1- import { createRequire } from "node:module" ;
21import { resolveEnvValue , saveConfigPreservingClaudeCode } from "../config" ;
32import type { OcxConfig , OcxProviderConfig } from "../types" ;
43import type { ProviderRegistryEntry } from "./registry" ;
4+ import {
5+ KEYCHAIN_REFERENCE_PREFIX ,
6+ invalidateResolvedProviderKeyCache ,
7+ isKeychainReference ,
8+ keychainAccount ,
9+ keychainReferenceBelongsToProvider ,
10+ probeProviderKeychain ,
11+ providerKeychainEntry ,
12+ } from "./api-key-resolve" ;
13+
14+ // The read-path (reference predicates, the OS entry factory, resolveProviderApiKey, the probe
15+ // and the kind classification) lives in ./api-key-resolve -- a leaf module that
16+ // reasoning-metadata can also import without pulling the ../config barrel into its
17+ // cycle-sensitive graph. Re-exported here so existing key-store consumers keep working.
18+ export {
19+ KEYCHAIN_REFERENCE_PREFIX ,
20+ PROVIDER_KEYCHAIN_SERVICE ,
21+ isKeychainReference ,
22+ probeProviderKeychain ,
23+ providerKeyStoreKind ,
24+ resolveProviderApiKey ,
25+ setProviderKeychainEntryFactoryForTests ,
26+ } from "./api-key-resolve" ;
27+ export type {
28+ ProviderKeychainEntry ,
29+ ProviderKeychainEntryFactory ,
30+ ProviderKeyStoreKind ,
31+ } from "./api-key-resolve" ;
532
633/** Shared with routing: a key-mode override is effective only while its key resolves. */
734export function providerUsesKeyAuthOverride (
@@ -27,109 +54,8 @@ export function providerUsesKeyAuthOverride(
2754 * (headless service, locked session) refuses rather than half-migrating.
2855 */
2956
30- export const KEYCHAIN_REFERENCE_PREFIX = "keychain:" ;
31- export const PROVIDER_KEYCHAIN_SERVICE = "opencodex.provider-api-key.v1" ;
32-
33- export interface ProviderKeychainEntry {
34- getPassword ( ) : string | null ;
35- setPassword ( password : string ) : void ;
36- deletePassword ( ) : boolean ;
37- }
38-
39- export type ProviderKeychainEntryFactory = ( service : string , account : string ) => ProviderKeychainEntry ;
40-
41- const nodeRequire = createRequire ( import . meta. url ) ;
42-
43- function defaultEntryFactory ( service : string , account : string ) : ProviderKeychainEntry {
44- const { Entry } = nodeRequire ( "@napi-rs/keyring" ) as { Entry : new ( s : string , a : string ) => ProviderKeychainEntry } ;
45- return new Entry ( service , account ) ;
46- }
47-
48- let entryFactory : ProviderKeychainEntryFactory = defaultEntryFactory ;
49- const resolvedCache = new Map < string , string > ( ) ;
50- const warnedAccounts = new Set < string > ( ) ;
51-
52- /** Test seam: swap the OS entry for an in-memory one and drop caches. */
53- export function setProviderKeychainEntryFactoryForTests ( factory : ProviderKeychainEntryFactory | null ) : void {
54- entryFactory = factory ?? defaultEntryFactory ;
55- resolvedCache . clear ( ) ;
56- warnedAccounts . clear ( ) ;
57- }
58-
59- export function isKeychainReference ( value : string | undefined ) : value is string {
60- return typeof value === "string" && value . startsWith ( KEYCHAIN_REFERENCE_PREFIX ) && value . length > KEYCHAIN_REFERENCE_PREFIX . length ;
61- }
62-
63- function keychainAccount ( reference : string ) : string {
64- return reference . slice ( KEYCHAIN_REFERENCE_PREFIX . length ) ;
65- }
66-
67- /**
68- * A reference belongs to `name` only when its account is that provider's own active account
69- * or one of its pool accounts. `storeProviderKeyInKeychain` writes exactly those two shapes,
70- * so anything else in a provider's config names another provider's secret.
71- */
72- function keychainReferenceBelongsToProvider ( reference : string , name : string ) : boolean {
73- const account = keychainAccount ( reference ) ;
74- return account === name || account . startsWith ( `${ name } /` ) ;
75- }
76-
77- function readKeychain ( account : string ) : string | undefined {
78- const cached = resolvedCache . get ( account ) ;
79- if ( cached !== undefined ) return cached ;
80- try {
81- const value = entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) . getPassword ( ) ;
82- if ( typeof value === "string" && value . trim ( ) ) {
83- resolvedCache . set ( account , value ) ;
84- return value ;
85- }
86- } catch {
87- // fall through to the single warning below
88- }
89- if ( ! warnedAccounts . has ( account ) ) {
90- warnedAccounts . add ( account ) ;
91- console . warn ( `[opencodex] provider key reference keychain:${ account } could not be read from the OS keychain; requests for this provider have no credential until the keychain is available (no plaintext fallback)` ) ;
92- }
93- return undefined ;
94- }
95-
96- /**
97- * Single resolver for provider key material: env references, keychain references, or the
98- * literal value. Every request-time read of `apiKey` goes through here.
99- */
100- export function resolveProviderApiKey ( value : string | undefined ) : string | undefined {
101- if ( ! value ) return undefined ;
102- if ( isKeychainReference ( value ) ) return readKeychain ( keychainAccount ( value ) ) ;
103- return resolveEnvValue ( value ) ;
104- }
105-
106- export type ProviderKeyStoreKind = "keychain" | "env" | "file" | "none" ;
107-
108- export function providerKeyStoreKind ( provider : Pick < OcxProviderConfig , "apiKey" > | undefined ) : ProviderKeyStoreKind {
109- const key = provider ?. apiKey ;
110- if ( ! key ) return "none" ;
111- if ( isKeychainReference ( key ) ) return "keychain" ;
112- if ( / ^ \$ \{ ? \w + \} ? $ / . test ( key ) ) return "env" ;
113- return "file" ;
114- }
115-
116- /** Probe the OS keychain with a throwaway account: write, read back, delete. */
117- export function probeProviderKeychain ( ) : { available : true } | { available : false ; reason : string } {
118- const account = `probe-${ process . pid } -${ Date . now ( ) } ` ;
119- try {
120- const entry = entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) ;
121- entry . setPassword ( "ok" ) ;
122- const back = entry . getPassword ( ) ;
123- try { entry . deletePassword ( ) ; } catch { /* best effort */ }
124- if ( back !== "ok" ) return { available : false , reason : "keychain read-back did not match" } ;
125- return { available : true } ;
126- } catch ( error ) {
127- return { available : false , reason : error instanceof Error ? error . message : "keychain unavailable" } ;
128- }
129- }
130-
13157function writeVerified ( account : string , secret : string ) : void {
132- const entry = entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) ;
58+ const entry = providerKeychainEntry ( account ) ;
13359 entry . setPassword ( secret ) ;
13460 if ( entry . getPassword ( ) !== secret ) throw new Error ( `keychain read-back mismatch for ${ account } ` ) ;
13561}
@@ -177,13 +103,12 @@ export function storeProviderKeyInKeychain(config: OcxConfig, name: string): { o
177103 }
178104 } catch ( error ) {
179105 for ( const account of written ) {
180- try { entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) . deletePassword ( ) ; } catch { /* best effort */ }
106+ try { providerKeychainEntry ( account ) . deletePassword ( ) ; } catch { /* best effort */ }
181107 }
182108 return { ok : false , error : `OS keychain write failed: ${ error instanceof Error ? error . message : "unknown" } ` , status : 503 } ;
183109 }
184110 for ( const apply of planned ) apply ( ) ;
185- resolvedCache . clear ( ) ;
186- warnedAccounts . clear ( ) ;
111+ invalidateResolvedProviderKeyCache ( ) ;
187112 saveConfigPreservingClaudeCode ( config ) ;
188113 return { ok : true , moved : written . length } ;
189114}
@@ -211,7 +136,7 @@ export function restoreProviderKeyFromKeychain(config: OcxConfig, name: string):
211136 const account = keychainAccount ( ref ) ;
212137 if ( resolved . has ( account ) ) continue ;
213138 let value : string | null = null ;
214- try { value = entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) . getPassword ( ) ; } catch { value = null ; }
139+ try { value = providerKeychainEntry ( account ) . getPassword ( ) ; } catch { value = null ; }
215140 if ( ! value ) return { ok : false , error : `OS keychain has no readable secret for ${ ref } ; config left unchanged` , status : 503 } ;
216141 resolved . set ( account , value ) ;
217142 }
@@ -220,10 +145,9 @@ export function restoreProviderKeyFromKeychain(config: OcxConfig, name: string):
220145 }
221146 if ( isKeychainReference ( provider . apiKey ) ) provider . apiKey = resolved . get ( keychainAccount ( provider . apiKey ) ) ! ;
222147 for ( const account of resolved . keys ( ) ) {
223- try { entryFactory ( PROVIDER_KEYCHAIN_SERVICE , account ) . deletePassword ( ) ; } catch { /* best effort */ }
148+ try { providerKeychainEntry ( account ) . deletePassword ( ) ; } catch { /* best effort */ }
224149 }
225- resolvedCache . clear ( ) ;
226- warnedAccounts . clear ( ) ;
150+ invalidateResolvedProviderKeyCache ( ) ;
227151 saveConfigPreservingClaudeCode ( config ) ;
228152 return { ok : true , restored : resolved . size } ;
229153}
0 commit comments