refactor: 移除已廢棄的自管加密金鑰機制(credential 全面託管 CF Workers Secrets)

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>
This commit is contained in:
2026-07-21 01:32:16 +08:00
committed by uncle6me-web
parent b9b94d7852
commit 20c7610371
64 changed files with 214 additions and 2197 deletions
+29 -37
View File
@@ -9,6 +9,7 @@
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { storeCredential } from './credentials';
export const authRouter = new Hono<{ Bindings: Bindings }>();
@@ -48,26 +49,13 @@ function getLandingOrigin(c: { req: { raw: Request } }): string {
return 'https://arcrun.dev';
}
/** 產生 API KeyHMAC-SHA256 of email,與 /register 相同邏輯) */
async function generateApiKey(email: string, encryptionKey: string): Promise<string> {
const keyData = new TextEncoder().encode(encryptionKey.slice(0, 32));
const msgData = new TextEncoder().encode(email);
const cryptoKey = await crypto.subtle.importKey(
'raw', keyData, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
);
const sig = await crypto.subtle.sign('HMAC', cryptoKey, msgData);
const hex = Array.from(new Uint8Array(sig)).map(b => b.toString(16).padStart(2, '0')).join('');
return 'ak_' + hex.slice(0, 32);
}
/** AES-GCM 加密,回傳 {encrypted, iv}base64),與 SDK 格式相同 */
async function aesEncrypt(plaintext: string, encryptionKey: string): Promise<{ encrypted: string; iv: string }> {
const keyBytes = new TextEncoder().encode(encryptionKey.slice(0, 32));
const cryptoKey = await crypto.subtle.importKey('raw', keyBytes, { name: 'AES-GCM' }, false, ['encrypt']);
const iv = crypto.getRandomValues(new Uint8Array(12));
const enc = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, cryptoKey, new TextEncoder().encode(plaintext));
const toB64 = (buf: ArrayBuffer | Uint8Array) => btoa(String.fromCharCode(...new Uint8Array(buf instanceof ArrayBuffer ? buf : buf)));
return { encrypted: toB64(enc), iv: toB64(iv) };
/**
* 產生 API Key(隨機,與 /me/api-key/rotate 同一套)。
*
* key 與 email 無關、不可預測;登入走 USERS_KV 讀出的 api_key,不重算。
*/
function generateApiKey(): string {
return 'ak_' + randomToken(24);
}
/** 幂等寫入 auth_recipe 到 RECIPES KV(若已存在相同版本則跳過) */
@@ -198,16 +186,14 @@ authRouter.get('/auth/callback', async (c) => {
}
await c.env.SESSIONS_KV.delete(`state:${state}`);
const encryptionKey = c.env.ENCRYPTION_KEY;
if (!encryptionKey) {
return Response.redirect(`${landingOrigin}/login?error=server_error`, 302);
}
try {
let email: string;
let displayName: string;
let avatarUrl: string | undefined;
let providerId: string;
// provider token 要存進 credential 新家,但必須用最終的 api_key 當租戶鍵,
// 而 api_key 要等下方 USERS_KV upsert 才決定 → 先暫存,稍後再寫。
let pendingCredential: { name: string; value: string; service: string } | null = null;
const provider = stateRecord.provider;
const redirectUri = 'https://cypher.arcrun.dev/auth/callback';
@@ -240,12 +226,10 @@ authRouter.get('/auth/callback', async (c) => {
avatarUrl = userInfo.picture;
providerId = userInfo.sub;
// 存 Google refresh_token(加密)到 CREDENTIALS_KV,供 auth_oauth2 零件使用
// Google 只在首次授權時回傳 refresh_token,後續登入 tokenData.refresh_token 為 undefined
// 存 Google refresh_token 供 auth_oauth2 零件使用(實際寫入在 apiKey 決定後,見下方
// pendingCredential)。Google 只在首次授權時回傳 refresh_token,後續登入為 undefined
if (tokenData.refresh_token) {
const credKey = `${await generateApiKey(email, encryptionKey)}:cred:google_refresh_token`;
const encrypted = await aesEncrypt(tokenData.refresh_token, encryptionKey);
await c.env.CREDENTIALS_KV.put(credKey, JSON.stringify(encrypted));
pendingCredential = { name: 'google_refresh_token', value: tokenData.refresh_token, service: 'google_user' };
// 種 auth_recipe:google_user(用戶自己的 Google OAuth2
void upsertAuthRecipe(c.env.RECIPES, {
@@ -319,12 +303,10 @@ authRouter.get('/auth/callback', async (c) => {
avatarUrl = userInfo.avatar_url;
providerId = String(userInfo.id);
// 存 GitHub access_token(加密)到 CREDENTIALS_KV,供 auth_oauth2 零件使用
// GitHub 沒有 refresh_tokenaccess_token 長效(直到 revoke
// 存 GitHub access_token 供 auth_static_key 零件使用(實際寫入在 apiKey 決定後,見
// 下方 pendingCredential)。GitHub 沒有 refresh_tokenaccess_token 長效(直到 revoke
if (tokenData.access_token) {
const credKey = `${await generateApiKey(email, encryptionKey)}:cred:github_access_token`;
const encrypted = await aesEncrypt(tokenData.access_token, encryptionKey);
await c.env.CREDENTIALS_KV.put(credKey, JSON.stringify(encrypted));
pendingCredential = { name: 'github_access_token', value: tokenData.access_token, service: 'github_user' };
// GitHub access_token 長效無 refresh 概念,用 static_key primitive
void upsertAuthRecipe(c.env.RECIPES, {
@@ -352,8 +334,8 @@ authRouter.get('/auth/callback', async (c) => {
const updated: UserRecord = { ...existing, display_name: displayName, avatar_url: avatarUrl };
await c.env.USERS_KV.put(userKey, JSON.stringify(updated));
} else {
// New user — generate api key (same HMAC logic as /register)
apiKey = await generateApiKey(email, encryptionKey);
// New user — generate a random api key
apiKey = generateApiKey();
const newUser: UserRecord = {
email, display_name: displayName, avatar_url: avatarUrl,
api_key: apiKey, provider, provider_id: providerId,
@@ -364,6 +346,16 @@ authRouter.get('/auth/callback', async (c) => {
await c.env.USERS_KV.put(`apikey:${apiKey}`, userKey);
}
// provider token → credential 新家(Workers Secrets + D1)。登入本身不該因為存
// credential 失敗而失敗(例如 self-hosted 未設 CF_SECRETS_API_TOKEN)→ 吞錯誤只記 log。
if (pendingCredential) {
try {
await storeCredential(c.env, apiKey, pendingCredential.name, pendingCredential.value, pendingCredential.service);
} catch (e) {
console.error('存 provider token 失敗(不影響登入):', e instanceof Error ? e.message : String(e));
}
}
// Create session (TTL 7 days)
const sessionId = randomToken(32);
const session: SessionRecord = {
+20 -71
View File
@@ -17,11 +17,7 @@
* 2026-07-03 T1.5 spike 定案)對舊格式的刻意取代,SDD §6 Q-b 仍列為需 leo 明確接受的
* 誠實 trade-off(本次實作先落地,若 leo 不接受選項甲需回頭改)。
*
* credential-store-migration T8(§4.2 回填)+ T9(§3 治理端點):
* - `POST /credentials/migrate-to-workers-secrets`:把呼叫者(X-Arcrun-API-Key)名下的舊
* `{api_key}:cred:{name}` KV row 逐一解密(重用 wasi-shim 唯一合法 crypto_decrypt 呼叫點,
* 不在本檔重新實作解密)→ PUT 進 Workers Secrets → D1 upsert 目錄。冪等:D1 已有可解析
* secret_ref 的 row 就跳過;逐筆誠實回報 ok/skipped/failmindset §7 不假綠)。
* credential-store-migration T9(§3 治理端點):
* - `GET /credentials`:改讀 D1(與 `/credentials/catalog` 共用同一份 query,同時保留
* `/catalog` 別名,Console 既有呼叫不受影響)。
* - `DELETE /credentials/:name`:先查 D1 拿 secret_ref → 有則刪 Workers Secret + D1 row
@@ -31,7 +27,6 @@
import { Hono } from 'hono';
import type { Bindings } from '../types';
import { sha256Prefix } from '../lib/hash';
import { createArcrunHostFunctions } from '../lib/wasi-shim';
export const credentialsRouter = new Hono<{ Bindings: Bindings }>();
@@ -52,6 +47,25 @@ async function deriveSecretRef(apiKey: string, name: string): Promise<string> {
return `CRED_${name.toUpperCase()}_${hash8.toUpperCase()}`;
}
/**
* 存一筆 credential 進「新家」(CF Workers Secrets 明文 + D1 目錄)。
*
* 給 OAuth callback 這類非 /credentials 端點的內部呼叫者用(存 provider token 供
* auth primitive 零件取用)。與 `POST /credentials` 共用同一條寫入路徑,
* 確保只有一套儲存。
*/
export async function storeCredential(
env: Bindings,
apiKey: string,
name: string,
value: string,
service: string | null,
): Promise<void> {
const secretRef = await deriveSecretRef(apiKey, name);
await putWorkerSecret(env, secretRef, value);
await upsertCredentialRow(env.CREDENTIALS_DB, apiKey, name, service, 'standard', secretRef);
}
function validateName(name: unknown): name is string {
return typeof name === 'string' && /^\w+$/.test(name);
}
@@ -308,68 +322,3 @@ credentialsRouter.get('/credentials', async (c) => {
return c.json({ success: false, error: e instanceof Error ? e.message : String(e) }, 502);
}
});
interface MigrateResult {
name: string;
ok: boolean;
skipped?: boolean;
error?: string;
}
// POST /credentials/migrate-to-workers-secrets — 回填(T8,§4.2):一次性、冪等、可審。
// 把呼叫者名下舊 `{api_key}:cred:{name}` KV row{encrypted, iv} AES-GCM 密文)逐一解密
// →(重用 wasi-shim 唯一合法 crypto_decrypt 呼叫點,本檔不重新實作解密)→ PUT 進 Workers
// Secrets → D1 upsert 目錄。冪等:D1 已有該 (api_key,name) row 且 secret_ref 非空 → 跳過。
// 不刪 KV 舊密文(§4.3 回滾錨點——雙讀 fallback、廢除 ENCRYPTION_KEY 前的安全網)。
credentialsRouter.post('/credentials/migrate-to-workers-secrets', async (c) => {
const apiKey = c.req.header('X-Arcrun-API-Key');
if (!apiKey) {
return c.json({ error: '缺少 X-Arcrun-API-Key header' }, 401);
}
const cryptoDecrypt = createArcrunHostFunctions(c.env, apiKey).crypto_decrypt;
if (!cryptoDecrypt) {
return c.json({ success: false, error: 'crypto_decrypt host function 未就緒' }, 500);
}
const prefix = `${apiKey}:cred:`;
const list = await c.env.CREDENTIALS_KV.list({ prefix });
const results: MigrateResult[] = [];
for (const key of list.keys) {
const name = key.name.slice(prefix.length);
try {
const existingRef = await findSecretRef(c.env.CREDENTIALS_DB, apiKey, name);
if (existingRef) {
results.push({ name, ok: true, skipped: true });
continue;
}
const raw = await c.env.CREDENTIALS_KV.get(key.name);
if (!raw) {
results.push({ name, ok: false, error: 'KV row 讀不到值(可能已被刪除)' });
continue;
}
const { encrypted, iv } = JSON.parse(raw) as { encrypted: string; iv: string };
const plaintext = await cryptoDecrypt(encrypted, iv);
const secretRef = await deriveSecretRef(apiKey, name);
await putWorkerSecret(c.env, secretRef, plaintext);
await upsertCredentialRow(c.env.CREDENTIALS_DB, apiKey, name, null, 'standard', secretRef);
results.push({ name, ok: true });
} catch (e) {
// 誠實回報逐筆 fail,不假綠(mindset §7
results.push({ name, ok: false, error: e instanceof Error ? e.message : String(e) });
}
}
const failed = results.filter(r => !r.ok);
return c.json({
success: failed.length === 0,
total: results.length,
migrated: results.filter(r => r.ok && !r.skipped).length,
skipped: results.filter(r => r.skipped).length,
failed: failed.length,
results,
});
});
+1 -1
View File
@@ -401,7 +401,7 @@ recipesRouter.delete('/recipes/:id', async (c) => {
* 2. rec_xxxxxxxx → idx:{hash} 反查 canonical_id → 再走 canonical 解析。
* 3. canonical_id → 先查 idx:installed:{canonical_id}(本部署安裝的唯一版本)→ recipe:{uuid}
* 查不到 fallback 舊 key recipe:{canonical_id}(種子 / migration 前資料)。
* 執行鏈路(component-loader/auth-dispatcher/credential-injector)都經此 → 不破執行。
* 執行鏈路(component-loader/auth-dispatcher)都經此 → 不破執行。
*/
export async function resolveRecipe(
id: string,
-46
View File
@@ -1,46 +0,0 @@
// POST /register — API Key 發放
// email → HMAC-SHA256(email, ENCRYPTION_KEY) → api_key (ak_ 前綴)
// 同一個 email 永遠得到相同的 Key,無需資料庫
import { Hono } from 'hono';
import type { Bindings } from '../types';
export const registerRouter = new Hono<{ Bindings: Bindings }>();
registerRouter.post('/register', async (c) => {
let email: string;
try {
const body = await c.req.json() as { email?: string };
email = (body.email ?? '').trim().toLowerCase();
} catch {
return c.json({ success: false, error: 'request body 必須為 JSON' }, 400);
}
if (!email || !email.includes('@')) {
return c.json({ success: false, error: 'email 格式不正確' }, 400);
}
const encryptionKey = c.env.ENCRYPTION_KEY;
if (!encryptionKey || encryptionKey.length < 32) {
return c.json({ success: false, error: 'server configuration error' }, 500);
}
// HMAC-SHA256(email, ENCRYPTION_KEY) → hex → 取前 32 字元 → ak_ 前綴
const keyData = new TextEncoder().encode(encryptionKey.slice(0, 32));
const msgData = new TextEncoder().encode(email);
const cryptoKey = await crypto.subtle.importKey(
'raw', keyData, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
);
const sig = await crypto.subtle.sign('HMAC', cryptoKey, msgData);
const hex = Array.from(new Uint8Array(sig)).map(b => b.toString(16).padStart(2, '0')).join('');
const apiKey = 'ak_' + hex.slice(0, 32);
return c.json({
success: true,
api_key: apiKey,
encryption_key: encryptionKey, // 用戶需要此 key 才能加密上傳 credential
email,
message: 'API Key 已發放,請妥善保存。相同 email 永遠得到相同的 Key。',
});
});