@quolu/lattice 0.52.0 → 0.52.2

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 (182) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-mcp.mjs +0 -0
  5. package/bin/lattice-scripted-adapter.mjs +0 -0
  6. package/bin/lattice-scripted-worker.mjs +0 -0
  7. package/bin/lattice-work-order-adapter.mjs +0 -0
  8. package/bin/lattice.mjs +0 -0
  9. package/docs/bridge-setup.md +132 -132
  10. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  11. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  12. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  13. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  14. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  15. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  16. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  17. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  18. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  19. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  20. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  21. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  22. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  23. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  24. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  25. package/package.json +103 -103
  26. package/sensor/LICENSE +21 -21
  27. package/sensor/NOTICE +19 -19
  28. package/sensor/dist/bin/lattice-sensor.js +9 -9
  29. package/sensor/dist/db/index.js +24 -24
  30. package/sensor/dist/db/migrations.js +41 -41
  31. package/sensor/dist/db/queries.js +164 -164
  32. package/sensor/dist/db/schema.sql +205 -205
  33. package/sensor/dist/directory.js +5 -5
  34. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  35. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  36. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  49. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  50. package/sensor/dist/mcp/server-instructions.js +95 -95
  51. package/sensor/package.json +56 -56
  52. package/src/artifact-contracts-v2.mjs +325 -325
  53. package/src/artifact-contracts.mjs +895 -895
  54. package/src/boundary-compiler.mjs +712 -712
  55. package/src/boundary-observation-compiler-v2.mjs +344 -344
  56. package/src/bounded-seam.mjs +230 -230
  57. package/src/bridge-address.mjs +107 -107
  58. package/src/bridge-cli.mjs +297 -297
  59. package/src/bridge-config.mjs +346 -346
  60. package/src/bridge-daemon.mjs +378 -378
  61. package/src/bridge-launch-agent.mjs +323 -323
  62. package/src/bridge-registrar.mjs +102 -102
  63. package/src/bridge-server.mjs +376 -376
  64. package/src/cli-help.mjs +308 -308
  65. package/src/cli-stdio.mjs +40 -40
  66. package/src/control-compiler.mjs +532 -532
  67. package/src/dag-chain.mjs +261 -261
  68. package/src/factory-diagnostics.mjs +188 -188
  69. package/src/hash-chain.mjs +76 -76
  70. package/src/hooks-cli.mjs +1057 -1053
  71. package/src/isolation-runner.mjs +409 -409
  72. package/src/node-version-guard.mjs +44 -44
  73. package/src/project-cli.mjs +697 -697
  74. package/src/project-identity.mjs +130 -130
  75. package/src/rc1-black-box-oracle.mjs +906 -906
  76. package/src/rc1-comparison.mjs +154 -154
  77. package/src/rc1-evidence-bundle.mjs +456 -456
  78. package/src/rc1-v4-campaign.mjs +708 -708
  79. package/src/rc1-v4-transform.mjs +467 -467
  80. package/src/rc1-v5-artifact-set.mjs +855 -855
  81. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  82. package/src/rc1-v5-campaign.mjs +797 -797
  83. package/src/rc1-v5-transform.mjs +421 -421
  84. package/src/rc1-v6-artifact-set.mjs +807 -807
  85. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  86. package/src/rc1-v6-campaign.mjs +623 -623
  87. package/src/rc1-v6-causal-binding.mjs +473 -473
  88. package/src/rc1-v6-measurement.mjs +313 -313
  89. package/src/rc2-artifact-set.mjs +1584 -1584
  90. package/src/rc2-campaign.mjs +1506 -1502
  91. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  92. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  93. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  94. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  95. package/src/rc3-actual-dogfood.mjs +652 -652
  96. package/src/rc3-dogfood-scaffold.mjs +315 -315
  97. package/src/rc3-scripted-campaign.mjs +1383 -1383
  98. package/src/rc4-stage1-dogfood.mjs +673 -673
  99. package/src/runtime-adapter-registry.mjs +524 -520
  100. package/src/runtime-cli.mjs +4588 -4584
  101. package/src/runtime-contracts.mjs +824 -824
  102. package/src/runtime-control-store.mjs +604 -600
  103. package/src/runtime-controller-protocol.mjs +587 -587
  104. package/src/runtime-decision-verifier.mjs +701 -701
  105. package/src/runtime-diff-observer.mjs +361 -361
  106. package/src/runtime-direct-os-observer.mjs +301 -301
  107. package/src/runtime-driver-state.mjs +166 -162
  108. package/src/runtime-engine.mjs +779 -779
  109. package/src/runtime-errors.mjs +356 -356
  110. package/src/runtime-event-store.mjs +189 -189
  111. package/src/runtime-front-end.mjs +925 -925
  112. package/src/runtime-gate-store.mjs +481 -477
  113. package/src/runtime-hold-recompile.mjs +916 -916
  114. package/src/runtime-io-sentinel.mjs +391 -391
  115. package/src/runtime-lifecycle-lock.mjs +294 -290
  116. package/src/runtime-managed-supervisor.mjs +1490 -1490
  117. package/src/runtime-multi-epoch-store.mjs +838 -834
  118. package/src/runtime-projection.mjs +269 -269
  119. package/src/runtime-pull-intake.mjs +1192 -1188
  120. package/src/runtime-scripted-adapter-controller.mjs +1160 -1156
  121. package/src/runtime-scripted-executor.mjs +163 -163
  122. package/src/runtime-scripted-worktree.mjs +104 -104
  123. package/src/runtime-seam-resolve.mjs +428 -428
  124. package/src/runtime-seam-treatment.mjs +173 -173
  125. package/src/runtime-socket-owner.mjs +125 -125
  126. package/src/runtime-work-order-contracts.mjs +91 -91
  127. package/src/runtime-work-order-controller.mjs +1171 -1167
  128. package/src/runtime-worktree-executor.mjs +199 -199
  129. package/src/schedulability-compiler-v2.mjs +303 -303
  130. package/src/schedulability-verifier-v2.mjs +317 -317
  131. package/src/seam-apply.mjs +549 -549
  132. package/src/seam-commit-shared.mjs +22 -22
  133. package/src/seam-commit-transform.mjs +81 -81
  134. package/src/seam-commit.mjs +18 -18
  135. package/src/seam-cost.mjs +322 -322
  136. package/src/seam-derivation.mjs +188 -188
  137. package/src/seam-gate.mjs +146 -146
  138. package/src/seam-proposal-contracts.mjs +446 -446
  139. package/src/seam-proposal-queries.mjs +521 -521
  140. package/src/seam-proposal.mjs +2011 -2011
  141. package/src/seam-ref.mjs +33 -33
  142. package/src/seam-rewrite.mjs +286 -286
  143. package/src/seam-transform.mjs +554 -554
  144. package/src/seam-verification.mjs +260 -260
  145. package/src/sensor-adapter.mjs +432 -432
  146. package/src/sensor-cli.mjs +139 -139
  147. package/src/sensor-diff.mjs +661 -661
  148. package/src/sensor-node-runtime.mjs +53 -53
  149. package/src/sensor-runtime.mjs +52 -52
  150. package/src/timestamp-contract.mjs +8 -8
  151. package/src/todo-audit-pending.mjs +91 -91
  152. package/src/todo-chain.mjs +178 -178
  153. package/src/todo-cli.mjs +3141 -3126
  154. package/src/todo-contracts.mjs +728 -728
  155. package/src/todo-dashboard-registry.mjs +573 -573
  156. package/src/todo-dispatch-shape.mjs +190 -190
  157. package/src/todo-gantt-html-independence.mjs +239 -239
  158. package/src/todo-gantt-html-shared.mjs +226 -226
  159. package/src/todo-gantt-html-style.mjs +131 -131
  160. package/src/todo-gantt-html.mjs +248 -248
  161. package/src/todo-gantt-layout.mjs +974 -974
  162. package/src/todo-gantt-live.mjs +361 -361
  163. package/src/todo-gantt-nested.mjs +263 -263
  164. package/src/todo-gantt-presentation.mjs +217 -217
  165. package/src/todo-gantt-scope.mjs +123 -123
  166. package/src/todo-gantt-svg.mjs +353 -353
  167. package/src/todo-independence-contracts.mjs +595 -595
  168. package/src/todo-independence-guidance.mjs +322 -322
  169. package/src/todo-independence.mjs +640 -640
  170. package/src/todo-markdown-renderer.mjs +260 -260
  171. package/src/todo-migration.mjs +448 -448
  172. package/src/todo-narrative-anchor.mjs +130 -130
  173. package/src/todo-note-store.mjs +629 -625
  174. package/src/todo-parallel-candidates.mjs +114 -114
  175. package/src/todo-revision.mjs +995 -995
  176. package/src/todo-split.mjs +472 -472
  177. package/src/todo-status.mjs +690 -690
  178. package/src/todo-store-git-transaction.mjs +418 -418
  179. package/src/todo-store.mjs +4322 -4314
  180. package/src/treatment-compiler.mjs +728 -728
  181. package/src/treatment-runner.mjs +656 -656
  182. 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
+ }