@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,323 +1,323 @@
1
- import { execFile } from 'node:child_process';
2
- import { randomBytes } from 'node:crypto';
3
- import { constants as fsConstants } from 'node:fs';
4
- import {
5
- chmod, lstat, mkdir, open, readFile, realpath, rename, rm, writeFile,
6
- } from 'node:fs/promises';
7
- import path from 'node:path';
8
- import { promisify } from 'node:util';
9
-
10
- import { BridgeConfigError, readBridgeConfig } from './bridge-config.mjs';
11
- import { readBridgeDaemonDescriptor } from './bridge-daemon.mjs';
12
- import { bridgeRegistrarSettings } from './bridge-registrar.mjs';
13
-
14
- export const BRIDGE_LAUNCH_AGENT_LABEL = 'dev.kitepon.lattice.bridge';
15
- const START_TIMEOUT_MS = 5_000;
16
- const STOP_TIMEOUT_MS = 3_000;
17
- const execFileAsync = promisify(execFile);
18
-
19
- function fail(code, message, cause = undefined) {
20
- return new BridgeConfigError(code, message, undefined, cause);
21
- }
22
-
23
- function userId() {
24
- const uid = process.getuid?.();
25
- if (!Number.isSafeInteger(uid) || uid < 0) {
26
- throw fail('BRIDGE_LAUNCH_AGENT_UID_INVALID', 'current user id is unavailable');
27
- }
28
- return uid;
29
- }
30
-
31
- export function bridgeLaunchAgentPaths(env = process.env) {
32
- const home = env.HOME;
33
- if (typeof home !== 'string' || !path.isAbsolute(home)) {
34
- throw fail('BRIDGE_LAUNCH_AGENT_HOME_INVALID', 'HOME must be an absolute path');
35
- }
36
- const directory = path.join(home, 'Library', 'LaunchAgents');
37
- return Object.freeze({ directory,
38
- plist: path.join(directory, `${BRIDGE_LAUNCH_AGENT_LABEL}.plist`) });
39
- }
40
-
41
- async function prepareDirectory(directory, uid = userId()) {
42
- const home = path.dirname(path.dirname(directory));
43
- const library = path.dirname(directory);
44
- await mkdir(home, { recursive: true, mode: 0o700 });
45
- for (const ref of [home, library, directory]) {
46
- await mkdir(ref, { mode: 0o700 }).catch((error) => {
47
- if (error?.code !== 'EEXIST') throw error;
48
- });
49
- const stats = await lstat(ref);
50
- if (!stats.isDirectory() || stats.isSymbolicLink() || stats.uid !== uid
51
- || (stats.mode & 0o022) !== 0) {
52
- throw fail('BRIDGE_LAUNCH_AGENT_DIR_UNSAFE', 'LaunchAgents path is unsafe');
53
- }
54
- }
55
- }
56
-
57
- async function strictPlist(ref, uid = userId()) {
58
- let before;
59
- let handle;
60
- try {
61
- before = await lstat(ref);
62
- if (!before.isFile() || before.isSymbolicLink() || before.uid !== uid
63
- || (before.mode & 0o777) !== 0o600 || before.size > 65_536) {
64
- throw new Error('unsafe plist');
65
- }
66
- handle = await open(ref, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
67
- const opened = await handle.stat();
68
- if (!opened.isFile() || opened.uid !== uid || opened.dev !== before.dev
69
- || opened.ino !== before.ino || opened.size !== before.size) {
70
- throw new Error('plist changed during validation');
71
- }
72
- const content = await handle.readFile('utf8');
73
- const after = await lstat(ref);
74
- if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size) {
75
- throw new Error('plist changed during read');
76
- }
77
- return content;
78
- } catch (error) {
79
- if (error?.code === 'ENOENT' && before === undefined) return null;
80
- throw fail('BRIDGE_LAUNCH_AGENT_PLIST_UNSAFE', 'bridge LaunchAgent plist is unsafe', error);
81
- } finally {
82
- await handle?.close();
83
- }
84
- }
85
-
86
- async function atomicPlist(ref, content) {
87
- const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
88
- try {
89
- await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
90
- await rename(temporary, ref);
91
- await chmod(ref, 0o600);
92
- } finally {
93
- await rm(temporary, { force: true });
94
- }
95
- }
96
-
97
- function xml(value) {
98
- return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
99
- .replaceAll('"', '&quot;').replaceAll("'", '&apos;');
100
- }
101
-
102
- async function executablePath(ref, label, { executable = true, uid = userId() } = {}) {
103
- if (typeof ref !== 'string' || !path.isAbsolute(ref)) {
104
- throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} path must be absolute`);
105
- }
106
- let resolved;
107
- let stats;
108
- try {
109
- resolved = await realpath(ref);
110
- stats = await lstat(resolved);
111
- } catch (error) {
112
- throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unavailable`, error);
113
- }
114
- if (!stats.isFile() || stats.isSymbolicLink() || ![0, uid].includes(stats.uid)
115
- || (stats.mode & 0o022) !== 0
116
- || executable && (stats.mode & 0o111) === 0) {
117
- throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unsafe`);
118
- }
119
- return resolved;
120
- }
121
-
122
- function plistDocument({ nodePath, bridgePath, instanceToken, env }) {
123
- const environment = [['LATTICE_BRIDGE_INSTANCE_TOKEN', instanceToken]];
124
- if (env.LATTICE_CONFIG_DIR !== undefined) {
125
- if (typeof env.LATTICE_CONFIG_DIR !== 'string' || !path.isAbsolute(env.LATTICE_CONFIG_DIR)) {
126
- throw fail('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
127
- }
128
- environment.push(['LATTICE_CONFIG_DIR', env.LATTICE_CONFIG_DIR]);
129
- }
130
- // The daemon registers its upstream on every new binding, but only if it can
131
- // see the registrar settings. launchd does not inherit the shell environment,
132
- // so without baking them in here the self-registration silently never fires —
133
- // which is exactly the kind of quiet non-recovery this whole path exists to
134
- // remove. `bridgeRegistrarSettings` rejects a half-configured pair rather than
135
- // installing an agent that would skip registration forever.
136
- const registrar = bridgeRegistrarSettings(env);
137
- if (registrar !== null) {
138
- environment.push(['LATTICE_BRIDGE_REGISTRAR_SSH_HOST', registrar.host]);
139
- environment.push(['LATTICE_BRIDGE_REGISTRAR_SCRIPT', registrar.script]);
140
- }
141
- const environmentXml = environment.map(([key, value]) =>
142
- ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join('\n');
143
- return `<?xml version="1.0" encoding="UTF-8"?>
144
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
145
- <plist version="1.0">
146
- <dict>
147
- <key>Label</key>
148
- <string>${BRIDGE_LAUNCH_AGENT_LABEL}</string>
149
- <key>ProgramArguments</key>
150
- <array>
151
- <string>${xml(nodePath)}</string>
152
- <string>${xml(bridgePath)}</string>
153
- </array>
154
- <key>EnvironmentVariables</key>
155
- <dict>
156
- ${environmentXml}
157
- </dict>
158
- <key>RunAtLoad</key>
159
- <true/>
160
- <key>KeepAlive</key>
161
- <true/>
162
- <key>ThrottleInterval</key>
163
- <integer>10</integer>
164
- </dict>
165
- </plist>
166
- `;
167
- }
168
-
169
- export async function defaultLaunchctlRunner(args) {
170
- try {
171
- const result = await execFileAsync('/bin/launchctl', args, { encoding: 'utf8' });
172
- return { code: 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
173
- } catch (error) {
174
- if (Number.isInteger(error?.code)) {
175
- return { code: error.code, stdout: error.stdout ?? '', stderr: error.stderr ?? '' };
176
- }
177
- throw fail('BRIDGE_LAUNCHCTL_UNAVAILABLE', 'launchctl could not be executed', error);
178
- }
179
- }
180
-
181
- function domain(uid) { return `gui/${uid}`; }
182
- function service(uid) { return `${domain(uid)}/${BRIDGE_LAUNCH_AGENT_LABEL}`; }
183
-
184
- async function launchctl(runner, args, code, message, accepted = [0]) {
185
- let result;
186
- try { result = await runner(args); } catch (error) {
187
- if (error instanceof BridgeConfigError) throw error;
188
- throw fail(code, message, error);
189
- }
190
- if (!result || !Number.isInteger(result.code) || !accepted.includes(result.code)) {
191
- throw fail(code, message);
192
- }
193
- return result;
194
- }
195
-
196
- async function loadedState(runner, uid) {
197
- const result = await launchctl(runner, ['print', service(uid)],
198
- 'BRIDGE_LAUNCHCTL_STATUS_FAILED', 'could not inspect bridge LaunchAgent', [0, 113]);
199
- return result.code === 0;
200
- }
201
-
202
- function healthHost(address) {
203
- if (address === '0.0.0.0') return '127.0.0.1';
204
- if (address === '::') return '[::1]';
205
- return address.includes(':') ? `[${address}]` : address;
206
- }
207
-
208
- async function defaultWaitReady({ config, instanceToken, env, timeoutMs = START_TIMEOUT_MS }) {
209
- const deadline = Date.now() + timeoutMs;
210
- while (Date.now() < deadline) {
211
- const descriptor = await readBridgeDaemonDescriptor({ env });
212
- if (descriptor?.address === config.listen.address && descriptor?.port === config.listen.port
213
- && descriptor?.config_updated_at === config.updated_at) {
214
- try {
215
- const response = await fetch(
216
- `http://${healthHost(descriptor.address)}:${descriptor.port}/__lattice/bridge-health`, {
217
- headers: { 'x-lattice-bridge-instance-token': instanceToken },
218
- signal: AbortSignal.timeout(400),
219
- });
220
- const body = response.status === 200 ? await response.json() : null;
221
- if (body?.schema === 'lattice.bridge_health.v1' && body.pid === descriptor.pid
222
- && body.updated_at === config.updated_at) return descriptor;
223
- } catch {}
224
- }
225
- await new Promise((resolve) => setTimeout(resolve, 50));
226
- }
227
- throw fail('BRIDGE_LAUNCH_AGENT_START_FAILED', 'bridge LaunchAgent did not become healthy');
228
- }
229
-
230
- async function defaultWaitStopped({ listen, timeoutMs = STOP_TIMEOUT_MS }) {
231
- if (listen === null) return;
232
- const deadline = Date.now() + timeoutMs;
233
- while (Date.now() < deadline) {
234
- try {
235
- await fetch(`http://${healthHost(listen.address)}:${listen.port}/__lattice/bridge-health`,
236
- { signal: AbortSignal.timeout(300) });
237
- } catch { return; }
238
- await new Promise((resolve) => setTimeout(resolve, 50));
239
- }
240
- throw fail('BRIDGE_LAUNCH_AGENT_STOP_FAILED', 'bridge LaunchAgent socket did not stop');
241
- }
242
-
243
- export async function snapshotBridgeLaunchAgent({ env = process.env,
244
- runner = defaultLaunchctlRunner, uid = userId() } = {}) {
245
- const refs = bridgeLaunchAgentPaths(env);
246
- await prepareDirectory(refs.directory, uid);
247
- const content = await strictPlist(refs.plist, uid);
248
- const loaded = await loadedState(runner, uid);
249
- if (loaded && content === null) {
250
- throw fail('BRIDGE_LAUNCH_AGENT_STATE_INVALID', 'loaded bridge LaunchAgent has no owned plist');
251
- }
252
- return Object.freeze({ installed: content !== null, loaded, content });
253
- }
254
-
255
- async function bootoutIfLoaded({ runner, uid }) {
256
- if (!await loadedState(runner, uid)) return false;
257
- await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
258
- 'could not stop bridge LaunchAgent');
259
- return true;
260
- }
261
-
262
- export async function installBridgeLaunchAgent({ config, env = process.env,
263
- runner = defaultLaunchctlRunner, uid = userId(), nodePath = process.execPath,
264
- bridgePath = path.resolve(import.meta.dirname, '../bin/lattice-bridge.mjs'),
265
- waitReady = defaultWaitReady, waitStopped = defaultWaitStopped,
266
- previousListen = null } = {}) {
267
- if (config?.enabled !== true) throw fail('BRIDGE_DISABLED', 'bridge is disabled');
268
- const refs = bridgeLaunchAgentPaths(env);
269
- await prepareDirectory(refs.directory, uid);
270
- await strictPlist(refs.plist, uid);
271
- const resolvedNode = await executablePath(nodePath, 'node executable', { uid });
272
- const resolvedBridge = await executablePath(bridgePath, 'bridge executable', { executable: false, uid });
273
- const instanceToken = randomBytes(32).toString('hex');
274
- const content = plistDocument({ nodePath: resolvedNode, bridgePath: resolvedBridge, instanceToken, env });
275
- const stopped = await bootoutIfLoaded({ runner, uid });
276
- if (stopped) await waitStopped({ listen: previousListen, env });
277
- await atomicPlist(refs.plist, content);
278
- await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
279
- 'BRIDGE_LAUNCHCTL_BOOTSTRAP_FAILED', 'could not start bridge LaunchAgent');
280
- return waitReady({ config, instanceToken, env });
281
- }
282
-
283
- export async function disableBridgeLaunchAgent({ snapshot, listen, env = process.env,
284
- runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped } = {}) {
285
- if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean') {
286
- throw new TypeError('bridge LaunchAgent snapshot required');
287
- }
288
- const refs = bridgeLaunchAgentPaths(env);
289
- if (snapshot.loaded) {
290
- await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
291
- 'could not stop bridge LaunchAgent');
292
- await waitStopped({ listen, env });
293
- }
294
- await rm(refs.plist, { force: true });
295
- return { removed: snapshot.installed, stopped: snapshot.loaded };
296
- }
297
-
298
- export async function restoreBridgeLaunchAgent({ snapshot, listen = null, env = process.env,
299
- runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped,
300
- config = undefined, waitReady = defaultWaitReady } = {}) {
301
- if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean'
302
- || (snapshot.installed && typeof snapshot.content !== 'string')) {
303
- throw new TypeError('bridge LaunchAgent snapshot required');
304
- }
305
- const refs = bridgeLaunchAgentPaths(env);
306
- await prepareDirectory(refs.directory, uid);
307
- const stopped = await bootoutIfLoaded({ runner, uid });
308
- if (stopped) await waitStopped({ listen, env });
309
- if (snapshot.installed) await atomicPlist(refs.plist, snapshot.content);
310
- else await rm(refs.plist, { force: true });
311
- if (snapshot.loaded) {
312
- await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
313
- 'BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'could not restore bridge LaunchAgent');
314
- const restoredConfig = config ?? await readBridgeConfig({ env });
315
- const tokenMatch = snapshot.content.match(
316
- /<key>LATTICE_BRIDGE_INSTANCE_TOKEN<\/key>\s*<string>([0-9a-f]{64})<\/string>/u);
317
- if (restoredConfig?.enabled !== true || tokenMatch === null) {
318
- throw fail('BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'restored bridge LaunchAgent is not attestable');
319
- }
320
- await waitReady({ config: restoredConfig, instanceToken: tokenMatch[1], env });
321
- }
322
- return snapshot;
323
- }
1
+ import { execFile } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import {
5
+ chmod, lstat, mkdir, open, readFile, realpath, rename, rm, writeFile,
6
+ } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { promisify } from 'node:util';
9
+
10
+ import { BridgeConfigError, readBridgeConfig } from './bridge-config.mjs';
11
+ import { readBridgeDaemonDescriptor } from './bridge-daemon.mjs';
12
+ import { bridgeRegistrarSettings } from './bridge-registrar.mjs';
13
+
14
+ export const BRIDGE_LAUNCH_AGENT_LABEL = 'dev.kitepon.lattice.bridge';
15
+ const START_TIMEOUT_MS = 5_000;
16
+ const STOP_TIMEOUT_MS = 3_000;
17
+ const execFileAsync = promisify(execFile);
18
+
19
+ function fail(code, message, cause = undefined) {
20
+ return new BridgeConfigError(code, message, undefined, cause);
21
+ }
22
+
23
+ function userId() {
24
+ const uid = process.getuid?.();
25
+ if (!Number.isSafeInteger(uid) || uid < 0) {
26
+ throw fail('BRIDGE_LAUNCH_AGENT_UID_INVALID', 'current user id is unavailable');
27
+ }
28
+ return uid;
29
+ }
30
+
31
+ export function bridgeLaunchAgentPaths(env = process.env) {
32
+ const home = env.HOME;
33
+ if (typeof home !== 'string' || !path.isAbsolute(home)) {
34
+ throw fail('BRIDGE_LAUNCH_AGENT_HOME_INVALID', 'HOME must be an absolute path');
35
+ }
36
+ const directory = path.join(home, 'Library', 'LaunchAgents');
37
+ return Object.freeze({ directory,
38
+ plist: path.join(directory, `${BRIDGE_LAUNCH_AGENT_LABEL}.plist`) });
39
+ }
40
+
41
+ async function prepareDirectory(directory, uid = userId()) {
42
+ const home = path.dirname(path.dirname(directory));
43
+ const library = path.dirname(directory);
44
+ await mkdir(home, { recursive: true, mode: 0o700 });
45
+ for (const ref of [home, library, directory]) {
46
+ await mkdir(ref, { mode: 0o700 }).catch((error) => {
47
+ if (error?.code !== 'EEXIST') throw error;
48
+ });
49
+ const stats = await lstat(ref);
50
+ if (!stats.isDirectory() || stats.isSymbolicLink() || stats.uid !== uid
51
+ || (stats.mode & 0o022) !== 0) {
52
+ throw fail('BRIDGE_LAUNCH_AGENT_DIR_UNSAFE', 'LaunchAgents path is unsafe');
53
+ }
54
+ }
55
+ }
56
+
57
+ async function strictPlist(ref, uid = userId()) {
58
+ let before;
59
+ let handle;
60
+ try {
61
+ before = await lstat(ref);
62
+ if (!before.isFile() || before.isSymbolicLink() || before.uid !== uid
63
+ || (before.mode & 0o777) !== 0o600 || before.size > 65_536) {
64
+ throw new Error('unsafe plist');
65
+ }
66
+ handle = await open(ref, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
67
+ const opened = await handle.stat();
68
+ if (!opened.isFile() || opened.uid !== uid || opened.dev !== before.dev
69
+ || opened.ino !== before.ino || opened.size !== before.size) {
70
+ throw new Error('plist changed during validation');
71
+ }
72
+ const content = await handle.readFile('utf8');
73
+ const after = await lstat(ref);
74
+ if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size) {
75
+ throw new Error('plist changed during read');
76
+ }
77
+ return content;
78
+ } catch (error) {
79
+ if (error?.code === 'ENOENT' && before === undefined) return null;
80
+ throw fail('BRIDGE_LAUNCH_AGENT_PLIST_UNSAFE', 'bridge LaunchAgent plist is unsafe', error);
81
+ } finally {
82
+ await handle?.close();
83
+ }
84
+ }
85
+
86
+ async function atomicPlist(ref, content) {
87
+ const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
88
+ try {
89
+ await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
90
+ await rename(temporary, ref);
91
+ await chmod(ref, 0o600);
92
+ } finally {
93
+ await rm(temporary, { force: true });
94
+ }
95
+ }
96
+
97
+ function xml(value) {
98
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
99
+ .replaceAll('"', '&quot;').replaceAll("'", '&apos;');
100
+ }
101
+
102
+ async function executablePath(ref, label, { executable = true, uid = userId() } = {}) {
103
+ if (typeof ref !== 'string' || !path.isAbsolute(ref)) {
104
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} path must be absolute`);
105
+ }
106
+ let resolved;
107
+ let stats;
108
+ try {
109
+ resolved = await realpath(ref);
110
+ stats = await lstat(resolved);
111
+ } catch (error) {
112
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unavailable`, error);
113
+ }
114
+ if (!stats.isFile() || stats.isSymbolicLink() || ![0, uid].includes(stats.uid)
115
+ || (stats.mode & 0o022) !== 0
116
+ || executable && (stats.mode & 0o111) === 0) {
117
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unsafe`);
118
+ }
119
+ return resolved;
120
+ }
121
+
122
+ function plistDocument({ nodePath, bridgePath, instanceToken, env }) {
123
+ const environment = [['LATTICE_BRIDGE_INSTANCE_TOKEN', instanceToken]];
124
+ if (env.LATTICE_CONFIG_DIR !== undefined) {
125
+ if (typeof env.LATTICE_CONFIG_DIR !== 'string' || !path.isAbsolute(env.LATTICE_CONFIG_DIR)) {
126
+ throw fail('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
127
+ }
128
+ environment.push(['LATTICE_CONFIG_DIR', env.LATTICE_CONFIG_DIR]);
129
+ }
130
+ // The daemon registers its upstream on every new binding, but only if it can
131
+ // see the registrar settings. launchd does not inherit the shell environment,
132
+ // so without baking them in here the self-registration silently never fires —
133
+ // which is exactly the kind of quiet non-recovery this whole path exists to
134
+ // remove. `bridgeRegistrarSettings` rejects a half-configured pair rather than
135
+ // installing an agent that would skip registration forever.
136
+ const registrar = bridgeRegistrarSettings(env);
137
+ if (registrar !== null) {
138
+ environment.push(['LATTICE_BRIDGE_REGISTRAR_SSH_HOST', registrar.host]);
139
+ environment.push(['LATTICE_BRIDGE_REGISTRAR_SCRIPT', registrar.script]);
140
+ }
141
+ const environmentXml = environment.map(([key, value]) =>
142
+ ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join('\n');
143
+ return `<?xml version="1.0" encoding="UTF-8"?>
144
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
145
+ <plist version="1.0">
146
+ <dict>
147
+ <key>Label</key>
148
+ <string>${BRIDGE_LAUNCH_AGENT_LABEL}</string>
149
+ <key>ProgramArguments</key>
150
+ <array>
151
+ <string>${xml(nodePath)}</string>
152
+ <string>${xml(bridgePath)}</string>
153
+ </array>
154
+ <key>EnvironmentVariables</key>
155
+ <dict>
156
+ ${environmentXml}
157
+ </dict>
158
+ <key>RunAtLoad</key>
159
+ <true/>
160
+ <key>KeepAlive</key>
161
+ <true/>
162
+ <key>ThrottleInterval</key>
163
+ <integer>10</integer>
164
+ </dict>
165
+ </plist>
166
+ `;
167
+ }
168
+
169
+ export async function defaultLaunchctlRunner(args) {
170
+ try {
171
+ const result = await execFileAsync('/bin/launchctl', args, { encoding: 'utf8' });
172
+ return { code: 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
173
+ } catch (error) {
174
+ if (Number.isInteger(error?.code)) {
175
+ return { code: error.code, stdout: error.stdout ?? '', stderr: error.stderr ?? '' };
176
+ }
177
+ throw fail('BRIDGE_LAUNCHCTL_UNAVAILABLE', 'launchctl could not be executed', error);
178
+ }
179
+ }
180
+
181
+ function domain(uid) { return `gui/${uid}`; }
182
+ function service(uid) { return `${domain(uid)}/${BRIDGE_LAUNCH_AGENT_LABEL}`; }
183
+
184
+ async function launchctl(runner, args, code, message, accepted = [0]) {
185
+ let result;
186
+ try { result = await runner(args); } catch (error) {
187
+ if (error instanceof BridgeConfigError) throw error;
188
+ throw fail(code, message, error);
189
+ }
190
+ if (!result || !Number.isInteger(result.code) || !accepted.includes(result.code)) {
191
+ throw fail(code, message);
192
+ }
193
+ return result;
194
+ }
195
+
196
+ async function loadedState(runner, uid) {
197
+ const result = await launchctl(runner, ['print', service(uid)],
198
+ 'BRIDGE_LAUNCHCTL_STATUS_FAILED', 'could not inspect bridge LaunchAgent', [0, 113]);
199
+ return result.code === 0;
200
+ }
201
+
202
+ function healthHost(address) {
203
+ if (address === '0.0.0.0') return '127.0.0.1';
204
+ if (address === '::') return '[::1]';
205
+ return address.includes(':') ? `[${address}]` : address;
206
+ }
207
+
208
+ async function defaultWaitReady({ config, instanceToken, env, timeoutMs = START_TIMEOUT_MS }) {
209
+ const deadline = Date.now() + timeoutMs;
210
+ while (Date.now() < deadline) {
211
+ const descriptor = await readBridgeDaemonDescriptor({ env });
212
+ if (descriptor?.address === config.listen.address && descriptor?.port === config.listen.port
213
+ && descriptor?.config_updated_at === config.updated_at) {
214
+ try {
215
+ const response = await fetch(
216
+ `http://${healthHost(descriptor.address)}:${descriptor.port}/__lattice/bridge-health`, {
217
+ headers: { 'x-lattice-bridge-instance-token': instanceToken },
218
+ signal: AbortSignal.timeout(400),
219
+ });
220
+ const body = response.status === 200 ? await response.json() : null;
221
+ if (body?.schema === 'lattice.bridge_health.v1' && body.pid === descriptor.pid
222
+ && body.updated_at === config.updated_at) return descriptor;
223
+ } catch {}
224
+ }
225
+ await new Promise((resolve) => setTimeout(resolve, 50));
226
+ }
227
+ throw fail('BRIDGE_LAUNCH_AGENT_START_FAILED', 'bridge LaunchAgent did not become healthy');
228
+ }
229
+
230
+ async function defaultWaitStopped({ listen, timeoutMs = STOP_TIMEOUT_MS }) {
231
+ if (listen === null) return;
232
+ const deadline = Date.now() + timeoutMs;
233
+ while (Date.now() < deadline) {
234
+ try {
235
+ await fetch(`http://${healthHost(listen.address)}:${listen.port}/__lattice/bridge-health`,
236
+ { signal: AbortSignal.timeout(300) });
237
+ } catch { return; }
238
+ await new Promise((resolve) => setTimeout(resolve, 50));
239
+ }
240
+ throw fail('BRIDGE_LAUNCH_AGENT_STOP_FAILED', 'bridge LaunchAgent socket did not stop');
241
+ }
242
+
243
+ export async function snapshotBridgeLaunchAgent({ env = process.env,
244
+ runner = defaultLaunchctlRunner, uid = userId() } = {}) {
245
+ const refs = bridgeLaunchAgentPaths(env);
246
+ await prepareDirectory(refs.directory, uid);
247
+ const content = await strictPlist(refs.plist, uid);
248
+ const loaded = await loadedState(runner, uid);
249
+ if (loaded && content === null) {
250
+ throw fail('BRIDGE_LAUNCH_AGENT_STATE_INVALID', 'loaded bridge LaunchAgent has no owned plist');
251
+ }
252
+ return Object.freeze({ installed: content !== null, loaded, content });
253
+ }
254
+
255
+ async function bootoutIfLoaded({ runner, uid }) {
256
+ if (!await loadedState(runner, uid)) return false;
257
+ await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
258
+ 'could not stop bridge LaunchAgent');
259
+ return true;
260
+ }
261
+
262
+ export async function installBridgeLaunchAgent({ config, env = process.env,
263
+ runner = defaultLaunchctlRunner, uid = userId(), nodePath = process.execPath,
264
+ bridgePath = path.resolve(import.meta.dirname, '../bin/lattice-bridge.mjs'),
265
+ waitReady = defaultWaitReady, waitStopped = defaultWaitStopped,
266
+ previousListen = null } = {}) {
267
+ if (config?.enabled !== true) throw fail('BRIDGE_DISABLED', 'bridge is disabled');
268
+ const refs = bridgeLaunchAgentPaths(env);
269
+ await prepareDirectory(refs.directory, uid);
270
+ await strictPlist(refs.plist, uid);
271
+ const resolvedNode = await executablePath(nodePath, 'node executable', { uid });
272
+ const resolvedBridge = await executablePath(bridgePath, 'bridge executable', { executable: false, uid });
273
+ const instanceToken = randomBytes(32).toString('hex');
274
+ const content = plistDocument({ nodePath: resolvedNode, bridgePath: resolvedBridge, instanceToken, env });
275
+ const stopped = await bootoutIfLoaded({ runner, uid });
276
+ if (stopped) await waitStopped({ listen: previousListen, env });
277
+ await atomicPlist(refs.plist, content);
278
+ await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
279
+ 'BRIDGE_LAUNCHCTL_BOOTSTRAP_FAILED', 'could not start bridge LaunchAgent');
280
+ return waitReady({ config, instanceToken, env });
281
+ }
282
+
283
+ export async function disableBridgeLaunchAgent({ snapshot, listen, env = process.env,
284
+ runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped } = {}) {
285
+ if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean') {
286
+ throw new TypeError('bridge LaunchAgent snapshot required');
287
+ }
288
+ const refs = bridgeLaunchAgentPaths(env);
289
+ if (snapshot.loaded) {
290
+ await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
291
+ 'could not stop bridge LaunchAgent');
292
+ await waitStopped({ listen, env });
293
+ }
294
+ await rm(refs.plist, { force: true });
295
+ return { removed: snapshot.installed, stopped: snapshot.loaded };
296
+ }
297
+
298
+ export async function restoreBridgeLaunchAgent({ snapshot, listen = null, env = process.env,
299
+ runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped,
300
+ config = undefined, waitReady = defaultWaitReady } = {}) {
301
+ if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean'
302
+ || (snapshot.installed && typeof snapshot.content !== 'string')) {
303
+ throw new TypeError('bridge LaunchAgent snapshot required');
304
+ }
305
+ const refs = bridgeLaunchAgentPaths(env);
306
+ await prepareDirectory(refs.directory, uid);
307
+ const stopped = await bootoutIfLoaded({ runner, uid });
308
+ if (stopped) await waitStopped({ listen, env });
309
+ if (snapshot.installed) await atomicPlist(refs.plist, snapshot.content);
310
+ else await rm(refs.plist, { force: true });
311
+ if (snapshot.loaded) {
312
+ await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
313
+ 'BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'could not restore bridge LaunchAgent');
314
+ const restoredConfig = config ?? await readBridgeConfig({ env });
315
+ const tokenMatch = snapshot.content.match(
316
+ /<key>LATTICE_BRIDGE_INSTANCE_TOKEN<\/key>\s*<string>([0-9a-f]{64})<\/string>/u);
317
+ if (restoredConfig?.enabled !== true || tokenMatch === null) {
318
+ throw fail('BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'restored bridge LaunchAgent is not attestable');
319
+ }
320
+ await waitReady({ config: restoredConfig, instanceToken: tokenMatch[1], env });
321
+ }
322
+ return snapshot;
323
+ }