Files
Arcrun/cli/src/lib/cf-api.ts
T
uncle6me-web 6a75117ba3 feat(kbdb): recipe 公庫/私庫雙向機制 + UUID 身份 + KBDB Base + 市場數據
kbdb-base SDD §7.5(公庫/私庫雙向機制,richblack 2026-06-07 拍板)。

## KBDB Base worker(新)
- kbdb/:D1-only 核心三表(entries/templates/entry_values)+ CRUD + LIKE search
  + recipe-stats 端點(市場數據)+ 0001_base.sql migration(含 recipe_stat seed)

## Phase 2.3:init 建 D1 + 套 migration
- cli cf-api.ts 加 listD1Databases/ensureD1Database;init 建 arcrun-kbdb D1
- deploy.ts 部署後對 D1 套 0001_base.sql(CF /d1/query API,idempotent)+ 注入 database_id

## Phase 5.1:recipe 成功記錄(市場數據來源)
- GraphExecutor 收集本次用到的 recipe uuid(usedRecipeKeys)
- executeWebhookGraph 執行結束一次性記 per-uuid 成功/失敗到 KBDB(fire-and-forget)

## Phase 7.5:recipe UUID 身份 + app-store 模型
- recipe 領 uuid=唯一身份;canonical_id/author/公私=屬性(§7.5.5)
- recipe:{uuid} + idx:canonical/installed/hash;resolveRecipe 向後相容不破執行鏈
- POST /recipes/submit=領新 uuid 新增作者版本(非覆蓋,app-store)
- GET /public-recipes 搜尋(多作者+per-uuid 市場星數)/ :id pull(選市場最佳)
- 落空→found:false 創作引導(§7.5.6 閉環)
- POST /recipes/migrate-uuid 一次性轉舊 key(增量寫不刪舊、冪等)
- init-seed 用 UUID(author=system)

## 薄殼(rule 07 §5:CLI + MCP 覆蓋同組能力)
- CLI: acr recipe search/pull/submit-p(config 加 DEFAULT_PUBLIC_LIBRARY_URL)
- MCP: arcrun_recipe_search/pull/submit_p/push/list/delete(補齊漂移)

## 壓測修正
- api-recipe-seeds: google_sheets_append PUT→POST(:append 正確動詞,階段12)

四 worker tsc 全綠(cypher/cli/kbdb/mcp)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 16:18:10 +08:00

207 lines
7.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Cloudflare KV REST API wrapper
* 使用 CF REST API 直接存取用戶的 KV namespace,不依賴 Wrangler CLI
*/
const CF_API_BASE = 'https://api.cloudflare.com/client/v4';
export interface CfKvClientOptions {
accountId: string;
namespaceId: string;
apiToken: string;
}
export class CfKvClient {
private base: string;
private headers: Record<string, string>;
constructor({ accountId, namespaceId, apiToken }: CfKvClientOptions) {
this.base = `${CF_API_BASE}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}`;
this.headers = {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json',
};
}
async put(key: string, value: string): Promise<void> {
const res = await fetch(`${this.base}/values/${encodeURIComponent(key)}`, {
method: 'PUT',
headers: { ...this.headers, 'Content-Type': 'text/plain' },
body: value,
});
if (!res.ok) {
const err = await res.text();
throw new Error(`KV PUT 失敗(${res.status}):${err.slice(0, 200)}`);
}
}
async get(key: string): Promise<string | null> {
const res = await fetch(`${this.base}/values/${encodeURIComponent(key)}`, {
headers: this.headers,
});
if (res.status === 404) return null;
if (!res.ok) {
const err = await res.text();
throw new Error(`KV GET 失敗(${res.status}):${err.slice(0, 200)}`);
}
return res.text();
}
async list(prefix?: string): Promise<Array<{ name: string; expiration?: number; metadata?: unknown }>> {
const url = new URL(`${this.base}/keys`);
if (prefix) url.searchParams.set('prefix', prefix);
url.searchParams.set('limit', '1000');
const res = await fetch(url.toString(), { headers: this.headers });
if (!res.ok) {
const err = await res.text();
throw new Error(`KV LIST 失敗(${res.status}):${err.slice(0, 200)}`);
}
const data = await res.json() as {
result: Array<{ name: string; expiration?: number; metadata?: unknown }>;
};
return data.result ?? [];
}
async delete(key: string): Promise<void> {
const res = await fetch(`${this.base}/values/${encodeURIComponent(key)}`, {
method: 'DELETE',
headers: this.headers,
});
if (!res.ok) {
const err = await res.text();
throw new Error(`KV DELETE 失敗(${res.status}):${err.slice(0, 200)}`);
}
}
}
/**
* Cloudflare Account-level API wrapperself-hosted installer 用)。
*
* 負責 acr init --self-hosted 的資源建立:驗 token、建/列 KV namespace、查 workers.dev subdomain。
* (不建 R2R2 是 dead storage 且綁卡違背開源免費;見 init.ts step 2 + registry-canon Phase 1.5。)
* 與 CfKvClient(綁單一 namespace 的 KV 操作)職責不同——這個是帳號層級的資源管理。
* 對應 SDD.agents/specs/arcrun/sdk-and-website/self-hosted-init.md §3 step 1-2
*/
export class CfAccountClient {
private accountBase: string;
private headers: Record<string, string>;
constructor(accountId: string, apiToken: string) {
this.accountBase = `${CF_API_BASE}/accounts/${accountId}`;
this.headers = {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json',
};
}
private async cf<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${this.accountBase}${path}`, {
...init,
headers: { ...this.headers, ...(init?.headers ?? {}) },
});
const data = await res.json().catch(() => null) as
| { success: boolean; result: T; errors?: Array<{ message: string }> }
| null;
if (!res.ok || !data?.success) {
const msg = data?.errors?.map(e => e.message).join('; ') ?? `HTTP ${res.status}`;
throw new Error(`CF API ${path} 失敗:${msg}`);
}
return data.result;
}
/** 驗證 token 能存取此 account(權限不足會在後續建立操作報錯,這裡先確認 account 可達)。*/
async verifyAccess(): Promise<void> {
// GET /accounts/{id} 能通 = token 有此 account 的基本讀權限
await this.cf<{ id: string; name: string }>('');
}
/** 列出現有 KV namespace(冪等用:已存在就重用,不重建)。回傳 title → id 對照。*/
async listKvNamespaces(): Promise<Map<string, string>> {
const result = await this.cf<Array<{ id: string; title: string }>>(
'/storage/kv/namespaces?per_page=100',
);
const map = new Map<string, string>();
for (const ns of result) map.set(ns.title, ns.id);
return map;
}
/** 建立 KV namespace(若同名已存在則回傳既有 id,冪等)。*/
async ensureKvNamespace(title: string, existing?: Map<string, string>): Promise<string> {
const known = existing ?? (await this.listKvNamespaces());
const found = known.get(title);
if (found) return found;
const result = await this.cf<{ id: string; title: string }>(
'/storage/kv/namespaces',
{ method: 'POST', body: JSON.stringify({ title }) },
);
return result.id;
}
/** 查 workers.dev subdomaincypher-executor WORKER_SUBDOMAIN 用,組對內 component URL)。*/
async getWorkersSubdomain(): Promise<string> {
const result = await this.cf<{ subdomain: string }>('/workers/subdomain');
return result.subdomain;
}
// D1 (KBDB Base). Free on Workers Free plan, no credit card (kbdb-base Q4 verified).
async listD1Databases(): Promise<Map<string, string>> {
const result = await this.cf<Array<{ uuid: string; name: string }>>('/d1/database?per_page=100');
const map = new Map<string, string>();
for (const db of result) map.set(db.name, db.uuid);
return map;
}
async ensureD1Database(name: string, existing?: Map<string, string>): Promise<string> {
const known = existing ?? (await this.listD1Databases());
const found = known.get(name);
if (found) return found;
const result = await this.cf<{ uuid: string; name: string }>(
'/d1/database',
{ method: 'POST', body: JSON.stringify({ name }) },
);
return result.uuid;
}
}
/** AES-GCM 加密 credential(與 cypher-executor credential-injector 解密邏輯對應)*/
export async function encryptCredential(value: string, encryptionKey: string): Promise<string> {
if (!encryptionKey || encryptionKey.length < 64) {
throw new Error(
'ARCRUN_ENCRYPTION_KEY 未設定或長度不足(需要 256-bit hex,即 64 個十六進位字元)\n' +
'生成指令:node -e "console.log(require(\'crypto\').randomBytes(32).toString(\'hex\'))"'
);
}
const keyBytes = hexToUint8Array(encryptionKey);
const cryptoKey = await crypto.subtle.importKey(
'raw',
keyBytes.buffer as ArrayBuffer,
{ name: 'AES-GCM' },
false,
['encrypt'],
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoded = new TextEncoder().encode(value);
const cipherBuffer = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, encoded);
return JSON.stringify({
encrypted: uint8ArrayToBase64(new Uint8Array(cipherBuffer)),
iv: uint8ArrayToBase64(iv),
});
}
function hexToUint8Array(hex: string): Uint8Array {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
}
return bytes;
}
function uint8ArrayToBase64(arr: Uint8Array): string {
return Buffer.from(arr).toString('base64');
}