@quolu/lattice 0.52.2 → 0.52.4

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 (134) hide show
  1. package/package.json +1 -1
  2. package/src/artifact-contracts-v2.mjs +325 -325
  3. package/src/artifact-contracts.mjs +895 -895
  4. package/src/boundary-compiler.mjs +712 -712
  5. package/src/boundary-observation-compiler-v2.mjs +344 -344
  6. package/src/bounded-seam.mjs +230 -230
  7. package/src/bridge-address.mjs +107 -107
  8. package/src/bridge-cli.mjs +297 -297
  9. package/src/bridge-config.mjs +346 -346
  10. package/src/bridge-daemon.mjs +378 -378
  11. package/src/bridge-hub-protocol.mjs +198 -0
  12. package/src/bridge-launch-agent.mjs +323 -323
  13. package/src/bridge-registrar.mjs +102 -102
  14. package/src/bridge-server.mjs +376 -376
  15. package/src/cli-help.mjs +308 -308
  16. package/src/cli-stdio.mjs +40 -40
  17. package/src/control-compiler.mjs +532 -532
  18. package/src/dag-chain.mjs +261 -261
  19. package/src/factory-diagnostics.mjs +188 -188
  20. package/src/git-process.mjs +72 -0
  21. package/src/hash-chain.mjs +76 -76
  22. package/src/hooks-cli.mjs +1057 -1057
  23. package/src/isolation-runner.mjs +409 -409
  24. package/src/node-version-guard.mjs +44 -44
  25. package/src/project-cli.mjs +699 -697
  26. package/src/project-identity.mjs +130 -130
  27. package/src/rc1-black-box-oracle.mjs +906 -906
  28. package/src/rc1-comparison.mjs +154 -154
  29. package/src/rc1-evidence-bundle.mjs +456 -456
  30. package/src/rc1-v4-campaign.mjs +708 -708
  31. package/src/rc1-v4-transform.mjs +467 -467
  32. package/src/rc1-v5-artifact-set.mjs +855 -855
  33. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  34. package/src/rc1-v5-campaign.mjs +797 -797
  35. package/src/rc1-v5-transform.mjs +421 -421
  36. package/src/rc1-v6-artifact-set.mjs +807 -807
  37. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  38. package/src/rc1-v6-campaign.mjs +623 -623
  39. package/src/rc1-v6-causal-binding.mjs +473 -473
  40. package/src/rc1-v6-measurement.mjs +313 -313
  41. package/src/rc2-artifact-set.mjs +1584 -1584
  42. package/src/rc2-campaign.mjs +1506 -1506
  43. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  44. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  45. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  46. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  47. package/src/rc3-actual-dogfood.mjs +652 -652
  48. package/src/rc3-dogfood-scaffold.mjs +315 -315
  49. package/src/rc3-scripted-campaign.mjs +1383 -1383
  50. package/src/rc4-stage1-dogfood.mjs +673 -673
  51. package/src/runtime-adapter-registry.mjs +524 -524
  52. package/src/runtime-cli.mjs +4588 -4588
  53. package/src/runtime-contracts.mjs +824 -824
  54. package/src/runtime-control-store.mjs +604 -604
  55. package/src/runtime-controller-protocol.mjs +587 -587
  56. package/src/runtime-decision-verifier.mjs +701 -701
  57. package/src/runtime-diff-observer.mjs +361 -361
  58. package/src/runtime-direct-os-observer.mjs +301 -301
  59. package/src/runtime-driver-state.mjs +166 -166
  60. package/src/runtime-engine.mjs +779 -779
  61. package/src/runtime-errors.mjs +356 -356
  62. package/src/runtime-event-store.mjs +189 -189
  63. package/src/runtime-front-end.mjs +925 -925
  64. package/src/runtime-gate-store.mjs +481 -481
  65. package/src/runtime-hold-recompile.mjs +916 -916
  66. package/src/runtime-io-sentinel.mjs +391 -391
  67. package/src/runtime-lifecycle-lock.mjs +294 -294
  68. package/src/runtime-managed-supervisor.mjs +1490 -1490
  69. package/src/runtime-multi-epoch-store.mjs +838 -838
  70. package/src/runtime-projection.mjs +269 -269
  71. package/src/runtime-pull-intake.mjs +1192 -1192
  72. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  73. package/src/runtime-scripted-executor.mjs +163 -163
  74. package/src/runtime-scripted-worktree.mjs +104 -104
  75. package/src/runtime-seam-resolve.mjs +428 -428
  76. package/src/runtime-seam-treatment.mjs +173 -173
  77. package/src/runtime-socket-owner.mjs +125 -125
  78. package/src/runtime-work-order-contracts.mjs +91 -91
  79. package/src/runtime-work-order-controller.mjs +1171 -1171
  80. package/src/runtime-worktree-executor.mjs +199 -199
  81. package/src/schedulability-compiler-v2.mjs +303 -303
  82. package/src/schedulability-verifier-v2.mjs +317 -317
  83. package/src/seam-apply.mjs +549 -549
  84. package/src/seam-commit-shared.mjs +22 -22
  85. package/src/seam-commit-transform.mjs +81 -81
  86. package/src/seam-commit.mjs +18 -18
  87. package/src/seam-cost.mjs +322 -322
  88. package/src/seam-derivation.mjs +188 -188
  89. package/src/seam-gate.mjs +146 -146
  90. package/src/seam-proposal-contracts.mjs +446 -446
  91. package/src/seam-proposal-queries.mjs +521 -521
  92. package/src/seam-proposal.mjs +2011 -2011
  93. package/src/seam-ref.mjs +33 -33
  94. package/src/seam-rewrite.mjs +286 -286
  95. package/src/seam-transform.mjs +554 -554
  96. package/src/seam-verification.mjs +260 -260
  97. package/src/sensor-adapter.mjs +432 -432
  98. package/src/sensor-cli.mjs +139 -139
  99. package/src/sensor-diff.mjs +661 -661
  100. package/src/sensor-node-runtime.mjs +53 -53
  101. package/src/sensor-runtime.mjs +52 -52
  102. package/src/timestamp-contract.mjs +8 -8
  103. package/src/todo-audit-pending.mjs +91 -91
  104. package/src/todo-chain.mjs +178 -178
  105. package/src/todo-cli.mjs +3143 -3141
  106. package/src/todo-contracts.mjs +728 -728
  107. package/src/todo-dashboard-registry.mjs +573 -573
  108. package/src/todo-dispatch-shape.mjs +190 -190
  109. package/src/todo-gantt-html-independence.mjs +239 -239
  110. package/src/todo-gantt-html-shared.mjs +226 -226
  111. package/src/todo-gantt-html-style.mjs +131 -131
  112. package/src/todo-gantt-html.mjs +248 -248
  113. package/src/todo-gantt-layout.mjs +974 -974
  114. package/src/todo-gantt-live.mjs +361 -361
  115. package/src/todo-gantt-nested.mjs +263 -263
  116. package/src/todo-gantt-presentation.mjs +217 -217
  117. package/src/todo-gantt-scope.mjs +123 -123
  118. package/src/todo-gantt-svg.mjs +353 -353
  119. package/src/todo-independence-contracts.mjs +595 -595
  120. package/src/todo-independence-guidance.mjs +322 -322
  121. package/src/todo-independence.mjs +640 -640
  122. package/src/todo-markdown-renderer.mjs +260 -260
  123. package/src/todo-migration.mjs +448 -448
  124. package/src/todo-narrative-anchor.mjs +130 -130
  125. package/src/todo-note-store.mjs +629 -629
  126. package/src/todo-parallel-candidates.mjs +114 -114
  127. package/src/todo-revision.mjs +995 -995
  128. package/src/todo-split.mjs +472 -472
  129. package/src/todo-status.mjs +690 -690
  130. package/src/todo-store-git-transaction.mjs +418 -418
  131. package/src/todo-store.mjs +4360 -4322
  132. package/src/treatment-compiler.mjs +728 -728
  133. package/src/treatment-runner.mjs +656 -656
  134. package/src/witness-scaffold.mjs +180 -180
@@ -1,346 +1,346 @@
1
- import { createServer } from 'node:http';
2
- import { randomBytes, randomInt } from 'node:crypto';
3
- import { homedir } from 'node:os';
4
- import { isIP } from 'node:net';
5
- import {
6
- chmod, lstat, mkdir, open, readFile, rename, rm, writeFile,
7
- } from 'node:fs/promises';
8
- import path from 'node:path';
9
- import { domainToASCII } from 'node:url';
10
- import { parseTree } from 'jsonc-parser';
11
-
12
- export const BRIDGE_CONFIG_SCHEMA = 'lattice.bridge_config.v1';
13
- export const BRIDGE_PORT_MIN = 49_152;
14
- export const BRIDGE_PORT_MAX = 65_535;
15
- const CONFIG_NAME = 'bridge.json';
16
- const LOCK_NAME = 'bridge.lock';
17
- const OPERATION_LOCK_NAME = 'bridge-operation.lock';
18
- const LOCK_ATTEMPTS = 240;
19
- const LOCK_WAIT_MS = 25;
20
- const LOCK_STALE_MS = 30_000;
21
- const AUTO_PORT_ATTEMPTS = 256;
22
-
23
- export class BridgeConfigError extends Error {
24
- constructor(code, message, detail = undefined, cause = undefined) {
25
- super(message, { cause });
26
- this.name = 'BridgeConfigError';
27
- this.code = code;
28
- if (detail !== undefined) this.detail = detail;
29
- }
30
- }
31
-
32
- function exact(value, keys) {
33
- return value !== null && typeof value === 'object' && !Array.isArray(value)
34
- && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
35
- }
36
-
37
- function configRoot(env) {
38
- const configured = env.LATTICE_CONFIG_DIR;
39
- if (configured !== undefined) {
40
- if (typeof configured !== 'string' || !path.isAbsolute(configured)) {
41
- throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
42
- }
43
- return configured;
44
- }
45
- return path.join(homedir(), '.lattice');
46
- }
47
-
48
- export function bridgeConfigPaths(env = process.env) {
49
- const root = configRoot(env);
50
- return Object.freeze({ root, config: path.join(root, CONFIG_NAME), lock: path.join(root, LOCK_NAME),
51
- operationLock: path.join(root, OPERATION_LOCK_NAME) });
52
- }
53
-
54
- function validTimestamp(value) {
55
- return typeof value === 'string' && Number.isFinite(Date.parse(value))
56
- && new Date(value).toISOString() === value;
57
- }
58
-
59
- function validateListen(listen) {
60
- if (!exact(listen, ['address', 'port']) || isIP(listen.address) === 0
61
- || !Number.isSafeInteger(listen.port) || listen.port < BRIDGE_PORT_MIN
62
- || listen.port > BRIDGE_PORT_MAX) {
63
- throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge listen configuration is invalid');
64
- }
65
- }
66
-
67
- export function normalizeBridgeAllowedHost(value) {
68
- if (typeof value !== 'string' || value.length === 0 || value !== value.trim()) {
69
- throw new BridgeConfigError('BRIDGE_ALLOWED_HOST_INVALID', 'allowed host is invalid');
70
- }
71
- if (isIP(value) !== 0) return value.toLowerCase();
72
- const withoutDot = value.endsWith('.') ? value.slice(0, -1) : value;
73
- const ascii = domainToASCII(withoutDot).toLowerCase();
74
- if (ascii.length === 0 || ascii.length > 253
75
- || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(ascii)
76
- || ascii.split('.').some((label) => label.length === 0 || label.length > 63
77
- || label.startsWith('-') || label.endsWith('-'))) {
78
- throw new BridgeConfigError('BRIDGE_ALLOWED_HOST_INVALID', 'allowed host is invalid');
79
- }
80
- return ascii;
81
- }
82
-
83
- function normalizeAllowedHosts(address, values) {
84
- if (!Array.isArray(values) || values.length > 32) {
85
- throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts must be an array');
86
- }
87
- const hosts = new Set([normalizeBridgeAllowedHost(address)]);
88
- if (address === '0.0.0.0') hosts.add('127.0.0.1');
89
- if (address === '::') hosts.add('::1');
90
- for (const value of values) hosts.add(normalizeBridgeAllowedHost(value));
91
- if (hosts.size > 32) throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'too many allowed hosts');
92
- return Object.freeze([...hosts].sort((left, right) => left.localeCompare(right, 'en')));
93
- }
94
-
95
- export function normalizeBridgeUpstream(upstream) {
96
- if (upstream?.mode === 'dashboard_descriptor' && exact(upstream, ['mode'])) {
97
- return Object.freeze({ mode: 'dashboard_descriptor' });
98
- }
99
- if (upstream?.mode !== 'url' || !exact(upstream, ['mode', 'url']) || typeof upstream.url !== 'string') {
100
- throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream configuration is invalid');
101
- }
102
- let parsed;
103
- try { parsed = new URL(upstream.url); } catch {
104
- throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream URL is invalid');
105
- }
106
- if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username !== '' || parsed.password !== ''
107
- || parsed.hash !== '' || parsed.search !== '') {
108
- throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream URL must be an HTTP origin or base path');
109
- }
110
- parsed.pathname = parsed.pathname.endsWith('/') ? parsed.pathname : `${parsed.pathname}/`;
111
- return Object.freeze({ mode: 'url', url: parsed.href });
112
- }
113
-
114
- export function validateBridgeConfig(value) {
115
- if (!exact(value, ['schema', 'enabled', 'listen', 'allowed_hosts', 'upstream', 'updated_at'])
116
- || value.schema !== BRIDGE_CONFIG_SCHEMA || typeof value.enabled !== 'boolean'
117
- || !validTimestamp(value.updated_at)) {
118
- throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge configuration schema is invalid');
119
- }
120
- validateListen(value.listen);
121
- const allowedHosts = normalizeAllowedHosts(value.listen.address, value.allowed_hosts);
122
- if (allowedHosts.length !== value.allowed_hosts.length
123
- || allowedHosts.some((host, index) => host !== value.allowed_hosts[index])) {
124
- throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts are not canonical');
125
- }
126
- const upstream = normalizeBridgeUpstream(value.upstream);
127
- return Object.freeze({
128
- schema: BRIDGE_CONFIG_SCHEMA,
129
- enabled: value.enabled,
130
- listen: Object.freeze({ address: value.listen.address, port: value.listen.port }),
131
- allowed_hosts: allowedHosts,
132
- upstream,
133
- updated_at: value.updated_at,
134
- });
135
- }
136
-
137
- async function prepareRoot(root) {
138
- await mkdir(root, { recursive: true, mode: 0o700 });
139
- const stats = await lstat(root);
140
- if (!stats.isDirectory() || stats.isSymbolicLink()) {
141
- throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'bridge config directory is unsafe');
142
- }
143
- if ((stats.mode & 0o077) !== 0) await chmod(root, 0o700);
144
- }
145
-
146
- async function readDocument(ref) {
147
- let stats;
148
- try { stats = await lstat(ref); } catch (error) {
149
- if (error?.code === 'ENOENT') return null;
150
- throw new BridgeConfigError('BRIDGE_CONFIG_UNREADABLE', 'bridge config cannot be read', undefined, error);
151
- }
152
- if (!stats.isFile() || stats.isSymbolicLink() || (stats.mode & 0o777) !== 0o600) {
153
- throw new BridgeConfigError('BRIDGE_CONFIG_MODE_INVALID', 'bridge config must be a regular 0600 file');
154
- }
155
- let value;
156
- try {
157
- const text = await readFile(ref, 'utf8');
158
- const errors = [];
159
- const tree = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true });
160
- const duplicate = (node) => {
161
- if (node?.type === 'object') {
162
- const keys = new Set();
163
- for (const property of node.children ?? []) {
164
- const [key, child] = property.children ?? [];
165
- if (keys.has(key?.value) || duplicate(child)) return true;
166
- keys.add(key?.value);
167
- }
168
- } else if (node?.type === 'array') return (node.children ?? []).some(duplicate);
169
- return false;
170
- };
171
- if (errors.length > 0 || tree === undefined || duplicate(tree)) {
172
- throw new Error('duplicate or invalid JSON');
173
- }
174
- value = JSON.parse(text);
175
- } catch (error) {
176
- throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge config JSON is invalid', undefined, error);
177
- }
178
- return validateBridgeConfig(value);
179
- }
180
-
181
- export async function readBridgeConfig({ env = process.env } = {}) {
182
- return readDocument(bridgeConfigPaths(env).config);
183
- }
184
-
185
- async function atomicWrite(ref, value) {
186
- const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
187
- try {
188
- await writeFile(temporary, `${JSON.stringify(value)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
189
- await rename(temporary, ref);
190
- await chmod(ref, 0o600);
191
- } finally {
192
- await rm(temporary, { force: true });
193
- }
194
- }
195
-
196
- async function withLock(ref, action) {
197
- for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
198
- let handle;
199
- try {
200
- handle = await open(ref, 'wx', 0o600);
201
- await handle.writeFile(`${JSON.stringify({ pid: process.pid, created_at: new Date().toISOString() })}\n`);
202
- try { return await action(); } finally {
203
- await handle.close();
204
- await rm(ref, { force: true });
205
- }
206
- } catch (error) {
207
- if (error?.code !== 'EEXIST') throw error;
208
- try {
209
- const lock = JSON.parse(await readFile(ref, 'utf8'));
210
- let alive = Number.isSafeInteger(lock.pid) && lock.pid > 0;
211
- if (alive) try { process.kill(lock.pid, 0); } catch { alive = false; }
212
- if (!alive || Date.now() - Date.parse(lock.created_at) > LOCK_STALE_MS) {
213
- await rm(ref, { force: true });
214
- continue;
215
- }
216
- } catch (lockError) {
217
- if (lockError?.code === 'ENOENT') continue;
218
- }
219
- await new Promise((resolve) => setTimeout(resolve, LOCK_WAIT_MS));
220
- }
221
- }
222
- throw new BridgeConfigError('BRIDGE_CONFIG_BUSY', 'bridge config lock timed out');
223
- }
224
-
225
- export async function withBridgeOperationLock({ env = process.env } = {}, action) {
226
- if (typeof action !== 'function') throw new TypeError('bridge operation action required');
227
- const refs = bridgeConfigPaths(env);
228
- await prepareRoot(refs.root);
229
- return withLock(refs.operationLock, action);
230
- }
231
-
232
- function closeServer(server) {
233
- return new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
234
- }
235
-
236
- async function bindCandidate(address, port, createCandidateServer) {
237
- const server = createCandidateServer();
238
- try {
239
- await new Promise((resolve, reject) => {
240
- server.once('error', reject);
241
- server.listen({ host: address, port, exclusive: true }, resolve);
242
- });
243
- return server;
244
- } catch (error) {
245
- try { server.close(); } catch {}
246
- if (['EADDRINUSE', 'EACCES', 'EADDRNOTAVAIL'].includes(error?.code)) return null;
247
- throw new BridgeConfigError('BRIDGE_BIND_FAILED', 'bridge candidate bind failed', { address, port }, error);
248
- }
249
- }
250
-
251
- async function reservePort({ address, requestedPort, createCandidateServer, choosePort }) {
252
- if (requestedPort !== null) {
253
- const server = await bindCandidate(address, requestedPort, createCandidateServer);
254
- if (server === null) {
255
- throw new BridgeConfigError('BRIDGE_PORT_UNAVAILABLE', 'requested bridge port is unavailable',
256
- { address, port: requestedPort });
257
- }
258
- return { port: requestedPort, server };
259
- }
260
- const attempted = new Set();
261
- while (attempted.size < AUTO_PORT_ATTEMPTS) {
262
- let port = choosePort();
263
- if (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX) {
264
- port = randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1);
265
- }
266
- while (attempted.has(port)) {
267
- port = port === BRIDGE_PORT_MAX ? BRIDGE_PORT_MIN : port + 1;
268
- }
269
- attempted.add(port);
270
- const server = await bindCandidate(address, port, createCandidateServer);
271
- if (server !== null) return { port, server };
272
- }
273
- throw new BridgeConfigError('BRIDGE_PORT_EXHAUSTED', 'no exclusive high bridge port could be bound',
274
- { address, attempts: attempted.size });
275
- }
276
-
277
- function validateMutation({ address, port, upstream, allowedHosts }) {
278
- if (typeof address !== 'string' || isIP(address) === 0) {
279
- throw new BridgeConfigError('BRIDGE_LISTEN_INVALID', 'bridge listen address must be an IP literal');
280
- }
281
- if (port !== null && (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX)) {
282
- throw new BridgeConfigError('BRIDGE_PORT_INVALID', `bridge port must be ${BRIDGE_PORT_MIN}..${BRIDGE_PORT_MAX}`);
283
- }
284
- return { upstream: normalizeBridgeUpstream(upstream), allowedHosts: normalizeAllowedHosts(address, allowedHosts) };
285
- }
286
-
287
- export async function configureBridge({
288
- address, port = null, upstream = { mode: 'dashboard_descriptor' }, allowedHosts = [],
289
- env = process.env, now = () => new Date(),
290
- createCandidateServer = () => createServer(),
291
- choosePort = () => randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1),
292
- reuseCurrentPort = true,
293
- } = {}) {
294
- const normalized = validateMutation({ address, port, upstream, allowedHosts });
295
- const refs = bridgeConfigPaths(env);
296
- await prepareRoot(refs.root);
297
- return withLock(refs.lock, async () => {
298
- const current = await readDocument(refs.config);
299
- const selectedPort = port ?? (reuseCurrentPort && current?.enabled && current.listen.address === address
300
- ? current.listen.port : null);
301
- const bindingUnchanged = current?.enabled === true && current.listen.address === address
302
- && current.listen.port === selectedPort;
303
- let reservation = null;
304
- try {
305
- if (!bindingUnchanged) {
306
- reservation = await reservePort({ address, requestedPort: selectedPort,
307
- createCandidateServer, choosePort });
308
- }
309
- const config = validateBridgeConfig({
310
- schema: BRIDGE_CONFIG_SCHEMA,
311
- enabled: true,
312
- listen: { address, port: bindingUnchanged ? selectedPort : reservation.port },
313
- allowed_hosts: normalized.allowedHosts,
314
- upstream: normalized.upstream,
315
- updated_at: now().toISOString(),
316
- });
317
- await atomicWrite(refs.config, config);
318
- return config;
319
- } finally {
320
- if (reservation !== null) await closeServer(reservation.server);
321
- }
322
- });
323
- }
324
-
325
- export async function disableBridge({ env = process.env, now = () => new Date() } = {}) {
326
- const refs = bridgeConfigPaths(env);
327
- await prepareRoot(refs.root);
328
- return withLock(refs.lock, async () => {
329
- const current = await readDocument(refs.config);
330
- if (current === null) return null;
331
- const config = validateBridgeConfig({ ...current, enabled: false, updated_at: now().toISOString() });
332
- await atomicWrite(refs.config, config);
333
- return config;
334
- });
335
- }
336
-
337
- export async function restoreBridgeConfig(config, { env = process.env } = {}) {
338
- if (config !== null) validateBridgeConfig(config);
339
- const refs = bridgeConfigPaths(env);
340
- await prepareRoot(refs.root);
341
- return withLock(refs.lock, async () => {
342
- if (config === null) await rm(refs.config, { force: true });
343
- else await atomicWrite(refs.config, config);
344
- return config;
345
- });
346
- }
1
+ import { createServer } from 'node:http';
2
+ import { randomBytes, randomInt } from 'node:crypto';
3
+ import { homedir } from 'node:os';
4
+ import { isIP } from 'node:net';
5
+ import {
6
+ chmod, lstat, mkdir, open, readFile, rename, rm, writeFile,
7
+ } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { domainToASCII } from 'node:url';
10
+ import { parseTree } from 'jsonc-parser';
11
+
12
+ export const BRIDGE_CONFIG_SCHEMA = 'lattice.bridge_config.v1';
13
+ export const BRIDGE_PORT_MIN = 49_152;
14
+ export const BRIDGE_PORT_MAX = 65_535;
15
+ const CONFIG_NAME = 'bridge.json';
16
+ const LOCK_NAME = 'bridge.lock';
17
+ const OPERATION_LOCK_NAME = 'bridge-operation.lock';
18
+ const LOCK_ATTEMPTS = 240;
19
+ const LOCK_WAIT_MS = 25;
20
+ const LOCK_STALE_MS = 30_000;
21
+ const AUTO_PORT_ATTEMPTS = 256;
22
+
23
+ export class BridgeConfigError extends Error {
24
+ constructor(code, message, detail = undefined, cause = undefined) {
25
+ super(message, { cause });
26
+ this.name = 'BridgeConfigError';
27
+ this.code = code;
28
+ if (detail !== undefined) this.detail = detail;
29
+ }
30
+ }
31
+
32
+ function exact(value, keys) {
33
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
34
+ && Object.keys(value).sort().join(',') === [...keys].sort().join(',');
35
+ }
36
+
37
+ function configRoot(env) {
38
+ const configured = env.LATTICE_CONFIG_DIR;
39
+ if (configured !== undefined) {
40
+ if (typeof configured !== 'string' || !path.isAbsolute(configured)) {
41
+ throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
42
+ }
43
+ return configured;
44
+ }
45
+ return path.join(homedir(), '.lattice');
46
+ }
47
+
48
+ export function bridgeConfigPaths(env = process.env) {
49
+ const root = configRoot(env);
50
+ return Object.freeze({ root, config: path.join(root, CONFIG_NAME), lock: path.join(root, LOCK_NAME),
51
+ operationLock: path.join(root, OPERATION_LOCK_NAME) });
52
+ }
53
+
54
+ function validTimestamp(value) {
55
+ return typeof value === 'string' && Number.isFinite(Date.parse(value))
56
+ && new Date(value).toISOString() === value;
57
+ }
58
+
59
+ function validateListen(listen) {
60
+ if (!exact(listen, ['address', 'port']) || isIP(listen.address) === 0
61
+ || !Number.isSafeInteger(listen.port) || listen.port < BRIDGE_PORT_MIN
62
+ || listen.port > BRIDGE_PORT_MAX) {
63
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge listen configuration is invalid');
64
+ }
65
+ }
66
+
67
+ export function normalizeBridgeAllowedHost(value) {
68
+ if (typeof value !== 'string' || value.length === 0 || value !== value.trim()) {
69
+ throw new BridgeConfigError('BRIDGE_ALLOWED_HOST_INVALID', 'allowed host is invalid');
70
+ }
71
+ if (isIP(value) !== 0) return value.toLowerCase();
72
+ const withoutDot = value.endsWith('.') ? value.slice(0, -1) : value;
73
+ const ascii = domainToASCII(withoutDot).toLowerCase();
74
+ if (ascii.length === 0 || ascii.length > 253
75
+ || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/u.test(ascii)
76
+ || ascii.split('.').some((label) => label.length === 0 || label.length > 63
77
+ || label.startsWith('-') || label.endsWith('-'))) {
78
+ throw new BridgeConfigError('BRIDGE_ALLOWED_HOST_INVALID', 'allowed host is invalid');
79
+ }
80
+ return ascii;
81
+ }
82
+
83
+ function normalizeAllowedHosts(address, values) {
84
+ if (!Array.isArray(values) || values.length > 32) {
85
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts must be an array');
86
+ }
87
+ const hosts = new Set([normalizeBridgeAllowedHost(address)]);
88
+ if (address === '0.0.0.0') hosts.add('127.0.0.1');
89
+ if (address === '::') hosts.add('::1');
90
+ for (const value of values) hosts.add(normalizeBridgeAllowedHost(value));
91
+ if (hosts.size > 32) throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'too many allowed hosts');
92
+ return Object.freeze([...hosts].sort((left, right) => left.localeCompare(right, 'en')));
93
+ }
94
+
95
+ export function normalizeBridgeUpstream(upstream) {
96
+ if (upstream?.mode === 'dashboard_descriptor' && exact(upstream, ['mode'])) {
97
+ return Object.freeze({ mode: 'dashboard_descriptor' });
98
+ }
99
+ if (upstream?.mode !== 'url' || !exact(upstream, ['mode', 'url']) || typeof upstream.url !== 'string') {
100
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream configuration is invalid');
101
+ }
102
+ let parsed;
103
+ try { parsed = new URL(upstream.url); } catch {
104
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream URL is invalid');
105
+ }
106
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username !== '' || parsed.password !== ''
107
+ || parsed.hash !== '' || parsed.search !== '') {
108
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'bridge upstream URL must be an HTTP origin or base path');
109
+ }
110
+ parsed.pathname = parsed.pathname.endsWith('/') ? parsed.pathname : `${parsed.pathname}/`;
111
+ return Object.freeze({ mode: 'url', url: parsed.href });
112
+ }
113
+
114
+ export function validateBridgeConfig(value) {
115
+ if (!exact(value, ['schema', 'enabled', 'listen', 'allowed_hosts', 'upstream', 'updated_at'])
116
+ || value.schema !== BRIDGE_CONFIG_SCHEMA || typeof value.enabled !== 'boolean'
117
+ || !validTimestamp(value.updated_at)) {
118
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge configuration schema is invalid');
119
+ }
120
+ validateListen(value.listen);
121
+ const allowedHosts = normalizeAllowedHosts(value.listen.address, value.allowed_hosts);
122
+ if (allowedHosts.length !== value.allowed_hosts.length
123
+ || allowedHosts.some((host, index) => host !== value.allowed_hosts[index])) {
124
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts are not canonical');
125
+ }
126
+ const upstream = normalizeBridgeUpstream(value.upstream);
127
+ return Object.freeze({
128
+ schema: BRIDGE_CONFIG_SCHEMA,
129
+ enabled: value.enabled,
130
+ listen: Object.freeze({ address: value.listen.address, port: value.listen.port }),
131
+ allowed_hosts: allowedHosts,
132
+ upstream,
133
+ updated_at: value.updated_at,
134
+ });
135
+ }
136
+
137
+ async function prepareRoot(root) {
138
+ await mkdir(root, { recursive: true, mode: 0o700 });
139
+ const stats = await lstat(root);
140
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
141
+ throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'bridge config directory is unsafe');
142
+ }
143
+ if ((stats.mode & 0o077) !== 0) await chmod(root, 0o700);
144
+ }
145
+
146
+ async function readDocument(ref) {
147
+ let stats;
148
+ try { stats = await lstat(ref); } catch (error) {
149
+ if (error?.code === 'ENOENT') return null;
150
+ throw new BridgeConfigError('BRIDGE_CONFIG_UNREADABLE', 'bridge config cannot be read', undefined, error);
151
+ }
152
+ if (!stats.isFile() || stats.isSymbolicLink() || (stats.mode & 0o777) !== 0o600) {
153
+ throw new BridgeConfigError('BRIDGE_CONFIG_MODE_INVALID', 'bridge config must be a regular 0600 file');
154
+ }
155
+ let value;
156
+ try {
157
+ const text = await readFile(ref, 'utf8');
158
+ const errors = [];
159
+ const tree = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true });
160
+ const duplicate = (node) => {
161
+ if (node?.type === 'object') {
162
+ const keys = new Set();
163
+ for (const property of node.children ?? []) {
164
+ const [key, child] = property.children ?? [];
165
+ if (keys.has(key?.value) || duplicate(child)) return true;
166
+ keys.add(key?.value);
167
+ }
168
+ } else if (node?.type === 'array') return (node.children ?? []).some(duplicate);
169
+ return false;
170
+ };
171
+ if (errors.length > 0 || tree === undefined || duplicate(tree)) {
172
+ throw new Error('duplicate or invalid JSON');
173
+ }
174
+ value = JSON.parse(text);
175
+ } catch (error) {
176
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge config JSON is invalid', undefined, error);
177
+ }
178
+ return validateBridgeConfig(value);
179
+ }
180
+
181
+ export async function readBridgeConfig({ env = process.env } = {}) {
182
+ return readDocument(bridgeConfigPaths(env).config);
183
+ }
184
+
185
+ async function atomicWrite(ref, value) {
186
+ const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
187
+ try {
188
+ await writeFile(temporary, `${JSON.stringify(value)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
189
+ await rename(temporary, ref);
190
+ await chmod(ref, 0o600);
191
+ } finally {
192
+ await rm(temporary, { force: true });
193
+ }
194
+ }
195
+
196
+ async function withLock(ref, action) {
197
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
198
+ let handle;
199
+ try {
200
+ handle = await open(ref, 'wx', 0o600);
201
+ await handle.writeFile(`${JSON.stringify({ pid: process.pid, created_at: new Date().toISOString() })}\n`);
202
+ try { return await action(); } finally {
203
+ await handle.close();
204
+ await rm(ref, { force: true });
205
+ }
206
+ } catch (error) {
207
+ if (error?.code !== 'EEXIST') throw error;
208
+ try {
209
+ const lock = JSON.parse(await readFile(ref, 'utf8'));
210
+ let alive = Number.isSafeInteger(lock.pid) && lock.pid > 0;
211
+ if (alive) try { process.kill(lock.pid, 0); } catch { alive = false; }
212
+ if (!alive || Date.now() - Date.parse(lock.created_at) > LOCK_STALE_MS) {
213
+ await rm(ref, { force: true });
214
+ continue;
215
+ }
216
+ } catch (lockError) {
217
+ if (lockError?.code === 'ENOENT') continue;
218
+ }
219
+ await new Promise((resolve) => setTimeout(resolve, LOCK_WAIT_MS));
220
+ }
221
+ }
222
+ throw new BridgeConfigError('BRIDGE_CONFIG_BUSY', 'bridge config lock timed out');
223
+ }
224
+
225
+ export async function withBridgeOperationLock({ env = process.env } = {}, action) {
226
+ if (typeof action !== 'function') throw new TypeError('bridge operation action required');
227
+ const refs = bridgeConfigPaths(env);
228
+ await prepareRoot(refs.root);
229
+ return withLock(refs.operationLock, action);
230
+ }
231
+
232
+ function closeServer(server) {
233
+ return new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
234
+ }
235
+
236
+ async function bindCandidate(address, port, createCandidateServer) {
237
+ const server = createCandidateServer();
238
+ try {
239
+ await new Promise((resolve, reject) => {
240
+ server.once('error', reject);
241
+ server.listen({ host: address, port, exclusive: true }, resolve);
242
+ });
243
+ return server;
244
+ } catch (error) {
245
+ try { server.close(); } catch {}
246
+ if (['EADDRINUSE', 'EACCES', 'EADDRNOTAVAIL'].includes(error?.code)) return null;
247
+ throw new BridgeConfigError('BRIDGE_BIND_FAILED', 'bridge candidate bind failed', { address, port }, error);
248
+ }
249
+ }
250
+
251
+ async function reservePort({ address, requestedPort, createCandidateServer, choosePort }) {
252
+ if (requestedPort !== null) {
253
+ const server = await bindCandidate(address, requestedPort, createCandidateServer);
254
+ if (server === null) {
255
+ throw new BridgeConfigError('BRIDGE_PORT_UNAVAILABLE', 'requested bridge port is unavailable',
256
+ { address, port: requestedPort });
257
+ }
258
+ return { port: requestedPort, server };
259
+ }
260
+ const attempted = new Set();
261
+ while (attempted.size < AUTO_PORT_ATTEMPTS) {
262
+ let port = choosePort();
263
+ if (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX) {
264
+ port = randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1);
265
+ }
266
+ while (attempted.has(port)) {
267
+ port = port === BRIDGE_PORT_MAX ? BRIDGE_PORT_MIN : port + 1;
268
+ }
269
+ attempted.add(port);
270
+ const server = await bindCandidate(address, port, createCandidateServer);
271
+ if (server !== null) return { port, server };
272
+ }
273
+ throw new BridgeConfigError('BRIDGE_PORT_EXHAUSTED', 'no exclusive high bridge port could be bound',
274
+ { address, attempts: attempted.size });
275
+ }
276
+
277
+ function validateMutation({ address, port, upstream, allowedHosts }) {
278
+ if (typeof address !== 'string' || isIP(address) === 0) {
279
+ throw new BridgeConfigError('BRIDGE_LISTEN_INVALID', 'bridge listen address must be an IP literal');
280
+ }
281
+ if (port !== null && (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX)) {
282
+ throw new BridgeConfigError('BRIDGE_PORT_INVALID', `bridge port must be ${BRIDGE_PORT_MIN}..${BRIDGE_PORT_MAX}`);
283
+ }
284
+ return { upstream: normalizeBridgeUpstream(upstream), allowedHosts: normalizeAllowedHosts(address, allowedHosts) };
285
+ }
286
+
287
+ export async function configureBridge({
288
+ address, port = null, upstream = { mode: 'dashboard_descriptor' }, allowedHosts = [],
289
+ env = process.env, now = () => new Date(),
290
+ createCandidateServer = () => createServer(),
291
+ choosePort = () => randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1),
292
+ reuseCurrentPort = true,
293
+ } = {}) {
294
+ const normalized = validateMutation({ address, port, upstream, allowedHosts });
295
+ const refs = bridgeConfigPaths(env);
296
+ await prepareRoot(refs.root);
297
+ return withLock(refs.lock, async () => {
298
+ const current = await readDocument(refs.config);
299
+ const selectedPort = port ?? (reuseCurrentPort && current?.enabled && current.listen.address === address
300
+ ? current.listen.port : null);
301
+ const bindingUnchanged = current?.enabled === true && current.listen.address === address
302
+ && current.listen.port === selectedPort;
303
+ let reservation = null;
304
+ try {
305
+ if (!bindingUnchanged) {
306
+ reservation = await reservePort({ address, requestedPort: selectedPort,
307
+ createCandidateServer, choosePort });
308
+ }
309
+ const config = validateBridgeConfig({
310
+ schema: BRIDGE_CONFIG_SCHEMA,
311
+ enabled: true,
312
+ listen: { address, port: bindingUnchanged ? selectedPort : reservation.port },
313
+ allowed_hosts: normalized.allowedHosts,
314
+ upstream: normalized.upstream,
315
+ updated_at: now().toISOString(),
316
+ });
317
+ await atomicWrite(refs.config, config);
318
+ return config;
319
+ } finally {
320
+ if (reservation !== null) await closeServer(reservation.server);
321
+ }
322
+ });
323
+ }
324
+
325
+ export async function disableBridge({ env = process.env, now = () => new Date() } = {}) {
326
+ const refs = bridgeConfigPaths(env);
327
+ await prepareRoot(refs.root);
328
+ return withLock(refs.lock, async () => {
329
+ const current = await readDocument(refs.config);
330
+ if (current === null) return null;
331
+ const config = validateBridgeConfig({ ...current, enabled: false, updated_at: now().toISOString() });
332
+ await atomicWrite(refs.config, config);
333
+ return config;
334
+ });
335
+ }
336
+
337
+ export async function restoreBridgeConfig(config, { env = process.env } = {}) {
338
+ if (config !== null) validateBridgeConfig(config);
339
+ const refs = bridgeConfigPaths(env);
340
+ await prepareRoot(refs.root);
341
+ return withLock(refs.lock, async () => {
342
+ if (config === null) await rm(refs.config, { force: true });
343
+ else await atomicWrite(refs.config, config);
344
+ return config;
345
+ });
346
+ }