@link-assistant/router 0.0.0-stage → 1.25.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68422 -0
  3. package/index.d.ts +5932 -0
  4. package/index.js +224 -0
  5. package/native.d.ts +106 -0
  6. package/package.json +61 -4
  7. package/portable/policy.mjs +117 -0
  8. package/schemas/accounts-list.v1.json +323 -0
  9. package/schemas/accounts-pause.v1.json +97 -0
  10. package/schemas/accounts-policy.v1.json +214 -0
  11. package/schemas/accounts-resume.v1.json +97 -0
  12. package/schemas/auth-claude.v1.json +97 -0
  13. package/schemas/auth-clear.v1.json +97 -0
  14. package/schemas/auth-codex.v1.json +97 -0
  15. package/schemas/auth-gh.v1.json +97 -0
  16. package/schemas/auth-import.v1.json +167 -0
  17. package/schemas/auth-status.v1.json +387 -0
  18. package/schemas/cli-error.v1.json +97 -0
  19. package/schemas/clients-backup-create.v1.json +97 -0
  20. package/schemas/clients-backup-list.v1.json +234 -0
  21. package/schemas/clients-backup-restore.v1.json +97 -0
  22. package/schemas/clients-backup-verify.v1.json +125 -0
  23. package/schemas/clients-doctor.v1.json +249 -0
  24. package/schemas/clients-install.v1.json +164 -0
  25. package/schemas/clients-list.v1.json +194 -0
  26. package/schemas/clients-reinstall.v1.json +164 -0
  27. package/schemas/clients-remove.v1.json +97 -0
  28. package/schemas/clients-repair.v1.json +109 -0
  29. package/schemas/clients-reset.v1.json +113 -0
  30. package/schemas/clients-setup.v1.json +97 -0
  31. package/schemas/clients-show.v1.json +191 -0
  32. package/schemas/clients-update.v1.json +164 -0
  33. package/schemas/configure.v1.json +97 -0
  34. package/schemas/contracts.v1.json +106 -0
  35. package/schemas/data-backup.v1.json +32 -0
  36. package/schemas/deploy.v1.json +546 -0
  37. package/schemas/doctor.v1.json +324 -0
  38. package/schemas/local-deployment.v1.json +364 -0
  39. package/schemas/logs-anomalies.v1.json +112 -0
  40. package/schemas/logs-show.v1.json +127 -0
  41. package/schemas/logs-summary.v1.json +129 -0
  42. package/schemas/model-catalog.v1.json +117 -0
  43. package/schemas/models-explain.v1.json +325 -0
  44. package/schemas/preservation.v1.json +47 -0
  45. package/schemas/providers-add.v1.json +185 -0
  46. package/schemas/providers-import.v1.json +97 -0
  47. package/schemas/providers-list.v1.json +182 -0
  48. package/schemas/providers-remove.v1.json +97 -0
  49. package/schemas/providers-show.v1.json +179 -0
  50. package/schemas/serve.v1.json +97 -0
  51. package/schemas/server-claim.v1.json +97 -0
  52. package/schemas/server-reap.v1.json +97 -0
  53. package/schemas/server-remove.v1.json +97 -0
  54. package/schemas/server-start.v1.json +97 -0
  55. package/schemas/server-status.v1.json +197 -0
  56. package/schemas/server-stop.v1.json +97 -0
  57. package/schemas/server-use.v1.json +97 -0
  58. package/schemas/staging.v1.json +47 -0
  59. package/schemas/tls-ca.v1.json +97 -0
  60. package/schemas/tls-generate.v1.json +97 -0
  61. package/schemas/tokens-expire.v1.json +97 -0
  62. package/schemas/tokens-import.v1.json +192 -0
  63. package/schemas/tokens-issue.v1.json +94 -0
  64. package/schemas/tokens-list.v1.json +272 -0
  65. package/schemas/tokens-recover-admin.v1.json +116 -0
  66. package/schemas/tokens-revoke.v1.json +97 -0
  67. package/schemas/tokens-rotate.v1.json +94 -0
  68. package/schemas/tokens-show.v1.json +269 -0
  69. package/schemas/tunnel-down.v1.json +97 -0
  70. package/schemas/tunnel-status.v1.json +165 -0
  71. package/schemas/tunnel-up.v1.json +97 -0
  72. package/schemas/usage.v1.json +621 -0
  73. package/schemas/verification.v1.json +254 -0
  74. package/schemas/verify.v1.json +338 -0
  75. package/schemas/version.v1.json +103 -0
  76. package/schemas/with.v1.json +105 -0
  77. package/src/accounts.mjs +233 -0
  78. package/src/activitypub.mjs +23 -0
  79. package/src/admin-assets.mjs +16 -0
  80. package/src/admin.mjs +108 -0
  81. package/src/affinities.mjs +180 -0
  82. package/src/affinity-schema-descriptor.mjs +2 -0
  83. package/src/affinity-schema.mjs +185 -0
  84. package/src/assets/admin/assets/app.js +1 -0
  85. package/src/assets/admin/assets/react.js +9 -0
  86. package/src/assets/admin/assets/rolldown-runtime.js +1 -0
  87. package/src/assets/admin/assets/ui-vendor.js +3 -0
  88. package/src/assets/admin/index.html +16 -0
  89. package/src/auth-service.mjs +149 -0
  90. package/src/claude-process-session.mjs +26 -0
  91. package/src/cli-output.mjs +21 -0
  92. package/src/cli.mjs +84 -0
  93. package/src/client-ca.mjs +8 -0
  94. package/src/client-catalog.mjs +52 -0
  95. package/src/client-codex-catalog.mjs +18 -0
  96. package/src/client-configure.mjs +72 -0
  97. package/src/client-files.mjs +82 -0
  98. package/src/client-global-repair.mjs +19 -0
  99. package/src/client-global-state.mjs +19 -0
  100. package/src/client-global.mjs +43 -0
  101. package/src/client-json.mjs +54 -0
  102. package/src/client-launch-plan.mjs +28 -0
  103. package/src/client-launch.mjs +35 -0
  104. package/src/client-persistent.mjs +66 -0
  105. package/src/client-process-profile.mjs +52 -0
  106. package/src/client-process-settings.mjs +36 -0
  107. package/src/client-process.mjs +44 -0
  108. package/src/client-profile-backup.mjs +29 -0
  109. package/src/client-remote-health.mjs +7 -0
  110. package/src/client-remote.mjs +55 -0
  111. package/src/client-run-credential.mjs +38 -0
  112. package/src/client-setup.mjs +97 -0
  113. package/src/client-status.mjs +102 -0
  114. package/src/client-toml-cst.mjs +71 -0
  115. package/src/client-transaction.mjs +48 -0
  116. package/src/codex-login.mjs +121 -0
  117. package/src/codex-loopback-transport.mjs +34 -0
  118. package/src/codex-loopback.mjs +60 -0
  119. package/src/config.mjs +198 -0
  120. package/src/core.mjs +198 -0
  121. package/src/credential-operations.mjs +119 -0
  122. package/src/doublets.mjs +157 -0
  123. package/src/emergency-auth.mjs +91 -0
  124. package/src/file-lock.mjs +107 -0
  125. package/src/gemini-protocol.mjs +133 -0
  126. package/src/geolocation.mjs +46 -0
  127. package/src/git-proxy.mjs +52 -0
  128. package/src/github-proxy.mjs +74 -0
  129. package/src/http-management.mjs +36 -0
  130. package/src/http-route-contract.mjs +479 -0
  131. package/src/index.mjs +4 -0
  132. package/src/local-router-discovery.mjs +31 -0
  133. package/src/managed-server.mjs +411 -0
  134. package/src/management-access.mjs +76 -0
  135. package/src/native-service.mjs +392 -0
  136. package/src/oauth.mjs +547 -0
  137. package/src/operation-input.mjs +20 -0
  138. package/src/operations.mjs +378 -0
  139. package/src/protocols.mjs +229 -0
  140. package/src/provider-manifest.mjs +46 -0
  141. package/src/provider-provision.mjs +24 -0
  142. package/src/remote-operations.mjs +166 -0
  143. package/src/request-log.mjs +99 -0
  144. package/src/resources.mjs +290 -0
  145. package/src/response-contracts.mjs +147 -0
  146. package/src/responses.mjs +103 -0
  147. package/src/routing.mjs +40 -0
  148. package/src/sensitive-data-sse.mjs +121 -0
  149. package/src/sensitive-data.mjs +254 -0
  150. package/src/server.mjs +552 -0
  151. package/src/storage.mjs +367 -0
  152. package/src/streams.mjs +232 -0
  153. package/src/token-import.mjs +68 -0
  154. package/src/token-reservation.mjs +8 -0
  155. package/src/tokens.mjs +172 -0
  156. package/src/usage.mjs +54 -0
  157. package/src/websocket-relay.mjs +131 -0
  158. package/testing.d.ts +7 -0
  159. package/testing.js +57 -0
@@ -0,0 +1,38 @@
1
+ /** Exact per-run model authority and renewable lifetime; no credential is persisted here. */
2
+ import {clientFailure,clientIntegration} from './client-files.mjs';
3
+ import {preflightNativeClientLaunch,nativeClientRequiresModel} from './client-launch-plan.mjs';
4
+ import {nativeClientModelAuthorized,selectNativeClientModel} from './client-catalog.mjs';
5
+ import {validateModelPolicy} from './tokens.mjs';import {prepareRemoteRunCredential} from './client-remote.mjs';import {sendRemoteManagement} from './remote-operations.mjs';
6
+ export function nativeRunBaseSelector(model){
7
+ if(typeof model!=='string'||Buffer.byteLength(model)>65536)throw clientFailure('Model selector must be bounded text');const open=model.lastIndexOf('(');if(open<=0||!model.endsWith(')'))return model;const suffix=model.slice(open+1,-1),word=suffix.toLowerCase();let interpreted=['none','auto','-1','minimal','low','medium','high','xhigh','max'].includes(word);
8
+ if(!interpreted&&(/^-0+$/u.test(suffix)||/^\+?\d+$/u.test(suffix))){try{const value=BigInt(suffix);interpreted=value>=0n&&value<=4294967295n;}catch{}}
9
+ return interpreted?model.slice(0,open):model;
10
+ }
11
+ export function requestNativeRunModelPolicy(client,options={}){
12
+ for(const flag of ['pick_model','allow_model_substitution'])if(options[flag]!==undefined&&typeof options[flag]!=='boolean')throw clientFailure('Run model flags must be Boolean');
13
+ const info=clientIntegration(client),preflight=preflightNativeClientLaunch(client,options),selected=options.model??preflight.forwardedModel;
14
+ if(selected!==null&&(typeof selected!=='string'||!selected.trim()))throw clientFailure('Explicit model id must be nonempty');const extra=options.allowed_models??[];if(!Array.isArray(extra)||extra.length>4096||extra.some(value=>typeof value!=='string'||!value.trim()))throw clientFailure('Allowed models require bounded nonempty ids');
15
+ if((extra.length||options.allow_model_substitution)&&selected===null&&!options.pick_model)throw clientFailure('Widening a model grant requires an explicit model or --pick-model');
16
+ const allowed=[...new Set([...(selected===null?[]:[selected]),...extra].map(nativeRunBaseSelector))].sort();if(allowed.some(value=>!value.trim()))throw clientFailure('Base model id must be nonempty');const policy=validateModelPolicy({allowed_models:allowed,allow_substitution:options.allow_model_substitution===true,substitution_source:options.allow_model_substitution?'router with --allow-model-substitution':null});return {client:info.client,selected,pick:options.pick_model===true,policy};
17
+ }
18
+ export function resolveNativeRunModel(request,catalog){
19
+ let selected=request.selected;if(selected===null&&request.pick){selected=selectNativeClientModel(request.client,catalog);if(selected===null)throw clientFailure('The authorized catalog contains no model for this client');}
20
+ if(selected===null&&nativeClientRequiresModel(request.client))throw clientFailure('This client requires an explicit model or --pick-model');
21
+ for(const model of request.policy.allowed_models)if(!nativeClientModelAuthorized(request.client,catalog,model))throw clientFailure('Allowed model is not available from the selected Router');if(selected!==null&&!nativeClientModelAuthorized(request.client,catalog,nativeRunBaseSelector(selected)))throw clientFailure('Selected model is not available from the authorized live catalog');return selected;
22
+ }
23
+ export function classifyNativeRunLeaseStatus(status){return status>=200&&status<=299?'renewed':[404,405].includes(status)?'unsupported':[401,403].includes(status)?'rejected':status===409?'refused':'transient';}
24
+ async function withLease(credential,context,operation){
25
+ if(!credential.runLease)return operation();const controller=new AbortController();let stopped=false,timer,inFlight=null,last='renewed';
26
+ const tick=async()=>{let state='transient';try{const answer=await sendRemoteManagement({server:credential.origin,managementServer:credential.origin,managementCaCert:credential.caCert,token:credential.token},{method:'POST',path:'/api/run-lease',response:'status-only'},{fetch:context.fetch,signal:controller.signal,deadlineMs:10000,maxOutputBytes:65536,cwd:context.invocation?.cwd});state=classifyNativeRunLeaseStatus(answer.status);}catch{}if(stopped)return;if(state!==last){if(Array.isArray(context.notes)&&context.notes.length<64)context.notes.push('run lease '+state);last=state;}if(state==='unsupported'){stopped=true;return;}timer=setTimeout(start,30000);};
27
+ const start=()=>{if(!stopped)inFlight=tick();};timer=setTimeout(start,30000);
28
+ try{return await operation();}finally{stopped=true;clearTimeout(timer);controller.abort();if(inFlight)await inFlight;}
29
+ }
30
+ export async function withNativeRunCredential(context,operation){
31
+ const request=requestNativeRunModelPolicy(context.client,context.options),options=context.options??{},held=[];let primary=null;
32
+ try{
33
+ let credential=await prepareRemoteRunCredential({...context,client:request.client,modelPolicy:request.pick?{allowed_models:[],allow_substitution:false,substitution_source:null}:request.policy,ttlHours:options.run_ttl_hours??1,slidingExpiry:!options.fixed_run_ttl,maxRequests:options.run_max_requests,label:options.label});held.push(credential);const selected=resolveNativeRunModel(request,credential.catalog);
34
+ if(request.pick&&selected!==null&&!request.policy.allowed_models.includes(nativeRunBaseSelector(selected))){const policy=validateModelPolicy({...request.policy,allowed_models:[...new Set([nativeRunBaseSelector(selected),...request.policy.allowed_models])].sort()});const replacement=await prepareRemoteRunCredential({...context,client:request.client,modelPolicy:policy,ttlHours:options.run_ttl_hours??1,slidingExpiry:!options.fixed_run_ttl,maxRequests:options.run_max_requests,label:options.label});held.push(replacement);await credential.cleanup();credential=replacement;resolveNativeRunModel({...request,selected,policy},credential.catalog);}
35
+ return await withLease(credential,context,()=>operation({...credential,selectedModel:selected}));
36
+ }catch(error){primary=error;throw error;}
37
+ finally{const failures=[];for(const credential of [...held].reverse())try{await credential.cleanup();}catch(error){failures.push(error);}if(failures.length){const failure=clientFailure('Run credential cleanup failed; the finite token TTL remains the backstop');Object.assign(failure,{cause:primary});throw failure;}}
38
+ }
@@ -0,0 +1,97 @@
1
+ /** Managed client token provisioning and atomic configuration for JSON clients. */
2
+ import {createHash} from 'node:crypto';
3
+ import {clientPaths,clientFailure,clientObject,optionalClientText,preferredClientPath,readClientEnvironment,writeClientEnvironment,writeClientMarker,removeClientFile} from './client-files.mjs';
4
+ import {fetchNativeClientCatalog,clientRouterOrigin} from './client-catalog.mjs';
5
+ import {setupClientJSON,removeClientJSON} from './client-json.mjs';
6
+ import {nativeClientStatus} from './client-status.mjs';
7
+ import {clientFileTransaction} from './client-transaction.mjs';
8
+ import {selectedManagedTarget} from './managed-server.mjs';
9
+ const implementedClients=new Set(['opencode','agent','qwen','grok','claude','codex']);
10
+ const completeBinding=(claims,client)=>{
11
+ if(claims.client_kind!==client || typeof claims.principal_id!=='string' || !claims.principal_id.trim() || typeof claims.sub!=='string' || !claims.sub) throw clientFailure('Supplied token requires the exact canonical managed-client binding and subscriber principal');
12
+ return {token_id:claims.sub,principal_id:claims.principal_id};
13
+ };
14
+ function decodedBinding(token,client) {
15
+ if(Buffer.byteLength(token)>65536 || !token.startsWith('la_sk_')) throw clientFailure('Supplied Router token requires la_sk_ prefix');
16
+ const parts=token.slice(6).split('.');if(parts.length!==3 || parts.some(part=>!part || !/^[A-Za-z0-9_-]+$/.test(part))) throw clientFailure('Invalid supplied Router token encoding');
17
+ let claims;try{claims=JSON.parse(new TextDecoder('utf8',{fatal:true}).decode(Buffer.from(parts[1],'base64url')));}catch{throw clientFailure('Invalid supplied Router token payload');}
18
+ return completeBinding(claims,client);
19
+ }
20
+ function canonicalOrigin(value) {const origin=clientRouterOrigin(value),url=new URL(origin);if(url.pathname!=='/') throw clientFailure('Client setup requires a Router origin without a path');return origin;}
21
+ function localOrigin(config) {let host=config.host ?? '127.0.0.1';if(host==='0.0.0.0') host='127.0.0.1';if(host==='::') host='::1';if(host.includes(':') && !host.startsWith('[')) host=`[${host}]`;return canonicalOrigin(`http://${host}:${config.port ?? 8080}`);}
22
+ const metadataPath=paths=>preferredClientPath(paths.metadata,paths.legacyMetadata);
23
+ async function setupNativeClientWithoutCodexBridge({options,invocation={},core,env={},fetch,checkpoint,codexBackend=null}={}) {
24
+ const paths=clientPaths(options.client,{home:options.home,env,cwd:invocation.cwd}),{info}=paths;
25
+ if(info.unsupported) throw clientFailure(info.unsupported);
26
+ if(!implementedClients.has(info.client)) throw clientFailure('This client does not support persistent Router configuration');
27
+ if(await optionalClientText(paths.config+'.with-router-state.json')!==null) throw clientFailure('Reversible global client state requires the full undo-state contract; existing setup preserved');
28
+ if(options.management_server&&!options.base_url) throw clientFailure('--management-server requires an explicit Router base URL');
29
+ if(!options.base_url && await selectedManagedTarget({name:'clients.setup',config:core.config,env,cwd:invocation.cwd})) throw clientFailure('clients setup mints locally; a selected remote Router requires configure or an explicit base URL');
30
+ const origin=options.base_url ? canonicalOrigin(options.base_url) : localOrigin(core.config),context={home:options.home,env,cwd:invocation.cwd};
31
+ const status=await nativeClientStatus(info.client,context),oldEnvironment=await preferredClientPath(paths.environment,paths.legacyEnvironment),oldMetadata=await optionalClientText(await metadataPath(paths));
32
+ const oldToken=readClientEnvironment(await optionalClientText(oldEnvironment),info.token),oldRecord=oldMetadata===null ? null : clientObject(oldMetadata,'Ownership metadata');
33
+ if(status.ownership_state==='managed-intact' && oldRecord?.router===origin && oldToken && await codexNativeBackendMatches(paths,origin,codexBackend)) {
34
+ try {if(options.management_server){if(!await reuseRemoteClientCredential({client:info.client,origin,managementServer:options.management_server,config:core.config,env,invocation,fetch},oldRecord,oldToken))throw clientFailure('Remote credential requires replacement');}else completeBinding(await core.tokens.validate(oldToken),info.client);return {output:[`${info.client} is already configured in ${paths.config}`,`credentials: ${oldEnvironment} (mode 0600)`]};}catch{/* Replacement must verify a new complete credential below. */}
35
+ }
36
+ let token=options.token_stdin ? String(invocation.stdin ?? '').trim() : String(options.token ?? env.LINK_ASSISTANT_ROUTER_TOKEN ?? env.LINK_ASSISTANT_TOKEN ?? '').trim();
37
+ let record,minted=null,catalog,foreign=false,setupBackup=null,remote=null;
38
+ try {
39
+ if(options.management_server){remote=await prepareRemoteClientCredential({client:info.client,origin,managementServer:options.management_server,suppliedToken:token,ttlHours:options.ttl_hours,config:core.config,env,invocation,fetch,nowUnix:core.clock()});token=remote.token;record=remote.record;catalog=remote.catalog;}else if(token) {
40
+ const decoded=decodedBinding(token,info.client);let local;
41
+ try {local=await core.tokens.validate(token);}catch{/* Issuing Router catalog must authenticate foreign credentials. */}
42
+ foreign=!local;const binding=local ? completeBinding(local,info.client) : decoded;
43
+ record={client:info.client,source:'supplied',...binding,label:null,issued_at:null,router:origin,principal_id:binding.principal_id,config_sha256:null};
44
+ } else {
45
+ const issued=await core.tokens.issue({ttl_hours:options.ttl_hours===undefined ? 24 : Number(options.ttl_hours),label:`client-${info.client}`,account:'primary',client_kind:info.client,principal_id:'primary'});
46
+ token=issued.token;minted=issued.id;record={client:info.client,source:'minted',token_id:issued.id,label:`client-${info.client}`,issued_at:core.clock(),router:origin,principal_id:'primary',config_sha256:null};
47
+ }
48
+ if(remote){catalog=remote.catalog;}else if(info.client!=='grok' || foreign) {
49
+ const all=await fetchNativeClientCatalog(info.client,origin,token,{fetch,signal:invocation.signal});
50
+ const preferred=info.owners.flatMap(owner=>all.filter(row=>row.owned_by===owner));catalog=info.owners.length && (preferred.length || info.strict) ? preferred : all;
51
+ } else catalog=[];
52
+ let backup;
53
+ const result=await clientFileTransaction(paths,async txn=>{
54
+ await txn.verify(paths.config);if(paths.marker) await txn.verify(paths.marker);
55
+ const configured=info.client==='grok' ? {path:paths.config,backup:null,changed:false} : await (['claude','codex'].includes(info.client)?setupPersistentClient:setupClientJSON)(paths,origin+info.suffix,catalog,{backendBaseURL:codexBackend,onWrite:async(path,result)=>{if(result?.backup) setupBackup=result.backup;await txn.advance([path]);}});backup=configured.backup;
56
+ await txn.checkpoint('config');await txn.verify(txn.environment);await writeClientEnvironment(paths,origin,token);await txn.advance([txn.environment]);
57
+ await txn.checkpoint('environment');await txn.verify(txn.metadata);
58
+ record.config_sha256=createHash('sha256').update(await optionalClientText(paths.config) ?? '').digest('hex');await writeClientMarker(txn.metadata,record);await txn.advance([txn.metadata]);await txn.checkpoint('metadata');return configured;
59
+ },{checkpoint});
60
+ return {output:[info.client==='grok' ? 'configured grok through its environment; its own config file was not changed' : `${result.changed ? 'configured' : 'already configured'} ${info.client} in ${paths.config}`,...(backup ? [`backup: ${backup}`] : []),`credentials: ${await preferredClientPath(paths.environment,paths.legacyEnvironment)} (mode 0600)`,'The token is not stored in the client config or printed to the terminal.']};
61
+ } catch(error) {if(remote) await remote.cleanup();if(minted) await core.tokens.revoke(minted);if(setupBackup) await removeClientFile(setupBackup);throw error;}
62
+ }
63
+ export async function removeNativeClient({options,invocation={},core,env={},checkpoint,fetch=globalThis.fetch}={}) {
64
+ const paths=clientPaths(options.client,{home:options.home,env,cwd:invocation.cwd}),{info}=paths;
65
+ if(!implementedClients.has(info.client)) throw clientFailure('This client does not support persistent Router removal');
66
+ if(await optionalClientText(paths.config+'.with-router-state.json')!==null) throw clientFailure('Reversible global client state requires the full undo-state contract; existing setup preserved');
67
+ const path=await metadataPath(paths),source=await optionalClientText(path),record=source===null ? null : clientObject(source,'Ownership metadata');
68
+ if(record && (![info.client,info.legacy].includes(record.client) || !['minted','supplied'].includes(record.source))) throw clientFailure('Invalid managed credential metadata');
69
+ if(record && (record.source==='minted' || options.revoke_supplied)) {
70
+ if(typeof record.token_id!=='string' || !record.token_id) {if(!options.force) throw clientFailure('Credential token ID is missing; configuration preserved');}
71
+ else if(record.management_server){await revokeRemoteClientCredential(record,{config:core.config,env,invocation,fetch});}
72
+ else {
73
+ const held=(await core.tokens.list()).find(token=>token.id===record.token_id);
74
+ if(!held && !options.force) throw clientFailure('Managed token does not belong to this local store; configuration preserved');
75
+ if(held) await core.tokens.revoke(record.token_id);
76
+ }
77
+ }
78
+ const result=await clientFileTransaction(paths,async txn=>{
79
+ const removed=info.client==='grok' ? {path:paths.config,backup:null,changed:false} : await (['claude','codex'].includes(info.client)?removePersistentClient:removeClientJSON)(paths,{onWrite:path=>txn.advance([path])});
80
+ await txn.checkpoint('config');await txn.verify(txn.environment);await removeClientFile(txn.environment);await txn.advance([txn.environment]);
81
+ await txn.verify(txn.metadata);await removeClientFile(txn.metadata);await txn.advance([txn.metadata]);await txn.checkpoint('metadata');return removed;
82
+ },{checkpoint});
83
+ await stopCodexNativeBridge(paths);
84
+ return {output:[`Removed Router configuration for ${info.client}`,...(result.backup ? [`backup: ${result.backup}`] : [])]};
85
+ }
86
+
87
+ import {setupPersistentClient,removePersistentClient} from './client-persistent.mjs';
88
+
89
+ import {prepareRemoteClientCredential,reuseRemoteClientCredential,revokeRemoteClientCredential} from './client-remote.mjs';
90
+
91
+ export async function setupNativeClient(args={}){
92
+ const {options,invocation={},core,env={}}=args,paths=clientPaths(options.client,{home:options.home,env,cwd:invocation.cwd});
93
+ if(paths.info.client!=='codex'||await optionalClientText(paths.config+'.with-router-state.json')!==null)return setupNativeClientWithoutCodexBridge(args);
94
+ const origin=options.base_url?canonicalOrigin(options.base_url):localOrigin(core.config);return withCodexNativeBridge(paths,origin,backend=>setupNativeClientWithoutCodexBridge({...args,codexBackend:backend}),{config:core.config,env,cwd:invocation.cwd});
95
+ }
96
+
97
+ import {withCodexNativeBridge,stopCodexNativeBridge,codexNativeBackendMatches} from './codex-loopback.mjs';
@@ -0,0 +1,102 @@
1
+ /** Secret-free observations and routing precedence for all eight client integrations. */
2
+ import {parseClientTomlSource} from './client-toml-cst.mjs';
3
+ import {clientPaths,optionalClientText,preferredClientPath,clientObject,readClientEnvironment,clientCommandExists,clientFailure} from './client-files.mjs';
4
+ const modelKeys=['ANTHROPIC_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_DEFAULT_HAIKU_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'];
5
+ const claudePrecedence=['ANTHROPIC_AUTH_TOKEN','ANTHROPIC_API_KEY',...modelKeys,'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY','CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC'];
6
+ const strip=value=>value?.replace(/\/+$/,'');
7
+ const text=value=>typeof value==='string' ? value : null;
8
+ const safeOrigin=value=>{try {const url=new URL(value);return ['http:','https:'].includes(url.protocol) ? url.origin : null;}catch{return null;}};
9
+ function publicDocument(client,source) {
10
+ if(client==='codex') {try{return parseClientTomlSource(source ?? '');}catch{throw clientFailure('Client configuration contains invalid TOML');}}
11
+ return clientObject(source);
12
+ }
13
+ function publicBase(paths,document,environment,env) {
14
+ switch(paths.info.client) {
15
+ case 'codex': {
16
+ const provider=document.model_providers?.['link-assistant'];
17
+ return document.model_provider==='link-assistant' && provider?.wire_api==='responses' && (provider?.env_key==='LINK_ASSISTANT_TOKEN'||provider?.requires_openai_auth===true) ? text(provider.base_url) : null;
18
+ }
19
+ case 'claude':return text(document.env?.ANTHROPIC_BASE_URL);
20
+ case 'opencode':case 'agent':return text(document.provider?.['link-assistant']?.options?.baseURL);
21
+ case 'qwen':return text((Array.isArray(document.modelProviders?.openai) ? document.modelProviders.openai : []).find(model=>model?.envKey==='LINK_ASSISTANT_TOKEN')?.baseUrl);
22
+ case 'gemini':case 'grok':return text(env[paths.info.base]) ?? readClientEnvironment(environment,paths.info.base);
23
+ default:return null;
24
+ }
25
+ }
26
+ function claudeEntries(marker) {
27
+ const env=marker?.gateway_env;
28
+ if(!env || typeof env!=='object' || Array.isArray(env)) return [];
29
+ return Object.entries(env).flatMap(([key,value])=>value && (value.managed===null || value.managed===undefined || typeof value.managed==='string') ? [{key,managed_value:value.managed ?? null}] : []);
30
+ }
31
+ function validClaudeMarker(marker,expected) {
32
+ // Current Rust markers retain env entries and user-owned model keys; old markers
33
+ // with just the endpoint are incomplete and never establish intact ownership.
34
+ const entries=claudeEntries(marker),users=marker?.user_model_keys ?? [];
35
+ if(!Array.isArray(users) || users.some(key=>!modelKeys.includes(key)) || new Set(users).size!==users.length || typeof marker?.anthropic_base_url!=='string') return false;
36
+ const get=key=>entries.find(entry=>entry.key===key),managed=key=>get(key)?.managed_value ?? null;
37
+ const fixed=[['CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY','1'],['ANTHROPIC_AUTH_TOKEN',null],['ANTHROPIC_API_KEY',null]].every(([key,value])=>get(key) && managed(key)===value);
38
+ const target=entries.find(entry=>['ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'].includes(entry.key))?.managed_value ?? null;
39
+ return (!expected || marker.anthropic_base_url===expected) && fixed && (target===null || typeof target==='string' && target.length>0)
40
+ && modelKeys.every(key=>Boolean(get(key))!==users.includes(key))
41
+ && ['ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'].every(key=>users.includes(key) || managed(key)===target)
42
+ && modelKeys.filter(key=>!['ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'].includes(key)).every(key=>users.includes(key) || get(key) && managed(key)===null)
43
+ && !get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC');
44
+ }
45
+ export async function nativeClientStatus(name,options={}) {
46
+ const paths=clientPaths(name,options),{info}=paths,ambientEnv=options.env ?? process.env,env=options.home!==undefined ? {} : ambientEnv,conflicts=[];
47
+ let source=null,document={},unreadable;
48
+ try {source=await optionalClientText(paths.config);document=publicDocument(info.client,source);}catch(error) {unreadable=error.message;conflicts.push('public-config:invalid');}
49
+ let environment=null,metadata=null,marker=null,environmentExists=false,metadataExists=false,markerExists=false;
50
+ try {const path=await preferredClientPath(paths.environment,paths.legacyEnvironment);environment=await optionalClientText(path);environmentExists=environment!==null;}catch{environmentExists=true;conflicts.push('managed-environment:invalid');}
51
+ try {const path=await preferredClientPath(paths.metadata,paths.legacyMetadata),value=await optionalClientText(path);metadataExists=value!==null;if(metadataExists) metadata=clientObject(value,'Ownership metadata');}catch{metadataExists=true;conflicts.push('ownership-metadata:invalid');}
52
+ if(paths.marker) try {const value=await optionalClientText(paths.marker);markerExists=value!==null;if(markerExists) marker=clientObject(value,'Ownership marker');}catch{markerExists=true;conflicts.push('ownership-marker:invalid');}
53
+ const metadataComplete=metadata && [info.client,info.legacy].includes(metadata.client) && typeof metadata.router==='string' && metadata.router.length>0 && ['minted','supplied'].includes(metadata.source);
54
+ if(metadata && !metadataComplete) conflicts.push('ownership-metadata:invalid');
55
+ const expected=metadata?.router ? strip(metadata.router)+info.suffix : null;
56
+ const token=info.token ? readClientEnvironment(environment,info.token) : null,managedBase=info.base ? readClientEnvironment(environment,info.base) : null;
57
+ const base=publicBase(paths,document,environment,env),ambient=info.base && typeof env[info.base]==='string' && env[info.base] ? env[info.base] : null;
58
+ let markerValid=!paths.marker;
59
+ if(markerExists) {
60
+ markerValid=info.client==='codex' ? Boolean(marker) : info.client==='claude' ? validClaudeMarker(marker,expected) : info.client==='qwen' ? Array.isArray(marker?.managed_models) : Object.hasOwn(marker ?? {},'managed_provider');
61
+ if(!markerValid) conflicts.push('ownership-marker:invalid');
62
+ }
63
+ if(ambient && expected && strip(ambient)!==strip(expected)) conflicts.push(`ambient:${info.base}`);
64
+ if(info.token && env[info.token] && token!==null && env[info.token]!==token) conflicts.push(`ambient:${info.token}`);
65
+ if(managedBase!==null && expected && strip(managedBase)!==strip(expected)) conflicts.push(`managed-environment:${info.base}`);
66
+ if(environmentExists && info.token && token===null) conflicts.push(`managed-environment:${info.token}`);
67
+ if(info.client==='codex') {
68
+ if(expected && document.model_provider!=='link-assistant') conflicts.push('public-config:model_provider');
69
+ if(expected && document.model_providers?.['link-assistant']?.base_url!==expected) conflicts.push('public-config:model_providers.link-assistant.base_url');
70
+ if(Object.hasOwn(document,'model_catalog_json')) conflicts.push('public-config:model_catalog_json');
71
+ } else if(['opencode','agent'].includes(info.client)) {
72
+ if(expected && document.provider?.['link-assistant']?.options?.baseURL!==expected) conflicts.push('public-config:provider.link-assistant.options.baseURL');
73
+ } else if(info.client==='qwen') {
74
+ if(expected && !(Array.isArray(document.modelProviders?.openai) ? document.modelProviders.openai : []).some(model=>model?.envKey==='LINK_ASSISTANT_TOKEN' && model?.baseUrl===expected)) conflicts.push('public-config:modelProviders.openai');
75
+ } else if(info.client==='claude') {
76
+ const entries=claudeEntries(marker),users=Array.isArray(marker?.user_model_keys) ? marker.user_model_keys : [],publicEnv=document.env ?? {};
77
+ if(expected && strip(publicEnv.ANTHROPIC_BASE_URL)!==strip(expected)) conflicts.push('public-config:ANTHROPIC_BASE_URL');
78
+ for(const key of ['ANTHROPIC_AUTH_TOKEN','ANTHROPIC_API_KEY']) if(Object.hasOwn(publicEnv,key)) conflicts.push(`public-config:${key}`);
79
+ for(const key of modelKeys) {
80
+ const wanted=entries.find(entry=>entry.key===key)?.managed_value ?? null;
81
+ if(!users.includes(key) && (text(publicEnv[key]) ?? null)!==wanted) conflicts.push(`public-config:${key}`);
82
+ if(env[key] && env[key]!==wanted) conflicts.push(`ambient:${key}`);
83
+ if(readClientEnvironment(environment,key)) conflicts.push(`managed-environment:${key}`);
84
+ }
85
+ const discovery='CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY';
86
+ if(readClientEnvironment(environment,discovery)!=='1') conflicts.push(`managed-environment:${discovery}`);
87
+ if(publicEnv[discovery]!=='1' && source!==null) conflicts.push(`public-config:${discovery}`);
88
+ if(env[discovery] && env[discovery]!=='1') conflicts.push(`ambient:${discovery}`);
89
+ for(const key of ['ANTHROPIC_API_KEY','CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC']) {
90
+ if(env[key]) conflicts.push(`ambient:${key}`);if(readClientEnvironment(environment,key)) conflicts.push(`managed-environment:${key}`);
91
+ }
92
+ }
93
+ const complete=environmentExists && metadataComplete && token!==null && (['grok','gemini'].includes(info.client) || source!==null) && markerValid;
94
+ const anyManaged=environmentExists || metadataExists || markerExists;
95
+ const any=source!==null || base!==null || managedBase!==null || ambient!==null || anyManaged || info.client==='claude' && claudePrecedence.some(key=>Boolean(env[key]));
96
+ const unique=[...new Set(conflicts)].sort();
97
+ const state=unreadable || unique.some(key=>key.endsWith(':invalid')) || anyManaged && !complete ? 'ambiguous' : complete ? unique.length ? 'managed-drifted' : 'managed-intact' : any ? 'foreign' : 'unconfigured';
98
+ const effective_source=ambient!==null ? 'ambient-environment' : base!==null ? 'public-config' : managedBase!==null ? 'managed-environment' : metadata?.router ? 'ownership-metadata' : null;
99
+ return {client:info.client,installed:await clientCommandExists(info.client,ambientEnv),configured:state==='managed-intact',config_path:paths.config,dialect:info.dialect,
100
+ base_url:safeOrigin(ambient ?? base ?? managedBase ?? metadata?.router),token_env:info.token,token_env_set:Boolean(info.token && (env[info.token] || token!==null)),ownership_state:state,
101
+ ...(effective_source ? {effective_source} : {}),conflicts:unique,...(unreadable ? {unreadable} : {}),...(info.unsupported ? {unsupported:info.unsupported} : {})};
102
+ }
@@ -0,0 +1,71 @@
1
+ /** Lossless TOML field substitutions; native parsing remains an external library. */
2
+ import TOML from '@iarna/toml';
3
+ import {types,isDeepStrictEqual} from 'node:util';
4
+ import {clientFailure} from './client-files.mjs';
5
+ const LIMIT=8*1024*1024;
6
+ const samePath=(left,right)=>left.length===right.length&&left.every((key,at)=>key===right[at]);
7
+ const prefix=(left,right)=>left.length<=right.length&&left.every((key,at)=>key===right[at]);
8
+ const fail=(message)=>{throw clientFailure(message);};
9
+ export function parseClientTomlSource(source){if(typeof source!=='string'||Buffer.byteLength(source)>LIMIT)fail('Client TOML source exceeds its bound');try{return TOML.parse((source[0]==='\uFEFF'?source.slice(1):source).replace(/\r\n/gu,'\n'));}catch{return fail('Client configuration contains invalid TOML');}}
10
+ function keyPath(text){
11
+ let value;try{value=TOML.parse(text+' = 0');}catch{fail('Client TOML key syntax is invalid');}const path=[];
12
+ for(let depth=0;depth<64;depth++){if(value===0)return path;const keys=Object.keys(value);if(keys.length!==1)fail('Client TOML key must have one source path');path.push(keys[0]);value=value[keys[0]];}return fail('Client TOML key depth exceeds its bound');
13
+ }
14
+ function tokenize(source){
15
+ const cells=[];let at=0;
16
+ while(at<source.length){if(cells.length>=200000)fail('Client TOML source token bound');const start=at,char=source[at];let kind='token';
17
+ if(/[ \t\r\n\uFEFF]/u.test(char)){kind='trivia';while(at<source.length&&/[ \t\r\n\uFEFF]/u.test(source[at]))at++;}
18
+ else if(char==='#'){kind='comment';while(at<source.length&&source[at]!=='\n')at++;}
19
+ else if(char==='"'||char==="'"){
20
+ kind='string';const triple=source.slice(at,at+3)===char.repeat(3);at+=triple?3:1;let closed=false;
21
+ while(at<source.length){if(char==='"'&&source[at]==='\\'){at+=2;continue;}if(source[at]===char){if(!triple){at++;closed=true;break;}let end=at;while(source[end]===char)end++;if(end-at>=3){at=end;closed=true;break;}at=end;}else at++;}
22
+ if(!closed)fail('Client TOML string is incomplete');
23
+ }else if('[]=,.{}'.includes(char)){at++;}
24
+ else {while(at<source.length&&!/[ \t\r\n#"'\[\]{}=,.]/u.test(source[at]))at++;if(at===start)at++;}
25
+ cells.push({kind,start,end:at,text:source.slice(start,at)});
26
+ }
27
+ const meta=JSON.stringify({schema:'router-client-toml-cst-v1',language:'TOML',representation:'ConcreteSyntax',cells}),decoded=JSON.parse(meta);let end=0,copy='';for(const cell of decoded.cells){if(cell.start!==end||cell.end!==cell.start+cell.text.length||source.slice(cell.start,cell.end)!==cell.text)fail('Client TOML CST span differs');end=cell.end;copy+=cell.text;}if(end!==source.length||copy!==source)fail('Client TOML CST inverse differs');return decoded.cells;
28
+ }
29
+ function structure(source){
30
+ const tokens=tokenize(source),nodes=[],headers=[];let work=0;
31
+ const trivia=(at)=>{while(at<tokens.length&&['trivia','comment'].includes(tokens[at].kind))at++;return at;};
32
+ const is=(at,word)=>tokens[at]?.kind==='token'&&tokens[at].text===word;
33
+ const lineStart=(at)=>{const start=source.lastIndexOf('\n',at-1)+1;return start===0&&source[0]==='\uFEFF'?1:start;};
34
+ const lineEnd=(at)=>{const end=source.indexOf('\n',at);return end<0?source.length:end+1;};
35
+ function value(at,path,id,depth){
36
+ if(++work>200000||depth>64)fail('Client TOML structure bound');at=trivia(at);const start=tokens[at]?.start;if(start===undefined)fail('Client TOML value is incomplete');
37
+ if(is(at,'{')){const children=[];let previous=null;at=trivia(at+1);while(!is(at,'}')){const entry=assignment(at,path,true,id,depth+1);entry.node.commaBefore=previous;children.push(entry.node.id);at=trivia(entry.after);if(is(at,',')){previous={start:tokens[at].start,end:tokens[at].end};entry.node.commaAfter=previous;at=trivia(at+1);}else if(!is(at,'}'))fail('Client TOML inline separator is incomplete');}return {after:at+1,start,end:tokens[at].end,kind:'inline',close:tokens[at].start,children};}
38
+ if(is(at,'[')){const stack=[']'];let end=at+1;for(;end<tokens.length&&stack.length;end++){if(tokens[end].kind!=='token')continue;const word=tokens[end].text;if(word==='[')stack.push(']');else if(word==='{')stack.push('}');else if(word===']'||word==='}'){if(stack.pop()!==word)fail('Client TOML array delimiter differs');}if(stack.length>64)fail('Client TOML array depth bound');}if(stack.length)fail('Client TOML array is incomplete');return {after:end,start,end:tokens[end-1].end,kind:'value'};}
39
+ let end=at,last=at;for(;end<tokens.length;end++){const token=tokens[end];if(token.kind==='comment'||token.kind==='trivia'&&/[\r\n]/u.test(token.text)||token.kind==='token'&&[',','}',']'].includes(token.text))break;if(token.kind!=='trivia')last=end;}if(end===at)fail('Client TOML scalar is incomplete');return {after:end,start,end:tokens[last].end,kind:'value'};
40
+ }
41
+ function assignment(at,scope,inline,parent,depth){
42
+ const begin=at;while(at<tokens.length&&!is(at,'='))at++;if(at===tokens.length)fail('Client TOML assignment is incomplete');const path=[...scope,...keyPath(source.slice(tokens[begin].start,tokens[at].start))],node={id:nodes.length,path,start:tokens[begin].start,inline,parent};nodes.push(node);const parsed=value(at+1,path,node.id,depth);Object.assign(node,{valueStart:parsed.start,valueEnd:parsed.end,valueKind:parsed.kind,close:parsed.close,children:parsed.children??[],lineStart:lineStart(node.start),lineEnd:lineEnd(parsed.end)});return {after:parsed.after,node};
43
+ }
44
+ let at=trivia(0),scope=[];while(at<tokens.length){if(++work>200000||nodes.length+headers.length>=16384)fail('Client TOML record bound');if(is(at,'[')){const start=at,array=is(at+1,'[');at+=array?2:1;const begin=at;while(at<tokens.length&&!is(at,']'))at++;if(at===tokens.length||array&&!is(at+1,']'))fail('Client TOML table header is incomplete');scope=keyPath(source.slice(tokens[begin].start,tokens[at].start));at+=array?2:1;headers.push({path:scope,start:lineStart(tokens[start].start),end:lineEnd(tokens[at-1].end),array});}else at=assignment(at,scope,false,null,0).after;at=trivia(at);}
45
+ const tables=[{path:[],start:0,bodyEnd:headers[0]?.start??source.length}];for(let index=0;index<headers.length;index++)tables.push({...headers[index],bodyEnd:headers[index+1]?.start??source.length});return {nodes,headers,tables};
46
+ }
47
+ function changeData(input){
48
+ if(!Array.isArray(input)||types.isProxy(input)||input.length>64)fail('Client TOML mutations require a bounded ordinary list');const changes=[];
49
+ for(let index=0;index<input.length;index++){const slot=Object.getOwnPropertyDescriptor(input,String(index));if(!slot||!Object.hasOwn(slot,'value'))fail('Client TOML mutation accessors are unsupported');const value=slot.value;if(!value||typeof value!=='object'||types.isProxy(value)||![Object.prototype,null].includes(Object.getPrototypeOf(value)))fail('Client TOML mutations require ordinary data');const fields=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(fields).some(key=>typeof key!=='string'||!['path','action','value'].includes(key)||!Object.hasOwn(fields[key],'value')))fail('Client TOML mutation fields differ');const path=fields.path?.value,action=fields.action?.value,replacement=fields.value?.value;if(!Array.isArray(path)||types.isProxy(path)||!path.length||path.length>64)fail('Client TOML mutation path is invalid');const copied=[];for(let at=0;at<path.length;at++){const key=Object.getOwnPropertyDescriptor(path,String(at));if(!key||!Object.hasOwn(key,'value')||typeof key.value!=='string'||key.value.length>4096)fail('Client TOML mutation path fields differ');copied.push(key.value);}if(!['set','delete'].includes(action)||action==='set'&&!['string','boolean'].includes(typeof replacement))fail('Client TOML field mutation requires a scalar string or Boolean');if(changes.some(row=>prefix(row.path,copied)||prefix(copied,row.path)))fail('Client TOML mutation paths overlap');changes.push({path:copied,action,value:replacement});}return changes;
50
+ }
51
+ const own=(object,key)=>object&&typeof object==='object'&&Object.hasOwn(object,key)?object[key]:undefined;
52
+ function assign(document,path,value,remove){let cursor=document;for(const key of path.slice(0,-1)){let child=own(cursor,key);if(child===undefined){if(remove)return;child={};Object.defineProperty(cursor,key,{value:child,writable:true,enumerable:true,configurable:true});}if(!child||typeof child!=='object'||Array.isArray(child)||child instanceof Date)fail('Client TOML field parent is not a table');cursor=child;}if(remove)delete cursor[path[path.length-1]];else Object.defineProperty(cursor,path[path.length-1],{value,writable:true,enumerable:true,configurable:true});}
53
+ export function editClientTomlSource(source,input){
54
+ if(typeof source!=='string'||Buffer.byteLength(source)>LIMIT)fail('Client TOML source exceeds its bound');const changes=changeData(input);let expected;try{expected=parseClientTomlSource(source);}catch{fail('Client configuration contains invalid TOML');}const newline=source.indexOf('\n')>0&&source[source.indexOf('\n')-1]==='\r'?'\r\n':'\n',tree=structure(source),edits=[],inserts=new Map(),deletions=[];
55
+ const erase=(node)=>{if(node.inline){const start=node.commaAfter?node.start:node.commaBefore?.start??node.start,end=node.commaAfter?.end??node.valueEnd;deletions.push({start,end,inline:true});}else deletions.push({start:node.lineStart,end:node.lineEnd});};
56
+ const remove=(path)=>{for(const node of tree.nodes)if(prefix(path,node.path))erase(node);for(const table of tree.tables)if(table.path.length&&prefix(path,table.path))deletions.push({start:table.start,end:table.bodyEnd});};
57
+ const put=(at,inline,container,text)=>{const row=inserts.get(at)??{inline,container,texts:[]};row.texts.push(text);inserts.set(at,row);};
58
+ for(const change of changes){assign(expected,change.path,change.value,change.action==='delete');if(change.action==='delete'){remove(change.path);continue;}const exact=tree.nodes.filter((node)=>samePath(node.path,change.path));if(exact.length>1)fail('Client TOML field has ambiguous source bindings');const stringify=TOML.stringify,text=stringify.value(change.value);if(exact.length){edits.push({start:exact[0].valueStart,end:exact[0].valueEnd,replacement:text});continue;}
59
+ const ancestors=tree.nodes.filter((node)=>node.valueKind==='inline'&&prefix(node.path,change.path)).sort((left,right)=>right.path.length-left.path.length);if(ancestors.length){const ancestor=ancestors[0],key=change.path.slice(ancestor.path.length).map(part=>JSON.stringify(part)).join('.');put(ancestor.close,true,ancestor,key+' = '+text);continue;}
60
+ remove(change.path);const table=tree.tables.filter((row)=>row.path.length<change.path.length&&prefix(row.path,change.path)&&!changes.some(other=>prefix(other.path,row.path))).sort((left,right)=>right.path.length-left.path.length)[0];if(!table)fail('Client TOML field lacks an insertion scope');put(table.bodyEnd,false,null,change.path.slice(table.path.length).map(part=>JSON.stringify(part)).join('.')+' = '+text);
61
+ }
62
+ deletions.sort((left,right)=>left.start-right.start||left.end-right.end);const removed=[];for(const row of deletions){const previous=removed.at(-1);if(previous&&(row.start<=previous.end||previous.inline&&row.inline&&/^[ \t]*$/u.test(source.slice(previous.end,row.start))))previous.end=Math.max(previous.end,row.end);else removed.push({...row});}
63
+ // A deleted run that ends at an inline table's closing brace also drops the comma before it.
64
+ for(const row of removed)if(row.inline){let next=row.end;while(next<source.length&&/[ \t]/u.test(source[next]))next++;if(source[next]==='}'){let back=row.start-1;while(back>=0&&/[ \t]/u.test(source[back]))back--;if(source[back]===',')row.start=back;}}
65
+ for(const row of removed)edits.push({start:row.start,end:row.end,replacement:''});
66
+ for(const [at,row]of inserts){let replacement;if(row.inline){const remaining=row.container.children.map((id)=>tree.nodes[id]).filter((node)=>!changes.some(change=>change.action==='delete'&&prefix(change.path,node.path)));replacement=(remaining.length?', ':' ')+row.texts.join(', ')+' ';}else replacement=(at&&source[at-1]!=='\n'?newline:'')+row.texts.join(newline)+newline;edits.push({start:at,end:at,replacement});}
67
+ edits.sort((left,right)=>left.start-right.start||left.end-right.end);let after='',cursor=0;for(const edit of edits){if(edit.start<cursor)fail('Client TOML source substitutions overlap');after+=source.slice(cursor,edit.start)+edit.replacement;cursor=edit.end;}after+=source.slice(cursor);if(Buffer.byteLength(after)>LIMIT)fail('Client TOML result exceeds its bound');let actual;try{actual=parseClientTomlSource(after);}catch{fail('Client TOML source substitutions produce invalid syntax');}
68
+ // TOML implicit parents disappear when their last source binding is removed.
69
+ for(const change of changes)if(change.action==='delete')for(let depth=change.path.length-1;depth>0;depth--){const path=change.path.slice(0,depth);let parent=expected;for(const key of path.slice(0,-1))parent=own(parent,key);const value=own(parent,path[path.length-1]);if(value&&typeof value==='object'&&!Array.isArray(value)&&!Object.keys(value).length&&!tree.headers.some((row)=>samePath(row.path,path))&&!tree.nodes.some((row)=>row.valueKind==='inline'&&samePath(row.path,path)))delete parent[path[path.length-1]];}
70
+ if(!isDeepStrictEqual(actual,expected))fail('Client TOML source substitutions differ from the requested field values');return {before:source,after,inverse:source,edits,stages:['language','repository'],sourceAuthority:false,semanticAuthority:false};
71
+ }
@@ -0,0 +1,48 @@
1
+ /** Fixed-allow-list client transactions with durable private snapshots and edit fences. */
2
+ import {lstat,mkdir,chmod,rm} from 'node:fs/promises';
3
+ import {join} from 'node:path';
4
+ import {createHash,randomUUID} from 'node:crypto';
5
+ import {optionalClientText,clientFailure,removeClientFile} from './client-files.mjs';
6
+ import {requireNativePath} from './operation-input.mjs';
7
+ import {atomicWrite,serialized} from './storage.mjs';
8
+ import {withAdvisoryFileLock} from './file-lock.mjs';
9
+ const hash=value=>value===null ? null : createHash('sha256').update(value).digest('hex');
10
+ async function state(path) {const source=await optionalClientText(path);return {source,hash:hash(source),mode:source!==null ? (await lstat(path)).mode & 0o7777 : null};}
11
+ export async function clientFileTransaction(paths,operation,{checkpoint=()=>{}}={}) {
12
+ const lock=join(paths.configHome,'link-assistant-router/clients',`${paths.info.client}.repair.lock`);
13
+ await requireNativePath(lock);
14
+ return serialized(lock,()=>withAdvisoryFileLock(lock,async()=>{
15
+ const id=randomUUID().replaceAll('-',''),root=join(paths.configHome,'link-assistant-router/repairs',id);
16
+ await requireNativePath(root);await mkdir(root,{recursive:true,mode:0o700});await chmod(root,0o700);
17
+ const allowed=[paths.config,await (await import('./client-files.mjs')).preferredClientPath(paths.environment,paths.legacyEnvironment),await (await import('./client-files.mjs')).preferredClientPath(paths.metadata,paths.legacyMetadata),...(paths.marker ? [paths.marker] : []),...await globalClientTransactionFiles(paths)].sort();
18
+ const entries=[];
19
+ try {
20
+ for(const [index,path] of [...new Set(allowed)].entries()) {
21
+ const before=await state(path),backup=before.source!==null ? `${index}.backup` : null;
22
+ if(backup) await atomicWrite(join(root,backup),before.source);
23
+ entries.push({path,existed:before.source!==null,mode:before.mode,before_sha256:before.hash,after_sha256:before.hash,backup});
24
+ }
25
+ const manifest={version:1,id,client:paths.info.client,entries};
26
+ const persist=()=>atomicWrite(join(root,'manifest.json'),JSON.stringify(manifest,null,2)+'\n');
27
+ await persist();
28
+ const verify=async path=>{const entry=entries.find(entry=>entry.path===path);if(!entry) throw clientFailure('Client path is outside its transaction allow-list');if((await state(path)).hash!==entry.after_sha256) throw clientFailure('Client configuration changed concurrently; retry');};
29
+ const advance=async changed=>{for(const path of changed) {const entry=entries.find(entry=>entry.path===path);if(!entry) throw clientFailure('Client path is outside its transaction allow-list');entry.after_sha256=(await state(path)).hash;}await persist();};
30
+ for(const path of allowed) await verify(path);
31
+ try {
32
+ const result=await operation({verify,advance,checkpoint,snapshot:id,environment:allowed.find(path=>path===paths.environment || path===paths.legacyEnvironment),metadata:allowed.find(path=>path===paths.metadata || path===paths.legacyMetadata)});
33
+ await advance(allowed);await rm(root,{recursive:true});return result;
34
+ } catch(error) {
35
+ let blocked=false;
36
+ for(const entry of entries) {
37
+ if((await state(entry.path)).hash!==entry.after_sha256) {blocked=true;continue;}
38
+ if(entry.backup) {const source=await optionalClientText(join(root,entry.backup));if(hash(source)!==entry.before_sha256) throw clientFailure('Client transaction snapshot is damaged');await atomicWrite(entry.path,source);if(entry.mode!==null) await chmod(entry.path,entry.mode);}
39
+ else await removeClientFile(entry.path);
40
+ }
41
+ if(blocked) throw clientFailure('Client transaction failed; concurrent edits were preserved and its private snapshot retained');
42
+ await rm(root,{recursive:true});throw error;
43
+ }
44
+ } catch(error) {throw error;}
45
+ }));
46
+ }
47
+
48
+ import {globalClientTransactionFiles} from './client-global-state.mjs';
@@ -0,0 +1,121 @@
1
+ /** Codex public-client device and loopback OAuth authorization. */
2
+ import {createServer} from 'node:http';
3
+ import {createHash,randomUUID} from 'node:crypto';
4
+ import {join} from 'node:path';
5
+ import {rm} from 'node:fs/promises';
6
+ import {setTimeout as sleep} from 'node:timers/promises';
7
+ import {atomicWrite} from './storage.mjs';
8
+ import {CODEX_CLIENT_ID,importCredential,validateCredentialCatalog} from './oauth.mjs';
9
+ const fail=(code,message,status=400)=>Object.assign(new Error(message),{code,status});
10
+ const nonce=()=>randomUUID().replaceAll('-','');
11
+ const encode=value=>encodeURIComponent(value).replace(/[!'()*]/g,char=>`%${char.charCodeAt(0).toString(16).toUpperCase()}`);
12
+ const nonempty=value=>typeof value==='string' && value.trim().length>0;
13
+ function issuerOrigin(value,allowLoopback) {
14
+ let url;try {url=new URL(value);}catch {throw fail('invalid_oauth_endpoint','Codex issuer must be an absolute URL');}
15
+ const local=['127.0.0.1','localhost','[::1]'].includes(url.hostname);
16
+ if (url.username || url.password || url.search || url.hash || !['','/'].includes(url.pathname) || url.origin!=='https://auth.openai.com' && !(allowLoopback && local && ['http:','https:'].includes(url.protocol))) throw fail('invalid_oauth_endpoint','Codex issuer must be official or an explicitly allowed loopback fixture');
17
+ return url.origin;
18
+ }
19
+ async function json(response,signal) {
20
+ const chunks=[];let bytes=0;const reader=response.body?.getReader();
21
+ const abort=new Promise((_,reject)=> {const stop=()=>reject(fail('login_cancelled','Codex authorization cancelled',409));if (signal.aborted) stop();else signal.addEventListener('abort',stop,{once:true});});
22
+ try {
23
+ if (reader) while (true) {const part=await Promise.race([reader.read(),abort]);if (part.done) break;bytes+=part.value.byteLength;if (bytes>1024*1024) throw fail('oauth_response_invalid','Codex response exceeds 1 MiB',502);chunks.push(part.value);}
24
+ const text=new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks,bytes));return text ? JSON.parse(text) : {};
25
+ } catch (error) {if (error.code) throw error;throw fail('oauth_response_invalid','Codex response is not valid UTF-8 JSON',502);}
26
+ finally {if (reader) {Promise.resolve(reader.cancel()).catch(()=>{});try {reader.releaseLock();}catch {}}}
27
+ }
28
+ export class CodexLogin {
29
+ constructor({home,manager,clock=()=>Math.floor(Date.now()/1000),signal,issuer='https://auth.openai.com',codexIssuer,allowLoopback=false,timeoutMs=900000,dataDir,validateCatalog=validateCredentialCatalog,catalogBaseURL,port=1455,flow='auto'}={}) {
30
+ if (!home || !manager?.fetch || !Number.isSafeInteger(timeoutMs) || timeoutMs<=0) throw fail('invalid_login_config','Codex login requires a home, fetch manager and positive deadline');
31
+ this.home=home;this.manager=manager;this.clock=clock;this.issuer=issuerOrigin(codexIssuer ?? issuer,allowLoopback);this.allowLoopback=allowLoopback;this.timeoutMs=timeoutMs;
32
+ this.dataDir=dataDir ?? join(home,'.router');this.validateCatalog=validateCatalog;this.catalogBaseURL=catalogBaseURL ?? (allowLoopback && this.issuer!=='https://auth.openai.com' ? this.issuer : undefined);
33
+ this.port=Number(port);this.flow=flow;this.controller=new AbortController();this.signal=signal ? AbortSignal.any([signal,this.controller.signal]) : this.controller.signal;this.used=false;
34
+ }
35
+ static async begin(options={}) {
36
+ const login=new CodexLogin(options);
37
+ if (['auto','device'].includes(login.flow)) await login.beginDevice();
38
+ else if (login.flow==='loopback') await login.bindCallback();
39
+ else throw fail('invalid_argument','Codex supports device or loopback authorization');
40
+ return login;
41
+ }
42
+ authorizationURL() {return this.url;}
43
+ async request(path,{body,form=false}={}) {
44
+ const signal=AbortSignal.any([this.signal,AbortSignal.timeout(Math.min(this.timeoutMs,20000))]);
45
+ const abort=new Promise((_,reject)=> {const stop=()=>reject(fail('login_cancelled','Codex authorization cancelled or its request deadline elapsed',409));if (signal.aborted) stop();else signal.addEventListener('abort',stop,{once:true});});
46
+ let response;try {response=await Promise.race([this.manager.fetch(this.issuer+path,{method:'POST',redirect:'error',signal,headers:{'content-type':form ? 'application/x-www-form-urlencoded' : 'application/json'},body:form ? body : JSON.stringify(body)}),abort]);}
47
+ catch (error) {if (error.code==='login_cancelled') throw error;throw fail('oauth_exchange_uncertain','Codex authorization request outcome is uncertain',502);}
48
+ if (response.url && new URL(response.url).origin!==this.issuer) throw fail('invalid_oauth_endpoint','Codex response changed issuer origin',502);
49
+ return {status:response.status,ok:response.ok,body:await json(response,signal)};
50
+ }
51
+ async beginDevice() {
52
+ const response=await this.request('/api/accounts/deviceauth/usercode',{body:{client_id:CODEX_CLIENT_ID}});
53
+ if (!response.ok) throw fail('device_authorization_rejected',response.status===404 ? 'Codex device authorization is disabled; use loopback flow' : 'Codex device authorization could not be started',response.status);
54
+ const device=response.body,interval=typeof device.interval==='string' && /^\s*\d+\s*$/.test(device.interval) ? Number(device.interval) : device.interval;
55
+ if (!nonempty(device.device_auth_id) || !nonempty(device.user_code ?? device.usercode) || !Number.isSafeInteger(interval) || interval<0) throw fail('oauth_response_invalid','Codex device response lacks a usable ID, code or interval',502);
56
+ this.deviceId=device.device_auth_id;this.userCode=device.user_code ?? device.usercode;this.interval=interval;this.url=this.issuer+'/codex/device';this.status='awaiting_device';
57
+ }
58
+ async bindCallback() {
59
+ if (this.signal.aborted) throw fail('login_cancelled','Codex callback cancelled',409);
60
+ if (!Number.isInteger(this.port) || this.port<0 || this.port>65535 || this.issuer==='https://auth.openai.com' && ![1455,1457].includes(this.port)) throw fail('invalid_argument','Codex OAuth registers loopback ports 1455 and 1457 only');
61
+ this.state=nonce();this.verifier=nonce()+nonce();let settle;
62
+ this.callback=new Promise((resolve,reject)=>settle={resolve,reject});this.callback.catch(()=>{});
63
+ this.signal.addEventListener('abort',()=>settle.reject(fail('login_cancelled','Codex callback cancelled',409)),{once:true});
64
+ this.server=createServer((request,response)=> {
65
+ const url=new URL(request.url,'http://localhost');
66
+ if (request.method!=='GET' || url.pathname!=='/auth/callback') {response.writeHead(404);response.end();return;}
67
+ if (url.searchParams.get('state')!==this.state) {response.writeHead(400);response.end('OAuth state did not match; authorization is still waiting');return;}
68
+ if (this.handled) {response.writeHead(409);response.end('Authorization callback was already handled');return;}
69
+ this.handled=true;
70
+ const providerError=url.searchParams.get('error'),code=url.searchParams.get('code');
71
+ if (providerError || !code) {
72
+ const safe=['access_denied','server_error','temporarily_unavailable'].includes(providerError) ? providerError : 'provider_error';
73
+ settle.reject(fail('authorization_failed',`Codex callback failed (${safe})`));response.writeHead(400);response.end('Authorization failed. You can close this window.');
74
+ } else {settle.resolve(code);response.writeHead(200);response.end('Authorization received. You can close this window.');}
75
+ });
76
+ this.server.maxHeadersCount=32;this.server.headersTimeout=10000;this.server.requestTimeout=10000;
77
+ await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(this.port,'127.0.0.1',resolve);});
78
+ this.port=this.server.address().port;this.redirectURI=`http://localhost:${this.port}/auth/callback`;
79
+ const pairs={response_type:'code',client_id:CODEX_CLIENT_ID,redirect_uri:this.redirectURI,scope:'openid profile email offline_access api.connectors.read api.connectors.invoke',code_challenge:createHash('sha256').update(this.verifier).digest('base64url'),code_challenge_method:'S256',id_token_add_organizations:'true',codex_cli_simplified_flow:'true',state:this.state,originator:'codex_cli_rs'};
80
+ this.url=this.issuer+'/oauth/authorize?'+Object.entries(pairs).map(([key,value])=>`${encode(key)}=${encode(value)}`).join('&');this.status='awaiting_callback';
81
+ }
82
+ async stopCallback() {
83
+ if (!this.server) return;const server=this.server;this.server=null;
84
+ await new Promise(resolve=>{server.close(resolve);server.closeAllConnections();});
85
+ }
86
+ async cancel() {this.controller.abort();await this.stopCallback();}
87
+ async wait({dataDir=this.dataDir,validateCatalog=this.validateCatalog,catalogBaseURL=this.catalogBaseURL,signal}={}) {
88
+ if (this.used) throw fail('pending_login_consumed','Codex authorization was already consumed',409);this.used=true;
89
+ const timer=setTimeout(()=>this.controller.abort(),this.timeoutMs),extraAbort=()=>this.controller.abort();signal?.addEventListener('abort',extraAbort,{once:true});if (signal?.aborted) extraAbort();
90
+ try {
91
+ let code,verifier,redirect;
92
+ if (this.flow==='loopback') {code=await this.callback;await this.stopCallback();verifier=this.verifier;redirect=this.redirectURI;}
93
+ else while (true) {
94
+ const response=await this.request('/api/accounts/deviceauth/token',{body:{device_auth_id:this.deviceId,user_code:this.userCode}});
95
+ if (response.ok) {
96
+ const value=response.body;
97
+ if (!nonempty(value.authorization_code) || !nonempty(value.code_verifier) || value.code_challenge!==createHash('sha256').update(value.code_verifier).digest('base64url')) throw fail('oauth_pkce_mismatch','Codex device authorization returned inconsistent PKCE values',502);
98
+ code=value.authorization_code;verifier=value.code_verifier;redirect=this.issuer+'/deviceauth/callback';break;
99
+ }
100
+ const providerError=String(response.body.error ?? '').toLowerCase();
101
+ if (response.status===429 || providerError==='slow_down') this.interval+=5;
102
+ else if (['expired_token','access_denied'].includes(providerError)) throw fail('authorization_failed',`Codex device authorization failed (${providerError})`,401);
103
+ else if (![403,404].includes(response.status) && providerError!=='authorization_pending') throw fail('device_authorization_rejected',`Codex device endpoint returned ${response.status}`,response.status);
104
+ await sleep(this.interval*1000,undefined,{signal:this.signal});
105
+ }
106
+ const body=Object.entries({grant_type:'authorization_code',code,redirect_uri:redirect,client_id:CODEX_CLIENT_ID,code_verifier:verifier}).map(([key,value])=>`${encode(key)}=${encode(value)}`).join('&');
107
+ const response=await this.request('/oauth/token',{body,form:true});
108
+ if (!response.ok) throw fail('authorization_failed',`Codex token endpoint returned ${response.status}`,response.status);
109
+ const tokens=response.body;if (!['id_token','access_token','refresh_token'].every(key=>nonempty(tokens[key]))) throw fail('oauth_response_invalid','Codex token response lacks required credential fields',502);
110
+ const document={auth_mode:'chatgpt',tokens:Object.fromEntries(['id_token','access_token','refresh_token'].map(key=>[key,tokens[key]])),last_refresh:new Date(this.clock()*1000).toISOString()};
111
+ const stage=join(dataDir,'auth-import-candidates',nonce()),sourceHome=join(stage,'codex');
112
+ // Preserve the exchanged rotating chain before any subsequent network
113
+ // validation. Failed acceptance retains this private recovery candidate.
114
+ await atomicWrite(join(sourceHome,'auth.json'),JSON.stringify(document,null,2)+'\n');
115
+ try {
116
+ const result=await importCredential({provider:'codex',sourceHome,destinationHome:this.home,dataDir,owned:true,fetch:this.manager.fetch,clock:this.clock,validateCatalog,catalogBaseURL,allowLoopback:this.allowLoopback,beforePromote:()=>{if (this.signal.aborted) throw fail('login_cancelled','Codex authorization cancelled before promotion',409);}});
117
+ await rm(stage,{recursive:true,force:true});return result;
118
+ } catch (error) {error.transaction_id=stage.split('/').at(-1);throw error;}
119
+ } finally {clearTimeout(timer);signal?.removeEventListener('abort',extraAbort);await this.stopCallback();}
120
+ }
121
+ }
@@ -0,0 +1,34 @@
1
+ /** Bounded Codex backend HTTP/WebSocket transport, with one fixed Router upstream. */
2
+ import {createServer,request as httpRequest} from 'node:http';
3
+ import {request as httpsRequest} from 'node:https';
4
+ import {relayWebSocket} from './websocket-relay.mjs';
5
+ import {normalizeManagedOrigin} from './managed-server.mjs';
6
+ import {clientFailure} from './client-files.mjs';
7
+ export const CODEX_BRIDGE_BACKEND='/api/services/codex/backend-api';
8
+ const transport=new Set(['host','connection','proxy-connection','keep-alive','transfer-encoding','upgrade','te','trailer','content-length','accept-encoding','forwarded','x-forwarded-for','x-forwarded-host','x-forwarded-proto','x-real-ip','sec-websocket-key','sec-websocket-version','sec-websocket-extensions','sec-websocket-accept']);
9
+ const hop=new Set(['connection','proxy-connection','keep-alive','transfer-encoding','upgrade','te','trailer','content-length']);
10
+ const credentials=new Set(['authorization','proxy-authorization','set-cookie','set-cookie2','x-api-key','x-goog-api-key','anthropic-auth-token','cookie','chatgpt-account-id']);
11
+ export function codexLoopbackRequired(origin){const host=new URL(normalizeManagedOrigin(origin)).hostname.toLowerCase();return host!=='localhost'&&host!=='[::1]'&&!/^127\.\d+\.\d+\.\d+$/u.test(host);}
12
+ export function codexBridgeHeaders(input,response=false){
13
+ const names=new Set(String(input.connection??'').split(',').map(value=>value.trim().toLowerCase())),headers={};for(const [key,value]of Object.entries(input)){const name=key.toLowerCase();if(value===undefined||names.has(name)||(response?hop.has(name)||credentials.has(name)||name.startsWith('x-router-')||name.startsWith('x-link-assistant-')||/^x-codex-(?:plan-type|active-limit|credits-balance)/u.test(name):transport.has(name)))continue;headers[name]=value;}return headers;
14
+ }
15
+ function target(origin,path){if(typeof path!=='string'||!path.startsWith(CODEX_BRIDGE_BACKEND+'/'))throw clientFailure('Codex bridge route is outside its backend namespace');const url=new URL(path,origin);if(url.origin!==origin||!url.pathname.startsWith(CODEX_BRIDGE_BACKEND+'/'))throw clientFailure('Codex bridge route escapes its backend namespace');return url;}
16
+ export async function startCodexLoopbackTransport({upstreamOrigin,nonce,port=0,onShutdown=async()=>{},upstreamCaCert=null,cwd=process.cwd()}){
17
+ const origin=normalizeManagedOrigin(upstreamOrigin);if(upstreamCaCert!==null){if(new URL(origin).protocol!=='https:')throw clientFailure('Selected Router CA requires an HTTPS bridge origin');await readClientRouterCA(upstreamCaCert,cwd);}if(typeof nonce!=='string'||!/^[a-f0-9]{32}$/u.test(nonce)||!Number.isSafeInteger(port)||port<0||port>65535)throw clientFailure('Codex bridge requires a private nonce and loopback port');const health='/__link_assistant_router/codex_bridge/'+nonce,sockets=new Set(),requests=new Set();let stopped=false;
18
+ const server=createServer(async(incoming,outgoing)=>{
19
+ if(incoming.method==='GET'&&incoming.url===health){outgoing.writeHead(200,{'x-link-assistant-router-codex-bridge':nonce});outgoing.end('ok');return;}
20
+ if(incoming.method==='POST'&&incoming.url===health+'/shutdown'){outgoing.writeHead(200,{'x-link-assistant-router-codex-bridge':nonce});outgoing.end('ok');setImmediate(()=>{void close().then(onShutdown).catch(()=>{});});return;}
21
+ let url;try{url=target(origin,incoming.url);}catch{outgoing.writeHead(404);outgoing.end();return;}
22
+ const parts=[];let bytes=0;try{for await(const part of incoming){bytes+=part.length;if(bytes>8*1024*1024){outgoing.writeHead(413);outgoing.end();incoming.resume();return;}parts.push(part);}}catch{outgoing.destroy();return;}
23
+ let ca;try{ca=upstreamCaCert===null?undefined:(await readClientRouterCA(upstreamCaCert,cwd)).ca;}catch{outgoing.writeHead(502);outgoing.end();return;}
24
+ const request=(url.protocol==='https:'?httpsRequest:httpRequest)(url,{method:incoming.method,headers:codexBridgeHeaders(incoming.headers),...(ca?{ca}:{})});requests.add(request);const timer=setTimeout(()=>request.destroy(Error('Codex bridge connect deadline')),15000);request.once('socket',socket=>{if(!socket.connecting)clearTimeout(timer);else socket.once(url.protocol==='https:'?'secureConnect':'connect',()=>clearTimeout(timer));});
25
+ outgoing.once('close',()=>request.destroy());request.once('close',()=>{clearTimeout(timer);requests.delete(request);});request.once('error',()=>{if(!outgoing.headersSent){outgoing.writeHead(502);outgoing.end();}else outgoing.destroy();});request.once('response',response=>{outgoing.writeHead(response.statusCode??502,codexBridgeHeaders(response.headers,true));response.once('error',()=>outgoing.destroy());response.pipe(outgoing);});request.end(Buffer.concat(parts,bytes));
26
+ });
27
+ server.on('connection',socket=>{sockets.add(socket);socket.once('close',()=>sockets.delete(socket));});server.on('upgrade',(incoming,socket,head)=>{let url;try{url=target(origin,incoming.url);}catch{socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');return;}void relayWebSocket(incoming,socket,head,{target:async()=>({url,headers:new Headers(codexBridgeHeaders(incoming.headers)),claims:{},...(upstreamCaCert===null?{}:{ca:(await readClientRouterCA(upstreamCaCert,cwd)).ca})}),authorize:async()=>{},core:{},maxMessageBytes:16*1024*1024,timeoutMs:15000}).catch(()=>socket.destroy());});
28
+ server.requestTimeout=15000;server.headersTimeout=10000;server.maxHeadersCount=256;server.maxConnections=64;
29
+ await new Promise((resolve,reject)=>{const failed=(error)=>reject(error);server.once('error',failed);server.listen(port,'127.0.0.1',()=>{server.removeListener('error',failed);resolve();});});
30
+ async function close(){if(stopped)return;stopped=true;for(const request of requests)request.destroy();for(const socket of sockets)socket.destroy();await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));}
31
+ const address=server.address();if(address===null||typeof address==='string'){await close();throw clientFailure('Codex bridge did not bind an IP listener');}const loopbackOrigin='http://127.0.0.1:'+address.port;return {loopbackOrigin,backendBaseURL:loopbackOrigin+CODEX_BRIDGE_BACKEND,healthURL:loopbackOrigin+health,close};
32
+ }
33
+
34
+ import {readClientRouterCA} from './client-ca.mjs';