@link-assistant/router 0.0.0-stage → 1.25.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68422 -0
  3. package/index.d.ts +5932 -0
  4. package/index.js +224 -0
  5. package/native.d.ts +106 -0
  6. package/package.json +61 -4
  7. package/portable/policy.mjs +117 -0
  8. package/schemas/accounts-list.v1.json +323 -0
  9. package/schemas/accounts-pause.v1.json +97 -0
  10. package/schemas/accounts-policy.v1.json +214 -0
  11. package/schemas/accounts-resume.v1.json +97 -0
  12. package/schemas/auth-claude.v1.json +97 -0
  13. package/schemas/auth-clear.v1.json +97 -0
  14. package/schemas/auth-codex.v1.json +97 -0
  15. package/schemas/auth-gh.v1.json +97 -0
  16. package/schemas/auth-import.v1.json +167 -0
  17. package/schemas/auth-status.v1.json +387 -0
  18. package/schemas/cli-error.v1.json +97 -0
  19. package/schemas/clients-backup-create.v1.json +97 -0
  20. package/schemas/clients-backup-list.v1.json +234 -0
  21. package/schemas/clients-backup-restore.v1.json +97 -0
  22. package/schemas/clients-backup-verify.v1.json +125 -0
  23. package/schemas/clients-doctor.v1.json +249 -0
  24. package/schemas/clients-install.v1.json +164 -0
  25. package/schemas/clients-list.v1.json +194 -0
  26. package/schemas/clients-reinstall.v1.json +164 -0
  27. package/schemas/clients-remove.v1.json +97 -0
  28. package/schemas/clients-repair.v1.json +109 -0
  29. package/schemas/clients-reset.v1.json +113 -0
  30. package/schemas/clients-setup.v1.json +97 -0
  31. package/schemas/clients-show.v1.json +191 -0
  32. package/schemas/clients-update.v1.json +164 -0
  33. package/schemas/configure.v1.json +97 -0
  34. package/schemas/contracts.v1.json +106 -0
  35. package/schemas/data-backup.v1.json +32 -0
  36. package/schemas/deploy.v1.json +546 -0
  37. package/schemas/doctor.v1.json +324 -0
  38. package/schemas/local-deployment.v1.json +364 -0
  39. package/schemas/logs-anomalies.v1.json +112 -0
  40. package/schemas/logs-show.v1.json +127 -0
  41. package/schemas/logs-summary.v1.json +129 -0
  42. package/schemas/model-catalog.v1.json +117 -0
  43. package/schemas/models-explain.v1.json +325 -0
  44. package/schemas/preservation.v1.json +47 -0
  45. package/schemas/providers-add.v1.json +185 -0
  46. package/schemas/providers-import.v1.json +97 -0
  47. package/schemas/providers-list.v1.json +182 -0
  48. package/schemas/providers-remove.v1.json +97 -0
  49. package/schemas/providers-show.v1.json +179 -0
  50. package/schemas/serve.v1.json +97 -0
  51. package/schemas/server-claim.v1.json +97 -0
  52. package/schemas/server-reap.v1.json +97 -0
  53. package/schemas/server-remove.v1.json +97 -0
  54. package/schemas/server-start.v1.json +97 -0
  55. package/schemas/server-status.v1.json +197 -0
  56. package/schemas/server-stop.v1.json +97 -0
  57. package/schemas/server-use.v1.json +97 -0
  58. package/schemas/staging.v1.json +47 -0
  59. package/schemas/tls-ca.v1.json +97 -0
  60. package/schemas/tls-generate.v1.json +97 -0
  61. package/schemas/tokens-expire.v1.json +97 -0
  62. package/schemas/tokens-import.v1.json +192 -0
  63. package/schemas/tokens-issue.v1.json +94 -0
  64. package/schemas/tokens-list.v1.json +272 -0
  65. package/schemas/tokens-recover-admin.v1.json +116 -0
  66. package/schemas/tokens-revoke.v1.json +97 -0
  67. package/schemas/tokens-rotate.v1.json +94 -0
  68. package/schemas/tokens-show.v1.json +269 -0
  69. package/schemas/tunnel-down.v1.json +97 -0
  70. package/schemas/tunnel-status.v1.json +165 -0
  71. package/schemas/tunnel-up.v1.json +97 -0
  72. package/schemas/usage.v1.json +621 -0
  73. package/schemas/verification.v1.json +254 -0
  74. package/schemas/verify.v1.json +338 -0
  75. package/schemas/version.v1.json +103 -0
  76. package/schemas/with.v1.json +105 -0
  77. package/src/accounts.mjs +233 -0
  78. package/src/activitypub.mjs +23 -0
  79. package/src/admin-assets.mjs +16 -0
  80. package/src/admin.mjs +108 -0
  81. package/src/affinities.mjs +180 -0
  82. package/src/affinity-schema-descriptor.mjs +2 -0
  83. package/src/affinity-schema.mjs +185 -0
  84. package/src/assets/admin/assets/app.js +1 -0
  85. package/src/assets/admin/assets/react.js +9 -0
  86. package/src/assets/admin/assets/rolldown-runtime.js +1 -0
  87. package/src/assets/admin/assets/ui-vendor.js +3 -0
  88. package/src/assets/admin/index.html +16 -0
  89. package/src/auth-service.mjs +149 -0
  90. package/src/claude-process-session.mjs +26 -0
  91. package/src/cli-output.mjs +21 -0
  92. package/src/cli.mjs +84 -0
  93. package/src/client-ca.mjs +8 -0
  94. package/src/client-catalog.mjs +52 -0
  95. package/src/client-codex-catalog.mjs +18 -0
  96. package/src/client-configure.mjs +72 -0
  97. package/src/client-files.mjs +82 -0
  98. package/src/client-global-repair.mjs +19 -0
  99. package/src/client-global-state.mjs +19 -0
  100. package/src/client-global.mjs +43 -0
  101. package/src/client-json.mjs +54 -0
  102. package/src/client-launch-plan.mjs +28 -0
  103. package/src/client-launch.mjs +35 -0
  104. package/src/client-persistent.mjs +66 -0
  105. package/src/client-process-profile.mjs +52 -0
  106. package/src/client-process-settings.mjs +36 -0
  107. package/src/client-process.mjs +44 -0
  108. package/src/client-profile-backup.mjs +29 -0
  109. package/src/client-remote-health.mjs +7 -0
  110. package/src/client-remote.mjs +55 -0
  111. package/src/client-run-credential.mjs +38 -0
  112. package/src/client-setup.mjs +97 -0
  113. package/src/client-status.mjs +102 -0
  114. package/src/client-toml-cst.mjs +71 -0
  115. package/src/client-transaction.mjs +48 -0
  116. package/src/codex-login.mjs +121 -0
  117. package/src/codex-loopback-transport.mjs +34 -0
  118. package/src/codex-loopback.mjs +60 -0
  119. package/src/config.mjs +198 -0
  120. package/src/core.mjs +198 -0
  121. package/src/credential-operations.mjs +119 -0
  122. package/src/doublets.mjs +157 -0
  123. package/src/emergency-auth.mjs +91 -0
  124. package/src/file-lock.mjs +107 -0
  125. package/src/gemini-protocol.mjs +133 -0
  126. package/src/geolocation.mjs +46 -0
  127. package/src/git-proxy.mjs +52 -0
  128. package/src/github-proxy.mjs +74 -0
  129. package/src/http-management.mjs +36 -0
  130. package/src/http-route-contract.mjs +479 -0
  131. package/src/index.mjs +4 -0
  132. package/src/local-router-discovery.mjs +31 -0
  133. package/src/managed-server.mjs +411 -0
  134. package/src/management-access.mjs +76 -0
  135. package/src/native-service.mjs +392 -0
  136. package/src/oauth.mjs +547 -0
  137. package/src/operation-input.mjs +20 -0
  138. package/src/operations.mjs +378 -0
  139. package/src/protocols.mjs +229 -0
  140. package/src/provider-manifest.mjs +46 -0
  141. package/src/provider-provision.mjs +24 -0
  142. package/src/remote-operations.mjs +166 -0
  143. package/src/request-log.mjs +99 -0
  144. package/src/resources.mjs +290 -0
  145. package/src/response-contracts.mjs +147 -0
  146. package/src/responses.mjs +103 -0
  147. package/src/routing.mjs +40 -0
  148. package/src/sensitive-data-sse.mjs +121 -0
  149. package/src/sensitive-data.mjs +254 -0
  150. package/src/server.mjs +552 -0
  151. package/src/storage.mjs +367 -0
  152. package/src/streams.mjs +232 -0
  153. package/src/token-import.mjs +68 -0
  154. package/src/token-reservation.mjs +8 -0
  155. package/src/tokens.mjs +172 -0
  156. package/src/usage.mjs +54 -0
  157. package/src/websocket-relay.mjs +131 -0
  158. package/testing.d.ts +7 -0
  159. package/testing.js +57 -0
@@ -0,0 +1,411 @@
1
+ // Native engine lifecycle. Docker's Rust registry is deliberately never read
2
+ // or overwritten: it identifies a different executable and storage owner.
3
+ import { spawn } from 'node:child_process';
4
+ import { createServer, request as httpRequest } from 'node:http';
5
+ import { randomBytes, randomUUID, createHmac, createHash, timingSafeEqual, X509Certificate } from 'node:crypto';
6
+ import { lstat, mkdir, chmod, open, readdir, rm } from 'node:fs/promises';
7
+ import { resolve, join, dirname, parse, isAbsolute } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { atomicWrite, serialized, withNativeFileLock } from './storage.mjs';
10
+
11
+ const ENGINE = 'link-assistant-router/native-managed/v1', SELF = fileURLToPath(import.meta.url);
12
+ const MAX_STATE = 1024 * 1024, children = new Map(), OWNER_BOOT = randomUUID();
13
+ const fail = message => Object.assign(new Error(message),{code:'managed_server'});
14
+ const unsupported = message => Object.assign(new Error(message),{code:'unsupported'});
15
+ const sleep = ms => new Promise(done=>setTimeout(done,ms));
16
+ const out = (...lines) => ({output:lines});
17
+ const nonce = () => randomBytes(32).toString('hex');
18
+ const digest = (key,text) => createHmac('sha256',key).update(text).digest('hex');
19
+ const fingerprint = value => createHash('sha256').update(value).digest('hex');
20
+ function equal(a,b) { return typeof a === 'string' && typeof b === 'string' && a.length === b.length && timingSafeEqual(Buffer.from(a),Buffer.from(b)); }
21
+ export const supportedManagedOperations = Object.freeze(Object.fromEntries(['start','stop','status','use','claim','reap','remove'].map(op=>[`server.${op}`,{
22
+ status:'partial', limitations:['Native Node daemon and namespaced JSON registry, not Rust Docker container/volume; loopback HTTP only; no systemd, TLS trust import, local discovery, OAuth adoption, or Docker leases; native references use explicit acquisition and dead-owner reaping.'],
23
+ }])));
24
+
25
+ async function info(path) { try { return await lstat(path); } catch (error) { if (error.code === 'ENOENT') return null; throw error; } }
26
+ async function noLinks(path) {
27
+ for (let current = resolve(path);;) {
28
+ if ((await info(current))?.isSymbolicLink()) throw fail('Native managed state contains a symlink');
29
+ if (current === parse(current).root) return; current = dirname(current);
30
+ }
31
+ }
32
+ async function readJSON(path) {
33
+ await noLinks(path); let file;
34
+ try {
35
+ file = await open(path,'r'); const stat = await file.stat();
36
+ if (!stat.isFile() || stat.size > MAX_STATE) throw fail('Native managed state requires a regular file within 1 MiB');
37
+ const bytes = Buffer.alloc(MAX_STATE+1); const {bytesRead} = await file.read(bytes,0,bytes.length,0);
38
+ if (bytesRead > MAX_STATE) throw fail('Native managed state exceeds 1 MiB');
39
+ return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(bytes.subarray(0,bytesRead)));
40
+ } catch (error) { if (error.code === 'ENOENT') return null; throw fail('Invalid or unreadable native managed state'); }
41
+ finally { await file?.close(); }
42
+ }
43
+ function paths(dataDir) {
44
+ if (typeof dataDir !== 'string' || !dataDir) throw fail('Managed operation requires a resolved data directory');
45
+ const root = join(resolve(dataDir),'native-managed');
46
+ return {root,state:join(root,'state.json'),selection:join(root,'server.json'),volume:join(root,'data')};
47
+ }
48
+ function selectionPath(p,env) {
49
+ const nonempty = value=>typeof value === 'string' && value.trim() ? value : undefined;
50
+ const root = nonempty(env.XDG_CONFIG_HOME) ?? (nonempty(env.HOME) ? join(env.HOME,'.config') : nonempty(env.APPDATA));
51
+ if (!root) return p.selection;
52
+ if (!isAbsolute(root)) throw fail('Managed server state directory must be absolute');
53
+ return join(root,'link-assistant-router','server.json');
54
+ }
55
+ function certificatePath(selection,name) {
56
+ if (typeof name !== 'string' || !/^ca-[a-f0-9]{64}\.pem$/.test(name)) throw fail('Persisted Router CA name is invalid');
57
+ return join(dirname(selection),'server-trust',name);
58
+ }
59
+ async function importCertificate(source,selection,cwd) {
60
+ const path = resolve(cwd,source);await noLinks(path);const file = await open(path,'r');let bytes;
61
+ try {
62
+ const stat = await file.stat();if (!stat.isFile() || stat.size > MAX_STATE) throw fail('CA certificate requires a regular PEM file within 1 MiB');
63
+ const buffer = Buffer.alloc(MAX_STATE+1),{bytesRead} = await file.read(buffer,0,buffer.length,0);
64
+ if (bytesRead > MAX_STATE) throw fail('CA certificate exceeds 1 MiB');bytes = buffer.subarray(0,bytesRead);
65
+ } finally {await file.close();}
66
+ const pem = new TextDecoder('utf-8',{fatal:true}).decode(bytes),blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
67
+ if (!blocks?.length) throw fail('CA bundle contains no certificates');for (const block of blocks) new X509Certificate(block);
68
+ const name = `ca-${createHash('sha256').update(bytes).digest('hex')}.pem`,destination = certificatePath(selection,name);
69
+ await noLinks(destination);await mkdir(dirname(destination),{recursive:true,mode:0o700});await chmod(dirname(destination),0o700);await atomicWrite(destination,bytes);await chmod(destination,0o600);return name;
70
+ }
71
+ async function writeJSON(path,value) {
72
+ const text = JSON.stringify(value); if (Buffer.byteLength(text) > MAX_STATE) throw fail('Native managed state exceeds 1 MiB');
73
+ await noLinks(path); await atomicWrite(path,text+'\n'); await chmod(path,0o600);
74
+ }
75
+ async function locked(p,operation) {
76
+ await noLinks(p.root); await mkdir(p.root,{recursive:true,mode:0o700}); await chmod(p.root,0o700);
77
+ return serialized(p.state,()=>withNativeFileLock(p.state,operation,12000));
78
+ }
79
+ function validateState(state) {
80
+ if (!state) return null;
81
+ if (state.schema !== ENGINE || state.engine !== 'node' || !/^[a-f0-9]{64}$/.test(state.control_key) || !/^[a-f0-9]{64}$/.test(state.token_secret) ||
82
+ typeof state.boot_id !== 'string' || !Number.isInteger(state.port) || state.port < 0 || state.port > 65535 ||
83
+ !Number.isInteger(state.control_port) || state.control_port < 0 || state.control_port > 65535 ||
84
+ (state.pid !== null && (!Number.isSafeInteger(state.pid) || state.pid <= 0)) || !Array.isArray(state.references) ||
85
+ state.references.length > 10000 || state.references.some(ref=>!Number.isSafeInteger(ref.pid) || ref.pid <= 0 || typeof ref.owner_boot !== 'string') ||
86
+ typeof state.claimed !== 'boolean' || typeof state.keep_running !== 'boolean' || !Number.isSafeInteger(state.created_at)) throw fail('Native managed registry is invalid or belongs to another engine');
87
+ return state;
88
+ }
89
+ const loadState = async p => validateState(await readJSON(p.state));
90
+ function alive(pid) {
91
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
92
+ try { process.kill(pid,0); return true; } catch (error) { if (error.code === 'ESRCH') return false; if (error.code === 'EPERM') return true; throw error; }
93
+ }
94
+ export function normalizeManagedOrigin(value) {
95
+ let url; try { url = new URL(String(value).trim()); } catch { throw fail('Server URL must be an absolute http:// or https:// origin without credentials, path, query, or fragment'); }
96
+ if (!['http:','https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw fail('Server URL must be an absolute http:// or https:// origin without credentials, path, query, or fragment');
97
+ return url.origin;
98
+ }
99
+ function request(url,{method = 'GET',headers = {},body,limit = 65536,timeout = 1200,phase = 'control'} = {}) {
100
+ return new Promise((done,reject)=> {
101
+ const started = performance.now();
102
+ const call = httpRequest(url,{method,headers,agent:false},response=> {
103
+ const chunks = []; let size = 0;
104
+ response.on('data',bytes=> { size += bytes.length; if (size > limit) call.destroy(fail('Managed control response exceeds its budget')); else chunks.push(bytes); });
105
+ response.on('error',reject); response.on('end',()=>done({status:response.statusCode,text:Buffer.concat(chunks).toString('utf8')}));
106
+ });
107
+ call.setTimeout(timeout,()=>call.destroy(fail(`Managed ${phase} request timed out (budget=${timeout}ms, elapsed=${Math.round(performance.now()-started)}ms)`))); call.on('error',reject); call.end(body);
108
+ });
109
+ }
110
+ async function proof(state,action = 'health',verifyBootstrap = false) {
111
+ const challenge = nonce(), body = JSON.stringify({challenge,boot_id:state.boot_id,verify_bootstrap:verifyBootstrap});
112
+ const result = await request(`http://127.0.0.1:${state.control_port}/${action}`,{method:'POST',headers:{authorization:`Bearer ${state.control_key}`,'content-type':'application/json'},body,phase:verifyBootstrap ? 'bootstrap verification' : `${action} proof`});
113
+ if (result.status !== 200) throw fail('Managed daemon ownership verification failed');
114
+ let report; try { report = JSON.parse(result.text); } catch { throw fail('Managed daemon ownership verification failed'); }
115
+ const {mac,...payload} = report;
116
+ if (!equal(mac,digest(state.control_key,JSON.stringify(payload))) || payload.challenge !== challenge || payload.boot_id !== state.boot_id || payload.pid !== state.pid || payload.role !== ENGINE || payload.healthy !== true) throw fail('Managed daemon process identity does not match the owned registry');
117
+ return payload;
118
+ }
119
+ async function verified(state,verifyBootstrap = false) {
120
+ if (!state.pid || !alive(state.pid)) throw fail('Managed daemon is stopped or its recorded process has exited');
121
+ const result = await proof(state,'health',verifyBootstrap);
122
+ const health = await request(`http://127.0.0.1:${state.port}/health`,{phase:'public health'});
123
+ if (health.status !== 200 || health.text.trim() !== 'ok') throw fail('Managed daemon public listener is not healthy');
124
+ return result;
125
+ }
126
+ function daemonConfig(config,state,p) {
127
+ // Parent-owned live Router data and credentials are never adopted. The
128
+ // managed daemon has its own volume and signing authority.
129
+ return {providers:config.providers ?? [],accounts:config.accounts ?? [],token_secret:state.token_secret,data_dir:p.volume,
130
+ storage_policy:'text',host:'127.0.0.1',port:0,account_strategy:config.account_strategy,account_failover:config.account_failover,
131
+ account_cooldown_seconds:config.account_cooldown_seconds,session_affinity_ttl_seconds:config.session_affinity_ttl_seconds};
132
+ }
133
+ async function start(p,state,config,keepRunning) {
134
+ if (state?.pid) {
135
+ if (alive(state.pid)) {
136
+ await verified(state); if (keepRunning) {state.keep_running = true; await writeJSON(p.state,state);} return state;
137
+ }
138
+ state.pid = null; state.control_port = 0;
139
+ }
140
+ state ??= {schema:ENGINE,engine:'node',token_secret:nonce(),control_key:nonce(),boot_id:randomUUID(),created_at:Math.floor(Date.now()/1000),pid:null,port:0,control_port:0,references:[],keep_running:false,claimed:false,bootstrap_token:null};
141
+ state.boot_id = randomUUID(); state.control_key = nonce(); state.keep_running ||= keepRunning;
142
+ await noLinks(p.volume);
143
+ await validateTree(p.volume);
144
+ const executable = process.versions.bun ? 'node' : process.execPath;
145
+ const child = spawn(executable,[SELF,'--daemon'],{detached:true,stdio:['ignore','ignore','ignore','ipc'],env:{PATH:process.env.PATH ?? '',SystemRoot:process.env.SystemRoot ?? ''}});
146
+ let committed = false;
147
+ try {
148
+ const ready = await new Promise((done,reject)=> {
149
+ const timer = setTimeout(()=>finish(reject)(fail('Managed daemon did not become ready within 10 seconds')),10000);
150
+ const finish = fn => value => {clearTimeout(timer); child.off('error',onError); child.off('exit',onExit); child.off('message',onMessage); fn(value);};
151
+ const onError = finish(reject), onExit = finish(()=>reject(fail('Managed daemon exited before readiness')));
152
+ const onMessage = finish(message=>message?.ready ? done(message) : reject(fail('Managed daemon failed to start')));
153
+ child.once('error',onError); child.once('exit',onExit); child.once('message',onMessage);
154
+ child.send({state,config:daemonConfig(config,state,p)});
155
+ });
156
+ if (ready.pid !== child.pid || ready.boot_id !== state.boot_id || !Number.isInteger(ready.port) || !Number.isInteger(ready.control_port)) throw fail('Managed readiness identity mismatch');
157
+ Object.assign(state,{pid:ready.pid,port:ready.port,control_port:ready.control_port,bootstrap_token:ready.bootstrap_token});
158
+ await verified(state); await writeJSON(p.state,state);
159
+ await new Promise((done,reject)=> {
160
+ const timer = setTimeout(()=>finish(reject)(fail('Managed daemon did not acknowledge commit within 10 seconds')),10000);
161
+ const finish = fn => value => {clearTimeout(timer); child.off('error',onError); child.off('exit',onExit); child.off('message',onMessage); fn(value);};
162
+ const onError = finish(reject), onExit = finish(()=>reject(fail('Managed daemon exited before commit')));
163
+ const onMessage = finish(message=>message?.committed && message.pid === child.pid && message.boot_id === state.boot_id ? done() : reject(fail('Managed commit identity mismatch')));
164
+ child.once('error',onError); child.once('exit',onExit); child.once('message',onMessage);
165
+ child.send({commit:true,boot_id:state.boot_id},error=> {if (error) onError(error);});
166
+ });
167
+ committed = true; children.set(child.pid,child);
168
+ child.once('exit',()=>children.delete(child.pid)); child.disconnect(); child.unref();
169
+ return state;
170
+ } finally {
171
+ if (!committed) {
172
+ // A failed readiness result is complete only after this owned child has
173
+ // exited. Otherwise test runners can kill a still-closing daemon and its
174
+ // delayed rejection can spill into the next fixture.
175
+ let timer;
176
+ const exited = child.exitCode !== null || child.signalCode !== null ? Promise.resolve() : new Promise(done=>child.once('exit',done));
177
+ if (child.connected) {
178
+ child.send({abort:true},()=>{});
179
+ child.disconnect();
180
+ }
181
+ child.unref();
182
+ try {await Promise.race([exited,new Promise((_,reject)=> {timer = setTimeout(()=>reject(fail('Aborted managed daemon did not exit within 4 seconds')),4000);})]);}
183
+ finally {clearTimeout(timer);}
184
+ }
185
+ }
186
+ }
187
+ async function stop(p,state) {
188
+ if (!state) throw fail('Managed router is absent; run server.start first');
189
+ if (state.pid && alive(state.pid)) {
190
+ await verified(state); await proof(state,'shutdown');
191
+ const deadline = Date.now()+6000;
192
+ while (alive(state.pid)) { if (Date.now() >= deadline) throw fail('Owned managed daemon has not exited; registry was retained'); await sleep(25); }
193
+ }
194
+ state.pid = null; state.control_port = 0; state.keep_running = false; state.references = [];
195
+ await writeJSON(p.state,state); return state;
196
+ }
197
+ async function validateTree(path) {
198
+ let files = 0;
199
+ const visit = async (path,depth) => {
200
+ if (++files > 10000 || depth > 32) throw unsupported('Native managed volume exceeds its 10000-entry / 32-level safety budget');
201
+ await noLinks(path); const stat = await info(path); if (!stat) return;
202
+ if (stat.isDirectory()) for (const name of await readdir(path)) await visit(join(path,name),depth+1);
203
+ else if (!stat.isFile()) throw fail('Managed volume contains a special file');
204
+ };
205
+ await visit(path,0);
206
+ }
207
+ async function selection(p,env,state) {
208
+ const configured = env.LINK_ASSISTANT_ROUTER_URL ?? env.ROUTER_URL;
209
+ if (configured !== undefined) return {source:'environment',url:normalizeManagedOrigin(configured),token_configured:!!(env.LINK_ASSISTANT_ROUTER_TOKEN ?? env.LINK_ASSISTANT_TOKEN)};
210
+ const saved = await readJSON(selectionPath(p,env));
211
+ if (saved) return {source:'persisted',url:normalizeManagedOrigin(saved.server),token_configured:typeof saved.token === 'string'};
212
+ return {source:'managed',url:state?.port ? `http://127.0.0.1:${state.port}` : null,token_configured:false};
213
+ }
214
+ // Operation dispatch uses this before local state changes. Selecting a server
215
+ // is an operator's target choice; absent remote delegation, it cannot silently
216
+ // become a local mutation. The explicit --local target may override it.
217
+ export async function selectedManagedServer({core,config = {},env = {}} = {}) {
218
+ config = core?.config ?? config;
219
+ const configured = env.LINK_ASSISTANT_ROUTER_URL ?? env.ROUTER_URL;
220
+ if (configured !== undefined) return normalizeManagedOrigin(configured);
221
+ const p = paths(config.data_dir ?? config.dataDir), saved = await readJSON(selectionPath(p,env));
222
+ return saved ? normalizeManagedOrigin(saved.server) : null;
223
+ }
224
+
225
+ /** Resolve a state command's selected deployment without touching local stores. */
226
+ export async function selectedManagedTarget({name,options = {},config = {},env = {},cwd = process.cwd()} = {}) {
227
+ if (options.local === true) return null;
228
+ if (options.managed === true) {
229
+ const error = fail(`--managed starts a disposable router for with/configure; ${name} cannot use one. Pass --local or --server instead.`);
230
+ error.exitCode = 2; throw error;
231
+ }
232
+ const p = paths(resolve(cwd,options.data_dir ?? config.data_dir ?? config.dataDir ?? env.DATA_DIR ?? '.router'));
233
+ let saved;
234
+ try {
235
+ saved = await readJSON(selectionPath(p,env));
236
+ if (saved) {
237
+ if (typeof saved !== 'object' || Array.isArray(saved)) throw fail('Invalid persisted server selection');
238
+ normalizeManagedOrigin(saved.server);
239
+ if (saved.management_server !== undefined) normalizeManagedOrigin(saved.management_server);
240
+ }
241
+ }
242
+ catch (error) { if (options.server === undefined) throw error; saved = undefined; }
243
+ const environmentServer = env.LINK_ASSISTANT_ROUTER_URL ?? env.ROUTER_URL;
244
+ const supplied = options.server ?? environmentServer ?? saved?.server;
245
+ if (supplied === undefined) {
246
+ if (options.management_server !== undefined) throw fail('A management server requires an inference server selection');
247
+ return null;
248
+ }
249
+ const server = normalizeManagedOrigin(supplied);
250
+ const source = options.server !== undefined ? 'flag' : environmentServer !== undefined ? 'environment' : 'persisted configuration';
251
+ const management = options.management_server ?? (options.server !== undefined ? server
252
+ : environmentServer !== undefined ? env.LINK_ASSISTANT_ROUTER_MANAGEMENT_URL ?? env.ROUTER_MANAGEMENT_URL ?? server
253
+ : saved.management_server ?? server);
254
+ const managementServer = normalizeManagedOrigin(management);
255
+ const same = saved && normalizeManagedOrigin(saved.server) === server;
256
+ const token = env.LINK_ASSISTANT_ROUTER_TOKEN ?? env.LINK_ASSISTANT_TOKEN ?? (same ? saved.token : undefined);
257
+ if (token !== undefined && (typeof token !== 'string' || !token.trim() || /[\r\n]/.test(token))) throw fail('Selected router credential is invalid');
258
+ const savedManagement = saved ? normalizeManagedOrigin(saved.management_server ?? saved.server) : null;
259
+ return {server,managementServer,source,...(token ? {token} : {}),
260
+ ...(same && saved.ca_cert ? {caCert:certificatePath(selectionPath(p,env),saved.ca_cert)} : {}),
261
+ ...(savedManagement === managementServer && (saved.management_ca_cert || same && saved.ca_cert)
262
+ ? {managementCaCert:certificatePath(selectionPath(p,env),saved.management_ca_cert ?? saved.ca_cert)} : {})};
263
+ }
264
+ async function status(p,state,env) {
265
+ let lifecycle = state ? 'stopped' : 'absent', detail = null;
266
+ if (state?.pid && alive(state.pid)) {
267
+ try { await verified(state); lifecycle = 'running'; } catch { lifecycle = 'unverified'; detail = 'Recorded process failed identity or health verification; no process action is authorized'; }
268
+ }
269
+ const selected = await selection(p,env,state);
270
+ return {selection:selected,managed:{present:!!state,state:lifecycle,detail,container:'native-node-daemon',volume:p.volume,url:state?.port ? `http://127.0.0.1:${state.port}` : null,
271
+ administrator_claimed:state?.claimed ?? false,users:state?.references.filter(ref=>alive(ref.pid)).length ?? 0,keep_running:state?.keep_running ?? false},
272
+ output:[`effective server: ${selected.source}${selected.url ? `: ${selected.url}` : ''}`,`managed server: ${lifecycle}; engine=node` ]};
273
+ }
274
+ function validateOptions(name,options,config) {
275
+ const allowed = new Set(['data_dir',...(name === 'server.use' ? ['server','management_server','token','token_stdin','clear','run_max_requests','ca_cert','management_ca_cert'] : name === 'server.reap' ? ['pid'] : name === 'server.remove' ? ['yes'] : [])]);
276
+ for (const [key,value] of Object.entries(options)) if (value !== undefined && value !== false && !allowed.has(key)) throw unsupported(`Native ${name} does not support ${key}`);
277
+ if (Object.entries(config).some(([key,value])=>value && /^(tls|https|listeners|systemd)/i.test(key))) throw unsupported('Native managed daemons support one loopback HTTP listener only');
278
+ if (name === 'server.remove' && options.yes !== true) throw fail('Removing the native managed volume destroys its saved credentials and requires --yes');
279
+ if (name === 'server.reap' && (!Number.isSafeInteger(Number(options.pid)) || Number(options.pid) <= 0)) throw fail('server.reap requires a positive PID');
280
+ }
281
+ export async function executeManagedOperation({name,options = {},invocation = {},core,config = {},env = {}}) {
282
+ if (!supportedManagedOperations[name]) throw unsupported(`Native ${name} is not implemented`);
283
+ config = core?.config ?? config; validateOptions(name,options,config);
284
+ const p = paths(options.data_dir ?? config.data_dir ?? config.dataDir);
285
+ if (name === 'server.use') {
286
+ p.selection = selectionPath(p,env);
287
+ if (options.clear && Object.entries(options).some(([key,value])=>!['clear','data_dir'].includes(key) && value !== undefined && value !== false)) throw fail('--clear cannot be combined with a server, token, or run budget');
288
+ let selected;
289
+ if (!options.clear) {
290
+ if (!options.server) throw fail('Provide a server URL or use --clear');
291
+ let token = options.token;
292
+ if (options.token_stdin) {if (token !== undefined) throw fail('token and token_stdin conflict'); token = String(invocation.stdin ?? '').split(/\r?\n/)[0].trim(); if (!token) throw fail('Standard input did not contain a token');}
293
+ if (token !== undefined && (typeof token !== 'string' || !token)) throw fail('Server token must be a nonempty string');
294
+ if (options.run_max_requests !== undefined && (!Number.isSafeInteger(Number(options.run_max_requests)) || Number(options.run_max_requests) <= 0)) throw fail('Run budget must be a positive integer');
295
+ const server = normalizeManagedOrigin(options.server), management = options.management_server === undefined ? undefined : normalizeManagedOrigin(options.management_server);
296
+ selected = {server,...(management && management !== server ? {management_server:management} : {}),...(token ? {token} : {}),...(options.run_max_requests !== undefined ? {run_max_requests:Number(options.run_max_requests)} : {})};
297
+ }
298
+ return locked(p,async()=> {
299
+ if (!options.clear) {
300
+ const previous = await readJSON(p.selection).catch(()=>null),same = previous?.server && normalizeManagedOrigin(previous.server) === selected.server;
301
+ const sameManagement = previous?.server && normalizeManagedOrigin(previous.management_server ?? previous.server) === (selected.management_server ?? selected.server);
302
+ selected.ca_cert = options.ca_cert ? await importCertificate(options.ca_cert,p.selection,invocation.cwd ?? process.cwd()) : same ? previous.ca_cert : undefined;
303
+ selected.management_ca_cert = options.management_ca_cert ? await importCertificate(options.management_ca_cert,p.selection,invocation.cwd ?? process.cwd()) : sameManagement ? previous.management_ca_cert : undefined;
304
+ if (!selected.management_server && !selected.management_ca_cert) selected.management_ca_cert = selected.ca_cert;
305
+ }
306
+ if (options.clear) {await noLinks(p.selection); await rm(p.selection,{force:true}); return out(`cleared persisted server selection at ${p.selection}`);} await writeJSON(p.selection,selected); return out(`saved server selection in ${p.selection} (token ${selected.token ? 'set' : 'unset'})`);});
307
+ }
308
+ return locked(p,async()=> {
309
+ let state = await loadState(p);
310
+ if (name === 'server.status') return status(p,state,env);
311
+ if (name === 'server.start') {state = await start(p,state,config,true); return out(`managed native router started at http://127.0.0.1:${state.port}`);}
312
+ if (name === 'server.stop') {await stop(p,state); return out('managed native router stopped; native credential volume was preserved');}
313
+ if (name === 'server.claim') {
314
+ if (!state) throw fail('Managed router is absent; run server.start first');
315
+ if (state.claimed) throw fail('Managed router administrator is already claimed; its credential is not printed twice');
316
+ const identity = await verified(state,true); if (!identity.bootstrap_valid || typeof state.bootstrap_token !== 'string' || identity.bootstrap_fingerprint !== fingerprint(state.bootstrap_token)) throw fail('Managed bootstrap administrator is unavailable, mismatched, or expired');
317
+ state.claimed = true; await writeJSON(p.state,state); return out(state.bootstrap_token);
318
+ }
319
+ if (name === 'server.reap') {
320
+ const pid = Number(options.pid); if (!state) return out();
321
+ if (alive(pid)) throw fail('Refusing to reap a live or reused owner PID');
322
+ state.references = state.references.filter(ref=>ref.pid !== pid);
323
+ if (!state.references.length && !state.keep_running) await stop(p,state); else await writeJSON(p.state,state);
324
+ return out();
325
+ }
326
+ if (!state) throw fail('Managed router is absent; no owned state was removed');
327
+ await stop(p,state); await validateTree(p.volume); await rm(p.volume,{recursive:true,force:true}); await noLinks(p.state); await rm(p.state,{force:true});
328
+ return out('removed the native managed daemon and its credential volume');
329
+ });
330
+ }
331
+
332
+ // Native wrapper leases are explicit until the `with` launcher is integrated.
333
+ export async function acquireManagedReference({core,config = {}}) {
334
+ config = core?.config ?? config; validateOptions('server.start',{},config); const p = paths(config.data_dir ?? config.dataDir);
335
+ return locked(p,async()=> {const state = await start(p,await loadState(p),config,false); if (!state.references.some(ref=>ref.pid === process.pid && ref.owner_boot === OWNER_BOOT)) state.references.push({pid:process.pid,owner_boot:OWNER_BOOT}); await writeJSON(p.state,state); return {pid:process.pid,url:`http://127.0.0.1:${state.port}`};});
336
+ }
337
+
338
+ async function daemon() {
339
+ let runtime, control, committed = false, started = false, ready = false, bootId;
340
+ const exit = async()=> {const timer = setTimeout(()=>process.exit(0),3000); timer.unref(); await runtime?.close().catch(()=>{}); control?.close(); process.exit(0);};
341
+ const deadline = setTimeout(()=>exit(),10000);
342
+ process.on('disconnect',()=> {if (!committed) exit();}); process.on('SIGTERM',exit); process.on('SIGINT',exit);
343
+ process.on('message',async message=> {
344
+ if (message?.commit) {
345
+ if (!ready || message.boot_id !== bootId) {await exit(); return;}
346
+ committed = true; clearTimeout(deadline);
347
+ process.send?.({committed:true,pid:process.pid,boot_id:bootId}); return;
348
+ }
349
+ if (message?.abort) {await exit(); return;}
350
+ if (started || !message?.config || !message?.state) return; started = true;
351
+ try {
352
+ const state = validateState(message.state), core = await (await import('./core.mjs')).createRouterCore({config:message.config,env:{}});
353
+ bootId = state.boot_id;
354
+ let token = state.bootstrap_token;
355
+ if (!token) token = (await core.tokens.issue({scope:'admin',ttl_hours:87600,label:'native-managed-bootstrap'})).token;
356
+ runtime = (await import('./server.mjs')).createNativeRouter({core}); await runtime.listen({host:'127.0.0.1',port:0});
357
+ control = createServer(async(req,res)=> {
358
+ try {
359
+ if (req.method !== 'POST' || !['/health','/shutdown'].includes(req.url) || !equal(req.headers.authorization,`Bearer ${state.control_key}`)) {res.writeHead(403); res.end(); return;}
360
+ const chunks = []; let length = 0;
361
+ for await (const bytes of req) {length += bytes.length; if (length > 4096) throw fail('Control body too large'); chunks.push(bytes);}
362
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
363
+ if (!/^[a-f0-9]{64}$/.test(body.challenge) || body.boot_id !== state.boot_id) throw fail('Invalid control challenge');
364
+ // Identity and listener health must remain available while an unrelated
365
+ // token transaction holds the store lock. Claim still checks the live
366
+ // administrator token before releasing it to the parent.
367
+ let bootstrapValid = false;
368
+ if (body.verify_bootstrap === true) try {await core.tokens.validate(token,{admin:true}); bootstrapValid = true;} catch {}
369
+ const payload = {challenge:body.challenge,boot_id:state.boot_id,pid:process.pid,role:ENGINE,healthy:!!runtime.address,bootstrap_valid:bootstrapValid,bootstrap_fingerprint:fingerprint(token)};
370
+ res.writeHead(200,{'content-type':'application/json'}); res.end(JSON.stringify({...payload,mac:digest(state.control_key,JSON.stringify(payload))}));
371
+ if (req.url === '/shutdown') setImmediate(exit);
372
+ } catch {if (!res.headersSent) res.writeHead(400); res.end();}
373
+ });
374
+ control.requestTimeout = 2000; control.headersTimeout = 2000;
375
+ await new Promise((done,reject)=> {control.once('error',reject); control.listen(0,'127.0.0.1',done);});
376
+ // Startup and the parent's verified registry commit each get a bounded
377
+ // phase. A late readiness result cannot inherit an almost-expired lease.
378
+ ready = true; deadline.refresh();
379
+ process.send?.({ready:true,pid:process.pid,boot_id:state.boot_id,port:runtime.address.port,control_port:control.address().port,bootstrap_token:token});
380
+ } catch {process.send?.({ready:false}); await exit();}
381
+ });
382
+ }
383
+ if (process.argv[1] === SELF && process.argv[2] === '--daemon') daemon();
384
+
385
+ // Private lifecycle helpers below use the existing authenticated daemon proof.
386
+ export async function withNativeManagedConfigureTarget(context,operation){
387
+ const {config={},options={},env={},cwd=process.cwd(),create=false}=context,p=paths(resolve(cwd,options.data_dir??config.data_dir??config.dataDir??env.DATA_DIR??'.router'));
388
+ const initial=await loadState(p);if(!initial&&!create)return null;
389
+ const lease=nonce();let selected;
390
+ await locked(p,async()=>{
391
+ let state=await loadState(p);if(!state&&!create)return;
392
+ const wasRunning=!!state?.pid&&alive(state.pid),keepRunning=state?.keep_running===true;
393
+ if(options.local&&!wasRunning)throw fail('--local requires an already-running owned Router');
394
+ if(!wasRunning){validateOptions('server.start',{},config);state=await start(p,state,config,false);}
395
+ try{
396
+ const identity=await verified(state,!state.claimed);let token=env.LINK_ASSISTANT_ROUTER_TOKEN??env.LINK_ASSISTANT_TOKEN;
397
+ if(token===undefined&&!state.claimed){if(!identity.bootstrap_valid||typeof state.bootstrap_token!=='string'||identity.bootstrap_fingerprint!==fingerprint(state.bootstrap_token))throw fail('Managed bootstrap administrator is unavailable or expired');token=state.bootstrap_token;}
398
+ if(token!==undefined&&(typeof token!=='string'||!token.trim()||/[\r\n]/u.test(token)))throw fail('Selected Router credential is invalid');
399
+ if(state.references.length>=10000)throw fail('Managed reference budget exhausted');state.references.push({pid:process.pid,owner_boot:OWNER_BOOT,lease_id:lease});validateState(state);await writeJSON(p.state,state);selected={boot:state.boot_id,started:!wasRunning,keepRunning,server:'http://127.0.0.1:'+state.port,token};
400
+ }catch(error){state.references=state.references.filter((reference)=>reference.lease_id!==lease);if(!wasRunning&&!keepRunning&&!state.references.length)await stop(p,state);throw error;}
401
+ });
402
+ if(!selected)return null;let succeeded=false,retained=false;
403
+ try{const value=await operation({server:selected.server,managementServer:selected.server,source:'managed native Node server',retainManagedServer:()=>{retained=true;},...(selected.token?{token:selected.token}:{})});succeeded=true;return value;}
404
+ finally{await locked(p,async()=>{
405
+ const state=await loadState(p);if(!state||state.boot_id!==selected.boot)throw fail('Managed Router changed while configure held its reference; replacement state was preserved');
406
+ if(!state.references.some((reference)=>reference.pid===process.pid&&reference.owner_boot===OWNER_BOOT&&reference.lease_id===lease))throw fail('Managed configure reference changed; state was preserved');
407
+ state.references=state.references.filter((reference)=>!(reference.pid===process.pid&&reference.owner_boot===OWNER_BOOT&&reference.lease_id===lease));
408
+ if((succeeded||retained)&&context.retainOnSuccess!==false){await verified(state);state.keep_running=true;await writeJSON(p.state,state);}
409
+ else if(selected.started&&!selected.keepRunning&&!state.keep_running&&!state.references.length)await stop(p,state);else await writeJSON(p.state,state);
410
+ });}
411
+ }
@@ -0,0 +1,76 @@
1
+ import { isIP } from 'node:net';
2
+ import { join } from 'node:path';
3
+ import { unlink } from 'node:fs/promises';
4
+ import { performance } from 'node:perf_hooks';
5
+ import { atomicWrite,encodeLino,serialized } from './storage.mjs';
6
+ import { RouterError } from './tokens.mjs';
7
+
8
+ export function normalizeManagementPeer(peer) {
9
+ if (typeof peer !== 'string' || !isIP(peer)) throw new RouterError('permission_error','Management requires a valid socket peer',403);
10
+ if (isIP(peer) === 4) return peer;
11
+ const normalized = new URL(`http://[${peer}]/`).hostname.slice(1,-1);
12
+ const mapped = /^::ffff:([0-9a-f]+):([0-9a-f]+)$/i.exec(normalized);
13
+ if (!mapped) return normalized;
14
+ const high = Number.parseInt(mapped[1],16), low = Number.parseInt(mapped[2],16);
15
+ return `${high>>>8}.${high&255}.${low>>>8}.${low&255}`;
16
+ }
17
+ const loopback = peer => peer === '::1' || /^127\./.test(peer);
18
+ /** Management bans use monotonic time; disk contains diagnostics only. */
19
+ export class ManagementAccess {
20
+ constructor({config = {},dataDir,persistent = true,clock = () => Math.floor(Date.now()/1000),monotonic = () => performance.now()/1000,maxClients = 4096} = {}) {
21
+ this.policy = {allow_remote:false,lockout_failures:5,lockout_secs:1800,exempt_loopback:true,...config};
22
+ for (const key of ['lockout_failures','lockout_secs']) if (!Number.isSafeInteger(this.policy[key]) || this.policy[key] < 0) throw new RouterError('invalid_config',`management ${key} must be nonnegative`);
23
+ this.path = dataDir ? join(dataDir,'management-lockouts.lenv') : null;
24
+ this.persistent = persistent; this.clock = clock; this.monotonic = monotonic; this.maxClients = maxClients;
25
+ this.attempts = new Map(); this.lastPersistenceError = null;
26
+ }
27
+ config() { return {...this.policy}; }
28
+ exempt(peer) { return !this.policy.lockout_failures || !this.policy.lockout_secs || this.policy.exempt_loopback && loopback(peer); }
29
+ remaining(entry,now = this.monotonic()) {
30
+ if (entry?.banned_at == null) return null;
31
+ const seconds = this.policy.lockout_secs-Math.max(0,now-entry.banned_at);
32
+ return seconds > 0 ? Math.ceil(seconds) : null;
33
+ }
34
+ expired(entry,now) { return entry.banned_at == null ? Math.max(0,now-entry.last_failure) >= this.policy.lockout_secs : this.remaining(entry,now) == null; }
35
+ check(peer) {
36
+ peer = normalizeManagementPeer(peer); if (this.exempt(peer)) return null;
37
+ const now = this.monotonic(), entry = this.attempts.get(peer);
38
+ if (entry && this.expired(entry,now)) {
39
+ this.attempts.delete(peer); if (entry.banned_at != null) this.save().catch(error => {this.lastPersistenceError = error.code ?? 'storage_failed';});
40
+ }
41
+ const existing = this.attempts.get(peer);
42
+ if (existing) return this.remaining(existing,now);
43
+ if (this.attempts.size >= this.maxClients) {
44
+ for (const [ip,held] of this.attempts) if (this.expired(held,now)) this.attempts.delete(ip);
45
+ this.save().catch(error => {this.lastPersistenceError = error.code ?? 'storage_failed';});
46
+ if (this.attempts.size >= this.maxClients) return 1;
47
+ }
48
+ return null;
49
+ }
50
+ async failure(peer) {
51
+ peer = normalizeManagementPeer(peer); if (this.exempt(peer)) return null;
52
+ const now = this.monotonic();
53
+ if (!this.attempts.has(peer) && this.attempts.size >= this.maxClients) return null;
54
+ const entry = this.attempts.get(peer) ?? {failures:0,last_failure:now,banned_at:null,expires_at:0};
55
+ if (this.expired(entry,now)) {entry.failures = 0; entry.banned_at = null;}
56
+ if (entry.banned_at != null) return null;
57
+ entry.failures = Math.min(0xffffffff,entry.failures+1); entry.last_failure = now; this.attempts.set(peer,entry);
58
+ if (entry.failures < this.policy.lockout_failures) return null;
59
+ entry.banned_at = now; entry.expires_at = this.clock()+this.policy.lockout_secs;
60
+ await this.save().catch(error => {this.lastPersistenceError = error.code ?? 'storage_failed';});
61
+ return {client_ip:peer,expires_at:entry.expires_at};
62
+ }
63
+ success(peer) { peer = normalizeManagementPeer(peer); if (this.attempts.get(peer)?.banned_at == null) this.attempts.delete(peer); }
64
+ activeBans() {
65
+ const now = this.monotonic(); for (const [peer,entry] of this.attempts) if (this.expired(entry,now)) this.attempts.delete(peer);
66
+ return [...this.attempts].filter(([,entry]) => entry.banned_at != null).map(([peer,entry]) => ({client_ip:peer,expires_at:entry.expires_at})).sort((left,right) => left.client_ip.localeCompare(right.client_ip));
67
+ }
68
+ async save() {
69
+ if (!this.persistent || !this.path) return;
70
+ return serialized(this.path,async () => {
71
+ const bans = [...this.attempts].filter(([,entry]) => entry.banned_at != null).map(([peer,entry]) => ({client_ip:peer,expires_at:entry.expires_at}));
72
+ if (bans.length) await atomicWrite(this.path,encodeLino(bans));
73
+ else try { await unlink(this.path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
74
+ });
75
+ }
76
+ }