@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.
Files changed (161) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68542 -0
  3. package/index.d.ts +5932 -0
  4. package/index.js +224 -0
  5. package/native.d.ts +106 -0
  6. package/package.json +62 -4
  7. package/portable/policy.mjs +117 -0
  8. package/schemas/accounts-list.v1.json +323 -0
  9. package/schemas/accounts-pause.v1.json +97 -0
  10. package/schemas/accounts-policy.v1.json +214 -0
  11. package/schemas/accounts-resume.v1.json +97 -0
  12. package/schemas/auth-claude.v1.json +97 -0
  13. package/schemas/auth-clear.v1.json +97 -0
  14. package/schemas/auth-codex.v1.json +97 -0
  15. package/schemas/auth-gh.v1.json +97 -0
  16. package/schemas/auth-import.v1.json +167 -0
  17. package/schemas/auth-status.v1.json +387 -0
  18. package/schemas/cli-error.v1.json +97 -0
  19. package/schemas/clients-backup-create.v1.json +97 -0
  20. package/schemas/clients-backup-list.v1.json +234 -0
  21. package/schemas/clients-backup-restore.v1.json +97 -0
  22. package/schemas/clients-backup-verify.v1.json +125 -0
  23. package/schemas/clients-doctor.v1.json +249 -0
  24. package/schemas/clients-install.v1.json +164 -0
  25. package/schemas/clients-list.v1.json +194 -0
  26. package/schemas/clients-reinstall.v1.json +164 -0
  27. package/schemas/clients-remove.v1.json +97 -0
  28. package/schemas/clients-repair.v1.json +109 -0
  29. package/schemas/clients-reset.v1.json +113 -0
  30. package/schemas/clients-setup.v1.json +97 -0
  31. package/schemas/clients-show.v1.json +191 -0
  32. package/schemas/clients-update.v1.json +164 -0
  33. package/schemas/configure.v1.json +97 -0
  34. package/schemas/contracts.v1.json +106 -0
  35. package/schemas/data-backup.v1.json +32 -0
  36. package/schemas/deploy.v1.json +546 -0
  37. package/schemas/doctor.v1.json +324 -0
  38. package/schemas/local-deployment.v1.json +364 -0
  39. package/schemas/logs-anomalies.v1.json +112 -0
  40. package/schemas/logs-show.v1.json +127 -0
  41. package/schemas/logs-summary.v1.json +129 -0
  42. package/schemas/model-catalog.v1.json +117 -0
  43. package/schemas/models-explain.v1.json +325 -0
  44. package/schemas/preservation.v1.json +47 -0
  45. package/schemas/providers-add.v1.json +185 -0
  46. package/schemas/providers-import.v1.json +97 -0
  47. package/schemas/providers-list.v1.json +182 -0
  48. package/schemas/providers-remove.v1.json +97 -0
  49. package/schemas/providers-show.v1.json +179 -0
  50. package/schemas/serve.v1.json +97 -0
  51. package/schemas/server-claim.v1.json +97 -0
  52. package/schemas/server-reap.v1.json +97 -0
  53. package/schemas/server-remove.v1.json +97 -0
  54. package/schemas/server-start.v1.json +97 -0
  55. package/schemas/server-status.v1.json +197 -0
  56. package/schemas/server-stop.v1.json +97 -0
  57. package/schemas/server-use.v1.json +97 -0
  58. package/schemas/staging.v1.json +47 -0
  59. package/schemas/tls-ca.v1.json +97 -0
  60. package/schemas/tls-generate.v1.json +97 -0
  61. package/schemas/tokens-expire.v1.json +97 -0
  62. package/schemas/tokens-import.v1.json +192 -0
  63. package/schemas/tokens-issue.v1.json +94 -0
  64. package/schemas/tokens-list.v1.json +272 -0
  65. package/schemas/tokens-recover-admin.v1.json +116 -0
  66. package/schemas/tokens-revoke.v1.json +97 -0
  67. package/schemas/tokens-rotate.v1.json +94 -0
  68. package/schemas/tokens-show.v1.json +269 -0
  69. package/schemas/tunnel-down.v1.json +97 -0
  70. package/schemas/tunnel-status.v1.json +165 -0
  71. package/schemas/tunnel-up.v1.json +97 -0
  72. package/schemas/usage.v1.json +621 -0
  73. package/schemas/verification.v1.json +254 -0
  74. package/schemas/verify.v1.json +338 -0
  75. package/schemas/version.v1.json +103 -0
  76. package/schemas/with.v1.json +105 -0
  77. package/src/accounts.mjs +233 -0
  78. package/src/activitypub.mjs +23 -0
  79. package/src/admin-assets.mjs +16 -0
  80. package/src/admin.mjs +108 -0
  81. package/src/affinities.mjs +180 -0
  82. package/src/affinity-schema-descriptor.mjs +2 -0
  83. package/src/affinity-schema.mjs +185 -0
  84. package/src/assets/admin/assets/app.js +1 -0
  85. package/src/assets/admin/assets/react.js +9 -0
  86. package/src/assets/admin/assets/rolldown-runtime.js +1 -0
  87. package/src/assets/admin/assets/ui-vendor.js +3 -0
  88. package/src/assets/admin/index.html +16 -0
  89. package/src/auth-service.mjs +149 -0
  90. package/src/claude-process-session.mjs +26 -0
  91. package/src/cli-output.mjs +21 -0
  92. package/src/cli.mjs +84 -0
  93. package/src/client-ca.mjs +8 -0
  94. package/src/client-catalog.mjs +52 -0
  95. package/src/client-codex-catalog.mjs +18 -0
  96. package/src/client-configure.mjs +72 -0
  97. package/src/client-files.mjs +82 -0
  98. package/src/client-global-repair.mjs +19 -0
  99. package/src/client-global-state.mjs +19 -0
  100. package/src/client-global.mjs +43 -0
  101. package/src/client-json.mjs +54 -0
  102. package/src/client-launch-plan.mjs +28 -0
  103. package/src/client-launch.mjs +35 -0
  104. package/src/client-persistent.mjs +66 -0
  105. package/src/client-process-profile.mjs +52 -0
  106. package/src/client-process-settings.mjs +36 -0
  107. package/src/client-process.mjs +44 -0
  108. package/src/client-profile-backup.mjs +29 -0
  109. package/src/client-remote-health.mjs +7 -0
  110. package/src/client-remote.mjs +55 -0
  111. package/src/client-run-credential.mjs +38 -0
  112. package/src/client-setup.mjs +97 -0
  113. package/src/client-status.mjs +102 -0
  114. package/src/client-toml-cst.mjs +71 -0
  115. package/src/client-transaction.mjs +48 -0
  116. package/src/codex-login.mjs +121 -0
  117. package/src/codex-loopback-transport.mjs +34 -0
  118. package/src/codex-loopback.mjs +60 -0
  119. package/src/config.mjs +198 -0
  120. package/src/core.mjs +198 -0
  121. package/src/credential-operations.mjs +119 -0
  122. package/src/doublets.mjs +157 -0
  123. package/src/emergency-auth.mjs +91 -0
  124. package/src/file-lock.mjs +107 -0
  125. package/src/gemini-protocol.mjs +133 -0
  126. package/src/geolocation.mjs +46 -0
  127. package/src/git-proxy.mjs +52 -0
  128. package/src/github-proxy.mjs +74 -0
  129. package/src/http-management.mjs +36 -0
  130. package/src/http-route-contract.mjs +479 -0
  131. package/src/index.mjs +4 -0
  132. package/src/local-router-discovery.mjs +31 -0
  133. package/src/managed-server.mjs +411 -0
  134. package/src/management-access.mjs +76 -0
  135. package/src/native-service.mjs +392 -0
  136. package/src/oauth.mjs +547 -0
  137. package/src/operation-input.mjs +20 -0
  138. package/src/operations.mjs +378 -0
  139. package/src/protocols.mjs +229 -0
  140. package/src/provider-manifest.mjs +46 -0
  141. package/src/provider-provision.mjs +24 -0
  142. package/src/remote-operations.mjs +166 -0
  143. package/src/request-log.mjs +99 -0
  144. package/src/resources.mjs +290 -0
  145. package/src/response-contracts.mjs +147 -0
  146. package/src/responses.mjs +103 -0
  147. package/src/routing.mjs +40 -0
  148. package/src/runtime-config.mjs +133 -0
  149. package/src/runtime-payload.mjs +190 -0
  150. package/src/sensitive-data-sse.mjs +121 -0
  151. package/src/sensitive-data.mjs +254 -0
  152. package/src/server.mjs +552 -0
  153. package/src/storage.mjs +367 -0
  154. package/src/streams.mjs +232 -0
  155. package/src/token-import.mjs +68 -0
  156. package/src/token-reservation.mjs +8 -0
  157. package/src/tokens.mjs +172 -0
  158. package/src/usage.mjs +54 -0
  159. package/src/websocket-relay.mjs +131 -0
  160. package/testing.d.ts +7 -0
  161. package/testing.js +57 -0
@@ -0,0 +1,74 @@
1
+ import {readFile} from 'node:fs/promises';
2
+ import {join} from 'node:path';
3
+ import {boundedBytes,nativeResponseHeaders} from './native-service.mjs';
4
+ import {ProtocolError} from './protocols.mjs';
5
+ const glob=(pattern,path)=>pattern.endsWith('/**') ? path===pattern.slice(0,-3) || path.startsWith(pattern.slice(0,-3)+'/') : pattern.split('/').length===path.split('/').length && pattern.split('/').every((part,index)=>part==='*' || part===path.split('/')[index]);
6
+ const parse=body=>{try{return JSON.parse(Buffer.from(body).toString('utf8'));}catch{return null;}};
7
+ function graphqlNames(query) {
8
+ const names=[];let position=0;
9
+ while(position<query.length) {
10
+ if(query[position]==='#'){while(position<query.length && query[position]!=='\n')position++;continue;}
11
+ if(query.startsWith('"""',position)){position+=3;while(position<query.length && !query.startsWith('"""',position))position++;position+=3;continue;}
12
+ if(query[position]==='"'){position++;while(position<query.length){if(query[position]==='\\'){position+=2;continue;}if(query[position++]==='"')break;}continue;}
13
+ const name=/^[_A-Za-z][_0-9A-Za-z]*/.exec(query.slice(position));if(name){names.push(name[0].toLowerCase());position+=name[0].length;}else position++;
14
+ }
15
+ return names;
16
+ }
17
+ function nested(value,predicate) {return value && typeof value==='object' && Object.entries(value).some(([key,child])=>predicate(key.toLowerCase(),child) || nested(child,predicate));}
18
+ export function destructiveGraphql(body) {
19
+ const value=parse(body);if(typeof value?.query!=='string')return false;
20
+ const names=graphqlNames(value.query),compact=value.query.replace(/\s/g,'').toLowerCase();if(!names.includes('mutation'))return false;
21
+ return names.some(name=>name.startsWith('delete')) || names.some(name=>['transferrepository','updaterepositoryruleset','createrepositoryruleset','updateorganizationruleset','createorganizationruleset','updatebranchprotectionrule','createbranchprotectionrule'].includes(name)) || names.includes('updaterepository') && (compact.includes('visibility:') || compact.includes('"visibility"')) || names.some(name=>['updateref','updaterefs'].includes(name)) && (compact.includes('force:true') || nested(value.variables,(key,v)=>key==='force' && v===true)) || names.includes('updaterefs') && (/afteroid:["']0{40,}["']/.test(compact) || nested(value.variables,(key,v)=>key==='afteroid' && typeof v==='string' && /^0{40,}$/.test(v)));
22
+ }
23
+ export function githubDecision(policy,method,path,body=new Uint8Array()) {
24
+ method=method.toUpperCase();const text=Buffer.from(body).toString('utf8').toLowerCase();
25
+ for(const rule of policy?.rules ?? [])if((!rule.method || rule.method.toUpperCase()===method) && glob(rule.path,path) && (!rule.body_contains || text.includes(rule.body_contains.toLowerCase())))return rule.effect;
26
+ const value=parse(body),segments=path.split('/');
27
+ const protection=segments[1]==='repos' && segments[4]==='branches' && segments.slice(5).includes('protection');
28
+ const ruleset=segments[1]==='repos' && segments[4]==='rulesets' || segments[1]==='orgs' && segments[3]==='rulesets';
29
+ const effect=['PUT','POST','PATCH'].includes(method) && (protection || ruleset) || method==='POST' && glob('/repos/*/*/transfer',path) || method==='PATCH' && glob('/repos/*/*',path.replace(/\/+$/,'')) && Object.keys(value ?? {}).some(key=>['archived','private','visibility','default_branch'].includes(key.toLowerCase()));
30
+ return method==='DELETE' || method==='PATCH' && path.includes('/git/refs/') && value?.force===true || effect || path==='/graphql' && destructiveGraphql(body) ? 'deny':'allow';
31
+ }
32
+ function validatePolicy(policy) {
33
+ if(!policy || typeof policy!=='object' || Array.isArray(policy) || Object.keys(policy).some(key=>key!=='rules') || policy.rules!==undefined && !Array.isArray(policy.rules))throw new ProtocolError('Invalid GitHub policy',500);
34
+ for(const rule of policy.rules ?? [])if(!rule || Object.keys(rule).some(key=>!['effect','method','path','body_contains'].includes(key)) || !['allow','deny'].includes(rule.effect) || typeof rule.path!=='string' || rule.method!=null && typeof rule.method!=='string' || rule.body_contains!=null && typeof rule.body_contains!=='string')throw new ProtocolError('Invalid GitHub policy rule',500);
35
+ return policy;
36
+ }
37
+ export async function githubConfiguration(config={},env={}) {
38
+ const specified=config.github ?? {},base_url=(specified.base_url ?? env.GITHUB_PROXY_BASE_URL ?? 'https://api.github.com').replace(/\/+$/,'');
39
+ let token=specified.token ?? env.GITHUB_PROXY_TOKEN;
40
+ if(!token && env.GITHUB_PROXY_TOKEN_FILE)token=(await readFile(env.GITHUB_PROXY_TOKEN_FILE,'utf8')).trim();
41
+ if(!token && env.GITHUB_PROXY_TOKEN_ENV)token=env[env.GITHUB_PROXY_TOKEN_ENV];
42
+ if(!token && config.data_dir){try{token=(await readFile(join(config.data_dir,'github-credential'),'utf8')).trim();}catch(error){if(error.code!=='ENOENT')throw error;}}
43
+ if(!token) {
44
+ const dir=env.GH_CONFIG_DIR || (env.HOME ? join(env.HOME,'.config','gh'):undefined);
45
+ if(dir) {let contents;try{contents=await readFile(join(dir,'hosts.yml'),'utf8');}catch(error){if(error.code!=='ENOENT')throw error;}
46
+ const host=new URL(base_url).hostname.replace(/^api\.github\.com$/,'github.com');let current;
47
+ for(const line of (contents ?? '').split('\n')){const match=/^([^:]+):(.*)$/.exec(line);if(!match)continue;if(!/^\s/.test(line))current=match[1].trim().replace(/^['"]|['"]$/g,'');else if(match[1].trim()==='oauth_token' && current?.toLowerCase()===host.toLowerCase())token=match[2].trim().replace(/^['"]|['"]$/g,'');}
48
+ }
49
+ }
50
+ const policy=specified.policy ?? (env.GITHUB_PROXY_POLICY ? JSON.parse(await readFile(env.GITHUB_PROXY_POLICY,'utf8')):{});
51
+ return {base_url,token:token || undefined,policy:validatePolicy(policy)};
52
+ }
53
+ export function githubAPIPath(path) {
54
+ if(['/api/graphql','/api/services/github/api/graphql'].includes(path))return '/graphql';
55
+ for(const prefix of ['/api/services/github/api/v3','/api/v3','/github'])if(path.startsWith(prefix) && path.length>prefix.length)return path.slice(prefix.length);
56
+ return path;
57
+ }
58
+ export async function relayGithub(request,{config,claims,fetch=globalThis.fetch,maxBodyBytes=4*1024*1024,timeoutMs=120000}) {
59
+ const error=(status,message,blocked=false)=>new Response(JSON.stringify({message}),{status,headers:{'content-type':'application/json',...(blocked?{'x-link-assistant-policy':'blocked'}:{})}});
60
+ if(!config.token)return error(503,'GitHub proxy is not configured');
61
+ const body=request.body ? await boundedBytes(request,maxBodyBytes):new Uint8Array(),url=new URL(request.url),path=githubAPIPath(url.pathname);
62
+ const allowed=claims.github_repos ?? claims.record?.github_repos ?? [],repository=/^\/repos\/([^/]+)\/([^/]+)/.exec(path)?.slice(1).join('/');
63
+ if(allowed.length && !allowed.some(value=>value.toLowerCase()===repository?.toLowerCase()))return error(403,"Blocked by Link.Assistant.Router GitHub policy: outside this token's repositories",true);
64
+ if(githubDecision(config.policy,request.method,path,body)==='deny')return error(403,'Blocked by Link.Assistant.Router GitHub policy',true);
65
+ let upstream=config.base_url+path;if(path==='/graphql' && config.base_url.endsWith('/api/v3'))upstream=config.base_url.slice(0,-7)+'/api/graphql';
66
+ const target=new URL(upstream+url.search);if(!['http:','https:'].includes(target.protocol) || target.username || target.password)throw new ProtocolError('Invalid GitHub upstream URL',500);
67
+ const headers=new Headers({authorization:`Bearer ${config.token}`});for(const name of ['accept','content-type','user-agent','time-zone','x-github-api-version','if-none-match','if-modified-since'])if(request.headers.has(name))headers.set(name,request.headers.get(name));
68
+ const controller=new AbortController(),abort=()=>controller.abort(request.signal.reason);request.signal.addEventListener('abort',abort,{once:true});if(request.signal.aborted)abort();
69
+ const timer=setTimeout(()=>controller.abort(),timeoutMs);timer.unref?.();const cleanup=()=>{clearTimeout(timer);request.signal.removeEventListener('abort',abort);};
70
+ let response;try{response=await fetch(target,{method:request.method,headers,...(['GET','HEAD'].includes(request.method)?{}:{body}),signal:controller.signal,redirect:'manual'});}catch{cleanup();return error(502,'GitHub upstream request failed');}
71
+ const reader=response.body?.getReader();if(!reader){cleanup();return new Response(null,{status:response.status,headers:nativeResponseHeaders(response.headers)});}
72
+ const stream=new ReadableStream({async pull(sink){try{const value=await reader.read();if(value.done){cleanup();sink.close();}else sink.enqueue(value.value);}catch(error){cleanup();sink.error(error);}},async cancel(reason){controller.abort();cleanup();await reader.cancel(reason);}});
73
+ return new Response(stream,{status:response.status,headers:nativeResponseHeaders(response.headers)});
74
+ }
@@ -0,0 +1,36 @@
1
+ import {ProtocolError} from './protocols.mjs';
2
+ const invoke = async (target,method,...args) => {if(typeof target?.[method] !== 'function')throw new ProtocolError('Management service is unavailable',503);return target[method](...args);};
3
+ /** Shared management routing delegates persistence/process work to core services. */
4
+ export async function managementOperation(core,request,path,body) {
5
+ const method=request.method;
6
+ if(path === '/api/management/admin/status' && method === 'GET')return invoke(core.admin,'status');
7
+ if(path === '/api/management/admin/bootstrap' && method === 'POST')return invoke(core.admin,'beginWithTtl',body?.ttl_hours);
8
+ if(path === '/api/management/admin/bootstrap/confirm' && method === 'POST') {
9
+ const token=request.headers.get('authorization')?.match(/^Bearer (.+)$/)?.[1];if(!token)throw new ProtocolError('Confirm must present the candidate token as a Bearer credential',401);
10
+ if(typeof body?.claim_id !== 'string' || !body.claim_id)throw new ProtocolError('claim_id is required');
11
+ await invoke(core.admin,'confirm',body.claim_id,token);return {claimed:true};
12
+ }
13
+ if(path === '/api/management/admin/rotate' && method === 'POST')return invoke(core.admin,'rotate',request.headers.get('authorization')?.replace(/^Bearer /,''),body?.ttl_hours);
14
+ if(path === '/api/management/admin/summary' && method === 'GET')return invoke(core.admin,'summary');
15
+ if(path === '/api/management/auth/status' && method === 'GET')return invoke(core,'credentialStatus');
16
+ if(path === '/api/management/auth/diagnostics' && method === 'GET')return core.diagnostics && core.emergency ? {diagnostics:core.diagnostics.snapshot(),emergency_auth:core.emergency.status()}:invoke(core,'authDiagnostics');
17
+ if(path === '/api/management/health/subscriptions' && method === 'GET')return invoke(core,'subscriptionHealth');
18
+ if(path === '/api/management/emergency-auth' && method === 'GET')return invoke(core.emergency ?? core.emergencyAuth,'status');
19
+ if(path === '/api/management/emergency-auth/disable' && method === 'POST'){const emergency=core.emergency ?? core.emergencyAuth,was_active=await invoke(emergency,'disable');return {disabled:true,was_active,status:await invoke(emergency,'status')};}
20
+ if(path === '/api/management/login' && method === 'POST') {
21
+ const provider=(body?.provider ?? 'claude').trim().toLowerCase();if(!['claude','codex'].includes(provider))throw new ProtocolError('provider must be claude or codex');
22
+ if(body?.mode && !['full','setup-token'].includes(body.mode))throw new ProtocolError('mode must be full or setup-token');
23
+ return invoke(core.login,'begin',{...body,provider});
24
+ }
25
+ const login=/^\/api\/management\/login\/([^/]+)(?:\/(code))?$/.exec(path);
26
+ if(login) {
27
+ const id=decodeURIComponent(login[1]);
28
+ if(login[2] && method === 'POST'){if(typeof body?.code !== 'string' || !body.code.trim())throw new ProtocolError('code must not be empty');return invoke(core.login,'submitCode',id,body.code);}
29
+ if(!login[2] && method === 'GET'){const result=await invoke(core.login,'status',id);if(!result)throw new ProtocolError('Login not found',404);return result;}
30
+ if(!login[2] && method === 'DELETE'){const result=await invoke(core.login,'cancel',id);if(!result)throw new ProtocolError('Login not found',404);return {cancelled:true};}
31
+ }
32
+ const definitions=/^\/api\/management\/routing\/model-definitions\/([^/]+)$/.exec(path);
33
+ if(definitions && method === 'GET')return invoke(core,'modelDefinitions',decodeURIComponent(definitions[1]));
34
+ if(path === '/api/management/server/latest-version' && method === 'GET')return invoke(core,'latestVersion');
35
+ return undefined;
36
+ }