@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.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 (576) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +85 -11
  3. package/docs/architecture.md +3020 -116
  4. package/package.json +31 -18
  5. package/packages/extension/package.json +10 -8
  6. package/packages/extension/src/ask-user-tool.ts +65 -3
  7. package/packages/extension/src/auto-session-namer.ts +190 -50
  8. package/packages/extension/src/bridge-handlers/dispatch.ts +504 -0
  9. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  10. package/packages/extension/src/bridge-handlers/instance.ts +229 -0
  11. package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -0
  12. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  13. package/packages/extension/src/bridge-identity-log.ts +45 -0
  14. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  15. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  16. package/packages/extension/src/bridge.ts +517 -2534
  17. package/packages/extension/src/canvas-tool.ts +2 -0
  18. package/packages/extension/src/command-handler.ts +259 -16
  19. package/packages/extension/src/connect-target.ts +23 -0
  20. package/packages/extension/src/connection.ts +294 -24
  21. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  22. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  25. package/packages/extension/src/flow-event-wiring.ts +1 -1
  26. package/packages/extension/src/followup-buffer.ts +1 -1
  27. package/packages/extension/src/followup-drain.ts +79 -0
  28. package/packages/extension/src/git-link-builder.ts +11 -2
  29. package/packages/extension/src/inbound-limits.ts +138 -0
  30. package/packages/extension/src/local-token-header.ts +232 -17
  31. package/packages/extension/src/message-update-coalescer.ts +3 -1
  32. package/packages/extension/src/model-refresh.ts +88 -0
  33. package/packages/extension/src/multiselect-list.ts +6 -2
  34. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  35. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  36. package/packages/extension/src/path-gate/decide.ts +15 -41
  37. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  38. package/packages/extension/src/path-gate/handler.ts +51 -2
  39. package/packages/extension/src/path-gate/index.ts +12 -1
  40. package/packages/extension/src/path-gate/resolve.ts +6 -124
  41. package/packages/extension/src/path-gate/roots.ts +4 -1
  42. package/packages/extension/src/path-gate/suppression.ts +4 -1
  43. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  44. package/packages/extension/src/pinned-endpoint.ts +44 -0
  45. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  46. package/packages/extension/src/project-trust-live.ts +143 -0
  47. package/packages/extension/src/project-trust.ts +258 -25
  48. package/packages/extension/src/prompt-expander.ts +5 -1
  49. package/packages/extension/src/prompt-meta.ts +64 -0
  50. package/packages/extension/src/provider-register.ts +146 -38
  51. package/packages/extension/src/remote-registration-gate.ts +21 -21
  52. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  53. package/packages/extension/src/role-manager.ts +5 -4
  54. package/packages/extension/src/role-model-tools.ts +47 -6
  55. package/packages/extension/src/server-auto-start.ts +13 -6
  56. package/packages/extension/src/server-launcher.ts +11 -13
  57. package/packages/extension/src/server-proof-probe.ts +117 -0
  58. package/packages/extension/src/session-move.ts +19 -0
  59. package/packages/extension/src/session-sync.ts +73 -50
  60. package/packages/extension/src/spawn-token.ts +46 -0
  61. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  62. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  63. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  64. package/packages/extension/src/vault-delivery.ts +404 -0
  65. package/packages/extension/src/vault-forwarder.ts +128 -0
  66. package/packages/extension/src/vault-masker.ts +165 -0
  67. package/packages/extension/src/vault-redaction.ts +181 -0
  68. package/packages/extension/src/vcs-info.ts +5 -2
  69. package/packages/server/bin/pi-dashboard.mjs +26 -89
  70. package/packages/server/package.json +29 -15
  71. package/packages/server/src/access/access-grants.ts +79 -8
  72. package/packages/server/src/access/access-health.ts +10 -0
  73. package/packages/server/src/access/access-plane.ts +5 -1
  74. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  75. package/packages/server/src/access/agent-grant.ts +1 -1
  76. package/packages/server/src/access/agent-yolo.ts +91 -0
  77. package/packages/server/src/access/containment-gate.ts +82 -17
  78. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  79. package/packages/server/src/access/cwd-verdict.ts +144 -0
  80. package/packages/server/src/access/grant-coordinator.ts +3 -1
  81. package/packages/server/src/access/pi-trust-live.ts +244 -0
  82. package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
  83. package/packages/server/src/access/planes.ts +116 -2
  84. package/packages/server/src/access/preview-egress-store.ts +153 -0
  85. package/packages/server/src/access/prompt-channel.ts +5 -0
  86. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  87. package/packages/server/src/access/provisioning.ts +763 -0
  88. package/packages/server/src/access/refusal-ledger.ts +6 -6
  89. package/packages/server/src/access/yolo-session.ts +127 -14
  90. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  91. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  92. package/packages/server/src/acp-bridge/acp-session-adapter.ts +549 -0
  93. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  94. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  95. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  96. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  97. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  98. package/packages/server/src/acp-bridge/main.ts +118 -0
  99. package/packages/server/src/acp-bridge/models.ts +33 -0
  100. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  101. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  102. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  103. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  104. package/packages/server/src/addons/addons-catalog.ts +408 -0
  105. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  106. package/packages/server/src/addons/addons-folder.ts +310 -0
  107. package/packages/server/src/addons/addons-service.ts +470 -0
  108. package/packages/server/src/addons/package-contents.ts +99 -0
  109. package/packages/server/src/addons/settings-entries.ts +120 -0
  110. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  111. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  112. package/packages/server/src/auth/approval-refusal.ts +87 -0
  113. package/packages/server/src/auth/audit-log.ts +80 -0
  114. package/packages/server/src/auth/auth-plugin.ts +329 -97
  115. package/packages/server/src/auth/auth.ts +102 -11
  116. package/packages/server/src/auth/bearer-auth.ts +74 -12
  117. package/packages/server/src/auth/cors-origin.ts +86 -29
  118. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  119. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  120. package/packages/server/src/auth/csp-report-store.ts +406 -0
  121. package/packages/server/src/auth/csp.ts +111 -9
  122. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  123. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  124. package/packages/server/src/auth/host-admission.ts +26 -0
  125. package/packages/server/src/auth/host-gate.ts +6 -1
  126. package/packages/server/src/auth/local-credential.ts +258 -0
  127. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  128. package/packages/server/src/auth/local-proof.ts +76 -22
  129. package/packages/server/src/auth/local-token.ts +16 -0
  130. package/packages/server/src/auth/localhost-guard.ts +298 -17
  131. package/packages/server/src/auth/nav-intent.ts +72 -0
  132. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  133. package/packages/server/src/auth/node-guard.ts +43 -0
  134. package/packages/server/src/auth/operate-required.ts +126 -0
  135. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  136. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  137. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  138. package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
  139. package/packages/server/src/auth/passkey/passkey-routes.ts +232 -0
  140. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  141. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  142. package/packages/server/src/auth/passkey/requester.ts +83 -0
  143. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  144. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  145. package/packages/server/src/auth/pi-legacy-credentials.ts +324 -0
  146. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  147. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  148. package/packages/server/src/auth/proven-tls.ts +45 -0
  149. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  150. package/packages/server/src/auth/provider-auth-storage.ts +61 -9
  151. package/packages/server/src/auth/radius-mcp.ts +1 -1
  152. package/packages/server/src/auth/radius-override.ts +13 -0
  153. package/packages/server/src/auth/request-principal.ts +32 -0
  154. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  155. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  156. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  157. package/packages/server/src/auth/secret-rotation.ts +246 -0
  158. package/packages/server/src/auth/secure-origin.ts +56 -0
  159. package/packages/server/src/auth/serve-app-host.ts +197 -0
  160. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  161. package/packages/server/src/auth/trust-mode.ts +83 -0
  162. package/packages/server/src/auth/ws-ticket.ts +39 -1
  163. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  164. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  165. package/packages/server/src/browse.ts +114 -2
  166. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  167. package/packages/server/src/browser-handlers/directory-handler.ts +151 -6
  168. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  169. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  170. package/packages/server/src/browser-handlers/session-action-handler.ts +138 -63
  171. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  172. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  173. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  174. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  175. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  176. package/packages/server/src/cli.ts +1063 -106
  177. package/packages/server/src/config-api.ts +166 -2
  178. package/packages/server/src/config-snapshot.ts +53 -1
  179. package/packages/server/src/directory-service.ts +545 -36
  180. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  181. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  182. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  183. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  184. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  185. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  186. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  187. package/packages/server/src/event-wiring.ts +349 -141
  188. package/packages/server/src/file-watch-manager.ts +187 -39
  189. package/packages/server/src/git-worktree/git-operations.ts +60 -15
  190. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  191. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  192. package/packages/server/src/git-worktree/worktree-init-trust.ts +91 -6
  193. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  194. package/packages/server/src/identity/host-resources.ts +3 -0
  195. package/packages/server/src/identity/http-road-classification.ts +31 -1
  196. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  197. package/packages/server/src/identity/plugin-identity.ts +19 -0
  198. package/packages/server/src/identity/policy-registry.ts +4 -1
  199. package/packages/server/src/identity/resolver-registry.ts +12 -3
  200. package/packages/server/src/identity/ws-message-scope.ts +10 -0
  201. package/packages/server/src/identity/ws-road-classification.ts +10 -0
  202. package/packages/server/src/known-server-moves.ts +196 -0
  203. package/packages/server/src/lib/browse-roots.ts +137 -0
  204. package/packages/server/src/lib/client-dist.ts +36 -21
  205. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  206. package/packages/server/src/lib/diagram-render.ts +4 -6
  207. package/packages/server/src/lib/digest-gate.ts +82 -0
  208. package/packages/server/src/lib/eml.ts +3 -8
  209. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  210. package/packages/server/src/lib/file-write-lock.ts +24 -0
  211. package/packages/server/src/lib/folder-project.ts +439 -0
  212. package/packages/server/src/lib/grep-worker.ts +23 -0
  213. package/packages/server/src/lib/grep.ts +93 -7
  214. package/packages/server/src/lib/index-html.ts +81 -0
  215. package/packages/server/src/lib/office-preview.ts +2 -3
  216. package/packages/server/src/lib/path-containment.ts +7 -0
  217. package/packages/server/src/lib/purify.ts +13 -5
  218. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  219. package/packages/server/src/lib/route-admission.ts +80 -0
  220. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  221. package/packages/server/src/lib/writable-md-target.ts +16 -1
  222. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  223. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  224. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  225. package/packages/server/src/lifecycle/recovery-server.ts +129 -6
  226. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  227. package/packages/server/src/live-server/capability-redact.ts +15 -0
  228. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  229. package/packages/server/src/live-server/live-capability.ts +461 -0
  230. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  231. package/packages/server/src/live-server/live-csp.ts +93 -0
  232. package/packages/server/src/live-server/live-egress.ts +435 -0
  233. package/packages/server/src/live-server/live-exposure.ts +149 -0
  234. package/packages/server/src/live-server/live-log.ts +21 -0
  235. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  236. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  237. package/packages/server/src/live-server/live-server-proxy.ts +326 -34
  238. package/packages/server/src/live-server/live-static.ts +228 -0
  239. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  240. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  241. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  242. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  243. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  244. package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
  245. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  246. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
  247. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
  248. package/packages/server/src/openspec/openspec-poll-worker.ts +286 -44
  249. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  250. package/packages/server/src/openspec/readiness.ts +9 -0
  251. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  252. package/packages/server/src/openspec/workflow-schema.ts +1002 -0
  253. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  254. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  255. package/packages/server/src/package/package-health-scanner.ts +133 -0
  256. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  257. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  258. package/packages/server/src/package/provider-probe.ts +13 -5
  259. package/packages/server/src/pairing/browser-gateway.ts +292 -16
  260. package/packages/server/src/pairing/device-token-services.ts +26 -0
  261. package/packages/server/src/pairing/knock-admission.ts +277 -0
  262. package/packages/server/src/pairing/paired-devices.ts +335 -22
  263. package/packages/server/src/pairing/pairing.ts +188 -31
  264. package/packages/server/src/pairing/socket-locality.ts +26 -0
  265. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  266. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  267. package/packages/server/src/peer-servers.ts +77 -0
  268. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  269. package/packages/server/src/persistence/boot-state.ts +48 -1
  270. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  271. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  272. package/packages/server/src/persistence/preferences-store.ts +125 -7
  273. package/packages/server/src/pi/bridge-channel.ts +33 -0
  274. package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
  275. package/packages/server/src/pi/folder-commands.ts +141 -0
  276. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  277. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  278. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  279. package/packages/server/src/pi/host-project-trust.ts +166 -33
  280. package/packages/server/src/pi/pi-gateway.ts +283 -29
  281. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  282. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  283. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  284. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  285. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  286. package/packages/server/src/pi/trust-challenges.ts +38 -0
  287. package/packages/server/src/pi-agent-settings.ts +701 -100
  288. package/packages/server/src/pi-settings-themes.ts +104 -0
  289. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  290. package/packages/server/src/plugin-event-seam.ts +116 -4
  291. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  292. package/packages/server/src/questions/brief-generator.ts +138 -0
  293. package/packages/server/src/questions/brief-model.ts +55 -0
  294. package/packages/server/src/questions/brief-policy.ts +36 -0
  295. package/packages/server/src/questions/brief-prompt.ts +92 -0
  296. package/packages/server/src/questions/brief-runtime.ts +50 -0
  297. package/packages/server/src/questions/question-answer.ts +55 -0
  298. package/packages/server/src/questions/question-broadcast.ts +106 -0
  299. package/packages/server/src/questions/question-files.ts +128 -0
  300. package/packages/server/src/questions/question-routes.ts +126 -0
  301. package/packages/server/src/questions/question-snapshot.ts +150 -0
  302. package/packages/server/src/questions/question-stack.ts +57 -0
  303. package/packages/server/src/questions/question-store.ts +477 -0
  304. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  305. package/packages/server/src/routes/access-routes.ts +274 -6
  306. package/packages/server/src/routes/acme-routes.ts +190 -0
  307. package/packages/server/src/routes/acp-routes.ts +16 -0
  308. package/packages/server/src/routes/addons-routes.ts +221 -0
  309. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  310. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  311. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  312. package/packages/server/src/routes/file-routes.ts +620 -209
  313. package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
  314. package/packages/server/src/routes/folder-project-routes.ts +105 -0
  315. package/packages/server/src/routes/git-routes.ts +334 -203
  316. package/packages/server/src/routes/grep-routes.ts +38 -14
  317. package/packages/server/src/routes/known-servers-routes.ts +433 -55
  318. package/packages/server/src/routes/live-server-routes.ts +438 -7
  319. package/packages/server/src/routes/local-proof-routes.ts +26 -7
  320. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  321. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  322. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  323. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  324. package/packages/server/src/routes/openspec-routes.ts +636 -55
  325. package/packages/server/src/routes/package-health-routes.ts +140 -0
  326. package/packages/server/src/routes/package-routes.ts +86 -11
  327. package/packages/server/src/routes/pairing-routes.ts +303 -33
  328. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  329. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  330. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  331. package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
  332. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  333. package/packages/server/src/routes/provider-auth-routes.ts +37 -7
  334. package/packages/server/src/routes/provider-routes.ts +29 -0
  335. package/packages/server/src/routes/resource-activation-routes.ts +33 -35
  336. package/packages/server/src/routes/session-routes.ts +100 -9
  337. package/packages/server/src/routes/system-routes.ts +286 -33
  338. package/packages/server/src/routes/tls-routes.ts +55 -0
  339. package/packages/server/src/routes/ui-link-base.ts +88 -0
  340. package/packages/server/src/routes/user-routes.ts +192 -0
  341. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  342. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  343. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  344. package/packages/server/src/server.ts +1537 -246
  345. package/packages/server/src/services/attached-driver.ts +175 -0
  346. package/packages/server/src/services/change-notifier.ts +55 -0
  347. package/packages/server/src/services/cli-service.ts +450 -0
  348. package/packages/server/src/services/command-runner.ts +92 -0
  349. package/packages/server/src/services/definitions-store.ts +121 -0
  350. package/packages/server/src/services/driver.ts +112 -0
  351. package/packages/server/src/services/health.ts +94 -0
  352. package/packages/server/src/services/leases.ts +117 -0
  353. package/packages/server/src/services/log-text.ts +97 -0
  354. package/packages/server/src/services/native-driver.ts +283 -0
  355. package/packages/server/src/services/oci-driver.ts +590 -0
  356. package/packages/server/src/services/output-capture.ts +183 -0
  357. package/packages/server/src/services/paths.ts +82 -0
  358. package/packages/server/src/services/ports.ts +26 -0
  359. package/packages/server/src/services/routes.ts +140 -0
  360. package/packages/server/src/services/runtime-detect.ts +108 -0
  361. package/packages/server/src/services/secret-delivery.ts +61 -0
  362. package/packages/server/src/services/secrets-resolver.ts +145 -0
  363. package/packages/server/src/services/secrets-store.ts +137 -0
  364. package/packages/server/src/services/service-manager.ts +1565 -0
  365. package/packages/server/src/services/start-record.ts +66 -0
  366. package/packages/server/src/services/state-machine.ts +241 -0
  367. package/packages/server/src/session/archive-sweeper.ts +92 -3
  368. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  369. package/packages/server/src/session/hydration-state.ts +148 -0
  370. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  371. package/packages/server/src/session/memory-session-manager.ts +60 -0
  372. package/packages/server/src/session/name-provenance.ts +102 -0
  373. package/packages/server/src/session/open-tool-calls.ts +15 -6
  374. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  375. package/packages/server/src/session/retained-transcript.ts +9 -2
  376. package/packages/server/src/session/session-api.ts +47 -12
  377. package/packages/server/src/session/session-archive.ts +56 -4
  378. package/packages/server/src/session/session-diff-cache.ts +11 -4
  379. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  380. package/packages/server/src/session/session-load-worker.ts +11 -2
  381. package/packages/server/src/session/session-scanner.ts +73 -3
  382. package/packages/server/src/session/session-to-meta.ts +15 -0
  383. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  384. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  385. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  386. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  387. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  388. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  389. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  390. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  391. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  392. package/packages/server/src/terminal/terminal-manager.ts +75 -1
  393. package/packages/server/src/tls/cert-files.ts +228 -0
  394. package/packages/server/src/tls/cert-manager.ts +703 -0
  395. package/packages/server/src/tls/cert-store.ts +69 -0
  396. package/packages/server/src/tls/source-registry.ts +71 -0
  397. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  398. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  399. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  400. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  401. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  402. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  403. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  404. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  405. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  406. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  407. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  408. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  409. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  410. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  411. package/packages/server/src/tls/tls-config-validation.ts +94 -0
  412. package/packages/server/src/tls/tls-listener.ts +351 -0
  413. package/packages/server/src/tls/types.ts +80 -0
  414. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  415. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  416. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  417. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  418. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  419. package/packages/server/src/vault/vault-bindings.ts +101 -0
  420. package/packages/server/src/vault/vault-delivery-hub.ts +424 -0
  421. package/packages/server/src/vault/vault-grants.ts +260 -0
  422. package/packages/server/src/vault/vault-import.ts +161 -0
  423. package/packages/server/src/vault/vault-permissions.ts +39 -0
  424. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  425. package/packages/server/src/vault/vault-projects.ts +156 -0
  426. package/packages/server/src/vault/vault-routes.ts +277 -0
  427. package/packages/server/src/vault/vault-store.ts +371 -0
  428. package/packages/server/src/watch-files-handler.ts +66 -0
  429. package/packages/shared/package.json +5 -2
  430. package/packages/shared/src/acp/acp-config.ts +123 -0
  431. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  432. package/packages/shared/src/acp/paths.ts +36 -0
  433. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  434. package/packages/shared/src/acp/update-model.ts +574 -0
  435. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  436. package/packages/shared/src/bind-reachability.ts +21 -2
  437. package/packages/shared/src/boot-state.ts +6 -0
  438. package/packages/shared/src/browser-host-identity.ts +49 -0
  439. package/packages/shared/src/browser-host-ipc.ts +107 -0
  440. package/packages/shared/src/browser-protocol.ts +533 -73
  441. package/packages/shared/src/canonical-subject.ts +27 -2
  442. package/packages/shared/src/canvas-declare.ts +27 -0
  443. package/packages/shared/src/card-sections.ts +185 -1
  444. package/packages/shared/src/chrome-profiles.ts +188 -0
  445. package/packages/shared/src/config.ts +817 -51
  446. package/packages/shared/src/containment-guard.ts +35 -0
  447. package/packages/shared/src/custom-event-groups.ts +5 -2
  448. package/packages/shared/src/cwd-guard.ts +381 -1
  449. package/packages/shared/src/dashboard-paths.ts +12 -0
  450. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  451. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  452. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  453. package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -0
  454. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  455. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  456. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  457. package/packages/shared/src/dashboard-plugin/index.ts +9 -3
  458. package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
  459. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  460. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  461. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  462. package/packages/shared/src/dashboard-plugin/slot-props.ts +139 -2
  463. package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
  464. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  465. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
  466. package/packages/shared/src/dashboard-starter.ts +30 -0
  467. package/packages/shared/src/display-name.ts +42 -0
  468. package/packages/shared/src/display-prefs.ts +13 -0
  469. package/packages/shared/src/doctor-core.ts +119 -134
  470. package/packages/shared/src/enabled-models-match.ts +47 -0
  471. package/packages/shared/src/event-forward-declaration.ts +187 -0
  472. package/packages/shared/src/file-kind.ts +54 -2
  473. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  474. package/packages/shared/src/grammar-types.ts +3 -1
  475. package/packages/shared/src/host-admission.ts +2 -1
  476. package/packages/shared/src/host-port.ts +34 -0
  477. package/packages/shared/src/launcher-origin.ts +26 -0
  478. package/packages/shared/src/live-server.ts +141 -0
  479. package/packages/shared/src/local-credential-proof.ts +219 -0
  480. package/packages/shared/src/local-proof-signal.ts +16 -0
  481. package/packages/shared/src/loopback-host.ts +26 -0
  482. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  483. package/packages/shared/src/markup-repair/types.ts +13 -0
  484. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  485. package/packages/shared/src/md-table-cell.ts +11 -0
  486. package/packages/shared/src/mdns-discovery.ts +414 -45
  487. package/packages/shared/src/models-json-reader.ts +6 -0
  488. package/packages/shared/src/nav-intent.ts +29 -0
  489. package/packages/shared/src/openspec-dependencies.ts +760 -0
  490. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  491. package/packages/shared/src/openspec-poller.ts +213 -11
  492. package/packages/shared/src/openspec-status-all.ts +393 -0
  493. package/packages/shared/src/operate-required.ts +29 -0
  494. package/packages/shared/src/pairing-knock-client.ts +301 -0
  495. package/packages/shared/src/pairing-knock.ts +71 -0
  496. package/packages/shared/src/pairing-refusal.ts +32 -0
  497. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  498. package/packages/shared/src/pi-settings-keys.ts +9 -0
  499. package/packages/shared/src/pi-settings-schema.ts +285 -0
  500. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  501. package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
  502. package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
  503. package/packages/shared/src/pi-trust-mirror.ts +354 -0
  504. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  505. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  506. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  507. package/packages/shared/src/platform/git-source.ts +88 -26
  508. package/packages/shared/src/platform/git.ts +210 -4
  509. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  510. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  511. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  512. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  513. package/packages/shared/src/platform/node-spawn.ts +1 -2
  514. package/packages/shared/src/platform/openspec.ts +129 -31
  515. package/packages/shared/src/platform/process-scan.ts +199 -1
  516. package/packages/shared/src/platform/process.ts +99 -4
  517. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  518. package/packages/shared/src/platform/runner.ts +46 -2
  519. package/packages/shared/src/platform/select-git-source.ts +7 -0
  520. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  521. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  522. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  523. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  524. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  525. package/packages/shared/src/preview-egress.ts +138 -0
  526. package/packages/shared/src/project-name.ts +42 -0
  527. package/packages/shared/src/project-root.ts +16 -0
  528. package/packages/shared/src/prompt-answer.ts +183 -0
  529. package/packages/shared/src/protocol.ts +172 -8
  530. package/packages/shared/src/question-types.ts +73 -0
  531. package/packages/shared/src/recommended-extensions.ts +98 -23
  532. package/packages/shared/src/recovery-timing.ts +39 -0
  533. package/packages/shared/src/redaction.ts +50 -0
  534. package/packages/shared/src/remote-credentials.ts +63 -0
  535. package/packages/shared/src/rest-api.ts +533 -3
  536. package/packages/shared/src/role-config-disk.ts +23 -0
  537. package/packages/shared/src/role-schema.ts +79 -0
  538. package/packages/shared/src/route-tiers.ts +181 -0
  539. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  540. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  541. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  542. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  543. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  544. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  545. package/packages/shared/src/safe-local-path.ts +24 -0
  546. package/packages/shared/src/sanitize-profiles.ts +98 -0
  547. package/packages/shared/src/server-identity.ts +51 -15
  548. package/packages/shared/src/server-launcher.ts +21 -34
  549. package/packages/shared/src/server-pinning.ts +136 -2
  550. package/packages/shared/src/server-routes.ts +462 -0
  551. package/packages/shared/src/services/offers.ts +114 -0
  552. package/packages/shared/src/services/schema.ts +628 -0
  553. package/packages/shared/src/services/status.ts +169 -0
  554. package/packages/shared/src/session-meta.ts +59 -2
  555. package/packages/shared/src/session-name.ts +8 -0
  556. package/packages/shared/src/session-ui-path.ts +11 -0
  557. package/packages/shared/src/skill-block-parser.ts +14 -0
  558. package/packages/shared/src/source-matching.ts +5 -1
  559. package/packages/shared/src/state-replay.ts +19 -0
  560. package/packages/shared/src/terminal-safe.ts +24 -0
  561. package/packages/shared/src/tls-only-token.ts +16 -0
  562. package/packages/shared/src/tls-status.ts +69 -0
  563. package/packages/shared/src/tool-path-resolve.ts +243 -0
  564. package/packages/shared/src/tool-registry/definitions.ts +31 -9
  565. package/packages/shared/src/tool-registry/index.ts +2 -2
  566. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  567. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  568. package/packages/shared/src/tunnel-provider.ts +3 -2
  569. package/packages/shared/src/types.ts +170 -9
  570. package/packages/shared/src/url-policy.ts +96 -0
  571. package/packages/shared/src/vault-delivery.ts +88 -0
  572. package/packages/shared/src/vault-origin.ts +51 -0
  573. package/packages/shared/src/vault-project-key.ts +53 -0
  574. package/packages/shared/src/worktree-init-hook.ts +69 -0
  575. package/packages/shared/src/ws-message-tiers.ts +136 -0
  576. package/tsconfig.base.json +1 -0
@@ -6,6 +6,7 @@ import crypto from "node:crypto";
6
6
  import fs from "node:fs";
7
7
  import type { AuthConfig, AuthProviderConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
8
8
  import { CONFIG_FILE, writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import { isTier, rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
9
10
  import jwt from "jsonwebtoken";
10
11
  import { getTunnelUrl } from "../tunnel/tunnel.js";
11
12
 
@@ -23,10 +24,16 @@ export interface ResolvedProvider {
23
24
  }
24
25
 
25
26
  export interface AuthUser {
26
- sub: string; // email
27
+ sub: string; // email (OAuth) or directory user id (passkey)
27
28
  name: string;
28
29
  username: string;
29
30
  provider: string;
31
+ /**
32
+ * Session tier. Optional: a JWT issued before this claim existed has none
33
+ * and is treated as `operate` on validation.
34
+ * See change: add-passkey-user-auth (D4).
35
+ */
36
+ tier?: Tier;
30
37
  }
31
38
 
32
39
  export interface TokenPayload extends AuthUser {
@@ -125,14 +132,32 @@ async function resolveProvider(
125
132
 
126
133
  // ─── Auth Secret Management ─────────────────────────────────────────────────
127
134
 
135
+ /** Minimum recommended `auth.secret` length in characters (32 hex = 16 bytes of entropy at worst). */
136
+ const MIN_SECRET_LENGTH = 32;
137
+ /** Module-level once flag: the short-secret warning prints once per process. */
138
+ let shortSecretWarned = false;
139
+
128
140
  /**
129
- * Ensure the auth config has a secret. If missing, generate one and persist.
141
+ * Ensure the auth config has a secret. If missing, generate one (32 random
142
+ * bytes, 64 hex chars) and persist. An existing non-empty secret is ALWAYS
143
+ * kept byte-identical (no forced logout); one shorter than 32 characters logs a
144
+ * single startup warning recommending rotation and never prints the value.
130
145
  * Returns the secret string.
146
+ * See change: harden-auth-credentials (D1).
131
147
  */
132
148
  export function ensureAuthSecret(authConfig: AuthConfig): string {
133
- if (authConfig.secret) return authConfig.secret;
149
+ if (authConfig.secret) {
150
+ if (authConfig.secret.length < MIN_SECRET_LENGTH && !shortSecretWarned) {
151
+ shortSecretWarned = true;
152
+ console.warn(
153
+ `⚠️ auth.secret is shorter than ${MIN_SECRET_LENGTH} characters; consider rotating it ` +
154
+ "(replace it with a random 64-hex value — rotation signs out existing sessions).",
155
+ );
156
+ }
157
+ return authConfig.secret;
158
+ }
134
159
 
135
- const secret = crypto.randomBytes(16).toString("hex"); // 32-char hex
160
+ const secret = crypto.randomBytes(32).toString("hex"); // 64-char hex
136
161
  authConfig.secret = secret;
137
162
 
138
163
  // Persist back to config file
@@ -157,7 +182,13 @@ export const COOKIE_NAME = "pi_dash_token";
157
182
 
158
183
  export function signToken(user: AuthUser, secret: string): string {
159
184
  return jwt.sign(
160
- { sub: user.sub, name: user.name, username: user.username, provider: user.provider },
185
+ {
186
+ sub: user.sub,
187
+ name: user.name,
188
+ username: user.username,
189
+ provider: user.provider,
190
+ ...(user.tier ? { tier: user.tier } : {}),
191
+ },
161
192
  secret,
162
193
  { expiresIn: TOKEN_EXPIRY },
163
194
  );
@@ -165,13 +196,63 @@ export function signToken(user: AuthUser, secret: string): string {
165
196
 
166
197
  export function verifyToken(token: string, secret: string): TokenPayload | null {
167
198
  try {
168
- const payload = jwt.verify(token, secret) as TokenPayload;
199
+ // Pin HS256: reject `none` and every other alg (algorithm confusion).
200
+ // See change: harden-auth-credentials (D1).
201
+ const payload = jwt.verify(token, secret, { algorithms: ["HS256"] }) as TokenPayload;
202
+ // A present-but-unknown tier is never widened to `operate`: reject the
203
+ // token outright (fail closed). See change: add-passkey-user-auth (D4).
204
+ if (payload.tier !== undefined && !isTier(payload.tier)) return null;
169
205
  return payload;
170
206
  } catch {
171
207
  return null;
172
208
  }
173
209
  }
174
210
 
211
+ /**
212
+ * `groups` claim of an OIDC `id_token`, or undefined.
213
+ *
214
+ * The token comes straight from the provider's token endpoint over the
215
+ * back-channel (TLS), so per OIDC Core §3.1.3.7 its signature need not be
216
+ * re-validated here; the `aud` claim must still name this client, so a token
217
+ * minted for another relying party is never trusted. Only `groups` is read.
218
+ * Non-string entries are dropped. See change: add-passkey-user-auth (D4).
219
+ */
220
+ export function idTokenGroups(idToken: string | undefined, clientId: string): string[] | undefined {
221
+ if (!idToken) return undefined;
222
+ const part = idToken.split(".")[1];
223
+ if (!part) return undefined;
224
+ let claims: { aud?: unknown; groups?: unknown };
225
+ try {
226
+ claims = JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
227
+ } catch {
228
+ return undefined;
229
+ }
230
+ const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
231
+ if (!aud.includes(clientId)) return undefined;
232
+ if (!Array.isArray(claims.groups)) return undefined;
233
+ return (claims.groups as unknown[]).filter((g): g is string => typeof g === "string");
234
+ }
235
+
236
+ /**
237
+ * Map an OIDC `groups` claim to a session tier (D4).
238
+ *
239
+ * - `groupTiers` unconfigured/empty → `operate` (legacy behaviour).
240
+ * - configured → the HIGHEST tier among matching groups; no match → `null`
241
+ * (login refused — fail closed).
242
+ */
243
+ export function resolveGroupTier(
244
+ groups: readonly string[] | undefined,
245
+ groupTiers: Record<string, Tier> | undefined,
246
+ ): Tier | null {
247
+ if (!groupTiers || Object.keys(groupTiers).length === 0) return "operate";
248
+ let best: Tier | null = null;
249
+ for (const g of groups ?? []) {
250
+ const t = Object.hasOwn(groupTiers, g) ? groupTiers[g] : undefined;
251
+ if (t && (best === null || rank(t) > rank(best))) best = t;
252
+ }
253
+ return best;
254
+ }
255
+
175
256
  // ─── Cookie Parsing ─────────────────────────────────────────────────────────
176
257
 
177
258
  /**
@@ -362,13 +443,15 @@ export function buildAuthorizeUrl(
362
443
  }
363
444
 
364
445
  /**
365
- * Exchange an authorization code for an access token.
446
+ * Exchange an authorization code for tokens: the access token plus, for OIDC
447
+ * providers, the `id_token` (read for its `groups` claim — see
448
+ * `idTokenGroups`). See change: add-passkey-user-auth (D4).
366
449
  */
367
450
  export async function exchangeCode(
368
451
  provider: ResolvedProvider,
369
452
  code: string,
370
453
  redirectUri: string,
371
- ): Promise<string | null> {
454
+ ): Promise<{ accessToken: string; idToken?: string } | null> {
372
455
  try {
373
456
  const body = new URLSearchParams({
374
457
  client_id: provider.clientId,
@@ -395,7 +478,11 @@ export async function exchangeCode(
395
478
  if (!res.ok) return null;
396
479
 
397
480
  const data = await res.json();
398
- return data.access_token ?? null;
481
+ if (typeof data.access_token !== "string" || !data.access_token) return null;
482
+ return {
483
+ accessToken: data.access_token,
484
+ ...(typeof data.id_token === "string" ? { idToken: data.id_token } : {}),
485
+ };
399
486
  } catch {
400
487
  return null;
401
488
  }
@@ -408,7 +495,7 @@ export async function exchangeCode(
408
495
  export async function fetchUserInfo(
409
496
  provider: ResolvedProvider,
410
497
  accessToken: string,
411
- ): Promise<{ email: string; name: string; username: string } | null> {
498
+ ): Promise<{ email: string; name: string; username: string; groups?: string[] } | null> {
412
499
  try {
413
500
  const res = await fetch(provider.userInfoUrl, {
414
501
  headers: { Authorization: `Bearer ${accessToken}` },
@@ -440,7 +527,11 @@ export async function fetchUserInfo(
440
527
  const email = data.email;
441
528
  const name = data.name || data.preferred_username || data.sub || "Unknown";
442
529
  const username = data.preferred_username || data.sub || "";
443
- return email ? { email, name, username } : null;
530
+ // `groups` (userinfo) feeds `auth.groupTiers`. Non-string entries dropped.
531
+ const groups = Array.isArray(data.groups)
532
+ ? (data.groups as unknown[]).filter((g): g is string => typeof g === "string")
533
+ : undefined;
534
+ return email ? { email, name, username, ...(groups ? { groups } : {}) } : null;
444
535
  } catch {
445
536
  return null;
446
537
  }
@@ -19,8 +19,15 @@
19
19
  * (`/api/ws-ticket`) and presents only that ticket on the socket
20
20
  * (see `ws-ticket.ts`).
21
21
  */
22
- import type { FastifyInstance, FastifyRequest } from "fastify";
22
+ import type { TLSSocket } from "node:tls";
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";
23
25
  import type { PairedDeviceRegistry } from "../pairing/paired-devices.js";
26
+ import { auditLine, auditPrefix } from "./audit-log.js";
27
+ import { hasProxyForwardingHeaders } from "./localhost-guard.js";
28
+ import { isLoopbackRange } from "./loopback.js";
29
+ import { bearerChannelOf } from "./proven-tls.js";
30
+ import { isSecureOrigin } from "./secure-origin.js";
24
31
 
25
32
  /** Extract a `Bearer` token from an Authorization header, or null. */
26
33
  export function parseBearerHeader(authorization: string | undefined): string | null {
@@ -36,15 +43,64 @@ export function parseBearerHeader(authorization: string | undefined): string | n
36
43
  }
37
44
 
38
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 };
39
56
  /** 400 days — `PairedDeviceRegistry` rows carry no expiry; revocation is the kill switch. */
40
57
  const DEVICE_COOKIE_MAX_AGE_S = 400 * 24 * 60 * 60;
41
58
 
59
+ /**
60
+ * `Secure` attribute for the device cookie, from the exchanging request's own
61
+ * transport: always `Secure` over a TLS socket; NOT `Secure` for a direct
62
+ * plain-http connection (no forwarding header) from a peer outside the loopback range (a browser paired
63
+ * over `http://<lan-ip>` would otherwise silently drop the cookie and lose its
64
+ * single-use bearer); otherwise the global resolved-base rule — so a tunnel / TLS
65
+ * reverse proxy that forwards plain http on the loopback hop still gets `Secure`.
66
+ * Uses the SOCKET peer, never `request.ip`. See change: add-lan-knock-pairing (D15).
67
+ */
68
+ function deviceCookieSecure(request: FastifyRequest, globalSecure: () => boolean): boolean {
69
+ const socket = request.raw.socket as TLSSocket;
70
+ if (socket.encrypted) return true;
71
+ const peer = socket.remoteAddress;
72
+ // DIRECT only: a request carrying proxy-forwarding headers came through a TLS-terminating
73
+ // proxy that may sit on another host/container (peer 172.x), and keeps the global rule.
74
+ if (peer && !isLoopbackRange(peer) && !hasProxyForwardingHeaders(request.headers)) return false;
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());
79
+ }
80
+
42
81
  /** Pathname of a request URL (no query/fragment). */
43
82
  function pathnameOf(url: string): string {
44
83
  const q = url.search(/[?#]/);
45
84
  return q < 0 ? url : url.slice(0, q);
46
85
  }
47
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
+
48
104
  /** Register the REST bearer onRequest branch. */
49
105
  export function registerBearerAuth(
50
106
  fastify: FastifyInstance,
@@ -58,17 +114,23 @@ export function registerBearerAuth(
58
114
  /* already decorated by another plugin */
59
115
  }
60
116
  }
61
- fastify.addHook("onRequest", async (request: FastifyRequest) => {
117
+ fastify.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
62
118
  if ((request as any).isAuthenticated) return;
63
119
  const headerToken = parseBearerHeader(request.headers.authorization);
64
- // Authorization wins. The cookie is a fallback for `/api/*` URLs only and is
65
- // never consulted when an Authorization header is present.
66
- const cookieToken =
67
- !request.headers.authorization && pathnameOf(request.url).startsWith("/api/")
68
- ? ((request.cookies as Record<string, string | undefined> | undefined)?.[DEVICE_COOKIE] ?? null)
69
- : null;
70
- const token = headerToken ?? cookieToken;
71
- 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;
72
134
  if (verified) {
73
135
  (request as any).isAuthenticated = true;
74
136
  // Additive marker: HOW the request authenticated. `operatorGuard` on the
@@ -95,7 +157,7 @@ export function registerDeviceSessionRoutes(
95
157
  ): void {
96
158
  fastify.post("/api/device-session", async (request, reply) => {
97
159
  const bearer = parseBearerHeader(request.headers.authorization);
98
- if (!bearer || !deps.registry.verify(bearer)) {
160
+ if (!bearer || !deps.registry.verify(bearer, bearerChannelOf(request.raw))) {
99
161
  reply.code(401);
100
162
  return { success: false as const, error: "device bearer required" };
101
163
  }
@@ -103,7 +165,7 @@ export function registerDeviceSessionRoutes(
103
165
  path: "/api/",
104
166
  httpOnly: true,
105
167
  sameSite: "strict",
106
- secure: deps.isSecure(),
168
+ secure: deviceCookieSecure(request, deps.isSecure),
107
169
  maxAge: DEVICE_COOKIE_MAX_AGE_S,
108
170
  });
109
171
  return { success: true as const };
@@ -14,6 +14,14 @@ import { isHostAdmitted } from "./host-admission.js";
14
14
  import { isBypassedHost } from "./localhost-guard.js";
15
15
  import type { WsRouteScope } from "./ws-ticket.js";
16
16
 
17
+ /**
18
+ * Methods advertised on CORS preflight. `@fastify/cors` v11 defaults to the
19
+ * safelisted GET,HEAD,POST, which blocks every cross-origin PUT/PATCH/DELETE
20
+ * (e.g. the Electron renderer). Widens no origin: this list only matters for
21
+ * origins the allow-decision already admits; auth still gates each mutation.
22
+ */
23
+ export const CORS_ALLOWED_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"];
24
+
17
25
  export interface CorsOriginOptions {
18
26
  /** Explicitly configured allowed origins (`cors.allowedOrigins`). */
19
27
  configuredOrigins: string[];
@@ -36,13 +44,14 @@ export interface CorsOriginOptions {
36
44
  /**
37
45
  * Allow ANY `*.share.zrok.io` / `*.shares.zrok.io` host (branch 5).
38
46
  *
39
- * `true` (default) for CORS readability, where the allowance shipped and is
40
- * load-bearing for tunnel-URL rotation. `false` for ADMISSION (WS upgrade,
41
- * mutating REST): zrok shares are free and self-service, so a stranger share
42
- * is very likely same-site to the victim's tunnel and the wildcard would let
43
- * it defeat even the OAuth'd gate. Tunnels the dashboard itself runs are live
44
- * tunnel origins (branch 4/4b) and stay admitted.
45
- * See change: fix-ws-origin-cswsh (D1 rule 2).
47
+ * Opt-in: only the boolean `true` enables it (`cors.allowZrokWildcard`,
48
+ * default `false`). Zrok shares are free and self-service, so a stranger
49
+ * share is very likely same-site to the victim's tunnel; the wildcard would
50
+ * let it read responses (CORS) and, for admission (WS upgrade, mutating
51
+ * REST), defeat even the OAuth'd gate — admission therefore ALWAYS forces it
52
+ * off. Tunnels the dashboard itself runs are live tunnel origins (branch
53
+ * 4/4b) and stay allowed with the wildcard off.
54
+ * See change: fix-ws-origin-cswsh (D1 rule 2), harden-cors-and-csp-reporting (B19).
46
55
  */
47
56
  allowZrokWildcard?: boolean;
48
57
  /** Top-level `allowedHosts` (live) — host-admission only. */
@@ -51,6 +60,8 @@ export interface CorsOriginOptions {
51
60
  publicBaseUrls?: string[];
52
61
  /** The boot-time bind address — host-admission only. */
53
62
  bindHost?: string;
63
+ /** TLS-listener certificate names (live) — host-admission only. See change: add-tailscale-cert-tls. */
64
+ tlsListenerNames?: () => string[];
54
65
  /**
55
66
  * Host-gate rollout mode (live). In `enforce` the same-origin-by-Host rule
56
67
  * additionally requires the `Host` to be admissible (D1); in `report` it is
@@ -61,6 +72,41 @@ export interface CorsOriginOptions {
61
72
  hostGateMode?: "report" | "enforce";
62
73
  }
63
74
 
75
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: detecting them is the point.
76
+ const HAS_CONTROL = /[\u0000-\u001f\u007f]/;
77
+
78
+ /**
79
+ * Canonical form of an origin or URL for tunnel comparison: lowercase scheme
80
+ * and host, default port elided, ONE trailing hostname dot stripped, path /
81
+ * query dropped. `null` for anything that is not a well-formed http(s) origin
82
+ * (padding, control characters, bad port, other schemes).
83
+ *
84
+ * A trailing-dot origin equals its dotless form, matching host admission.
85
+ * See change: harden-cors-and-csp-reporting (R2).
86
+ */
87
+ export function canonicalOrigin(raw: string): string | null {
88
+ if (typeof raw !== "string" || raw !== raw.trim() || HAS_CONTROL.test(raw)) return null;
89
+ try {
90
+ const u = new URL(raw);
91
+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;
92
+ const host = u.hostname.endsWith(".") ? u.hostname.slice(0, -1) : u.hostname;
93
+ if (host === "") return null;
94
+ return `${u.protocol}//${host}${u.port ? `:${u.port}` : ""}`;
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /** Run a dynamic getter; a throwing getter means "nothing live", never a 500. */
101
+ function safely<T>(read: (() => T) | undefined, fallback: T): T {
102
+ if (!read) return fallback;
103
+ try {
104
+ return read() ?? fallback;
105
+ } catch {
106
+ return fallback;
107
+ }
108
+ }
109
+
64
110
  /**
65
111
  * Why a CORS origin decision came out the way it did.
66
112
  *
@@ -101,7 +147,8 @@ export interface CorsAllowance {
101
147
  * 3. Loopback host (any port) → allow.
102
148
  * 4. Active zrok tunnel URL → allow.
103
149
  * 4b. Any CURRENTLY connected tunnel origin (any provider) → allow.
104
- * 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow.
150
+ * 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow, ONLY
151
+ * when `allowZrokWildcard === true` (opt-in, default off).
105
152
  * 6. Neutral static PWA shell `https://pi-dashboard.dev` → allow.
106
153
  * 7. Explicitly configured origin → allow.
107
154
  * 8. Origin host matches a trusted network (CIDR / wildcard / exact) → allow.
@@ -120,6 +167,9 @@ export function classifyCorsOrigin(
120
167
  // 2. Opaque-origin document. Never echo an ACAO for it, so an embedded
121
168
  // untrusted app cannot call dashboard APIs even cross-origin.
122
169
  if (origin === "null") return { allowed: false, revocable: false, kind: "opaque" };
170
+ // Padding / control characters are never sent by a browser; `new URL()`
171
+ // silently strips them, so do not normalize them into a trusted value.
172
+ if (origin !== origin.trim() || HAS_CONTROL.test(origin)) return { allowed: false, revocable: false, kind: "denied" };
123
173
  try {
124
174
  const u = new URL(origin);
125
175
  const host = u.hostname;
@@ -127,26 +177,25 @@ export function classifyCorsOrigin(
127
177
  if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1") {
128
178
  return allow("loopback");
129
179
  }
180
+ // Tunnel branches compare CANONICAL origins (case, default port, one
181
+ // trailing dot, path), so the recorded URL and the browser's Origin agree.
182
+ const requestOrigin = canonicalOrigin(origin);
130
183
  // 4. Active zrok tunnel URL (dynamic — rotation without restart).
131
- const tunnelUrl = opts.getTunnelUrl?.() ?? null;
132
- if (tunnelUrl && origin === tunnelUrl) return allow("active-tunnel");
133
- // 4b. Any live tunnel's origin, for every provider. Compared as ORIGINS,
134
- // not as URLs: a provider reports `https://host/path`, and a browser
135
- // sends `https://host`, so a string equality against the raw URL would
136
- // silently never match for any provider that carries a path.
137
- for (const raw of opts.getLiveTunnelOrigins?.() ?? []) {
138
- let candidate: string;
139
- try {
140
- candidate = new URL(raw).origin;
141
- } catch {
142
- continue;
143
- }
144
- if (candidate === u.origin) return allow("live-tunnel");
184
+ const tunnelUrl = safely(opts.getTunnelUrl, null);
185
+ const canonicalTunnel = tunnelUrl ? canonicalOrigin(tunnelUrl) : null;
186
+ if (requestOrigin && canonicalTunnel && requestOrigin === canonicalTunnel) return allow("active-tunnel");
187
+ // 4b. Any live tunnel's origin, for every provider. Compared as canonical
188
+ // ORIGINS, not URLs: a provider reports `https://host/path`, and a
189
+ // browser sends `https://host`. Malformed entries are skipped.
190
+ for (const raw of safely(opts.getLiveTunnelOrigins, [] as string[])) {
191
+ const candidate = canonicalOrigin(raw);
192
+ if (candidate && requestOrigin && candidate === requestOrigin) return allow("live-tunnel");
145
193
  }
146
- // 5. Any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
194
+ // 5. Opt-in only: any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
195
+ const bareHost = host.endsWith(".") ? host.slice(0, -1) : host;
147
196
  if (
148
- opts.allowZrokWildcard !== false &&
149
- (host.endsWith(".share.zrok.io") || host.endsWith(".shares.zrok.io"))
197
+ opts.allowZrokWildcard === true &&
198
+ (bareHost.endsWith(".share.zrok.io") || bareHost.endsWith(".shares.zrok.io"))
150
199
  ) {
151
200
  return allow("zrok-wildcard");
152
201
  }
@@ -217,7 +266,11 @@ export function isSameOriginByHost(
217
266
  try {
218
267
  const o = new URL(origin);
219
268
  const h = new URL(`${o.protocol}//${hostHeader}`);
220
- if (h.host === "" || o.host !== h.host) return false;
269
+ if (h.host === "") return false;
270
+ // Canonical compare: case, default port and one trailing dot all agree.
271
+ const co = canonicalOrigin(origin);
272
+ const ch = canonicalOrigin(`${o.protocol}//${hostHeader}`);
273
+ if (!co || !ch || co !== ch) return false;
221
274
  } catch {
222
275
  return false;
223
276
  }
@@ -255,16 +308,20 @@ export function isOriginAdmitted(
255
308
  * WS upgrade admission, per route scope.
256
309
  *
257
310
  * `live` admits the opaque `Origin: null` — the sandboxed preview iframe is its
258
- * only intended client and rejecting it would silently break HMR (D3). Every
259
- * other scope (including `bridge` and the unrouted `null` scope) is strict.
311
+ * only intended client and rejecting it would silently break HMR (D3) — but ONLY
312
+ * for an upgrade that carries a VALID capability (`liveCapabilityValid`): an
313
+ * opaque frame without one would otherwise reach any port target. Every other
314
+ * scope (including `bridge` and the unrouted `null` scope) is strict.
315
+ * See change: improve-canvas-html-and-url-ux (design D10).
260
316
  */
261
317
  export function isWsOriginTrusted(
262
318
  origin: string | undefined,
263
319
  hostHeader: string | undefined,
264
320
  scope: WsRouteScope | null,
265
321
  opts: CorsOriginOptions,
322
+ liveCapabilityValid = false,
266
323
  ): boolean {
267
- if (scope === "live" && origin === "null") return true;
324
+ if (scope === "live" && origin === "null") return liveCapabilityValid;
268
325
  return isOriginAdmitted(origin, hostHeader, opts);
269
326
  }
270
327
 
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Shared path contract for the baseline CSP report sink. Emission (`csp.ts`)
3
+ * and the sink route (`csp-report-sink.ts`) both import from here so the
4
+ * `report-uri` a header advertises can never drift from the route that serves it.
5
+ *
6
+ * `/__pi/csp-report/:policy` sits at the root, OUTSIDE guard jurisdiction
7
+ * (`/api`, `/v1`, `/editor`, `/live`), and is distinct from the per-preview
8
+ * `/live/<id>/__pi/csp-report` sink.
9
+ *
10
+ * See change: harden-cors-and-csp-reporting (D8).
11
+ */
12
+
13
+ export const CSP_REPORT_PREFIX = "/__pi/csp-report/";
14
+
15
+ /** Policy labels a report can be filed under; anything else → 404. */
16
+ export const CSP_REPORT_POLICIES = ["baseline", "strict", "trusted-types"] as const;
17
+ export type CspReportPolicy = (typeof CSP_REPORT_POLICIES)[number];
18
+
19
+ export function isCspReportPolicy(v: string): v is CspReportPolicy {
20
+ return (CSP_REPORT_POLICIES as readonly string[]).includes(v);
21
+ }
22
+
23
+ /** `/__pi/csp-report/<policy>` */
24
+ export function cspReportPath(policy: CspReportPolicy): string {
25
+ return `${CSP_REPORT_PREFIX}${policy}`;
26
+ }
27
+
28
+ /** Reporting API endpoint name declared in `Reporting-Endpoints` (`csp-<policy>`). */
29
+ export function cspReportEndpointName(policy: CspReportPolicy): string {
30
+ return `csp-${policy}`;
31
+ }