@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
package/src/oauth.mjs
ADDED
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { access, mkdir, open, realpath, rename, rm, unlink } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { tokenExpired } from '../portable/policy.mjs';
|
|
6
|
+
import { atomicWrite, decodeLino, encodeLino, serialized } from './storage.mjs';
|
|
7
|
+
import { withAdvisoryFileLock } from './file-lock.mjs';
|
|
8
|
+
import { RouterError } from './tokens.mjs';
|
|
9
|
+
|
|
10
|
+
export const CLAUDE_CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';
|
|
11
|
+
export const CODEX_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann';
|
|
12
|
+
export const CLAUDE_TOKEN_URL = 'https://platform.claude.com/v1/oauth/token';
|
|
13
|
+
export const CODEX_TOKEN_URL = 'https://auth.openai.com/oauth/token';
|
|
14
|
+
export const GEMINI_TOKEN_URL = 'https://oauth2.googleapis.com/token';
|
|
15
|
+
export const QWEN_TOKEN_URL = 'https://chat.qwen.ai/api/v1/oauth2/token';
|
|
16
|
+
export const GEMINI_CLIENT_ID = '681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com';
|
|
17
|
+
// The official installed application embeds this public client value.
|
|
18
|
+
export const GEMINI_CLIENT_SECRET = 'GOCSPX-4uHgMPm'+'-1o7Sk-geV6Cu5clXFsxl';
|
|
19
|
+
export const QWEN_CLIENT_ID = 'f0304373b74a44d2b584a3fb70ca9e56';
|
|
20
|
+
export const CLAUDE_AUTHORIZE_URL = 'https://claude.com/cai/oauth/authorize';
|
|
21
|
+
export const CLAUDE_REDIRECT_URI = 'https://platform.claude.com/oauth/code/callback';
|
|
22
|
+
export const CLAUDE_SCOPES = 'org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload';
|
|
23
|
+
export const CLAUDE_INFERENCE_SCOPE = 'user:inference';
|
|
24
|
+
export const CLAUDE_OAUTH_USER_AGENT = 'anthropic-sdk-typescript/0.112.1 userOAuthProvider';
|
|
25
|
+
const PENDING_FILE = '.link-assistant-router-claude-login.json';
|
|
26
|
+
const files = {claude:['.credentials.json','credentials.json','auth.json','oauth.json','config.json'],codex:['auth.json'],gemini:['oauth_creds.json'],qwen:['oauth_creds.json']};
|
|
27
|
+
const flights = new Map();
|
|
28
|
+
const uncertain = new Map();
|
|
29
|
+
const nonempty = value => typeof value === 'string' && value.length ? value : null;
|
|
30
|
+
const field = (object,...names) => names.map(name => object?.[name]).find(value => value != null) ?? null;
|
|
31
|
+
const fail = (code,message,status = 400) => new RouterError(code,message,status);
|
|
32
|
+
const CREDENTIAL_FILE_LIMIT = 4*1024*1024;
|
|
33
|
+
const PENDING_FILE_LIMIT = 16*1024;
|
|
34
|
+
// Check the opened inode, not a path stat that could be replaced before reading.
|
|
35
|
+
// Nonblocking open also lets a FIFO/device be rejected without waiting for data.
|
|
36
|
+
async function boundedOAuthFile(path,{maxBytes = CREDENTIAL_FILE_LIMIT,optional = false,code = 'credential_read_failed',status = 401} = {}) {
|
|
37
|
+
let handle;
|
|
38
|
+
try { handle = await open(path,constants.O_RDONLY | (constants.O_NONBLOCK ?? 0)); }
|
|
39
|
+
catch (error) { if (optional && error.code === 'ENOENT') return null; throw fail(code,'OAuth state file cannot be read',status); }
|
|
40
|
+
try {
|
|
41
|
+
const metadata = await handle.stat();
|
|
42
|
+
if (!metadata.isFile()) throw fail(code,'OAuth state must be stored in a regular file',status);
|
|
43
|
+
if (metadata.size > maxBytes) throw fail(code,'OAuth state file exceeds the allowed size',status);
|
|
44
|
+
const buffer = Buffer.alloc(Math.min(64*1024,maxBytes+1));
|
|
45
|
+
const decoder = new TextDecoder('utf-8',{fatal:true});
|
|
46
|
+
let bytes = 0, text = '';
|
|
47
|
+
for (;;) {
|
|
48
|
+
// Read one byte beyond the bound to detect growth after the size check,
|
|
49
|
+
// without ever allocating in proportion to the file's declared size.
|
|
50
|
+
const length = Math.min(buffer.length,maxBytes-bytes+1);
|
|
51
|
+
const {bytesRead} = await handle.read(buffer,0,length,null);
|
|
52
|
+
if (!bytesRead) break;
|
|
53
|
+
bytes += bytesRead;
|
|
54
|
+
if (bytes > maxBytes) throw fail(code,'OAuth state file exceeds the allowed size',status);
|
|
55
|
+
text += decoder.decode(buffer.subarray(0,bytesRead),{stream:true});
|
|
56
|
+
}
|
|
57
|
+
return text+decoder.decode();
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof RouterError) throw error;
|
|
60
|
+
throw fail(code,'OAuth state file is unreadable or invalid UTF-8',status);
|
|
61
|
+
} finally { await handle.close(); }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function subscriptionProvider(value) {
|
|
65
|
+
const name = String(value).trim().toLowerCase();
|
|
66
|
+
if (['claude','anthropic','claude-code'].includes(name)) return 'claude';
|
|
67
|
+
if (['codex','chatgpt','openai-codex'].includes(name)) return 'codex';
|
|
68
|
+
if (['gemini','google','code-assist'].includes(name)) return 'gemini';
|
|
69
|
+
if (['qwen','qwen-code','dashscope'].includes(name)) return 'qwen';
|
|
70
|
+
throw fail('invalid_provider','Unknown subscription credential provider');
|
|
71
|
+
}
|
|
72
|
+
export function subscriptionHome(provider,{config = {},env = {}} = {}) {
|
|
73
|
+
provider = subscriptionProvider(provider);
|
|
74
|
+
if (provider === 'gemini' && env.GEMINI_CLI_HOME) return resolve(env.GEMINI_CLI_HOME,'.gemini');
|
|
75
|
+
return resolve(config[`${provider}_home`] ?? (provider === 'claude' ? config.claude_code_home : null) ?? env[provider === 'claude' ? 'CLAUDE_CODE_HOME' : `${provider.toUpperCase()}_HOME`] ?? join(config.home ?? env.HOME ?? config.data_dir ?? '.',`.${provider}`));
|
|
76
|
+
}
|
|
77
|
+
export function subscriptionBaseURL(provider,token = {}) {
|
|
78
|
+
provider = subscriptionProvider(provider);
|
|
79
|
+
const defaults = {claude:'https://api.anthropic.com',codex:'https://chatgpt.com/backend-api/codex',gemini:'https://cloudcode-pa.googleapis.com',qwen:'https://dashscope.aliyuncs.com/compatible-mode/v1'};
|
|
80
|
+
if (!token.resource_url) return defaults[provider];
|
|
81
|
+
const value = /^https?:\/\//.test(token.resource_url) ? token.resource_url : `https://${token.resource_url}`;
|
|
82
|
+
const url = new URL(value);
|
|
83
|
+
if (!['https:','http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw fail('credential_invalid','Subscription resource URL is invalid');
|
|
84
|
+
return provider === 'qwen' && !value.replace(/\/+$/,'').endsWith('/v1') ? `${value.replace(/\/+$/,'')}/v1` : value;
|
|
85
|
+
}
|
|
86
|
+
function integer(value,name) {
|
|
87
|
+
if (value == null) return null;
|
|
88
|
+
if (!Number.isSafeInteger(value)) throw fail('credential_invalid',`${name} must be a safe integer`);
|
|
89
|
+
return value;
|
|
90
|
+
}
|
|
91
|
+
function jwtHint(token) {
|
|
92
|
+
try {
|
|
93
|
+
const payload = token.split('.')[1];
|
|
94
|
+
if (!payload || !/^[A-Za-z0-9_-]+$/.test(payload)) return null;
|
|
95
|
+
const parsed = JSON.parse(Buffer.from(payload,'base64url'));
|
|
96
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
97
|
+
} catch { return null; }
|
|
98
|
+
}
|
|
99
|
+
function scopesFrom(block) {
|
|
100
|
+
const scopes = block?.scopes ?? [];
|
|
101
|
+
if (!Array.isArray(scopes) || scopes.some(value => typeof value !== 'string')) throw fail('credential_invalid','Credential scopes must be strings');
|
|
102
|
+
if (block?.scope != null && typeof block.scope !== 'string') throw fail('credential_invalid','Credential scope must be a string');
|
|
103
|
+
return [...new Set([...scopes,...(block?.scope?.split(/\s+/).filter(Boolean) ?? [])])];
|
|
104
|
+
}
|
|
105
|
+
// JWT fields here are local expiry/account hints, never proof of authentication.
|
|
106
|
+
// The OAuth endpoint and authenticated provider catalog remain authoritative.
|
|
107
|
+
export function parseCredentialDocument(provider, input) {
|
|
108
|
+
provider = subscriptionProvider(provider);
|
|
109
|
+
let document;
|
|
110
|
+
try { document = typeof input === 'string' ? JSON.parse(input) : structuredClone(input); }
|
|
111
|
+
catch { throw fail('credential_invalid','Credential document is not valid JSON'); }
|
|
112
|
+
if (!document || typeof document !== 'object' || Array.isArray(document)) throw fail('credential_invalid','Credential document must be an object');
|
|
113
|
+
let token;
|
|
114
|
+
if (provider === 'claude') {
|
|
115
|
+
const nested = document.claudeAiOauth ?? document.claude_ai_oauth;
|
|
116
|
+
const nestedAccess = nonempty(field(nested,'accessToken','access_token')) ?? nonempty(field(nested,'oauthToken','oauth_token','token'));
|
|
117
|
+
const block = nestedAccess ? nested : document;
|
|
118
|
+
const accessToken = nestedAccess ?? nonempty(field(block,'accessToken','access_token')) ?? nonempty(field(block,'oauthToken','oauth_token','token'));
|
|
119
|
+
if (!accessToken) throw fail('credential_missing_token','Claude credential contains no access token',401);
|
|
120
|
+
token = {access_token:accessToken,refresh_token:nonempty(field(block,'refreshToken','refresh_token')),
|
|
121
|
+
expires_at_ms:integer(field(block,'expiresAt','expires_at','expiryDate','expiry_date'),'Credential expiry'),account_id:null,resource_url:null};
|
|
122
|
+
return {document,token,scopes:scopesFrom(block)};
|
|
123
|
+
}
|
|
124
|
+
if (provider === 'gemini' || provider === 'qwen') {
|
|
125
|
+
const accessToken = nonempty(field(document,'access_token','accessToken','token','oauthToken','oauth_token'));
|
|
126
|
+
if (!accessToken) throw fail('credential_missing_token','Subscription credential contains no access token',401);
|
|
127
|
+
token = {access_token:accessToken,refresh_token:nonempty(field(document,'refresh_token','refreshToken')),
|
|
128
|
+
expires_at_ms:integer(field(document,'expiry_date','expiryDate','expiresAt','expires_at'),'Credential expiry'),
|
|
129
|
+
account_id:nonempty(field(document,'account_id','accountId','chatgpt_account_id')),resource_url:nonempty(field(document,'resource_url','resourceUrl'))};
|
|
130
|
+
return {document,token,scopes:scopesFrom(document)};
|
|
131
|
+
}
|
|
132
|
+
const block = document.tokens;
|
|
133
|
+
const accessToken = nonempty(field(block,'access_token','accessToken'));
|
|
134
|
+
if (!accessToken) throw fail('credential_missing_token','Codex credential contains no subscription access token',401);
|
|
135
|
+
const hint = jwtHint(accessToken), idHint = jwtHint(field(block,'id_token','idToken') ?? '');
|
|
136
|
+
const exp = hint?.exp;
|
|
137
|
+
const expiryHint = Number.isSafeInteger(exp) && Number.isSafeInteger(exp*1000) ? exp*1000 : null;
|
|
138
|
+
const auth = idHint?.['https://api.openai.com/auth'];
|
|
139
|
+
const account = nonempty(field(block,'account_id','accountId')) ?? nonempty(field(document,'account_id','accountId','chatgpt_account_id')) ?? nonempty(auth?.chatgpt_account_id ?? idHint?.chatgpt_account_id ?? auth?.account_id);
|
|
140
|
+
token = {access_token:accessToken,refresh_token:nonempty(field(block,'refresh_token','refreshToken')),
|
|
141
|
+
expires_at_ms:integer(field(document,'expiry_date','expiryDate','expiresAt','expires_at'),'Credential expiry') ?? expiryHint,account_id:account,resource_url:null};
|
|
142
|
+
return {document,token,scopes:scopesFrom(document)};
|
|
143
|
+
}
|
|
144
|
+
export function mergeCredentialDocument(provider, document, token, nowMs) {
|
|
145
|
+
provider = subscriptionProvider(provider); document = structuredClone(document);
|
|
146
|
+
if (provider === 'claude') {
|
|
147
|
+
const nestedName = Object.hasOwn(document,'claudeAiOauth') ? 'claudeAiOauth' : Object.hasOwn(document,'claude_ai_oauth') ? 'claude_ai_oauth' : null;
|
|
148
|
+
const target = nestedName ? document[nestedName] : document;
|
|
149
|
+
const key = (camel,snake) => Object.hasOwn(target,snake) && !Object.hasOwn(target,camel) ? snake : camel;
|
|
150
|
+
target[key('accessToken','access_token')] = token.access_token;
|
|
151
|
+
if (token.refresh_token) target[key('refreshToken','refresh_token')] = token.refresh_token;
|
|
152
|
+
if (token.expires_at_ms != null) target[key('expiresAt','expires_at')] = token.expires_at_ms;
|
|
153
|
+
} else if (provider === 'codex') {
|
|
154
|
+
document.tokens ??= {};
|
|
155
|
+
document.tokens.access_token = token.access_token;
|
|
156
|
+
if (token.refresh_token) document.tokens.refresh_token = token.refresh_token;
|
|
157
|
+
document.last_refresh = new Date(nowMs).toISOString();
|
|
158
|
+
} else {
|
|
159
|
+
document.access_token = token.access_token;
|
|
160
|
+
if (token.refresh_token) document.refresh_token = token.refresh_token;
|
|
161
|
+
if (token.expires_at_ms != null) document.expiry_date = token.expires_at_ms;
|
|
162
|
+
}
|
|
163
|
+
return document;
|
|
164
|
+
}
|
|
165
|
+
export function credentialFingerprint(token) {
|
|
166
|
+
const hash = createHash('sha256');
|
|
167
|
+
const string = value => {
|
|
168
|
+
if (value == null) { hash.update(Buffer.from([0])); return; }
|
|
169
|
+
const bytes = Buffer.from(value), length = Buffer.alloc(8); length.writeBigUInt64LE(BigInt(bytes.length));
|
|
170
|
+
hash.update(Buffer.from([1])); hash.update(length); hash.update(bytes);
|
|
171
|
+
};
|
|
172
|
+
string(token.access_token); string(token.refresh_token);
|
|
173
|
+
if (token.expires_at_ms == null) hash.update(Buffer.from([0]));
|
|
174
|
+
else { const expiry = Buffer.alloc(8); expiry.writeBigInt64LE(BigInt(token.expires_at_ms)); hash.update(Buffer.from([1])); hash.update(expiry); }
|
|
175
|
+
string(token.account_id); string(token.resource_url); return hash.digest('hex');
|
|
176
|
+
}
|
|
177
|
+
export function validateOAuthEndpoint(value,{allowLoopback = false,expected} = {}) {
|
|
178
|
+
let url;
|
|
179
|
+
try { url = new URL(value); } catch { throw fail('invalid_oauth_endpoint','OAuth endpoint must be an absolute URL'); }
|
|
180
|
+
const loopback = ['localhost','127.0.0.1','[::1]'].includes(url.hostname);
|
|
181
|
+
if (url.username || url.password || url.hash || url.search || !['https:','http:'].includes(url.protocol) || url.protocol === 'http:' && !(allowLoopback && loopback)) throw fail('invalid_oauth_endpoint','OAuth endpoint must use HTTPS or an explicitly allowed loopback test endpoint');
|
|
182
|
+
if (expected && url.href.replace(/\/$/,'') !== new URL(expected).href.replace(/\/$/,'') && !(allowLoopback && loopback)) throw fail('invalid_oauth_endpoint','OAuth token endpoint must match the configured provider');
|
|
183
|
+
return url.href;
|
|
184
|
+
}
|
|
185
|
+
export function oauthHeaders(provider, token, {codexVersion = '0.154.0'} = {}) {
|
|
186
|
+
provider = subscriptionProvider(provider);
|
|
187
|
+
if (provider === 'claude') return {'anthropic-version':'2023-06-01','anthropic-beta':'oauth-2025-04-20'};
|
|
188
|
+
if (provider === 'gemini') return {'x-goog-api-client':'gl-node/22.14.0','user-agent':'google-api-nodejs-client/10.9.0'};
|
|
189
|
+
if (provider === 'qwen') return {accept:'application/json'};
|
|
190
|
+
const headers = {originator:'codex_cli_rs','user-agent':`codex_cli_rs/${codexVersion} (${process.platform}; ${process.arch}) unknown`};
|
|
191
|
+
if (token.account_id && !/[\r\n\0]/.test(token.account_id)) headers['chatgpt-account-id'] = token.account_id;
|
|
192
|
+
return headers;
|
|
193
|
+
}
|
|
194
|
+
export class CredentialFileStore {
|
|
195
|
+
constructor({provider,home,path,dataDir,account = 'primary',origin = 'file',write = atomicWrite,clock = () => Math.floor(Date.now()/1000)}) {
|
|
196
|
+
this.provider = subscriptionProvider(provider);
|
|
197
|
+
if (!home && !path) throw fail('invalid_argument','An explicit credential home or path is required');
|
|
198
|
+
if (!['file','adopted','external','keychain','binary'].includes(origin)) throw fail('invalid_argument','Unknown credential origin');
|
|
199
|
+
if (['keychain','binary'].includes(origin)) throw fail('native_unsupported','Native OAuth does not implement platform keychain or binary credential stores',501);
|
|
200
|
+
this.home = resolve(home ?? dirname(path)); this.path = path ? resolve(path) : null;
|
|
201
|
+
this.dataDir = resolve(dataDir ?? join(this.home,'.router')); this.account = account; this.origin = origin; this.write = write; this.clock = clock;
|
|
202
|
+
const digest = createHash('sha256').update(account).digest('hex');
|
|
203
|
+
this.recoveryPath = join(this.dataDir,'refresh-recovery',`${this.provider}-${digest}.json`);
|
|
204
|
+
this.lockPath = join(this.dataDir,'refresh-recovery',`${this.provider}-${digest}.lock`);
|
|
205
|
+
}
|
|
206
|
+
async readPrimary() {
|
|
207
|
+
let lastError;
|
|
208
|
+
for (const candidate of this.path ? [this.path] : files[this.provider].map(name => join(this.home,name))) {
|
|
209
|
+
let raw;
|
|
210
|
+
raw = await boundedOAuthFile(candidate,{optional:true});
|
|
211
|
+
if (raw == null) continue;
|
|
212
|
+
try {
|
|
213
|
+
let parsed = JSON.parse(raw), target = candidate, origin = this.origin;
|
|
214
|
+
const metadata = parsed?._link_assistant_router;
|
|
215
|
+
if (metadata?.credential_source) {
|
|
216
|
+
const source = metadata.credential_source;
|
|
217
|
+
if (typeof source !== 'string' || !isAbsolute(source) || resolve(source) === resolve(candidate)) throw fail('credential_invalid','Adopted credential source is invalid');
|
|
218
|
+
target = await realpath(source);
|
|
219
|
+
parsed = JSON.parse(await boundedOAuthFile(target));
|
|
220
|
+
if (parsed?._link_assistant_router?.credential_source) throw fail('credential_invalid','Nested adopted credential sources are unsupported');
|
|
221
|
+
origin = 'adopted';
|
|
222
|
+
}
|
|
223
|
+
if (metadata?.refresh_owner === 'external' || parsed?._link_assistant_router?.refresh_owner === 'external') origin = 'external';
|
|
224
|
+
const normalized = parseCredentialDocument(this.provider,parsed);
|
|
225
|
+
return {...normalized,path:target,pointer:candidate,origin};
|
|
226
|
+
} catch (error) { lastError = error; }
|
|
227
|
+
}
|
|
228
|
+
if (lastError) throw fail(lastError.code ?? 'credential_invalid','Subscription credential file is unusable',401);
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
async reload() {
|
|
232
|
+
const primary = await this.readPrimary();
|
|
233
|
+
const raw = await boundedOAuthFile(this.recoveryPath,{optional:true,code:'credential_recovery_invalid',status:503}); if (raw == null) return primary;
|
|
234
|
+
let record;
|
|
235
|
+
try { record = JSON.parse(raw); }
|
|
236
|
+
catch { throw fail('credential_recovery_invalid','Credential recovery record is unusable',503); }
|
|
237
|
+
if (record.version !== 1 || record.provider !== this.provider || typeof record.token?.access_token !== 'string' || !record.token.access_token || ['account_id','resource_url'].some(field => record.token[field] != null && typeof record.token[field] !== 'string') || record.token.refresh_token != null && typeof record.token.refresh_token !== 'string' || record.baseline_fingerprint != null && !/^[a-f0-9]{64}$/.test(record.baseline_fingerprint)) throw fail('credential_recovery_invalid','Credential recovery record is unusable',503);
|
|
238
|
+
integer(record.token.expires_at_ms,'Recovery expiry');
|
|
239
|
+
const primaryHash = primary ? credentialFingerprint(primary.token) : null, recoveredHash = credentialFingerprint(record.token);
|
|
240
|
+
if (primaryHash === recoveredHash || primaryHash != null && primaryHash !== record.baseline_fingerprint) { await unlink(this.recoveryPath); return primary; }
|
|
241
|
+
if (!primary) throw fail('credential_recovery_invalid','Recovery has no primary credential document',503);
|
|
242
|
+
try { await this.persistPrimary(primary,record.token); await unlink(this.recoveryPath); } catch {}
|
|
243
|
+
return {...primary,token:record.token,recovered:true};
|
|
244
|
+
}
|
|
245
|
+
async prepareRefresh(held) {
|
|
246
|
+
if (held.origin === 'external') throw fail('external_refresh_owner','Cannot spend an externally owned refresh chain',401);
|
|
247
|
+
if (!held.token.refresh_token) throw fail('no_refresh_token','Subscription credential has no refresh token',401);
|
|
248
|
+
await mkdir(dirname(this.recoveryPath),{recursive:true,mode:0o700});
|
|
249
|
+
const probe = `${this.recoveryPath}.${randomUUID()}.probe`;
|
|
250
|
+
let file;
|
|
251
|
+
try { file = await open(probe,'wx',0o600); await file.writeFile(''); await file.sync(); await file.close(); file = null; }
|
|
252
|
+
catch { throw fail('credential_persistence_unavailable','A durable refresh recovery store is required',503); }
|
|
253
|
+
finally { await file?.close(); await unlink(probe).catch(error => {if (error.code !== 'ENOENT') throw error;}); }
|
|
254
|
+
}
|
|
255
|
+
async persistPrimary(held, token) {
|
|
256
|
+
if (held.origin === 'external') throw fail('external_refresh_owner','Cannot rewrite externally owned refresh credentials',401);
|
|
257
|
+
const document = mergeCredentialDocument(this.provider,held.document,token,this.clock()*1000);
|
|
258
|
+
await this.write(held.path,JSON.stringify(document,null,2)+'\n');
|
|
259
|
+
}
|
|
260
|
+
async persist(held, token) {
|
|
261
|
+
try { await this.persistPrimary(held,token); await unlink(this.recoveryPath).catch(error => {if (error.code !== 'ENOENT') throw error;}); }
|
|
262
|
+
catch {
|
|
263
|
+
const record = {version:1,provider:this.provider,baseline_fingerprint:credentialFingerprint(held.token),token};
|
|
264
|
+
try { await this.write(this.recoveryPath,JSON.stringify(record)+'\n'); }
|
|
265
|
+
catch { throw fail('credential_persistence_failed','Rotated credential could not be durably persisted',503); }
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
async transaction(operation) { return serialized(this.lockPath,() => withAdvisoryFileLock(this.lockPath,operation,{timeout:5000})); }
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async function boundedJSON(response,code,maxBytes = 1024*1024) {
|
|
272
|
+
const declared = Number(response.headers.get('content-length'));
|
|
273
|
+
if (Number.isFinite(declared) && declared > maxBytes) throw fail(code,'OAuth response exceeds the allowed size',502);
|
|
274
|
+
const reader = response.body?.getReader();
|
|
275
|
+
let text = '';
|
|
276
|
+
if (reader) {
|
|
277
|
+
const buffers = []; let bytes = 0;
|
|
278
|
+
try { for (;;) { const part = await reader.read(); if (part.done) break; bytes += part.value.byteLength; if (bytes > maxBytes) { await reader.cancel(); throw fail(code,'OAuth response exceeds the allowed size',502); } buffers.push(part.value); } }
|
|
279
|
+
finally { reader.releaseLock(); }
|
|
280
|
+
text = Buffer.concat(buffers).toString('utf8');
|
|
281
|
+
} else text = await response.text();
|
|
282
|
+
try { return JSON.parse(text); } catch { throw fail(code,'Provider returned an invalid JSON response',502); }
|
|
283
|
+
}
|
|
284
|
+
export class OAuthManager {
|
|
285
|
+
constructor({fetch = globalThis.fetch,clock = () => Math.floor(Date.now()/1000),endpoints = {},allowLoopback = false,timeoutMs = 20000,env = {}} = {}) {
|
|
286
|
+
if (typeof fetch !== 'function') throw fail('invalid_argument','OAuth requires a fetch implementation');
|
|
287
|
+
this.fetch = fetch; this.clock = clock; this.allowLoopback = allowLoopback; this.timeoutMs = timeoutMs; this.env = env;
|
|
288
|
+
this.endpoints = {};
|
|
289
|
+
for (const [provider,official] of [['claude',CLAUDE_TOKEN_URL],['codex',CODEX_TOKEN_URL],['gemini',GEMINI_TOKEN_URL],['qwen',QWEN_TOKEN_URL]]) this.endpoints[provider] = validateOAuthEndpoint(endpoints[provider] ?? official,{allowLoopback,expected:official});
|
|
290
|
+
}
|
|
291
|
+
async exchange(provider,body) {
|
|
292
|
+
provider = subscriptionProvider(provider);
|
|
293
|
+
const form = provider === 'gemini' || provider === 'qwen';
|
|
294
|
+
const headers = {'content-type':form ? 'application/x-www-form-urlencoded' : 'application/json'};
|
|
295
|
+
if (provider === 'claude') { headers['anthropic-beta'] = 'oauth-2025-04-20'; headers['user-agent'] = CLAUDE_OAUTH_USER_AGENT; }
|
|
296
|
+
else Object.assign(headers,oauthHeaders(provider,{}));
|
|
297
|
+
let response;
|
|
298
|
+
try { response = await this.fetch(this.endpoints[provider],{method:'POST',headers,body:form ? new URLSearchParams(body).toString() : JSON.stringify(body),redirect:'error',signal:AbortSignal.timeout(this.timeoutMs)}); }
|
|
299
|
+
catch { throw fail('oauth_exchange_uncertain','OAuth exchange outcome is uncertain; the refresh grant was not retried',502); }
|
|
300
|
+
if (!response.ok) {
|
|
301
|
+
const data = await boundedJSON(response,'oauth_response_invalid').catch(() => ({}));
|
|
302
|
+
const recognized = ['invalid_grant','invalid_client','unauthorized_client','unsupported_grant_type'].includes(data.error) ? data.error : 'oauth_rejected';
|
|
303
|
+
throw fail(recognized,`OAuth token endpoint rejected the ${provider} grant`,response.status === 429 ? 429 : 401);
|
|
304
|
+
}
|
|
305
|
+
const data = await boundedJSON(response,'oauth_response_invalid');
|
|
306
|
+
if (!nonempty(data.access_token) || data.token_type != null && !/^bearer$/i.test(data.token_type)) throw fail('oauth_response_invalid','OAuth response has no usable bearer access token',502);
|
|
307
|
+
if (data.expires_in != null && (!Number.isSafeInteger(data.expires_in) || data.expires_in < 0 || !Number.isSafeInteger(this.clock()*1000+data.expires_in*1000))) throw fail('oauth_response_invalid','OAuth expiry is not representable',502);
|
|
308
|
+
if (data.refresh_token != null && typeof data.refresh_token !== 'string') throw fail('oauth_response_invalid','OAuth refresh token is invalid',502);
|
|
309
|
+
return data;
|
|
310
|
+
}
|
|
311
|
+
async getFresh(store,{force = false} = {}) {
|
|
312
|
+
if (!(store instanceof CredentialFileStore)) throw fail('invalid_argument','A native file credential store is required');
|
|
313
|
+
const key = store.lockPath;
|
|
314
|
+
if (flights.has(key)) return structuredClone(await flights.get(key));
|
|
315
|
+
const flight = store.transaction(async () => {
|
|
316
|
+
const held = await store.reload(); if (!held) throw fail('credentials_missing','Subscription credentials are absent',401);
|
|
317
|
+
const fingerprint = credentialFingerprint(held.token);
|
|
318
|
+
if (uncertain.get(key) === fingerprint) throw fail('oauth_exchange_uncertain','Previous OAuth exchange is uncertain; credential must advance before another grant is spent',503);
|
|
319
|
+
if (uncertain.has(key)) uncertain.delete(key);
|
|
320
|
+
const nowMs = this.clock()*1000;
|
|
321
|
+
const due = force || held.token.expires_at_ms != null && tokenExpired(nowMs,held.token.expires_at_ms,-300000);
|
|
322
|
+
if (!due || !held.token.refresh_token && (held.token.expires_at_ms == null || !tokenExpired(nowMs,held.token.expires_at_ms,0))) return {...held.token,scopes:held.scopes};
|
|
323
|
+
await store.prepareRefresh(held);
|
|
324
|
+
let response;
|
|
325
|
+
const client = {claude:CLAUDE_CLIENT_ID,codex:CODEX_CLIENT_ID,gemini:GEMINI_CLIENT_ID,qwen:QWEN_CLIENT_ID};
|
|
326
|
+
const body = {grant_type:'refresh_token',refresh_token:held.token.refresh_token,client_id:client[store.provider]};
|
|
327
|
+
if (store.provider === 'gemini') {
|
|
328
|
+
const id = nonempty(this.env.GEMINI_OAUTH_CLIENT_ID?.trim()), secret = nonempty(this.env.GEMINI_OAUTH_CLIENT_SECRET?.trim());
|
|
329
|
+
if (Boolean(id) !== Boolean(secret)) throw fail('invalid_oauth_client','Custom Gemini OAuth client requires both client ID and client secret');
|
|
330
|
+
body.client_id = id ?? GEMINI_CLIENT_ID; body.client_secret = secret ?? GEMINI_CLIENT_SECRET;
|
|
331
|
+
}
|
|
332
|
+
try { response = await this.exchange(store.provider,body); }
|
|
333
|
+
catch (error) { if (error.code === 'oauth_exchange_uncertain' || error.code === 'oauth_response_invalid') uncertain.set(key,fingerprint); throw error; }
|
|
334
|
+
const token = {...held.token,access_token:response.access_token,refresh_token:nonempty(response.refresh_token) ?? held.token.refresh_token,
|
|
335
|
+
expires_at_ms:response.expires_in == null ? null : nowMs+response.expires_in*1000};
|
|
336
|
+
try { await store.persist(held,token); } catch (error) { uncertain.set(key,fingerprint); throw error; }
|
|
337
|
+
return {...token,scopes:held.scopes};
|
|
338
|
+
});
|
|
339
|
+
flights.set(key,flight);
|
|
340
|
+
try { return structuredClone(await flight); } finally { if (flights.get(key) === flight) flights.delete(key); }
|
|
341
|
+
}
|
|
342
|
+
async headers(store, options) {
|
|
343
|
+
const token = await this.getFresh(store,options);
|
|
344
|
+
if (store.provider === 'claude' && token.scopes.length && !token.scopes.includes(CLAUDE_INFERENCE_SCOPE)) throw fail('oauth_scope_missing','Claude credential lacks user:inference scope',403);
|
|
345
|
+
return {token,headers:oauthHeaders(store.provider,token)};
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
export async function validateCredentialCatalog({provider,token,fetch = globalThis.fetch,baseURL,allowLoopback = false,timeoutMs = 20000}) {
|
|
350
|
+
provider = subscriptionProvider(provider);
|
|
351
|
+
const official = provider === 'gemini' ? 'https://generativelanguage.googleapis.com' : subscriptionBaseURL(provider,token);
|
|
352
|
+
const base = validateOAuthEndpoint(baseURL ?? official,{allowLoopback,expected:official+'/'}).replace(/\/$/,'');
|
|
353
|
+
const models = [], seen = new Set(); let cursor = null;
|
|
354
|
+
for (let page = 0;page < 100;page++) {
|
|
355
|
+
const url = new URL(base+(provider === 'claude' ? '/v1/models' : provider === 'gemini' ? '/v1beta/models' : '/models'));
|
|
356
|
+
if (provider === 'claude') url.searchParams.set('limit','1000');
|
|
357
|
+
if (provider === 'codex') url.searchParams.set('client_version','0.154.0');
|
|
358
|
+
if (provider === 'gemini') url.searchParams.set('pageSize','1000');
|
|
359
|
+
if (cursor) url.searchParams.set(cursor.key,cursor.value);
|
|
360
|
+
let response;
|
|
361
|
+
try { response = await fetch(url,{method:'GET',headers:{authorization:`Bearer ${token.access_token}`,...oauthHeaders(provider,token)},redirect:'error',signal:AbortSignal.timeout(timeoutMs)}); }
|
|
362
|
+
catch { throw fail('catalog_unverified','Subscription catalog could not be verified',502); }
|
|
363
|
+
if (!response.ok) throw fail('catalog_rejected','Subscription catalog rejected the credential',401);
|
|
364
|
+
const data = await boundedJSON(response,'catalog_invalid',4*1024*1024);
|
|
365
|
+
const rows = provider === 'gemini' || provider === 'codex' ? data.models : data.data;
|
|
366
|
+
if (!Array.isArray(rows)) throw fail('catalog_invalid','Subscription catalog has no model array',502);
|
|
367
|
+
const identity = provider === 'gemini' ? 'name' : provider === 'codex' ? 'slug' : 'id';
|
|
368
|
+
const pageModels = rows.filter(row => row && typeof row === 'object' && !Array.isArray(row) &&
|
|
369
|
+
(provider !== 'gemini' || !Array.isArray(row.supportedGenerationMethods) || row.supportedGenerationMethods.includes('generateContent')))
|
|
370
|
+
.map(row => nonempty(row[identity])).filter(Boolean);
|
|
371
|
+
for (const id of pageModels) if (!models.includes(id)) models.push(id);
|
|
372
|
+
const pageToken = nonempty(data.nextPageToken ?? data.next_page_token), nextCursor = nonempty(data.next_cursor ?? data.cursor ?? data.next ?? data.pagination?.next_cursor);
|
|
373
|
+
if (pageToken) cursor = {key:provider === 'gemini' ? 'pageToken' : 'page_token',value:pageToken};
|
|
374
|
+
else if (nextCursor) cursor = {key:'cursor',value:nextCursor};
|
|
375
|
+
else if (data.has_more === true) {
|
|
376
|
+
const next = nonempty(data.last_id) ?? pageModels.at(-1);
|
|
377
|
+
if (!next) throw fail('catalog_invalid','Subscription catalog pagination is invalid',502);
|
|
378
|
+
cursor = {key:provider === 'claude' ? 'after_id' : 'after',value:next};
|
|
379
|
+
} else { if (!models.length) throw fail('catalog_unverified','Subscription catalog returned no executable models',403); return models; }
|
|
380
|
+
const key = `${cursor.key}=${cursor.value}`;
|
|
381
|
+
if (seen.has(key)) throw fail('catalog_invalid','Subscription catalog pagination repeats a cursor',502);
|
|
382
|
+
seen.add(key);
|
|
383
|
+
}
|
|
384
|
+
throw fail('catalog_invalid','Subscription catalog exceeded pagination limits',502);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function loginMode(value = 'full') {
|
|
388
|
+
const normalized = String(value).trim().toLowerCase();
|
|
389
|
+
if (['','full','login','default'].includes(normalized)) return 'full';
|
|
390
|
+
if (['setup-token','setup_token','inference','narrow'].includes(normalized)) return 'setup-token';
|
|
391
|
+
throw fail('invalid_argument','Claude login mode must be full or setup-token');
|
|
392
|
+
}
|
|
393
|
+
function acceptedModels(value) {
|
|
394
|
+
if (!Array.isArray(value) || !value.length || value.some(model => typeof model !== 'string' || !model)) throw fail('catalog_unverified','Credential catalog acceptance requires exact nonempty model ids',403);
|
|
395
|
+
return [...new Set(value)];
|
|
396
|
+
}
|
|
397
|
+
export async function installAcceptedDocument({provider,document,sourcePath,destinationHome,dataDir,ifAbsent = false,follow = false,snapshot = false,beforePromote}) {
|
|
398
|
+
const store = new CredentialFileStore({provider,home:destinationHome,dataDir});
|
|
399
|
+
return store.transaction(async () => {
|
|
400
|
+
const previous = await store.readPrimary();
|
|
401
|
+
if (ifAbsent && previous) return {schema_version:1,results:[{provider,phase:'preflight',outcome:'already_present',transaction_id:null,previous_credential_safe:true}]};
|
|
402
|
+
const destination = previous?.pointer ?? join(store.home,files[store.provider][0]);
|
|
403
|
+
const transactionId = randomUUID().replaceAll('-','');
|
|
404
|
+
let installed = structuredClone(document);
|
|
405
|
+
if (follow) installed = {_link_assistant_router:{credential_source:await realpath(sourcePath),promotion_receipt:transactionId}};
|
|
406
|
+
else {
|
|
407
|
+
installed._link_assistant_router = {...installed._link_assistant_router,promotion_receipt:transactionId};
|
|
408
|
+
if (snapshot) installed._link_assistant_router.refresh_owner = 'external';
|
|
409
|
+
}
|
|
410
|
+
if (beforePromote) await beforePromote({provider,destination,transaction_id:transactionId});
|
|
411
|
+
await atomicWrite(destination,JSON.stringify(installed,null,2)+'\n');
|
|
412
|
+
return {schema_version:1,results:[{provider,phase:'promotion',outcome:'promoted',transaction_id:transactionId,previous_credential_safe:true}]};
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
// Non-destructive access-token validation followed by an atomic source reference
|
|
417
|
+
// is a supported import path. Full Rust rotating-candidate resume is not claimed.
|
|
418
|
+
export async function importCredential({provider,sourceHome,destinationHome,dataDir,ifAbsent = false,snapshot = false,owned = false,fetch = globalThis.fetch,clock = () => Math.floor(Date.now()/1000),validateCatalog = validateCredentialCatalog,catalogBaseURL,allowLoopback = false,beforePromote} = {}) {
|
|
419
|
+
provider = subscriptionProvider(provider);
|
|
420
|
+
if (!sourceHome || !destinationHome || !dataDir) throw fail('invalid_argument','Import requires explicit source, destination and Router data directories');
|
|
421
|
+
const source = new CredentialFileStore({provider,home:sourceHome,dataDir:join(dataDir,'import-source'),clock});
|
|
422
|
+
const destination = new CredentialFileStore({provider,home:destinationHome,dataDir,clock});
|
|
423
|
+
if (resolve(sourceHome) === resolve(destinationHome)) throw fail('invalid_argument','Credential import source and destination must differ');
|
|
424
|
+
const existing = await destination.readPrimary();
|
|
425
|
+
if (ifAbsent && existing) return {schema_version:1,results:[{provider,phase:'preflight',outcome:'already_present',transaction_id:null,previous_credential_safe:true}]};
|
|
426
|
+
const held = await source.readPrimary();
|
|
427
|
+
if (!held) throw fail('credentials_missing','Credential import source has no usable file credential',401);
|
|
428
|
+
if (existing?.path === held.path || await realpath(destinationHome).catch(() => resolve(destinationHome)) === await realpath(sourceHome)) throw fail('invalid_argument','Credential import source and destination must differ');
|
|
429
|
+
if (held.token.expires_at_ms != null && tokenExpired(clock()*1000,held.token.expires_at_ms,0)) throw fail('credential_expired','Import requires a live access token; externally owned grants are not spent',401);
|
|
430
|
+
if (held.origin === 'external' && !snapshot) throw fail('external_refresh_owner','A non-snapshot import requires a writable owning source file',401);
|
|
431
|
+
if (!snapshot) {
|
|
432
|
+
try { await access(dirname(held.path),constants.W_OK); await access(held.path,constants.W_OK); }
|
|
433
|
+
catch { throw fail('credential_persistence_unavailable','Owning source credential must be writable for safe refresh-chain import',503); }
|
|
434
|
+
}
|
|
435
|
+
const stage = join(dataDir,'auth-import-candidates',randomUUID().replaceAll('-',''));
|
|
436
|
+
const stagePath = join(stage,provider,files[provider][0]);
|
|
437
|
+
await atomicWrite(stagePath,JSON.stringify(held.document,null,2)+'\n');
|
|
438
|
+
try {
|
|
439
|
+
const models = acceptedModels(await validateCatalog({provider,token:held.token,fetch,baseURL:catalogBaseURL,allowLoopback}));
|
|
440
|
+
// Re-read after validation: a source file moved by its owner must be validated
|
|
441
|
+
// again, rather than installing the different chain link it now contains.
|
|
442
|
+
const current = await source.readPrimary();
|
|
443
|
+
if (!current || credentialFingerprint(current.token) !== credentialFingerprint(held.token)) throw fail('credential_changed','Credential changed during import; retry validation',409);
|
|
444
|
+
return await installAcceptedDocument({provider,document:held.document,sourcePath:held.path,destinationHome,dataDir,ifAbsent,follow:!snapshot && !owned,snapshot,models,beforePromote});
|
|
445
|
+
} finally { await rm(stage,{recursive:true,force:true}); }
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export class ClaudeLogin {
|
|
449
|
+
#pending;
|
|
450
|
+
constructor({home,mode = 'full',manager = new OAuthManager(),authorizeURL = CLAUDE_AUTHORIZE_URL,allowLoopback = false,clock = () => Math.floor(Date.now()/1000),pending} = {}) {
|
|
451
|
+
if (!home) throw fail('invalid_argument','Claude login requires an explicit credential home');
|
|
452
|
+
this.home = resolve(home); this.mode = loginMode(mode); this.manager = manager; this.clock = clock;
|
|
453
|
+
this.authorizeURL = validateOAuthEndpoint(authorizeURL,{allowLoopback,expected:CLAUDE_AUTHORIZE_URL});
|
|
454
|
+
this.#pending = pending ?? {state:randomBytes(32).toString('base64url'),code_verifier:randomBytes(32).toString('base64url'),expires_at:clock()*1000+600000};
|
|
455
|
+
this.used = false; this.pendingClaimed = false;
|
|
456
|
+
}
|
|
457
|
+
static async begin(options = {}) {
|
|
458
|
+
const login = new ClaudeLogin(options);
|
|
459
|
+
await atomicWrite(join(login.home,PENDING_FILE),encodeLino(login.#pending));
|
|
460
|
+
return login;
|
|
461
|
+
}
|
|
462
|
+
static async resume(options = {}) {
|
|
463
|
+
if (!options.home) throw fail('invalid_argument','Claude login requires an explicit credential home');
|
|
464
|
+
const path = join(resolve(options.home),PENDING_FILE), claimed = `${path}.${randomUUID()}.claimed`;
|
|
465
|
+
try { await rename(path,claimed); } catch { throw fail('pending_login_missing','No pending Claude authorization; begin a code flow first',404); }
|
|
466
|
+
let pending;
|
|
467
|
+
try {
|
|
468
|
+
const raw = await boundedOAuthFile(claimed,{maxBytes:PENDING_FILE_LIMIT,code:'pending_login_invalid',status:400});
|
|
469
|
+
if (raw === null) throw fail('pending_login_invalid','Pending Claude authorization is missing');
|
|
470
|
+
pending = raw.trim().startsWith('{') ? JSON.parse(raw) : decodeLino(raw);
|
|
471
|
+
}
|
|
472
|
+
catch { throw fail('pending_login_invalid','Pending Claude authorization is invalid'); }
|
|
473
|
+
finally { await unlink(claimed); }
|
|
474
|
+
const now = (options.clock?.() ?? Math.floor(Date.now()/1000))*1000;
|
|
475
|
+
if (!pending?.state || !pending.code_verifier || !Number.isSafeInteger(pending.expires_at) || pending.expires_at <= now) throw fail('pending_login_expired','Pending Claude authorization expired');
|
|
476
|
+
const login = new ClaudeLogin({...options,pending}); login.pendingClaimed = true; return login;
|
|
477
|
+
}
|
|
478
|
+
authorizationURL() {
|
|
479
|
+
const url = new URL(this.authorizeURL);
|
|
480
|
+
for (const [name,value] of Object.entries({code:'true',client_id:CLAUDE_CLIENT_ID,response_type:'code',redirect_uri:CLAUDE_REDIRECT_URI,
|
|
481
|
+
scope:this.mode === 'setup-token' ? CLAUDE_INFERENCE_SCOPE : CLAUDE_SCOPES,
|
|
482
|
+
code_challenge:createHash('sha256').update(this.#pending.code_verifier).digest('base64url'),code_challenge_method:'S256',state:this.#pending.state})) url.searchParams.set(name,value);
|
|
483
|
+
return url.href;
|
|
484
|
+
}
|
|
485
|
+
async complete(pasted,{dataDir = join(this.home,'.router'),validateCatalog = validateCredentialCatalog,catalogBaseURL,allowLoopback = false} = {}) {
|
|
486
|
+
if (this.used) throw fail('pending_login_consumed','Claude authorization code flow already consumed');
|
|
487
|
+
if (!this.pendingClaimed) {
|
|
488
|
+
const claimed = await ClaudeLogin.resume({home:this.home,mode:this.mode,manager:this.manager,authorizeURL:this.authorizeURL,clock:this.clock,allowLoopback:this.manager.allowLoopback});
|
|
489
|
+
if (claimed.#pending.state !== this.#pending.state) throw fail('pending_login_changed','Pending Claude authorization belongs to another login');
|
|
490
|
+
this.pendingClaimed = true;
|
|
491
|
+
}
|
|
492
|
+
this.used = true;
|
|
493
|
+
const [code,returnedState] = String(pasted).trim().split('#');
|
|
494
|
+
if (!code) throw fail('invalid_argument','Claude authorization code is empty');
|
|
495
|
+
if (returnedState != null && returnedState !== this.#pending.state) throw fail('oauth_state_mismatch','Claude authorization state did not match');
|
|
496
|
+
if (this.#pending.expires_at <= this.clock()*1000) throw fail('pending_login_expired','Pending Claude authorization expired');
|
|
497
|
+
const response = await this.manager.exchange('claude',{grant_type:'authorization_code',code,state:returnedState ?? this.#pending.state,
|
|
498
|
+
client_id:CLAUDE_CLIENT_ID,redirect_uri:CLAUDE_REDIRECT_URI,code_verifier:this.#pending.code_verifier});
|
|
499
|
+
const scopes = response.scope == null ? (this.mode === 'setup-token' ? CLAUDE_INFERENCE_SCOPE : CLAUDE_SCOPES).split(' ') : typeof response.scope === 'string' ? response.scope.split(/\s+/).filter(Boolean) : null;
|
|
500
|
+
if (!scopes) throw fail('oauth_response_invalid','Claude response has invalid granted scopes',502);
|
|
501
|
+
const oauth = {accessToken:response.access_token,scopes,subscriptionType:response.subscription_type ?? null,rateLimitTier:response.rate_limit_tier ?? null};
|
|
502
|
+
if (response.refresh_token) oauth.refreshToken = response.refresh_token;
|
|
503
|
+
if (response.expires_in != null) oauth.expiresAt = this.clock()*1000+response.expires_in*1000;
|
|
504
|
+
if (response.refresh_token_expires_in != null) {
|
|
505
|
+
if (!Number.isSafeInteger(response.refresh_token_expires_in) || response.refresh_token_expires_in < 0 || !Number.isSafeInteger(this.clock()*1000+response.refresh_token_expires_in*1000)) throw fail('oauth_response_invalid','Claude refresh expiry is invalid',502);
|
|
506
|
+
oauth.refreshTokenExpiresAt = this.clock()*1000+response.refresh_token_expires_in*1000;
|
|
507
|
+
}
|
|
508
|
+
const document = {claudeAiOauth:oauth};
|
|
509
|
+
const parsed = parseCredentialDocument('claude',document);
|
|
510
|
+
const stage = join(dataDir,'auth-import-candidates',randomUUID().replaceAll('-',''));
|
|
511
|
+
await atomicWrite(join(stage,'claude','.credentials.json'),JSON.stringify(document,null,2)+'\n');
|
|
512
|
+
let accepted = false;
|
|
513
|
+
try {
|
|
514
|
+
const models = acceptedModels(await validateCatalog({provider:'claude',token:parsed.token,fetch:this.manager.fetch,baseURL:catalogBaseURL,allowLoopback}));
|
|
515
|
+
const report = await installAcceptedDocument({provider:'claude',document,destinationHome:this.home,dataDir,models});
|
|
516
|
+
accepted = true;
|
|
517
|
+
return report;
|
|
518
|
+
} catch (error) {
|
|
519
|
+
// A successfully exchanged rotating chain is retained in its durable stage
|
|
520
|
+
// when catalog/promotion fails. No Rust resume parity is implied.
|
|
521
|
+
error.transaction_id = stage.split('/').at(-1);
|
|
522
|
+
throw error;
|
|
523
|
+
} finally { if (accepted) await rm(stage,{recursive:true,force:true}); }
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
export async function executeAuthOperation({name,options = {},core,config = core?.config ?? {},env = {},fetch = globalThis.fetch,clockSeconds = core?.clock ?? (() => Math.floor(Date.now()/1000)),oauth = {}} = {}) {
|
|
528
|
+
if (!['auth.import','auth.claude','auth.codex'].includes(name)) throw fail('native_unsupported','Native OAuth operation is not implemented',501);
|
|
529
|
+
if (options.router || options.url || options.target) throw fail('native_unsupported','Native local credential adoption does not support remote deployment targets',501);
|
|
530
|
+
if (options.all || options.resume || options.force || options.clear || options.port || options.agent || options.device) throw fail('native_unsupported','Native OAuth does not implement bulk, rotating transaction resume, forced adoption or credential withdrawal',501);
|
|
531
|
+
const provider = subscriptionProvider(name === 'auth.import' ? options.provider : name.slice(5));
|
|
532
|
+
const home = options.home ?? (provider === 'claude' ? config.claude_code_home ?? env.CLAUDE_CODE_HOME : config.codex_home ?? env.CODEX_HOME);
|
|
533
|
+
if (!home) throw fail('invalid_argument','Native OAuth requires an explicit destination credential home');
|
|
534
|
+
const sourceHome = options.dir ?? options.from_claude_home ?? options.from_codex_home;
|
|
535
|
+
const manager = new OAuthManager({fetch,clock:clockSeconds,...oauth});
|
|
536
|
+
if (name === 'auth.import' || sourceHome != null) {
|
|
537
|
+
if (!sourceHome) throw fail('native_unsupported','Native import requires an explicit source directory; platform keychain defaults are not implemented',501);
|
|
538
|
+
return importCredential({provider,sourceHome,destinationHome:home,dataDir:config.data_dir,ifAbsent:options.if_absent,snapshot:options.snapshot,fetch,clock:clockSeconds,...oauth});
|
|
539
|
+
}
|
|
540
|
+
if (name === 'auth.codex') throw fail('native_unsupported','Native Codex browser/device authorization is not implemented; use an explicit validated file import',501);
|
|
541
|
+
if (options.flow && !['auto','code'].includes(options.flow)) throw fail('native_unsupported','Native Claude authorization supports the code flow',501);
|
|
542
|
+
const loginOptions = {home,mode:options.mode,manager,clock:clockSeconds,...oauth};
|
|
543
|
+
if (!options.code) { const login = await ClaudeLogin.begin(loginOptions); return {output:[login.authorizationURL()]}; }
|
|
544
|
+
const login = await ClaudeLogin.resume(loginOptions);
|
|
545
|
+
const result = await login.complete(options.code,{dataDir:config.data_dir,...oauth});
|
|
546
|
+
return {output:[`Claude authorization ${result.results[0].outcome}.`]};
|
|
547
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {open,lstat} from 'node:fs/promises';
|
|
2
|
+
import {constants} from 'node:fs';
|
|
3
|
+
import {resolve,dirname,parse} from 'node:path';
|
|
4
|
+
const fail=message=>Object.assign(new Error(message),{code:'operation_input',exitCode:2});
|
|
5
|
+
export async function requireNativePath(path) {
|
|
6
|
+
for (let current=resolve(path);;) {
|
|
7
|
+
let stat;try {stat=await lstat(current);}catch(error) {if (error.code!=='ENOENT') throw error;}
|
|
8
|
+
if (stat?.isSymbolicLink()) throw fail('Operation input contains a symlink');
|
|
9
|
+
if (current===parse(current).root) return stat;current=dirname(current);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export async function readNativeText(path,{cwd=process.cwd(),maxBytes=64*1024*1024}={}) {
|
|
13
|
+
path=resolve(cwd,path);await requireNativePath(path);const file=await open(path,constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
14
|
+
try {
|
|
15
|
+
const stat=await file.stat();if (!stat.isFile() || stat.size>maxBytes) throw fail('Operation input requires a regular file within its byte budget');
|
|
16
|
+
const chunks=[];let bytes=0;
|
|
17
|
+
while (true) {const buffer=Buffer.alloc(Math.min(65536,maxBytes-bytes+1)),part=await file.read(buffer,0,buffer.length,null);if (!part.bytesRead) break;bytes+=part.bytesRead;if (bytes>maxBytes) throw fail('Operation input exceeds its byte budget');chunks.push(buffer.subarray(0,part.bytesRead));}
|
|
18
|
+
return new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(Buffer.concat(chunks,bytes));
|
|
19
|
+
} finally {await file.close();}
|
|
20
|
+
}
|