@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.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 (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -18,21 +18,50 @@
18
18
  */
19
19
  import crypto from "node:crypto";
20
20
  import type { Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
21
+ import type { ResolvedPreviewOrigins } from "@blackbelt-technology/pi-dashboard-shared/preview-origins.js";
21
22
  import type { Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
22
23
  import type { TokenPayload } from "../auth/auth.js";
24
+ import { isLocallyTrusted } from "../auth/localhost-guard.js";
25
+ import { CAPABILITY_SEGMENT, redactCapability } from "./capability-redact.js";
26
+ import { generatePreviewLabel, hashPreviewKey, splitCanonicalHost } from "./preview-origin.js";
27
+ import { parsePreviewPath } from "./preview-path.js";
23
28
 
24
29
  // Lifetime note: a capability's life is bounded by its own idle/absolute limits and
25
30
  // by revocation (target removed, device revoked, logout / passkey revoke, restart).
26
31
  // It is deliberately independent of the minting session JWT's natural `exp`.
27
32
  export const CAPABILITY_IDLE_MS = 30 * 60_000;
28
33
  export const CAPABILITY_MAX_MS = 12 * 60 * 60_000;
34
+ /** Static-target tokens live shorter: 10 min idle / 2 h absolute. See change: improve-canvas-html-and-url-ux (D3). */
35
+ export const STATIC_CAPABILITY_IDLE_MS = 10 * 60_000;
36
+ export const STATIC_CAPABILITY_MAX_MS = 2 * 60 * 60_000;
37
+ /** Allow-once origins kept per viewer, and viewers kept (oldest viewer dropped first). */
38
+ const MAX_ALLOW_ONCE_PER_VIEWER = 32;
39
+ const MAX_ALLOW_ONCE_VIEWERS = 256;
29
40
  /** Hard cap on live tokens (oldest dropped): a loop minting tokens cannot grow memory. */
30
41
  const MAX_TOKENS = 1024;
31
42
  /** Live tokens per minting principal: one caller's mint loop evicts only ITS OWN oldest tokens. */
32
43
  const MAX_TOKENS_PER_PRINCIPAL = 64;
33
- /** `/~c/<token>` anywhere in a path or `Referer`. Tokens are base64url. */
34
- const CAPABILITY_SEGMENT = /\/~c\/[A-Za-z0-9_-]+/g;
35
44
  const TOKEN_SHAPE = /^[A-Za-z0-9_-]{22,}$/;
45
+ /** A mint for tiers 1-4 returns the live entry only while MORE than this remains: twice the 10-minute client re-mint lead (D2). */
46
+ const REUSE_MIN_REMAINING_MS = 20 * 60_000;
47
+ /** The store owns an `unref()`'d sweep so idle entries (and their pool ports) release without waiting for a mint (Q12). */
48
+ const SWEEP_INTERVAL_MS = 60_000;
49
+ /** Attempts to find a label not already in the index before the mint fails. */
50
+ const LABEL_RETRIES = 8;
51
+
52
+ /** Capability tier: 1-4 are origin-bound previews (D1), 5 the stable `/preview/<pid>/` path (D8, `PreviewPathStore`); `legacy` is the `/live/<id>/~c/<token>/` path. */
53
+ export type CapabilityTier = 1 | 2 | 3 | 4 | 5 | "legacy";
54
+
55
+ /** Why an entry left the store — the `onDelete` reason (D5, D13). */
56
+ export type CapabilityDeleteReason =
57
+ | "idle"
58
+ | "max"
59
+ | "revoked"
60
+ | "evicted"
61
+ | "disabled"
62
+ | "shutdown"
63
+ | "config-changed"
64
+ | "listener-error";
36
65
 
37
66
  /** Who minted a capability — the identity and tier an accepted request carries. */
38
67
  export interface CapabilityPrincipal {
@@ -54,11 +83,102 @@ export interface CapabilityPrincipal {
54
83
  identityExpiresAt?: number;
55
84
  }
56
85
 
57
- interface Entry {
86
+ /** Egress policy a token carries. Fail-closed default: `restricted`, scripts off. */
87
+ export interface LivePolicy {
88
+ egress: "open" | "restricted";
89
+ scripts: boolean;
90
+ }
91
+
92
+ /** Whether the target is a loopback port target or a static document root. */
93
+ export type LiveTargetKind = "port" | "static";
94
+
95
+ /** Dashboard exposure when a token was minted. */
96
+ export type LiveExposure = "local-only" | "exposed";
97
+
98
+ /** Opaque id for a client-generated viewer instance (carries allow-once sets across re-mints). */
99
+ const VIEWER_ID_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
100
+ export const isViewerId = (v: unknown): v is string => typeof v === "string" && VIEWER_ID_SHAPE.test(v);
101
+
102
+ export interface LiveCapabilityEntry {
58
103
  targetId: string;
59
104
  principal: CapabilityPrincipal;
60
105
  mintedAt: number;
61
106
  lastUsedAt: number;
107
+ /** Non-secret handle distinct from the token (touch / egress / allow-once address tokens by it). */
108
+ tokenId: string;
109
+ kind: LiveTargetKind;
110
+ policy: LivePolicy;
111
+ viewerId?: string;
112
+ /** Identity of the minting principal ({@link principalKeyOf}); egress/touch/allow-once check it. */
113
+ minterKey: string;
114
+ /** Exposure at mint time (a restricted scripted token minted `local-only` dies on the flip to `exposed`). */
115
+ mintExposure: LiveExposure;
116
+ /** Minted by a genuinely local caller: valid only from genuinely local requests. */
117
+ localBound: boolean;
118
+ idleMs: number;
119
+ maxMs: number;
120
+ /** `legacy` for a `/live/<id>/~c/<token>/` path; 1-4 for an origin-bound preview (D2). */
121
+ tier: CapabilityTier;
122
+ /** Canonical `host[:port]` of the preview origin (tiers 1-4). Lookup key together with the label hash. */
123
+ originHost?: string;
124
+ /** Full origin (`scheme://originHost`). CSP sources come from here, never from the request (D6). Memory only. */
125
+ origin?: string;
126
+ /** Plaintext label (tiers 1, 2, 4). Memory only: never persisted, never logged unredacted. */
127
+ label?: string;
128
+ /** Canonical `Origin` of the mint request (fallback `scheme://Host`): who may frame this origin. */
129
+ ancestors: string[];
130
+ /** Tier 3: the pool port the listener is bound to. */
131
+ poolPort?: number;
132
+ }
133
+ type Entry = LiveCapabilityEntry;
134
+
135
+ /** What the capability hook / proxy learn about a validated token. Never contains the secret. */
136
+ export interface LiveCapabilityGrant {
137
+ targetId: string;
138
+ tokenId: string;
139
+ kind: LiveTargetKind;
140
+ policy: LivePolicy;
141
+ viewerId?: string;
142
+ minterKey: string;
143
+ principal: CapabilityPrincipal;
144
+ tier: CapabilityTier;
145
+ origin?: string;
146
+ originHost?: string;
147
+ poolPort?: number;
148
+ ancestors: string[];
149
+ }
150
+
151
+ /** Origin binding of a mint for tiers 1-4 (D1, D2). */
152
+ interface PreviewMintBinding {
153
+ tier: 1 | 2 | 3 | 4;
154
+ /** Canonical `Origin` of the mint request (fallback `scheme://Host`). */
155
+ ancestors: string[];
156
+ /** Tiers 1, 2, 4: builds the origin from a freshly generated label. */
157
+ buildOrigin?: (label: string) => { origin: string; originHost: string };
158
+ /** Tier 3: the bound listener's origin (`http://<ip>:<port>`), `host:port`, and port. */
159
+ fixed?: { origin: string; originHost: string; poolPort: number };
160
+ }
161
+
162
+ export interface MintOptions {
163
+ /** Origin binding for tiers 1-4; absent = legacy path token. */
164
+ preview?: PreviewMintBinding;
165
+ kind?: LiveTargetKind;
166
+ policy?: Partial<LivePolicy>;
167
+ viewerId?: string;
168
+ exposure?: LiveExposure;
169
+ /**
170
+ * The minting request was genuinely local (loopback peer, no forwarding header) and the
171
+ * minter held no revocable credential: the token then works only from genuinely local
172
+ * requests. Decided by the mint route from the request — never inferred from the principal
173
+ * kind, which is also `local` for an identity principal reaching the dashboard remotely.
174
+ */
175
+ localBound?: boolean;
176
+ }
177
+
178
+ /** Request-boundary facts the store cannot know itself. */
179
+ export interface ValidateContext {
180
+ /** Is the request genuinely local (loopback peer, no forwarding header)? */
181
+ genuinelyLocal: boolean;
62
182
  }
63
183
 
64
184
  export interface LiveCapabilityStoreOptions {
@@ -67,105 +187,537 @@ export interface LiveCapabilityStoreOptions {
67
187
  isPrincipalLive?: (principal: CapabilityPrincipal) => boolean;
68
188
  /** Is the target still registered? */
69
189
  isTargetLive?: (targetId: string) => boolean;
190
+ /**
191
+ * Called ONCE per entry, after it has left every index, on every deletion path
192
+ * (idle/max, revoke, eviction, `enabled` flip, shutdown, listener error). Closes pool listeners.
193
+ * A throwing hook is logged (redacted) and never blocks the other deletions.
194
+ */
195
+ onDelete?: (entry: Readonly<LiveCapabilityEntry>, reason: CapabilityDeleteReason) => void;
196
+ /** Resolved preview-origin config; entries it no longer covers are revoked on every sweep (D12, Q8). */
197
+ getPreviewConfig?: () => ResolvedPreviewOrigins | undefined;
198
+ /** Random bytes source for labels (tests inject collisions). */
199
+ labelBytes?: (n: number) => Buffer;
200
+ /** Sweep interval; default 60 s (tests drive it with fake timers). */
201
+ sweepIntervalMs?: number;
70
202
  }
71
203
 
204
+ /** A host-keyed lookup result. Refusals carry the ONLY detail logs may show; the HTTP answer is identical for all. */
205
+ export type HostLookup =
206
+ | { ok: true; grant: LiveCapabilityGrant }
207
+ | { ok: false; reason: "unknown" | "expired" | "wrong-host" | "wrong-port" };
208
+
72
209
  /** Stable identity of a minting principal (device id, session key, else the shared "local"/"network" bucket). */
73
210
  const principalKey = (p: CapabilityPrincipal): string =>
74
211
  p.deviceId ? `device:${p.deviceId}` : p.sessionKey ? `session:${p.sessionKey}` : p.kind;
75
212
 
76
- const hash = (token: string): string => crypto.createHash("sha256").update(token).digest("hex");
213
+ /** Stable identity of a minting principal; the egress / touch / allow-once routes compare it. */
214
+ export const principalKeyOf = principalKey;
215
+
216
+ const hash = hashPreviewKey;
77
217
 
78
218
  /** sha256 of a session cookie value, for {@link CapabilityPrincipal.sessionKey}. */
79
219
  export function sessionKeyOf(cookieValue: string): string {
80
220
  return hash(cookieValue);
81
221
  }
82
222
 
223
+ const sameList = (a: readonly string[], b: readonly string[]): boolean =>
224
+ a.length === b.length && a.every((v, i) => v === b[i]);
225
+
226
+ /** Does `entry` still fall under the tier's CURRENT resolved config? (Tier 1 needs none.) */
227
+ function entryMatchesConfig(e: Entry, cfg: ResolvedPreviewOrigins): boolean {
228
+ if (e.tier === "legacy" || e.tier === 1) return true;
229
+ if (e.tier === 3) return !!cfg.pool && e.poolPort !== undefined && e.poolPort >= cfg.pool.from && e.poolPort <= cfg.pool.to;
230
+ const host = e.originHost ? splitCanonicalHost(e.originHost) : undefined;
231
+ if (!host) return false;
232
+ if (e.tier === 2) {
233
+ const w = cfg.wildcard;
234
+ if (!w || !e.label) return false;
235
+ return host.hostname === `${e.label}.${w.suffix}` && host.port === w.port && !!e.origin?.startsWith(`${w.scheme}://`);
236
+ }
237
+ // tier 4
238
+ return !!cfg.ipDnsSuffix && host.hostname.endsWith(`.${cfg.ipDnsSuffix}`);
239
+ }
240
+
83
241
  export class LiveCapabilityStore {
242
+ /** `hash(secret)` → entry. The secret is the label (tiers 1, 2, 4) or a random token (tier 3, legacy). */
84
243
  private readonly entries = new Map<string, Entry>();
244
+ /** `hash(originHost)` → entry key (tiers 1-4): the dynamic admission set; holds no plaintext label. */
245
+ private readonly byOriginHost = new Map<string, string>();
246
+ /** viewerId → allow-once origins (insertion-ordered, bounded). */
247
+ private readonly allowOnce = new Map<string, Set<string>>();
85
248
  private readonly now: () => number;
86
249
  private readonly isPrincipalLive: (p: CapabilityPrincipal) => boolean;
87
250
  private readonly isTargetLive: (id: string) => boolean;
251
+ private readonly onDelete?: LiveCapabilityStoreOptions["onDelete"];
252
+ private readonly getPreviewConfig?: () => ResolvedPreviewOrigins | undefined;
253
+ private readonly labelBytes?: (n: number) => Buffer;
254
+ private readonly sweepIntervalMs: number;
255
+ private sweeper: ReturnType<typeof setInterval> | undefined;
88
256
 
89
257
  constructor(opts: LiveCapabilityStoreOptions = {}) {
90
258
  this.now = opts.now ?? Date.now;
91
259
  this.isPrincipalLive = opts.isPrincipalLive ?? (() => true);
92
260
  this.isTargetLive = opts.isTargetLive ?? (() => true);
261
+ this.onDelete = opts.onDelete;
262
+ this.getPreviewConfig = opts.getPreviewConfig;
263
+ this.labelBytes = opts.labelBytes;
264
+ this.sweepIntervalMs = opts.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
265
+ }
266
+
267
+ /**
268
+ * A live entry a new mint for tiers 1-4 may be answered with (D2 re-mint reuse): same target, minter,
269
+ * policy, tier and ancestors (never `viewerId`: the viewer mints a fresh id per mount), with MORE than
270
+ * 20 minutes of absolute lifetime left. Never resurrects an expired / revoked entry. Tier 3 callers
271
+ * check this BEFORE allocating a pool port.
272
+ */
273
+ findReusable(
274
+ targetId: string,
275
+ principal: CapabilityPrincipal,
276
+ opts: MintOptions,
277
+ ): { entry: Readonly<Entry>; grant: LiveCapabilityGrant } | null {
278
+ const b = opts.preview;
279
+ if (!b) return null;
280
+ const now = this.now();
281
+ const kind: LiveTargetKind = opts.kind === "static" ? "static" : "port";
282
+ const egress = opts.policy?.egress === "open" ? "open" : "restricted";
283
+ const scripts = opts.policy?.scripts === true;
284
+ const who = principalKey(principal);
285
+ for (const [key, e] of this.entries) {
286
+ if (e.tier !== b.tier || e.targetId !== targetId || e.minterKey !== who || e.kind !== kind) continue;
287
+ if (e.policy.egress !== egress || e.policy.scripts !== scripts) continue;
288
+ if (e.localBound !== (opts.localBound === true) || e.mintExposure !== (opts.exposure ?? "exposed")) continue;
289
+ if (!sameList(e.ancestors, b.ancestors)) continue;
290
+ if (this.expiryReason(e, now)) continue;
291
+ if (e.mintedAt + e.maxMs - now <= REUSE_MIN_REMAINING_MS) continue;
292
+ if (!this.isTargetLive(e.targetId) || !this.isPrincipalLive(e.principal)) {
293
+ this.remove(key, "revoked");
294
+ continue;
295
+ }
296
+ return { entry: e, grant: grantOf(e) };
297
+ }
298
+ return null;
93
299
  }
94
300
 
95
- /** Mint a token for `targetId`. Only its hash is kept. */
96
- mint(targetId: string, principal: CapabilityPrincipal): { token: string; expiresAt: number } {
301
+ /**
302
+ * Mint a capability for `targetId`. Only a hash is kept. The policy is fail-closed
303
+ * (`restricted`, scripts off) unless the caller states otherwise; static targets
304
+ * get the shorter 10 min / 2 h lifetime.
305
+ *
306
+ * With `opts.preview` (tiers 1-4) the entry is bound to its origin: tiers 1, 2, 4 generate a
307
+ * 128-bit label (re-drawn on a collision) and `token` is that label; a mint that matches a live
308
+ * entry (see {@link findReusable}) returns it with `reused: true`.
309
+ */
310
+ mint(
311
+ targetId: string,
312
+ principal: CapabilityPrincipal,
313
+ opts: MintOptions = {},
314
+ ): {
315
+ token: string;
316
+ tokenId: string;
317
+ expiresAt: number;
318
+ policy: LivePolicy;
319
+ tier: CapabilityTier;
320
+ origin?: string;
321
+ originHost?: string;
322
+ poolPort?: number;
323
+ reused: boolean;
324
+ } {
97
325
  const now = this.now();
98
326
  this.sweep(now);
99
- const token = crypto.randomBytes(32).toString("base64url");
100
- this.entries.set(hash(token), { targetId, principal, mintedAt: now, lastUsedAt: now });
101
- // Evict within the minting principal first, so a mint loop cannot push out
102
- // another user's active preview tokens.
103
- const who = principalKey(principal);
104
- let mine = [...this.entries].filter(([, e]) => principalKey(e.principal) === who);
105
- while (mine.length > MAX_TOKENS_PER_PRINCIPAL) {
106
- this.entries.delete(mine[0][0]);
107
- mine = mine.slice(1);
327
+ const binding = opts.preview;
328
+ const reusable = this.findReusable(targetId, principal, opts);
329
+ if (reusable) {
330
+ const e = reusable.entry as Entry;
331
+ e.lastUsedAt = now;
332
+ return {
333
+ token: e.label ?? "",
334
+ tokenId: e.tokenId,
335
+ expiresAt: e.mintedAt + e.maxMs,
336
+ policy: { ...e.policy },
337
+ tier: e.tier,
338
+ origin: e.origin,
339
+ originHost: e.originHost,
340
+ poolPort: e.poolPort,
341
+ reused: true,
342
+ };
343
+ }
344
+ const kind: LiveTargetKind = opts.kind === "static" ? "static" : "port";
345
+ const policy: LivePolicy = {
346
+ egress: opts.policy?.egress === "open" ? "open" : "restricted",
347
+ scripts: opts.policy?.scripts === true,
348
+ };
349
+ const idleMs = kind === "static" ? STATIC_CAPABILITY_IDLE_MS : CAPABILITY_IDLE_MS;
350
+ const maxMs = kind === "static" ? STATIC_CAPABILITY_MAX_MS : CAPABILITY_MAX_MS;
351
+ const tokenId = crypto.randomBytes(16).toString("base64url");
352
+
353
+ let secret: string;
354
+ let preview: Pick<Entry, "tier" | "originHost" | "origin" | "label" | "poolPort" | "ancestors"> = {
355
+ tier: "legacy",
356
+ ancestors: [],
357
+ };
358
+ if (!binding) {
359
+ secret = crypto.randomBytes(32).toString("base64url");
360
+ } else if (binding.tier === 3) {
361
+ if (!binding.fixed) throw new Error("tier 3 mint needs the bound listener");
362
+ secret = crypto.randomBytes(32).toString("base64url");
363
+ preview = { tier: 3, ...binding.fixed, ancestors: [...binding.ancestors] };
364
+ } else {
365
+ if (!binding.buildOrigin) throw new Error(`tier ${binding.tier} mint needs buildOrigin`);
366
+ let label = "";
367
+ for (let i = 0; i < LABEL_RETRIES; i++) {
368
+ label = generatePreviewLabel(this.labelBytes);
369
+ if (!this.entries.has(hash(label))) break;
370
+ label = "";
371
+ }
372
+ if (!label) throw new Error("could not allocate a unique preview label");
373
+ secret = label;
374
+ const built = binding.buildOrigin(label);
375
+ preview = { tier: binding.tier, ...built, label, ancestors: [...binding.ancestors] };
108
376
  }
377
+
378
+ const key = hash(secret);
379
+ const entry: Entry = {
380
+ targetId,
381
+ principal,
382
+ mintedAt: now,
383
+ lastUsedAt: now,
384
+ tokenId,
385
+ kind,
386
+ policy,
387
+ ...(isViewerId(opts.viewerId) ? { viewerId: opts.viewerId } : {}),
388
+ minterKey: principalKey(principal),
389
+ mintExposure: opts.exposure ?? "exposed",
390
+ localBound: opts.localBound === true,
391
+ idleMs,
392
+ maxMs,
393
+ ...preview,
394
+ };
395
+ this.entries.set(key, entry);
396
+ if (entry.originHost) this.byOriginHost.set(hash(entry.originHost), key);
397
+ this.ensureSweeper();
398
+ // Evict within the minting principal first, so a mint loop cannot push out
399
+ // another user's active preview capabilities.
400
+ const who = entry.minterKey;
401
+ const mine = [...this.entries].filter(([, e]) => e.minterKey === who);
402
+ for (let i = 0; i < mine.length - MAX_TOKENS_PER_PRINCIPAL; i++) this.remove(mine[i][0], "evicted");
109
403
  while (this.entries.size > MAX_TOKENS) {
110
404
  const oldest = this.entries.keys().next().value;
111
405
  if (oldest === undefined) break;
112
- this.entries.delete(oldest);
406
+ this.remove(oldest, "evicted");
113
407
  }
114
- return { token, expiresAt: now + CAPABILITY_MAX_MS };
408
+ return {
409
+ token: secret,
410
+ tokenId,
411
+ expiresAt: now + maxMs,
412
+ policy,
413
+ tier: entry.tier,
414
+ origin: entry.origin,
415
+ originHost: entry.originHost,
416
+ poolPort: entry.poolPort,
417
+ reused: false,
418
+ };
115
419
  }
116
420
 
117
421
  /**
118
- * Validate `token` for `targetId`. A hit extends the idle expiry. A missing,
119
- * unknown, wrong-target, expired or no-longer-live token returns `null` — the
120
- * caller cannot tell which.
422
+ * Validate a LEGACY `/live/<id>/~c/<token>/` token for `targetId`. A hit extends the idle expiry.
423
+ * A missing, unknown, wrong-target, expired or no-longer-live token returns `null` — the
424
+ * caller cannot tell which. Origin-bound entries (tiers 1-4) never validate here: their label has
425
+ * the token's shape but must not open a `/live/` path.
426
+ *
427
+ * `ctx` carries request-boundary facts: a token minted by a genuinely local
428
+ * caller is refused when `ctx.genuinelyLocal` is false. Every request-facing
429
+ * caller (HTTP hook, WS upgrade) MUST pass it; only store-level unit tests omit it.
121
430
  */
122
- validate(targetId: string, token: string): CapabilityPrincipal | null {
431
+ validate(targetId: string, token: string, ctx?: ValidateContext): CapabilityPrincipal | null {
432
+ return this.validateGrant(targetId, token, ctx)?.principal ?? null;
433
+ }
434
+
435
+ /** {@link validate}, returning everything the proxy needs to apply the token's policy. */
436
+ validateGrant(targetId: string, token: string, ctx?: ValidateContext): LiveCapabilityGrant | null {
123
437
  if (!TOKEN_SHAPE.test(token)) return null;
124
438
  const key = hash(token);
125
439
  const entry = this.entries.get(key);
126
- if (!entry || entry.targetId !== targetId) return null;
440
+ if (!entry || entry.tier !== "legacy" || entry.targetId !== targetId) return null;
127
441
  const now = this.now();
128
- if (now - entry.lastUsedAt >= CAPABILITY_IDLE_MS || now - entry.mintedAt >= CAPABILITY_MAX_MS) {
129
- this.entries.delete(key);
442
+ const expired = this.expiryReason(entry, now);
443
+ if (expired) {
444
+ this.remove(key, expired);
130
445
  return null;
131
446
  }
132
447
  if (!this.isTargetLive(entry.targetId) || !this.isPrincipalLive(entry.principal)) {
133
- this.entries.delete(key);
448
+ this.remove(key, "revoked");
134
449
  return null;
135
450
  }
451
+ // Bound to the local machine: a leaked local token is useless from anywhere else.
452
+ // Refused, not deleted — the genuine local holder keeps a working token.
453
+ if (entry.localBound && ctx && !ctx.genuinelyLocal) return null;
454
+ entry.lastUsedAt = now;
455
+ return grantOf(entry);
456
+ }
457
+
458
+ /**
459
+ * Look an origin-bound entry up by `hash(label)` and the request's canonical Host (D2, D3).
460
+ * The Host must equal `entry.originHost` exactly (no tier crossing, no port crossing); a tier-1
461
+ * or local-bound entry is served only to a genuinely local peer (`peerLocal`). A hit extends the
462
+ * idle expiry. `expired` is reported only while the entry still exists between expiry and sweep;
463
+ * afterwards the entry is gone and the answer is `unknown` (no tombstones, Q25).
464
+ */
465
+ lookupByHost(labelHash: string, canonicalHost: string, peerLocal: boolean): HostLookup {
466
+ const entry = this.entries.get(labelHash);
467
+ if (!entry || entry.tier === "legacy" || entry.tier === 3 || !entry.originHost) return { ok: false, reason: "unknown" };
468
+ const now = this.now();
469
+ const expired = this.expiryReason(entry, now);
470
+ if (expired) {
471
+ this.remove(labelHash, expired);
472
+ return { ok: false, reason: "expired" };
473
+ }
474
+ if (!this.isTargetLive(entry.targetId) || !this.isPrincipalLive(entry.principal)) {
475
+ this.remove(labelHash, "revoked");
476
+ return { ok: false, reason: "unknown" };
477
+ }
478
+ if (canonicalHost !== entry.originHost) {
479
+ const want = splitCanonicalHost(entry.originHost);
480
+ const got = splitCanonicalHost(canonicalHost);
481
+ return { ok: false, reason: want.hostname === got.hostname ? "wrong-port" : "wrong-host" };
482
+ }
483
+ if ((entry.tier === 1 || entry.localBound) && !peerLocal) return { ok: false, reason: "wrong-host" };
136
484
  entry.lastUsedAt = now;
137
- return entry.principal;
485
+ return { ok: true, grant: grantOf(entry) };
486
+ }
487
+
488
+ /** Tier 3: the live entry bound to pool `port`, or `null`. Does not touch. */
489
+ findByPoolPort(port: number): LiveCapabilityGrant | null {
490
+ const now = this.now();
491
+ for (const [key, e] of this.entries) {
492
+ if (e.tier !== 3 || e.poolPort !== port) continue;
493
+ const expired = this.expiryReason(e, now);
494
+ if (expired) {
495
+ this.remove(key, expired);
496
+ return null;
497
+ }
498
+ return grantOf(e);
499
+ }
500
+ return null;
501
+ }
502
+
503
+ /** Is `canonicalHost` the origin host of a live (unexpired) entry? The dynamic admission set; never enumerates labels. */
504
+ isAdmittedHost(canonicalHost: string): boolean {
505
+ const key = this.byOriginHost.get(hash(canonicalHost));
506
+ const e = key ? this.entries.get(key) : undefined;
507
+ return !!e && !this.expiryReason(e, this.now());
508
+ }
509
+
510
+ /** The live capability behind a non-secret `tokenId`, or `null` (expired / unknown). Does not extend idle. */
511
+ findByTokenId(tokenId: string): LiveCapabilityGrant | null {
512
+ const now = this.now();
513
+ for (const [key, e] of this.entries) {
514
+ if (e.tokenId !== tokenId) continue;
515
+ const expired = this.expiryReason(e, now);
516
+ if (expired) {
517
+ this.remove(key, expired);
518
+ return null;
519
+ }
520
+ return grantOf(e);
521
+ }
522
+ return null;
523
+ }
524
+
525
+ /**
526
+ * Extend a capability's idle expiry (keepalive) without a request through its path.
527
+ * Only the minting principal may: `minterKey` must equal the entry's. Never
528
+ * extends past the absolute lifetime. Returns whether a live capability was touched.
529
+ */
530
+ touch(tokenId: string, minterKey: string): boolean {
531
+ const now = this.now();
532
+ for (const [key, e] of this.entries) {
533
+ if (e.tokenId !== tokenId) continue;
534
+ if (e.minterKey !== minterKey) return false;
535
+ const expired = this.expiryReason(e, now);
536
+ if (expired) {
537
+ this.remove(key, expired);
538
+ return false;
539
+ }
540
+ if (!this.isTargetLive(e.targetId) || !this.isPrincipalLive(e.principal)) {
541
+ this.remove(key, "revoked");
542
+ return false;
543
+ }
544
+ e.lastUsedAt = now;
545
+ return true;
546
+ }
547
+ return false;
548
+ }
549
+
550
+ /** Remember an allow-once origin for a viewer (bounded: 32 origins, 256 viewers). */
551
+ addAllowOnce(viewerId: string, origin: string): void {
552
+ if (!isViewerId(viewerId)) return;
553
+ let set = this.allowOnce.get(viewerId);
554
+ if (set) this.allowOnce.delete(viewerId); // re-insert: most recently used last
555
+ else set = new Set<string>();
556
+ set.delete(origin);
557
+ set.add(origin);
558
+ while (set.size > MAX_ALLOW_ONCE_PER_VIEWER) {
559
+ const oldest = set.values().next().value;
560
+ if (oldest === undefined) break;
561
+ set.delete(oldest);
562
+ }
563
+ this.allowOnce.set(viewerId, set);
564
+ while (this.allowOnce.size > MAX_ALLOW_ONCE_VIEWERS) {
565
+ const oldest = this.allowOnce.keys().next().value;
566
+ if (oldest === undefined) break;
567
+ this.allowOnce.delete(oldest);
568
+ }
569
+ }
570
+
571
+ /** The viewer's allow-once origins (a copy; empty when none). */
572
+ getAllowOnce(viewerId: string | undefined): string[] {
573
+ return viewerId ? [...(this.allowOnce.get(viewerId) ?? [])] : [];
574
+ }
575
+
576
+ /** Revoke every capability whose record matches `pred`. Returns how many died. Never exposes a secret. */
577
+ revokeWhere(
578
+ pred: (e: Readonly<{ kind: LiveTargetKind; policy: LivePolicy; mintExposure: LiveExposure; targetId: string }>) => boolean,
579
+ reason: CapabilityDeleteReason = "revoked",
580
+ ): number {
581
+ let n = 0;
582
+ for (const [key, e] of [...this.entries]) {
583
+ if (pred(e)) {
584
+ this.remove(key, reason);
585
+ n++;
586
+ }
587
+ }
588
+ return n;
138
589
  }
139
590
 
140
591
  revokeByTarget(targetId: string): void {
141
- for (const [key, e] of this.entries) if (e.targetId === targetId) this.entries.delete(key);
592
+ for (const [key, e] of [...this.entries]) if (e.targetId === targetId) this.remove(key, "revoked");
142
593
  }
143
594
 
144
595
  revokeByDevice(deviceId: string): void {
145
- for (const [key, e] of this.entries) if (e.principal.deviceId === deviceId) this.entries.delete(key);
596
+ for (const [key, e] of [...this.entries]) if (e.principal.deviceId === deviceId) this.remove(key, "revoked");
146
597
  }
147
598
 
148
599
  revokeBySessionKey(sessionKey: string): void {
149
- for (const [key, e] of this.entries) if (e.principal.sessionKey === sessionKey) this.entries.delete(key);
600
+ for (const [key, e] of [...this.entries]) if (e.principal.sessionKey === sessionKey) this.remove(key, "revoked");
601
+ }
602
+
603
+ /**
604
+ * Delete the entry bound to pool `port` (its listener errored or closed outside the store's control,
605
+ * Q36). The next mint reallocates; no rebind, so no zombie entry holds a listener-cap slot.
606
+ */
607
+ revokeByPoolPort(port: number, reason: CapabilityDeleteReason = "listener-error"): void {
608
+ for (const [key, e] of [...this.entries]) if (e.tier === 3 && e.poolPort === port) this.remove(key, reason);
609
+ }
610
+
611
+ /**
612
+ * Reconcile with the resolved preview-origin config (D12, Q8): `enabled:false` revokes every
613
+ * origin-bound entry (`disabled`); otherwise an entry whose `originHost` no longer matches its
614
+ * tier's current resolved config is revoked (`config-changed`). Legacy entries are untouched.
615
+ */
616
+ reconcilePreviewConfig(cfg: ResolvedPreviewOrigins): number {
617
+ let n = 0;
618
+ for (const [key, e] of [...this.entries]) {
619
+ if (e.tier === "legacy") continue;
620
+ if (!cfg.enabled) {
621
+ this.remove(key, "disabled");
622
+ n++;
623
+ } else if (!entryMatchesConfig(e, cfg)) {
624
+ this.remove(key, "config-changed");
625
+ n++;
626
+ }
627
+ }
628
+ return n;
150
629
  }
151
630
 
152
- /** Count of live tokens (tests, diagnostics). Never exposes a token or its hash. */
631
+ /** Delete everything (dashboard close) and stop the sweeper. */
632
+ close(reason: CapabilityDeleteReason = "shutdown"): void {
633
+ for (const key of [...this.entries.keys()]) this.remove(key, reason);
634
+ this.stopSweeper();
635
+ }
636
+
637
+ /** Count of live capabilities (tests, diagnostics). Never exposes a secret or its hash. */
153
638
  size(): number {
154
639
  return this.entries.size;
155
640
  }
156
641
 
157
- /** True when no stored key equals the plaintext token (hash-only storage check). */
642
+ /** Size of the dynamic admission index (tests, leak soak). */
643
+ admittedHostCount(): number {
644
+ return this.byOriginHost.size;
645
+ }
646
+
647
+ /** Live per-viewer allow-once sets (tests, leak soak). */
648
+ allowOnceSize(): number {
649
+ return this.allowOnce.size;
650
+ }
651
+
652
+ /** True when no stored key equals the plaintext secret (hash-only storage check). */
158
653
  holdsPlaintext(token: string): boolean {
159
- return this.entries.has(token);
654
+ return this.entries.has(token) || this.byOriginHost.has(token);
655
+ }
656
+
657
+ /** `max` / `idle` when the entry's lifetime is over, else `null`. */
658
+ private expiryReason(e: Entry, now: number): "max" | "idle" | null {
659
+ if (now - e.mintedAt >= e.maxMs) return "max";
660
+ if (now - e.lastUsedAt >= e.idleMs) return "idle";
661
+ return null;
662
+ }
663
+
664
+ /**
665
+ * Delete one entry from every index, THEN run the hook: a hook that throws or mints leaves a
666
+ * consistent store (X6). Exactly once per entry.
667
+ */
668
+ private remove(key: string, reason: CapabilityDeleteReason): void {
669
+ const e = this.entries.get(key);
670
+ if (!e) return;
671
+ this.entries.delete(key);
672
+ if (e.originHost) {
673
+ const hk = hash(e.originHost);
674
+ if (this.byOriginHost.get(hk) === key) this.byOriginHost.delete(hk);
675
+ }
676
+ try {
677
+ this.onDelete?.(e, reason);
678
+ } catch (err) {
679
+ console.error(redactCapability(`[live-preview] onDelete hook failed reason=${reason}: ${err instanceof Error ? err.message : String(err)}`));
680
+ }
681
+ if (this.entries.size === 0) this.stopSweeper();
160
682
  }
161
683
 
162
684
  private sweep(now: number): void {
163
- for (const [key, e] of this.entries) {
164
- if (now - e.lastUsedAt >= CAPABILITY_IDLE_MS || now - e.mintedAt >= CAPABILITY_MAX_MS) this.entries.delete(key);
685
+ for (const [key, e] of [...this.entries]) {
686
+ const reason = this.expiryReason(e, now);
687
+ if (reason) this.remove(key, reason);
165
688
  }
689
+ const cfg = this.getPreviewConfig?.();
690
+ if (cfg) this.reconcilePreviewConfig(cfg);
691
+ }
692
+
693
+ private ensureSweeper(): void {
694
+ if (this.sweeper) return;
695
+ this.sweeper = setInterval(() => this.sweep(this.now()), this.sweepIntervalMs);
696
+ this.sweeper.unref?.();
697
+ }
698
+
699
+ private stopSweeper(): void {
700
+ if (!this.sweeper) return;
701
+ clearInterval(this.sweeper);
702
+ this.sweeper = undefined;
166
703
  }
167
704
  }
168
705
 
706
+ const grantOf = (e: Entry): LiveCapabilityGrant => ({
707
+ targetId: e.targetId,
708
+ tokenId: e.tokenId,
709
+ kind: e.kind,
710
+ policy: { ...e.policy },
711
+ ...(e.viewerId ? { viewerId: e.viewerId } : {}),
712
+ minterKey: e.minterKey,
713
+ principal: e.principal,
714
+ tier: e.tier,
715
+ ...(e.origin ? { origin: e.origin } : {}),
716
+ ...(e.originHost ? { originHost: e.originHost } : {}),
717
+ ...(e.poolPort !== undefined ? { poolPort: e.poolPort } : {}),
718
+ ancestors: [...e.ancestors],
719
+ });
720
+
169
721
  /** A parsed capability URL. `rest` starts with `/` (or is `/`); `prefix` is `/live/<id>/~c/<token>`. */
170
722
  export interface CapabilityPath {
171
723
  targetId: string;
@@ -204,10 +756,7 @@ export function parseCapabilityPath(url: string | undefined): CapabilityPath | n
204
756
  return { targetId, token, prefix, rest: rest.startsWith("/") ? rest : `/${rest}` };
205
757
  }
206
758
 
207
- /** Replace any `/~c/<token>` in a log field / path with a redaction marker. */
208
- export function redactCapability(text: string): string {
209
- return text.replace(CAPABILITY_SEGMENT, "/~c/<redacted>");
210
- }
759
+ export { redactCapability };
211
760
 
212
761
  /** Remove any `/~c/<token>` segment (forwarded `Referer`). */
213
762
  export function stripCapabilitySegment(text: string): string {
@@ -223,6 +772,8 @@ interface CapabilityRequestState {
223
772
  principal?: Principal | null;
224
773
  principalExpiresAt?: number | null;
225
774
  liveCapabilityPrefix?: string;
775
+ /** Set with the prefix: the validated token's policy and ids (never the secret). */
776
+ liveCapability?: LiveCapabilityGrant;
226
777
  }
227
778
 
228
779
  /**
@@ -233,13 +784,32 @@ interface CapabilityRequestState {
233
784
  * left untouched — the normal admission rules decide, and cannot tell a bad
234
785
  * token from none.
235
786
  */
236
- export function createLiveCapabilityHook(store: LiveCapabilityStore) {
237
- return async function liveCapabilityHook(request: { url: string }): Promise<void> {
238
- if (!request.url.startsWith("/live/")) return;
239
- const cap = parseCapabilityPath(request.url);
787
+ export function createLiveCapabilityHook(
788
+ store: LiveCapabilityStore,
789
+ previewPaths?: { validate: (pid: string, ctx: { genuinelyLocal: boolean }) => LiveCapabilityGrant | null },
790
+ ) {
791
+ return async function liveCapabilityHook(request: {
792
+ url: string;
793
+ ip?: string;
794
+ headers?: Record<string, unknown>;
795
+ }): Promise<void> {
796
+ const isPreview = request.url.startsWith("/preview/");
797
+ if (!isPreview && !request.url.startsWith("/live/")) return;
798
+ // A token minted by a genuinely local caller works only from genuinely local requests.
799
+ const ctx = { genuinelyLocal: isLocallyTrusted({ ip: request.ip ?? "", headers: request.headers ?? {} }) };
800
+ let cap: { prefix: string; grant: LiveCapabilityGrant } | null = null;
801
+ if (isPreview) {
802
+ const path = previewPaths ? parsePreviewPath(request.url) : null;
803
+ const g = path && previewPaths ? previewPaths.validate(path.pid, ctx) : null;
804
+ cap = path && g ? { prefix: path.prefix, grant: g } : null;
805
+ } else {
806
+ const parsed = parseCapabilityPath(request.url);
807
+ const g = parsed ? store.validateGrant(parsed.targetId, parsed.token, ctx) : null;
808
+ cap = parsed && g ? { prefix: parsed.prefix, grant: g } : null;
809
+ }
240
810
  if (!cap) return;
241
- const principal = store.validate(cap.targetId, cap.token);
242
- if (!principal) return;
811
+ const grant = cap.grant;
812
+ const principal = grant.principal;
243
813
  const r = request as unknown as CapabilityRequestState;
244
814
  r.isAuthenticated = true;
245
815
  r.authVia = "live-capability";
@@ -250,5 +820,6 @@ export function createLiveCapabilityHook(store: LiveCapabilityStore) {
250
820
  r.principalExpiresAt = principal.identityExpiresAt ?? null;
251
821
  }
252
822
  r.liveCapabilityPrefix = cap.prefix;
823
+ r.liveCapability = grant;
253
824
  };
254
825
  }