@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
@@ -20,10 +20,14 @@
20
20
  * (see `ws-ticket.ts`).
21
21
  */
22
22
  import type { TLSSocket } from "node:tls";
23
- import type { FastifyInstance, FastifyRequest } from "fastify";
23
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
24
+ import { TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
24
25
  import type { PairedDeviceRegistry } from "../pairing/paired-devices.js";
26
+ import { auditLine, auditPrefix } from "./audit-log.js";
25
27
  import { hasProxyForwardingHeaders } from "./localhost-guard.js";
26
28
  import { isLoopbackRange } from "./loopback.js";
29
+ import { bearerChannelOf } from "./proven-tls.js";
30
+ import { isSecureOrigin } from "./secure-origin.js";
27
31
 
28
32
  /** Extract a `Bearer` token from an Authorization header, or null. */
29
33
  export function parseBearerHeader(authorization: string | undefined): string | null {
@@ -39,6 +43,16 @@ export function parseBearerHeader(authorization: string | undefined): string | n
39
43
  }
40
44
 
41
45
  export const DEVICE_COOKIE = "pi_dash_device";
46
+ /** Route pattern of the browser-bearer rotation (the one route whose refusals are audited, D2). */
47
+ export const ROTATE_ROUTE = "/api/paired-devices/rotate";
48
+ /** 401 body for an expired browser bearer (distinct from revoked/unknown, which carry no `code`). */
49
+ /** 401 body for a `pi_tls_` bearer presented off a proven channel (a named cause, not "unpaired or revoked"). */
50
+ const TLS_ONLY_UNTRUSTED_BODY = {
51
+ success: false as const,
52
+ error: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
53
+ code: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
54
+ };
55
+ const BEARER_EXPIRED_BODY = { success: false as const, error: "bearer_expired", code: "bearer_expired" as const };
42
56
  /** 400 days — `PairedDeviceRegistry` rows carry no expiry; revocation is the kill switch. */
43
57
  const DEVICE_COOKIE_MAX_AGE_S = 400 * 24 * 60 * 60;
44
58
 
@@ -58,7 +72,10 @@ function deviceCookieSecure(request: FastifyRequest, globalSecure: () => boolean
58
72
  // DIRECT only: a request carrying proxy-forwarding headers came through a TLS-terminating
59
73
  // proxy that may sit on another host/container (peer 172.x), and keeps the global rule.
60
74
  if (peer && !isLoopbackRange(peer) && !hasProxyForwardingHeaders(request.headers)) return false;
61
- return globalSecure();
75
+ // The global rule is the ONE predicate shared with the OAuth state + session cookies:
76
+ // https base || loopback socket peer + Host equal to a live https tunnel origin.
77
+ // See change: harden-auth-credentials (D3).
78
+ return isSecureOrigin(request, globalSecure());
62
79
  }
63
80
 
64
81
  /** Pathname of a request URL (no query/fragment). */
@@ -67,6 +84,23 @@ function pathnameOf(url: string): string {
67
84
  return q < 0 ? url : url.slice(0, q);
68
85
  }
69
86
 
87
+ /**
88
+ * The device cookie's bearer. Authorization wins: the cookie is a fallback for
89
+ * `/api/*` URLs only and is never consulted when an Authorization header is present.
90
+ */
91
+ function deviceCookieToken(request: FastifyRequest): string | null {
92
+ if (request.headers.authorization || !pathnameOf(request.url).startsWith("/api/")) return null;
93
+ return (request.cookies as Record<string, string | undefined> | undefined)?.[DEVICE_COOKIE] ?? null;
94
+ }
95
+
96
+ /** 401 `bearer_expired`; a refused ROTATION of a known device is also audited (A-G4): id prefix, reason, socket peer only. */
97
+ function refuseExpired(request: FastifyRequest, reply: FastifyReply, deviceId: string): FastifyReply {
98
+ if (request.method === "POST" && request.routeOptions?.url === ROTATE_ROUTE) {
99
+ auditLine("pairing", "rotate_refused", { id: auditPrefix(deviceId), reason: "bearer_expired", ip: request.ip });
100
+ }
101
+ return reply.code(401).send(BEARER_EXPIRED_BODY);
102
+ }
103
+
70
104
  /** Register the REST bearer onRequest branch. */
71
105
  export function registerBearerAuth(
72
106
  fastify: FastifyInstance,
@@ -80,17 +114,23 @@ export function registerBearerAuth(
80
114
  /* already decorated by another plugin */
81
115
  }
82
116
  }
83
- fastify.addHook("onRequest", async (request: FastifyRequest) => {
117
+ fastify.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
84
118
  if ((request as any).isAuthenticated) return;
85
119
  const headerToken = parseBearerHeader(request.headers.authorization);
86
- // Authorization wins. The cookie is a fallback for `/api/*` URLs only and is
87
- // never consulted when an Authorization header is present.
88
- const cookieToken =
89
- !request.headers.authorization && pathnameOf(request.url).startsWith("/api/")
90
- ? ((request.cookies as Record<string, string | undefined> | undefined)?.[DEVICE_COOKIE] ?? null)
91
- : null;
92
- const token = headerToken ?? cookieToken;
93
- const verified = token ? deps.registry.verify(token) : null;
120
+ const token = headerToken ?? deviceCookieToken(request);
121
+ // The channel is judged from the request itself and the registry records any off-channel use.
122
+ const verdict = token ? deps.registry.verifyDetailed(token, bearerChannelOf(request.raw)) : null;
123
+ // A TLS-only bearer off a proven channel is marked, then refused with a distinct, named cause.
124
+ // See change: prove-vault-bridge-tls (D4, D9).
125
+ if (verdict?.status === "tls_only_refused") return reply.code(401).send(TLS_ONLY_UNTRUSTED_BODY);
126
+ // A PRESENTED Authorization bearer is always judged, before any network
127
+ // trust: an expired browser bearer is a distinct 401 the client re-pairs
128
+ // on, even from a loopback / trusted peer. (A cookie-carried bearer that
129
+ // expired falls through unauthenticated, like a revoked one.) Revoked,
130
+ // unknown and superseded-after-grace bearers stay a plain denial.
131
+ // See change: harden-auth-credentials (D5, A-G12).
132
+ if (verdict?.status === "expired" && headerToken) return refuseExpired(request, reply, verdict.id);
133
+ const verified = verdict?.status === "ok" ? verdict : null;
94
134
  if (verified) {
95
135
  (request as any).isAuthenticated = true;
96
136
  // Additive marker: HOW the request authenticated. `operatorGuard` on the
@@ -117,7 +157,7 @@ export function registerDeviceSessionRoutes(
117
157
  ): void {
118
158
  fastify.post("/api/device-session", async (request, reply) => {
119
159
  const bearer = parseBearerHeader(request.headers.authorization);
120
- if (!bearer || !deps.registry.verify(bearer)) {
160
+ if (!bearer || !deps.registry.verify(bearer, bearerChannelOf(request.raw))) {
121
161
  reply.code(401);
122
162
  return { success: false as const, error: "device bearer required" };
123
163
  }
@@ -13,9 +13,16 @@
13
13
  * or a genuinely-local caller on this host (which could have used the unix
14
14
  * socket and needs no ticket at all on POSIX, but does on Windows — D6).
15
15
  *
16
- * See change: add-pi-gateway-transport-identity (task 6.2).
16
+ * The mint enforces `operate` ITSELF (the `/api/ws-ticket` route is `operate`, but the
17
+ * route-tier gate is exempt for a `legacy`-mode trusted-network peer and a
18
+ * genuinely-local caller, so the decider cannot rely on it). A below-operate bearer
19
+ * falls through to the genuinely-local branch (a deviceless local ticket) or is refused.
20
+ *
21
+ * See change: add-pi-gateway-transport-identity (task 6.2),
22
+ * harden-bridge-session-claim (D2).
17
23
  */
18
24
 
25
+ import { rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
19
26
  import type { LocalTrustContext } from "./local-proof.js";
20
27
  import { isLocallyTrusted } from "./localhost-guard.js";
21
28
 
@@ -32,9 +39,10 @@ export interface BridgeMintInput {
32
39
  * minted it: a session registered over that ticket is then attributable,
33
40
  * which is what the origin gate needs to refuse local file reads for a
34
41
  * remote session (#E15). Takes the object the registry now returns
35
- * (`{ id, tier }`; change: expand-mcp-tiered-surface) and reads only `id`.
42
+ * (`{ id, tier }`; change: expand-mcp-tiered-surface); the mint reads `tier` too:
43
+ * only `operate` may mint a bridge ticket as a device.
36
44
  */
37
- verifyDeviceBearer: (token: string) => { id: string } | null;
45
+ verifyDeviceBearer: (token: string) => { id: string; tier: Tier } | null;
38
46
  }
39
47
 
40
48
  export interface BridgeMintDecision {
@@ -42,6 +50,13 @@ export interface BridgeMintDecision {
42
50
  reason: string;
43
51
  /** Set when the caller authenticated AS a paired device. */
44
52
  deviceId?: string;
53
+ /** Set when a valid paired-device bearer was refused for being below `operate` (for the audit line). */
54
+ belowOperate?: { tier: Tier; deviceId: string };
55
+ }
56
+
57
+ /** The refusal audit line: tier + an 8-char device prefix, never the full id or the token. */
58
+ export function formatBridgeTicketRefusalLine(tier: Tier, devicePrefix: string): string {
59
+ return `[auth] bridge ticket refused: tier=${tier} device=${devicePrefix}`;
45
60
  }
46
61
 
47
62
  /**
@@ -64,19 +79,47 @@ function bearerFrom(authorization: string | undefined): string | null {
64
79
  return token.length > 0 ? token : null;
65
80
  }
66
81
 
82
+ /**
83
+ * Rate-limited audit logger for below-operate refusals: one line per device per `windowMs`
84
+ * (the contention window), keyed by the full device id but logging only an 8-char prefix.
85
+ * A `verdict` without `belowOperate`, or an allowed one, logs nothing.
86
+ */
87
+ export function createTicketRefusalLog(opts: {
88
+ windowMs: number;
89
+ prefix: (deviceId: string) => string;
90
+ now?: () => number;
91
+ log?: (line: string) => void;
92
+ }): (verdict: BridgeMintDecision) => void {
93
+ const last = new Map<string, number>();
94
+ const now = opts.now ?? Date.now;
95
+ const log = opts.log ?? ((line: string) => console.error(line));
96
+ return (verdict) => {
97
+ if (!verdict.belowOperate || verdict.allow) return;
98
+ const { tier, deviceId } = verdict.belowOperate;
99
+ const t = now();
100
+ const prev = last.get(deviceId);
101
+ if (prev !== undefined && t - prev < opts.windowMs) return;
102
+ last.set(deviceId, t);
103
+ log(formatBridgeTicketRefusalLine(tier, opts.prefix(deviceId)));
104
+ };
105
+ }
106
+
67
107
  export function decideBridgeTicketMint(input: BridgeMintInput): BridgeMintDecision {
68
108
  const bearer = bearerFrom(input.authorization);
69
- const deviceId = bearer ? (input.verifyDeviceBearer(bearer)?.id ?? null) : null;
70
- if (deviceId) {
71
- return { allow: true, reason: "paired device bearer", deviceId };
109
+ const device = bearer ? input.verifyDeviceBearer(bearer) : null;
110
+ if (device && rank(device.tier) >= rank("operate")) {
111
+ return { allow: true, reason: "paired device bearer", deviceId: device.id };
72
112
  }
113
+ const belowOperate = device ? { tier: device.tier, deviceId: device.id } : undefined;
73
114
  if (isLocallyTrusted({ ip: input.ip, headers: input.headers }, input.localTrust)) {
74
- return { allow: true, reason: "genuinely-local caller" };
115
+ return { allow: true, reason: "genuinely-local caller", belowOperate };
75
116
  }
76
117
  return {
77
118
  allow: false,
78
- reason:
79
- "bridge tickets require a paired-device bearer or a genuinely-local caller; " +
80
- "a cookie session or trusted-network host is not sufficient",
119
+ reason: device
120
+ ? "bridge tickets require a paired device at the operate tier; this device's tier is lower"
121
+ : "bridge tickets require an operate-tier paired-device bearer or a genuinely-local caller; " +
122
+ "a cookie session or trusted-network host is not sufficient",
123
+ belowOperate,
81
124
  };
82
125
  }
@@ -10,6 +10,7 @@
10
10
  * See change: fix-remote-connect-cors-gates.
11
11
  */
12
12
 
13
+ import { isPreviewShapedOriginUrl } from "../live-server/preview-origin.js";
13
14
  import { isHostAdmitted } from "./host-admission.js";
14
15
  import { isBypassedHost } from "./localhost-guard.js";
15
16
  import type { WsRouteScope } from "./ws-ticket.js";
@@ -44,13 +45,14 @@ export interface CorsOriginOptions {
44
45
  /**
45
46
  * Allow ANY `*.share.zrok.io` / `*.shares.zrok.io` host (branch 5).
46
47
  *
47
- * `true` (default) for CORS readability, where the allowance shipped and is
48
- * load-bearing for tunnel-URL rotation. `false` for ADMISSION (WS upgrade,
49
- * mutating REST): zrok shares are free and self-service, so a stranger share
50
- * is very likely same-site to the victim's tunnel and the wildcard would let
51
- * it defeat even the OAuth'd gate. Tunnels the dashboard itself runs are live
52
- * tunnel origins (branch 4/4b) and stay admitted.
53
- * See change: fix-ws-origin-cswsh (D1 rule 2).
48
+ * Opt-in: only the boolean `true` enables it (`cors.allowZrokWildcard`,
49
+ * default `false`). Zrok shares are free and self-service, so a stranger
50
+ * share is very likely same-site to the victim's tunnel; the wildcard would
51
+ * let it read responses (CORS) and, for admission (WS upgrade, mutating
52
+ * REST), defeat even the OAuth'd gate — admission therefore ALWAYS forces it
53
+ * off. Tunnels the dashboard itself runs are live tunnel origins (branch
54
+ * 4/4b) and stay allowed with the wildcard off.
55
+ * See change: fix-ws-origin-cswsh (D1 rule 2), harden-cors-and-csp-reporting (B19).
54
56
  */
55
57
  allowZrokWildcard?: boolean;
56
58
  /** Top-level `allowedHosts` (live) — host-admission only. */
@@ -71,6 +73,41 @@ export interface CorsOriginOptions {
71
73
  hostGateMode?: "report" | "enforce";
72
74
  }
73
75
 
76
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: detecting them is the point.
77
+ const HAS_CONTROL = /[\u0000-\u001f\u007f]/;
78
+
79
+ /**
80
+ * Canonical form of an origin or URL for tunnel comparison: lowercase scheme
81
+ * and host, default port elided, ONE trailing hostname dot stripped, path /
82
+ * query dropped. `null` for anything that is not a well-formed http(s) origin
83
+ * (padding, control characters, bad port, other schemes).
84
+ *
85
+ * A trailing-dot origin equals its dotless form, matching host admission.
86
+ * See change: harden-cors-and-csp-reporting (R2).
87
+ */
88
+ export function canonicalOrigin(raw: string): string | null {
89
+ if (typeof raw !== "string" || raw !== raw.trim() || HAS_CONTROL.test(raw)) return null;
90
+ try {
91
+ const u = new URL(raw);
92
+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;
93
+ const host = u.hostname.endsWith(".") ? u.hostname.slice(0, -1) : u.hostname;
94
+ if (host === "") return null;
95
+ return `${u.protocol}//${host}${u.port ? `:${u.port}` : ""}`;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ /** Run a dynamic getter; a throwing getter means "nothing live", never a 500. */
102
+ function safely<T>(read: (() => T) | undefined, fallback: T): T {
103
+ if (!read) return fallback;
104
+ try {
105
+ return read() ?? fallback;
106
+ } catch {
107
+ return fallback;
108
+ }
109
+ }
110
+
74
111
  /**
75
112
  * Why a CORS origin decision came out the way it did.
76
113
  *
@@ -92,6 +129,7 @@ export type CorsAllowanceKind =
92
129
  | "pwa-shell"
93
130
  | "trusted-network"
94
131
  | "configured"
132
+ | "preview"
95
133
  | "denied";
96
134
 
97
135
  export interface CorsAllowance {
@@ -111,7 +149,8 @@ export interface CorsAllowance {
111
149
  * 3. Loopback host (any port) → allow.
112
150
  * 4. Active zrok tunnel URL → allow.
113
151
  * 4b. Any CURRENTLY connected tunnel origin (any provider) → allow.
114
- * 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow.
152
+ * 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow, ONLY
153
+ * when `allowZrokWildcard === true` (opt-in, default off).
115
154
  * 6. Neutral static PWA shell `https://pi-dashboard.dev` → allow.
116
155
  * 7. Explicitly configured origin → allow.
117
156
  * 8. Origin host matches a trusted network (CIDR / wildcard / exact) → allow.
@@ -130,6 +169,15 @@ export function classifyCorsOrigin(
130
169
  // 2. Opaque-origin document. Never echo an ACAO for it, so an embedded
131
170
  // untrusted app cannot call dashboard APIs even cross-origin.
132
171
  if (origin === "null") return { allowed: false, revocable: false, kind: "opaque" };
172
+ // Padding / control characters are never sent by a browser; `new URL()`
173
+ // silently strips them, so do not normalize them into a trusted value.
174
+ if (origin !== origin.trim() || HAS_CONTROL.test(origin)) return { allowed: false, revocable: false, kind: "denied" };
175
+ // 2b. A live-preview origin (`<label>.localhost`, a configured suffix, `<ip>:<pool port>`) is another
176
+ // app's origin: it never gains dashboard trust — not through loopback, a trusted network, a live
177
+ // tunnel nor an explicit `cors.allowedOrigins` entry. Evaluated BEFORE all of them, so the
178
+ // static `ip-address` admission of an IP-literal pool origin can never exempt it.
179
+ // See change: serve-live-previews-on-capability-origin (D4).
180
+ if (isPreviewShapedOriginUrl(origin)) return { allowed: false, revocable: false, kind: "preview" };
133
181
  try {
134
182
  const u = new URL(origin);
135
183
  const host = u.hostname;
@@ -137,26 +185,25 @@ export function classifyCorsOrigin(
137
185
  if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1") {
138
186
  return allow("loopback");
139
187
  }
188
+ // Tunnel branches compare CANONICAL origins (case, default port, one
189
+ // trailing dot, path), so the recorded URL and the browser's Origin agree.
190
+ const requestOrigin = canonicalOrigin(origin);
140
191
  // 4. Active zrok tunnel URL (dynamic — rotation without restart).
141
- const tunnelUrl = opts.getTunnelUrl?.() ?? null;
142
- if (tunnelUrl && origin === tunnelUrl) return allow("active-tunnel");
143
- // 4b. Any live tunnel's origin, for every provider. Compared as ORIGINS,
144
- // not as URLs: a provider reports `https://host/path`, and a browser
145
- // sends `https://host`, so a string equality against the raw URL would
146
- // silently never match for any provider that carries a path.
147
- for (const raw of opts.getLiveTunnelOrigins?.() ?? []) {
148
- let candidate: string;
149
- try {
150
- candidate = new URL(raw).origin;
151
- } catch {
152
- continue;
153
- }
154
- if (candidate === u.origin) return allow("live-tunnel");
192
+ const tunnelUrl = safely(opts.getTunnelUrl, null);
193
+ const canonicalTunnel = tunnelUrl ? canonicalOrigin(tunnelUrl) : null;
194
+ if (requestOrigin && canonicalTunnel && requestOrigin === canonicalTunnel) return allow("active-tunnel");
195
+ // 4b. Any live tunnel's origin, for every provider. Compared as canonical
196
+ // ORIGINS, not URLs: a provider reports `https://host/path`, and a
197
+ // browser sends `https://host`. Malformed entries are skipped.
198
+ for (const raw of safely(opts.getLiveTunnelOrigins, [] as string[])) {
199
+ const candidate = canonicalOrigin(raw);
200
+ if (candidate && requestOrigin && candidate === requestOrigin) return allow("live-tunnel");
155
201
  }
156
- // 5. Any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
202
+ // 5. Opt-in only: any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
203
+ const bareHost = host.endsWith(".") ? host.slice(0, -1) : host;
157
204
  if (
158
- opts.allowZrokWildcard !== false &&
159
- (host.endsWith(".share.zrok.io") || host.endsWith(".shares.zrok.io"))
205
+ opts.allowZrokWildcard === true &&
206
+ (bareHost.endsWith(".share.zrok.io") || bareHost.endsWith(".shares.zrok.io"))
160
207
  ) {
161
208
  return allow("zrok-wildcard");
162
209
  }
@@ -227,7 +274,11 @@ export function isSameOriginByHost(
227
274
  try {
228
275
  const o = new URL(origin);
229
276
  const h = new URL(`${o.protocol}//${hostHeader}`);
230
- if (h.host === "" || o.host !== h.host) return false;
277
+ if (h.host === "") return false;
278
+ // Canonical compare: case, default port and one trailing dot all agree.
279
+ const co = canonicalOrigin(origin);
280
+ const ch = canonicalOrigin(`${o.protocol}//${hostHeader}`);
281
+ if (!co || !ch || co !== ch) return false;
231
282
  } catch {
232
283
  return false;
233
284
  }
@@ -257,6 +308,8 @@ export function isOriginAdmitted(
257
308
  // would normalize into a loopback match. No browser sends padding — deny it
258
309
  // rather than normalize an attacker-shaped value into a trusted one.
259
310
  if (origin !== origin.trim()) return false;
311
+ // A preview origin never acts on the dashboard: not via the same-origin-by-Host rule, nor any list (D4).
312
+ if (isPreviewShapedOriginUrl(origin)) return false;
260
313
  if (isSameOriginByHost(origin, hostHeader, opts)) return true;
261
314
  return isCorsOriginAllowed(origin, { ...opts, allowZrokWildcard: false });
262
315
  }
@@ -265,16 +318,20 @@ export function isOriginAdmitted(
265
318
  * WS upgrade admission, per route scope.
266
319
  *
267
320
  * `live` admits the opaque `Origin: null` — the sandboxed preview iframe is its
268
- * only intended client and rejecting it would silently break HMR (D3). Every
269
- * other scope (including `bridge` and the unrouted `null` scope) is strict.
321
+ * only intended client and rejecting it would silently break HMR (D3) — but ONLY
322
+ * for an upgrade that carries a VALID capability (`liveCapabilityValid`): an
323
+ * opaque frame without one would otherwise reach any port target. Every other
324
+ * scope (including `bridge` and the unrouted `null` scope) is strict.
325
+ * See change: improve-canvas-html-and-url-ux (design D10).
270
326
  */
271
327
  export function isWsOriginTrusted(
272
328
  origin: string | undefined,
273
329
  hostHeader: string | undefined,
274
330
  scope: WsRouteScope | null,
275
331
  opts: CorsOriginOptions,
332
+ liveCapabilityValid = false,
276
333
  ): boolean {
277
- if (scope === "live" && origin === "null") return true;
334
+ if (scope === "live" && origin === "null") return liveCapabilityValid;
278
335
  return isOriginAdmitted(origin, hostHeader, opts);
279
336
  }
280
337
 
@@ -295,7 +352,10 @@ export function isPluginWsOriginAdmitted(
295
352
  admitOrigins: readonly string[],
296
353
  opts: CorsOriginOptions,
297
354
  ): boolean {
298
- if (admitOrigins.length > 0) return origin !== undefined && admitOrigins.includes(origin);
355
+ if (admitOrigins.length > 0) {
356
+ // A plugin's own allow-list cannot re-admit a preview origin either (D4).
357
+ return origin !== undefined && !isPreviewShapedOriginUrl(origin) && admitOrigins.includes(origin);
358
+ }
299
359
  return isWsOriginTrusted(origin, hostHeader, null, opts);
300
360
  }
301
361
 
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Whole-file AES-256-GCM envelope for the two credential files, plus the
3
+ * `JsonFileCodec` that plugs it into `locked-json-file` (opt-in `codec`).
4
+ *
5
+ * Format (D2): a magic first line, then ONE JSON line:
6
+ *
7
+ * pi-dashboard-encrypted:v1
8
+ * {"alg":"A256GCM","kid":"<16 hex>","iv":"<b64 12 B>","tag":"<b64 16 B>","ct":"<b64>"}
9
+ *
10
+ * Pure module: no key resolution, no keychain, no logging. Key material never
11
+ * appears in a return value, an error or a message here.
12
+ *
13
+ * Classification contract (D3): any file whose first line starts with
14
+ * `pi-dashboard-encrypted:` is an envelope and is NEVER `corrupt`: an unknown
15
+ * version is `unsupported`, a bad v1 header is `damaged`.
16
+ *
17
+ * See change: encrypt-credentials-at-rest (D1, D2, D3).
18
+ */
19
+
20
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
21
+ import {
22
+ type CredentialFileId,
23
+ type CredentialKeyFailureReason,
24
+ type CredentialLockReason,
25
+ credentialRemedy,
26
+ ENVELOPE_MAGIC_PREFIX,
27
+ ENVELOPE_MAGIC_V1,
28
+ } from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
29
+ import type { JsonFileCodec } from "./locked-json-file.js";
30
+
31
+ export type EnvelopeClass = "absent" | "envelope" | "plaintext" | "unsupported" | "damaged" | "corrupt";
32
+
33
+ export type EnvelopeDecodeResult =
34
+ | { kind: "document"; doc: Record<string, unknown>; kid: string }
35
+ | { kind: "locked"; reason: Extract<CredentialLockReason, "key_mismatch" | "unsupported_format" | "envelope_damaged"> }
36
+ | { kind: "not-envelope"; class: "absent" | "plaintext" | "corrupt"; doc?: Record<string, unknown> };
37
+
38
+ export type KeyAvailability = { ok: true; key: Buffer } | { ok: false; reason: CredentialKeyFailureReason };
39
+
40
+ const KEY_BYTES = 32;
41
+ const IV_BYTES = 12;
42
+ const TAG_BYTES = 16;
43
+ const ALG = "A256GCM";
44
+ const KID_PREFIX = Buffer.from("pi-dashboard-kid\0");
45
+ const KID_RE = /^[0-9a-f]{16}$/;
46
+
47
+ /** First 8 bytes of SHA-256("pi-dashboard-kid\0" ‖ key), hex. One-way: tells keys apart without revealing one. */
48
+ export function deriveKid(key: Buffer): string {
49
+ return createHash("sha256").update(KID_PREFIX).update(key).digest("hex").slice(0, 16);
50
+ }
51
+
52
+ const aadFor = (fileId: CredentialFileId) => Buffer.from(`pi-dashboard:v1:${fileId}`);
53
+
54
+ function assertKey(key: Buffer): void {
55
+ if (!Buffer.isBuffer(key) || key.length !== KEY_BYTES) throw new TypeError("credential key must be 32 bytes");
56
+ }
57
+
58
+ /** Strict standard base64: canonical padding, canonical round trip. Returns undefined when invalid. */
59
+ function strictBase64(value: unknown): Buffer | undefined {
60
+ if (typeof value !== "string" || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return undefined;
61
+ const buf = Buffer.from(value, "base64");
62
+ return buf.toString("base64") === value ? buf : undefined;
63
+ }
64
+
65
+ interface ParsedHeader {
66
+ kid: string;
67
+ iv: Buffer;
68
+ tag: Buffer;
69
+ ct: Buffer;
70
+ }
71
+
72
+ type Analysis =
73
+ | { kind: "absent" }
74
+ | { kind: "plaintext"; doc: Record<string, unknown> }
75
+ | { kind: "corrupt" }
76
+ | { kind: "unsupported" }
77
+ | { kind: "damaged" }
78
+ | { kind: "envelope"; header: ParsedHeader };
79
+
80
+ type BytesLike = Buffer | Uint8Array | string | null | undefined;
81
+
82
+ function parseEnvelopeFile(text: string): Analysis {
83
+ const lines = text.split(/\r?\n/);
84
+ if (lines[0] !== ENVELOPE_MAGIC_V1) return { kind: "unsupported" };
85
+ // Anything but whitespace after the envelope line is damage; a trailing newline is not.
86
+ if (lines.slice(2).some((l) => l.trim().length > 0)) return { kind: "damaged" };
87
+ let raw: unknown;
88
+ try {
89
+ raw = JSON.parse(lines[1] ?? "");
90
+ } catch {
91
+ return { kind: "damaged" };
92
+ }
93
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return { kind: "damaged" };
94
+ const h = raw as Record<string, unknown>;
95
+ if (h.alg !== ALG || typeof h.kid !== "string" || !KID_RE.test(h.kid)) return { kind: "damaged" };
96
+ const iv = strictBase64(h.iv);
97
+ const tag = strictBase64(h.tag);
98
+ const ct = strictBase64(h.ct);
99
+ if (!iv || iv.length !== IV_BYTES || !tag || tag.length !== TAG_BYTES || !ct || ct.length === 0) {
100
+ return { kind: "damaged" };
101
+ }
102
+ return { kind: "envelope", header: { kid: h.kid, iv, tag, ct } };
103
+ }
104
+
105
+ function parsePlainFile(text: string): Analysis {
106
+ try {
107
+ const parsed: unknown = JSON.parse(text);
108
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
109
+ return { kind: "plaintext", doc: parsed as Record<string, unknown> };
110
+ }
111
+ } catch {
112
+ /* corrupt below */
113
+ }
114
+ return { kind: "corrupt" };
115
+ }
116
+
117
+ function analyze(bytes: BytesLike): Analysis {
118
+ if (bytes === null || bytes === undefined) return { kind: "absent" };
119
+ let text = typeof bytes === "string" ? bytes : Buffer.from(bytes).toString("utf8");
120
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // one leading BOM
121
+ // The magic prefix decides: such a file is never "corrupt".
122
+ return text.startsWith(ENVELOPE_MAGIC_PREFIX) ? parseEnvelopeFile(text) : parsePlainFile(text);
123
+ }
124
+
125
+ /** Classify raw file bytes (`null`/`undefined` = the file is absent). */
126
+ export function classify(bytes: BytesLike): EnvelopeClass {
127
+ return analyze(bytes).kind;
128
+ }
129
+
130
+ /** Encrypt `doc` as a v1 envelope file for `fileId`. A fresh random IV per call. */
131
+ export function encodeEnvelope(doc: unknown, key: Buffer, fileId: CredentialFileId): Buffer {
132
+ assertKey(key);
133
+ const iv = randomBytes(IV_BYTES);
134
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
135
+ cipher.setAAD(aadFor(fileId));
136
+ const ct = Buffer.concat([cipher.update(Buffer.from(JSON.stringify(doc), "utf8")), cipher.final()]);
137
+ const header = { alg: ALG, kid: deriveKid(key), iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), ct: ct.toString("base64") };
138
+ return Buffer.from(`${ENVELOPE_MAGIC_V1}\n${JSON.stringify(header)}\n`, "utf8");
139
+ }
140
+
141
+ /** Authenticate and decrypt a well-formed header. Any failure is `locked`, never a partial document. */
142
+ function decryptHeader(header: ParsedHeader, key: Buffer, fileId: CredentialFileId): EnvelopeDecodeResult {
143
+ if (header.kid !== deriveKid(key)) return { kind: "locked", reason: "key_mismatch" };
144
+ let plain: Buffer;
145
+ try {
146
+ const decipher = createDecipheriv("aes-256-gcm", key, header.iv);
147
+ decipher.setAAD(aadFor(fileId));
148
+ decipher.setAuthTag(header.tag);
149
+ plain = Buffer.concat([decipher.update(header.ct), decipher.final()]);
150
+ } catch {
151
+ return { kind: "locked", reason: "key_mismatch" };
152
+ }
153
+ try {
154
+ const doc: unknown = JSON.parse(plain.toString("utf8"));
155
+ if (doc !== null && typeof doc === "object" && !Array.isArray(doc)) {
156
+ return { kind: "document", doc: doc as Record<string, unknown>, kid: header.kid };
157
+ }
158
+ } catch {
159
+ /* authenticated but not a JSON object: damaged */
160
+ }
161
+ return { kind: "locked", reason: "envelope_damaged" };
162
+ }
163
+
164
+ /** The result for analyses that need no key. */
165
+ function withoutKey(a: Exclude<Analysis, { kind: "envelope" }>): EnvelopeDecodeResult {
166
+ if (a.kind === "unsupported") return { kind: "locked", reason: "unsupported_format" };
167
+ if (a.kind === "damaged") return { kind: "locked", reason: "envelope_damaged" };
168
+ if (a.kind === "plaintext") return { kind: "not-envelope", class: "plaintext", doc: a.doc };
169
+ return { kind: "not-envelope", class: a.kind };
170
+ }
171
+
172
+ /**
173
+ * Decode an envelope. Never returns a partial document: any failure is a
174
+ * `locked` result with exactly one reason. Non-envelope bytes are reported as
175
+ * `not-envelope` (plaintext carries its parsed document).
176
+ */
177
+ export function decodeEnvelope(bytes: BytesLike, key: Buffer, fileId: CredentialFileId): EnvelopeDecodeResult {
178
+ assertKey(key);
179
+ const a = analyze(bytes);
180
+ return a.kind === "envelope" ? decryptHeader(a.header, key, fileId) : withoutKey(a);
181
+ }
182
+
183
+ /** Thrown when a credential write is refused. Carries a non-secret reason and the fixed remedy text. */
184
+ export class CredentialLockedError extends Error {
185
+ readonly code = "credential_locked";
186
+ readonly reason: CredentialLockReason;
187
+ constructor(reason: CredentialLockReason) {
188
+ super(`Credential write refused (${reason}). ${credentialRemedy(reason)}`);
189
+ this.name = "CredentialLockedError";
190
+ this.reason = reason;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Codec over a key getter. `getKey` is called on every decode/encode, so a
196
+ * singleton can answer "not ready" until the key has been resolved.
197
+ */
198
+ export function createEnvelopeCodec(fileId: CredentialFileId, getKey: () => KeyAvailability): JsonFileCodec {
199
+ const decode: JsonFileCodec["decode"] = (bytes) => {
200
+ const a = analyze(bytes);
201
+ let out: EnvelopeDecodeResult;
202
+ if (a.kind === "envelope") {
203
+ const k = getKey();
204
+ if (!k.ok) return { kind: "locked", reason: k.reason };
205
+ out = decryptHeader(a.header, k.key, fileId);
206
+ } else {
207
+ if (a.kind === "absent") return { kind: "absent" };
208
+ out = withoutKey(a);
209
+ }
210
+ if (out.kind === "document") return { kind: "document", data: out.doc, encrypted: true };
211
+ if (out.kind === "locked") return { kind: "locked", reason: out.reason };
212
+ if (out.class === "plaintext" && out.doc) return { kind: "document", data: out.doc, encrypted: false };
213
+ return { kind: "corrupt" };
214
+ };
215
+ return {
216
+ fileId,
217
+ decode,
218
+ unavailableReason: () => {
219
+ const k = getKey();
220
+ return k.ok ? undefined : k.reason;
221
+ },
222
+ encode: (data, existing) => {
223
+ // Never overwrite an envelope this process cannot read.
224
+ if (existing) {
225
+ const cur = decode(existing);
226
+ if (cur.kind === "locked") throw new CredentialLockedError(cur.reason);
227
+ }
228
+ const k = getKey();
229
+ if (!k.ok) throw new CredentialLockedError(k.reason);
230
+ return encodeEnvelope(data, k.key, fileId);
231
+ },
232
+ };
233
+ }