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" ;
66import { join , dirname } from "node:path" ;
77import { homedir } from "node:os" ;
8+ import { createHash } from "node:crypto" ;
89import type { Credential } from "./types.js" ;
910
1011const STORE_DIR = join ( homedir ( ) , ".zcode-proxy" ) ;
1112const STORE_FILE = join ( STORE_DIR , "credentials.json" ) ;
1213const 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+
72104export 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
79111export 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