@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,68 @@
|
|
|
1
|
+
/** Non-mutating source decoders and safe transactional token import. */
|
|
2
|
+
import {lstat} from 'node:fs/promises';
|
|
3
|
+
import {resolve,join,extname} from 'node:path';
|
|
4
|
+
import {randomUUID} from 'node:crypto';
|
|
5
|
+
import {readNativeText,requireNativePath} from './operation-input.mjs';
|
|
6
|
+
import {decodeTokenRecords,mergeSaferRecord,atomicWrite} from './storage.mjs';
|
|
7
|
+
import {readBinaryTokenRecords} from './doublets.mjs';
|
|
8
|
+
const fail=message=>Object.assign(new Error(message),{code:'token_import',exitCode:2});
|
|
9
|
+
const stat=async path=>lstat(path).catch(error=>{if (error.code==='ENOENT') return null;throw error;});
|
|
10
|
+
function ordered(value) {
|
|
11
|
+
if (Array.isArray(value)) return value.map(ordered);
|
|
12
|
+
if (value && typeof value==='object') return Object.fromEntries(Object.keys(value).sort().map(key=>[key,ordered(value[key])]));
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
const same=(left,right)=>JSON.stringify(ordered(left))===JSON.stringify(ordered(right));
|
|
16
|
+
async function recordsFromFile(path) {
|
|
17
|
+
await requireNativePath(path);const info=await stat(path);if (!info?.isFile()) throw fail('Token import source is not a regular file');
|
|
18
|
+
if (extname(path)==='.bin') return readBinaryTokenRecords(path);
|
|
19
|
+
const source=await readNativeText(path);
|
|
20
|
+
if (extname(path)==='.lino') return decodeTokenRecords(source);
|
|
21
|
+
if (extname(path)==='.json') {const records=JSON.parse(source);if (!Array.isArray(records)) throw fail('Token JSON export must be an array');return records;}
|
|
22
|
+
throw fail('Token import requires a .lino, .bin or .json file');
|
|
23
|
+
}
|
|
24
|
+
export async function readTokenImportSource(path,{cwd=process.cwd(),validateRecord=()=>{}}={}) {
|
|
25
|
+
path=resolve(cwd,path);await requireNativePath(path);const info=await stat(path);if (!info) throw fail('Token import source does not exist');
|
|
26
|
+
const records=new Map();
|
|
27
|
+
const merge=values=> {
|
|
28
|
+
const fileIds=new Set();for (const value of values) {
|
|
29
|
+
validateRecord(value);if (fileIds.has(value.id)) throw fail('Duplicate imported token id');fileIds.add(value.id);
|
|
30
|
+
if (records.has(value.id)) mergeSaferRecord(records.get(value.id),value);else records.set(value.id,structuredClone(value));
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
if (info.isFile()) merge(await recordsFromFile(path));
|
|
34
|
+
else if (info.isDirectory()) {
|
|
35
|
+
const filenames=['tokens.lino','tokens.bin','tokens.json'];
|
|
36
|
+
const holds=async directory=>(await Promise.all(filenames.map(name=>stat(join(directory,name))))).some(info=>info?.isFile());
|
|
37
|
+
if (!await holds(path) && await holds(join(path,'data'))) path=join(path,'data');
|
|
38
|
+
let files=0;for (const name of filenames) {const file=join(path,name);if (await stat(file)) {merge(await recordsFromFile(file));files++;}}
|
|
39
|
+
if (!files) throw fail('Token import directory holds no tokens.lino, tokens.bin or tokens.json');
|
|
40
|
+
} else throw fail('Token import requires a file or directory');
|
|
41
|
+
return [...records.values()].sort((left,right)=>left.id.localeCompare(right.id));
|
|
42
|
+
}
|
|
43
|
+
export async function importTokenRecords({source,store,options={},dataDir,clock=()=>Math.floor(Date.now()/1000)}) {
|
|
44
|
+
const wanted=new Set(options.ids===undefined ? [] : Array.isArray(options.ids) ? options.ids : [options.ids]);
|
|
45
|
+
const report={mode:options.replace ? 'replace' : 'merge-missing',dry_run:options.dry_run ?? false,source_records:source.length,target_records_before:0,
|
|
46
|
+
added:[],unchanged:[],conflicts:[],replaced:[],kept_revoked:[],missing_from_source:[...wanted].filter(id=>!source.some(record=>record.id===id)).sort()};
|
|
47
|
+
const apply=async records=> {
|
|
48
|
+
report.target_records_before=records.size;const updates=[];
|
|
49
|
+
for (const incoming of source) {
|
|
50
|
+
if (wanted.size && !wanted.has(incoming.id)) continue;const existing=records.get(incoming.id);
|
|
51
|
+
if (!existing) {report.added.push(incoming.id);updates.push(incoming);continue;}
|
|
52
|
+
if (same(existing,incoming)) {report.unchanged.push(incoming.id);continue;}
|
|
53
|
+
const fields=[...new Set([...Object.keys(existing),...Object.keys(incoming)])].filter(key=>!same(existing[key],incoming[key])).sort();
|
|
54
|
+
if (!options.replace) {report.conflicts.push({id:incoming.id,fields});continue;}
|
|
55
|
+
const replacement=mergeSaferRecord(structuredClone(incoming),existing);if (existing.revoked) report.kept_revoked.push(incoming.id);
|
|
56
|
+
if (same(existing,replacement)) {report.unchanged.push(incoming.id);continue;}report.replaced.push({id:incoming.id,fields});updates.push(replacement);
|
|
57
|
+
}
|
|
58
|
+
if (report.dry_run || !updates.length) return;
|
|
59
|
+
if (report.replaced.length) {
|
|
60
|
+
const date=new Date(clock()*1000).toISOString().replace(/[-:]/g,'').replace('.000Z','Z');
|
|
61
|
+
const backup=join(dataDir,'token-import-backups',`tokens-${date}-${randomUUID().replaceAll('-','').slice(0,8)}.json`);
|
|
62
|
+
await requireNativePath(backup);await atomicWrite(backup,JSON.stringify([...records.values()].sort((a,b)=>a.id.localeCompare(b.id)),null,2)+'\n');report.backup=backup;
|
|
63
|
+
}
|
|
64
|
+
for (const record of updates) records.set(record.id,structuredClone(record));
|
|
65
|
+
};
|
|
66
|
+
if (report.dry_run) await apply(new Map((await store.list()).map(record=>[record.id,record])));else await store.transaction(apply);
|
|
67
|
+
return report;
|
|
68
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Source contract: src/token_reservation.rs; UTF-8 byte lengths match Rust str.len().
|
|
2
|
+
const totalStrings=value=>typeof value==='string'?Buffer.byteLength(value):value && typeof value==='object'?Object.values(value).reduce((sum,child)=>Math.min(Number.MAX_SAFE_INTEGER,sum+totalStrings(child)),0):0;
|
|
3
|
+
export function estimateRequestBudget(body) {
|
|
4
|
+
let characters=0;for(const field of ['messages','input','contents','system','prompt','tools'])characters=Math.min(Number.MAX_SAFE_INTEGER,characters+totalStrings(body?.[field]));
|
|
5
|
+
const caps=[body?.max_output_tokens,body?.max_completion_tokens,body?.max_tokens,body?.generationConfig?.maxOutputTokens];
|
|
6
|
+
const output=caps.find(value=>Number.isSafeInteger(value) && value>=0) ?? 4096,input=Math.ceil(characters/4);
|
|
7
|
+
return {input,output,total:Math.min(Number.MAX_SAFE_INTEGER,input+output)};
|
|
8
|
+
}
|
package/src/tokens.mjs
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual, randomUUID } from 'node:crypto';
|
|
2
|
+
import { tokenBudgetPermits } from '../portable/policy.mjs';
|
|
3
|
+
import { MemoryTokenStore } from './storage.mjs';
|
|
4
|
+
import { isSyntheticTokenId,diagnosticReason,firstAuthenticationOutcome } from './emergency-auth.mjs';
|
|
5
|
+
|
|
6
|
+
export class RouterError extends Error {
|
|
7
|
+
constructor(code, message, status = 400) { super(message); this.name = 'RouterError'; this.code = code; this.status = status; }
|
|
8
|
+
}
|
|
9
|
+
export function ensureRealSecret(secret) {
|
|
10
|
+
if (!secret || secret.startsWith('\0') || ['unused-by-remote-command','unused-by-auth','unused-by-this-client-command'].includes(secret)) throw new RouterError('issuer_secret_unset', 'TOKEN_SECRET is required', 401);
|
|
11
|
+
return secret;
|
|
12
|
+
}
|
|
13
|
+
const encode = object => Buffer.from(JSON.stringify(object)).toString('base64url');
|
|
14
|
+
const clients = new Set(['claude','codex','cursor','opencode','gemini','grok','qwen','agent']);
|
|
15
|
+
const clientAliases = new Map([['claude-code','claude'],['cursor-agent','cursor'],['gemini-cli','gemini'],['grok-cli','grok'],['qwen-code','qwen']]);
|
|
16
|
+
const number = (value, name, positive = false) => {
|
|
17
|
+
if (!Number.isSafeInteger(value) || value < (positive ? 1 : 0)) throw new RouterError('invalid_argument', `${name} must be a ${positive ? 'positive' : 'nonnegative'} safe integer`);
|
|
18
|
+
return value;
|
|
19
|
+
};
|
|
20
|
+
const defaults = {
|
|
21
|
+
ephemeral: false, run_lease_expires_at: null, sliding_window_seconds: null,
|
|
22
|
+
account: null, max_requests: null, used_requests: 0, max_tokens: null, used_tokens: 0,
|
|
23
|
+
reserved_tokens: 0, rate_limit_per_minute: null, rate_window_started_at: 0,
|
|
24
|
+
rate_window_requests: 0, scope: '', github_repos: [], client_kind: null, principal_id: null, model_policy: {},
|
|
25
|
+
};
|
|
26
|
+
export function validateModelPolicy(policy = {}) {
|
|
27
|
+
const models = policy.allowed_models ?? [];
|
|
28
|
+
if (!Array.isArray(models) || models.some(model => typeof model !== 'string' || !model.trim()) || new Set(models).size !== models.length) throw new RouterError('invalid_argument', 'allowed model ids must be nonempty and unique');
|
|
29
|
+
if (policy.allow_substitution ? !policy.substitution_source?.trim() : policy.substitution_source != null) throw new RouterError('invalid_argument', 'model substitution must name its configuration source');
|
|
30
|
+
return policy;
|
|
31
|
+
}
|
|
32
|
+
export class TokenManager {
|
|
33
|
+
constructor({ secret, store = new MemoryTokenStore(), clock = () => Math.floor(Date.now()/1000), leeway = 60,emergency,diagnostics } = {}) {
|
|
34
|
+
this.secret = secret; this.store = store; this.clock = clock; this.leeway = leeway;this.emergency=emergency;this.diagnostics=diagnostics;
|
|
35
|
+
}
|
|
36
|
+
sign(claims) {
|
|
37
|
+
ensureRealSecret(this.secret);
|
|
38
|
+
const body = `${encode({typ:'JWT',alg:'HS256'})}.${encode(claims)}`;
|
|
39
|
+
return `la_sk_${body}.${createHmac('sha256', this.secret).update(body).digest('base64url')}`;
|
|
40
|
+
}
|
|
41
|
+
async issue(options = {}) {
|
|
42
|
+
ensureRealSecret(this.secret);
|
|
43
|
+
options = {...options};
|
|
44
|
+
if (options.client_kind != null) { const name = String(options.client_kind).trim().toLowerCase(); options.client_kind = clientAliases.get(name) ?? name; }
|
|
45
|
+
const ttl = number(options.ttl_hours ?? 24, 'ttl_hours', true);
|
|
46
|
+
if (ttl > 87600) throw new RouterError('invalid_argument', 'ttl_hours must not exceed 87600');
|
|
47
|
+
for (const field of ['max_requests','max_tokens','rate_limit_per_minute','sliding_window_seconds','run_lease_seconds']) if (options[field] != null) number(options[field], field, true);
|
|
48
|
+
if (!['','admin'].includes(options.scope ?? '')) throw new RouterError('invalid_argument', 'scope must be empty (client) or admin');
|
|
49
|
+
if ((options.client_kind != null) !== (options.principal_id != null)) throw new RouterError('invalid_argument', 'client_kind and principal_id must be paired');
|
|
50
|
+
if (options.client_kind != null && (!clients.has(options.client_kind) || !options.principal_id?.trim() || options.account !== options.principal_id || options.scope === 'admin')) throw new RouterError('invalid_argument', 'invalid client/principal/account binding');
|
|
51
|
+
if (options.github_repos != null && (!Array.isArray(options.github_repos) || options.github_repos.some(repo => typeof repo !== 'string' || !/^[^\s/]+\/[^\s/]+$/.test(repo)))) throw new RouterError('invalid_argument', 'github repository scope must be owner/repo');
|
|
52
|
+
if (typeof (options.label ?? '') !== 'string') throw new RouterError('invalid_argument','label must be a string');
|
|
53
|
+
validateModelPolicy(options.model_policy);
|
|
54
|
+
const now = this.clock(), id = randomUUID();
|
|
55
|
+
const claims = { sub:id, iat:now, exp:now+ttl*3600, label:options.label ?? '' };
|
|
56
|
+
for (const field of ['scope','github_repos','client_kind','principal_id']) if (options[field] && (field !== 'github_repos' || options[field].length)) claims[field] = options[field];
|
|
57
|
+
const record = { ...structuredClone(defaults), id, label:claims.label, issued_at:now, expires_at:claims.exp, revoked:false };
|
|
58
|
+
for (const field of Object.keys(defaults)) if (Object.hasOwn(options, field)) record[field] = structuredClone(options[field]);
|
|
59
|
+
if (options.run_lease_seconds != null) record.run_lease_expires_at = now + options.run_lease_seconds;
|
|
60
|
+
const token = this.sign(claims);
|
|
61
|
+
await this.store.transaction(records => {
|
|
62
|
+
for (const [key, held] of records) if (held.ephemeral && (held.revoked || held.expires_at <= now)) records.delete(key);
|
|
63
|
+
records.set(id, record);
|
|
64
|
+
});
|
|
65
|
+
return { token, id, record:structuredClone(record) };
|
|
66
|
+
}
|
|
67
|
+
async validate(token, { admin = false, model, repository } = {}) {
|
|
68
|
+
ensureRealSecret(this.secret);
|
|
69
|
+
const jwt = typeof token === 'string' ? token.replace(/^(la_sk_|at-)/, '') : '';
|
|
70
|
+
if (!token?.startsWith('la_sk_') && !token?.startsWith('at-')) throw new RouterError('invalid_prefix', 'Invalid Router token prefix', 401);
|
|
71
|
+
const parts = jwt.split('.');
|
|
72
|
+
if (parts.length !== 3 || parts.some(part => !/^[A-Za-z0-9_-]+$/.test(part))) throw new RouterError('invalid_token', 'Invalid token encoding', 401);
|
|
73
|
+
let header, claims;
|
|
74
|
+
try { header = JSON.parse(Buffer.from(parts[0],'base64url')); claims = JSON.parse(Buffer.from(parts[1],'base64url')); }
|
|
75
|
+
catch { throw new RouterError('invalid_token', 'Invalid token JSON', 401); }
|
|
76
|
+
if (header.alg !== 'HS256') throw new RouterError('invalid_token', 'Only HS256 tokens are accepted', 401);
|
|
77
|
+
const expected = createHmac('sha256', this.secret).update(`${parts[0]}.${parts[1]}`).digest();
|
|
78
|
+
const actual = Buffer.from(parts[2], 'base64url');
|
|
79
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) throw new RouterError('signature_invalid', 'Token signature is invalid', 401);
|
|
80
|
+
if (typeof claims.sub !== 'string' || !claims.sub || !Number.isSafeInteger(claims.exp) || !Number.isSafeInteger(claims.iat)) throw new RouterError('invalid_token', 'Missing token claims', 401);
|
|
81
|
+
if (claims.nbf != null && (!Number.isSafeInteger(claims.nbf) || claims.nbf > this.clock()+this.leeway)) throw new RouterError('not_yet_valid', 'Token is not yet valid', 401);
|
|
82
|
+
const stored = await this.store.get(claims.sub);
|
|
83
|
+
const record = stored ? { ...structuredClone(defaults), ...stored } : null;
|
|
84
|
+
if (claims.exp < this.clock()-this.leeway && !(record?.sliding_window_seconds && record.expires_at > this.clock())) throw new RouterError('expired', 'Token expired', 401);
|
|
85
|
+
if (record?.revoked) throw new RouterError('revoked', 'Token revoked', 401);
|
|
86
|
+
if (record && ((record.client_kind ?? null) !== (claims.client_kind ?? null) || (record.principal_id ?? null) !== (claims.principal_id ?? null))) throw new RouterError('binding_mismatch', 'Token binding mismatch', 401);
|
|
87
|
+
if (!record && (claims.client_kind || claims.principal_id)) throw new RouterError('missing_record', 'Bound token record is missing', 401);
|
|
88
|
+
if (admin && claims.scope !== 'admin') throw new RouterError('admin_required', 'Administrative token required', 403);
|
|
89
|
+
const repos = claims.github_repos ?? [];
|
|
90
|
+
if (!Array.isArray(repos) || repos.some(repo => typeof repo !== 'string')) throw new RouterError('invalid_token', 'Invalid repository scope', 401);
|
|
91
|
+
if (repository && repos.length && !repos.some(repo => repo.toLowerCase() === repository.toLowerCase())) throw new RouterError('repository_not_allowed', 'Repository outside token scope', 403);
|
|
92
|
+
if (model && !record) throw new RouterError('model_policy_unavailable', 'Durable model authority is unavailable', 403);
|
|
93
|
+
const allowed = record?.model_policy?.allowed_models ?? [];
|
|
94
|
+
if (model && allowed.length && !allowed.includes(model)) throw new RouterError('model_not_allowed', 'Model outside token scope', 403);
|
|
95
|
+
return { ...claims, account: record?.account ?? null, record, is_admin:claims.scope === 'admin' };
|
|
96
|
+
}
|
|
97
|
+
async list() { return (await this.store.list()).sort((a,b) => a.issued_at-b.issued_at || a.id.localeCompare(b.id)); }
|
|
98
|
+
async authenticateIncoming(token,options = {}) {
|
|
99
|
+
const count=firstAuthenticationOutcome();
|
|
100
|
+
if (typeof token !== 'string' || !token) {
|
|
101
|
+
const error=new RouterError('missing_credential','Router credential is required',401);
|
|
102
|
+
if (count) this.diagnostics?.record('missing_credential');throw error;
|
|
103
|
+
}
|
|
104
|
+
let claims,error;
|
|
105
|
+
try {claims=await this.validate(token,options);} catch (failure) {error=failure;}
|
|
106
|
+
if (!options.admin && this.emergency?.isActive()) return this.emergency.admit(token,options.headers ?? {},error ? diagnosticReason(error) : 'none',count);
|
|
107
|
+
if (error) {if (count) this.diagnostics?.record(diagnosticReason(error),token);throw error;}
|
|
108
|
+
return claims;
|
|
109
|
+
}
|
|
110
|
+
async get(id) { return this.store.get(id); }
|
|
111
|
+
async authorizeModel(id, model) {
|
|
112
|
+
if (isSyntheticTokenId(id)) return {};
|
|
113
|
+
const record = await this.get(id);
|
|
114
|
+
if (!record) throw new RouterError('model_policy_unavailable','Durable model authority is unavailable',403);
|
|
115
|
+
if (record.model_policy?.allowed_models?.length && !record.model_policy.allowed_models.includes(model)) throw new RouterError('model_not_allowed','Model outside token scope',403);
|
|
116
|
+
return record.model_policy ?? {};
|
|
117
|
+
}
|
|
118
|
+
async revoke(id) { return this.store.transaction(records => { const r = records.get(id); if (!r) throw new RouterError('not_found','Token not found',404); const changed = !r.revoked; r.revoked = true; return changed; }); }
|
|
119
|
+
async expire(id) { return this.store.transaction(records => { const r = records.get(id); if (!r) throw new RouterError('not_found','Token not found',404); r.revoked = true; r.expires_at = this.clock(); return r; }); }
|
|
120
|
+
async rotate(id, overrides = {}) {
|
|
121
|
+
const held = await this.get(id);
|
|
122
|
+
if (!held) throw new RouterError('not_found','Token not found',404);
|
|
123
|
+
const options = {ttl_hours:Math.max(1,Math.floor((held.expires_at-this.clock())/3600))};
|
|
124
|
+
for (const field of ['label','account','max_requests','max_tokens','rate_limit_per_minute']) options[field] = overrides[field] ?? held[field];
|
|
125
|
+
options.ttl_hours = overrides.ttl_hours ?? options.ttl_hours;
|
|
126
|
+
for (const field of ['scope','github_repos','client_kind','principal_id','model_policy']) options[field] = held[field];
|
|
127
|
+
// Rust rotation mints a fresh durable, fixed-clock token with reset usage,
|
|
128
|
+
// then revokes the old token after successful issuance.
|
|
129
|
+
const replacement = await this.issue(options);
|
|
130
|
+
await this.revoke(id); return replacement;
|
|
131
|
+
}
|
|
132
|
+
async admit(id, reserve = 0) {
|
|
133
|
+
if (isSyntheticTokenId(id)) return 'admitted';
|
|
134
|
+
number(reserve, 'reserve');
|
|
135
|
+
return this.store.transaction(records => {
|
|
136
|
+
const r = records.get(id); if (!r) return 'admitted';
|
|
137
|
+
const now = this.clock();
|
|
138
|
+
if (r.revoked || (r.expires_at < now-this.leeway)) throw new RouterError('revoked','Token unavailable',401);
|
|
139
|
+
if (r.max_requests != null && r.used_requests >= r.max_requests) return 'request_limit_exceeded';
|
|
140
|
+
if (r.max_tokens != null && (r.used_tokens ?? 0)+(r.reserved_tokens ?? 0) >= r.max_tokens || !tokenBudgetPermits(r.used_tokens ?? 0,r.reserved_tokens ?? 0,reserve,r.max_tokens ?? -1)) return 'token_limit_exceeded';
|
|
141
|
+
if (r.rate_limit_per_minute != null) {
|
|
142
|
+
if (now-r.rate_window_started_at >= 60) { r.rate_window_started_at = now; r.rate_window_requests = 0; }
|
|
143
|
+
if (r.rate_window_requests >= r.rate_limit_per_minute) return 'rate_limit_exceeded';
|
|
144
|
+
r.rate_window_requests++;
|
|
145
|
+
}
|
|
146
|
+
r.used_requests++; r.reserved_tokens = (r.reserved_tokens ?? 0)+reserve;
|
|
147
|
+
if (r.sliding_window_seconds) r.expires_at = Math.max(r.expires_at,now+r.sliding_window_seconds);
|
|
148
|
+
return 'admitted';
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
async settle(id, reserved, actual) {
|
|
152
|
+
if (isSyntheticTokenId(id)) return;
|
|
153
|
+
number(reserved,'reserved'); number(actual,'actual');
|
|
154
|
+
return this.store.transaction(records => { const r = records.get(id); if (r) { r.reserved_tokens = Math.max(0,(r.reserved_tokens ?? 0)-reserved); r.used_tokens = Math.min(Number.MAX_SAFE_INTEGER,(r.used_tokens ?? 0)+actual); } });
|
|
155
|
+
}
|
|
156
|
+
async releaseStaleReservations() { return this.store.transaction(records => { let n = 0; for (const r of records.values()) if (r.reserved_tokens) { r.reserved_tokens = 0; n++; } return n; }); }
|
|
157
|
+
async enforceRequestBudget(id,reserve = 0) {
|
|
158
|
+
const verdict = await this.admit(id,reserve);
|
|
159
|
+
if (verdict !== 'admitted') {const error=new RouterError(verdict,'Router token budget is exhausted',429);this.diagnostics?.record(diagnosticReason(error));throw error;}
|
|
160
|
+
}
|
|
161
|
+
async recordUsage(id,tokens) { return this.settle(id,0,tokens); }
|
|
162
|
+
async renewRunLease(id) {
|
|
163
|
+
if (isSyntheticTokenId(id)) return this.clock()+120;
|
|
164
|
+
return this.store.transaction(records => {
|
|
165
|
+
const record = records.get(id), now = this.clock();
|
|
166
|
+
if (!record?.ephemeral || record.revoked || record.expires_at <= now || record.run_lease_expires_at == null) throw new RouterError('invalid_token','Run lease is absent, revoked, expired as a token, or not ephemeral',401);
|
|
167
|
+
record.run_lease_expires_at = now+120;
|
|
168
|
+
return record.run_lease_expires_at;
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
export const codexTokenAlias = token => token.startsWith('la_sk_') ? `at-${token.slice(6)}` : null;
|
package/src/usage.mjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/** Vendor usage extraction and partial-stream output estimation from src/usage.rs. */
|
|
2
|
+
const integer = value => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
3
|
+
const first = (value,keys) => keys.map(key=>integer(value?.[key])).find(value=>value !== undefined);
|
|
4
|
+
function parts(value) {
|
|
5
|
+
const usage=value?.usage;
|
|
6
|
+
if(usage) {
|
|
7
|
+
const total=integer(usage.total_tokens);if(total !== undefined)return {total};
|
|
8
|
+
const raw=first(usage,['input_tokens','prompt_tokens']),output=first(usage,['output_tokens','completion_tokens']);
|
|
9
|
+
const input=raw === undefined?undefined:raw+(integer(usage.cache_creation_input_tokens) ?? 0)+(integer(usage.cache_read_input_tokens) ?? 0);
|
|
10
|
+
if(input !== undefined || output !== undefined)return {input,output};
|
|
11
|
+
}
|
|
12
|
+
const gemini=value?.usageMetadata;
|
|
13
|
+
if(gemini){const total=integer(gemini.totalTokenCount);if(total !== undefined)return {total};const input=integer(gemini.promptTokenCount),output=integer(gemini.candidatesTokenCount);if(input !== undefined || output !== undefined)return {input,output};}
|
|
14
|
+
return value?.response ? parts(value.response) : value?.message ? parts(value.message):undefined;
|
|
15
|
+
}
|
|
16
|
+
const chars = value => typeof value === 'string'?[...value].length:0;
|
|
17
|
+
function outputChars(value) {
|
|
18
|
+
if(value?.type === 'content_block_delta')return ['text','thinking','partial_json'].reduce((n,key)=>n+chars(value.delta?.[key]),0);
|
|
19
|
+
if(value?.type?.startsWith('response.') && value.type.endsWith('.delta'))return chars(value.delta);
|
|
20
|
+
if(value?.type)return 0;
|
|
21
|
+
const chat=(value?.choices ?? []).reduce((n,choice)=>n+['content','reasoning_content','reasoning'].reduce((m,key)=>m+chars(choice.delta?.[key]),0)+(choice.delta?.tool_calls ?? []).reduce((m,call)=>m+chars(call.function?.arguments),0),0);
|
|
22
|
+
const gemini=(value?.response ?? value)?.candidates?.reduce((n,candidate)=>n+(candidate.content?.parts ?? []).reduce((m,part)=>m+chars(part.text),0),0) ?? 0;
|
|
23
|
+
return chat+gemini;
|
|
24
|
+
}
|
|
25
|
+
function finalUsage(value) {
|
|
26
|
+
if(value.type === 'message_delta')return value.usage && typeof value.usage === 'object';
|
|
27
|
+
if(['response.completed','response.incomplete','response.failed'].includes(value.type))return true;
|
|
28
|
+
if(value.type)return false;
|
|
29
|
+
if(value.usage && typeof value.usage === 'object')return true;
|
|
30
|
+
const native=value.response ?? value;return native.usageMetadata && native.candidates?.some(c=>c.finishReason);
|
|
31
|
+
}
|
|
32
|
+
export class UsageTracker {
|
|
33
|
+
constructor({maxBytes=32*1024*1024} = {}) {this.maxBytes=maxBytes;this.buffer=Buffer.alloc(0);this.json=[];this.jsonBytes=0;this.sse=false;this.total=0;this.input=0;this.output=0;this.streamedChars=0;this.final=false;this.finished=false;}
|
|
34
|
+
add(raw) {
|
|
35
|
+
let value;try{value=JSON.parse(Buffer.from(raw).toString('utf8'));}catch{return;}
|
|
36
|
+
if(this.sse){this.streamedChars+=outputChars(value);this.final ||= Boolean(finalUsage(value));}else this.final=true;
|
|
37
|
+
const usage=parts(value);if(usage){this.total=Math.max(this.total,usage.total ?? 0);this.input=Math.max(this.input,usage.input ?? 0);this.output=Math.max(this.output,usage.output ?? 0);}
|
|
38
|
+
}
|
|
39
|
+
feed(bytes) {
|
|
40
|
+
if(this.finished)return;
|
|
41
|
+
if(!this.sse && this.jsonBytes+bytes.byteLength <= this.maxBytes){this.json.push(Buffer.from(bytes));this.jsonBytes+=bytes.byteLength;}
|
|
42
|
+
this.buffer=Buffer.concat([this.buffer,bytes]);let end;
|
|
43
|
+
while((end=this.buffer.indexOf(10))>=0){const line=this.buffer.subarray(0,end).toString('utf8').replace(/\r$/,'');this.buffer=this.buffer.subarray(end+1);if(!line.startsWith('data:'))continue;this.sse=true;this.json=[];this.jsonBytes=0;this.add(line.slice(5).replace(/^ /,''));}
|
|
44
|
+
if(this.buffer.length>this.maxBytes)this.buffer=Buffer.alloc(0);
|
|
45
|
+
}
|
|
46
|
+
settlement() {
|
|
47
|
+
const estimate=this.sse && !this.final?Math.ceil(this.streamedChars/4):0,estimated=estimate>this.output,output=Math.max(this.output,estimate);
|
|
48
|
+
return {tokens:Math.max(this.total,this.input+output),estimated};
|
|
49
|
+
}
|
|
50
|
+
finish() {
|
|
51
|
+
if(!this.finished){if(!this.sse)this.add(Buffer.concat(this.json,this.jsonBytes));else if(this.buffer.toString('utf8').startsWith('data: '))this.add(this.buffer.subarray(6));this.finished=true;this.json=[];this.buffer=Buffer.alloc(0);}
|
|
52
|
+
return this.settlement();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import {request as httpRequest} from 'node:http';
|
|
2
|
+
import {request as httpsRequest} from 'node:https';
|
|
3
|
+
import {createHash,randomBytes} from 'node:crypto';
|
|
4
|
+
import {ProtocolError,normalizeUsage} from './protocols.mjs';
|
|
5
|
+
import {sanitizeGeolocation,sharesGeolocation} from './geolocation.mjs';
|
|
6
|
+
const guid='258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
7
|
+
const accept = key => createHash('sha1').update(key+guid).digest('base64');
|
|
8
|
+
/** Encode one complete bounded message after inspection, with a fresh client mask. */
|
|
9
|
+
export function encodeWebSocketFrame(opcode,payload,masked=true) {
|
|
10
|
+
const prefix=payload.length<126 ? 2:payload.length<=65535 ? 4:10;
|
|
11
|
+
const header=Buffer.alloc(prefix+(masked?4:0));header[0]=0x80|opcode;
|
|
12
|
+
header[1]=(masked?0x80:0)|(prefix===2 ? payload.length:prefix===4 ? 126:127);
|
|
13
|
+
if(prefix===4)header.writeUInt16BE(payload.length,2);
|
|
14
|
+
if(prefix===10)header.writeBigUInt64BE(BigInt(payload.length),2);
|
|
15
|
+
const body=Buffer.from(payload);
|
|
16
|
+
if(masked){const mask=randomBytes(4);mask.copy(header,prefix);for(let i=0;i<body.length;i++)body[i]^=mask[i%4];}
|
|
17
|
+
return Buffer.concat([header,body]);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function privateWebSocketPayload(opcode,payload,share=false) {
|
|
21
|
+
if(opcode !== 1 || share)return payload;
|
|
22
|
+
let value;try{value=JSON.parse(payload.toString('utf8'));}catch{return payload;}
|
|
23
|
+
return sanitizeGeolocation(value) ? Buffer.from(JSON.stringify(value)):payload;
|
|
24
|
+
}
|
|
25
|
+
const closeFrame = (code,reason,masked=false) => {
|
|
26
|
+
const text=Buffer.from(reason).subarray(0,123),payload=Buffer.alloc(2+text.length);payload.writeUInt16BE(code);text.copy(payload,2);
|
|
27
|
+
if(!masked)return Buffer.concat([Buffer.from([0x88,payload.length]),payload]);
|
|
28
|
+
const mask=randomBytes(4);for(let i=0;i<payload.length;i++)payload[i]^=mask[i%4];return Buffer.concat([Buffer.from([0x88,0x80|payload.length]),mask,payload]);
|
|
29
|
+
};
|
|
30
|
+
/** Inspect complete bounded RFC6455 messages and interleaved control frames. */
|
|
31
|
+
export class WebSocketInspector {
|
|
32
|
+
constructor({masked,maxMessageBytes=4*1024*1024,onMessage=()=>{}}) {this.masked=masked;this.limit=maxMessageBytes;this.onMessage=onMessage;this.buffer=Buffer.alloc(0);this.parts=[];this.size=0;this.opcode=null;}
|
|
33
|
+
async feed(chunk) {
|
|
34
|
+
this.buffer=Buffer.concat([this.buffer,chunk]);
|
|
35
|
+
while(this.buffer.length >= 2) {
|
|
36
|
+
const first=this.buffer[0],second=this.buffer[1],fin=Boolean(first&0x80),opcode=first&15,masked=Boolean(second&0x80);
|
|
37
|
+
if(first&0x70 || masked !== this.masked || ![0,1,2,8,9,10].includes(opcode))throw new ProtocolError('Invalid WebSocket frame',400);
|
|
38
|
+
let length=second&127,offset=2;
|
|
39
|
+
if(length === 126){if(this.buffer.length < 4)return;length=this.buffer.readUInt16BE(2);offset=4;}
|
|
40
|
+
if(length === 127){if(this.buffer.length < 10)return;const wide=this.buffer.readBigUInt64BE(2);if(wide > BigInt(this.limit))throw new ProtocolError('WebSocket frame exceeds limit',413);length=Number(wide);offset=10;}
|
|
41
|
+
if(length > this.limit || opcode >= 8 && (!fin || length > 125))throw new ProtocolError('WebSocket frame exceeds limit or has invalid control framing',413);
|
|
42
|
+
const maskLength=masked?4:0;
|
|
43
|
+
if(this.buffer.length < offset+maskLength+length)return;
|
|
44
|
+
const payload=Buffer.from(this.buffer.subarray(offset+maskLength,offset+maskLength+length));
|
|
45
|
+
if(masked){const mask=this.buffer.subarray(offset,offset+4);for(let i=0;i<payload.length;i++)payload[i]^=mask[i%4];}
|
|
46
|
+
this.buffer=this.buffer.subarray(offset+maskLength+length);
|
|
47
|
+
if(opcode >= 8){await this.onMessage(opcode,payload);continue;}
|
|
48
|
+
if(opcode === 0 && this.opcode == null || opcode !== 0 && this.opcode != null)throw new ProtocolError('Invalid fragmented WebSocket message',400);
|
|
49
|
+
if(opcode !== 0)this.opcode=opcode;
|
|
50
|
+
this.size+=payload.length;if(this.size > this.limit)throw new ProtocolError('WebSocket message exceeds limit',413);this.parts.push(payload);
|
|
51
|
+
if(fin){const value=Buffer.concat(this.parts,this.size),kind=this.opcode;this.parts=[];this.size=0;this.opcode=null;if(kind === 1)new TextDecoder('utf8',{fatal:true}).decode(value);await this.onMessage(kind,value);}
|
|
52
|
+
}
|
|
53
|
+
if(this.buffer.length > this.limit+14)throw new ProtocolError('WebSocket buffer exceeds limit',413);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function reject(socket,status,message) {
|
|
57
|
+
const body=JSON.stringify({error:{message,type:'api_error'}});
|
|
58
|
+
socket.end(`HTTP/1.1 ${status} Error\r\nContent-Type: application/json\r\nContent-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`);
|
|
59
|
+
}
|
|
60
|
+
/** Upgrade only after the exact upstream handshake; never disclose upstream credentials. */
|
|
61
|
+
export async function relayWebSocket(incoming,downstream,head,{target,authorize,core,maxMessageBytes=4*1024*1024,timeoutMs=15000}) {
|
|
62
|
+
const key=incoming.headers['sec-websocket-key'];
|
|
63
|
+
if(typeof key !== 'string' || !/^[A-Za-z0-9+/]{22}==$/.test(key) || incoming.headers['sec-websocket-version'] !== '13'){reject(downstream,400,'Invalid WebSocket handshake');return;}
|
|
64
|
+
let binding;try{binding=await target();}catch(error){reject(downstream,error.status ?? 500,error.message);return;}
|
|
65
|
+
const {url,headers,claims,privacy}=binding,upstreamKey=randomBytes(16).toString('base64');
|
|
66
|
+
const shareGeolocation=sharesGeolocation(new Headers(incoming.headers));
|
|
67
|
+
const options={...(binding.ca?{ca:binding.ca}:{}),method:'GET',headers:{...Object.fromEntries(headers),connection:'Upgrade',upgrade:'websocket','sec-websocket-key':upstreamKey,'sec-websocket-version':'13'},timeout:timeoutMs};
|
|
68
|
+
let connecting=true;
|
|
69
|
+
const request=(url.protocol === 'https:' ? httpsRequest:httpRequest)(url,options);
|
|
70
|
+
request.once('timeout',()=>request.destroy(new Error('WebSocket connect timeout')));
|
|
71
|
+
request.once('error',()=>{if(connecting)reject(downstream,502,'Upstream WebSocket connection failed');});
|
|
72
|
+
downstream.once('close',()=>request.destroy());
|
|
73
|
+
request.once('response',response=>{connecting=false;const chunks=[];let size=0;response.on('data',chunk=>{size+=chunk.length;if(size > maxMessageBytes){response.destroy();downstream.destroy();}else chunks.push(chunk);});response.once('end',()=>{const body=Buffer.concat(chunks);downstream.end(Buffer.concat([Buffer.from(`HTTP/1.1 ${response.statusCode} Upstream\r\nContent-Type: ${response.headers['content-type'] ?? 'application/json'}\r\nContent-Length: ${body.length}\r\nConnection: close\r\n\r\n`),body]));});});
|
|
74
|
+
request.once('upgrade',(response,upstream,upstreamHead)=>{
|
|
75
|
+
connecting=false;
|
|
76
|
+
if(response.headers['sec-websocket-accept'] !== accept(upstreamKey)){upstream.destroy();reject(downstream,502,'Invalid upstream WebSocket handshake');return;}
|
|
77
|
+
const protocol=response.headers['sec-websocket-protocol'];
|
|
78
|
+
const offered=String(incoming.headers['sec-websocket-protocol'] ?? '').split(',').map(v=>v.trim());
|
|
79
|
+
if(protocol && !offered.includes(protocol)){upstream.destroy();reject(downstream,502,'Upstream selected an unoffered WebSocket protocol');return;}
|
|
80
|
+
downstream.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept(key)}\r\n${protocol ? `Sec-WebSocket-Protocol: ${protocol}\r\n`:''}\r\n`);
|
|
81
|
+
const completed=new Set();let inFlight=0,closed=false;
|
|
82
|
+
const tokenId=claims.sub ?? claims.id;
|
|
83
|
+
const stop=async (code,reason) => {if(closed)return;closed=true;downstream.end(closeFrame(code,reason));upstream.end(closeFrame(code,reason,true));while(inFlight>0){inFlight--;await core.tokens?.settle?.(tokenId,0,0);}};
|
|
84
|
+
async function write(socket,frame) {
|
|
85
|
+
if (!socket.write(frame)) await new Promise(resolve=>socket.once('drain',resolve));
|
|
86
|
+
}
|
|
87
|
+
const fromClient=new WebSocketInspector({masked:true,maxMessageBytes,onMessage:async(opcode,payload)=>{
|
|
88
|
+
if (privacy && opcode >= 8) {
|
|
89
|
+
if (opcode === 8) await stop(1000,'WebSocket closed');
|
|
90
|
+
if (opcode === 9) await write(downstream,encodeWebSocketFrame(10,payload,false));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
let event;try{if(opcode===1)event=JSON.parse(payload.toString('utf8'));}catch{/* Preserve non-JSON text. */}
|
|
94
|
+
if (privacy) {
|
|
95
|
+
if (!event || typeof event !== 'object' || Array.isArray(event)) throw new ProtocolError('Sensitive data protection requires JSON events',415);
|
|
96
|
+
sanitizeGeolocation(event,shareGeolocation);
|
|
97
|
+
}
|
|
98
|
+
if(event?.type === 'response.create') {
|
|
99
|
+
const model=event.response?.model ?? event.model;
|
|
100
|
+
const allowed=claims.record?.model_policy?.allowed_models ?? [];
|
|
101
|
+
if(allowed.length && (!model || !allowed.includes(model)))throw new ProtocolError(model?'model_not_allowed':'model_required',403);
|
|
102
|
+
if(model)await authorize(model);
|
|
103
|
+
if(tokenId && core.tokens?.admit){const admitted=await core.tokens.admit(tokenId,0);if(admitted === false || typeof admitted === 'string' && admitted !== 'admitted')throw new ProtocolError('Router token budget is exhausted',429);inFlight++;}
|
|
104
|
+
}
|
|
105
|
+
const outgoing = privacy ? await privacy.protectEvent(event) : privateWebSocketPayload(opcode,payload,shareGeolocation);
|
|
106
|
+
if (outgoing.length > maxMessageBytes) throw new ProtocolError('Protected WebSocket message exceeds limit',413);
|
|
107
|
+
await write(upstream,encodeWebSocketFrame(opcode,outgoing));
|
|
108
|
+
}});
|
|
109
|
+
const fromUpstream=new WebSocketInspector({masked:false,maxMessageBytes,onMessage:async(opcode,payload)=>{
|
|
110
|
+
if (privacy) {
|
|
111
|
+
if (opcode === 9) await write(upstream,encodeWebSocketFrame(10,payload));
|
|
112
|
+
else if (opcode !== 10) await write(downstream,encodeWebSocketFrame(opcode,opcode === 1 ? privacy.restoreEvent(payload) : payload,false));
|
|
113
|
+
}
|
|
114
|
+
if(opcode !== 1)return;let event;try{event=JSON.parse(payload.toString('utf8'));}catch{return;}
|
|
115
|
+
const response=event.response;if(!['response.completed','response.done'].includes(event.type) || !response?.id || completed.has(response.id))return;
|
|
116
|
+
completed.add(response.id);if(completed.size>10000)throw new ProtocolError('WebSocket response identity limit exceeded',413);
|
|
117
|
+
const usage=normalizeUsage(response.usage);if(tokenId)await core.tokens?.settle?.(tokenId,0,usage.total);if(inFlight>0)inFlight--;
|
|
118
|
+
}});
|
|
119
|
+
const forward=(source,sink,inspector,initial,raw=true)=>{
|
|
120
|
+
let pending=Promise.resolve();
|
|
121
|
+
const consume=chunk=>{source.pause();pending=pending.then(async()=>{if(closed)return;await inspector.feed(chunk);if(raw && !sink.write(chunk))await new Promise(resolve=>sink.once('drain',resolve));source.resume();}).catch(()=>stop(1008,'Router rejected WebSocket message'));};
|
|
122
|
+
source.on('data',consume);
|
|
123
|
+
source.once('end',()=>{pending=pending.then(()=>sink.end());});
|
|
124
|
+
source.once('error',()=>stop(1011,'WebSocket peer disconnected'));
|
|
125
|
+
source.once('close',()=>{if(!source.readableEnded)void pending.then(()=>sink.destroy());});
|
|
126
|
+
if(initial.length)consume(initial);
|
|
127
|
+
};
|
|
128
|
+
forward(downstream,upstream,fromClient,head,false);forward(upstream,downstream,fromUpstream,upstreamHead,!privacy);
|
|
129
|
+
});
|
|
130
|
+
request.end();
|
|
131
|
+
}
|
package/testing.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Router, Invocation, JsonValue } from './index.js';
|
|
2
|
+
export interface FixtureHome { home: string; env: Record<string, string>; close(): Promise<void>; }
|
|
3
|
+
export function temporaryHome(): Promise<FixtureHome>;
|
|
4
|
+
export interface MockRequest { method: string; path: string; body: JsonValue; }
|
|
5
|
+
export function mockUpstream(handler?: (request: MockRequest) => { status?: number; body: JsonValue | string }): Promise<{ origin: string; requests: MockRequest[]; close(): Promise<void> }>;
|
|
6
|
+
export function vendorStub(options?: { name?: string; version?: string; output?: string; exitCode?: number }): Promise<{ binary: string; directory: string; env: Record<string, string>; close(): Promise<void> }>;
|
|
7
|
+
export function verifyContracts(options?: { router?: Router; areas?: string[]; linux?: boolean; repository?: string; output?: string; clientVersions?: 'installed' | 'ci' | 'latest'; requireParity?: boolean; deadlineMs?: number; env?: Record<string, string> }): Promise<JsonValue>;
|
package/testing.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Reusable, isolated fixtures for downstream contract tests. */
|
|
2
|
+
import { createServer } from 'node:http';
|
|
3
|
+
import { mkdtemp, mkdir, writeFile, rm, readFile } from 'node:fs/promises';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { join, resolve } from 'node:path';
|
|
6
|
+
import { Router, RouterError, runProcess, validateOperation } from './index.js';
|
|
7
|
+
|
|
8
|
+
export async function temporaryHome() {
|
|
9
|
+
const home = await mkdtemp(join(tmpdir(), 'router-home-'));
|
|
10
|
+
const env = { HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: join(home, '.config'), XDG_DATA_HOME: join(home, '.local/share'), XDG_CACHE_HOME: join(home, '.cache'), CODEX_HOME: join(home, '.codex'), CLAUDE_CONFIG_DIR: join(home, '.claude'), DATA_DIR: join(home, 'router-data') };
|
|
11
|
+
return { home, env, close: () => rm(home, { recursive: true, force: true }) };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Loopback upstream with finite request bodies and recorded, secret-free requests. */
|
|
15
|
+
export async function mockUpstream(handler = request => ({ status: 200, body: request.path.endsWith('/models') ? { object: 'list', data: [{ id: 'fixture-model', object: 'model', owned_by: 'fixture' }] } : { id: 'fixture-completion', object: 'chat.completion', model: 'fixture-model', choices: [{ index: 0, message: { role: 'assistant', content: 'fixture answer' }, finish_reason: 'stop' }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } } })) {
|
|
16
|
+
const requests = [];
|
|
17
|
+
const server = createServer(async (request, response) => {
|
|
18
|
+
try {
|
|
19
|
+
let bytes = 0, body = '';
|
|
20
|
+
for await (const chunk of request) { bytes += chunk.length; if (bytes > 1_048_576) { response.writeHead(413).end(); return; } body += chunk; }
|
|
21
|
+
const record = { method: request.method, path: request.url, body: body ? JSON.parse(body) : null };
|
|
22
|
+
requests.push(record);
|
|
23
|
+
const result = await handler(record);
|
|
24
|
+
response.writeHead(result.status ?? 200, { 'content-type': 'application/json', ...result.headers });
|
|
25
|
+
response.end(typeof result.body === 'string' ? result.body : JSON.stringify(result.body));
|
|
26
|
+
} catch { response.writeHead(500).end(); }
|
|
27
|
+
});
|
|
28
|
+
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
29
|
+
return { origin: `http://127.0.0.1:${server.address().port}`, requests, close: () => new Promise((resolve, reject) => { server.closeAllConnections?.(); server.close(error => error && error.code !== 'ERR_SERVER_NOT_RUNNING' ? reject(error) : resolve()); }) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** A vendor executable that never contacts a paid service. */
|
|
33
|
+
export async function vendorStub({ name = 'codex', version = '0.158.0', output = 'fixture answer', exitCode = 0 } = {}) {
|
|
34
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new RouterError('Invalid stub executable name', { code: 'options' });
|
|
35
|
+
const directory = await mkdtemp(join(tmpdir(), 'router-vendor-'));
|
|
36
|
+
const binary = join(directory, name);
|
|
37
|
+
const source = `#!/usr/bin/env node\nif(process.argv.includes('--version')){console.log(${JSON.stringify(version)});process.exit(0)}console.log(${JSON.stringify(output)});process.exit(${Number(exitCode)});\n`;
|
|
38
|
+
await writeFile(binary, source, { mode: 0o755 });
|
|
39
|
+
return { binary, directory, env: { PATH: `${directory}${process.platform === 'win32' ? ';' : ':'}${process.env.PATH ?? ''}` }, close: () => rm(directory, { recursive: true, force: true }) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Run the authoritative native verifier or the disposable Linux boundary. */
|
|
43
|
+
export async function verifyContracts({ router = new Router(), areas = [], linux = false, repository = process.cwd(), output, clientVersions = 'installed', deadlineMs = 3_600_000, requireParity = false, env = {} } = {}) {
|
|
44
|
+
const args = areas.flatMap(area => ['--area', area]);
|
|
45
|
+
if (requireParity) args.push('--require-parity');
|
|
46
|
+
if (!linux) {
|
|
47
|
+
if (output) args.push('--output', resolve(output));
|
|
48
|
+
return (await router.verify({ arguments: args }, { deadlineMs, cwd: repository, env })).data;
|
|
49
|
+
}
|
|
50
|
+
const response = await runProcess('bash', [join(repository, 'scripts/verify-contracts-in-linux.sh'), '--client-versions', clientVersions, ...args], { env, deadlineMs, cwd: repository });
|
|
51
|
+
const path = join(repository, 'target/verification-linux/result.json');
|
|
52
|
+
let result;
|
|
53
|
+
try { result = JSON.parse(await readFile(path, 'utf8')); } catch (cause) { throw new RouterError('Linux verification produced no result.json', { code: 'schema', stderr: response.stderr, exitCode: response.exitCode, cause }); }
|
|
54
|
+
validateOperation('verify', { schema: 'link-assistant-router/verify/v1', operation: 'verify', success: response.exitCode === 0, exit_code: response.exitCode, data: result, diagnostics: [] });
|
|
55
|
+
if (response.exitCode !== 0) throw new RouterError('Linux verification failed', { exitCode: response.exitCode, stderr: response.stderr, result });
|
|
56
|
+
return result;
|
|
57
|
+
}
|