@quolu/lattice 0.1.0 → 0.12.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 (370) hide show
  1. package/README.md +87 -4
  2. package/bin/lattice-bridge.mjs +87 -0
  3. package/bin/lattice-dashboard.mjs +70 -0
  4. package/bin/lattice-mcp.mjs +9 -9
  5. package/bin/lattice.mjs +61 -8
  6. package/docs/bridge-setup.md +87 -0
  7. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -0
  8. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -0
  9. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -0
  10. package/package.json +19 -7
  11. package/sensor/dist/bin/command-supervision.d.ts +1 -1
  12. package/sensor/dist/bin/command-supervision.js +4 -4
  13. package/sensor/dist/bin/command-supervision.js.map +1 -1
  14. package/sensor/dist/bin/fatal-handler.js +2 -2
  15. package/sensor/dist/bin/fatal-handler.js.map +1 -1
  16. package/sensor/dist/bin/{codegraph.js → lattice-sensor.js} +207 -328
  17. package/sensor/dist/bin/node-version-check.d.ts +7 -5
  18. package/sensor/dist/bin/node-version-check.d.ts.map +1 -1
  19. package/sensor/dist/bin/node-version-check.js +19 -14
  20. package/sensor/dist/bin/node-version-check.js.map +1 -1
  21. package/sensor/dist/context/index.d.ts +1 -1
  22. package/sensor/dist/context/index.js +6 -6
  23. package/sensor/dist/context/index.js.map +1 -1
  24. package/sensor/dist/db/index.d.ts +5 -5
  25. package/sensor/dist/db/index.d.ts.map +1 -1
  26. package/sensor/dist/db/index.js +7 -7
  27. package/sensor/dist/db/index.js.map +1 -1
  28. package/sensor/dist/db/migrations.js +1 -1
  29. package/sensor/dist/db/migrations.js.map +1 -1
  30. package/sensor/dist/db/queries.d.ts +1 -1
  31. package/sensor/dist/db/queries.js +5 -5
  32. package/sensor/dist/db/queries.js.map +1 -1
  33. package/sensor/dist/db/schema.sql +2 -2
  34. package/sensor/dist/db/sqlite-adapter.d.ts +2 -2
  35. package/sensor/dist/db/sqlite-adapter.js +3 -3
  36. package/sensor/dist/db/sqlite-adapter.js.map +1 -1
  37. package/sensor/dist/db/wal-valve.d.ts +1 -1
  38. package/sensor/dist/db/wal-valve.d.ts.map +1 -1
  39. package/sensor/dist/db/wal-valve.js +2 -2
  40. package/sensor/dist/db/wal-valve.js.map +1 -1
  41. package/sensor/dist/directory.d.ts +27 -63
  42. package/sensor/dist/directory.d.ts.map +1 -1
  43. package/sensor/dist/directory.js +78 -134
  44. package/sensor/dist/directory.js.map +1 -1
  45. package/sensor/dist/errors.d.ts +15 -15
  46. package/sensor/dist/errors.d.ts.map +1 -1
  47. package/sensor/dist/errors.js +21 -21
  48. package/sensor/dist/errors.js.map +1 -1
  49. package/sensor/dist/extraction/dynamic-import.d.ts +1 -1
  50. package/sensor/dist/extraction/dynamic-import.js +1 -1
  51. package/sensor/dist/extraction/extraction-version.d.ts +1 -1
  52. package/sensor/dist/extraction/extraction-version.js +1 -1
  53. package/sensor/dist/extraction/generated-detection.d.ts +1 -1
  54. package/sensor/dist/extraction/generated-detection.js +1 -1
  55. package/sensor/dist/extraction/grammars.d.ts +3 -3
  56. package/sensor/dist/extraction/grammars.js +5 -5
  57. package/sensor/dist/extraction/grammars.js.map +1 -1
  58. package/sensor/dist/extraction/index.d.ts +6 -6
  59. package/sensor/dist/extraction/index.js +50 -50
  60. package/sensor/dist/extraction/index.js.map +1 -1
  61. package/sensor/dist/extraction/kernel/decode.d.ts +1 -1
  62. package/sensor/dist/extraction/kernel/decode.js +1 -1
  63. package/sensor/dist/extraction/kernel/index.d.ts +3 -3
  64. package/sensor/dist/extraction/kernel/index.js +6 -6
  65. package/sensor/dist/extraction/kernel/index.js.map +1 -1
  66. package/sensor/dist/extraction/kernel/layout.d.ts +1 -1
  67. package/sensor/dist/extraction/kernel/layout.js +1 -1
  68. package/sensor/dist/extraction/kernel/loader.d.ts +6 -6
  69. package/sensor/dist/extraction/kernel/loader.js +13 -13
  70. package/sensor/dist/extraction/kernel/loader.js.map +1 -1
  71. package/sensor/dist/extraction/languages/cfquery.d.ts +1 -1
  72. package/sensor/dist/extraction/languages/cfquery.js +1 -1
  73. package/sensor/dist/extraction/languages/lua.d.ts +11 -0
  74. package/sensor/dist/extraction/languages/lua.d.ts.map +1 -1
  75. package/sensor/dist/extraction/languages/lua.js +1 -0
  76. package/sensor/dist/extraction/languages/lua.js.map +1 -1
  77. package/sensor/dist/extraction/parse-pool.d.ts +5 -5
  78. package/sensor/dist/extraction/parse-pool.d.ts.map +1 -1
  79. package/sensor/dist/extraction/parse-pool.js +4 -4
  80. package/sensor/dist/extraction/parse-worker.js +1 -1
  81. package/sensor/dist/extraction/parse-worker.js.map +1 -1
  82. package/sensor/dist/extraction/store-writer.d.ts +1 -1
  83. package/sensor/dist/extraction/store-writer.js +1 -1
  84. package/sensor/dist/extraction/svelte-extractor.d.ts +1 -1
  85. package/sensor/dist/extraction/svelte-extractor.js +1 -1
  86. package/sensor/dist/extraction/tree-sitter-helpers.js +1 -1
  87. package/sensor/dist/extraction/tree-sitter.d.ts +2 -2
  88. package/sensor/dist/extraction/tree-sitter.d.ts.map +1 -1
  89. package/sensor/dist/extraction/tree-sitter.js +71 -4
  90. package/sensor/dist/extraction/tree-sitter.js.map +1 -1
  91. package/sensor/dist/extraction/wasm-runtime-flags.d.ts +2 -2
  92. package/sensor/dist/extraction/wasm-runtime-flags.d.ts.map +1 -1
  93. package/sensor/dist/extraction/wasm-runtime-flags.js +5 -5
  94. package/sensor/dist/extraction/wasm-runtime-flags.js.map +1 -1
  95. package/sensor/dist/index.d.ts +36 -36
  96. package/sensor/dist/index.d.ts.map +1 -1
  97. package/sensor/dist/index.js +71 -71
  98. package/sensor/dist/index.js.map +1 -1
  99. package/sensor/dist/mcp/daemon-manager.js +1 -1
  100. package/sensor/dist/mcp/daemon-paths.d.ts +3 -3
  101. package/sensor/dist/mcp/daemon-paths.js +7 -7
  102. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  103. package/sensor/dist/mcp/daemon-registry.d.ts +2 -2
  104. package/sensor/dist/mcp/daemon-registry.js +5 -5
  105. package/sensor/dist/mcp/daemon.d.ts +7 -7
  106. package/sensor/dist/mcp/daemon.d.ts.map +1 -1
  107. package/sensor/dist/mcp/daemon.js +21 -21
  108. package/sensor/dist/mcp/daemon.js.map +1 -1
  109. package/sensor/dist/mcp/dynamic-boundaries.js +1 -1
  110. package/sensor/dist/mcp/engine.d.ts +9 -9
  111. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  112. package/sensor/dist/mcp/engine.js +44 -44
  113. package/sensor/dist/mcp/engine.js.map +1 -1
  114. package/sensor/dist/mcp/index.d.ts +14 -14
  115. package/sensor/dist/mcp/index.d.ts.map +1 -1
  116. package/sensor/dist/mcp/index.js +41 -41
  117. package/sensor/dist/mcp/index.js.map +1 -1
  118. package/sensor/dist/mcp/liveness-watchdog.js +7 -7
  119. package/sensor/dist/mcp/liveness-watchdog.js.map +1 -1
  120. package/sensor/dist/mcp/ppid-watchdog.d.ts +3 -3
  121. package/sensor/dist/mcp/ppid-watchdog.js +2 -2
  122. package/sensor/dist/mcp/proxy.d.ts.map +1 -1
  123. package/sensor/dist/mcp/proxy.js +37 -37
  124. package/sensor/dist/mcp/proxy.js.map +1 -1
  125. package/sensor/dist/mcp/query-pool.d.ts +3 -3
  126. package/sensor/dist/mcp/query-pool.js +7 -7
  127. package/sensor/dist/mcp/query-pool.js.map +1 -1
  128. package/sensor/dist/mcp/query-worker.d.ts +2 -2
  129. package/sensor/dist/mcp/query-worker.js +7 -7
  130. package/sensor/dist/mcp/query-worker.js.map +1 -1
  131. package/sensor/dist/mcp/server-instructions.d.ts +10 -12
  132. package/sensor/dist/mcp/server-instructions.d.ts.map +1 -1
  133. package/sensor/dist/mcp/server-instructions.js +39 -37
  134. package/sensor/dist/mcp/server-instructions.js.map +1 -1
  135. package/sensor/dist/mcp/session.d.ts +2 -2
  136. package/sensor/dist/mcp/session.js +18 -18
  137. package/sensor/dist/mcp/session.js.map +1 -1
  138. package/sensor/dist/mcp/startup-handshake.d.ts +3 -3
  139. package/sensor/dist/mcp/startup-handshake.d.ts.map +1 -1
  140. package/sensor/dist/mcp/startup-handshake.js +3 -3
  141. package/sensor/dist/mcp/startup-handshake.js.map +1 -1
  142. package/sensor/dist/mcp/tools.d.ts +53 -53
  143. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  144. package/sensor/dist/mcp/tools.js +180 -216
  145. package/sensor/dist/mcp/tools.js.map +1 -1
  146. package/sensor/dist/mcp/transport.d.ts +1 -1
  147. package/sensor/dist/mcp/transport.js +6 -6
  148. package/sensor/dist/mcp/transport.js.map +1 -1
  149. package/sensor/dist/mcp/version.d.ts +2 -2
  150. package/sensor/dist/mcp/version.d.ts.map +1 -1
  151. package/sensor/dist/mcp/version.js +3 -3
  152. package/sensor/dist/mcp/version.js.map +1 -1
  153. package/sensor/dist/project-config.d.ts +6 -6
  154. package/sensor/dist/project-config.d.ts.map +1 -1
  155. package/sensor/dist/project-config.js +10 -10
  156. package/sensor/dist/project-config.js.map +1 -1
  157. package/sensor/dist/resolution/callback-synthesizer.js +4 -4
  158. package/sensor/dist/resolution/callback-synthesizer.js.map +1 -1
  159. package/sensor/dist/resolution/frameworks/drupal.d.ts +3 -3
  160. package/sensor/dist/resolution/frameworks/drupal.js +3 -3
  161. package/sensor/dist/resolution/frameworks/fabric.js +1 -1
  162. package/sensor/dist/resolution/frameworks/fabric.js.map +1 -1
  163. package/sensor/dist/resolution/frameworks/java.js +1 -1
  164. package/sensor/dist/resolution/frameworks/java.js.map +1 -1
  165. package/sensor/dist/resolution/frameworks/svelte.js +1 -1
  166. package/sensor/dist/resolution/frameworks/svelte.js.map +1 -1
  167. package/sensor/dist/resolution/goframe-synthesizer.d.ts +1 -1
  168. package/sensor/dist/resolution/goframe-synthesizer.js +1 -1
  169. package/sensor/dist/resolution/index.d.ts +1 -1
  170. package/sensor/dist/resolution/index.js +9 -9
  171. package/sensor/dist/resolution/index.js.map +1 -1
  172. package/sensor/dist/resolution/name-matcher.js +2 -2
  173. package/sensor/dist/resolution/name-matcher.js.map +1 -1
  174. package/sensor/dist/resolution/resolver-pool.d.ts +2 -2
  175. package/sensor/dist/resolution/resolver-pool.js +4 -4
  176. package/sensor/dist/resolution/resolver-pool.js.map +1 -1
  177. package/sensor/dist/resolution/resolver-worker.js +2 -2
  178. package/sensor/dist/resolution/resolver-worker.js.map +1 -1
  179. package/sensor/dist/resolution/workspace-packages.js +1 -1
  180. package/sensor/dist/resolution/workspace-packages.js.map +1 -1
  181. package/sensor/dist/search/identifier-segments.d.ts +1 -1
  182. package/sensor/dist/search/identifier-segments.js +1 -1
  183. package/sensor/dist/search/query-utils.d.ts +1 -0
  184. package/sensor/dist/search/query-utils.d.ts.map +1 -1
  185. package/sensor/dist/search/query-utils.js +10 -3
  186. package/sensor/dist/search/query-utils.js.map +1 -1
  187. package/sensor/dist/sync/git-hooks.d.ts +9 -9
  188. package/sensor/dist/sync/git-hooks.d.ts.map +1 -1
  189. package/sensor/dist/sync/git-hooks.js +15 -15
  190. package/sensor/dist/sync/git-hooks.js.map +1 -1
  191. package/sensor/dist/sync/watch-policy.d.ts +2 -2
  192. package/sensor/dist/sync/watch-policy.js +5 -5
  193. package/sensor/dist/sync/watch-policy.js.map +1 -1
  194. package/sensor/dist/sync/watcher.d.ts +2 -2
  195. package/sensor/dist/sync/watcher.d.ts.map +1 -1
  196. package/sensor/dist/sync/watcher.js +16 -16
  197. package/sensor/dist/sync/watcher.js.map +1 -1
  198. package/sensor/dist/sync/worktree.d.ts +5 -5
  199. package/sensor/dist/sync/worktree.d.ts.map +1 -1
  200. package/sensor/dist/sync/worktree.js +9 -9
  201. package/sensor/dist/sync/worktree.js.map +1 -1
  202. package/sensor/dist/telemetry/index.d.ts +8 -8
  203. package/sensor/dist/telemetry/index.d.ts.map +1 -1
  204. package/sensor/dist/telemetry/index.js +16 -16
  205. package/sensor/dist/telemetry/index.js.map +1 -1
  206. package/sensor/dist/types.d.ts +2 -2
  207. package/sensor/dist/types.js +1 -1
  208. package/sensor/dist/ui/color.d.ts +2 -2
  209. package/sensor/dist/ui/color.js +2 -2
  210. package/sensor/dist/ui/glyphs.d.ts +3 -3
  211. package/sensor/dist/ui/glyphs.js +7 -7
  212. package/sensor/dist/ui/glyphs.js.map +1 -1
  213. package/sensor/dist/utils.d.ts +4 -4
  214. package/sensor/dist/utils.js +8 -8
  215. package/sensor/dist/utils.js.map +1 -1
  216. package/sensor/package.json +8 -13
  217. package/src/artifact-contracts.mjs +2 -2
  218. package/src/boundary-compiler.mjs +28 -28
  219. package/src/boundary-observation-compiler-v2.mjs +10 -10
  220. package/src/bounded-seam.mjs +144 -0
  221. package/src/bridge-cli.mjs +227 -0
  222. package/src/bridge-config.mjs +346 -0
  223. package/src/bridge-daemon.mjs +328 -0
  224. package/src/bridge-launch-agent.mjs +311 -0
  225. package/src/bridge-server.mjs +309 -0
  226. package/src/cli-help.mjs +163 -0
  227. package/src/control-compiler.mjs +30 -30
  228. package/src/dag-chain.mjs +261 -0
  229. package/src/factory-diagnostics.mjs +8 -7
  230. package/src/hash-chain.mjs +76 -0
  231. package/src/node-version-guard.mjs +5 -4
  232. package/src/project-cli.mjs +392 -0
  233. package/src/project-identity.mjs +71 -0
  234. package/src/rc1-evidence-bundle.mjs +16 -16
  235. package/src/rc1-v4-campaign.mjs +15 -14
  236. package/src/rc1-v5-artifact-set.mjs +2 -2
  237. package/src/rc1-v5-campaign.mjs +15 -14
  238. package/src/rc1-v6-artifact-set.mjs +18 -18
  239. package/src/rc1-v6-campaign.mjs +16 -16
  240. package/src/rc1-v6-causal-binding.mjs +16 -14
  241. package/src/rc1-v6-measurement.mjs +20 -38
  242. package/src/rc2-artifact-set.mjs +45 -40
  243. package/src/rc2-campaign.mjs +48 -66
  244. package/src/rc2-delivery-policy-front-end.mjs +30 -30
  245. package/src/rc2-rc1-transfer-front-end.mjs +5 -5
  246. package/src/rc3-actual-dogfood.mjs +6 -6
  247. package/src/rc3-dogfood-scaffold.mjs +12 -7
  248. package/src/rc3-scripted-campaign.mjs +75 -21
  249. package/src/rc4-stage1-dogfood.mjs +24 -7
  250. package/src/runtime-cli.mjs +2424 -45
  251. package/src/runtime-contracts.mjs +7 -7
  252. package/src/runtime-control-store.mjs +547 -0
  253. package/src/runtime-controller-protocol.mjs +517 -0
  254. package/src/runtime-direct-os-observer.mjs +284 -0
  255. package/src/runtime-engine.mjs +2 -2
  256. package/src/runtime-errors.mjs +1 -1
  257. package/src/runtime-event-store.mjs +15 -43
  258. package/src/runtime-front-end.mjs +26 -26
  259. package/src/runtime-gate-store.mjs +477 -0
  260. package/src/runtime-hold-recompile.mjs +214 -23
  261. package/src/runtime-lifecycle-lock.mjs +290 -0
  262. package/src/runtime-managed-supervisor.mjs +1276 -0
  263. package/src/runtime-multi-epoch-store.mjs +761 -0
  264. package/src/runtime-projection.mjs +62 -0
  265. package/src/seam-transform.mjs +38 -38
  266. package/src/{codegraph-adapter.mjs → sensor-adapter.mjs} +7 -7
  267. package/src/sensor-cli.mjs +107 -0
  268. package/src/sensor-runtime.mjs +48 -0
  269. package/src/timestamp-contract.mjs +8 -0
  270. package/src/todo-chain.mjs +178 -0
  271. package/src/todo-cli.mjs +1032 -0
  272. package/src/todo-contracts.mjs +501 -0
  273. package/src/todo-dashboard-registry.mjs +318 -0
  274. package/src/todo-gantt-html.mjs +416 -0
  275. package/src/todo-gantt-layout.mjs +603 -0
  276. package/src/todo-gantt-live.mjs +269 -0
  277. package/src/todo-gantt-presentation.mjs +217 -0
  278. package/src/todo-gantt-svg.mjs +249 -0
  279. package/src/todo-markdown-renderer.mjs +260 -0
  280. package/src/todo-migration.mjs +260 -0
  281. package/src/todo-narrative-anchor.mjs +130 -0
  282. package/src/todo-revision.mjs +425 -0
  283. package/src/todo-status.mjs +340 -0
  284. package/src/todo-store.mjs +3451 -0
  285. package/src/treatment-compiler.mjs +28 -28
  286. package/src/treatment-runner.mjs +42 -44
  287. package/sensor/dist/bin/codegraph.d.ts +0 -26
  288. package/sensor/dist/bin/codegraph.d.ts.map +0 -1
  289. package/sensor/dist/bin/codegraph.js.map +0 -1
  290. package/sensor/dist/bin/uninstall.d.ts +0 -14
  291. package/sensor/dist/bin/uninstall.d.ts.map +0 -1
  292. package/sensor/dist/bin/uninstall.js +0 -36
  293. package/sensor/dist/bin/uninstall.js.map +0 -1
  294. package/sensor/dist/installer/beta-signup.d.ts +0 -54
  295. package/sensor/dist/installer/beta-signup.d.ts.map +0 -1
  296. package/sensor/dist/installer/beta-signup.js +0 -178
  297. package/sensor/dist/installer/beta-signup.js.map +0 -1
  298. package/sensor/dist/installer/config-writer.d.ts +0 -28
  299. package/sensor/dist/installer/config-writer.d.ts.map +0 -1
  300. package/sensor/dist/installer/config-writer.js +0 -91
  301. package/sensor/dist/installer/config-writer.js.map +0 -1
  302. package/sensor/dist/installer/index.d.ts +0 -142
  303. package/sensor/dist/installer/index.d.ts.map +0 -1
  304. package/sensor/dist/installer/index.js +0 -622
  305. package/sensor/dist/installer/index.js.map +0 -1
  306. package/sensor/dist/installer/instructions-template.d.ts +0 -41
  307. package/sensor/dist/installer/instructions-template.d.ts.map +0 -1
  308. package/sensor/dist/installer/instructions-template.js +0 -53
  309. package/sensor/dist/installer/instructions-template.js.map +0 -1
  310. package/sensor/dist/installer/targets/antigravity.d.ts +0 -57
  311. package/sensor/dist/installer/targets/antigravity.d.ts.map +0 -1
  312. package/sensor/dist/installer/targets/antigravity.js +0 -308
  313. package/sensor/dist/installer/targets/antigravity.js.map +0 -1
  314. package/sensor/dist/installer/targets/claude.d.ts +0 -62
  315. package/sensor/dist/installer/targets/claude.d.ts.map +0 -1
  316. package/sensor/dist/installer/targets/claude.js +0 -454
  317. package/sensor/dist/installer/targets/claude.js.map +0 -1
  318. package/sensor/dist/installer/targets/codex.d.ts +0 -18
  319. package/sensor/dist/installer/targets/codex.d.ts.map +0 -1
  320. package/sensor/dist/installer/targets/codex.js +0 -185
  321. package/sensor/dist/installer/targets/codex.js.map +0 -1
  322. package/sensor/dist/installer/targets/cursor.d.ts +0 -35
  323. package/sensor/dist/installer/targets/cursor.d.ts.map +0 -1
  324. package/sensor/dist/installer/targets/cursor.js +0 -254
  325. package/sensor/dist/installer/targets/cursor.js.map +0 -1
  326. package/sensor/dist/installer/targets/gemini.d.ts +0 -26
  327. package/sensor/dist/installer/targets/gemini.d.ts.map +0 -1
  328. package/sensor/dist/installer/targets/gemini.js +0 -165
  329. package/sensor/dist/installer/targets/gemini.js.map +0 -1
  330. package/sensor/dist/installer/targets/hermes.d.ts +0 -18
  331. package/sensor/dist/installer/targets/hermes.d.ts.map +0 -1
  332. package/sensor/dist/installer/targets/hermes.js +0 -359
  333. package/sensor/dist/installer/targets/hermes.js.map +0 -1
  334. package/sensor/dist/installer/targets/kiro.d.ts +0 -27
  335. package/sensor/dist/installer/targets/kiro.d.ts.map +0 -1
  336. package/sensor/dist/installer/targets/kiro.js +0 -178
  337. package/sensor/dist/installer/targets/kiro.js.map +0 -1
  338. package/sensor/dist/installer/targets/opencode.d.ts +0 -38
  339. package/sensor/dist/installer/targets/opencode.d.ts.map +0 -1
  340. package/sensor/dist/installer/targets/opencode.js +0 -288
  341. package/sensor/dist/installer/targets/opencode.js.map +0 -1
  342. package/sensor/dist/installer/targets/registry.d.ts +0 -35
  343. package/sensor/dist/installer/targets/registry.d.ts.map +0 -1
  344. package/sensor/dist/installer/targets/registry.js +0 -91
  345. package/sensor/dist/installer/targets/registry.js.map +0 -1
  346. package/sensor/dist/installer/targets/shared.d.ts +0 -101
  347. package/sensor/dist/installer/targets/shared.d.ts.map +0 -1
  348. package/sensor/dist/installer/targets/shared.js +0 -264
  349. package/sensor/dist/installer/targets/shared.js.map +0 -1
  350. package/sensor/dist/installer/targets/toml.d.ts +0 -52
  351. package/sensor/dist/installer/targets/toml.d.ts.map +0 -1
  352. package/sensor/dist/installer/targets/toml.js +0 -147
  353. package/sensor/dist/installer/targets/toml.js.map +0 -1
  354. package/sensor/dist/installer/targets/types.d.ts +0 -108
  355. package/sensor/dist/installer/targets/types.d.ts.map +0 -1
  356. package/sensor/dist/installer/targets/types.js +0 -16
  357. package/sensor/dist/installer/targets/types.js.map +0 -1
  358. package/sensor/dist/upgrade/index.d.ts +0 -171
  359. package/sensor/dist/upgrade/index.d.ts.map +0 -1
  360. package/sensor/dist/upgrade/index.js +0 -659
  361. package/sensor/dist/upgrade/index.js.map +0 -1
  362. package/sensor/dist/upgrade/remove-binary.d.ts +0 -87
  363. package/sensor/dist/upgrade/remove-binary.d.ts.map +0 -1
  364. package/sensor/dist/upgrade/remove-binary.js +0 -289
  365. package/sensor/dist/upgrade/remove-binary.js.map +0 -1
  366. package/sensor/dist/upgrade/update-check.d.ts +0 -92
  367. package/sensor/dist/upgrade/update-check.d.ts.map +0 -1
  368. package/sensor/dist/upgrade/update-check.js +0 -258
  369. package/sensor/dist/upgrade/update-check.js.map +0 -1
  370. package/src/bootstrap.mjs +0 -88
@@ -0,0 +1,311 @@
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
+
13
+ export const BRIDGE_LAUNCH_AGENT_LABEL = 'dev.kitepon.lattice.bridge';
14
+ const START_TIMEOUT_MS = 5_000;
15
+ const STOP_TIMEOUT_MS = 3_000;
16
+ const execFileAsync = promisify(execFile);
17
+
18
+ function fail(code, message, cause = undefined) {
19
+ return new BridgeConfigError(code, message, undefined, cause);
20
+ }
21
+
22
+ function userId() {
23
+ const uid = process.getuid?.();
24
+ if (!Number.isSafeInteger(uid) || uid < 0) {
25
+ throw fail('BRIDGE_LAUNCH_AGENT_UID_INVALID', 'current user id is unavailable');
26
+ }
27
+ return uid;
28
+ }
29
+
30
+ export function bridgeLaunchAgentPaths(env = process.env) {
31
+ const home = env.HOME;
32
+ if (typeof home !== 'string' || !path.isAbsolute(home)) {
33
+ throw fail('BRIDGE_LAUNCH_AGENT_HOME_INVALID', 'HOME must be an absolute path');
34
+ }
35
+ const directory = path.join(home, 'Library', 'LaunchAgents');
36
+ return Object.freeze({ directory,
37
+ plist: path.join(directory, `${BRIDGE_LAUNCH_AGENT_LABEL}.plist`) });
38
+ }
39
+
40
+ async function prepareDirectory(directory, uid = userId()) {
41
+ const home = path.dirname(path.dirname(directory));
42
+ const library = path.dirname(directory);
43
+ await mkdir(home, { recursive: true, mode: 0o700 });
44
+ for (const ref of [home, library, directory]) {
45
+ await mkdir(ref, { mode: 0o700 }).catch((error) => {
46
+ if (error?.code !== 'EEXIST') throw error;
47
+ });
48
+ const stats = await lstat(ref);
49
+ if (!stats.isDirectory() || stats.isSymbolicLink() || stats.uid !== uid
50
+ || (stats.mode & 0o022) !== 0) {
51
+ throw fail('BRIDGE_LAUNCH_AGENT_DIR_UNSAFE', 'LaunchAgents path is unsafe');
52
+ }
53
+ }
54
+ }
55
+
56
+ async function strictPlist(ref, uid = userId()) {
57
+ let before;
58
+ let handle;
59
+ try {
60
+ before = await lstat(ref);
61
+ if (!before.isFile() || before.isSymbolicLink() || before.uid !== uid
62
+ || (before.mode & 0o777) !== 0o600 || before.size > 65_536) {
63
+ throw new Error('unsafe plist');
64
+ }
65
+ handle = await open(ref, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
66
+ const opened = await handle.stat();
67
+ if (!opened.isFile() || opened.uid !== uid || opened.dev !== before.dev
68
+ || opened.ino !== before.ino || opened.size !== before.size) {
69
+ throw new Error('plist changed during validation');
70
+ }
71
+ const content = await handle.readFile('utf8');
72
+ const after = await lstat(ref);
73
+ if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size) {
74
+ throw new Error('plist changed during read');
75
+ }
76
+ return content;
77
+ } catch (error) {
78
+ if (error?.code === 'ENOENT' && before === undefined) return null;
79
+ throw fail('BRIDGE_LAUNCH_AGENT_PLIST_UNSAFE', 'bridge LaunchAgent plist is unsafe', error);
80
+ } finally {
81
+ await handle?.close();
82
+ }
83
+ }
84
+
85
+ async function atomicPlist(ref, content) {
86
+ const temporary = `${ref}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
87
+ try {
88
+ await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
89
+ await rename(temporary, ref);
90
+ await chmod(ref, 0o600);
91
+ } finally {
92
+ await rm(temporary, { force: true });
93
+ }
94
+ }
95
+
96
+ function xml(value) {
97
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
98
+ .replaceAll('"', '&quot;').replaceAll("'", '&apos;');
99
+ }
100
+
101
+ async function executablePath(ref, label, { executable = true, uid = userId() } = {}) {
102
+ if (typeof ref !== 'string' || !path.isAbsolute(ref)) {
103
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} path must be absolute`);
104
+ }
105
+ let resolved;
106
+ let stats;
107
+ try {
108
+ resolved = await realpath(ref);
109
+ stats = await lstat(resolved);
110
+ } catch (error) {
111
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unavailable`, error);
112
+ }
113
+ if (!stats.isFile() || stats.isSymbolicLink() || ![0, uid].includes(stats.uid)
114
+ || (stats.mode & 0o022) !== 0
115
+ || executable && (stats.mode & 0o111) === 0) {
116
+ throw fail('BRIDGE_LAUNCH_AGENT_EXECUTABLE_INVALID', `${label} is unsafe`);
117
+ }
118
+ return resolved;
119
+ }
120
+
121
+ function plistDocument({ nodePath, bridgePath, instanceToken, env }) {
122
+ const environment = [['LATTICE_BRIDGE_INSTANCE_TOKEN', instanceToken]];
123
+ if (env.LATTICE_CONFIG_DIR !== undefined) {
124
+ if (typeof env.LATTICE_CONFIG_DIR !== 'string' || !path.isAbsolute(env.LATTICE_CONFIG_DIR)) {
125
+ throw fail('BRIDGE_CONFIG_DIR_INVALID', 'LATTICE_CONFIG_DIR must be absolute');
126
+ }
127
+ environment.push(['LATTICE_CONFIG_DIR', env.LATTICE_CONFIG_DIR]);
128
+ }
129
+ const environmentXml = environment.map(([key, value]) =>
130
+ ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join('\n');
131
+ return `<?xml version="1.0" encoding="UTF-8"?>
132
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
133
+ <plist version="1.0">
134
+ <dict>
135
+ <key>Label</key>
136
+ <string>${BRIDGE_LAUNCH_AGENT_LABEL}</string>
137
+ <key>ProgramArguments</key>
138
+ <array>
139
+ <string>${xml(nodePath)}</string>
140
+ <string>${xml(bridgePath)}</string>
141
+ </array>
142
+ <key>EnvironmentVariables</key>
143
+ <dict>
144
+ ${environmentXml}
145
+ </dict>
146
+ <key>RunAtLoad</key>
147
+ <true/>
148
+ <key>KeepAlive</key>
149
+ <true/>
150
+ <key>ThrottleInterval</key>
151
+ <integer>10</integer>
152
+ </dict>
153
+ </plist>
154
+ `;
155
+ }
156
+
157
+ export async function defaultLaunchctlRunner(args) {
158
+ try {
159
+ const result = await execFileAsync('/bin/launchctl', args, { encoding: 'utf8' });
160
+ return { code: 0, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
161
+ } catch (error) {
162
+ if (Number.isInteger(error?.code)) {
163
+ return { code: error.code, stdout: error.stdout ?? '', stderr: error.stderr ?? '' };
164
+ }
165
+ throw fail('BRIDGE_LAUNCHCTL_UNAVAILABLE', 'launchctl could not be executed', error);
166
+ }
167
+ }
168
+
169
+ function domain(uid) { return `gui/${uid}`; }
170
+ function service(uid) { return `${domain(uid)}/${BRIDGE_LAUNCH_AGENT_LABEL}`; }
171
+
172
+ async function launchctl(runner, args, code, message, accepted = [0]) {
173
+ let result;
174
+ try { result = await runner(args); } catch (error) {
175
+ if (error instanceof BridgeConfigError) throw error;
176
+ throw fail(code, message, error);
177
+ }
178
+ if (!result || !Number.isInteger(result.code) || !accepted.includes(result.code)) {
179
+ throw fail(code, message);
180
+ }
181
+ return result;
182
+ }
183
+
184
+ async function loadedState(runner, uid) {
185
+ const result = await launchctl(runner, ['print', service(uid)],
186
+ 'BRIDGE_LAUNCHCTL_STATUS_FAILED', 'could not inspect bridge LaunchAgent', [0, 113]);
187
+ return result.code === 0;
188
+ }
189
+
190
+ function healthHost(address) {
191
+ if (address === '0.0.0.0') return '127.0.0.1';
192
+ if (address === '::') return '[::1]';
193
+ return address.includes(':') ? `[${address}]` : address;
194
+ }
195
+
196
+ async function defaultWaitReady({ config, instanceToken, env, timeoutMs = START_TIMEOUT_MS }) {
197
+ const deadline = Date.now() + timeoutMs;
198
+ while (Date.now() < deadline) {
199
+ const descriptor = await readBridgeDaemonDescriptor({ env });
200
+ if (descriptor?.address === config.listen.address && descriptor?.port === config.listen.port
201
+ && descriptor?.config_updated_at === config.updated_at) {
202
+ try {
203
+ const response = await fetch(
204
+ `http://${healthHost(descriptor.address)}:${descriptor.port}/__lattice/bridge-health`, {
205
+ headers: { 'x-lattice-bridge-instance-token': instanceToken },
206
+ signal: AbortSignal.timeout(400),
207
+ });
208
+ const body = response.status === 200 ? await response.json() : null;
209
+ if (body?.schema === 'lattice.bridge_health.v1' && body.pid === descriptor.pid
210
+ && body.updated_at === config.updated_at) return descriptor;
211
+ } catch {}
212
+ }
213
+ await new Promise((resolve) => setTimeout(resolve, 50));
214
+ }
215
+ throw fail('BRIDGE_LAUNCH_AGENT_START_FAILED', 'bridge LaunchAgent did not become healthy');
216
+ }
217
+
218
+ async function defaultWaitStopped({ listen, timeoutMs = STOP_TIMEOUT_MS }) {
219
+ if (listen === null) return;
220
+ const deadline = Date.now() + timeoutMs;
221
+ while (Date.now() < deadline) {
222
+ try {
223
+ await fetch(`http://${healthHost(listen.address)}:${listen.port}/__lattice/bridge-health`,
224
+ { signal: AbortSignal.timeout(300) });
225
+ } catch { return; }
226
+ await new Promise((resolve) => setTimeout(resolve, 50));
227
+ }
228
+ throw fail('BRIDGE_LAUNCH_AGENT_STOP_FAILED', 'bridge LaunchAgent socket did not stop');
229
+ }
230
+
231
+ export async function snapshotBridgeLaunchAgent({ env = process.env,
232
+ runner = defaultLaunchctlRunner, uid = userId() } = {}) {
233
+ const refs = bridgeLaunchAgentPaths(env);
234
+ await prepareDirectory(refs.directory, uid);
235
+ const content = await strictPlist(refs.plist, uid);
236
+ const loaded = await loadedState(runner, uid);
237
+ if (loaded && content === null) {
238
+ throw fail('BRIDGE_LAUNCH_AGENT_STATE_INVALID', 'loaded bridge LaunchAgent has no owned plist');
239
+ }
240
+ return Object.freeze({ installed: content !== null, loaded, content });
241
+ }
242
+
243
+ async function bootoutIfLoaded({ runner, uid }) {
244
+ if (!await loadedState(runner, uid)) return false;
245
+ await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
246
+ 'could not stop bridge LaunchAgent');
247
+ return true;
248
+ }
249
+
250
+ export async function installBridgeLaunchAgent({ config, env = process.env,
251
+ runner = defaultLaunchctlRunner, uid = userId(), nodePath = process.execPath,
252
+ bridgePath = path.resolve(import.meta.dirname, '../bin/lattice-bridge.mjs'),
253
+ waitReady = defaultWaitReady, waitStopped = defaultWaitStopped,
254
+ previousListen = null } = {}) {
255
+ if (config?.enabled !== true) throw fail('BRIDGE_DISABLED', 'bridge is disabled');
256
+ const refs = bridgeLaunchAgentPaths(env);
257
+ await prepareDirectory(refs.directory, uid);
258
+ await strictPlist(refs.plist, uid);
259
+ const resolvedNode = await executablePath(nodePath, 'node executable', { uid });
260
+ const resolvedBridge = await executablePath(bridgePath, 'bridge executable', { executable: false, uid });
261
+ const instanceToken = randomBytes(32).toString('hex');
262
+ const content = plistDocument({ nodePath: resolvedNode, bridgePath: resolvedBridge, instanceToken, env });
263
+ const stopped = await bootoutIfLoaded({ runner, uid });
264
+ if (stopped) await waitStopped({ listen: previousListen, env });
265
+ await atomicPlist(refs.plist, content);
266
+ await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
267
+ 'BRIDGE_LAUNCHCTL_BOOTSTRAP_FAILED', 'could not start bridge LaunchAgent');
268
+ return waitReady({ config, instanceToken, env });
269
+ }
270
+
271
+ export async function disableBridgeLaunchAgent({ snapshot, listen, env = process.env,
272
+ runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped } = {}) {
273
+ if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean') {
274
+ throw new TypeError('bridge LaunchAgent snapshot required');
275
+ }
276
+ const refs = bridgeLaunchAgentPaths(env);
277
+ if (snapshot.loaded) {
278
+ await launchctl(runner, ['bootout', service(uid)], 'BRIDGE_LAUNCHCTL_BOOTOUT_FAILED',
279
+ 'could not stop bridge LaunchAgent');
280
+ await waitStopped({ listen, env });
281
+ }
282
+ await rm(refs.plist, { force: true });
283
+ return { removed: snapshot.installed, stopped: snapshot.loaded };
284
+ }
285
+
286
+ export async function restoreBridgeLaunchAgent({ snapshot, listen = null, env = process.env,
287
+ runner = defaultLaunchctlRunner, uid = userId(), waitStopped = defaultWaitStopped,
288
+ config = undefined, waitReady = defaultWaitReady } = {}) {
289
+ if (!snapshot || typeof snapshot.installed !== 'boolean' || typeof snapshot.loaded !== 'boolean'
290
+ || (snapshot.installed && typeof snapshot.content !== 'string')) {
291
+ throw new TypeError('bridge LaunchAgent snapshot required');
292
+ }
293
+ const refs = bridgeLaunchAgentPaths(env);
294
+ await prepareDirectory(refs.directory, uid);
295
+ const stopped = await bootoutIfLoaded({ runner, uid });
296
+ if (stopped) await waitStopped({ listen, env });
297
+ if (snapshot.installed) await atomicPlist(refs.plist, snapshot.content);
298
+ else await rm(refs.plist, { force: true });
299
+ if (snapshot.loaded) {
300
+ await launchctl(runner, ['bootstrap', domain(uid), refs.plist],
301
+ 'BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'could not restore bridge LaunchAgent');
302
+ const restoredConfig = config ?? await readBridgeConfig({ env });
303
+ const tokenMatch = snapshot.content.match(
304
+ /<key>LATTICE_BRIDGE_INSTANCE_TOKEN<\/key>\s*<string>([0-9a-f]{64})<\/string>/u);
305
+ if (restoredConfig?.enabled !== true || tokenMatch === null) {
306
+ throw fail('BRIDGE_LAUNCHCTL_ROLLBACK_FAILED', 'restored bridge LaunchAgent is not attestable');
307
+ }
308
+ await waitReady({ config: restoredConfig, instanceToken: tokenMatch[1], env });
309
+ }
310
+ return snapshot;
311
+ }
@@ -0,0 +1,309 @@
1
+ import { createServer, request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import { lstat, open } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { parseTree } from 'jsonc-parser';
7
+
8
+ import {
9
+ BridgeConfigError, bridgeConfigPaths, normalizeBridgeAllowedHost, readBridgeConfig,
10
+ } from './bridge-config.mjs';
11
+
12
+ const HOP_BY_HOP = new Set([
13
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
14
+ 'te', 'trailer', 'transfer-encoding', 'upgrade',
15
+ ]);
16
+ const UNTRUSTED_CLIENT_IP_HEADERS = new Set([
17
+ 'cf-connecting-ip', 'client-ip', 'fastly-client-ip', 'true-client-ip',
18
+ 'x-cluster-client-ip', 'x-proxyuser-ip',
19
+ ]);
20
+
21
+ function dashboardRuntimeDir(env) {
22
+ const configured = env.LATTICE_DASHBOARD_RUNTIME_DIR;
23
+ return typeof configured === 'string' && path.isAbsolute(configured)
24
+ ? configured : path.join(bridgeConfigPaths(env).root, 'dashboard');
25
+ }
26
+
27
+ function duplicateJsonKey(node) {
28
+ if (node?.type === 'object') {
29
+ const keys = new Set();
30
+ for (const property of node.children ?? []) {
31
+ const [key, child] = property.children ?? [];
32
+ if (keys.has(key?.value) || duplicateJsonKey(child)) return true;
33
+ keys.add(key?.value);
34
+ }
35
+ } else if (node?.type === 'array') return (node.children ?? []).some(duplicateJsonKey);
36
+ return false;
37
+ }
38
+
39
+ async function readDashboardDescriptor(ref) {
40
+ let before;
41
+ let handle;
42
+ try {
43
+ before = await lstat(ref);
44
+ if (!before.isFile() || before.isSymbolicLink() || (before.mode & 0o777) !== 0o600 || before.size > 65_536) {
45
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'dashboard descriptor is unsafe');
46
+ }
47
+ handle = await open(ref, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
48
+ const opened = await handle.stat();
49
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino
50
+ || opened.size !== before.size || opened.size > 65_536) {
51
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'dashboard descriptor changed during validation');
52
+ }
53
+ const text = await handle.readFile('utf8');
54
+ const after = await lstat(ref);
55
+ if (after.dev !== opened.dev || after.ino !== opened.ino || after.size !== opened.size) {
56
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'dashboard descriptor changed during read');
57
+ }
58
+ const errors = [];
59
+ const tree = parseTree(text, errors, { allowTrailingComma: false, disallowComments: true });
60
+ if (errors.length > 0 || tree === undefined || duplicateJsonKey(tree)) {
61
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'dashboard descriptor JSON is invalid');
62
+ }
63
+ return JSON.parse(text);
64
+ } catch (error) {
65
+ if (error instanceof BridgeConfigError) throw error;
66
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_UNAVAILABLE', 'dashboard descriptor is unavailable', undefined, error);
67
+ } finally { await handle?.close(); }
68
+ }
69
+
70
+ export async function resolveBridgeUpstream(upstream, { env = process.env } = {}) {
71
+ if (upstream.mode === 'url') return new URL(upstream.url);
72
+ let descriptor;
73
+ try {
74
+ descriptor = await readDashboardDescriptor(path.join(dashboardRuntimeDir(env), 'daemon.json'));
75
+ } catch (error) {
76
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_UNAVAILABLE', 'dashboard descriptor is unavailable', undefined, error);
77
+ }
78
+ if (descriptor?.schema !== 'lattice.todo_dashboard_daemon.v1'
79
+ || Object.keys(descriptor).sort().join(',') !== 'pid,port,schema,started_at'
80
+ || !Number.isSafeInteger(descriptor.pid) || descriptor.pid <= 0
81
+ || !Number.isSafeInteger(descriptor.port) || descriptor.port <= 0 || descriptor.port > 65_535
82
+ || typeof descriptor.started_at !== 'string') {
83
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_INVALID', 'dashboard descriptor is invalid');
84
+ }
85
+ try {
86
+ const response = await fetch(`http://127.0.0.1:${descriptor.port}/__lattice/health`, {
87
+ signal: AbortSignal.timeout(500),
88
+ });
89
+ const health = response.status === 200 ? await response.json() : null;
90
+ if (health?.schema !== 'lattice.todo_dashboard_health.v1' || health.pid !== descriptor.pid
91
+ || health.port !== descriptor.port) throw new Error('dashboard health mismatch');
92
+ } catch (error) {
93
+ throw new BridgeConfigError('BRIDGE_UPSTREAM_UNAVAILABLE',
94
+ 'dashboard descriptor could not be attested against loopback health', undefined, error);
95
+ }
96
+ return new URL(`http://127.0.0.1:${descriptor.port}/`);
97
+ }
98
+
99
+ function responseError(response, status, code) {
100
+ if (response.headersSent) {
101
+ response.destroy();
102
+ return;
103
+ }
104
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
105
+ response.end(`${JSON.stringify({ schema: 'lattice.bridge_http_error.v1', code })}\n`);
106
+ }
107
+
108
+ function connectionTokens(headers) {
109
+ const value = headers.connection;
110
+ return new Set((Array.isArray(value) ? value.join(',') : value ?? '')
111
+ .split(',').map((entry) => entry.trim().toLowerCase()).filter(Boolean));
112
+ }
113
+
114
+ function forwardHeaders(headers) {
115
+ const nominated = connectionTokens(headers);
116
+ return Object.fromEntries(Object.entries(headers)
117
+ .filter(([name, value]) => value !== undefined && name !== 'host'
118
+ && name.toLowerCase() !== 'forwarded' && name.toLowerCase() !== 'x-real-ip'
119
+ && !name.toLowerCase().startsWith('x-forwarded-')
120
+ && !UNTRUSTED_CLIENT_IP_HEADERS.has(name.toLowerCase())
121
+ && !HOP_BY_HOP.has(name.toLowerCase()) && !nominated.has(name.toLowerCase())));
122
+ }
123
+
124
+ function validatedRequestHost(value) {
125
+ if (typeof value !== 'string' || value.length === 0 || value.length > 512
126
+ || /[\s\\/@,]/u.test(value)) {
127
+ throw new BridgeConfigError('BRIDGE_HOST_INVALID', 'request Host is invalid');
128
+ }
129
+ let parsed;
130
+ try { parsed = new URL(`http://${value}`); } catch {
131
+ throw new BridgeConfigError('BRIDGE_HOST_INVALID', 'request Host is invalid');
132
+ }
133
+ if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/'
134
+ || parsed.search !== '' || parsed.hash !== '') {
135
+ throw new BridgeConfigError('BRIDGE_HOST_INVALID', 'request Host is invalid');
136
+ }
137
+ const rawHostname = parsed.hostname.startsWith('[') && parsed.hostname.endsWith(']')
138
+ ? parsed.hostname.slice(1, -1) : parsed.hostname;
139
+ const hostname = normalizeBridgeAllowedHost(rawHostname);
140
+ const authorityHost = hostname.includes(':') ? `[${hostname}]` : hostname;
141
+ return { hostname, authority: parsed.port === '' ? authorityHost : `${authorityHost}:${parsed.port}` };
142
+ }
143
+
144
+ function forwardedHeaders(incoming, host) {
145
+ const remote = incoming.socket.remoteAddress ?? 'unknown';
146
+ const forwardedFor = remote.includes(':') ? `"[${remote}]"` : remote;
147
+ return {
148
+ forwarded: `for=${forwardedFor};host="${host.authority}";proto=http`,
149
+ 'x-forwarded-for': remote,
150
+ 'x-forwarded-host': host.authority,
151
+ 'x-forwarded-proto': 'http',
152
+ 'x-real-ip': remote,
153
+ };
154
+ }
155
+
156
+ function upstreamUrl(base, requestUrl) {
157
+ if (typeof requestUrl !== 'string' || requestUrl.includes('#') || !/^\/(?!\/)[^\s]*$/u.test(requestUrl)) {
158
+ throw new BridgeConfigError('BRIDGE_REQUEST_TARGET_INVALID', 'bridge requires an origin-form request target');
159
+ }
160
+ const rawPath = requestUrl.split('?', 1)[0];
161
+ if (rawPath.includes('\\') || rawPath.includes('%')) {
162
+ throw new BridgeConfigError('BRIDGE_REQUEST_TARGET_INVALID',
163
+ 'bridge request target contains encoded path bytes or a backslash');
164
+ }
165
+ if (rawPath.split('/').some((segment) => segment === '.' || segment === '..')) {
166
+ throw new BridgeConfigError('BRIDGE_REQUEST_TARGET_INVALID', 'bridge request target contains a dot segment');
167
+ }
168
+ const basePath = base.pathname.endsWith('/') ? base.pathname : `${base.pathname}/`;
169
+ const target = new URL(requestUrl.slice(1), base);
170
+ if (target.origin !== base.origin || !target.pathname.startsWith(basePath)) {
171
+ throw new BridgeConfigError('BRIDGE_REQUEST_TARGET_INVALID', 'bridge request target escapes upstream base');
172
+ }
173
+ return target;
174
+ }
175
+
176
+ function decodedRequestPath(requestUrl) {
177
+ if (typeof requestUrl !== 'string') return null;
178
+ try { return decodeURIComponent(requestUrl.split('?', 1)[0]); } catch { return null; }
179
+ }
180
+
181
+ export async function startBridgeServer({
182
+ config, env = process.env,
183
+ instanceToken = null,
184
+ resolveUpstream = (upstream) => resolveBridgeUpstream(upstream, { env }),
185
+ } = {}) {
186
+ if (config?.enabled !== true) throw new BridgeConfigError('BRIDGE_DISABLED', 'bridge is disabled');
187
+ if (!Array.isArray(config.allowed_hosts) || config.allowed_hosts.length === 0) {
188
+ throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge allowed hosts are required');
189
+ }
190
+ let allowedHosts = new Set(config.allowed_hosts);
191
+ let currentConfig = config;
192
+ const handleRequest = async (incoming, response) => {
193
+ let requestHost;
194
+ try { requestHost = validatedRequestHost(incoming.headers.host); } catch (error) {
195
+ responseError(response, 400, error?.code ?? 'BRIDGE_HOST_INVALID');
196
+ return;
197
+ }
198
+ if (!allowedHosts.has(requestHost.hostname)) {
199
+ responseError(response, 421, 'BRIDGE_HOST_NOT_ALLOWED');
200
+ return;
201
+ }
202
+ if (incoming.url === '/__lattice/bridge-health') {
203
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
204
+ const attested = typeof instanceToken === 'string'
205
+ && incoming.headers['x-lattice-bridge-instance-token'] === instanceToken;
206
+ response.end(`${JSON.stringify(attested
207
+ ? { schema: 'lattice.bridge_health.v1', pid: process.pid,
208
+ address: currentConfig.listen.address, port: currentConfig.listen.port,
209
+ updated_at: currentConfig.updated_at ?? null }
210
+ : { schema: 'lattice.bridge_health.v1', status: 'available' })}\n`);
211
+ return;
212
+ }
213
+ if (decodedRequestPath(incoming.url) === '/__lattice/health') {
214
+ responseError(response, 404, 'BRIDGE_INTERNAL_PATH_DENIED');
215
+ return;
216
+ }
217
+ let target;
218
+ try { target = upstreamUrl(await resolveUpstream(currentConfig.upstream), incoming.url); } catch (error) {
219
+ responseError(response, error?.code === 'BRIDGE_REQUEST_TARGET_INVALID' ? 400 : 503,
220
+ error?.code ?? 'BRIDGE_UPSTREAM_UNAVAILABLE');
221
+ return;
222
+ }
223
+ let upstreamResponse = null;
224
+ const request = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, {
225
+ method: incoming.method,
226
+ headers: { ...forwardHeaders(incoming.headers), ...forwardedHeaders(incoming, requestHost), host: target.host },
227
+ }, (incomingResponse) => {
228
+ upstreamResponse = incomingResponse;
229
+ response.writeHead(incomingResponse.statusCode ?? 502, forwardHeaders(incomingResponse.headers));
230
+ incomingResponse.once('error', () => response.destroy());
231
+ incomingResponse.pipe(response);
232
+ });
233
+ request.once('error', (error) => responseError(response, 502,
234
+ error?.code === 'ECONNREFUSED' ? 'BRIDGE_UPSTREAM_REFUSED' : 'BRIDGE_PROXY_FAILED'));
235
+ incoming.once('aborted', () => request.destroy());
236
+ response.once('close', () => {
237
+ if (!response.writableFinished) {
238
+ request.destroy();
239
+ upstreamResponse?.destroy();
240
+ }
241
+ });
242
+ incoming.pipe(request);
243
+ };
244
+ const server = createServer((incoming, response) => {
245
+ handleRequest(incoming, response).catch((error) => responseError(response, 500,
246
+ error?.code ?? 'BRIDGE_REQUEST_FAILED'));
247
+ });
248
+ await new Promise((resolve, reject) => {
249
+ server.once('error', reject);
250
+ server.listen({ host: config.listen.address, port: config.listen.port, exclusive: true }, resolve);
251
+ }).catch((error) => {
252
+ throw new BridgeConfigError(error?.code === 'EADDRINUSE' ? 'BRIDGE_PORT_UNAVAILABLE' : 'BRIDGE_BIND_FAILED',
253
+ 'bridge listen failed', { ...config.listen }, error);
254
+ });
255
+ let closed = false;
256
+ return Object.freeze({
257
+ address: config.listen.address,
258
+ port: config.listen.port,
259
+ updateConfig(next) {
260
+ if (next?.enabled !== true || next.listen.address !== config.listen.address
261
+ || next.listen.port !== config.listen.port) {
262
+ throw new BridgeConfigError('BRIDGE_RECONFIGURE_INVALID', 'live bridge binding cannot be mutated in place');
263
+ }
264
+ currentConfig = next;
265
+ allowedHosts = new Set(next.allowed_hosts);
266
+ },
267
+ close: async () => {
268
+ if (closed) return;
269
+ closed = true;
270
+ const completion = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
271
+ server.closeAllConnections?.();
272
+ await completion;
273
+ },
274
+ });
275
+ }
276
+
277
+ export function bridgeRuntimeController({ env = process.env, instanceToken = null } = {}) {
278
+ let active = null;
279
+ let fingerprint = null;
280
+ return Object.freeze({
281
+ async reconcile() {
282
+ const config = await readBridgeConfig({ env });
283
+ const next = config === null || !config.enabled ? null : JSON.stringify(config);
284
+ if (next === fingerprint) return active;
285
+ if (next === null) {
286
+ await active?.close();
287
+ active = null;
288
+ fingerprint = null;
289
+ return null;
290
+ }
291
+ if (active !== null && active.address === config.listen.address && active.port === config.listen.port) {
292
+ active.updateConfig(config);
293
+ fingerprint = next;
294
+ return active;
295
+ }
296
+ const replacement = await startBridgeServer({ config, env, instanceToken });
297
+ const previous = active;
298
+ active = replacement;
299
+ fingerprint = next;
300
+ await previous?.close();
301
+ return active;
302
+ },
303
+ async close() {
304
+ await active?.close();
305
+ active = null;
306
+ fingerprint = null;
307
+ },
308
+ });
309
+ }