@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (474) hide show
  1. package/AGENTS.md +4 -2
  2. package/README.md +64 -18
  3. package/docs/architecture.md +2325 -270
  4. package/package.json +36 -20
  5. package/packages/extension/package.json +18 -9
  6. package/packages/extension/src/bridge-context.ts +6 -0
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
  9. package/packages/extension/src/bridge-handlers/instance.ts +31 -13
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
  11. package/packages/extension/src/bridge-shutdown.ts +44 -0
  12. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  13. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  14. package/packages/extension/src/bridge.ts +309 -284
  15. package/packages/extension/src/canvas-tool.ts +2 -0
  16. package/packages/extension/src/command-handler.ts +106 -37
  17. package/packages/extension/src/connect-target.ts +23 -0
  18. package/packages/extension/src/connection.ts +153 -38
  19. package/packages/extension/src/credential-guard.ts +300 -0
  20. package/packages/extension/src/custom-entry-forward.ts +27 -18
  21. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  22. package/packages/extension/src/default-model-apply.ts +83 -0
  23. package/packages/extension/src/dev-build.ts +11 -1
  24. package/packages/extension/src/flow-event-wiring.ts +19 -95
  25. package/packages/extension/src/followup-drain.ts +19 -5
  26. package/packages/extension/src/git-link-builder.ts +11 -2
  27. package/packages/extension/src/inbound-limits.ts +138 -0
  28. package/packages/extension/src/local-token-header.ts +77 -6
  29. package/packages/extension/src/model-refresh.ts +69 -0
  30. package/packages/extension/src/path-gate/decide.ts +68 -5
  31. package/packages/extension/src/path-gate/handler.ts +16 -8
  32. package/packages/extension/src/path-gate/index.ts +2 -2
  33. package/packages/extension/src/path-gate/roots.ts +15 -3
  34. package/packages/extension/src/path-gate/suppression.ts +3 -0
  35. package/packages/extension/src/pi-env.d.ts +8 -1
  36. package/packages/extension/src/pi-retry-settings.ts +11 -2
  37. package/packages/extension/src/pinned-endpoint.ts +44 -0
  38. package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
  39. package/packages/extension/src/preview-path-link.ts +151 -0
  40. package/packages/extension/src/project-init/scaffold.ts +98 -35
  41. package/packages/extension/src/project-trust-live.ts +143 -0
  42. package/packages/extension/src/project-trust.ts +178 -30
  43. package/packages/extension/src/provider-model-cache.ts +118 -0
  44. package/packages/extension/src/provider-register.ts +487 -46
  45. package/packages/extension/src/remote-registration-gate.ts +21 -21
  46. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  47. package/packages/extension/src/retry-tracker.ts +90 -7
  48. package/packages/extension/src/role-manager.ts +4 -2
  49. package/packages/extension/src/role-model-tools.ts +68 -10
  50. package/packages/extension/src/server-auto-start.ts +69 -3
  51. package/packages/extension/src/server-launcher.ts +26 -8
  52. package/packages/extension/src/server-proof-probe.ts +117 -0
  53. package/packages/extension/src/session-sync.ts +53 -24
  54. package/packages/extension/src/spawn-new-session.ts +22 -0
  55. package/packages/extension/src/steer-buffer.ts +164 -0
  56. package/packages/extension/src/stream-forward-buffer.ts +64 -15
  57. package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
  58. package/packages/extension/src/sudo-askpass/controller.ts +405 -0
  59. package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
  60. package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
  61. package/packages/extension/src/sudo-askpass/index.ts +11 -0
  62. package/packages/extension/src/sudo-askpass/install.ts +143 -0
  63. package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
  64. package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
  65. package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
  66. package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
  67. package/packages/extension/src/terminal-reload.ts +19 -5
  68. package/packages/extension/src/tool-update-filter-registry.ts +210 -0
  69. package/packages/extension/src/vault-delivery.ts +11 -1
  70. package/packages/extension/src/vault-redaction.ts +4 -3
  71. package/packages/server/package.json +17 -14
  72. package/packages/server/src/access/access-denials.ts +8 -0
  73. package/packages/server/src/access/access-grants.ts +303 -64
  74. package/packages/server/src/access/access-health.ts +10 -0
  75. package/packages/server/src/access/access-plane.ts +12 -1
  76. package/packages/server/src/access/containment-gate.ts +113 -30
  77. package/packages/server/src/access/cwd-verdict.ts +3 -3
  78. package/packages/server/src/access/denial-hold.ts +3 -0
  79. package/packages/server/src/access/grant-coordinator.ts +17 -1
  80. package/packages/server/src/access/named-grant.ts +3 -0
  81. package/packages/server/src/access/pending-grant-registry.ts +32 -5
  82. package/packages/server/src/access/pi-trust-live.ts +244 -0
  83. package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
  84. package/packages/server/src/access/planes.ts +107 -1
  85. package/packages/server/src/access/preview-egress-store.ts +153 -0
  86. package/packages/server/src/access/prompt-channel.ts +5 -0
  87. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  88. package/packages/server/src/access/provisioning.ts +763 -0
  89. package/packages/server/src/access/verified-read.ts +24 -7
  90. package/packages/server/src/access/yolo-session.ts +54 -2
  91. package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
  92. package/packages/server/src/acp-bridge/server-requests.ts +10 -4
  93. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  94. package/packages/server/src/auth/audit-log.ts +108 -0
  95. package/packages/server/src/auth/auth-plugin.ts +230 -38
  96. package/packages/server/src/auth/auth.ts +104 -4
  97. package/packages/server/src/auth/bearer-auth.ts +52 -12
  98. package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
  99. package/packages/server/src/auth/cors-origin.ts +90 -30
  100. package/packages/server/src/auth/credential-envelope.ts +233 -0
  101. package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
  102. package/packages/server/src/auth/credential-key-worker.mjs +108 -0
  103. package/packages/server/src/auth/credential-key.ts +479 -0
  104. package/packages/server/src/auth/credential-migration.ts +162 -0
  105. package/packages/server/src/auth/csp-report-paths.ts +26 -0
  106. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  107. package/packages/server/src/auth/csp-report-store.ts +406 -0
  108. package/packages/server/src/auth/csp.ts +145 -11
  109. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  110. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  111. package/packages/server/src/auth/device-proof.ts +202 -0
  112. package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
  113. package/packages/server/src/auth/host-admission.ts +7 -0
  114. package/packages/server/src/auth/host-gate.ts +13 -2
  115. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  116. package/packages/server/src/auth/local-proof.ts +69 -18
  117. package/packages/server/src/auth/localhost-guard.ts +98 -33
  118. package/packages/server/src/auth/locked-json-file.ts +68 -6
  119. package/packages/server/src/auth/models-json-store.ts +269 -0
  120. package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
  121. package/packages/server/src/auth/nav-intent.ts +72 -0
  122. package/packages/server/src/auth/node-guard.ts +36 -49
  123. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  124. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  125. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  126. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  127. package/packages/server/src/auth/plugin-credential-store.ts +81 -10
  128. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  129. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  130. package/packages/server/src/auth/proven-tls.ts +45 -0
  131. package/packages/server/src/auth/provider-auth-storage.ts +214 -12
  132. package/packages/server/src/auth/provider-block-checks.ts +321 -0
  133. package/packages/server/src/auth/provider-host-detect.ts +151 -0
  134. package/packages/server/src/auth/provider-key-file.ts +71 -0
  135. package/packages/server/src/auth/provider-readiness.ts +91 -0
  136. package/packages/server/src/auth/radius-mcp.ts +1 -1
  137. package/packages/server/src/auth/request-principal.ts +32 -0
  138. package/packages/server/src/auth/route-tier-gate.ts +3 -2
  139. package/packages/server/src/auth/secret-rotation.ts +246 -0
  140. package/packages/server/src/auth/secure-origin.ts +56 -0
  141. package/packages/server/src/auth/serve-app-host.ts +111 -11
  142. package/packages/server/src/auth/vertex-key-check.ts +140 -0
  143. package/packages/server/src/auth/ws-ticket.ts +40 -2
  144. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  145. package/packages/server/src/browse.ts +73 -20
  146. package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
  147. package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
  148. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  149. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  150. package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
  151. package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
  152. package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
  153. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  154. package/packages/server/src/build-plugin-send-prompt.ts +18 -0
  155. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  156. package/packages/server/src/cli/credentials-command.ts +555 -0
  157. package/packages/server/src/cli.ts +229 -53
  158. package/packages/server/src/config-api.ts +53 -35
  159. package/packages/server/src/config-snapshot.ts +197 -1
  160. package/packages/server/src/directory-service.ts +193 -68
  161. package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
  162. package/packages/server/src/event-wiring.ts +322 -207
  163. package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
  164. package/packages/server/src/git-worktree/git-operations.ts +45 -11
  165. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  166. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  167. package/packages/server/src/git-worktree/repo-lock.ts +42 -0
  168. package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
  169. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  170. package/packages/server/src/git-worktree/worktree-init.ts +5 -1
  171. package/packages/server/src/identity/http-road-classification.ts +18 -2
  172. package/packages/server/src/identity/identity-floor.ts +5 -2
  173. package/packages/server/src/identity/ws-message-scope.ts +11 -3
  174. package/packages/server/src/identity/ws-road-classification.ts +3 -1
  175. package/packages/server/src/known-server-moves.ts +36 -15
  176. package/packages/server/src/lib/browse-roots.ts +129 -17
  177. package/packages/server/src/lib/client-dist.ts +36 -21
  178. package/packages/server/src/lib/content-disposition.ts +20 -0
  179. package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
  180. package/packages/server/src/lib/diagram-render.ts +4 -6
  181. package/packages/server/src/lib/eml.ts +5 -10
  182. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  183. package/packages/server/src/lib/frame-policy-probe.ts +308 -0
  184. package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
  185. package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
  186. package/packages/server/src/lib/grep-worker.ts +23 -0
  187. package/packages/server/src/lib/grep.ts +96 -7
  188. package/packages/server/src/lib/index-html.ts +81 -0
  189. package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
  190. package/packages/server/src/lib/office-preview.ts +49 -13
  191. package/packages/server/src/lib/path-containment.ts +50 -10
  192. package/packages/server/src/lib/resolve-file-mention.ts +234 -40
  193. package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
  194. package/packages/server/src/lib/route-admission.ts +80 -0
  195. package/packages/server/src/lib/writable-handler-target.ts +4 -0
  196. package/packages/server/src/lib/writable-md-target.ts +26 -0
  197. package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
  198. package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
  199. package/packages/server/src/lifecycle/exit-signal.ts +43 -0
  200. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  201. package/packages/server/src/live-server/capability-redact.ts +31 -0
  202. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  203. package/packages/server/src/live-server/live-capability.ts +615 -44
  204. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  205. package/packages/server/src/live-server/live-csp.ts +141 -0
  206. package/packages/server/src/live-server/live-egress.ts +435 -0
  207. package/packages/server/src/live-server/live-exposure.ts +149 -0
  208. package/packages/server/src/live-server/live-log.ts +25 -0
  209. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  210. package/packages/server/src/live-server/live-server-manager.ts +220 -33
  211. package/packages/server/src/live-server/live-server-proxy.ts +411 -50
  212. package/packages/server/src/live-server/live-static.ts +231 -0
  213. package/packages/server/src/live-server/preview-dispatch.ts +286 -0
  214. package/packages/server/src/live-server/preview-observe.ts +53 -0
  215. package/packages/server/src/live-server/preview-origin.ts +182 -0
  216. package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
  217. package/packages/server/src/live-server/preview-path-store.ts +420 -0
  218. package/packages/server/src/live-server/preview-path.ts +40 -0
  219. package/packages/server/src/live-server/preview-pool.ts +385 -0
  220. package/packages/server/src/live-server/preview-preflight.ts +41 -0
  221. package/packages/server/src/live-server/preview-reserve.ts +44 -0
  222. package/packages/server/src/live-server/preview-tier.ts +217 -0
  223. package/packages/server/src/live-server/preview-viewers.ts +54 -0
  224. package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
  225. package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
  226. package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
  227. package/packages/server/src/model-proxy/internal-registry.ts +283 -21
  228. package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
  229. package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
  230. package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
  231. package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
  232. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  233. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  234. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  235. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  236. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  237. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  238. package/packages/server/src/openspec/readiness.ts +1 -1
  239. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  240. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  241. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  242. package/packages/server/src/package/provider-probe.ts +202 -7
  243. package/packages/server/src/pairing/browser-gateway.ts +325 -51
  244. package/packages/server/src/pairing/device-key-intake.ts +120 -0
  245. package/packages/server/src/pairing/device-token-services.ts +26 -0
  246. package/packages/server/src/pairing/paired-devices.ts +702 -27
  247. package/packages/server/src/pairing/pairing.ts +103 -11
  248. package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
  249. package/packages/server/src/pairing/socket-locality.ts +26 -0
  250. package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
  251. package/packages/server/src/pending/pending-attach-registry.ts +15 -0
  252. package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
  253. package/packages/server/src/persistence/memory-event-store.ts +251 -296
  254. package/packages/server/src/persistence/preferences-store.ts +61 -2
  255. package/packages/server/src/pi/bridge-channel.ts +33 -0
  256. package/packages/server/src/pi/bridge-contention.ts +84 -2
  257. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  258. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  259. package/packages/server/src/pi/host-project-trust.ts +29 -15
  260. package/packages/server/src/pi/pi-gateway.ts +398 -41
  261. package/packages/server/src/pi/provisional-registration.ts +4 -1
  262. package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
  263. package/packages/server/src/pi-agent-settings.ts +95 -301
  264. package/packages/server/src/pi-default-remirror.ts +89 -0
  265. package/packages/server/src/plugin-append-event.ts +35 -0
  266. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  267. package/packages/server/src/plugin-entry-stats.ts +61 -0
  268. package/packages/server/src/plugin-event-seam.ts +116 -4
  269. package/packages/server/src/plugin-local-request.ts +207 -0
  270. package/packages/server/src/plugin-ownership.ts +111 -0
  271. package/packages/server/src/plugin-policy-registry.ts +297 -0
  272. package/packages/server/src/plugin-request-lane.ts +92 -16
  273. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  274. package/packages/server/src/preferences-relay.ts +20 -0
  275. package/packages/server/src/project-seed.ts +347 -0
  276. package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
  277. package/packages/server/src/questions/question-store.ts +3 -2
  278. package/packages/server/src/routes/access-routes.ts +182 -15
  279. package/packages/server/src/routes/acme-routes.ts +14 -4
  280. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  281. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  282. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  283. package/packages/server/src/routes/file-routes.ts +640 -279
  284. package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
  285. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  286. package/packages/server/src/routes/frame-policy-routes.ts +215 -0
  287. package/packages/server/src/routes/git-routes.ts +340 -273
  288. package/packages/server/src/routes/grep-routes.ts +64 -14
  289. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  290. package/packages/server/src/routes/live-server-routes.ts +572 -15
  291. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  292. package/packages/server/src/routes/models-introspection-routes.ts +1 -1
  293. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  294. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  295. package/packages/server/src/routes/openspec-routes.ts +396 -31
  296. package/packages/server/src/routes/package-routes.ts +58 -10
  297. package/packages/server/src/routes/pairing-routes.ts +342 -17
  298. package/packages/server/src/routes/pi-settings-routes.ts +2 -0
  299. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  300. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  301. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  302. package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
  303. package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
  304. package/packages/server/src/routes/provider-auth-routes.ts +181 -10
  305. package/packages/server/src/routes/provider-override-routes.ts +158 -0
  306. package/packages/server/src/routes/provider-routes.ts +348 -86
  307. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  308. package/packages/server/src/routes/session-routes.ts +75 -25
  309. package/packages/server/src/routes/system-routes.ts +169 -52
  310. package/packages/server/src/routes/ui-link-base.ts +88 -0
  311. package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
  312. package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
  313. package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
  314. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  315. package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
  316. package/packages/server/src/server.ts +1139 -291
  317. package/packages/server/src/services/cli-service.ts +59 -10
  318. package/packages/server/src/services/secrets-resolver.ts +46 -30
  319. package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
  320. package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
  321. package/packages/server/src/session/death-reason.ts +11 -7
  322. package/packages/server/src/session/event-status-extraction.ts +5 -1
  323. package/packages/server/src/session/hydration-state.ts +148 -0
  324. package/packages/server/src/session/memory-session-manager.ts +31 -2
  325. package/packages/server/src/session/open-tool-calls.ts +81 -47
  326. package/packages/server/src/session/pid-target.ts +127 -0
  327. package/packages/server/src/session/replay-compaction.ts +18 -5
  328. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  329. package/packages/server/src/session/retained-transcript.ts +9 -2
  330. package/packages/server/src/session/seed-discovered-history.ts +85 -0
  331. package/packages/server/src/session/server-pid-context.ts +14 -0
  332. package/packages/server/src/session/session-api.ts +78 -29
  333. package/packages/server/src/session/session-archive.ts +7 -0
  334. package/packages/server/src/session/session-bootstrap.ts +9 -54
  335. package/packages/server/src/session/session-load-worker-pool.ts +11 -1
  336. package/packages/server/src/session/session-load-worker.ts +32 -4
  337. package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
  338. package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
  339. package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
  340. package/packages/server/src/spawn-process/link-register.ts +42 -0
  341. package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
  342. package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
  343. package/packages/server/src/spawn-process/process-classifier.ts +8 -3
  344. package/packages/server/src/spawn-process/process-manager.ts +61 -6
  345. package/packages/server/src/spawn-process/restored-identity.ts +112 -0
  346. package/packages/server/src/spawn-process/session-terminator.ts +179 -18
  347. package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
  348. package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
  349. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
  350. package/packages/server/src/sudo-credential/relay.ts +337 -0
  351. package/packages/server/src/terminal/terminal-gateway.ts +10 -0
  352. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  353. package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
  354. package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
  355. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  356. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  357. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  358. package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
  359. package/packages/server/src/vault/vault-routes.ts +9 -2
  360. package/packages/server/src/vault/vault-store.ts +87 -24
  361. package/packages/server/src/watch-files-handler.ts +66 -0
  362. package/packages/server/vendor/xlsx/LICENSE +201 -0
  363. package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
  364. package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
  365. package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
  366. package/packages/shared/package.json +4 -2
  367. package/packages/shared/src/agent-credential-files.ts +32 -0
  368. package/packages/shared/src/browser-protocol.ts +285 -59
  369. package/packages/shared/src/canvas-declare.ts +27 -0
  370. package/packages/shared/src/canvas-detect.ts +1 -1
  371. package/packages/shared/src/canvas-types.ts +2 -2
  372. package/packages/shared/src/config.ts +443 -187
  373. package/packages/shared/src/containment-guard.ts +45 -0
  374. package/packages/shared/src/credential-encryption.ts +87 -0
  375. package/packages/shared/src/custom-event-groups.ts +2 -0
  376. package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
  377. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  378. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  379. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  380. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  381. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  382. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  383. package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
  384. package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
  385. package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
  386. package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
  387. package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
  388. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
  389. package/packages/shared/src/device-key-proof.ts +309 -0
  390. package/packages/shared/src/display-prefs.ts +13 -0
  391. package/packages/shared/src/doctor-core.ts +94 -27
  392. package/packages/shared/src/event-forward-declaration.ts +85 -12
  393. package/packages/shared/src/forbidden-subjects.ts +126 -14
  394. package/packages/shared/src/heap-limits.ts +0 -30
  395. package/packages/shared/src/host-admission.ts +2 -1
  396. package/packages/shared/src/index.ts +7 -6
  397. package/packages/shared/src/live-server.ts +161 -0
  398. package/packages/shared/src/local-proof-signal.ts +16 -0
  399. package/packages/shared/src/loopback-host.ts +26 -0
  400. package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
  401. package/packages/shared/src/mdns-discovery.ts +25 -6
  402. package/packages/shared/src/models-json-reader.ts +41 -0
  403. package/packages/shared/src/nav-intent.ts +29 -0
  404. package/packages/shared/src/network-denial-signal.ts +15 -0
  405. package/packages/shared/src/node-version.ts +63 -60
  406. package/packages/shared/src/openspec-dependencies.ts +760 -0
  407. package/packages/shared/src/openspec-poller.ts +3 -2
  408. package/packages/shared/src/pairing-knock-client.ts +135 -11
  409. package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
  410. package/packages/shared/src/pi-path-compare.ts +31 -0
  411. package/packages/shared/src/pi-settings-schema.ts +52 -9
  412. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  413. package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
  414. package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
  415. package/packages/shared/src/pi-trust-mirror.ts +47 -11
  416. package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
  417. package/packages/shared/src/pid-namespace.ts +86 -0
  418. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  419. package/packages/shared/src/platform/git-source.ts +88 -26
  420. package/packages/shared/src/platform/git.ts +14 -8
  421. package/packages/shared/src/platform/native-ts-register.mjs +1 -1
  422. package/packages/shared/src/platform/process.ts +452 -5
  423. package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
  424. package/packages/shared/src/platform/select-git-source.ts +7 -0
  425. package/packages/shared/src/platform/spawn-runtime.ts +193 -7
  426. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  427. package/packages/shared/src/preview-egress.ts +192 -0
  428. package/packages/shared/src/preview-origins.ts +398 -0
  429. package/packages/shared/src/project-root.ts +16 -0
  430. package/packages/shared/src/prompt-answer.ts +9 -5
  431. package/packages/shared/src/protocol.ts +187 -86
  432. package/packages/shared/src/provider-env-catalog.ts +413 -0
  433. package/packages/shared/src/provider-overrides.ts +112 -0
  434. package/packages/shared/src/question-types.ts +6 -0
  435. package/packages/shared/src/recommended-extensions.ts +97 -26
  436. package/packages/shared/src/recovery-timing.ts +27 -0
  437. package/packages/shared/src/remote-credentials.ts +63 -0
  438. package/packages/shared/src/renderer-by-ext.ts +5 -2
  439. package/packages/shared/src/rest-api.ts +148 -11
  440. package/packages/shared/src/role-schema.ts +24 -0
  441. package/packages/shared/src/route-tiers.ts +149 -4
  442. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  443. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  444. package/packages/shared/src/runtime-overlay/compat.ts +70 -6
  445. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  446. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  447. package/packages/shared/src/safe-local-path.ts +24 -0
  448. package/packages/shared/src/sanitize-profiles.ts +98 -0
  449. package/packages/shared/src/secret-patterns.ts +49 -0
  450. package/packages/shared/src/server-launcher.ts +9 -1
  451. package/packages/shared/src/server-pinning.ts +55 -2
  452. package/packages/shared/src/server-routes.ts +462 -0
  453. package/packages/shared/src/session-ui-path.ts +11 -0
  454. package/packages/shared/src/source-matching.ts +2 -2
  455. package/packages/shared/src/state-replay.ts +40 -24
  456. package/packages/shared/src/sudo-credential.ts +71 -0
  457. package/packages/shared/src/tls-only-token.ts +16 -0
  458. package/packages/shared/src/tool-path-resolve.ts +16 -1
  459. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  460. package/packages/shared/src/tool-registry/strategies.ts +13 -12
  461. package/packages/shared/src/tool-workdir.ts +56 -0
  462. package/packages/shared/src/trusted-types-mode.ts +72 -0
  463. package/packages/shared/src/types.ts +134 -109
  464. package/packages/shared/src/url-policy.ts +96 -0
  465. package/packages/shared/src/vault-delivery.ts +15 -0
  466. package/packages/shared/src/vertex-regions.ts +81 -0
  467. package/packages/shared/src/ws-message-tiers.ts +11 -3
  468. package/packages/extension/src/subagent-fanout-admission.ts +0 -234
  469. package/packages/extension/src/subagent-forward-sites.ts +0 -69
  470. package/packages/extension/src/subagent-frame-buffer.ts +0 -245
  471. package/packages/extension/src/subagent-frame-strip.ts +0 -109
  472. package/packages/extension/src/subagent-saturation.ts +0 -196
  473. package/packages/extension/src/subagent-tick-throttle.ts +0 -252
  474. package/packages/shared/src/anthropic-messages-source.ts +0 -8
@@ -6,16 +6,24 @@
6
6
  * additionally present PROOF: the `X-Pi-Local-Token` header or a `pi_dash_local`
7
7
  * cookie bootstrapped from the local token (`pi-dashboard open` / Electron).
8
8
  *
9
- * Cookie value: `<id>.<expiresAt>.<HMAC(k_local, "<id>.<expiresAt>")>` with
10
- * `k_local = HMAC(localToken, "pi-dashboard/local-proof/v1")`. Rotating the local
11
- * token invalidates every proof cookie.
12
- * See change: harden-trust-and-credential-boundaries (D2).
9
+ * Cookie value: `<id>.<issuedAt>.<lastUse>.<port>.<HMAC(k_local, "<id>.<issuedAt>.<lastUse>.<port>")>`
10
+ * with `k_local = HMAC(localToken, "pi-dashboard/local-proof/v1")`. It is bound to the port
11
+ * of the listener that issued it (a browser sends it to every `localhost:<port>` site, so a
12
+ * cookie captured by another local web app only replays against the right port), expires
13
+ * after 12 h idle (re-signed when a request arrives more than 1 h after the last refresh) and
14
+ * has an absolute 30-day cap. Rotating the local token invalidates every proof cookie.
15
+ * See change: harden-trust-and-credential-boundaries (D2); close-container-loopback-impersonation (D12).
13
16
  */
14
17
  import crypto from "node:crypto";
15
18
  import { hasLocalCredential } from "./local-credential.js";
16
19
 
17
20
  export const LOCAL_PROOF_COOKIE = "pi_dash_local";
21
+ /** Absolute cap from `issuedAt`, and the cookie's browser `Max-Age`. */
18
22
  export const LOCAL_PROOF_MAX_AGE_S = 30 * 24 * 60 * 60;
23
+ /** A cookie unused (never re-signed) for longer than this is no longer proof. */
24
+ const LOCAL_PROOF_IDLE_MS = 12 * 60 * 60 * 1000;
25
+ /** An admitted request this long after the last refresh gets a re-signed cookie. */
26
+ const LOCAL_PROOF_REFRESH_AFTER_MS = 60 * 60 * 1000;
19
27
  const CODE_TTL_MS = 60_000;
20
28
 
21
29
  export interface LocalTrustContext {
@@ -24,13 +32,20 @@ export interface LocalTrustContext {
24
32
  localToken: string;
25
33
  /** `HMAC(localToken, "pi-dashboard/local-proof/v1")`. */
26
34
  proofKey: Buffer;
35
+ /** The listening port the cookie is bound to; absent ⇒ 0 (a context with no listener, e.g. `inject()`). */
36
+ port?: () => number;
27
37
  }
28
38
 
29
- export function createLocalTrustContext(localToken: string, strict: () => boolean): LocalTrustContext {
39
+ export function createLocalTrustContext(
40
+ localToken: string,
41
+ strict: () => boolean,
42
+ port?: () => number,
43
+ ): LocalTrustContext {
30
44
  return {
31
45
  strict,
32
46
  localToken,
33
47
  proofKey: crypto.createHmac("sha256", localToken).update("pi-dashboard/local-proof/v1").digest(),
48
+ ...(port ? { port } : {}),
34
49
  };
35
50
  }
36
51
 
@@ -38,27 +53,63 @@ function mac(key: Buffer, payload: string): string {
38
53
  return crypto.createHmac("sha256", key).update(payload).digest("base64url");
39
54
  }
40
55
 
41
- /** Mint a `pi_dash_local` cookie value. */
42
- export function signLocalProof(ctx: LocalTrustContext, now = Date.now(), maxAgeS = LOCAL_PROOF_MAX_AGE_S): string {
43
- const payload = `${crypto.randomBytes(12).toString("base64url")}.${now + maxAgeS * 1000}`;
56
+ const ctxPort = (ctx: LocalTrustContext): number => ctx.port?.() ?? 0;
57
+
58
+ function seal(ctx: LocalTrustContext, id: string, issuedAt: number, lastUse: number): string {
59
+ const payload = `${id}.${issuedAt}.${lastUse}.${ctxPort(ctx)}`;
44
60
  return `${payload}.${mac(ctx.proofKey, payload)}`;
45
61
  }
46
62
 
47
- /** Valid, unexpired, correctly signed proof cookie value? */
48
- export function verifyLocalProofCookie(value: string | undefined, ctx: LocalTrustContext, now = Date.now()): boolean {
49
- if (!value) return false;
63
+ /** Mint a `pi_dash_local` cookie value bound to this context's port. */
64
+ export function signLocalProof(ctx: LocalTrustContext, now = Date.now()): string {
65
+ return seal(ctx, crypto.randomBytes(12).toString("base64url"), now, now);
66
+ }
67
+
68
+ export interface LocalProofCookieInfo {
69
+ /** True when a request this long after `lastUse` should be given a re-signed cookie. */
70
+ needsRefresh: boolean;
71
+ /** A re-signed value (same id and `issuedAt`, `lastUse = now`). */
72
+ refreshed: string;
73
+ /** Seconds the re-signed cookie may live (remaining time to the absolute cap). */
74
+ maxAgeS: number;
75
+ }
76
+
77
+ /**
78
+ * `null` unless the cookie is correctly signed, bound to this port, within the idle window and
79
+ * within the absolute cap. Otherwise what a refresh would look like.
80
+ */
81
+ export function inspectLocalProofCookie(
82
+ value: string | undefined,
83
+ ctx: LocalTrustContext,
84
+ now = Date.now(),
85
+ ): LocalProofCookieInfo | null {
86
+ if (!value) return null;
50
87
  const parts = value.split(".");
51
- if (parts.length !== 3) return false;
52
- const [id, exp, sig] = parts as [string, string, string];
53
- const expiresAt = Number(exp);
54
- if (!id || !Number.isFinite(expiresAt) || expiresAt <= now) return false;
55
- const want = Buffer.from(mac(ctx.proofKey, `${id}.${exp}`));
88
+ if (parts.length !== 5) return null;
89
+ const [id, issued, last, port, sig] = parts as [string, string, string, string, string];
90
+ const issuedAt = Number(issued);
91
+ const lastUse = Number(last);
92
+ if (!id || !Number.isFinite(issuedAt) || !Number.isFinite(lastUse) || Number(port) !== ctxPort(ctx)) return null;
93
+ const want = Buffer.from(mac(ctx.proofKey, `${id}.${issued}.${last}.${port}`));
56
94
  const got = Buffer.from(sig);
57
- return want.length === got.length && crypto.timingSafeEqual(want, got);
95
+ if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return null;
96
+ if (lastUse < issuedAt || now - lastUse > LOCAL_PROOF_IDLE_MS) return null;
97
+ const absoluteEnd = issuedAt + LOCAL_PROOF_MAX_AGE_S * 1000;
98
+ if (now > absoluteEnd) return null;
99
+ return {
100
+ needsRefresh: now - lastUse > LOCAL_PROOF_REFRESH_AFTER_MS,
101
+ refreshed: seal(ctx, id, issuedAt, now),
102
+ maxAgeS: Math.max(1, Math.floor((absoluteEnd - now) / 1000)),
103
+ };
104
+ }
105
+
106
+ /** Valid, unexpired, port-bound, correctly signed proof cookie value? */
107
+ export function verifyLocalProofCookie(value: string | undefined, ctx: LocalTrustContext, now = Date.now()): boolean {
108
+ return inspectLocalProofCookie(value, ctx, now) !== null;
58
109
  }
59
110
 
60
111
  /** Read one cookie from a raw `Cookie` header (works on WS upgrade paths). */
61
- function readCookie(headers: Record<string, unknown> | undefined, name: string): string | undefined {
112
+ export function readCookie(headers: Record<string, unknown> | undefined, name: string): string | undefined {
62
113
  const raw = headers?.cookie;
63
114
  const header = Array.isArray(raw) ? raw.join("; ") : raw;
64
115
  if (typeof header !== "string") return undefined;
@@ -5,9 +5,10 @@
5
5
 
6
6
  import { isIPv4, isIPv6 } from "node:net";
7
7
  import os from "node:os";
8
+ import { GENERIC_NETWORK_DENIED_HINT, NETWORK_NOT_ALLOWED } from "@blackbelt-technology/pi-dashboard-shared/network-denial-signal.js";
8
9
  import { routeTier } from "@blackbelt-technology/pi-dashboard-shared/route-tiers.js";
9
10
  import type { FastifyReply, FastifyRequest } from "fastify";
10
- import { redactCapability } from "../live-server/live-capability.js";
11
+ import { redactCapability } from "../live-server/capability-redact.js";
11
12
  import { blockEvents } from "../tunnel/tunnel-block-events.js";
12
13
  import { isBypassed } from "./bypass-urls.js";
13
14
  import { hasLocalCredential } from "./local-credential.js";
@@ -38,7 +39,7 @@ const PROXY_FORWARDING_HEADERS = [
38
39
  * Core callers keep the 5-header list above: widening the shared constant
39
40
  * would change core admission; plugin scopes get the stricter set.
40
41
  */
41
- const PLUGIN_PROXY_FORWARDING_HEADERS = [
42
+ export const PLUGIN_PROXY_FORWARDING_HEADERS = [
42
43
  ...PROXY_FORWARDING_HEADERS,
43
44
  "via",
44
45
  "x-forwarded-server",
@@ -99,6 +100,21 @@ export function isLocallyTrusted(
99
100
  return hasLocalProof(input.headers, ctx);
100
101
  }
101
102
 
103
+ /**
104
+ * Is this a genuinely-local caller that the strict default refuses ONLY for want
105
+ * of proof — i.e. the remedy is `pi-dashboard open`? Built from the one shared
106
+ * predicate: the call without ctx means "genuinely local", the call with ctx
107
+ * means "trusted now". A signed-in or paired caller is not asked for proof.
108
+ * See change: close-container-loopback-impersonation (D3).
109
+ */
110
+ export function needsLocalProof(
111
+ request: { ip: string; headers: unknown; isAuthenticated?: boolean },
112
+ ctx: LocalTrustContext | undefined,
113
+ ): boolean {
114
+ const input = { ip: request.ip, headers: request.headers as HeaderBag };
115
+ return isLocallyTrusted(input) && !isLocallyTrusted(input, ctx) && request.isAuthenticated !== true;
116
+ }
117
+
102
118
  /**
103
119
  * May this request see the access-prompting posture (host-gate mode, whether
104
120
  * prompting is on, why a denial was not asked about)? Authenticated OR
@@ -146,13 +162,20 @@ export function isPluginScopePeerLocal(
146
162
  hostHeader: string | undefined,
147
163
  headers: HeaderBag,
148
164
  ctx?: LocalTrustContext,
165
+ /**
166
+ * `peerCredential: "plugin"` scope: the plugin authenticates the peer itself (a ticket in the URL), so
167
+ * ONLY the strict local-proof requirement is skipped here; loopback peer, loopback Host and
168
+ * no-forwarding-header still hold. See change: close-container-loopback-impersonation (D10).
169
+ */
170
+ opts: { pluginAuthenticatesPeer?: boolean } = {},
149
171
  ): boolean {
150
172
  return (
151
173
  isLoopback(ip) &&
152
174
  isLoopbackHostHeader(hostHeader) &&
153
175
  !hasProxyForwardingHeaders(headers, { extended: true }) &&
154
- // Strict: a marker-less relay is indistinguishable here; require proof.
155
- (!ctx || !ctx.strict() || hasLocalProof(headers, ctx))
176
+ // Strict: a marker-less relay is indistinguishable here; require proof (unless the plugin
177
+ // authenticates the peer with its own credential).
178
+ (opts.pluginAuthenticatesPeer === true || !ctx || !ctx.strict() || hasLocalProof(headers, ctx))
156
179
  );
157
180
  }
158
181
 
@@ -325,6 +348,19 @@ function readRequestOrigin(headers: FastifyRequest["headers"]): string | undefin
325
348
  */
326
349
  let networkDenialObserver: ((request: FastifyRequest) => void) | null = null;
327
350
 
351
+ /**
352
+ * Observer told about every REST refusal whose only fault is missing local proof
353
+ * (`local_proof_required`). The server installs its rate-limited logger here and
354
+ * clears it on stop. Best-effort: a throwing observer never alters the refusal.
355
+ * See change: close-container-loopback-impersonation (D6).
356
+ */
357
+ let localProofRefusalObserver: ((request: FastifyRequest) => void) | null = null;
358
+
359
+ /** Install (or clear, with `null`) the local-proof refusal observer. */
360
+ export function setLocalProofRefusalObserver(observer: ((request: FastifyRequest) => void) | null): void {
361
+ localProofRefusalObserver = observer;
362
+ }
363
+
328
364
  /** Install (or clear, with `null`) the network-denial observer. */
329
365
  export function setNetworkDenialObserver(observer: ((request: FastifyRequest) => void) | null): void {
330
366
  networkDenialObserver = observer;
@@ -344,17 +380,20 @@ function sendNetworkDenied(request: FastifyRequest, reply: FastifyReply, localTr
344
380
  // No grant prompt for a relayed-loopback peer: "trust 127.0.0.1?" would name
345
381
  // the tunnel agent, and the resulting entry is inert under isTrustedSource
346
382
  // (grant->deny loop). See change: fix-trusted-network-tunnel-bypass (D4).
347
- if (!isRelayedLoopback(request.ip, request.headers as Record<string, unknown>)) {
383
+ // Nor for a bare-loopback caller that merely lacks proof: the remedy is `pi-dashboard open`,
384
+ // and an unproven local caller must not be able to raise an operator prompt.
385
+ // See change: close-container-loopback-impersonation (D3, D8).
386
+ const proofNeeded = needsLocalProof(request as unknown as { ip: string; headers: unknown; isAuthenticated?: boolean }, localTrust);
387
+ if (!proofNeeded && !isRelayedLoopback(request.ip, request.headers as Record<string, unknown>)) {
348
388
  try {
349
389
  networkDenialObserver?.(request);
350
390
  } catch { /* observing is best-effort, never blocks the denial */ }
351
391
  }
352
392
  // Strict mode: a bare-loopback caller lacking proof gets an actionable denial.
353
- if (
354
- localTrust?.strict() &&
355
- isGenuinelyLocal(request.ip, request.headers as Record<string, unknown>) &&
356
- !hasLocalProof(request.headers as Record<string, unknown>, localTrust)
357
- ) {
393
+ if (proofNeeded) {
394
+ try {
395
+ localProofRefusalObserver?.(request);
396
+ } catch { /* logging is best-effort, never blocks the refusal */ }
358
397
  reply.code(403).send({
359
398
  success: false,
360
399
  error: "network_not_allowed",
@@ -369,11 +408,11 @@ function sendNetworkDenied(request: FastifyRequest, reply: FastifyReply, localTr
369
408
  // distinguish-offline-from-network-denied.
370
409
  reply.code(403).send({
371
410
  success: false,
372
- error: "network_not_allowed",
411
+ error: NETWORK_NOT_ALLOWED,
373
412
  // Identical in every trust mode: this body goes to credential-less callers
374
413
  // and must not disclose the mode or point at a trusted list.
375
414
  reason: "Source IP is not loopback and the request is not authenticated.",
376
- hint: "Pair this device (Request access) or sign in.",
415
+ hint: GENERIC_NETWORK_DENIED_HINT,
377
416
  });
378
417
  }
379
418
 
@@ -395,36 +434,50 @@ function hasNetworkPassCondition(
395
434
  request: FastifyRequest,
396
435
  opts: { readTrusted: () => string[]; localToken?: string; localTrust?: LocalTrustContext },
397
436
  ): boolean {
437
+ const { passed, trustedList } = evaluateNetworkPass(request, opts);
438
+ // Telemetry stays on the guard paths: refusals included, so the loopback-entry
439
+ // warning keeps firing.
440
+ if (trustedList) noteTrustedList(trustedList);
441
+ // Admitted by the network match alone — counted once per request (the
442
+ // per-route guard and the universal hook both evaluate it).
443
+ if (passed === "trusted") noteNetworkOnlyAdmission(request as unknown as NetworkOnlySource);
444
+ return passed !== null;
445
+ }
446
+
447
+ /** Which arm of the network pass predicate admitted a request (`null` = refused). */
448
+ export type NetworkPassArm = "local" | "strict-exception" | "token" | "auth" | "trusted";
449
+
450
+ /**
451
+ * PURE network-pass core: same ordered arms as the guards, but no telemetry and
452
+ * no request mutation. `trustedList` is set iff the core read the admission list.
453
+ * Shared by the guards (via `hasNetworkPassCondition`) and `GET /api/health`'s
454
+ * `networkAccess` verdict so the two cannot drift.
455
+ * See change: surface-network-denial-on-health (D2).
456
+ */
457
+ export function evaluateNetworkPass(
458
+ request: FastifyRequest,
459
+ opts: { readTrusted: () => string[]; localToken?: string; localTrust?: LocalTrustContext },
460
+ ): { passed: NetworkPassArm | null; trustedList?: string[] } {
398
461
  const headers = request.headers as Record<string, unknown>;
399
- // Genuine same-host origin (loopback AND no proxy-forwarding header). A tunnel
400
- // presenting as 127.0.0.1 injects a forwarding header and is NOT exempted here
401
- // (D10, narrowed). Under `requireLocalProof` it additionally needs proof.
402
- if (isLocallyTrusted({ ip: request.ip, headers }, opts.localTrust)) return true;
462
+ // Genuine same-origin (loopback AND no proxy-forwarding header). Under `requireLocalProof` it additionally needs proof.
463
+ if (isLocallyTrusted({ ip: request.ip, headers }, opts.localTrust)) return { passed: "local" };
403
464
  // Strict exceptions for a bare local caller: READ observe-tier REST routes, and
404
- // the `/v1/*` model proxy (local pi processes call it with no proof; admission is
405
- // unchanged by design — a documented trade-off).
465
+ // the `/v1/*` model proxy (admission unchanged by design — a documented trade-off).
406
466
  if (
407
467
  opts.localTrust?.strict() &&
408
468
  isGenuinelyLocal(request.ip, headers) &&
409
469
  (isObserveApiRequest(request) || isModelProxyRequest(request))
410
470
  ) {
411
- return true;
471
+ return { passed: "strict-exception" };
412
472
  }
413
473
  // Affirmative local-IPC token.
414
- if (opts.localToken && hasLocalCredential(headers)) return true;
474
+ if (opts.localToken && hasLocalCredential(headers)) return { passed: "token" };
415
475
  // Credentials BEFORE the network match, so a request that holds one is never
416
- // classified (or counted) as network-only. Admission outcomes are unchanged:
417
- // both are "allow". See change: retire-trusted-networks-bypass (D3).
418
- if ((request as any).isAuthenticated) return true;
419
- const trusted = opts.readTrusted();
420
- noteTrustedList(trusted);
421
- if (isTrustedSource(request.ip, headers, trusted, opts.localTrust)) {
422
- // Admitted by the network match alone — counted once per request (the
423
- // per-route guard and the universal hook both evaluate it).
424
- noteNetworkOnlyAdmission(request as unknown as NetworkOnlySource);
425
- return true;
426
- }
427
- return false;
476
+ // classified as network-only. See change: retire-trusted-networks-bypass (D3).
477
+ if ((request as any).isAuthenticated) return { passed: "auth" };
478
+ const trustedList = opts.readTrusted();
479
+ if (isTrustedSource(request.ip, headers, trustedList, opts.localTrust)) return { passed: "trusted", trustedList };
480
+ return { passed: null, trustedList };
428
481
  }
429
482
 
430
483
  /**
@@ -476,7 +529,7 @@ export function createNetworkGuard(
476
529
  * Every dangerous route in the server lives under one of these; the
477
530
  * namespace-coverage test enforces that. See change: add-universal-network-guard.
478
531
  */
479
- const GUARD_JURISDICTION_PREFIXES = ["/api/", "/v1/", "/editor/", "/live/"] as const;
532
+ const GUARD_JURISDICTION_PREFIXES = ["/api/", "/v1/", "/editor/", "/live/", "/preview/"] as const;
480
533
 
481
534
  /**
482
535
  * Fixed in-namespace public endpoints, compared against the EXACT pathname.
@@ -493,6 +546,17 @@ const PUBLIC_IN_NAMESPACE_PATHS: ReadonlySet<string> = new Set([
493
546
  "/api/identity/login-config",
494
547
  ]);
495
548
 
549
+ /**
550
+ * Plugin OAuth return endpoints reachable WITHOUT a dashboard session, network pass condition or signed-in
551
+ * principal (GET only). The browser that completes a Google consent may be the system browser or another
552
+ * device with no dashboard cookie. The route accepts a code only for a pending sign-in whose unguessable
553
+ * `state` this dashboard issued (one-shot, 300 s) — the state is the credential, exactly like the login
554
+ * `/auth/callback/*`. Exact paths only; no prefix match. See change: add-google-connect (D12b).
555
+ */
556
+ export const PUBLIC_PLUGIN_CALLBACK_PATHS: ReadonlySet<string> = new Set([
557
+ "/api/plugins/google/oauth/remote-callback",
558
+ ]);
559
+
496
560
  /**
497
561
  * Resolve `.` / `..` segments (RFC 3986 "remove_dot_segments") in an already
498
562
  * decoded absolute path. `..` above the root is clamped, as RFC 3986 requires.
@@ -776,6 +840,7 @@ export function createNetworkGuardHook(opts: NetworkGuardHookOptions) {
776
840
  const bypassUrls = opts.getBypassUrls?.() ?? [];
777
841
  const isPublicInNamespace = (path: string): boolean =>
778
842
  (PUBLIC_IN_NAMESPACE_PATHS.has(path) && methodAllowsHealth) ||
843
+ (PUBLIC_PLUGIN_CALLBACK_PATHS.has(path) && methodAllowsHealth) ||
779
844
  pairingPrefixes.some((prefix) => path.startsWith(prefix)) ||
780
845
  isBypassed(path, bypassUrls);
781
846
  if (isPublicInNamespace(target.raw) && isPublicInNamespace(target.resolved)) return;
@@ -14,6 +14,10 @@ import { createHash } from "node:crypto";
14
14
  import fs from "node:fs";
15
15
  import { createRequire } from "node:module";
16
16
  import path from "node:path";
17
+ import type {
18
+ CredentialFileId,
19
+ CredentialLockReason,
20
+ } from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
17
21
 
18
22
  const _require = createRequire(import.meta.url);
19
23
  const _lockfile = _require("proper-lockfile") as typeof import("proper-lockfile");
@@ -63,7 +67,7 @@ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve,
63
67
  * would stall every HTTP request and WebSocket frame for the whole wait.
64
68
  * See change: fix-provider-auth-lock-contention.
65
69
  */
66
- async function acquireLock(
70
+ export async function acquireLock(
67
71
  filePath: string,
68
72
  budgetMs: number,
69
73
  onCompromised: (err: Error) => void,
@@ -86,6 +90,34 @@ async function acquireLock(
86
90
  }
87
91
  }
88
92
 
93
+ // ── Opt-in codec seam ─────────────────────────────────────────────────
94
+ //
95
+ // Only the two credential stores pass a codec (design D1); every other caller
96
+ // keeps byte-identical plain-JSON behaviour. See change: encrypt-credentials-at-rest.
97
+
98
+ /** What a codec makes of the bytes on disk. */
99
+ type CodecReadResult =
100
+ | { kind: "absent" }
101
+ /** `encrypted:false` = a valid plaintext JSON object (readable; encrypted by the next write). */
102
+ | { kind: "document"; data: Record<string, unknown>; encrypted: boolean }
103
+ /** An envelope this process cannot read. NEVER quarantined, NEVER overwritten. */
104
+ | { kind: "locked"; reason: CredentialLockReason }
105
+ | { kind: "corrupt" };
106
+
107
+ /** Encode/decode seam for `readJsonChecked` / `writeJsonAtomic` / `withLockedJsonFile`. */
108
+ export interface JsonFileCodec {
109
+ readonly fileId: CredentialFileId;
110
+ decode(bytes: Buffer): CodecReadResult;
111
+ /**
112
+ * Bytes to write for `data`. `existing` = the bytes currently on disk (if
113
+ * any). Throws (`code: "credential_locked"`) when no key is available or the
114
+ * existing bytes are a locked envelope: a locked file is never overwritten.
115
+ */
116
+ encode(data: unknown, existing?: Buffer): Buffer;
117
+ /** The key-failure reason while no key is available (writes are refused), else `undefined`. */
118
+ unavailableReason(): CredentialLockReason | undefined;
119
+ }
120
+
89
121
  /** Rejects promise-like results at the type level (see `withLockedJsonFile`). */
90
122
  export type NotPromise<T> = T extends PromiseLike<unknown> ? never : unknown;
91
123
 
@@ -98,6 +130,11 @@ export interface LockedJsonFileOptions {
98
130
  logTag?: string;
99
131
  /** Abort the lock-retry wait. Checked before every attempt; never interrupts `fn`. */
100
132
  signal?: AbortSignal;
133
+ /**
134
+ * Credential codec. With one, no plaintext `{}` placeholder is pre-created:
135
+ * the file first appears already encoded, on the first successful write.
136
+ */
137
+ codec?: JsonFileCodec;
101
138
  }
102
139
 
103
140
  /**
@@ -117,13 +154,13 @@ export interface LockedJsonFileOptions {
117
154
  export async function withLockedJsonFile<T>(
118
155
  filePath: string,
119
156
  fn: () => T & NotPromise<T>,
120
- { budgetMs = LOCK_RETRY_BUDGET_MS, createIfMissing = true, logTag = "locked-json", signal }: LockedJsonFileOptions = {},
157
+ { budgetMs = LOCK_RETRY_BUDGET_MS, createIfMissing = true, logTag = "locked-json", signal, codec }: LockedJsonFileOptions = {},
121
158
  ): Promise<T> {
122
159
  signal?.throwIfAborted();
123
160
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
124
161
  // With `realpath: false` proper-lockfile only `mkdir`s `<file>.lock`, so the
125
162
  // target need not exist; the placeholder is for interactive writers.
126
- if (createIfMissing && !fs.existsSync(filePath)) {
163
+ if (createIfMissing && !codec && !fs.existsSync(filePath)) {
127
164
  // 0600 explicitly: without it the placeholder lands at 0666 & ~umask
128
165
  // (≈0644) and writeJsonAtomic's permission preservation carries that onto
129
166
  // every later write. See change: fix-corrupt-auth-json-500.
@@ -165,6 +202,10 @@ export interface CheckedJsonRead<T> {
165
202
  corrupt: boolean;
166
203
  /** A backup of these exact bytes exists on disk (this call, or a dedup hit). */
167
204
  quarantined: boolean;
205
+ /** Codec reads only: the file is an envelope this process cannot read. `data` is `{}`; nothing was quarantined. */
206
+ locked?: CredentialLockReason;
207
+ /** Codec reads only: `true` = decoded from an envelope, `false` = valid plaintext (to be encrypted by the next write). */
208
+ encrypted?: boolean;
168
209
  }
169
210
 
170
211
  /** In-process dedup of quarantined content: path → sha256 hex set, recorded only on a successful copy. */
@@ -239,6 +280,7 @@ function parseJsonObject(raw: string, name: string): Record<string, unknown> {
239
280
  export function readJsonChecked<T extends object = Record<string, unknown>>(
240
281
  filePath: string,
241
282
  logTag = "locked-json",
283
+ codec?: JsonFileCodec,
242
284
  ): CheckedJsonRead<T> {
243
285
  let bytes: Buffer;
244
286
  try {
@@ -247,6 +289,14 @@ export function readJsonChecked<T extends object = Record<string, unknown>>(
247
289
  if ((err as NodeJS.ErrnoException).code === "ENOENT") return { data: {} as T, corrupt: false, quarantined: false };
248
290
  throw err;
249
291
  }
292
+ if (codec) {
293
+ const out = codec.decode(bytes);
294
+ if (out.kind === "document") return { data: out.data as T, corrupt: false, quarantined: false, encrypted: out.encrypted };
295
+ if (out.kind === "locked") return { data: {} as T, corrupt: false, quarantined: false, locked: out.reason };
296
+ if (out.kind === "absent") return { data: {} as T, corrupt: false, quarantined: false };
297
+ // corrupt: today's byte-exact quarantine
298
+ return { data: {} as T, corrupt: true, quarantined: quarantineCorruptFile(filePath, bytes, logTag) };
299
+ }
250
300
  try {
251
301
  return { data: parseJsonObject(bytes.toString("utf-8"), path.basename(filePath)) as T, corrupt: false, quarantined: false };
252
302
  } catch (err) {
@@ -294,10 +344,22 @@ export function corruptUnbackedRefusal(filePath: string): Error {
294
344
  * Atomic tmp+rename write. Preserves the existing mode with group/world bits
295
345
  * cleared, or 0600 for a new file; `forceMode` overrides (corrupt-file repair).
296
346
  */
297
- export function writeJsonAtomic(filePath: string, data: unknown, forceMode?: number): void {
347
+ export function writeJsonAtomic(filePath: string, data: unknown, forceMode?: number, codec?: JsonFileCodec): void {
298
348
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
299
- const tmp = filePath + ".tmp";
300
- const content = JSON.stringify(data, null, 2) + "\n";
349
+ const tmp = `${filePath}.tmp`;
350
+ let content: string | Buffer;
351
+ if (codec) {
352
+ let existing: Buffer | undefined;
353
+ try {
354
+ existing = fs.readFileSync(filePath);
355
+ } catch (err) {
356
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
357
+ }
358
+ // Throws before any byte is written when no key is available or the file is a locked envelope.
359
+ content = codec.encode(data, existing);
360
+ } else {
361
+ content = `${JSON.stringify(data, null, 2)}\n`;
362
+ }
301
363
 
302
364
  let mode = 0o600;
303
365
  if (forceMode !== undefined) {