20c7610371
leo 2026-07-20 明令:「已經改用 cf 自己的 secrets,不要再說它了」 「我希望以後再也看不到這個詞再出現」 背景:credential 早已遷移至 CF Workers per-script Secrets + D1 目錄, 舊的自管金鑰(client 端 AES-GCM + KV 密文 + crypto_decrypt)是遷移期遺留。 本次連根移除,含一併作廢的死 SaaS 碼。 移除: - 舊 KV 密文解密路徑(credential-injector.ts 整檔、dual-read fallback) 前置驗證:leo21c / youlin 兩帳號 CREDENTIALS_KV 實測 *:cred:* 皆 0 筆 - migrate-to-workers-secrets 搬家端點(回填已完成,無可回填) - /register 路由與 generateApiKey(HMAC 產 ak_ key 是 SaaS 遺物; self-hosted 走 namespace 明碼 D21,已無人使用) - platform_crypto component(三帳號實測 404 已退役,無 workflow 引用) 保留(附理由): - crypto_decrypt 保留為永遠回失敗的 stub——現役三個 auth .wasm 仍宣告該 import,缺項會讓 WASM instantiate 直接失敗。待零件重編後可真正刪除。 順帶修復(原不在範圍,但會實際壞事): - /auth/callback 有 `if (!key) redirect(server_error)` 閘,未設該 secret 的 實例會登入直接失敗 → 已移除 - OAuth 兩處把 provider token 寫進舊加密 KV(租戶鍵與實際 api_key 在 rotate 後必然分歧,已失效)→ 改導向 Workers Secrets,包 try/catch 不影響登入 - acr init Standard 模式呼叫已刪除的 /register → 改引導 OAuth 取 key - .claude/rules 與 system-dev/docs 是同一規範的兩份鏡像,先前只改 rules 導致鏡像仍在教舊做法 → 已同步(此類雙檔同步應納入檢查) 新用戶安裝從此零 secret 前置。 測試 187/188(唯一 fail 為 pre-existing,stash 驗證與本次無關); cypher-executor 與 cli typecheck 全綠。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
167 lines
6.0 KiB
TypeScript
167 lines
6.0 KiB
TypeScript
/**
|
||
* 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 wrapper(self-hosted installer 用)。
|
||
*
|
||
* 負責 acr init --self-hosted 的資源建立:驗 token、建/列 KV namespace、查 workers.dev subdomain。
|
||
* (不建 R2:R2 是 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 subdomain(cypher-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;
|
||
}
|
||
}
|