@blackbelt-technology/pi-agent-dashboard 0.11.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 (337) hide show
  1. package/AGENTS.md +2 -0
  2. package/README.md +17 -12
  3. package/docs/architecture.md +973 -224
  4. package/package.json +29 -18
  5. package/packages/extension/package.json +16 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +21 -12
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge.ts +272 -260
  13. package/packages/extension/src/command-handler.ts +26 -31
  14. package/packages/extension/src/connection.ts +123 -31
  15. package/packages/extension/src/credential-guard.ts +300 -0
  16. package/packages/extension/src/custom-entry-forward.ts +27 -18
  17. package/packages/extension/src/default-model-apply.ts +83 -0
  18. package/packages/extension/src/flow-event-wiring.ts +19 -95
  19. package/packages/extension/src/followup-drain.ts +19 -5
  20. package/packages/extension/src/path-gate/decide.ts +68 -5
  21. package/packages/extension/src/path-gate/handler.ts +16 -8
  22. package/packages/extension/src/path-gate/index.ts +2 -2
  23. package/packages/extension/src/path-gate/roots.ts +15 -3
  24. package/packages/extension/src/path-gate/suppression.ts +3 -0
  25. package/packages/extension/src/pi-env.d.ts +8 -1
  26. package/packages/extension/src/pi-retry-settings.ts +11 -2
  27. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  28. package/packages/extension/src/preview-path-link.ts +151 -0
  29. package/packages/extension/src/project-init/scaffold.ts +98 -35
  30. package/packages/extension/src/project-trust.ts +24 -15
  31. package/packages/extension/src/provider-model-cache.ts +118 -0
  32. package/packages/extension/src/provider-register.ts +428 -28
  33. package/packages/extension/src/retry-tracker.ts +90 -7
  34. package/packages/extension/src/role-manager.ts +4 -2
  35. package/packages/extension/src/role-model-tools.ts +21 -4
  36. package/packages/extension/src/server-auto-start.ts +68 -2
  37. package/packages/extension/src/server-launcher.ts +26 -8
  38. package/packages/extension/src/session-sync.ts +11 -12
  39. package/packages/extension/src/spawn-new-session.ts +22 -0
  40. package/packages/extension/src/steer-buffer.ts +164 -0
  41. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  42. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  43. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  44. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  45. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  46. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  47. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  48. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  49. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  50. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  51. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  52. package/packages/extension/src/terminal-reload.ts +19 -5
  53. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  54. package/packages/extension/src/vault-redaction.ts +4 -3
  55. package/packages/server/package.json +17 -14
  56. package/packages/server/src/access/access-denials.ts +8 -0
  57. package/packages/server/src/access/access-grants.ts +244 -58
  58. package/packages/server/src/access/access-plane.ts +7 -0
  59. package/packages/server/src/access/containment-gate.ts +66 -21
  60. package/packages/server/src/access/denial-hold.ts +3 -0
  61. package/packages/server/src/access/grant-coordinator.ts +17 -1
  62. package/packages/server/src/access/named-grant.ts +3 -0
  63. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
  65. package/packages/server/src/access/planes.ts +1 -0
  66. package/packages/server/src/access/verified-read.ts +24 -7
  67. package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
  68. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  69. package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
  70. package/packages/server/src/auth/audit-log.ts +28 -0
  71. package/packages/server/src/auth/auth-plugin.ts +188 -15
  72. package/packages/server/src/auth/auth.ts +80 -0
  73. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  74. package/packages/server/src/auth/cors-origin.ts +14 -1
  75. package/packages/server/src/auth/credential-envelope.ts +233 -0
  76. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  77. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  78. package/packages/server/src/auth/credential-key.ts +479 -0
  79. package/packages/server/src/auth/credential-migration.ts +162 -0
  80. package/packages/server/src/auth/csp-report-paths.ts +0 -5
  81. package/packages/server/src/auth/csp.ts +74 -36
  82. package/packages/server/src/auth/device-proof.ts +202 -0
  83. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  84. package/packages/server/src/auth/host-admission.ts +7 -0
  85. package/packages/server/src/auth/host-gate.ts +13 -2
  86. package/packages/server/src/auth/localhost-guard.ts +50 -23
  87. package/packages/server/src/auth/locked-json-file.ts +68 -6
  88. package/packages/server/src/auth/models-json-store.ts +269 -0
  89. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  90. package/packages/server/src/auth/node-guard.ts +36 -49
  91. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  92. package/packages/server/src/auth/provider-auth-storage.ts +208 -11
  93. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  94. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  95. package/packages/server/src/auth/provider-key-file.ts +71 -0
  96. package/packages/server/src/auth/provider-readiness.ts +91 -0
  97. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  98. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  99. package/packages/server/src/auth/ws-ticket.ts +1 -1
  100. package/packages/server/src/browse.ts +73 -20
  101. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  102. package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
  103. package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
  104. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  105. package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
  106. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  107. package/packages/server/src/cli/credentials-command.ts +555 -0
  108. package/packages/server/src/cli.ts +21 -16
  109. package/packages/server/src/config-api.ts +34 -38
  110. package/packages/server/src/config-snapshot.ts +149 -0
  111. package/packages/server/src/directory-service.ts +33 -14
  112. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  113. package/packages/server/src/event-wiring.ts +181 -101
  114. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  115. package/packages/server/src/git-worktree/git-operations.ts +1 -1
  116. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  117. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  118. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  119. package/packages/server/src/identity/http-road-classification.ts +5 -1
  120. package/packages/server/src/identity/identity-floor.ts +5 -2
  121. package/packages/server/src/identity/ws-message-scope.ts +10 -3
  122. package/packages/server/src/identity/ws-road-classification.ts +2 -1
  123. package/packages/server/src/lib/browse-roots.ts +13 -2
  124. package/packages/server/src/lib/content-disposition.ts +20 -0
  125. package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
  126. package/packages/server/src/lib/eml.ts +2 -2
  127. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  128. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  129. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  130. package/packages/server/src/lib/grep.ts +4 -1
  131. package/packages/server/src/lib/index-html.ts +2 -2
  132. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  133. package/packages/server/src/lib/office-preview.ts +47 -10
  134. package/packages/server/src/lib/path-containment.ts +45 -12
  135. package/packages/server/src/lib/resolve-file-mention.ts +230 -38
  136. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  137. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  138. package/packages/server/src/lib/writable-md-target.ts +22 -0
  139. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  140. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  141. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  142. package/packages/server/src/live-server/capability-redact.ts +21 -5
  143. package/packages/server/src/live-server/live-capability.ts +416 -52
  144. package/packages/server/src/live-server/live-csp-report.ts +1 -1
  145. package/packages/server/src/live-server/live-csp.ts +64 -16
  146. package/packages/server/src/live-server/live-log.ts +5 -1
  147. package/packages/server/src/live-server/live-server-manager.ts +11 -0
  148. package/packages/server/src/live-server/live-server-proxy.ts +268 -52
  149. package/packages/server/src/live-server/live-static.ts +4 -1
  150. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  151. package/packages/server/src/live-server/preview-observe.ts +53 -0
  152. package/packages/server/src/live-server/preview-origin.ts +182 -0
  153. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  154. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  155. package/packages/server/src/live-server/preview-path.ts +40 -0
  156. package/packages/server/src/live-server/preview-pool.ts +385 -0
  157. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  158. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  159. package/packages/server/src/live-server/preview-tier.ts +217 -0
  160. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  161. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  162. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  163. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  164. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  165. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  166. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  167. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  168. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  169. package/packages/server/src/openspec/readiness.ts +1 -1
  170. package/packages/server/src/package/provider-probe.ts +194 -5
  171. package/packages/server/src/pairing/browser-gateway.ts +140 -42
  172. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  173. package/packages/server/src/pairing/paired-devices.ts +370 -8
  174. package/packages/server/src/pairing/pairing.ts +69 -7
  175. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  176. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  177. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  178. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  179. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  180. package/packages/server/src/persistence/preferences-store.ts +52 -2
  181. package/packages/server/src/pi/bridge-contention.ts +84 -2
  182. package/packages/server/src/pi/host-project-trust.ts +15 -9
  183. package/packages/server/src/pi/pi-gateway.ts +208 -21
  184. package/packages/server/src/pi/provisional-registration.ts +4 -1
  185. package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
  186. package/packages/server/src/pi-agent-settings.ts +95 -301
  187. package/packages/server/src/pi-default-remirror.ts +89 -0
  188. package/packages/server/src/plugin-append-event.ts +35 -0
  189. package/packages/server/src/plugin-entry-stats.ts +61 -0
  190. package/packages/server/src/plugin-local-request.ts +207 -0
  191. package/packages/server/src/plugin-ownership.ts +111 -0
  192. package/packages/server/src/plugin-policy-registry.ts +297 -0
  193. package/packages/server/src/plugin-request-lane.ts +92 -16
  194. package/packages/server/src/preferences-relay.ts +20 -0
  195. package/packages/server/src/project-seed.ts +347 -0
  196. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  197. package/packages/server/src/questions/question-store.ts +3 -2
  198. package/packages/server/src/routes/access-routes.ts +23 -6
  199. package/packages/server/src/routes/acme-routes.ts +14 -4
  200. package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
  201. package/packages/server/src/routes/file-routes.ts +327 -86
  202. package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
  203. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  204. package/packages/server/src/routes/git-routes.ts +29 -78
  205. package/packages/server/src/routes/grep-routes.ts +26 -0
  206. package/packages/server/src/routes/live-server-routes.ts +198 -4
  207. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  208. package/packages/server/src/routes/openspec-routes.ts +17 -3
  209. package/packages/server/src/routes/pairing-routes.ts +200 -11
  210. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  211. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  212. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  213. package/packages/server/src/routes/provider-auth-routes.ts +167 -9
  214. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  215. package/packages/server/src/routes/provider-routes.ts +348 -86
  216. package/packages/server/src/routes/session-routes.ts +25 -22
  217. package/packages/server/src/routes/system-routes.ts +87 -39
  218. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  219. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  220. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  221. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  222. package/packages/server/src/server.ts +512 -175
  223. package/packages/server/src/services/cli-service.ts +59 -10
  224. package/packages/server/src/services/secrets-resolver.ts +46 -30
  225. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  226. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  227. package/packages/server/src/session/death-reason.ts +11 -7
  228. package/packages/server/src/session/event-status-extraction.ts +5 -1
  229. package/packages/server/src/session/memory-session-manager.ts +24 -2
  230. package/packages/server/src/session/open-tool-calls.ts +81 -47
  231. package/packages/server/src/session/pid-target.ts +127 -0
  232. package/packages/server/src/session/replay-compaction.ts +18 -5
  233. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  234. package/packages/server/src/session/server-pid-context.ts +14 -0
  235. package/packages/server/src/session/session-api.ts +78 -29
  236. package/packages/server/src/session/session-archive.ts +7 -0
  237. package/packages/server/src/session/session-bootstrap.ts +9 -54
  238. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  239. package/packages/server/src/session/session-load-worker.ts +22 -3
  240. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  241. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  242. package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
  243. package/packages/server/src/spawn-process/link-register.ts +42 -0
  244. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  245. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  246. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  247. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  248. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  249. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  250. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  251. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  252. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  253. package/packages/server/src/sudo-credential/relay.ts +337 -0
  254. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  255. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  256. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  257. package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
  258. package/packages/server/src/vault/vault-routes.ts +9 -2
  259. package/packages/server/src/vault/vault-store.ts +87 -24
  260. package/packages/server/vendor/xlsx/LICENSE +201 -0
  261. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  262. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  263. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  264. package/packages/shared/package.json +4 -2
  265. package/packages/shared/src/agent-credential-files.ts +32 -0
  266. package/packages/shared/src/browser-protocol.ts +137 -57
  267. package/packages/shared/src/canvas-detect.ts +1 -1
  268. package/packages/shared/src/canvas-types.ts +2 -2
  269. package/packages/shared/src/config.ts +73 -136
  270. package/packages/shared/src/containment-guard.ts +14 -4
  271. package/packages/shared/src/credential-encryption.ts +87 -0
  272. package/packages/shared/src/custom-event-groups.ts +2 -0
  273. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  274. package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
  275. package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
  276. package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
  277. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  278. package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
  279. package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
  280. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
  281. package/packages/shared/src/device-key-proof.ts +309 -0
  282. package/packages/shared/src/event-forward-declaration.ts +85 -12
  283. package/packages/shared/src/forbidden-subjects.ts +126 -14
  284. package/packages/shared/src/heap-limits.ts +0 -30
  285. package/packages/shared/src/host-admission.ts +2 -1
  286. package/packages/shared/src/index.ts +7 -6
  287. package/packages/shared/src/live-server.ts +20 -0
  288. package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
  289. package/packages/shared/src/models-json-reader.ts +41 -0
  290. package/packages/shared/src/network-denial-signal.ts +15 -0
  291. package/packages/shared/src/node-version.ts +63 -60
  292. package/packages/shared/src/pairing-knock-client.ts +92 -8
  293. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  294. package/packages/shared/src/pi-path-compare.ts +31 -0
  295. package/packages/shared/src/pi-settings-schema.ts +52 -9
  296. package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
  297. package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
  298. package/packages/shared/src/pi-trust-mirror.ts +18 -8
  299. package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
  300. package/packages/shared/src/pid-namespace.ts +86 -0
  301. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  302. package/packages/shared/src/platform/process.ts +404 -1
  303. package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
  304. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  305. package/packages/shared/src/preview-egress.ts +56 -2
  306. package/packages/shared/src/preview-origins.ts +398 -0
  307. package/packages/shared/src/prompt-answer.ts +9 -5
  308. package/packages/shared/src/protocol.ts +147 -85
  309. package/packages/shared/src/provider-env-catalog.ts +413 -0
  310. package/packages/shared/src/provider-overrides.ts +112 -0
  311. package/packages/shared/src/question-types.ts +6 -0
  312. package/packages/shared/src/recommended-extensions.ts +79 -26
  313. package/packages/shared/src/renderer-by-ext.ts +5 -2
  314. package/packages/shared/src/rest-api.ts +93 -3
  315. package/packages/shared/src/role-schema.ts +24 -0
  316. package/packages/shared/src/route-tiers.ts +94 -3
  317. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  318. package/packages/shared/src/secret-patterns.ts +49 -0
  319. package/packages/shared/src/source-matching.ts +2 -2
  320. package/packages/shared/src/state-replay.ts +40 -24
  321. package/packages/shared/src/sudo-credential.ts +71 -0
  322. package/packages/shared/src/tool-path-resolve.ts +16 -1
  323. package/packages/shared/src/tool-registry/strategies.ts +1 -1
  324. package/packages/shared/src/tool-workdir.ts +56 -0
  325. package/packages/shared/src/trusted-types-mode.ts +72 -0
  326. package/packages/shared/src/types.ts +68 -109
  327. package/packages/shared/src/vertex-regions.ts +81 -0
  328. package/packages/shared/src/ws-message-tiers.ts +10 -3
  329. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  330. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  331. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  332. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  333. package/packages/extension/src/subagent-saturation.ts +0 -196
  334. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  335. package/packages/shared/src/anthropic-messages-source.ts +0 -8
  336. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
  337. package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
@@ -19,31 +19,39 @@
19
19
  * `-Report-Only`; off mode registers no hook and the mount sets its own).
20
20
  * See change: add-plugin-capability-routes (D7).
21
21
  *
22
- * Trusted Types (`require-trusted-types-for 'script'`) has its own mode,
23
- * `PI_DASHBOARD_TRUSTED_TYPES=off|report|enforce`; unset follows the baseline
24
- * (`off` iff `PI_DASHBOARD_CSP=off`, else `report`), so an existing `enforce`
22
+ * Trusted Types (`require-trusted-types-for 'script'`) has its own mode, resolved by the shared
23
+ * `resolveTrustedTypesMode` (env `PI_DASHBOARD_TRUSTED_TYPES`, then config `security.trustedTypes`, then the
24
+ * default: `off` iff `PI_DASHBOARD_CSP=off`, else `report`), so an existing `enforce`
25
25
  * deployment never gets TT enforcement by accident. Matching modes append the
26
26
  * directive to the baseline header; differing modes set the OTHER header kind
27
- * with the directive alone (never comma-joined). See change: harden-client-sinks (D7).
27
+ * with the directive alone (never comma-joined). See change: harden-client-sinks (D7), enforce-trusted-types-default (D3).
28
28
  *
29
29
  * Strict policy (S3b): identical to the baseline except `script-src 'self' 'nonce-<n>'` (no
30
30
  * `'unsafe-inline'`/`'unsafe-eval'`). `report` mode emits baseline + strict as two Report-Only headers;
31
- * `enforce` emits strict enforcing only. Each carries `report-uri`/`report-to` for its own label (the TT-only
32
- * header: `trusted-types`) plus a `Reporting-Endpoints` header. The nonce is minted per HTML response by
31
+ * `enforce` emits strict enforcing only. Each carries `report-uri` for its own label (the TT-only
32
+ * header: `trusted-types`); never `report-to` / `Reporting-Endpoints` (Chromium and Firefox never deliver
33
+ * those on plain http, and `report-to` suppresses `report-uri`). The nonce is minted per HTML response by
33
34
  * `cspNonceFor(reply)` (memoized; non-HTML responses carry none). A response proxied to Vite
34
35
  * (`markViteProxied`) is a dev response: baseline only (legacy `script-src`), no strict, no nonce, no report
35
- * destination. Default mode stays `report`. See change: harden-cors-and-csp-reporting (D9, D10).
36
+ * destination. Default mode stays `report`. See change: harden-cors-and-csp-reporting (D9, D10), fix-csp-report-delivery (D1).
36
37
  *
37
38
  * See change: improve-content-editor (baseline CSP §7).
38
39
  */
39
40
  import { randomBytes } from "node:crypto";
41
+ import { isIP } from "node:net";
42
+ import type { ResolvedPreviewOrigins } from "@blackbelt-technology/pi-dashboard-shared/preview-origins.js";
40
43
  import type { FastifyInstance, FastifyReply } from "fastify";
41
- import { type CspReportPolicy, cspReportEndpointName, cspReportPath } from "./csp-report-paths.js";
44
+ import { getResolvedPreviewOrigins } from "../config-snapshot.js";
45
+ import { splitHostHeader } from "../live-server/preview-origin.js";
46
+ import { type CspReportPolicy, cspReportPath } from "./csp-report-paths.js";
47
+
48
+ // One resolver for the server and the dev plugin; re-exported so the server's callers keep one import site.
49
+ export { resolveTrustedTypesMode } from "@blackbelt-technology/pi-dashboard-shared/trusted-types-mode.js";
42
50
 
43
51
  export type CspMode = "off" | "report" | "enforce";
44
52
 
45
53
  /** Prefixes served by a reverse proxy / sandbox — never stamp our CSP on them. */
46
- const SKIP_PREFIXES = ["/live/"];
54
+ const SKIP_PREFIXES = ["/live/", "/preview/"];
47
55
 
48
56
  /**
49
57
  * Baseline directives. `script-src`/`style-src` keep `'unsafe-inline'` (Vite +
@@ -53,7 +61,7 @@ const SKIP_PREFIXES = ["/live/"];
53
61
  * `worker-src 'self' blob:` keeps Monaco/pdfjs workers alive. `connect-src`
54
62
  * allows same-origin + WebSocket (dashboard `/ws`, Vite HMR, zrok wss).
55
63
  */
56
- function directives(scriptSrc: string): string {
64
+ function directives(scriptSrc: string, previewFrames: readonly string[] = []): string {
57
65
  return [
58
66
  "default-src 'self'",
59
67
  scriptSrc,
@@ -62,7 +70,10 @@ function directives(scriptSrc: string): string {
62
70
  "font-src 'self' data:",
63
71
  "worker-src 'self' blob:",
64
72
  "connect-src 'self' ws: wss:",
65
- "frame-src 'self'",
73
+ // `https:` for operator-gated web-page previews (opaque sandbox) and the fixed YouTube embed.
74
+ // Untrusted HTML cannot create frames (markdown schema + DOMPurify drop `<iframe>`); http:/data:/blob:/* stay blocked.
75
+ // See change: rich-chat-links (D13).
76
+ ["frame-src 'self' https:", ...previewFrames].join(" "),
66
77
  "object-src 'none'",
67
78
  "base-uri 'self'",
68
79
  "frame-ancestors 'self'",
@@ -70,13 +81,53 @@ function directives(scriptSrc: string): string {
70
81
  }
71
82
 
72
83
  /** The `baseline` policy (legacy `script-src`). */
73
- export function buildCsp(): string {
74
- return directives("script-src 'self' 'unsafe-inline' 'unsafe-eval'");
84
+ export function buildCsp(previewFrames: readonly string[] = []): string {
85
+ return directives("script-src 'self' 'unsafe-inline' 'unsafe-eval'", previewFrames);
75
86
  }
76
87
 
77
88
  /** The `strict` policy: `script-src 'self'` plus the response nonce when there is one (HTML only). */
78
- export function buildStrictCsp(nonce?: string): string {
79
- return directives(nonce ? `script-src 'self' 'nonce-${nonce}'` : "script-src 'self'");
89
+ export function buildStrictCsp(nonce?: string, previewFrames: readonly string[] = []): string {
90
+ return directives(nonce ? `script-src 'self' 'nonce-${nonce}'` : "script-src 'self'", previewFrames);
91
+ }
92
+
93
+ /**
94
+ * The live-preview frame sources the dashboard page may embed, built per request from the page's `Host` (D6).
95
+ * `<HostPort>` = the Host's port, else the accepting socket's port, elided when it is the http default, so the
96
+ * frame source equals the minted origin (D1). Never `:*` except the tier-3 IP entry; never an IPv6 entry; never a
97
+ * bare scheme source. Pure.
98
+ */
99
+ export function previewFrameSources(
100
+ hostHeader: string | undefined,
101
+ socketPort: number | undefined,
102
+ resolvedIn?: ResolvedPreviewOrigins,
103
+ ): string[] {
104
+ const resolved = readResolved(resolvedIn);
105
+ if (!resolved?.enabled) return [];
106
+ const host = splitHostHeader(hostHeader);
107
+ if (!host || !/^[a-z0-9.-]+$/.test(host.hostname)) return []; // malformed or IPv6 literal: CSP has no form for it
108
+ const portPart = portSuffix(host.port ?? socketPort);
109
+ const out = [`http://*.localhost${portPart}`];
110
+ if (isIP(host.hostname) === 4) {
111
+ if (resolved.ipDnsSuffix) out.push(`http://*.${host.hostname.replaceAll(".", "-")}.${resolved.ipDnsSuffix}${portPart}`);
112
+ if (resolved.pool) out.push(`http://${host.hostname}:*`);
113
+ }
114
+ const wc = resolved.wildcard;
115
+ if (wc?.scheme === "http") out.push(`http://*.${wc.suffix}${portSuffix(wc.port)}`);
116
+ return out;
117
+ }
118
+
119
+ /** `:<port>`, elided when absent or the http default. */
120
+ const portSuffix = (port: number | undefined): string => (port === undefined || port === 80 ? "" : `:${port}`);
121
+
122
+ /** The resolved config, or `undefined` when the read fails: a failing read must not fail the page (degrades to `'self' https:`). */
123
+ function readResolved(given: ResolvedPreviewOrigins | undefined): ResolvedPreviewOrigins | undefined {
124
+ if (given) return given;
125
+ try {
126
+ return getResolvedPreviewOrigins();
127
+ } catch (err) {
128
+ console.error("[csp] preview frame-src unavailable:", err);
129
+ return undefined;
130
+ }
80
131
  }
81
132
 
82
133
  export function resolveCspMode(raw: string | undefined): CspMode {
@@ -86,12 +137,6 @@ export function resolveCspMode(raw: string | undefined): CspMode {
86
137
 
87
138
  const TRUSTED_TYPES_DIRECTIVE = "require-trusted-types-for 'script'";
88
139
 
89
- /** `PI_DASHBOARD_TRUSTED_TYPES`: explicit value wins; unset / unknown → `off` iff the baseline is `off`, else `report`. */
90
- export function resolveTrustedTypesMode(raw: string | undefined, cspMode: CspMode): CspMode {
91
- if (raw === "off" || raw === "report" || raw === "enforce") return raw;
92
- return cspMode === "off" ? "off" : "report";
93
- }
94
-
95
140
  const nonces = new WeakMap<FastifyReply, string>();
96
141
  const viteProxied = new WeakSet<FastifyReply>();
97
142
 
@@ -117,7 +162,7 @@ const headerFor = (mode: CspMode) => (mode === "enforce" ? EN : RO);
117
162
  type Plan = Map<string, Array<{ value: string; label?: CspReportPolicy }>>;
118
163
 
119
164
  /** Header kind → policy values for one response. `label` = report destination (absent in dev / for nothing). */
120
- function plan(mode: CspMode, ttMode: CspMode, dev: boolean, nonce: string | undefined): Plan {
165
+ function plan(mode: CspMode, ttMode: CspMode, dev: boolean, nonce: string | undefined, frames: readonly string[]): Plan {
121
166
  const out: Plan = new Map();
122
167
  const add = (kind: string, value: string, label?: CspReportPolicy) => {
123
168
  const list = out.get(kind) ?? [];
@@ -126,12 +171,12 @@ function plan(mode: CspMode, ttMode: CspMode, dev: boolean, nonce: string | unde
126
171
  };
127
172
  const tt = (on: boolean) => (on ? `; ${TRUSTED_TYPES_DIRECTIVE}` : "");
128
173
  if (mode === "report") {
129
- add(RO, buildCsp() + tt(ttMode === mode), "baseline");
130
- if (!dev) add(RO, buildStrictCsp(nonce), "strict");
174
+ add(RO, buildCsp(frames) + tt(ttMode === mode), "baseline");
175
+ if (!dev) add(RO, buildStrictCsp(nonce, frames), "strict");
131
176
  } else if (mode === "enforce") {
132
177
  // dev: the baseline policy enforcing (legacy dev `script-src`); production: the strict policy.
133
- if (dev) add(EN, buildCsp() + tt(ttMode === mode), "baseline");
134
- else add(EN, buildStrictCsp(nonce) + tt(ttMode === mode), "strict");
178
+ if (dev) add(EN, buildCsp(frames) + tt(ttMode === mode), "baseline");
179
+ else add(EN, buildStrictCsp(nonce, frames) + tt(ttMode === mode), "strict");
135
180
  }
136
181
  if (ttMode !== "off" && ttMode !== mode) add(headerFor(ttMode), TRUSTED_TYPES_DIRECTIVE, "trusted-types");
137
182
  return out;
@@ -148,20 +193,13 @@ export function registerCsp(fastify: FastifyInstance, mode: CspMode, ttMode: Csp
148
193
  const url = request.url;
149
194
  if (SKIP_PREFIXES.some((p) => url.startsWith(p))) return payload;
150
195
  const dev = viteProxied.has(reply);
151
- const used = new Set<CspReportPolicy>();
152
196
  // Each header kind is added only when absent (a route-level policy stands).
153
- for (const [kind, entries] of plan(mode, ttMode, dev, nonces.get(reply))) {
197
+ const frames = previewFrameSources(request.headers.host, request.raw.socket?.localPort);
198
+ for (const [kind, entries] of plan(mode, ttMode, dev, nonces.get(reply), frames)) {
154
199
  if (reply.getHeader(kind)) continue;
155
- const values = entries.map(({ value, label }) => {
156
- if (!label) return value;
157
- used.add(label);
158
- return `${value}; report-uri ${cspReportPath(label)}; report-to ${cspReportEndpointName(label)}`;
159
- });
200
+ const values = entries.map(({ value, label }) => (label ? `${value}; report-uri ${cspReportPath(label)}` : value));
160
201
  reply.header(kind, values.length === 1 ? values[0] : values);
161
202
  }
162
- if (used.size > 0 && !reply.getHeader("reporting-endpoints")) {
163
- reply.header("reporting-endpoints", [...used].map((l) => `${cspReportEndpointName(l)}="${cspReportPath(l)}"`).join(", "));
164
- }
165
203
  return payload;
166
204
  });
167
205
  }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Device-key proof plumbing for the server (Node crypto): the single-use
3
+ * challenge nonce store, the per-peer device-status limiter, the Ed25519
4
+ * verifier and the throttled `revoked_answer` log line.
5
+ *
6
+ * Verify-before-lookup: a signature is checked against the key the CALLER
7
+ * presents, and only a verified key is ever looked up in the registry, so the
8
+ * reply discloses nothing about keys the caller cannot sign for.
9
+ *
10
+ * See change: device-key-mutual-check (D1, D2, D10).
11
+ */
12
+ import crypto from "node:crypto";
13
+ import {
14
+ DEVICE_NONCE_TTL_MS,
15
+ isDeviceNonce,
16
+ isDevicePub,
17
+ isDeviceSig,
18
+ rawEd25519PubToSpki,
19
+ } from "@blackbelt-technology/pi-dashboard-shared/device-key-proof.js";
20
+ import { auditLine } from "./audit-log.js";
21
+
22
+ /** Bound on unused nonces; the oldest is evicted first. */
23
+ export const DEVICE_NONCE_MAX = 10_000;
24
+ /** Device-status requests allowed per peer inside {@link DEVICE_STATUS_WINDOW_MS}. */
25
+ const DEVICE_STATUS_LIMIT = 60;
26
+ const DEVICE_STATUS_WINDOW_MS = 60_000;
27
+ /** Tracked peers; the oldest is evicted first (same bound as the knock limiter). */
28
+ export const DEVICE_STATUS_MAX_PEERS = 1024;
29
+ /** At most one `revoked_answer` line per key id inside this window. */
30
+ const REVOKED_ANSWER_LOG_MS = 10 * 60_000;
31
+ const REVOKED_ANSWER_MAX_KEYS = 1024;
32
+
33
+ /**
34
+ * Single-use server nonces for the device check. 32 random bytes, base64url
35
+ * (43 chars). A nonce is consumed on FIRST presentation whether or not the
36
+ * proof that carries it is valid, so a captured proof cannot be replayed.
37
+ * In-memory only; carries no secret.
38
+ */
39
+ export class DeviceNonceStore {
40
+ private readonly now: () => number;
41
+ private readonly ttlMs: number;
42
+ private readonly max: number;
43
+ /** Insertion-ordered: the first key is the oldest unused nonce. */
44
+ private readonly nonces = new Map<string, number>();
45
+
46
+ constructor(opts: { now?: () => number; ttlMs?: number; max?: number } = {}) {
47
+ this.now = opts.now ?? Date.now;
48
+ this.ttlMs = opts.ttlMs ?? DEVICE_NONCE_TTL_MS;
49
+ this.max = opts.max ?? DEVICE_NONCE_MAX;
50
+ }
51
+
52
+ size(): number {
53
+ return this.nonces.size;
54
+ }
55
+
56
+ issue(): string {
57
+ const nonce = crypto.randomBytes(32).toString("base64url");
58
+ this.nonces.set(nonce, this.now() + this.ttlMs);
59
+ while (this.nonces.size > this.max) {
60
+ const oldest = this.nonces.keys().next().value;
61
+ if (oldest === undefined) break;
62
+ this.nonces.delete(oldest);
63
+ }
64
+ return nonce;
65
+ }
66
+
67
+ /** True only for a known, unexpired, never-presented nonce. Always deletes it. */
68
+ consume(nonce: unknown): boolean {
69
+ if (typeof nonce !== "string") return false;
70
+ const expiresAt = this.nonces.get(nonce);
71
+ this.nonces.delete(nonce);
72
+ return expiresAt !== undefined && expiresAt >= this.now();
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Sliding-window limiter for `POST /api/pair/device-status`: 60 per minute per
78
+ * peer address. EVERY request counts (valid or not). Blocked requests do not
79
+ * extend the window, so the peer recovers one window after its first request.
80
+ * The peer map is bounded; the identity challenge never consults this.
81
+ * Logs one line per peer when it trips (not once per blocked request).
82
+ */
83
+ export class DeviceStatusLimiter {
84
+ private readonly now: () => number;
85
+ private readonly limit: number;
86
+ private readonly windowMs: number;
87
+ private readonly maxPeers: number;
88
+ private readonly onTrip: (peer: string) => void;
89
+ private readonly peers = new Map<string, { hits: number[]; tripped: boolean }>();
90
+
91
+ constructor(
92
+ opts: { now?: () => number; limit?: number; windowMs?: number; maxPeers?: number; onTrip?: (peer: string) => void } = {},
93
+ ) {
94
+ this.now = opts.now ?? Date.now;
95
+ this.limit = opts.limit ?? DEVICE_STATUS_LIMIT;
96
+ this.windowMs = opts.windowMs ?? DEVICE_STATUS_WINDOW_MS;
97
+ this.maxPeers = opts.maxPeers ?? DEVICE_STATUS_MAX_PEERS;
98
+ this.onTrip = opts.onTrip ?? ((peer) => auditLine("pairing", "device_status_limited", { ip: peer }));
99
+ }
100
+
101
+ /** Number of tracked peers (bounded by `maxPeers`). */
102
+ size(): number {
103
+ return this.peers.size;
104
+ }
105
+
106
+ /** Record one request from `peer`; true when it is within the budget. */
107
+ allow(peer: string): boolean {
108
+ const t = this.now();
109
+ const state = this.peers.get(peer) ?? { hits: [], tripped: false };
110
+ // Re-insert so Map order is least-recently-used first.
111
+ this.peers.delete(peer);
112
+ this.peers.set(peer, state);
113
+ while (this.peers.size > this.maxPeers) {
114
+ const oldest = this.peers.keys().next().value;
115
+ if (oldest === undefined) break;
116
+ this.peers.delete(oldest);
117
+ }
118
+ state.hits = state.hits.filter((h) => h > t - this.windowMs);
119
+ if (state.hits.length >= this.limit) {
120
+ if (!state.tripped) {
121
+ state.tripped = true;
122
+ try {
123
+ this.onTrip(peer);
124
+ } catch {
125
+ // A broken log sink must not change the answer.
126
+ }
127
+ }
128
+ return false;
129
+ }
130
+ state.tripped = false;
131
+ state.hits.push(t);
132
+ return true;
133
+ }
134
+ }
135
+
136
+ /** Ed25519 verify of `message` (UTF-8) by the RAW 32-byte key `pub`; any malformed input is `false`. */
137
+ export function verifyDeviceSignature(pub: string, message: string, sig: string): boolean {
138
+ if (!isDevicePub(pub) || !isDeviceSig(sig)) return false;
139
+ try {
140
+ const key = crypto.createPublicKey({
141
+ key: Buffer.from(rawEd25519PubToSpki(Buffer.from(pub, "base64url"))),
142
+ format: "der",
143
+ type: "spki",
144
+ });
145
+ return crypto.verify(null, Buffer.from(message, "utf8"), key, Buffer.from(sig, "base64url"));
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Consume the proof's nonce, then verify its signature over `message(nonce)`.
153
+ * The nonce is spent on first presentation even when the signature is bad.
154
+ * `fields` are untrusted request values; any wrong shape is simply `false`.
155
+ */
156
+ export function verifyNonceProof(
157
+ store: DeviceNonceStore,
158
+ fields: { deviceNonce?: unknown; pub?: unknown; sig?: unknown },
159
+ messageFor: (deviceNonce: string) => string,
160
+ ): fields is { deviceNonce: string; pub: string; sig: string } {
161
+ const nonceOk = isDeviceNonce(fields.deviceNonce) && store.consume(fields.deviceNonce);
162
+ if (!nonceOk || !isDevicePub(fields.pub) || !isDeviceSig(fields.sig)) return false;
163
+ return verifyDeviceSignature(fields.pub, messageFor(fields.deviceNonce as string), fields.sig);
164
+ }
165
+
166
+ /**
167
+ * Throttled, transition-only `[pairing] revoked_answer key=dk:<12>` line: the
168
+ * first `revoked` answer for a key id after a different answer, at most once per
169
+ * key id per 10 minutes. Other answers (paired, expired, unknown) never log.
170
+ * Takes the short key id only — never a key, signature or nonce.
171
+ */
172
+ export class RevokedAnswerLog {
173
+ private readonly now: () => number;
174
+ private readonly emit: (keyId: string) => void;
175
+ private readonly last = new Map<string, { status: string; loggedAt?: number }>();
176
+
177
+ constructor(opts: { now?: () => number; emit?: (keyId: string) => void } = {}) {
178
+ this.now = opts.now ?? Date.now;
179
+ this.emit = opts.emit ?? ((keyId) => auditLine("pairing", "revoked_answer", { key: keyId }));
180
+ }
181
+
182
+ note(keyId: string, status: string): void {
183
+ const t = this.now();
184
+ const prev = this.last.get(keyId);
185
+ this.last.delete(keyId);
186
+ const next = { status, loggedAt: prev?.loggedAt };
187
+ this.last.set(keyId, next);
188
+ while (this.last.size > REVOKED_ANSWER_MAX_KEYS) {
189
+ const oldest = this.last.keys().next().value;
190
+ if (oldest === undefined) break;
191
+ this.last.delete(oldest);
192
+ }
193
+ if (status !== "revoked" || prev?.status === "revoked") return;
194
+ if (next.loggedAt !== undefined && t - next.loggedAt < REVOKED_ANSWER_LOG_MS) return;
195
+ next.loggedAt = t;
196
+ try {
197
+ this.emit(keyId);
198
+ } catch {
199
+ // Fail-open, like every audit line.
200
+ }
201
+ }
202
+ }
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Duplicate `pi_dash_*` cookie refusal (D10). A sibling subdomain (or a path-scoped planting) can toss a second
3
+ * cookie with the same NAME as a dashboard credential; the browser then sends both and the server would read an
4
+ * arbitrary one. The dashboard refuses every request (HTTP and WS upgrade) whose `Cookie` header carries any
5
+ * `pi_dash_*` name more than once — by NAME only, never by value — and the 400 response expires that name at every
6
+ * path that could have been planted, so the refusal self-heals.
7
+ *
8
+ * host gate → duplicate-cookie gate (400, no CORS headers) → origin gates (403) → auth
9
+ *
10
+ * 400, not 401: a 401 sends the client into re-auth, which cannot clear a tossed cookie. Preview origins are served
11
+ * by `previewApp` (own Fastify instance) and are exempt by construction.
12
+ *
13
+ * See change: serve-live-previews-on-capability-origin (D10).
14
+ */
15
+ import type { FastifyReply, FastifyRequest } from "fastify";
16
+ import { getResolvedPreviewOrigins } from "../config-snapshot.js";
17
+ import { redactCapability } from "../live-server/capability-redact.js";
18
+ import { sanitizeHeaderForLog } from "./cors-origin.js";
19
+ import { wantsHtml } from "./host-gate.js";
20
+
21
+ /** Dashboard cookie namespace (literal, case-sensitive). Mirrors `live-server-proxy.ts`. */
22
+ const DASHBOARD_COOKIE_PREFIX = "pi_dash_";
23
+ /** Names echoed in a body or log are truncated to this many characters (Q28). */
24
+ const COOKIE_NAME_ECHO_MAX = 128;
25
+ /** Self-heal covers prefixes of the first N path segments. */
26
+ const EXPIRY_MAX_SEGMENTS = 16;
27
+ /** Hard cap on `Set-Cookie` expiry lines per refusal. */
28
+ const EXPIRY_MAX_LINES = 64;
29
+ /**
30
+ * Hard cap on the total size of the expiry lines. A long request path puts that path into every line, and Node's
31
+ * HTTP parser rejects a head over `http.maxHeaderSize` (16 KiB); half of it leaves room for the other headers.
32
+ */
33
+ const EXPIRY_MAX_BYTES = 8192;
34
+ /** The paths the dashboard itself sets cookies at (token / local `/`, device `/api/`, oauth_state `/auth/`). */
35
+ const CANONICAL_COOKIE_PATHS = ["/", "/api/", "/auth/"] as const;
36
+ /** Refusal log: one line per name per window, ≤ this many names tracked (parity with the host gate). */
37
+ const LOG_WINDOW_MS = 60_000;
38
+ const LOG_MAX_NAMES = 256;
39
+
40
+ /** RFC 6265 cookie-name `token` characters. */
41
+ const TOKEN_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
42
+ /** A request path we are willing to put in `Set-Cookie: …; Path=`. */
43
+ const SAFE_PATH = /^\/[\x21-\x7e]*$/;
44
+
45
+ export interface DuplicateCookie {
46
+ name: string;
47
+ count: number;
48
+ }
49
+
50
+ /**
51
+ * The first `pi_dash_*` name (in header order) that appears more than once in a raw `Cookie` header, with its total
52
+ * count. Parses the raw header — pairs split on `;`, name = text before the first `=` (or the whole pair), trimmed —
53
+ * so quoting, empty pairs, valueless pairs and spacing never hide a duplicate. Never throws.
54
+ */
55
+ export function findDuplicateDashboardCookie(cookieHeader: string | string[] | undefined): DuplicateCookie | null {
56
+ if (cookieHeader === undefined) return null;
57
+ const raw = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
58
+ if (typeof raw !== "string" || raw.length === 0 || !raw.includes(DASHBOARD_COOKIE_PREFIX)) return null;
59
+ const counts = new Map<string, number>();
60
+ let first: string | null = null;
61
+ for (const pair of raw.split(";")) {
62
+ const eq = pair.indexOf("=");
63
+ const name = (eq === -1 ? pair : pair.slice(0, eq)).trim();
64
+ if (!name.startsWith(DASHBOARD_COOKIE_PREFIX)) continue;
65
+ const n = (counts.get(name) ?? 0) + 1;
66
+ counts.set(name, n);
67
+ if (n === 2 && first === null) first = name;
68
+ }
69
+ if (first === null) return null;
70
+ return { name: first, count: counts.get(first) ?? 2 };
71
+ }
72
+
73
+ /** The path part of a request URL (no query, no fragment). */
74
+ function pathOf(url: string): string {
75
+ const cut = url.search(/[?#]/);
76
+ return cut === -1 ? url : url.slice(0, cut);
77
+ }
78
+
79
+ /**
80
+ * Every `Path=` a browser could have stored a planted cookie at for this request: each `/`-boundary prefix (with and
81
+ * without the trailing slash) of the first {@link EXPIRY_MAX_SEGMENTS} segments, the exact request path, and the
82
+ * canonical dashboard paths. Cookie identity is (name, domain, exact path), so expiring at all of them clears it.
83
+ */
84
+ export function expiryPaths(url: string): string[] {
85
+ const path = pathOf(url);
86
+ const out = new Set<string>(["/"]);
87
+ const segments = path.split("/").filter((s) => s.length > 0);
88
+ let acc = "";
89
+ const prefixes = segments.slice(0, EXPIRY_MAX_SEGMENTS);
90
+ prefixes.forEach((seg, i) => {
91
+ acc = `${acc}/${seg}`;
92
+ out.add(acc);
93
+ // a proper prefix is also a directory path (`/api/`); the full path keeps only its exact form
94
+ if (i < segments.length - 1) out.add(`${acc}/`);
95
+ });
96
+ // the exact request path, even beyond the segment cap (still one line)
97
+ const exact = `/${segments.join("/")}`;
98
+ out.add(exact);
99
+ if (path.endsWith("/") && segments.length > 0) out.add(`${exact}/`);
100
+ for (const p of CANONICAL_COOKIE_PATHS) out.add(p);
101
+ return [...out].filter((p) => SAFE_PATH.test(p));
102
+ }
103
+
104
+ /** Ancestor domains (≥ 2 labels, strictly above the host) of a hostname `Host`; none for IPs / single labels. */
105
+ export function ancestorDomains(hostHeader: string | undefined): string[] {
106
+ if (typeof hostHeader !== "string") return [];
107
+ let h = hostHeader.trim().toLowerCase();
108
+ if (!h || h.startsWith("[")) return [];
109
+ const colon = h.indexOf(":");
110
+ if (colon !== -1) h = h.slice(0, colon);
111
+ if (h.endsWith(".")) h = h.slice(0, -1);
112
+ if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/.test(h) || /^\d+(\.\d+){3}$/.test(h)) return [];
113
+ const labels = h.split(".");
114
+ const out: string[] = [];
115
+ for (let i = 1; i <= labels.length - 2; i++) out.push(labels.slice(i).join("."));
116
+ return out;
117
+ }
118
+
119
+ /** Is tier 2 (wildcard preview origins) active right now? Only then can a sibling subdomain toss a parent-domain cookie. */
120
+ function tier2Active(): boolean {
121
+ const r = getResolvedPreviewOrigins();
122
+ return r.enabled && r.tiers.includes(2) && !!r.wildcard;
123
+ }
124
+
125
+ /**
126
+ * Keep the expiry lines within {@link EXPIRY_MAX_BYTES}: the dashboard's own cookie paths first (that is where a
127
+ * legitimate credential lives), then the rest in order, skipping any line that no longer fits. Order is preserved.
128
+ */
129
+ function fitExpiryBudget(lines: string[]): string[] {
130
+ if (lines.reduce((n, l) => n + l.length, 0) <= EXPIRY_MAX_BYTES) return lines;
131
+ const isCanonical = (l: string): boolean => (CANONICAL_COOKIE_PATHS as readonly string[]).includes(/Path=([^;]+)/.exec(l)?.[1] ?? "");
132
+ const byPriority = lines.map((l, i) => ({ l, i, canonical: isCanonical(l) })).sort((a, b) => Number(b.canonical) - Number(a.canonical) || a.i - b.i);
133
+ const keep = new Set<number>();
134
+ let used = 0;
135
+ for (const { l, i } of byPriority) {
136
+ if (used + l.length > EXPIRY_MAX_BYTES) continue;
137
+ used += l.length;
138
+ keep.add(i);
139
+ }
140
+ return lines.filter((_, i) => keep.has(i));
141
+ }
142
+
143
+ /** `Set-Cookie` lines that expire `name` at every candidate path (host-only first, then parent-domain variants). */
144
+ export function buildExpiryLines(name: string, url: string, hostHeader: string | undefined, withDomains: boolean): string[] {
145
+ if (!TOKEN_NAME.test(name) || name.length > COOKIE_NAME_ECHO_MAX) return [];
146
+ const paths = expiryPaths(url);
147
+ const lines = paths.map((p) => `${name}=; Max-Age=0; Path=${p}`);
148
+ if (withDomains) {
149
+ for (const domain of ancestorDomains(hostHeader)) {
150
+ for (const p of paths) lines.push(`${name}=; Max-Age=0; Path=${p}; Domain=${domain}`);
151
+ }
152
+ }
153
+ return fitExpiryBudget(lines.slice(0, EXPIRY_MAX_LINES));
154
+ }
155
+
156
+ const truncate = (s: string, max: number): string => (s.length > max ? s.slice(0, max) : s);
157
+ const escapeHtml = (v: string): string =>
158
+ v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
159
+
160
+ /** The JSON refusal body. */
161
+ function duplicateCookieBody(name: string): { success: false; error: "duplicate_dashboard_cookie"; cookie: string } {
162
+ return { success: false, error: "duplicate_dashboard_cookie", cookie: truncate(name, COOKIE_NAME_ECHO_MAX) };
163
+ }
164
+
165
+ /** Static page for navigations: no script, no asset reference; the cookie name is escaped. */
166
+ function renderDuplicateCookieHtml(name: string): string {
167
+ const safe = escapeHtml(truncate(name, COOKIE_NAME_ECHO_MAX));
168
+ return `<!doctype html>
169
+ <html lang="en">
170
+ <head>
171
+ <meta charset="utf-8">
172
+ <meta name="viewport" content="width=device-width, initial-scale=1">
173
+ <title>Duplicate dashboard cookie</title>
174
+ <style>:root{color-scheme:light dark}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;font:16px/1.55 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}main{max-width:34rem;padding:2.5rem 1.75rem}code{font-family:ui-monospace,Menlo,monospace;background:rgba(127,127,127,.16);padding:.1rem .35rem;border-radius:.25rem}</style>
175
+ </head>
176
+ <body>
177
+ <main>
178
+ <h1>Your browser holds two copies of a dashboard cookie</h1>
179
+ <p>The cookie <code>${safe}</code> was sent twice, so the dashboard cannot tell which one is yours. This response asked your browser to delete it; reload this page.</p>
180
+ <p>If this page appears again, clear this site's cookies and sign in again.</p>
181
+ </main>
182
+ </body>
183
+ </html>
184
+ `;
185
+ }
186
+
187
+ /** Rate-limited refusal log: ≤ 1 line per name per window, ≤ 256 names tracked (least-recently-logged evicted). */
188
+ export class DuplicateCookieLog {
189
+ private readonly seen = new Map<string, number>();
190
+ private readonly sink: (line: string) => void;
191
+ private readonly now: () => number;
192
+ constructor(sink: (line: string) => void = (l) => console.warn(l), now: () => number = Date.now) {
193
+ this.sink = sink;
194
+ this.now = now;
195
+ }
196
+
197
+ note(name: string, count: number, url: string): void {
198
+ const key = truncate(name, COOKIE_NAME_ECHO_MAX);
199
+ const t = this.now();
200
+ const last = this.seen.get(key);
201
+ if (last !== undefined && t - last < LOG_WINDOW_MS) return;
202
+ this.seen.delete(key);
203
+ this.seen.set(key, t);
204
+ while (this.seen.size > LOG_MAX_NAMES) {
205
+ const oldest = this.seen.keys().next().value;
206
+ if (oldest === undefined) break;
207
+ this.seen.delete(oldest);
208
+ }
209
+ const route = truncate(redactCapability(sanitizeHeaderForLog(pathOf(url), 120)), 120);
210
+ this.sink(`[cookie-gate] refused duplicate cookie name=${sanitizeHeaderForLog(key, COOKIE_NAME_ECHO_MAX)} count=${count} route=${route}`);
211
+ }
212
+ }
213
+
214
+ export interface DuplicateCookieGateOptions {
215
+ log?: DuplicateCookieLog;
216
+ /** Defaults to {@link tier2Active}; injectable for tests. */
217
+ tier2?: () => boolean;
218
+ }
219
+
220
+ /** `onRequest` hook: refuse a request carrying a duplicated `pi_dash_*` cookie name with a self-healing 400. */
221
+ export function createDuplicateCookieGate(opts: DuplicateCookieGateOptions = {}) {
222
+ const log = opts.log ?? defaultLog;
223
+ const tier2 = opts.tier2 ?? tier2Active;
224
+ return function duplicateCookieGate(req: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void): void {
225
+ const dup = findDuplicateDashboardCookie(req.headers.cookie);
226
+ if (!dup) return done();
227
+ // A failing log sink must never change the refusal: the response is the security decision, the log is a courtesy.
228
+ try {
229
+ log.note(dup.name, dup.count, req.url);
230
+ } catch {
231
+ /* fall through: still refuse */
232
+ }
233
+ const lines = buildExpiryLines(dup.name, req.url, req.headers.host, tier2());
234
+ if (lines.length > 0) reply.header("set-cookie", lines);
235
+ reply.header("cache-control", "no-store");
236
+ if (wantsHtml(req.headers.accept)) reply.code(400).type("text/html; charset=utf-8").send(renderDuplicateCookieHtml(dup.name));
237
+ else reply.code(400).send(duplicateCookieBody(dup.name));
238
+ };
239
+ }
240
+
241
+ /**
242
+ * The same check for a WS upgrade (raw socket). Returns `true` when the upgrade was refused (the socket is written
243
+ * to and destroyed); the caller returns before any ticket is consumed or any scope handler runs.
244
+ */
245
+ export function refuseDuplicateCookieUpgrade(
246
+ request: import("node:http").IncomingMessage,
247
+ socket: import("node:stream").Duplex,
248
+ opts: DuplicateCookieGateOptions = {},
249
+ ): boolean {
250
+ const dup = findDuplicateDashboardCookie(request.headers.cookie);
251
+ if (!dup) return false;
252
+ // Fail closed: whatever goes wrong while composing or writing the head (a throwing log sink, a dead socket), the
253
+ // upgrade is refused and the socket destroyed — never left half-open, never an uncaught exception from `upgrade`.
254
+ const url = request.url ?? "/";
255
+ try {
256
+ (opts.log ?? defaultLog).note(dup.name, dup.count, url);
257
+ } catch {
258
+ /* a failing log sink must not cost the client its self-healing head */
259
+ }
260
+ try {
261
+ const lines = buildExpiryLines(dup.name, url, request.headers.host, (opts.tier2 ?? tier2Active)());
262
+ const head = ["HTTP/1.1 400 Bad Request", "Connection: close", "Content-Length: 0", ...lines.map((l) => `Set-Cookie: ${l}`)];
263
+ socket.write(`${head.join("\r\n")}\r\n\r\n`);
264
+ } catch {
265
+ /* socket already gone, or the head could not be composed */
266
+ }
267
+ socket.destroy();
268
+ return true;
269
+ }
270
+
271
+ const defaultLog = new DuplicateCookieLog();