@quolu/lattice 0.52.3 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge.mjs +25 -0
  5. package/bin/lattice-hub.mjs +67 -0
  6. package/bin/lattice-mcp.mjs +0 -0
  7. package/bin/lattice-scripted-adapter.mjs +0 -0
  8. package/bin/lattice-scripted-worker.mjs +0 -0
  9. package/bin/lattice-work-order-adapter.mjs +0 -0
  10. package/bin/lattice.mjs +0 -0
  11. package/docs/bridge-setup.md +132 -132
  12. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  13. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  14. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  15. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  16. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  17. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  18. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  19. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  20. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  21. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  23. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  24. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  25. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  26. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  27. package/package.json +103 -103
  28. package/sensor/LICENSE +21 -21
  29. package/sensor/NOTICE +19 -19
  30. package/sensor/dist/bin/lattice-sensor.js +9 -9
  31. package/sensor/dist/db/index.js +24 -24
  32. package/sensor/dist/db/migrations.js +41 -41
  33. package/sensor/dist/db/queries.js +164 -164
  34. package/sensor/dist/db/schema.sql +205 -205
  35. package/sensor/dist/directory.js +5 -5
  36. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  37. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  51. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  52. package/sensor/dist/mcp/server-instructions.js +95 -95
  53. package/sensor/package.json +56 -56
  54. package/src/artifact-contracts-v2.mjs +325 -325
  55. package/src/artifact-contracts.mjs +895 -895
  56. package/src/boundary-compiler.mjs +712 -712
  57. package/src/boundary-observation-compiler-v2.mjs +344 -344
  58. package/src/bounded-seam.mjs +230 -230
  59. package/src/bridge-address.mjs +107 -107
  60. package/src/bridge-cli.mjs +303 -297
  61. package/src/bridge-config.mjs +382 -346
  62. package/src/bridge-daemon.mjs +378 -378
  63. package/src/bridge-hub-heartbeat.mjs +170 -0
  64. package/src/bridge-hub-protocol.mjs +198 -0
  65. package/src/bridge-hub-server.mjs +544 -0
  66. package/src/bridge-launch-agent.mjs +323 -323
  67. package/src/bridge-registrar.mjs +102 -102
  68. package/src/bridge-server.mjs +376 -376
  69. package/src/cli-help.mjs +308 -308
  70. package/src/cli-stdio.mjs +40 -40
  71. package/src/control-compiler.mjs +532 -532
  72. package/src/dag-chain.mjs +261 -261
  73. package/src/factory-diagnostics.mjs +188 -188
  74. package/src/git-process.mjs +72 -0
  75. package/src/hash-chain.mjs +76 -76
  76. package/src/hooks-cli.mjs +1057 -1057
  77. package/src/isolation-runner.mjs +409 -409
  78. package/src/node-version-guard.mjs +44 -44
  79. package/src/project-cli.mjs +3 -3
  80. package/src/project-identity.mjs +130 -130
  81. package/src/rc1-black-box-oracle.mjs +906 -906
  82. package/src/rc1-comparison.mjs +154 -154
  83. package/src/rc1-evidence-bundle.mjs +456 -456
  84. package/src/rc1-v4-campaign.mjs +708 -708
  85. package/src/rc1-v4-transform.mjs +467 -467
  86. package/src/rc1-v5-artifact-set.mjs +855 -855
  87. package/src/rc1-v5-behavior-evidence.mjs +594 -594
  88. package/src/rc1-v5-campaign.mjs +797 -797
  89. package/src/rc1-v5-transform.mjs +421 -421
  90. package/src/rc1-v6-artifact-set.mjs +807 -807
  91. package/src/rc1-v6-behavior-evidence.mjs +273 -273
  92. package/src/rc1-v6-campaign.mjs +623 -623
  93. package/src/rc1-v6-causal-binding.mjs +473 -473
  94. package/src/rc1-v6-measurement.mjs +313 -313
  95. package/src/rc2-artifact-set.mjs +1584 -1584
  96. package/src/rc2-campaign.mjs +1506 -1506
  97. package/src/rc2-delivery-policy-front-end.mjs +1079 -1079
  98. package/src/rc2-delivery-policy-oracle.mjs +134 -134
  99. package/src/rc2-delivery-policy-transform.mjs +1127 -1127
  100. package/src/rc2-rc1-transfer-front-end.mjs +511 -511
  101. package/src/rc3-actual-dogfood.mjs +652 -652
  102. package/src/rc3-dogfood-scaffold.mjs +315 -315
  103. package/src/rc3-scripted-campaign.mjs +1383 -1383
  104. package/src/rc4-stage1-dogfood.mjs +673 -673
  105. package/src/runtime-adapter-registry.mjs +524 -524
  106. package/src/runtime-cli.mjs +4588 -4588
  107. package/src/runtime-contracts.mjs +824 -824
  108. package/src/runtime-control-store.mjs +604 -604
  109. package/src/runtime-controller-protocol.mjs +587 -587
  110. package/src/runtime-decision-verifier.mjs +701 -701
  111. package/src/runtime-diff-observer.mjs +361 -361
  112. package/src/runtime-direct-os-observer.mjs +301 -301
  113. package/src/runtime-driver-state.mjs +166 -166
  114. package/src/runtime-engine.mjs +779 -779
  115. package/src/runtime-errors.mjs +356 -356
  116. package/src/runtime-event-store.mjs +189 -189
  117. package/src/runtime-front-end.mjs +925 -925
  118. package/src/runtime-gate-store.mjs +481 -481
  119. package/src/runtime-hold-recompile.mjs +916 -916
  120. package/src/runtime-io-sentinel.mjs +391 -391
  121. package/src/runtime-lifecycle-lock.mjs +294 -294
  122. package/src/runtime-managed-supervisor.mjs +1490 -1490
  123. package/src/runtime-multi-epoch-store.mjs +838 -838
  124. package/src/runtime-projection.mjs +269 -269
  125. package/src/runtime-pull-intake.mjs +1192 -1192
  126. package/src/runtime-scripted-adapter-controller.mjs +1160 -1160
  127. package/src/runtime-scripted-executor.mjs +163 -163
  128. package/src/runtime-scripted-worktree.mjs +104 -104
  129. package/src/runtime-seam-resolve.mjs +428 -428
  130. package/src/runtime-seam-treatment.mjs +173 -173
  131. package/src/runtime-socket-owner.mjs +125 -125
  132. package/src/runtime-work-order-contracts.mjs +91 -91
  133. package/src/runtime-work-order-controller.mjs +1171 -1171
  134. package/src/runtime-worktree-executor.mjs +199 -199
  135. package/src/schedulability-compiler-v2.mjs +303 -303
  136. package/src/schedulability-verifier-v2.mjs +317 -317
  137. package/src/seam-apply.mjs +549 -549
  138. package/src/seam-commit-shared.mjs +22 -22
  139. package/src/seam-commit-transform.mjs +81 -81
  140. package/src/seam-commit.mjs +18 -18
  141. package/src/seam-cost.mjs +322 -322
  142. package/src/seam-derivation.mjs +188 -188
  143. package/src/seam-gate.mjs +146 -146
  144. package/src/seam-proposal-contracts.mjs +446 -446
  145. package/src/seam-proposal-queries.mjs +521 -521
  146. package/src/seam-proposal.mjs +2011 -2011
  147. package/src/seam-ref.mjs +33 -33
  148. package/src/seam-rewrite.mjs +286 -286
  149. package/src/seam-transform.mjs +554 -554
  150. package/src/seam-verification.mjs +260 -260
  151. package/src/sensor-adapter.mjs +432 -432
  152. package/src/sensor-cli.mjs +139 -139
  153. package/src/sensor-diff.mjs +661 -661
  154. package/src/sensor-node-runtime.mjs +53 -53
  155. package/src/sensor-runtime.mjs +52 -52
  156. package/src/timestamp-contract.mjs +8 -8
  157. package/src/todo-audit-pending.mjs +91 -91
  158. package/src/todo-chain.mjs +178 -178
  159. package/src/todo-cli.mjs +8 -8
  160. package/src/todo-contracts.mjs +728 -728
  161. package/src/todo-dashboard-registry.mjs +573 -573
  162. package/src/todo-dispatch-shape.mjs +190 -190
  163. package/src/todo-gantt-html-independence.mjs +239 -239
  164. package/src/todo-gantt-html-shared.mjs +226 -226
  165. package/src/todo-gantt-html-style.mjs +131 -131
  166. package/src/todo-gantt-html.mjs +248 -248
  167. package/src/todo-gantt-layout.mjs +974 -974
  168. package/src/todo-gantt-live.mjs +361 -361
  169. package/src/todo-gantt-nested.mjs +263 -263
  170. package/src/todo-gantt-presentation.mjs +217 -217
  171. package/src/todo-gantt-scope.mjs +123 -123
  172. package/src/todo-gantt-svg.mjs +353 -353
  173. package/src/todo-independence-contracts.mjs +595 -595
  174. package/src/todo-independence-guidance.mjs +322 -322
  175. package/src/todo-independence.mjs +640 -640
  176. package/src/todo-markdown-renderer.mjs +260 -260
  177. package/src/todo-migration.mjs +448 -448
  178. package/src/todo-narrative-anchor.mjs +130 -130
  179. package/src/todo-note-store.mjs +629 -629
  180. package/src/todo-parallel-candidates.mjs +114 -114
  181. package/src/todo-revision.mjs +995 -995
  182. package/src/todo-split.mjs +472 -472
  183. package/src/todo-status.mjs +690 -690
  184. package/src/todo-store-git-transaction.mjs +418 -418
  185. package/src/todo-store.mjs +42 -21
  186. package/src/treatment-compiler.mjs +728 -728
  187. package/src/treatment-runner.mjs +656 -656
  188. package/src/witness-scaffold.mjs +180 -180
@@ -1,346 +1,382 @@
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
+ /**
115
+ * The hub this terminal heartbeats to (bh3), or null when unconfigured most
116
+ * terminals never opt in. Unlike `upstream`, there is only one shape: an
117
+ * explicit HTTP(S) origin. There is no descriptor-derived variant because the
118
+ * hub is a separate host on the LAN, not something this terminal can discover
119
+ * from its own local state.
120
+ */
121
+ export function normalizeBridgeHubUrl(hub) {
122
+ if (hub === null) return null;
123
+ if (!exact(hub, ['url']) || typeof hub.url !== 'string') {
124
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub configuration is invalid');
125
+ }
126
+ let parsed;
127
+ try { parsed = new URL(hub.url); } catch {
128
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub URL is invalid');
129
+ }
130
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username !== '' || parsed.password !== ''
131
+ || parsed.hash !== '' || parsed.search !== '') {
132
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub URL must be an HTTP origin');
133
+ }
134
+ parsed.pathname = parsed.pathname.endsWith('/') ? parsed.pathname : `${parsed.pathname}/`;
135
+ return Object.freeze({ url: parsed.href });
136
+ }
137
+
138
+ export function validateBridgeConfig(value) {
139
+ if (!exact(value, ['schema', 'enabled', 'listen', 'allowed_hosts', 'upstream', 'hub', 'updated_at'])
140
+ || value.schema !== BRIDGE_CONFIG_SCHEMA || typeof value.enabled !== 'boolean'
141
+ || !validTimestamp(value.updated_at)) {
142
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge configuration schema is invalid');
143
+ }
144
+ validateListen(value.listen);
145
+ const allowedHosts = normalizeAllowedHosts(value.listen.address, value.allowed_hosts);
146
+ if (allowedHosts.length !== value.allowed_hosts.length
147
+ || allowedHosts.some((host, index) => host !== value.allowed_hosts[index])) {
148
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts are not canonical');
149
+ }
150
+ const upstream = normalizeBridgeUpstream(value.upstream);
151
+ const hub = normalizeBridgeHubUrl(value.hub);
152
+ return Object.freeze({
153
+ schema: BRIDGE_CONFIG_SCHEMA,
154
+ enabled: value.enabled,
155
+ listen: Object.freeze({ address: value.listen.address, port: value.listen.port }),
156
+ allowed_hosts: allowedHosts,
157
+ upstream,
158
+ hub,
159
+ updated_at: value.updated_at,
160
+ });
161
+ }
162
+
163
+ async function prepareRoot(root) {
164
+ await mkdir(root, { recursive: true, mode: 0o700 });
165
+ const stats = await lstat(root);
166
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
167
+ throw new BridgeConfigError('BRIDGE_CONFIG_DIR_INVALID', 'bridge config directory is unsafe');
168
+ }
169
+ if ((stats.mode & 0o077) !== 0) await chmod(root, 0o700);
170
+ }
171
+
172
+ async function readDocument(ref) {
173
+ let stats;
174
+ try { stats = await lstat(ref); } catch (error) {
175
+ if (error?.code === 'ENOENT') return null;
176
+ throw new BridgeConfigError('BRIDGE_CONFIG_UNREADABLE', 'bridge config cannot be read', undefined, error);
177
+ }
178
+ if (!stats.isFile() || stats.isSymbolicLink() || (stats.mode & 0o777) !== 0o600) {
179
+ throw new BridgeConfigError('BRIDGE_CONFIG_MODE_INVALID', 'bridge config must be a regular 0600 file');
180
+ }
181
+ let value;
182
+ try {
183
+ const text = await readFile(ref, 'utf8');
184
+ const errors = [];
185
+ const tree = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true });
186
+ const duplicate = (node) => {
187
+ if (node?.type === 'object') {
188
+ const keys = new Set();
189
+ for (const property of node.children ?? []) {
190
+ const [key, child] = property.children ?? [];
191
+ if (keys.has(key?.value) || duplicate(child)) return true;
192
+ keys.add(key?.value);
193
+ }
194
+ } else if (node?.type === 'array') return (node.children ?? []).some(duplicate);
195
+ return false;
196
+ };
197
+ if (errors.length > 0 || tree === undefined || duplicate(tree)) {
198
+ throw new Error('duplicate or invalid JSON');
199
+ }
200
+ value = JSON.parse(text);
201
+ } catch (error) {
202
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge config JSON is invalid', undefined, error);
203
+ }
204
+ // `hub` (bh3) postdates this schema's v1 tag, which never changed — an on-disk
205
+ // config written before bh3 has no `hub` key at all. Treat that absence as
206
+ // "never configured" rather than a schema violation, so a bridge that has
207
+ // been running since before hub support existed keeps reading its own
208
+ // config instead of failing closed the next time this code is deployed.
209
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && value.hub === undefined) {
210
+ value = { ...value, hub: null };
211
+ }
212
+ return validateBridgeConfig(value);
213
+ }
214
+
215
+ export async function readBridgeConfig({ env = process.env } = {}) {
216
+ return readDocument(bridgeConfigPaths(env).config);
217
+ }
218
+
219
+ async function atomicWrite(ref, value) {
220
+ const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
221
+ try {
222
+ await writeFile(temporary, `${JSON.stringify(value)}\n`, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
223
+ await rename(temporary, ref);
224
+ await chmod(ref, 0o600);
225
+ } finally {
226
+ await rm(temporary, { force: true });
227
+ }
228
+ }
229
+
230
+ async function withLock(ref, action) {
231
+ for (let attempt = 0; attempt < LOCK_ATTEMPTS; attempt += 1) {
232
+ let handle;
233
+ try {
234
+ handle = await open(ref, 'wx', 0o600);
235
+ await handle.writeFile(`${JSON.stringify({ pid: process.pid, created_at: new Date().toISOString() })}\n`);
236
+ try { return await action(); } finally {
237
+ await handle.close();
238
+ await rm(ref, { force: true });
239
+ }
240
+ } catch (error) {
241
+ if (error?.code !== 'EEXIST') throw error;
242
+ try {
243
+ const lock = JSON.parse(await readFile(ref, 'utf8'));
244
+ let alive = Number.isSafeInteger(lock.pid) && lock.pid > 0;
245
+ if (alive) try { process.kill(lock.pid, 0); } catch { alive = false; }
246
+ if (!alive || Date.now() - Date.parse(lock.created_at) > LOCK_STALE_MS) {
247
+ await rm(ref, { force: true });
248
+ continue;
249
+ }
250
+ } catch (lockError) {
251
+ if (lockError?.code === 'ENOENT') continue;
252
+ }
253
+ await new Promise((resolve) => setTimeout(resolve, LOCK_WAIT_MS));
254
+ }
255
+ }
256
+ throw new BridgeConfigError('BRIDGE_CONFIG_BUSY', 'bridge config lock timed out');
257
+ }
258
+
259
+ export async function withBridgeOperationLock({ env = process.env } = {}, action) {
260
+ if (typeof action !== 'function') throw new TypeError('bridge operation action required');
261
+ const refs = bridgeConfigPaths(env);
262
+ await prepareRoot(refs.root);
263
+ return withLock(refs.operationLock, action);
264
+ }
265
+
266
+ function closeServer(server) {
267
+ return new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
268
+ }
269
+
270
+ async function bindCandidate(address, port, createCandidateServer) {
271
+ const server = createCandidateServer();
272
+ try {
273
+ await new Promise((resolve, reject) => {
274
+ server.once('error', reject);
275
+ server.listen({ host: address, port, exclusive: true }, resolve);
276
+ });
277
+ return server;
278
+ } catch (error) {
279
+ try { server.close(); } catch {}
280
+ if (['EADDRINUSE', 'EACCES', 'EADDRNOTAVAIL'].includes(error?.code)) return null;
281
+ throw new BridgeConfigError('BRIDGE_BIND_FAILED', 'bridge candidate bind failed', { address, port }, error);
282
+ }
283
+ }
284
+
285
+ async function reservePort({ address, requestedPort, createCandidateServer, choosePort }) {
286
+ if (requestedPort !== null) {
287
+ const server = await bindCandidate(address, requestedPort, createCandidateServer);
288
+ if (server === null) {
289
+ throw new BridgeConfigError('BRIDGE_PORT_UNAVAILABLE', 'requested bridge port is unavailable',
290
+ { address, port: requestedPort });
291
+ }
292
+ return { port: requestedPort, server };
293
+ }
294
+ const attempted = new Set();
295
+ while (attempted.size < AUTO_PORT_ATTEMPTS) {
296
+ let port = choosePort();
297
+ if (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX) {
298
+ port = randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1);
299
+ }
300
+ while (attempted.has(port)) {
301
+ port = port === BRIDGE_PORT_MAX ? BRIDGE_PORT_MIN : port + 1;
302
+ }
303
+ attempted.add(port);
304
+ const server = await bindCandidate(address, port, createCandidateServer);
305
+ if (server !== null) return { port, server };
306
+ }
307
+ throw new BridgeConfigError('BRIDGE_PORT_EXHAUSTED', 'no exclusive high bridge port could be bound',
308
+ { address, attempts: attempted.size });
309
+ }
310
+
311
+ function validateMutation({ address, port, upstream, hub, allowedHosts }) {
312
+ if (typeof address !== 'string' || isIP(address) === 0) {
313
+ throw new BridgeConfigError('BRIDGE_LISTEN_INVALID', 'bridge listen address must be an IP literal');
314
+ }
315
+ if (port !== null && (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX)) {
316
+ throw new BridgeConfigError('BRIDGE_PORT_INVALID', `bridge port must be ${BRIDGE_PORT_MIN}..${BRIDGE_PORT_MAX}`);
317
+ }
318
+ return { upstream: normalizeBridgeUpstream(upstream), hub: normalizeBridgeHubUrl(hub),
319
+ allowedHosts: normalizeAllowedHosts(address, allowedHosts) };
320
+ }
321
+
322
+ export async function configureBridge({
323
+ address, port = null, upstream = { mode: 'dashboard_descriptor' }, hub = null, allowedHosts = [],
324
+ env = process.env, now = () => new Date(),
325
+ createCandidateServer = () => createServer(),
326
+ choosePort = () => randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1),
327
+ reuseCurrentPort = true,
328
+ } = {}) {
329
+ const normalized = validateMutation({ address, port, upstream, hub, allowedHosts });
330
+ const refs = bridgeConfigPaths(env);
331
+ await prepareRoot(refs.root);
332
+ return withLock(refs.lock, async () => {
333
+ const current = await readDocument(refs.config);
334
+ const selectedPort = port ?? (reuseCurrentPort && current?.enabled && current.listen.address === address
335
+ ? current.listen.port : null);
336
+ const bindingUnchanged = current?.enabled === true && current.listen.address === address
337
+ && current.listen.port === selectedPort;
338
+ let reservation = null;
339
+ try {
340
+ if (!bindingUnchanged) {
341
+ reservation = await reservePort({ address, requestedPort: selectedPort,
342
+ createCandidateServer, choosePort });
343
+ }
344
+ const config = validateBridgeConfig({
345
+ schema: BRIDGE_CONFIG_SCHEMA,
346
+ enabled: true,
347
+ listen: { address, port: bindingUnchanged ? selectedPort : reservation.port },
348
+ allowed_hosts: normalized.allowedHosts,
349
+ upstream: normalized.upstream,
350
+ hub: normalized.hub,
351
+ updated_at: now().toISOString(),
352
+ });
353
+ await atomicWrite(refs.config, config);
354
+ return config;
355
+ } finally {
356
+ if (reservation !== null) await closeServer(reservation.server);
357
+ }
358
+ });
359
+ }
360
+
361
+ export async function disableBridge({ env = process.env, now = () => new Date() } = {}) {
362
+ const refs = bridgeConfigPaths(env);
363
+ await prepareRoot(refs.root);
364
+ return withLock(refs.lock, async () => {
365
+ const current = await readDocument(refs.config);
366
+ if (current === null) return null;
367
+ const config = validateBridgeConfig({ ...current, enabled: false, updated_at: now().toISOString() });
368
+ await atomicWrite(refs.config, config);
369
+ return config;
370
+ });
371
+ }
372
+
373
+ export async function restoreBridgeConfig(config, { env = process.env } = {}) {
374
+ if (config !== null) validateBridgeConfig(config);
375
+ const refs = bridgeConfigPaths(env);
376
+ await prepareRoot(refs.root);
377
+ return withLock(refs.lock, async () => {
378
+ if (config === null) await rm(refs.config, { force: true });
379
+ else await atomicWrite(refs.config, config);
380
+ return config;
381
+ });
382
+ }