Skip to content

Commit 477b7a4

Browse files
committed
fix(config/auth): plan 硬校验 + YAML 保注释 + resolver shape 校验 + SHA-256 KDF 迁移 + 常数时间 key 比较
- CL-07: resolvePlan 对未识别值 throw(对齐 provider 校验风格),拼写错误 不再静默回落 coding-plan 打到错误上游;缺省/null 仍走默认 - CL-24: updateConfigYaml 改用 yaml parseDocument(原生保注释);抽共享 ensureConfigFile 供 serve/android/auth login/TUI 建配置去重 - CL-06: findOrCreateApiKey 校验创建/列表命中 key 的 shape(漂移时登录 明确报错而非存入 undefined 字符串);resolveZaiBizToken 对 access_token 缺失 throw;列表命中 key 非法时回落创建路径 - R2-13: 凭据 store KDF 升级为 SHA-256(seed)(替换 XOR 折叠伪 KDF;默认机 导种子场景安全增益≈0,动机是 env-secret 部署的结构性增益);loadCredential 新钥失败回落旧钥解密并原子重存(temp+rename 0o600),重存失败仅 warn 不 影响本次 load;双失败保持 corrupt → warn+null 语义 - R2-10: checkProxyKey 改 timingSafeEqual 常数时间比较(长度不等先短路)
1 parent 7ee56dd commit 477b7a4

11 files changed

Lines changed: 329 additions & 54 deletions

File tree

‎src/auth/resolver.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,16 @@ function mockFetch(responses: Record<string, (body?: string) => Response>): type
2424
}
2525

2626
describe("KeyResolver", () => {
27+
it("resolveZaiBizToken THROWS on shape drift (access_token missing) instead of returning undefined (CL-06)", async () => {
28+
const fetchImpl = mockFetch({
29+
"/auth/z/login": () => new Response(JSON.stringify({ renamed_token: "biz_token_123" }), {
30+
status: 200, headers: { "content-type": "application/json" },
31+
}),
32+
});
33+
const resolver = new KeyResolver(fetchImpl);
34+
await expect(resolver.resolveZaiBizToken("access_abc")).rejects.toThrow(/unexpected shape/);
35+
});
36+
2737
it("resolveZaiBizToken exchanges access token for biz token", async () => {
2838
const fetchImpl = mockFetch({
2939
"/auth/z/login": () => new Response(JSON.stringify({
@@ -104,6 +114,35 @@ describe("KeyResolver", () => {
104114
expect(result.apiKey).toBe("newApiKey123");
105115
});
106116

117+
it("findOrCreateApiKey THROWS when the create response loses apiKey (shape drift, CL-06)", async () => {
118+
const fetchImpl = mockFetch({
119+
"api_keys": (body) => {
120+
if (body) return bizResponse({ key: "renamed-field" }); // drift: apiKey → key
121+
return bizResponse([]);
122+
},
123+
});
124+
const resolver = new KeyResolver(fetchImpl);
125+
await expect(resolver.findOrCreateApiKey("https://api.z.ai", "Bearer tok", "org1", "proj1"))
126+
.rejects.toThrow(/unexpected shape/);
127+
});
128+
129+
it("findOrCreateApiKey falls through to create when the listed key entry is malformed (CL-06)", async () => {
130+
let created = false;
131+
const fetchImpl = mockFetch({
132+
"api_keys": (body) => {
133+
if (body) {
134+
created = true;
135+
return bizResponse({ apiKey: "freshlyCreated" });
136+
}
137+
return bizResponse([{ name: "zcode-api-key", apiKey: "" }]);
138+
},
139+
});
140+
const resolver = new KeyResolver(fetchImpl);
141+
const result = await resolver.findOrCreateApiKey("https://api.z.ai", "Bearer tok", "org1", "proj1");
142+
expect(created).toBe(true);
143+
expect(result.apiKey).toBe("freshlyCreated");
144+
});
145+
107146
it("getSecretKey retrieves secret via apiKey value", async () => {
108147
const fetchImpl = mockFetch({
109148
"copy/": () => bizResponse({ secretKey: "theSecretKey" }),

‎src/auth/resolver.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,13 @@ export class KeyResolver {
4444
throw new Error(`z/login failed: ${resp.status}`);
4545
}
4646
const data = await resp.json();
47-
return data.access_token ?? data.accessToken ?? data.data?.access_token;
47+
const token = data.access_token ?? data.accessToken ?? data.data?.access_token;
48+
// Shape guard: silently returning undefined used to store a bogus
49+
// credential that surfaced only as cryptic upstream 401s.
50+
if (typeof token !== "string" || token.length === 0) {
51+
throw new Error("z/login returned unexpected shape: access_token missing or empty");
52+
}
53+
return token;
4854
}
4955

5056
async resolveCustomerInfo(
@@ -94,7 +100,10 @@ export class KeyResolver {
94100

95101
if (Array.isArray(existing)) {
96102
const found = existing.find((k: any) => k.name === ZAI_API_KEY_NAME);
97-
if (found?.apiKey) {
103+
// Reuse the listed key only when it has a usable shape; a malformed
104+
// entry falls through to the create path instead of poisoning the
105+
// stored credential.
106+
if (found && typeof found.apiKey === "string" && found.apiKey.length > 0) {
98107
return { apiKey: found.apiKey };
99108
}
100109
}
@@ -103,6 +112,12 @@ export class KeyResolver {
103112
method: "POST",
104113
body: JSON.stringify({ name: ZAI_API_KEY_NAME }),
105114
});
115+
// Shape guard (CL-06): an upstream response drift (renamed/nested field)
116+
// must fail the login with a clear error — not store the string
117+
// "undefined" and 401 on every later request.
118+
if (typeof created?.apiKey !== "string" || created.apiKey.length === 0) {
119+
throw new Error("API key creation returned unexpected shape: apiKey missing or empty");
120+
}
106121
return { apiKey: created.apiKey };
107122
}
108123

‎src/auth/store.test.ts‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,30 @@
33
* @see .omo/plans/zcode-proxy.md Task 14
44
*/
55
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
6-
import { saveCredential, loadCredential, clearCredential } from "./store.js";
6+
import { saveCredential, loadCredential, clearCredential, getStorePath } from "./store.js";
7+
import { writeFileSync, readFileSync } from "node:fs";
8+
import { homedir } from "node:os";
79
import type { Credential } from "./types.js";
810

911
const TEST_SECRET = "test-encryption-secret-for-zcode-proxy";
1012

13+
/** Legacy XOR-fold key + AES-GCM encrypt (pre-SHA-256 store format). */
14+
async function legacyEncrypt(plaintext: string): Promise<string> {
15+
const seed = process.env.ZCODE_PROXY_CREDENTIAL_SECRET ?? `${homedir()}-${process.platform}-${process.arch}`;
16+
const keyBytes = new Uint8Array(new ArrayBuffer(32));
17+
const seedBytes = new TextEncoder().encode(seed);
18+
for (let i = 0; i < seedBytes.length; i++) {
19+
keyBytes[i % 32] ^= seedBytes[i];
20+
}
21+
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt"]);
22+
const iv = crypto.getRandomValues(new Uint8Array(12));
23+
const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, new TextEncoder().encode(plaintext));
24+
const combined = new Uint8Array(iv.length + encrypted.byteLength);
25+
combined.set(iv, 0);
26+
combined.set(new Uint8Array(encrypted), iv.length);
27+
return Buffer.from(combined).toString("base64");
28+
}
29+
1130
describe("credential store", () => {
1231
beforeEach(() => {
1332
process.env.ZCODE_PROXY_CREDENTIAL_SECRET = TEST_SECRET;
@@ -70,3 +89,50 @@ describe("credential store", () => {
7089
expect(loaded!.expiresAt).toBe(9999999999999);
7190
});
7291
});
92+
93+
describe("credential store — SHA-256 KDF migration (R2-13)", () => {
94+
beforeEach(() => {
95+
process.env.ZCODE_PROXY_CREDENTIAL_SECRET = TEST_SECRET;
96+
clearCredential();
97+
});
98+
99+
afterEach(() => {
100+
clearCredential();
101+
delete process.env.ZCODE_PROXY_CREDENTIAL_SECRET;
102+
});
103+
104+
it("migrates a legacy XOR-fold-encrypted file: loads AND re-stores under the new KDF", async () => {
105+
const cred: Credential = { apiKey: "legacyKey", provider: "zai" };
106+
const legacyPayload = await legacyEncrypt(JSON.stringify(cred));
107+
writeFileSync(getStorePath(), JSON.stringify({ encrypted: legacyPayload }), "utf-8");
108+
109+
const loaded = await loadCredential();
110+
expect(loaded).not.toBeNull();
111+
expect(loaded!.apiKey).toBe("legacyKey");
112+
113+
// The file must now be re-encrypted under the NEW key: the legacy key can
114+
// no longer decrypt it.
115+
const restored = JSON.parse(readFileSync(getStorePath(), "utf-8"));
116+
expect(restored.encrypted).not.toBe(legacyPayload);
117+
const reLoaded = await loadCredential(); // second load goes through the new KDF directly
118+
expect(reLoaded!.apiKey).toBe("legacyKey");
119+
});
120+
121+
it("returns null for a file decryptable under NEITHER key (corrupt/foreign)", async () => {
122+
writeFileSync(getStorePath(), JSON.stringify({ encrypted: Buffer.from("garbage-not-base64-encrypted").toString("base64") }), "utf-8");
123+
const loaded = await loadCredential();
124+
expect(loaded).toBeNull();
125+
});
126+
127+
it("returns null for valid-base64 but undecryptable ciphertext", async () => {
128+
// Encrypt under a DIFFERENT secret → both the new and legacy keys fail.
129+
const saved = process.env.ZCODE_PROXY_CREDENTIAL_SECRET;
130+
process.env.ZCODE_PROXY_CREDENTIAL_SECRET = "a-totally-different-secret";
131+
const foreign = await legacyEncrypt(JSON.stringify({ apiKey: "x", provider: "zai" }));
132+
process.env.ZCODE_PROXY_CREDENTIAL_SECRET = saved;
133+
134+
writeFileSync(getStorePath(), JSON.stringify({ encrypted: foreign }), "utf-8");
135+
const loaded = await loadCredential();
136+
expect(loaded).toBeNull();
137+
});
138+
});

‎src/auth/store.ts‎

Lines changed: 75 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,35 @@
22
* Encrypted file-based credential store.
33
* @see .omo/plans/zcode-proxy.md Task 14
44
*/
5-
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
5+
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, renameSync } from "node:fs";
66
import { join, dirname } from "node:path";
77
import { homedir } from "node:os";
8+
import { createHash } from "node:crypto";
89
import type { Credential } from "./types.js";
910

1011
const STORE_DIR = join(homedir(), ".zcode-proxy");
1112
const STORE_FILE = join(STORE_DIR, "credentials.json");
1213
const ENV_SECRET = "ZCODE_PROXY_CREDENTIAL_SECRET";
1314

14-
function getEncryptionKey() {
15+
/**
16+
* Derive the AES-GCM key as SHA-256(seed) (audit R2-13). The previous XOR-fold
17+
* construction was a pseudo-KDF: a seed shorter than 32 bytes left zero blocks
18+
* in the key. Scope note: on default machine-derived seeds the security gain
19+
* is ~0 (any same-user process can re-derive the seed either way, 0o600 only
20+
* stops other users) — the motivation is structural: env-secret deployments
21+
* (`ZCODE_PROXY_CREDENTIAL_SECRET`) get real 32-byte diffusion, and the
22+
* misleading "KDF" is gone.
23+
*/
24+
function getEncryptionKey(): Uint8Array {
25+
const seed = process.env[ENV_SECRET] ?? `${homedir()}-${process.platform}-${process.arch}`;
26+
return new Uint8Array(createHash("sha256").update(seed, "utf-8").digest());
27+
}
28+
29+
/**
30+
* Legacy XOR-fold key (pre-SHA-256 store format). Kept ONLY for the one-shot
31+
* migration decrypt in {@link loadCredential} — never used for new writes.
32+
*/
33+
function getLegacyEncryptionKey(): Uint8Array {
1534
const hash = new Uint8Array(new ArrayBuffer(32));
1635
const encoder = new TextEncoder();
1736

@@ -23,20 +42,35 @@ function getEncryptionKey() {
2342
return hash;
2443
}
2544

26-
async function encrypt(plaintext: string): Promise<string> {
27-
const key = await crypto.subtle.importKey(
45+
/** Atomic store write: temp file (0o600) + rename over the target. */
46+
function atomicWriteStore(contents: string): void {
47+
const tmp = `${STORE_FILE}.tmp-${process.pid}-${Date.now()}`;
48+
writeFileSync(tmp, contents, { mode: 0o600 });
49+
renameSync(tmp, STORE_FILE);
50+
}
51+
52+
async function importAesKey(raw: Uint8Array): Promise<CryptoKey> {
53+
// Copy into a plain ArrayBuffer: bun-types types Uint8Array as
54+
// ArrayBufferLike, which is not assignable to BufferSource.
55+
const ab = new ArrayBuffer(raw.byteLength);
56+
new Uint8Array(ab).set(raw);
57+
return crypto.subtle.importKey(
2858
"raw",
29-
getEncryptionKey(),
59+
ab,
3060
{ name: "AES-GCM" },
3161
false,
3262
["encrypt", "decrypt"],
3363
);
64+
}
65+
66+
async function encryptWith(key: Uint8Array, plaintext: string): Promise<string> {
67+
const aesKey = await importAesKey(key);
3468

3569
const iv = crypto.getRandomValues(new Uint8Array(12));
3670
const encoder = new TextEncoder();
3771
const encrypted = await crypto.subtle.encrypt(
3872
{ name: "AES-GCM", iv },
39-
key,
73+
aesKey,
4074
encoder.encode(plaintext),
4175
);
4276

@@ -47,48 +81,68 @@ async function encrypt(plaintext: string): Promise<string> {
4781
return Buffer.from(combined).toString("base64");
4882
}
4983

50-
async function decrypt(ciphertext: string): Promise<string> {
51-
const key = await crypto.subtle.importKey(
52-
"raw",
53-
getEncryptionKey(),
54-
{ name: "AES-GCM" },
55-
false,
56-
["encrypt", "decrypt"],
57-
);
84+
async function decryptWith(key: Uint8Array, ciphertext: string): Promise<string> {
85+
const aesKey = await importAesKey(key);
5886

5987
const combined = Buffer.from(ciphertext, "base64");
6088
const iv = combined.slice(0, 12);
6189
const data = combined.slice(12);
6290

6391
const decrypted = await crypto.subtle.decrypt(
6492
{ name: "AES-GCM", iv },
65-
key,
93+
aesKey,
6694
data,
6795
);
6896

6997
return new TextDecoder().decode(decrypted);
7098
}
7199

100+
async function encrypt(plaintext: string): Promise<string> {
101+
return encryptWith(getEncryptionKey(), plaintext);
102+
}
103+
72104
export async function saveCredential(cred: Credential): Promise<void> {
73105
mkdirSync(dirname(STORE_FILE), { recursive: true });
74106
const json = JSON.stringify(cred);
75107
const encrypted = await encrypt(json);
76-
writeFileSync(STORE_FILE, JSON.stringify({ encrypted }), { mode: 0o600 });
108+
atomicWriteStore(JSON.stringify({ encrypted }));
77109
}
78110

79111
export async function loadCredential(): Promise<Credential | null> {
80112
if (!existsSync(STORE_FILE)) return null;
81113
const raw = readFileSync(STORE_FILE, "utf-8");
82114
const parsed = JSON.parse(raw);
83115
if (!parsed.encrypted) return null;
116+
117+
let json: string;
118+
try {
119+
json = await decryptWith(getEncryptionKey(), parsed.encrypted);
120+
} catch {
121+
// Not decryptable under the new SHA-256 KDF — try the legacy XOR-fold key
122+
// (one-shot migration), then transparently re-store under the new format.
123+
try {
124+
json = await decryptWith(getLegacyEncryptionKey(), parsed.encrypted);
125+
} catch (e) {
126+
// Stale/corrupt credential file — key derivation is machine-specific
127+
// ({homedir}-{platform}-{arch}), so cross-machine copies or OS reinstalls
128+
// produce undecryptable ciphertext. Silently treat as "not logged in".
129+
console.warn(`Ignoring corrupted or stale credentials at ${STORE_FILE}: ${(e as Error).message}`);
130+
return null;
131+
}
132+
// Re-store under the new KDF. Best-effort by design: the credential is
133+
// already decrypted in memory, so a failed re-write (read-only dir, AV
134+
// lock on Windows, ...) must NOT fail this load — it retries next boot.
135+
try {
136+
atomicWriteStore(JSON.stringify({ encrypted: await encrypt(json) }));
137+
} catch (e) {
138+
console.warn(`Credential re-encryption under the new key derivation failed (will retry on next load): ${(e as Error).message}`);
139+
}
140+
}
141+
84142
try {
85-
const json = await decrypt(parsed.encrypted);
86143
return JSON.parse(json) as Credential;
87144
} catch (e) {
88-
// Stale/corrupt credential file — key derivation is machine-specific
89-
// ({homedir}-{platform}-{arch}), so cross-machine copies or OS reinstalls
90-
// produce undecryptable ciphertext. Silently treat as "not logged in".
91-
console.warn(`Ignoring corrupted or stale credentials at ${STORE_FILE}: ${(e as Error).message}`);
145+
console.warn(`Ignoring corrupted credentials at ${STORE_FILE}: ${(e as Error).message}`);
92146
return null;
93147
}
94148
}

0 commit comments

Comments
 (0)