@link-assistant/router 0.0.0-stage → 1.26.0
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.
- package/README.md +35 -2
- package/catalog.json +68542 -0
- package/index.d.ts +5932 -0
- package/index.js +224 -0
- package/native.d.ts +106 -0
- package/package.json +62 -4
- package/portable/policy.mjs +117 -0
- package/schemas/accounts-list.v1.json +323 -0
- package/schemas/accounts-pause.v1.json +97 -0
- package/schemas/accounts-policy.v1.json +214 -0
- package/schemas/accounts-resume.v1.json +97 -0
- package/schemas/auth-claude.v1.json +97 -0
- package/schemas/auth-clear.v1.json +97 -0
- package/schemas/auth-codex.v1.json +97 -0
- package/schemas/auth-gh.v1.json +97 -0
- package/schemas/auth-import.v1.json +167 -0
- package/schemas/auth-status.v1.json +387 -0
- package/schemas/cli-error.v1.json +97 -0
- package/schemas/clients-backup-create.v1.json +97 -0
- package/schemas/clients-backup-list.v1.json +234 -0
- package/schemas/clients-backup-restore.v1.json +97 -0
- package/schemas/clients-backup-verify.v1.json +125 -0
- package/schemas/clients-doctor.v1.json +249 -0
- package/schemas/clients-install.v1.json +164 -0
- package/schemas/clients-list.v1.json +194 -0
- package/schemas/clients-reinstall.v1.json +164 -0
- package/schemas/clients-remove.v1.json +97 -0
- package/schemas/clients-repair.v1.json +109 -0
- package/schemas/clients-reset.v1.json +113 -0
- package/schemas/clients-setup.v1.json +97 -0
- package/schemas/clients-show.v1.json +191 -0
- package/schemas/clients-update.v1.json +164 -0
- package/schemas/configure.v1.json +97 -0
- package/schemas/contracts.v1.json +106 -0
- package/schemas/data-backup.v1.json +32 -0
- package/schemas/deploy.v1.json +546 -0
- package/schemas/doctor.v1.json +324 -0
- package/schemas/local-deployment.v1.json +364 -0
- package/schemas/logs-anomalies.v1.json +112 -0
- package/schemas/logs-show.v1.json +127 -0
- package/schemas/logs-summary.v1.json +129 -0
- package/schemas/model-catalog.v1.json +117 -0
- package/schemas/models-explain.v1.json +325 -0
- package/schemas/preservation.v1.json +47 -0
- package/schemas/providers-add.v1.json +185 -0
- package/schemas/providers-import.v1.json +97 -0
- package/schemas/providers-list.v1.json +182 -0
- package/schemas/providers-remove.v1.json +97 -0
- package/schemas/providers-show.v1.json +179 -0
- package/schemas/serve.v1.json +97 -0
- package/schemas/server-claim.v1.json +97 -0
- package/schemas/server-reap.v1.json +97 -0
- package/schemas/server-remove.v1.json +97 -0
- package/schemas/server-start.v1.json +97 -0
- package/schemas/server-status.v1.json +197 -0
- package/schemas/server-stop.v1.json +97 -0
- package/schemas/server-use.v1.json +97 -0
- package/schemas/staging.v1.json +47 -0
- package/schemas/tls-ca.v1.json +97 -0
- package/schemas/tls-generate.v1.json +97 -0
- package/schemas/tokens-expire.v1.json +97 -0
- package/schemas/tokens-import.v1.json +192 -0
- package/schemas/tokens-issue.v1.json +94 -0
- package/schemas/tokens-list.v1.json +272 -0
- package/schemas/tokens-recover-admin.v1.json +116 -0
- package/schemas/tokens-revoke.v1.json +97 -0
- package/schemas/tokens-rotate.v1.json +94 -0
- package/schemas/tokens-show.v1.json +269 -0
- package/schemas/tunnel-down.v1.json +97 -0
- package/schemas/tunnel-status.v1.json +165 -0
- package/schemas/tunnel-up.v1.json +97 -0
- package/schemas/usage.v1.json +621 -0
- package/schemas/verification.v1.json +254 -0
- package/schemas/verify.v1.json +338 -0
- package/schemas/version.v1.json +103 -0
- package/schemas/with.v1.json +105 -0
- package/src/accounts.mjs +233 -0
- package/src/activitypub.mjs +23 -0
- package/src/admin-assets.mjs +16 -0
- package/src/admin.mjs +108 -0
- package/src/affinities.mjs +180 -0
- package/src/affinity-schema-descriptor.mjs +2 -0
- package/src/affinity-schema.mjs +185 -0
- package/src/assets/admin/assets/app.js +1 -0
- package/src/assets/admin/assets/react.js +9 -0
- package/src/assets/admin/assets/rolldown-runtime.js +1 -0
- package/src/assets/admin/assets/ui-vendor.js +3 -0
- package/src/assets/admin/index.html +16 -0
- package/src/auth-service.mjs +149 -0
- package/src/claude-process-session.mjs +26 -0
- package/src/cli-output.mjs +21 -0
- package/src/cli.mjs +84 -0
- package/src/client-ca.mjs +8 -0
- package/src/client-catalog.mjs +52 -0
- package/src/client-codex-catalog.mjs +18 -0
- package/src/client-configure.mjs +72 -0
- package/src/client-files.mjs +82 -0
- package/src/client-global-repair.mjs +19 -0
- package/src/client-global-state.mjs +19 -0
- package/src/client-global.mjs +43 -0
- package/src/client-json.mjs +54 -0
- package/src/client-launch-plan.mjs +28 -0
- package/src/client-launch.mjs +35 -0
- package/src/client-persistent.mjs +66 -0
- package/src/client-process-profile.mjs +52 -0
- package/src/client-process-settings.mjs +36 -0
- package/src/client-process.mjs +44 -0
- package/src/client-profile-backup.mjs +29 -0
- package/src/client-remote-health.mjs +7 -0
- package/src/client-remote.mjs +55 -0
- package/src/client-run-credential.mjs +38 -0
- package/src/client-setup.mjs +97 -0
- package/src/client-status.mjs +102 -0
- package/src/client-toml-cst.mjs +71 -0
- package/src/client-transaction.mjs +48 -0
- package/src/codex-login.mjs +121 -0
- package/src/codex-loopback-transport.mjs +34 -0
- package/src/codex-loopback.mjs +60 -0
- package/src/config.mjs +198 -0
- package/src/core.mjs +198 -0
- package/src/credential-operations.mjs +119 -0
- package/src/doublets.mjs +157 -0
- package/src/emergency-auth.mjs +91 -0
- package/src/file-lock.mjs +107 -0
- package/src/gemini-protocol.mjs +133 -0
- package/src/geolocation.mjs +46 -0
- package/src/git-proxy.mjs +52 -0
- package/src/github-proxy.mjs +74 -0
- package/src/http-management.mjs +36 -0
- package/src/http-route-contract.mjs +479 -0
- package/src/index.mjs +4 -0
- package/src/local-router-discovery.mjs +31 -0
- package/src/managed-server.mjs +411 -0
- package/src/management-access.mjs +76 -0
- package/src/native-service.mjs +392 -0
- package/src/oauth.mjs +547 -0
- package/src/operation-input.mjs +20 -0
- package/src/operations.mjs +378 -0
- package/src/protocols.mjs +229 -0
- package/src/provider-manifest.mjs +46 -0
- package/src/provider-provision.mjs +24 -0
- package/src/remote-operations.mjs +166 -0
- package/src/request-log.mjs +99 -0
- package/src/resources.mjs +290 -0
- package/src/response-contracts.mjs +147 -0
- package/src/responses.mjs +103 -0
- package/src/routing.mjs +40 -0
- package/src/runtime-config.mjs +133 -0
- package/src/runtime-payload.mjs +190 -0
- package/src/sensitive-data-sse.mjs +121 -0
- package/src/sensitive-data.mjs +254 -0
- package/src/server.mjs +552 -0
- package/src/storage.mjs +367 -0
- package/src/streams.mjs +232 -0
- package/src/token-import.mjs +68 -0
- package/src/token-reservation.mjs +8 -0
- package/src/tokens.mjs +172 -0
- package/src/usage.mjs +54 -0
- package/src/websocket-relay.mjs +131 -0
- package/testing.d.ts +7 -0
- package/testing.js +57 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** Separate native-JS Codex bridge owner state; never signals an unproved PID. */
|
|
2
|
+
import {request} from 'node:http';
|
|
3
|
+
import {spawn} from 'node:child_process';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {lstat} from 'node:fs/promises';
|
|
6
|
+
import {join,dirname,resolve,isAbsolute} from 'node:path';
|
|
7
|
+
import {fileURLToPath} from 'node:url';
|
|
8
|
+
import {optionalClientText,removeClientFile,clientFailure} from './client-files.mjs';
|
|
9
|
+
import {atomicWrite,serialized} from './storage.mjs';
|
|
10
|
+
import {withAdvisoryFileLock} from './file-lock.mjs';
|
|
11
|
+
import {requireNativePath} from './operation-input.mjs';
|
|
12
|
+
import {normalizeManagedOrigin} from './managed-server.mjs';
|
|
13
|
+
import {startCodexLoopbackTransport,CODEX_BRIDGE_BACKEND,codexLoopbackRequired} from './codex-loopback-transport.mjs';
|
|
14
|
+
const SELF=fileURLToPath(import.meta.url),ENGINE='router-native-codex-loopback-v1',MARKER='LINK_ASSISTANT_ROUTER_NATIVE_CODEX_BRIDGE';
|
|
15
|
+
const sleep=(ms)=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
16
|
+
export function codexNativeBridgeStatePath(paths){return join(dirname(paths.environment),'codex.native-loopback-bridge.json');}
|
|
17
|
+
async function readState(path){
|
|
18
|
+
const source=await optionalClientText(path);if(source===null)return null;if(Buffer.byteLength(source)>65536)throw clientFailure('Codex bridge state exceeds its bound');if(process.platform!=='win32'&&((await lstat(path)).mode&0o077)!==0)throw clientFailure('Codex bridge state must be owner-private');let state;try{state=JSON.parse(source);}catch{throw clientFailure('Codex bridge state is malformed');}
|
|
19
|
+
if(!state||state.engine!==ENGINE||state.version!==1||!Number.isSafeInteger(state.pid)||state.pid<=0||typeof state.nonce!=='string'||!/^[a-f0-9]{32}$/u.test(state.nonce)||normalizeManagedOrigin(state.upstream_origin)!==state.upstream_origin||typeof state.loopback_origin!=='string')throw clientFailure('Codex bridge state is not owned by this runtime');if(state.ca_cert_path!==undefined&&state.ca_cert_path!==null&&(typeof state.ca_cert_path!=='string'||!isAbsolute(state.ca_cert_path)||state.ca_cert_path.includes('\0')))throw clientFailure('Codex bridge CA path is invalid');const url=new URL(state.loopback_origin);if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||!url.port||url.origin!==state.loopback_origin)throw clientFailure('Codex bridge state requires a literal IPv4 loopback listener');return {source,state};
|
|
20
|
+
}
|
|
21
|
+
async function matching(path,saved){return await optionalClientText(path)===saved.source;}
|
|
22
|
+
async function removeMatching(path,saved){const current=await optionalClientText(path);if(current===null)return;if(current!==saved.source)throw clientFailure('Codex bridge state changed concurrently; it was preserved');await removeClientFile(path);}
|
|
23
|
+
function alive(pid){try{process.kill(pid,0);return true;}catch(error){return Object(error).code!=='ESRCH';}}
|
|
24
|
+
function probe(state,shutdown=false){
|
|
25
|
+
return new Promise(resolve=>{let done=false;const settle=(value)=>{if(done)return;done=true;clearTimeout(timer);resolve(value);},url=state.loopback_origin+'/__link_assistant_router/codex_bridge/'+state.nonce+(shutdown?'/shutdown':''),timer=setTimeout(()=>{call.destroy();settle(false);},shutdown?1000:300),call=request(url,{method:shutdown?'POST':'GET',agent:false},response=>{const valid=response.statusCode===200&&response.headers['x-link-assistant-router-codex-bridge']===state.nonce;response.resume();response.once('end',()=>settle(valid));response.once('error',()=>settle(false));});call.once('error',()=>settle(false));call.end();});
|
|
26
|
+
}
|
|
27
|
+
async function stopOwned(path,saved){
|
|
28
|
+
if(!await matching(path,saved))throw clientFailure('Codex bridge state changed concurrently');if(!await probe(saved.state)){if(alive(saved.state.pid))throw clientFailure('Codex bridge process is live but its ownership probe failed; state preserved');await removeMatching(path,saved);return;}if(!await probe(saved.state,true))throw clientFailure('Owned Codex bridge refused shutdown');const deadline=Date.now()+3000;while(await probe(saved.state)){if(Date.now()>=deadline)throw clientFailure('Owned Codex bridge did not stop within its deadline');await sleep(25);}const current=await optionalClientText(path);if(current!==null)await removeMatching(path,saved);
|
|
29
|
+
}
|
|
30
|
+
async function startOwned(path,origin,port,caCert=null){
|
|
31
|
+
const nonce=randomUUID().replaceAll('-',''),env={[MARKER]:'1',ROUTER_CODEX_BRIDGE_STATE:path,ROUTER_CODEX_BRIDGE_UPSTREAM:origin,ROUTER_CODEX_BRIDGE_NONCE:nonce,ROUTER_CODEX_BRIDGE_PORT:String(port)};if(caCert!==null)env.ROUTER_CODEX_BRIDGE_CA=caCert;if(process.platform==='win32')for(const key of ['SystemRoot','WINDIR','TEMP','TMP'])if(process.env[key])env[key]=process.env[key];
|
|
32
|
+
const child=spawn(process.execPath,[SELF],{env,stdio:'ignore',detached:process.platform!=='win32',windowsHide:true});let exited=false;child.once('exit',()=>{exited=true;});child.once('error',()=>{exited=true;});child.unref();const deadline=Date.now()+5000;
|
|
33
|
+
try{while(Date.now()<deadline){let saved;try{saved=await readState(path);}catch{saved=null;}if(saved&&saved.state.pid===child.pid&&saved.state.nonce===nonce&&saved.state.upstream_origin===origin&&(saved.state.ca_cert_path??null)===caCert&&await probe(saved.state))return {...saved,child};if(exited)throw clientFailure('Codex bridge child failed before ownership verification');await sleep(25);}throw clientFailure('Codex bridge startup deadline exceeded');}catch(error){if(!exited)await terminateSpawned(child);const saved=await readState(path).catch(()=>null);if(saved&&saved.state.pid===child.pid&&saved.state.nonce===nonce)await removeMatching(path,saved);throw error;}
|
|
34
|
+
}
|
|
35
|
+
async function terminateSpawned(child){
|
|
36
|
+
if(!child||child.exitCode!==null||child.signalCode!==null)return;child.kill('SIGTERM');let deadline=Date.now()+3000;while(child.exitCode===null&&child.signalCode===null&&Date.now()<deadline)await sleep(25);if(child.exitCode===null&&child.signalCode===null){child.kill('SIGKILL');deadline=Date.now()+1000;while(child.exitCode===null&&child.signalCode===null&&Date.now()<deadline)await sleep(25);if(child.exitCode===null&&child.signalCode===null)throw clientFailure('Owned newly spawned Codex child did not exit after termination');}
|
|
37
|
+
}
|
|
38
|
+
async function rollbackStarted(path,saved){
|
|
39
|
+
try{await stopOwned(path,saved);}catch(error){await terminateSpawned(saved.child);throw error;}
|
|
40
|
+
}
|
|
41
|
+
export async function withCodexNativeBridge(paths,origin,operation,context={}){
|
|
42
|
+
origin=normalizeManagedOrigin(origin);if(paths.info.client!=='codex')return operation(null);const selected=await selectedManagedTarget({name:'clients.setup',options:{server:origin},config:context.config??{},env:context.env??{},cwd:context.cwd??process.cwd()}),selectedCA=context.caCert??selected?.caCert??null,caCert=selectedCA===null?null:(await readClientRouterCA(selectedCA,context.cwd??process.cwd())).path;const path=codexNativeBridgeStatePath(paths),lock=path+'.lock';await requireNativePath(lock);
|
|
43
|
+
return serialized(lock,()=>withAdvisoryFileLock(lock,async()=>{let saved=await readState(path),started=false;
|
|
44
|
+
if(!codexLoopbackRequired(origin)){const result=await operation(null);if(saved)await stopOwned(path,saved);return result;}
|
|
45
|
+
if(!saved||saved.state.upstream_origin!==origin||(saved.state.ca_cert_path??null)!==caCert||!await probe(saved.state)){const port=saved&&saved.state.upstream_origin===origin?Number(new URL(saved.state.loopback_origin).port):0;if(saved)await stopOwned(path,saved);try{saved=await startOwned(path,origin,port,caCert);}catch(error){if(!port)throw error;saved=await startOwned(path,origin,0,caCert);}started=true;}
|
|
46
|
+
try{return await operation(saved.state.loopback_origin+CODEX_BRIDGE_BACKEND);}catch(error){if(started)await rollbackStarted(path,saved);throw error;}
|
|
47
|
+
},{timeout:5000}));
|
|
48
|
+
}
|
|
49
|
+
export async function stopCodexNativeBridge(paths){if(paths.info.client!=='codex')return;const path=codexNativeBridgeStatePath(paths),lock=path+'.lock';await requireNativePath(lock);await serialized(lock,()=>withAdvisoryFileLock(lock,async()=>{const saved=await readState(path);if(saved)await stopOwned(path,saved);},{timeout:3000}));}
|
|
50
|
+
async function runDaemon(){
|
|
51
|
+
const path=process.env.ROUTER_CODEX_BRIDGE_STATE,origin=process.env.ROUTER_CODEX_BRIDGE_UPSTREAM,nonce=process.env.ROUTER_CODEX_BRIDGE_NONCE,port=Number(process.env.ROUTER_CODEX_BRIDGE_PORT),caCert=process.env.ROUTER_CODEX_BRIDGE_CA??null;if(!path||!isAbsolute(path)||!origin||!nonce)throw clientFailure('Incomplete owned Codex bridge child environment');await requireNativePath(path);let saved=null;const finish=async()=>{if(saved&&await optionalClientText(path)===saved.source)await removeMatching(path,saved);};
|
|
52
|
+
const server=await startCodexLoopbackTransport({upstreamOrigin:origin,nonce,port,onShutdown:finish,upstreamCaCert:caCert});const state={engine:ENGINE,version:1,pid:process.pid,upstream_origin:normalizeManagedOrigin(origin),loopback_origin:server.loopbackOrigin,nonce,ca_cert_path:caCert},source=JSON.stringify(state)+'\n';await atomicWrite(path,source);saved={source,state};const stop=()=>{void server.close().then(finish).catch(()=>{});};process.once('SIGTERM',stop);process.once('SIGINT',stop);
|
|
53
|
+
}
|
|
54
|
+
if(process.argv[1]&&resolve(process.argv[1])===SELF){if(process.env[MARKER]!=='1')throw clientFailure('Codex bridge entry requires its owned child environment');await runDaemon();}
|
|
55
|
+
|
|
56
|
+
import {parseClientTomlSource} from './client-toml-cst.mjs';
|
|
57
|
+
export async function codexNativeBackendMatches(paths,origin,backend){if(paths.info.client!=='codex')return true;const source=await optionalClientText(paths.config);if(source===null)return false;try{return parseClientTomlSource(source).chatgpt_base_url===(backend??normalizeManagedOrigin(origin)+CODEX_BRIDGE_BACKEND);}catch{return false;}}
|
|
58
|
+
|
|
59
|
+
import {selectedManagedTarget} from './managed-server.mjs';
|
|
60
|
+
import {readClientRouterCA} from './client-ca.mjs';
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { createHash, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { transactionalWrite, recoverTransactionalWrite, readOptional, serialized } from './storage.mjs';
|
|
5
|
+
import { rustLockPath, withAdvisoryFileLock } from './file-lock.mjs';
|
|
6
|
+
import { RouterError, ensureRealSecret } from './tokens.mjs';
|
|
7
|
+
import { normalizeEmergencyConfig } from './emergency-auth.mjs';
|
|
8
|
+
|
|
9
|
+
export function parseLenv(text) {
|
|
10
|
+
const values = Object.create(null);
|
|
11
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
12
|
+
const line = raw.trim(); if (!line || line.startsWith('#')) continue;
|
|
13
|
+
const match = /^([A-Za-z_][\w]*)(?:\s*:\s*|\s*=\s*)(.*)$/.exec(line);
|
|
14
|
+
if (!match) throw new RouterError('invalid_config',`Invalid configuration line: ${line.split(/[=:]/)[0]}`);
|
|
15
|
+
let value = match[2];
|
|
16
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1,-1);
|
|
17
|
+
values[match[1]] = value;
|
|
18
|
+
}
|
|
19
|
+
return values;
|
|
20
|
+
}
|
|
21
|
+
const bool = value => {
|
|
22
|
+
if (typeof value === 'boolean') return value;
|
|
23
|
+
const normalized = String(value).trim().toLowerCase();
|
|
24
|
+
if (['true','1','yes','on'].includes(normalized)) return true;
|
|
25
|
+
if (['false','0','no','off'].includes(normalized)) return false;
|
|
26
|
+
throw new RouterError('invalid_config','Boolean configuration must be true or false');
|
|
27
|
+
};
|
|
28
|
+
export const nativeConfigOptions = new Set(['token_secret','data_dir','storage_policy','host','port','account_strategy',
|
|
29
|
+
'account_failover','account_cooldown_seconds','account_max_cooldown_seconds','session_affinity_ttl_seconds',
|
|
30
|
+
'token_admin_key','admin_key','allow_anonymous_admin','disable_login_api','login_max_sessions','login_session_ttl_secs',
|
|
31
|
+
'claude_code_home','claude_home','codex_home','gemini_home','qwen_home','home','openai_compatible_provider_name',
|
|
32
|
+
'management_allow_remote','management_lockout_failures','management_lockout_secs','management_lockout_exempt_loopback',
|
|
33
|
+
'emergency_accept_any_token','emergency_allow_non_loopback','emergency_duration_minutes']);
|
|
34
|
+
export const nativeConfigEnvironment = {TOKEN_SECRET:'token_secret',DATA_DIR:'data_dir',STORAGE_POLICY:'storage_policy',HOST:'host',PORT:'port',
|
|
35
|
+
ACCOUNT_STRATEGY:'account_strategy',ACCOUNT_FAILOVER:'account_failover',ACCOUNT_COOLDOWN_SECONDS:'account_cooldown_seconds',
|
|
36
|
+
SESSION_AFFINITY_TTL_SECONDS:'session_affinity_ttl_seconds',TOKEN_ADMIN_KEY:'token_admin_key',CLAUDE_CODE_HOME:'claude_code_home',CODEX_HOME:'codex_home',GEMINI_HOME:'gemini_home',QWEN_HOME:'qwen_home',
|
|
37
|
+
MANAGEMENT_ALLOW_REMOTE:'management_allow_remote',MANAGEMENT_LOCKOUT_FAILURES:'management_lockout_failures',MANAGEMENT_LOCKOUT_SECS:'management_lockout_secs',MANAGEMENT_LOCKOUT_EXEMPT_LOOPBACK:'management_lockout_exempt_loopback',
|
|
38
|
+
EMERGENCY_ACCEPT_ANY_TOKEN:'emergency_accept_any_token',EMERGENCY_ALLOW_NON_LOOPBACK:'emergency_allow_non_loopback',EMERGENCY_DURATION_MINUTES:'emergency_duration_minutes'};
|
|
39
|
+
export function normalizeProvider(record, env = process.env) {
|
|
40
|
+
const name = record.name ?? record.provider_name ?? record.provider;
|
|
41
|
+
if (typeof name !== 'string' || !/^[A-Za-z0-9._-]+$/.test(name)) throw new RouterError('invalid_provider','Provider name must contain ASCII letters, digits, dash, underscore or dot');
|
|
42
|
+
const base = record.base_url ?? record.baseUrl;
|
|
43
|
+
let url;
|
|
44
|
+
try { url = new URL(base); } catch { throw new RouterError('invalid_provider','Provider base_url must be an absolute HTTP URL'); }
|
|
45
|
+
if (!['http:','https:'].includes(url.protocol) || url.username || url.password) throw new RouterError('invalid_provider','Provider base_url must be an HTTP URL without embedded credentials');
|
|
46
|
+
const models = record.models ?? (record.default_model ? [record.default_model] : []);
|
|
47
|
+
if (!Array.isArray(models) || models.some(m => typeof m !== 'string' || !m.trim())) throw new RouterError('invalid_provider','models must contain exact nonempty model ids');
|
|
48
|
+
const aliases = {openai:'openai-compatible',litellm:'openai-compatible','open-a-i-compatible':'openai-compatible',openai_like:'openai-compatible',claude:'anthropic','zai-coding-plan':'z.ai-coding-plan','vertex-ai':'vertex'};
|
|
49
|
+
const rawKind = (record.kind ?? 'openai-compatible').toLowerCase();
|
|
50
|
+
const kind = aliases[rawKind] ?? rawKind;
|
|
51
|
+
if (!['openai-compatible','lefine','z.ai-coding-plan','anthropic','codex','gemini','qwen','gonka','vertex','bedrock'].includes(kind)) throw new RouterError('invalid_provider',`Unknown provider kind '${kind}'`);
|
|
52
|
+
const defaultClients = {anthropic:['claude'],codex:['codex'],gemini:['gemini'],qwen:['qwen'],lefine:['grok','opencode','qwen'],'z.ai-coding-plan':['claude','codex','opencode']};
|
|
53
|
+
const clients = ['lefine','z.ai-coding-plan'].includes(kind) ? [...defaultClients[kind],...(kind === 'z.ai-coding-plan' ? record.unsupported_clients ?? record.acknowledge_unsupported_clients ?? [] : [])] : record.supported_clients ?? defaultClients[kind] ?? [];
|
|
54
|
+
if (!Array.isArray(clients) || clients.some(client => typeof client !== 'string' || !client.trim())) throw new RouterError('invalid_provider','supported_clients must contain exact client names');
|
|
55
|
+
return { ...record, name, kind, base_url:base.replace(/\/+$/,''), models:[...new Set(models)], supported_clients:[...new Set(clients)].sort(), enabled:record.enabled !== false,
|
|
56
|
+
protocol:record.protocol ?? ({anthropic:'anthropic',codex:'responses',gemini:'gemini',vertex:'vertex',bedrock:'bedrock','z.ai-coding-plan':'anthropic'}[kind] ?? 'openai'),
|
|
57
|
+
api_key:record.api_key ?? record.apiKey ?? (record.api_key_env ? env[record.api_key_env] : null) ?? null };
|
|
58
|
+
}
|
|
59
|
+
export function normalizeConfig(input = {}, env = process.env) {
|
|
60
|
+
const config = { ...input };
|
|
61
|
+
config.token_secret = input.token_secret ?? input.tokenSecret ?? env.TOKEN_SECRET;
|
|
62
|
+
config.data_dir = resolve(input.data_dir ?? input.dataDir ?? env.DATA_DIR ?? '.router');
|
|
63
|
+
const rawStorage = input.storage_policy ?? input.storagePolicy ?? env.STORAGE_POLICY ?? 'both';
|
|
64
|
+
config.storage_policy = ({mem:'memory',none:'memory',txt:'text',lino:'text',bin:'binary','link-cli':'binary',linkcli:'binary',clink:'binary',dual:'both'}[rawStorage] ?? rawStorage);
|
|
65
|
+
if (!['memory','text','binary','both'].includes(config.storage_policy)) throw new RouterError('invalid_config','Unknown storage_policy');
|
|
66
|
+
config.host = input.host ?? env.HOST ?? '127.0.0.1'; config.port = Number(input.port ?? env.PORT ?? 8080);
|
|
67
|
+
if (!Number.isInteger(config.port) || config.port < 0 || config.port > 65535) throw new RouterError('invalid_config','port must be between 0 and 65535');
|
|
68
|
+
config.account_strategy = input.account_strategy ?? env.ACCOUNT_STRATEGY ?? 'round-robin';
|
|
69
|
+
config.account_failover = bool(input.account_failover ?? env.ACCOUNT_FAILOVER ?? false);
|
|
70
|
+
config.account_cooldown_seconds = Number(input.account_cooldown_seconds ?? env.ACCOUNT_COOLDOWN_SECONDS ?? 60);
|
|
71
|
+
config.account_max_cooldown_seconds = Number(input.account_max_cooldown_seconds ?? 604800);
|
|
72
|
+
config.session_affinity_ttl_seconds = Number(input.session_affinity_ttl_seconds ?? env.SESSION_AFFINITY_TTL_SECONDS ?? 3600);
|
|
73
|
+
for (const name of ['account_cooldown_seconds','account_max_cooldown_seconds','session_affinity_ttl_seconds']) if (!Number.isSafeInteger(config[name]) || config[name] < 0) throw new RouterError('invalid_config',`${name} must be nonnegative seconds`);
|
|
74
|
+
let providers = input.providers ?? [];
|
|
75
|
+
if (!Array.isArray(providers)) providers = Object.entries(providers).map(([name,value]) => ({ name,...value }));
|
|
76
|
+
if (!providers.length && (env.OPENAI_COMPATIBLE_BASE_URL || input.openai_compatible)) {
|
|
77
|
+
providers = [{ name:env.OPENAI_COMPATIBLE_PROVIDER_NAME ?? 'litellm',base_url:env.OPENAI_COMPATIBLE_BASE_URL ?? 'http://localhost:4000/v1',api_key:env.OPENAI_COMPATIBLE_API_KEY,
|
|
78
|
+
default_model:env.OPENAI_COMPATIBLE_MODEL,models:(env.OPENAI_COMPATIBLE_MODELS ?? env.OPENAI_COMPATIBLE_MODEL ?? '').split(',').filter(Boolean),...input.openai_compatible }];
|
|
79
|
+
}
|
|
80
|
+
config.providers = providers.map(p => normalizeProvider(p,env));
|
|
81
|
+
if (new Set(config.providers.map(p => p.name)).size !== config.providers.length) throw new RouterError('invalid_config','Provider names must be unique');
|
|
82
|
+
config.accounts = input.accounts ?? [];
|
|
83
|
+
config.token_admin_key = input.token_admin_key ?? input.admin_key ?? env.TOKEN_ADMIN_KEY ?? null;
|
|
84
|
+
config.allow_anonymous_admin = bool(input.allow_anonymous_admin ?? false);
|
|
85
|
+
config.disable_login_api = bool(input.disable_login_api ?? false);
|
|
86
|
+
config.emergency = normalizeEmergencyConfig(input,env);
|
|
87
|
+
config.management = {
|
|
88
|
+
allow_remote:bool(input.management_allow_remote ?? input.management?.allow_remote ?? env.MANAGEMENT_ALLOW_REMOTE ?? false),
|
|
89
|
+
exempt_loopback:bool(input.management_lockout_exempt_loopback ?? input.management?.exempt_loopback ?? env.MANAGEMENT_LOCKOUT_EXEMPT_LOOPBACK ?? true),
|
|
90
|
+
lockout_failures:Number(input.management_lockout_failures ?? input.management?.lockout_failures ?? env.MANAGEMENT_LOCKOUT_FAILURES ?? 5),
|
|
91
|
+
lockout_secs:Number(input.management_lockout_secs ?? input.management?.lockout_secs ?? env.MANAGEMENT_LOCKOUT_SECS ?? 1800),
|
|
92
|
+
};
|
|
93
|
+
for (const field of ['lockout_failures','lockout_secs']) if (!Number.isSafeInteger(config.management[field]) || config.management[field] < 0) throw new RouterError('invalid_config',`management ${field} must be nonnegative`);
|
|
94
|
+
for (const [environment,field] of Object.entries(nativeConfigEnvironment)) if (config[field] == null && env[environment] != null) config[field] = env[environment];
|
|
95
|
+
for (const field of ['login_max_sessions','login_session_ttl_secs']) if (config[field] != null) {
|
|
96
|
+
config[field] = Number(config[field]); if (!Number.isSafeInteger(config[field]) || config[field] <= 0) throw new RouterError('invalid_config',`${field} must be positive`);
|
|
97
|
+
}
|
|
98
|
+
return config;
|
|
99
|
+
}
|
|
100
|
+
export async function loadConfig({ config = {}, configPath, env = process.env } = {}) {
|
|
101
|
+
let fromFile = {};
|
|
102
|
+
if (configPath) {
|
|
103
|
+
const text = await readFile(configPath,'utf8');
|
|
104
|
+
if (configPath.endsWith('.json') || text.trim().startsWith('{')) fromFile = JSON.parse(text);
|
|
105
|
+
else env = { ...parseLenv(text), ...env };
|
|
106
|
+
}
|
|
107
|
+
if (!config.token_secret && !env.TOKEN_SECRET && env.TOKEN_SECRET_FILE) {
|
|
108
|
+
let secret = await readFile(env.TOKEN_SECRET_FILE,'utf8');
|
|
109
|
+
secret = secret.replace(/\r?\n$/,''); if (!secret) throw new RouterError('invalid_config','TOKEN_SECRET_FILE is empty');
|
|
110
|
+
config = { ...config, token_secret:secret };
|
|
111
|
+
}
|
|
112
|
+
return normalizeConfig({ ...fromFile, ...config },env);
|
|
113
|
+
}
|
|
114
|
+
export function encryptProviderSecret(secret, tokenSecret) {
|
|
115
|
+
const key = createHash('sha256').update(ensureRealSecret(tokenSecret)).digest(), nonce = randomBytes(12);
|
|
116
|
+
const cipher = createCipheriv('aes-256-gcm',key,nonce);
|
|
117
|
+
const encrypted = Buffer.concat([cipher.update(secret,'utf8'),cipher.final(),cipher.getAuthTag()]);
|
|
118
|
+
return `aes256gcm:${Buffer.concat([nonce,encrypted]).toString('base64')}`;
|
|
119
|
+
}
|
|
120
|
+
export function decryptProviderSecret(secret, tokenSecret) {
|
|
121
|
+
if (!secret.startsWith('aes256gcm:')) throw new RouterError('invalid_provider','Unsupported provider secret format');
|
|
122
|
+
const packed = Buffer.from(secret.slice(10),'base64');
|
|
123
|
+
if (packed.length < 28) throw new RouterError('invalid_provider','Encrypted provider secret is too short');
|
|
124
|
+
const key = createHash('sha256').update(ensureRealSecret(tokenSecret)).digest();
|
|
125
|
+
const decipher = createDecipheriv('aes-256-gcm',key,packed.subarray(0,12));
|
|
126
|
+
decipher.setAuthTag(packed.subarray(-16));
|
|
127
|
+
try { return Buffer.concat([decipher.update(packed.subarray(12,-16)),decipher.final()]).toString('utf8'); }
|
|
128
|
+
catch { throw new RouterError('provider_secret_invalid','Provider secret cannot be decrypted',500); }
|
|
129
|
+
}
|
|
130
|
+
const redact = r => { const { api_key, encrypted_api_key, ...safe } = r; return { ...safe, has_encrypted_api_key:!!encrypted_api_key }; };
|
|
131
|
+
export class ProviderStore {
|
|
132
|
+
constructor({ dataDir, secret, env = process.env, records = [], persistent = true }) { this.path = `${dataDir}/providers.lenv`; this.secret = secret; this.env = env; this.records = new Map(records.map(r => [r.name,r])); this.persistent = persistent; }
|
|
133
|
+
async loadUnlocked() {
|
|
134
|
+
if (this.persistent) await recoverTransactionalWrite(this.path);
|
|
135
|
+
const text = this.persistent ? await readOptional(this.path,null) : null;
|
|
136
|
+
const map = text == null ? new Map(this.records) : new Map();
|
|
137
|
+
for (const line of (text ?? '').split(/\r?\n/)) if (line.trim().startsWith('PROVIDER: ')) { const record = JSON.parse(line.trim().slice(10)); map.set(record.name,record); }
|
|
138
|
+
return map;
|
|
139
|
+
}
|
|
140
|
+
async load() { return this.persistent ? withAdvisoryFileLock(rustLockPath(this.path),() => this.loadUnlocked()) : this.loadUnlocked(); }
|
|
141
|
+
async resolve() {
|
|
142
|
+
return [...(await this.load()).values()].filter(r => r.enabled !== false).map(r => normalizeProvider({ ...r,api_key:r.api_key ?? (r.api_key_env ? this.env[r.api_key_env] : null) ?? (r.encrypted_api_key ? decryptProviderSecret(r.encrypted_api_key,this.secret) : null) },this.env));
|
|
143
|
+
}
|
|
144
|
+
async list() { return [...(await this.load()).values()].map(redact).sort((a,b) => a.name.localeCompare(b.name)); }
|
|
145
|
+
async get(name) { return (await this.list()).find(r => r.name === name) ?? null; }
|
|
146
|
+
async mutate(operation,{skipWriteWhen=()=>false}={}) {
|
|
147
|
+
const operationWithState = async () => {
|
|
148
|
+
const records = await this.loadUnlocked(); const result = await operation(records);
|
|
149
|
+
if (this.persistent && !skipWriteWhen(result)) {
|
|
150
|
+
for (const [name,held] of records) {
|
|
151
|
+
const {api_key,...safe} = held;
|
|
152
|
+
if (api_key) safe.encrypted_api_key = encryptProviderSecret(api_key,this.secret);
|
|
153
|
+
records.set(name,safe);
|
|
154
|
+
}
|
|
155
|
+
const sorted = [...records.values()].sort((a,b) => a.name.localeCompare(b.name));
|
|
156
|
+
await transactionalWrite(this.path,'# Link.Assistant.Router provider store\n# Each PROVIDER value is JSON; inline API keys are encrypted.\n'+sorted.map(r => `PROVIDER: ${JSON.stringify(r)}`).join('\n')+'\n');
|
|
157
|
+
}
|
|
158
|
+
this.records = records; return result;
|
|
159
|
+
};
|
|
160
|
+
return serialized(this.path,() => this.persistent ? withAdvisoryFileLock(rustLockPath(this.path),operationWithState) : operationWithState());
|
|
161
|
+
}
|
|
162
|
+
stage(input) {
|
|
163
|
+
const normalized = normalizeProvider({...input,name:typeof input.name === 'string' ? input.name.trim() : input.name},{});
|
|
164
|
+
if (!['openai-compatible','lefine','z.ai-coding-plan'].includes(normalized.kind)) throw new RouterError('invalid_provider','Subscription services are configured separately from persisted providers');
|
|
165
|
+
const { api_key, apiKey, protocol, if_absent, acknowledge_intermediary_risk, acknowledge_unsupported_clients, ...record } = normalized;
|
|
166
|
+
record.intermediary_risk_acknowledged = input.acknowledge_intermediary_risk ?? input.intermediary_risk_acknowledged ?? false;
|
|
167
|
+
record.unsupported_clients = input.acknowledge_unsupported_clients ?? input.unsupported_clients ?? [];
|
|
168
|
+
if (record.kind === 'z.ai-coding-plan' && (typeof record.subscriber_id !== 'string' || !record.subscriber_id.trim())) throw new RouterError('invalid_provider','z.ai Coding Plan requires one subscriber_id');
|
|
169
|
+
if (record.kind === 'openai-compatible') {
|
|
170
|
+
const canonical = new Set(['codex','claude','gemini','qwen','grok','opencode','agent','cursor-agent']);
|
|
171
|
+
if (record.supported_clients.some(client => !canonical.has(client))) throw new RouterError('invalid_provider','supported_clients must use canonical client names');
|
|
172
|
+
if (record.name === 'z.ai') throw new RouterError('invalid_provider',"Provider name z.ai is reserved for the Coding Plan namespace");
|
|
173
|
+
if (record.subscriber_id || record.intermediary_risk_acknowledged || record.unsupported_clients.length) throw new RouterError('invalid_provider','Subscriber/risk settings require a Coding Plan provider');
|
|
174
|
+
}
|
|
175
|
+
if (api_key) record.encrypted_api_key = encryptProviderSecret(api_key,this.secret);
|
|
176
|
+
return record;
|
|
177
|
+
}
|
|
178
|
+
async install(input) {
|
|
179
|
+
// Stage every candidate before looking up IfAbsent, then decide under the store lock.
|
|
180
|
+
const record = this.stage(input);
|
|
181
|
+
return this.mutate(records => {
|
|
182
|
+
const prior = records.get(record.name);
|
|
183
|
+
if (input.if_absent && prior) return {outcome:'already_present',record:redact(prior)};
|
|
184
|
+
if (record.kind === 'z.ai-coding-plan' && record.enabled && [...records.values()].some(existing => existing.enabled && existing.kind === record.kind && existing.name !== record.name)) throw new RouterError('invalid_provider','Only one personal z.ai Coding Plan subscriber may be enabled');
|
|
185
|
+
records.set(record.name,record);
|
|
186
|
+
return {outcome:prior ? 'replaced' : 'created',record:redact(record)};
|
|
187
|
+
},{skipWriteWhen:result=>result.outcome === 'already_present'});
|
|
188
|
+
}
|
|
189
|
+
async upsert(input) {
|
|
190
|
+
const record = this.stage(input);
|
|
191
|
+
return this.mutate(records => {
|
|
192
|
+
if (input.if_absent && records.has(record.name)) throw new RouterError('conflict','Provider already exists',409);
|
|
193
|
+
if (record.kind === 'z.ai-coding-plan' && record.enabled && [...records.values()].some(existing => existing.enabled && existing.kind === record.kind && existing.name !== record.name)) throw new RouterError('invalid_provider','Only one personal z.ai Coding Plan subscriber may be enabled');
|
|
194
|
+
records.set(record.name,record); return redact(record);
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
async remove(name) { return this.mutate(records => records.delete(name)); }
|
|
198
|
+
}
|
package/src/core.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { loadConfig, ProviderStore,nativeConfigEnvironment } from './config.mjs';
|
|
2
|
+
import { createTokenStore } from './storage.mjs';
|
|
3
|
+
import { TokenManager, RouterError } from './tokens.mjs';
|
|
4
|
+
import { AccountRouter,principalAccountName,principalAccountScope } from './accounts.mjs';
|
|
5
|
+
import { OAuthManager, CredentialFileStore, subscriptionProvider,subscriptionHome,subscriptionBaseURL } from './oauth.mjs';
|
|
6
|
+
import { modelCandidates, catalogModels } from './routing.mjs';
|
|
7
|
+
import { AffinityStore } from './affinities.mjs';
|
|
8
|
+
import { AdminClaim } from './admin.mjs';
|
|
9
|
+
import { NativeLoginManager,nativeCredentialStatus } from './auth-service.mjs';
|
|
10
|
+
import { ManagementAccess } from './management-access.mjs';
|
|
11
|
+
import { EmergencyAuthentication,AuthenticationDiagnostics,withAuthenticationScope } from './emergency-auth.mjs';
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { resolve } from 'node:path';
|
|
14
|
+
|
|
15
|
+
export class RouterCore {
|
|
16
|
+
constructor({ config, storage, clock = () => Math.floor(Date.now()/1000), env = process.env, fetch = globalThis.fetch, oauth = {},management = {} }) {
|
|
17
|
+
this.config = config; this.clock = clock; this.env = env; this.fetch = fetch; this.oauthOptions = oauth; this.contexts = new Map();
|
|
18
|
+
this.emergency = new EmergencyAuthentication({config:config.emergency,clock});this.emergency.start([config.host]);
|
|
19
|
+
this.diagnostics = new AuthenticationDiagnostics({clock});this.withAuthenticationScope=withAuthenticationScope;
|
|
20
|
+
this.tokens = new TokenManager({secret:config.token_secret,store:createTokenStore({...config,storage}),clock,emergency:this.emergency,diagnostics:this.diagnostics});
|
|
21
|
+
this.providers = new ProviderStore({dataDir:config.data_dir,secret:config.token_secret,env,records:config.providers,persistent:config.storage_policy !== 'memory'});
|
|
22
|
+
this.accounts = new AccountRouter({config,clock});
|
|
23
|
+
this.oauth = new OAuthManager({fetch,clock,env,...oauth});
|
|
24
|
+
this.credentialStores = new Map();
|
|
25
|
+
this.affinities = new AffinityStore({dataDir:config.data_dir,persistent:config.storage_policy !== 'memory',clock});
|
|
26
|
+
this.admin = new AdminClaim(this,{env});
|
|
27
|
+
this.login = new NativeLoginManager(this,{env,fetch,clock,...oauth});
|
|
28
|
+
this.credentialStatus = () => nativeCredentialStatus(this,{env,fetch,...oauth});
|
|
29
|
+
this.managementAccess = new ManagementAccess({config:config.management,dataDir:config.data_dir,persistent:config.storage_policy !== 'memory',clock,...management});
|
|
30
|
+
}
|
|
31
|
+
async listProviders() { return this.providers.list(); }
|
|
32
|
+
async showProvider(name) { return this.providers.get(name); }
|
|
33
|
+
async upsertProvider(input) {
|
|
34
|
+
const result = await this.providers.upsert(input);
|
|
35
|
+
this.activateProviderAccount(input);
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
async installProvider(input) {
|
|
39
|
+
const result = await this.providers.install(input);
|
|
40
|
+
if (result.outcome !== 'already_present') this.activateProviderAccount(result.record);
|
|
41
|
+
return result;
|
|
42
|
+
}
|
|
43
|
+
activateProviderAccount(input) {
|
|
44
|
+
if (![...this.accounts.records.values()].some(a => a.provider === input.name)) {
|
|
45
|
+
const fresh = new AccountRouter({config:{...this.config,accounts:[],providers:[input]},clock:this.clock});
|
|
46
|
+
for (const [name,account] of fresh.records) this.accounts.records.set(name,account);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async removeProvider(name) { return this.providers.remove(name); }
|
|
50
|
+
async listAccounts() { return this.accounts.list(); }
|
|
51
|
+
async accountAction(name,action,body = {}) {
|
|
52
|
+
if (action === 'pause') return this.accounts.pause(name,body);
|
|
53
|
+
if (action === 'resume') return this.accounts.resume(name);
|
|
54
|
+
if (action === 'policy') return this.accounts.policy(name,body.policy ?? body);
|
|
55
|
+
throw new TypeError(`Unknown account action: ${action}`);
|
|
56
|
+
}
|
|
57
|
+
async updateRouting({strategy} = {}) { if (typeof strategy !== 'string') throw new TypeError('strategy is required'); return this.accounts.setStrategy(strategy); }
|
|
58
|
+
async resetCooldowns() { return this.accounts.resetCooldowns(); }
|
|
59
|
+
async resetCooldown(name,model) { return this.accounts.resetCooldowns(name,model); }
|
|
60
|
+
async models() { return catalogModels(await this.providers.resolve(),this.accounts.records); }
|
|
61
|
+
async catalogFor(context = {}) {
|
|
62
|
+
const {client,provider}=context,pinnedAccount=context.pinnedAccount ?? context.pinned_account;
|
|
63
|
+
const providers = (await this.providers.resolve()).filter(record => (!provider || record.name === provider) && (!client || record.supported_clients.includes(client)));
|
|
64
|
+
const accounts = principalAccountScope(this.accounts.records,providers,context);
|
|
65
|
+
if (pinnedAccount && !this.accounts.records.has(pinnedAccount)) throw new RouterError('unknown_pinned_account','Pinned account does not exist',404);
|
|
66
|
+
return catalogModels(providers,accounts);
|
|
67
|
+
}
|
|
68
|
+
async candidates(context = {}) {
|
|
69
|
+
const providers = await this.providers.resolve();
|
|
70
|
+
const scoped=principalAccountScope(this.accounts.records,providers,context);
|
|
71
|
+
const ordered = this.accounts.order(modelCandidates(providers,scoped,context),context);
|
|
72
|
+
return this.attachCredentials(ordered,providers);
|
|
73
|
+
}
|
|
74
|
+
attachCredentials(ordered,providers) {
|
|
75
|
+
for (const candidate of ordered) {
|
|
76
|
+
const account = this.accounts.records.get(candidate.account), provider = providers.find(p => p.name === candidate.provider);
|
|
77
|
+
candidate.native_account=principalAccountName(account,provider);
|
|
78
|
+
const subscription = ['anthropic','claude','codex','gemini','qwen'].includes(provider?.kind);
|
|
79
|
+
const home = account?.credential_home ?? account?.oauth?.home ?? provider?.credential_home ?? provider?.oauth?.home ?? (subscription ? account?.home ?? subscriptionHome(provider.kind,{config:this.config,env:this.env}) : null);
|
|
80
|
+
if (home) {
|
|
81
|
+
const kind = subscriptionProvider(account?.oauth_provider ?? account?.oauth?.provider ?? provider?.oauth?.provider ?? provider.kind);
|
|
82
|
+
const key = `${kind}\0${candidate.account}\0${home}`;
|
|
83
|
+
if (!this.credentialStores.has(key)) this.credentialStores.set(key,new CredentialFileStore({provider:kind,home,dataDir:this.config.data_dir,account:candidate.native_account,clock:this.clock}));
|
|
84
|
+
candidate.auth_type = 'oauth'; candidate.oauth_provider = kind;
|
|
85
|
+
Object.defineProperty(candidate,'credential_key',{value:key,enumerable:false});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return ordered;
|
|
89
|
+
}
|
|
90
|
+
async nativeCandidates(context = {}) {
|
|
91
|
+
const service = context.service;
|
|
92
|
+
const kinds = {openai:['openai-compatible','openai','litellm'],anthropic:['anthropic','claude'],codex:['codex'],
|
|
93
|
+
'codex-backend':['codex'],qwen:['qwen'],gemini:['gemini'],vertex:['vertex','vertex-ai'],bedrock:['bedrock']};
|
|
94
|
+
if (!kinds[service]) throw new RouterError('invalid_argument','Unknown native service');
|
|
95
|
+
const providers = (await this.providers.resolve()).filter(provider => kinds[service].includes(provider.kind));
|
|
96
|
+
// Resource lifecycle and known continuations resolve their recorded exact
|
|
97
|
+
// destination independently of the current default, as Rust pin_state and
|
|
98
|
+
// forward_stored_provider do. This is an internal affinity-store context,
|
|
99
|
+
// never a provider override read from the client request body.
|
|
100
|
+
const recorded = context.resourceDestination;
|
|
101
|
+
if (recorded && (!['stored_provider','subscription'].includes(recorded.destination_kind) || recorded.provider !== context.provider)) throw new RouterError('invalid_argument','Invalid recorded resource destination');
|
|
102
|
+
const configured = recorded ? undefined : this.config.services?.[service]?.provider ?? (service === 'openai' ? this.config.openai_compatible_provider_name : undefined);
|
|
103
|
+
const selected = providers.filter(provider => (!context.provider || context.provider === provider.name || context.provider === (provider.kind === 'anthropic' ? 'claude' : provider.kind)) &&
|
|
104
|
+
(!configured || provider.name === configured) && (!context.client || provider.supported_clients.includes(context.client)));
|
|
105
|
+
if (!selected.length) throw new RouterError('native_provider_unavailable','Native service provider is unavailable',503);
|
|
106
|
+
if (service === 'openai' && selected.length > 1 && !configured && !context.provider) throw new RouterError('provider_conflict','Native OpenAI service requires an exact provider selection',409);
|
|
107
|
+
const scoped=principalAccountScope(this.accounts.records,selected,context);
|
|
108
|
+
if(!scoped.size && (context.pinnedAccount ?? context.pinned_account ?? context.principalAccount))throw new RouterError('pinned_account_unavailable','The bound subscription account is unavailable',503);
|
|
109
|
+
let candidates;
|
|
110
|
+
if (context.model) candidates = modelCandidates(selected,scoped,{...context,provider:undefined});
|
|
111
|
+
else candidates = selected.flatMap(provider => [...scoped.values()].filter(account => account.provider === provider.name && account.enabled !== false).map(account => ({
|
|
112
|
+
provider:provider.name,kind:provider.kind,account:account.name,base_url:provider.base_url,baseUrl:provider.base_url,
|
|
113
|
+
api_key:account.api_key ?? provider.api_key,apiKey:account.api_key ?? provider.api_key,protocol:provider.protocol,
|
|
114
|
+
headers:{...account.policy.headers},supported_clients:provider.supported_clients,default_model:provider.default_model,
|
|
115
|
+
})));
|
|
116
|
+
for (const candidate of candidates) {
|
|
117
|
+
const subscription = !['openai-compatible','openai','litellm'].includes(candidate.kind);
|
|
118
|
+
candidate.provider_kind = candidate.kind === 'anthropic' ? 'claude' : ['openai','litellm'].includes(candidate.kind) ? 'openai-compatible' : candidate.kind;
|
|
119
|
+
candidate.destination_kind = subscription ? 'subscription' : 'stored_provider';
|
|
120
|
+
}
|
|
121
|
+
return this.attachCredentials(this.accounts.order(candidates,context),selected);
|
|
122
|
+
}
|
|
123
|
+
async prepareCandidate(candidate) {
|
|
124
|
+
if (!this.accounts.serves(candidate.account,candidate.model)) throw new RouterError('account_unavailable','Account became unavailable',503);
|
|
125
|
+
if (candidate.auth_type !== 'oauth') return candidate;
|
|
126
|
+
const store = this.credentialStores.get(candidate.credential_key);
|
|
127
|
+
if (!store) throw new RouterError('credentials_missing','Credential route is not configured',401);
|
|
128
|
+
const {token,headers} = await this.oauth.headers(store);
|
|
129
|
+
if (!this.accounts.serves(candidate.account,candidate.model)) throw new RouterError('account_unavailable','Account became unavailable during credential preparation',503);
|
|
130
|
+
const {credential_key,...prepared} = candidate;
|
|
131
|
+
return {...prepared,api_key:token.access_token,apiKey:token.access_token,account_id:token.account_id,oauth_headers:headers,
|
|
132
|
+
...(store.provider === 'qwen' && token.resource_url ? {base_url:subscriptionBaseURL('qwen',token),baseUrl:subscriptionBaseURL('qwen',token)} : {}),
|
|
133
|
+
...(store.provider === 'codex' ? {endpointPath:'/responses',protocol:'responses'} : {})};
|
|
134
|
+
}
|
|
135
|
+
async resolveCandidates(model, context = {}) { return this.candidates({ ...context,model }); }
|
|
136
|
+
async route(context = {}) { const candidate = await this.prepareCandidate((await this.candidates(context))[0]); this.accounts.recordUse(candidate,context); return candidate; }
|
|
137
|
+
async reportFailure(candidate, details) { return this.accounts.reportFailure(candidate,details); }
|
|
138
|
+
async reportSuccess(candidate) { return this.accounts.reportSuccess(candidate); }
|
|
139
|
+
async authenticate(token, options) {
|
|
140
|
+
if (options?.admin && (this.config.allow_anonymous_admin || await this.admin.verify(token))) {
|
|
141
|
+
try { return await this.tokens.validate(token,options); }
|
|
142
|
+
catch { return {scope:'admin',is_admin:true,admin_credential_kind:this.config.allow_anonymous_admin ? 'anonymous' : this.admin.envKey ? 'environment' : 'legacy_opaque',record:null}; }
|
|
143
|
+
}
|
|
144
|
+
return options?.admin ? this.tokens.validate(token,options) : this.tokens.authenticateIncoming(token,options);
|
|
145
|
+
}
|
|
146
|
+
async withConfig(overrides = {},{env = this.env,cwd = process.cwd()} = {}) {
|
|
147
|
+
const input = {...this.config,...overrides};
|
|
148
|
+
for (const [environment,field] of Object.entries(nativeConfigEnvironment)) if (!Object.hasOwn(overrides,field) && env[environment] !== this.env[environment]) input[field] = env[environment];
|
|
149
|
+
if (overrides.data_dir != null || overrides.dataDir != null) input.data_dir = resolve(cwd,overrides.data_dir ?? overrides.dataDir);
|
|
150
|
+
if (overrides.home != null) input.home = resolve(cwd,overrides.home);
|
|
151
|
+
const config = await loadConfig({config:input,env});
|
|
152
|
+
const identity = createHash('sha256').update(JSON.stringify([config.data_dir,config.storage_policy,config.token_secret])).digest('hex');
|
|
153
|
+
const baseIdentity = createHash('sha256').update(JSON.stringify([this.config.data_dir,this.config.storage_policy,this.config.token_secret])).digest('hex');
|
|
154
|
+
if (identity !== baseIdentity) {
|
|
155
|
+
if (!this.contexts.has(identity)) this.contexts.set(identity,await createRouterCore({config,env,clock:this.clock,fetch:this.fetch,oauth:this.oauthOptions}));
|
|
156
|
+
return this.contexts.get(identity).withConfig({}, {env,cwd});
|
|
157
|
+
}
|
|
158
|
+
const context = Object.assign(Object.create(Object.getPrototypeOf(this)),this,{config,env});
|
|
159
|
+
context.oauth = Object.assign(Object.create(Object.getPrototypeOf(this.oauth)),this.oauth,{env});
|
|
160
|
+
context.providers = Object.assign(Object.create(Object.getPrototypeOf(this.providers)),this.providers,{env});
|
|
161
|
+
Object.defineProperty(context.providers,'records',{get:() => this.providers.records,set:value => {this.providers.records=value;},enumerable:true});
|
|
162
|
+
context.accounts = Object.assign(Object.create(Object.getPrototypeOf(this.accounts)),this.accounts,{config});
|
|
163
|
+
for (const key of ['cursor','failoverCursor']) Object.defineProperty(context.accounts,key,{get:() => this.accounts[key],set:value => {this.accounts[key]=value;},enumerable:true});
|
|
164
|
+
if (overrides.account_strategy != null) context.accounts.setStrategy(config.account_strategy);
|
|
165
|
+
context.admin = Object.assign(Object.create(Object.getPrototypeOf(this.admin)),this.admin,{core:context,envKey:config.token_admin_key});
|
|
166
|
+
for (const key of ['file','candidate']) Object.defineProperty(context.admin,key,{get:() => this.admin[key],set:value => {this.admin[key]=value;},enumerable:true});
|
|
167
|
+
context.login = Object.assign(Object.create(Object.getPrototypeOf(this.login)),this.login,{core:context,env,enabled:config.login?.enabled ?? !config.disable_login_api,
|
|
168
|
+
maxSessions:config.login?.max_sessions ?? config.login_max_sessions ?? this.login.maxSessions,
|
|
169
|
+
ttlSeconds:config.login?.session_ttl_secs ?? config.login_session_ttl_secs ?? this.login.ttlSeconds});
|
|
170
|
+
context.credentialStatus = () => nativeCredentialStatus(context,{env,fetch:this.fetch,...this.oauthOptions});
|
|
171
|
+
context.managementAccess = Object.assign(Object.create(Object.getPrototypeOf(this.managementAccess)),this.managementAccess,{policy:config.management});
|
|
172
|
+
return context;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
export async function createOperationContext(baseCore,{configOverrides = {},env,cwd = process.cwd(),signal} = {}) {
|
|
176
|
+
env = {...baseCore.env,...env};
|
|
177
|
+
const core = await baseCore.withConfig(configOverrides,{env,cwd});
|
|
178
|
+
return {core,config:core.config,env,cwd,signal};
|
|
179
|
+
}
|
|
180
|
+
export async function createRouterCore(options = {}) {
|
|
181
|
+
const config = await loadConfig(options);
|
|
182
|
+
const core = new RouterCore({...options,config});
|
|
183
|
+
// Resolve persisted provider catalog before establishing account isolation.
|
|
184
|
+
const providers = await core.providers.resolve();
|
|
185
|
+
core.accounts = new AccountRouter({config:{...config,providers},clock:core.clock});
|
|
186
|
+
await core.accounts.load();
|
|
187
|
+
// Rust open_with_limits validates the existing typed affinity file before use.
|
|
188
|
+
if (core.affinities?.verify) await core.affinities.verify();
|
|
189
|
+
return core;
|
|
190
|
+
}
|
|
191
|
+
export { TokenManager, RouterError, codexTokenAlias } from './tokens.mjs';
|
|
192
|
+
export { loadConfig, normalizeConfig, ProviderStore } from './config.mjs';
|
|
193
|
+
export { nativeConfigOptions } from './config.mjs';
|
|
194
|
+
export { MemoryTokenStore, TextTokenStore, BinaryTokenStore, DualTokenStore, createTokenStore } from './storage.mjs';
|
|
195
|
+
export { AffinityStore } from './affinities.mjs';
|
|
196
|
+
export { AccountRouter } from './accounts.mjs';
|
|
197
|
+
|
|
198
|
+
export { OAuthManager, CredentialFileStore, ClaudeLogin, importCredential, executeAuthOperation } from './oauth.mjs';
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** Local credential observation/withdrawal without constructing token authentication. */
|
|
2
|
+
import {unlink,stat} from 'node:fs/promises';
|
|
3
|
+
import {join,resolve} from 'node:path';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {execFile} from 'node:child_process';
|
|
6
|
+
import {promisify} from 'node:util';
|
|
7
|
+
import {loadConfig,ProviderStore,nativeConfigOptions} from './config.mjs';
|
|
8
|
+
import {CredentialFileStore,OAuthManager,subscriptionHome,subscriptionProvider} from './oauth.mjs';
|
|
9
|
+
import {nativeCredentialStatus} from './auth-service.mjs';
|
|
10
|
+
import {readNativeText} from './operation-input.mjs';
|
|
11
|
+
import {atomicWrite} from './storage.mjs';
|
|
12
|
+
const exec=promisify(execFile),subscriptions=['claude','codex','gemini','qwen'];
|
|
13
|
+
const candidates={claude:['.credentials.json','credentials.json','auth.json','oauth.json','config.json'],codex:['auth.json'],gemini:['oauth_creds.json'],qwen:['oauth_creds.json']};
|
|
14
|
+
const fail=(code,message,exitCode=1)=>Object.assign(new Error(message),{code,exitCode});
|
|
15
|
+
const output=lines=>({output:lines});
|
|
16
|
+
export function credentialWithdrawal(name,options) {return name==='auth.clear' || name==='auth.status' && options.clear_all || ['auth.claude','auth.codex','auth.gh'].includes(name) && options.clear;}
|
|
17
|
+
async function context({routerOptions={},options={},invocation={},env={}}) {
|
|
18
|
+
const overrides=Object.fromEntries(Object.entries(options).filter(([key])=>nativeConfigOptions.has(key)));
|
|
19
|
+
const input={...(routerOptions.config ?? routerOptions.core?.config ?? {}),...overrides};
|
|
20
|
+
if(invocation.cwd) {
|
|
21
|
+
for(const key of ['data_dir','home','claude_home','claude_code_home','codex_home','gemini_home','qwen_home'])if(input[key])input[key]=resolve(invocation.cwd,input[key]);
|
|
22
|
+
if(!input.data_dir)input.data_dir=resolve(invocation.cwd,env.DATA_DIR ?? '.router');
|
|
23
|
+
}
|
|
24
|
+
// Observation/deletion never decrypt a provider key or sign a router token.
|
|
25
|
+
const configEnv={...env};delete configEnv.TOKEN_SECRET_FILE;
|
|
26
|
+
const config=await loadConfig({...routerOptions,config:input,env:configEnv});
|
|
27
|
+
const clock=routerOptions.clock ?? routerOptions.core?.clock ?? (()=>Math.floor(Date.now()/1000));
|
|
28
|
+
const inherited=routerOptions.core;
|
|
29
|
+
const providers=inherited?.config?.data_dir === config.data_dir ? inherited.providers : new ProviderStore({dataDir:config.data_dir,secret:config.token_secret,env,records:[],persistent:config.storage_policy!=='memory'});
|
|
30
|
+
const oauth=inherited?.oauth ?? new OAuthManager({fetch:routerOptions.fetch ?? globalThis.fetch,clock,env,...routerOptions.oauth});
|
|
31
|
+
return {config,clock,providers,oauth};
|
|
32
|
+
}
|
|
33
|
+
async function remove(path) {try{await unlink(path);return true;}catch(error){if(error.code==='ENOENT')return false;throw fail('credential_clear','Credential path cannot be removed');}}
|
|
34
|
+
async function hasFile(path) {try{return (await stat(path)).isFile();}catch(error){if(error.code==='ENOENT')return false;throw fail('credential_read','Credential location cannot be inspected');}}
|
|
35
|
+
function keychainService(env) {const dir=env.CLAUDE_CONFIG_DIR;return 'Claude Code-credentials'+(dir ? '-'+createHash('sha256').update(dir).digest('hex').slice(0,8):'');}
|
|
36
|
+
async function keychainPresent(service,settings) {
|
|
37
|
+
if(settings.keychainHasEntry)return settings.keychainHasEntry(service);
|
|
38
|
+
if((settings.platform ?? process.platform)!=='darwin')return false;
|
|
39
|
+
try {await exec('/usr/bin/security',['find-generic-password','-s',service],{timeout:3000,maxBuffer:128*1024});return true;}catch{return false;}
|
|
40
|
+
}
|
|
41
|
+
function ghDirectory(env) {return env.GH_CONFIG_DIR || (env.HOME ? join(env.HOME,'.config','gh'):null);}
|
|
42
|
+
async function ghToken(config,env,directory,cwd) {
|
|
43
|
+
const expected=new URL(config.github?.base_url ?? env.GITHUB_PROXY_BASE_URL ?? 'https://api.github.com').hostname.replace(/^api\.github\.com$/,'github.com');
|
|
44
|
+
const text=await readNativeText(join(directory,'hosts.yml'),{cwd,maxBytes:1024*1024});let host;
|
|
45
|
+
for(const line of text.split('\n')) {
|
|
46
|
+
const match=/^([^:]+):(.*)$/.exec(line);if(!match)continue;
|
|
47
|
+
if(!/^\s/.test(line))host=match[1].trim().replace(/^['"]|['"]$/g,'');
|
|
48
|
+
else if(host?.toLowerCase()===expected.toLowerCase() && match[1].trim()==='oauth_token') {
|
|
49
|
+
const token=match[2].trim().replace(/^['"]|['"]$/g,'');if(token)return token;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
async function configuredGithub(config,env) {
|
|
55
|
+
const variable=config.github?.token ?? env.GITHUB_PROXY_TOKEN ?? (env.GITHUB_PROXY_TOKEN_ENV ? env[env.GITHUB_PROXY_TOKEN_ENV]:null);
|
|
56
|
+
if(variable)return true;
|
|
57
|
+
try {
|
|
58
|
+
if(env.GITHUB_PROXY_TOKEN_FILE)return Boolean((await readNativeText(env.GITHUB_PROXY_TOKEN_FILE,{maxBytes:1024*1024})).trim());
|
|
59
|
+
const dir=ghDirectory(env);return dir ? Boolean(await ghToken(config,env,dir)):false;
|
|
60
|
+
}catch{return false;}
|
|
61
|
+
}
|
|
62
|
+
async function withdraw(core,name,options,{env={},oauth={}}={}) {
|
|
63
|
+
let selected=[],github=false,api=[];
|
|
64
|
+
if(name==='auth.clear') {
|
|
65
|
+
if(options.all && options.provider)throw fail('options','provider and all cannot be combined',2);
|
|
66
|
+
if(options.all){selected=subscriptions;github=true;api=(await core.providers.list()).filter(row=>row.has_encrypted_api_key || row.api_key_env);}
|
|
67
|
+
else if(options.provider) {
|
|
68
|
+
const requested=options.provider.toLowerCase();
|
|
69
|
+
if(['gh','github'].includes(requested))github=true;
|
|
70
|
+
else {try{selected=[subscriptionProvider(requested)];}catch{const row=await core.providers.get(options.provider);if(!row)throw fail('credential_clear','No credential with that provider name');api=[row];}}
|
|
71
|
+
} else throw fail('options','Nothing to clear; name a provider or pass all',2);
|
|
72
|
+
} else if(name==='auth.status'){selected=subscriptions;github=true;api=(await core.providers.list()).filter(row=>row.has_encrypted_api_key || row.api_key_env);}
|
|
73
|
+
else if(name==='auth.gh')github=true;
|
|
74
|
+
else selected=[name.slice(5)];
|
|
75
|
+
if(selected.length+Number(github)+api.length>1 && !options.yes)throw fail('credential_confirmation','Multiple credential withdrawals require yes');
|
|
76
|
+
const lines=[],errors=[];
|
|
77
|
+
for(const provider of selected) {
|
|
78
|
+
const home=subscriptionHome(provider,{config:core.config,env});const store=new CredentialFileStore({provider,home,dataDir:core.config.data_dir,clock:core.clock});
|
|
79
|
+
try {
|
|
80
|
+
const removed=await store.transaction(async()=>{const rows=[];for(const file of candidates[provider]){const path=join(home,file);if(await remove(path))rows.push(path);}return rows;});
|
|
81
|
+
lines.push(...(removed.length ? removed.map(path=>`${provider.padEnd(8)} removed ${path}`):[`${provider.padEnd(8)} absent`]));
|
|
82
|
+
if(provider==='claude') {const service=keychainService(env);if(await keychainPresent(service,oauth))lines.push(`claude note: ${JSON.stringify(service)} still holds a vendor-owned Keychain entry; remove it with the vendor client`);}
|
|
83
|
+
} catch(error) {errors.push(error);lines.push(`${provider.padEnd(8)} withdrawal failed (${error.code ?? 'credential_clear'})`);}
|
|
84
|
+
}
|
|
85
|
+
if(github) {
|
|
86
|
+
try {const path=join(core.config.data_dir,'github-credential');lines.push(await remove(path) ? `github removed ${path}`:'github absent');if(await configuredGithub(core.config,env))lines.push('github note: an environment or mounted gh credential remains configured');lines.push('github note: restart to withdraw routes mounted at startup');}catch(error){errors.push(error);lines.push('github withdrawal failed');}
|
|
87
|
+
}
|
|
88
|
+
for(const row of api) {
|
|
89
|
+
try {const deleted=await core.providers.remove(row.name);lines.push(`${row.name.padEnd(8)} ${deleted ? 'removed the stored API key and provider entry':'absent'}`);if(row.api_key_env && env[row.api_key_env])lines.push(`${row.name.padEnd(8)} note: ${row.api_key_env} still holds a key in this environment`);}catch(error){errors.push(error);lines.push(`${row.name.padEnd(8)} withdrawal failed`);}
|
|
90
|
+
}
|
|
91
|
+
lines.push('note: this removes local credentials only; minted tokens remain valid upstream and should be revoked there');
|
|
92
|
+
if(errors.length){const error=fail('credential_clear','One or more local credential withdrawals failed');error.data=output(lines);throw error;}
|
|
93
|
+
return output(lines);
|
|
94
|
+
}
|
|
95
|
+
async function ghOperation(core,options,invocation,env) {
|
|
96
|
+
const path=join(core.config.data_dir,'github-credential');
|
|
97
|
+
if(options.status)return output([`github credential: ${await hasFile(path) ? `stored at ${path}`:await configuredGithub(core.config,env) ? 'configured from the environment':'absent'}`]);
|
|
98
|
+
if(options.token_stdin && options.from_gh_config)throw fail('options','token-stdin and from-gh-config cannot be combined',2);
|
|
99
|
+
let token;
|
|
100
|
+
if(options.token_stdin){token=String(invocation.stdin ?? '').trim();if(!token)throw fail('credential_input','Token stdin must not be empty');}
|
|
101
|
+
else {
|
|
102
|
+
const dir=options.from_gh_config ?? ghDirectory(env);
|
|
103
|
+
if(!dir)throw fail('credential_input','No gh configuration directory; pass from-gh-config');
|
|
104
|
+
token=await ghToken(core.config,env,dir,invocation.cwd);
|
|
105
|
+
if(!token)throw fail('credential_input','No GitHub credential found in the selected gh configuration');
|
|
106
|
+
}
|
|
107
|
+
if(/[\r\n\0]/.test(token))throw fail('credential_input','GitHub credential contains invalid control characters');
|
|
108
|
+
await atomicWrite(path,token);return output([`stored the GitHub credential in ${path}`]);
|
|
109
|
+
}
|
|
110
|
+
export async function executeCredentialOperation({name,options,invocation={},routerOptions={},env={}}) {
|
|
111
|
+
if(invocation.deadlineMs!==undefined || invocation.maxOutputBytes!==undefined)throw fail('unsupported','Credential operations do not yet implement per-invocation deadline/output accounting');
|
|
112
|
+
const core=await context({routerOptions,options,invocation,env});
|
|
113
|
+
if(credentialWithdrawal(name,options))return withdraw(core,name,options,{env,oauth:routerOptions.oauth});
|
|
114
|
+
if(name==='auth.gh')return ghOperation(core,options,invocation,env);
|
|
115
|
+
const report=await nativeCredentialStatus(core,{env,fetch:routerOptions.fetch,...routerOptions.core?.oauthOptions,...routerOptions.oauth});
|
|
116
|
+
report.api_key_providers=report.api_key_providers.filter(row=>row.has_encrypted_api_key || row.api_key_env);
|
|
117
|
+
if(report.credentials.some(row=>row.state==='refresh-failed')){const error=fail('credential_refresh','A subscription credential refresh failed');error.data=report;throw error;}
|
|
118
|
+
return report;
|
|
119
|
+
}
|