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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -2,17 +2,17 @@
2
2
  * Dashboard HTTP + WebSocket server.
3
3
  */
4
4
 
5
- import { readFileSync } from "node:fs";
5
+ import { readFileSync, realpathSync } from "node:fs";
6
6
  import { createRequire } from "node:module";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
9
  import { monitorEventLoopDelay } from "node:perf_hooks";
10
10
  import { fileURLToPath } from "node:url";
11
- import { createGatedProviderAuth, createIsPiExtensionInstalled, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, resolvePluginEnabled } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
+ import { createGatedProviderAuth, createIsPiExtensionInstalled, createPluginServiceRegistry, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginServerAllowed, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, registerPluginAssetsRoute, resolvePluginEnabled, type ServerLoadDeps, setDeclaredBundledPluginIds } from "@blackbelt-technology/dashboard-plugin-runtime/server";
12
12
  import {
13
13
  createMcpClientConfigService,
14
14
  createRealConfigIO,
15
- } from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
15
+ } from "@blackbelt-technology/pi-dashboard-mcp-core";
16
16
  import type { ExitIntent } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
17
17
  import { isRecoveryAllowed } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
18
18
  import { findBundledExtension, registerBridgeExtension } from "@blackbelt-technology/pi-dashboard-shared/bridge-register.js";
@@ -25,7 +25,6 @@ import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/das
25
25
  import type { HostAction, HostResource, Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
26
26
  import { advertiseDashboard, createBrowser, type DashboardBrowser, type DiscoveredServer, resolveAdvertisedAddresses, stopAdvertising } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
27
27
  import { DEFAULT_MEMORY_LIMITS } from "@blackbelt-technology/pi-dashboard-shared/memory-limits.js";
28
- import { setWindowsGitSourceSetting } from "@blackbelt-technology/pi-dashboard-shared/platform/git-source.js";
29
28
  import {
30
29
  deregisterPluginBridge,
31
30
  reconcilePluginBridgePackages,
@@ -40,7 +39,6 @@ import {
40
39
  readRuntimeRequest,
41
40
  readRuntimeState,
42
41
  } from "@blackbelt-technology/pi-dashboard-shared/runtime-overlay/state.js";
43
- import { createSemaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
44
42
  import { proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
45
43
  import { discoverServiceOffers } from "@blackbelt-technology/pi-dashboard-shared/services/offers.js";
46
44
  import { isRecoveryCandidate, isShutdownWindowCandidate, mergeSessionMeta, type SessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
@@ -54,7 +52,7 @@ import cors from "@fastify/cors";
54
52
  import rateLimit from "@fastify/rate-limit";
55
53
  import fastifyStatic from "@fastify/static";
56
54
  import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
57
- import { listGrants as listAccessGrants, setGrantsChangedListener } from "./access/access-grants.js";
55
+ import { listGrants as listAccessGrants, setGrantsChangedListener, setSessionGrantsChangedListener } from "./access/access-grants.js";
58
56
  import { snapshotAccessGrantHealth } from "./access/access-health.js";
59
57
  import { AccessPlaneRegistry, isGrantPromptKilled } from "./access/access-plane.js";
60
58
  import { shouldIssuePromptCapability } from "./access/capability-issuance.js";
@@ -64,9 +62,13 @@ import { createCwdHold } from "./access/cwd-verdict.js";
64
62
  import { installGrantCoordinator } from "./access/denial-hold.js";
65
63
  import { GrantCoordinator } from "./access/grant-coordinator.js";
66
64
  import { ensureGrantStoreId } from "./access/grant-store-id.js";
65
+ import { createPiTrustLiveProvider } from "./access/pi-trust-live.js";
67
66
  import { createPiTrustMirrorService, setPiTrustMirror } from "./access/pi-trust-mirror-service.js";
68
- import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane } from "./access/planes.js";
67
+ import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane, createPreviewEgressPlane } from "./access/planes.js";
68
+ import { projectEgressGrants } from "./access/preview-egress-store.js";
69
69
  import { promptChannelCount } from "./access/prompt-channel.js";
70
+ import { createDefaultProvisioningGrantStore } from "./access/provisioning.js";
71
+ import { installProvisioning } from "./access/provisioning-wiring.js";
70
72
  import { clearRefusal, isRefused, listRefusals, recordRefusal } from "./access/refusal-ledger.js";
71
73
  import { sourceChannel } from "./access/source-channel.js";
72
74
  import { YOLO_ENV } from "./access/yolo-env.js";
@@ -92,7 +94,11 @@ import {
92
94
  isWsOriginTrusted,
93
95
  sanitizeHeaderForLog,
94
96
  } from "./auth/cors-origin.js";
95
- import { registerCsp, resolveCspMode } from "./auth/csp.js";
97
+ import { cspNonceFor, markViteProxied, registerCsp, resolveCspMode, resolveTrustedTypesMode } from "./auth/csp.js";
98
+ import { registerCspReportSink } from "./auth/csp-report-sink.js";
99
+ import { CspReportStore } from "./auth/csp-report-store.js";
100
+ import { stateCallerFor } from "./auth/dashboard-state-caller.js";
101
+ import { isHostAdmitted } from "./auth/host-admission.js";
96
102
  import {
97
103
  createHostGate,
98
104
  evaluateHostGate,
@@ -105,26 +111,33 @@ import {
105
111
  import { ensureServerIdentity } from "./auth/identity.js";
106
112
  import { createLocalCredentialVerifier, hasLocalCredential, listenWithProofFloor } from "./auth/local-credential.js";
107
113
  import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
114
+ import { createLocalProofRefusalLogger } from "./auth/local-proof-refusal-log.js";
108
115
  import { ensureLocalToken } from "./auth/local-token.js";
109
116
  import {
110
117
  createLanInterfaceProvider,
111
118
  createNetworkGuard,
112
119
  createNetworkGuardHook,
120
+ isLocallyTrusted,
113
121
  isPluginScopePeerLocal,
122
+ needsLocalProof,
114
123
  noteTrustedList,
115
124
  parseGuardTarget,
125
+ setLocalProofRefusalObserver,
116
126
  setNetworkDenialObserver,
117
127
  } from "./auth/localhost-guard.js";
118
128
  import { createMutationOriginGate } from "./auth/mutation-origin-gate.js";
129
+ import { NavIntents } from "./auth/nav-intent.js";
119
130
  import { PasskeyService } from "./auth/passkey/passkey-service.js";
120
131
  import { resolveRpContext } from "./auth/passkey/rp-context.js";
121
132
  import { UserDirectory } from "./auth/passkey/user-directory.js";
122
133
  import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
123
134
  import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
135
+ import { isServerTrusted } from "./auth/plugin-server-trust.js";
124
136
  import { setOAuthRegistryRuntimeSource } from "./auth/provider-auth-registry.js";
125
137
  import { readAuthJson } from "./auth/provider-auth-storage.js";
126
138
  import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
127
139
  import { createRouteTierGate } from "./auth/route-tier-gate.js";
140
+ import { RotationError, rotateSecretsOnce } from "./auth/secret-rotation.js";
128
141
  import { createHostServeApp } from "./auth/serve-app-host.js";
129
142
  import { mintSpawnToken } from "./auth/spawn-token.js";
130
143
  import { admissionTrustedNetworks, effectiveTrustMode } from "./auth/trust-mode.js";
@@ -133,6 +146,7 @@ import {
133
146
  type CoreWsRouteScope,
134
147
  extractTicket,
135
148
  isCoreWsRouteScope,
149
+ mintBridgeTicket,
136
150
  routeScopeForUrl,
137
151
  setPluginScopeResolver,
138
152
  type WsRouteScope,
@@ -147,12 +161,14 @@ import {
147
161
  } from "./browser-handlers/session-action-handler.js";
148
162
  import { runLifecycleAction } from "./browser-handlers/session-lifecycle.js";
149
163
  import { createCommitDraftRelay } from "./commit-draft-relay.js";
150
- import { readRawConfig, writeConfigPartial } from "./config-api.js";
164
+ import { readRawConfig, seedWindowsSourceSettings, writeConfigPartial } from "./config-api.js";
151
165
  import {
152
166
  liveAcceptLanRequests,
153
167
  liveAllowedHosts,
154
168
  liveCorsAllowedOrigins,
169
+ liveCorsAllowZrokWildcard,
155
170
  liveHostGateMode,
171
+ livePreviewExposureOverride,
156
172
  livePublicBaseUrls,
157
173
  liveRequireLocalProof,
158
174
  liveTrustedNetworks,
@@ -164,8 +180,14 @@ import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycl
164
180
  import { createPluginSessionCloseApi, createSessionCloserRegistry } from "./embed-lifecycle/plugin-session-close.js";
165
181
  import { wireEvents } from "./event-wiring.js";
166
182
  import { createFileWatchManager } from "./file-watch-manager.js";
183
+ import { resolveMainPath } from "./git-worktree/git-operations.js";
167
184
  import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
168
- import { listPersistedTrust as listPersistedWorktreeTrust, setTrustChangedListener } from "./git-worktree/worktree-init-trust.js";
185
+ import {
186
+ listPersistedTrust as listPersistedWorktreeTrust,
187
+ listSessionTrust as listSessionWorktreeTrust,
188
+ setSessionTrustChangedListener,
189
+ setTrustChangedListener,
190
+ } from "./git-worktree/worktree-init-trust.js";
169
191
  import { identityDisarmedWarning, isIdentityEnforced } from "./identity/activation.js";
170
192
  import { buildAuthContext } from "./identity/auth-context.js";
171
193
  import { type BootstrapGrants, DENY_ALL_GRANTS, decideBootstrapGrants } from "./identity/bootstrap-grants.js";
@@ -187,12 +209,17 @@ import { canAccessSession, isLocalOperator, markLocalOperator, sessionPrincipalO
187
209
  import { scheduleAtExpiry } from "./identity/socket-lifetime.js";
188
210
  import { authorizeRoadUpgrade } from "./identity/upgrade-gate.js";
189
211
  import { createKnownServerMoves } from "./known-server-moves.js";
212
+ import { buildBrowseRootSources, resolveBrowseRoots } from "./lib/browse-roots.js";
190
213
  import {
191
214
  clientBuildDiagnostic,
192
215
  clientBuildSnapshotFor,
216
+ readServedBundledPluginIds,
193
217
  resolveStaticClientDir,
194
218
  } from "./lib/client-dist.js";
219
+ import { runWithStateCaller } from "./lib/dashboard-state-guard.js";
195
220
  import { collectRuleSources } from "./lib/folder-project.js";
221
+ import { createIndexHtmlSender } from "./lib/index-html.js";
222
+ import { listKnownFolderCwds, type RouteAdmissionDeps } from "./lib/route-admission.js";
196
223
  import { bootParentPid, isBootParentProvablyDead } from "./lifecycle/boot-parent-liveness.js";
197
224
  import { runBoundedStartup } from "./lifecycle/bounded-startup.js";
198
225
  import { startEphemeralParentWatch } from "./lifecycle/ephemeral-parent-watch.js";
@@ -204,6 +231,9 @@ import {
204
231
  redactCapability,
205
232
  sessionKeyOf,
206
233
  } from "./live-server/live-capability.js";
234
+ import { createReservedHandler } from "./live-server/live-csp-report.js";
235
+ import { createEgressGrantRequester, createPreviewEgress, requestOriginsOf } from "./live-server/live-egress.js";
236
+ import { createPreviewExposure, wirePreviewExposure } from "./live-server/live-exposure.js";
207
237
  import { createLiveServerManager } from "./live-server/live-server-manager.js";
208
238
  import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
209
239
  import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
@@ -220,8 +250,13 @@ import { logPackageHealthAtBoot } from "./package/package-health-scanner.js";
220
250
  import { type OperationResult, PackageManagerWrapper } from "./package/package-manager-wrapper.js";
221
251
  import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
222
252
  import { createRequestAccessAvailable, type KnockPeerDeps } from "./pairing/knock-admission.js";
253
+ import { bearerChannelOf, isProvenTls } from "./auth/proven-tls.js";
254
+ import { createDeviceTokenServices } from "./pairing/device-token-services.js";
255
+ import { onTlsBridgeSwitchChanged, routeBridgeUpgrade } from "./tls/tls-bridge-route.js";
256
+ import { startDeviceExpirySweep } from "./vault/device-expiry-sweep.js";
223
257
  import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
224
258
  import { PairingManager, wirePendingHint } from "./pairing/pairing.js";
259
+ import { stampSocketLocality } from "./pairing/socket-locality.js";
225
260
  import type { TieredSocket } from "./pairing/ws-tier-gate.js";
226
261
  import { buildSelfServer, wirePeerServers } from "./peer-servers.js";
227
262
  import { createPendingArchiveIntentRegistry } from "./pending/pending-archive-intent-registry.js";
@@ -245,22 +280,28 @@ import { PiCoreChecker } from "./pi/pi-core-checker.js";
245
280
  import { PiCoreUpdater } from "./pi/pi-core-updater.js";
246
281
  import { createPiGateway } from "./pi/pi-gateway.js";
247
282
  import { listGlobalSkills } from "./pi/pi-resource-scanner.js";
283
+ import { createPackageCompletionHandler, createPluginDiscoveryWiring, type PluginDiscoveryWiring } from "./plugin-discovery-wiring.js";
248
284
  import * as pluginEventSeam from "./plugin-event-seam.js";
249
285
  import { pluginIntentCache } from "./plugin-intent-cache.js";
250
286
  import { createPluginRequestLane } from "./plugin-request-lane.js";
287
+ import { getRuntimeClientRegistry, installRuntimeClientRegistry, logRuntimeAdmissions } from "./plugin-runtime-clients.js";
251
288
  import { createPushService, type PushService } from "./push/push-service.js";
252
289
  import type { SessionPresence } from "./questions/question-files.js";
253
290
  import { registerQuestionRoutes } from "./questions/question-routes.js";
291
+ import { createAgentEventHub } from "./agent-events/agent-event-hub.js";
292
+ import { registerAgentEventStreamRoutes } from "./routes/agent-event-stream-routes.js";
254
293
  import { createQuestionStack, persistedPresence } from "./questions/question-stack.js";
255
294
  import { registerAccessPromptRoutes } from "./routes/access-prompt-routes.js";
256
295
  import { registerAccessRoutes } from "./routes/access-routes.js";
296
+ import { registerAcmeRoutes } from "./routes/acme-routes.js";
257
297
  import { registerAcpRoutes } from "./routes/acp-routes.js";
258
298
  import { registerAddonsRoutes } from "./routes/addons-routes.js";
259
299
  import { registerAttachmentRoutes } from "./routes/attachment-routes.js";
260
300
  import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
301
+ import { registerCspViolationRoutes } from "./routes/csp-violations-routes.js";
261
302
  import { registerCustomEventGroupsRoutes } from "./routes/custom-event-groups-routes.js";
262
303
  import { registerDoctorRoutes } from "./routes/doctor-routes.js";
263
- import { registerFileRoutes } from "./routes/file-routes.js";
304
+ import { denialBody, gateFilePath, registerFileRoutes } from "./routes/file-routes.js";
264
305
  import { registerFolderProjectRoutes } from "./routes/folder-project-routes.js";
265
306
  import { registerGitRoutes } from "./routes/git-routes.js";
266
307
  import { registerGrepRoutes } from "./routes/grep-routes.js";
@@ -275,6 +316,7 @@ import { registerModelProxyDiagnosticsRoutes } from "./routes/model-proxy-diagno
275
316
  import { registerModelProxyRefreshRoutes } from "./routes/model-proxy-refresh-routes.js";
276
317
  import { registerModelProxyRoutes } from "./routes/model-proxy-routes.js";
277
318
  import { registerModelsIntrospectionRoute } from "./routes/models-introspection-routes.js";
319
+ import { registerNavIntentRoutes } from "./routes/nav-intent-routes.js";
278
320
  import { registerNodeRuntimeRoutes } from "./routes/node-runtime-routes.js";
279
321
  import { registerOpenSpecGroupRoutes } from "./routes/openspec-group-routes.js";
280
322
  import { registerOpenSpecRoutes } from "./routes/openspec-routes.js";
@@ -286,8 +328,10 @@ import { registerPiCoreRoutes } from "./routes/pi-core-routes.js";
286
328
  import { registerPiRetryRoutes } from "./routes/pi-retry-routes.js";
287
329
  import { registerPiRuntimeRoutes } from "./routes/pi-runtime-routes.js";
288
330
  import { registerPiSettingsRoutes } from "./routes/pi-settings-routes.js";
331
+ import { registerPiTrustQueryRoutes } from "./routes/pi-trust-query-routes.js";
289
332
  import { registerPluginActivationRoutes, setPluginsEnabled } from "./routes/plugin-activation-routes.js";
290
333
  import { registerPluginConfigRoutes } from "./routes/plugin-config-routes.js";
334
+ import { registerPluginRuntimeClientRoutes } from "./routes/plugin-runtime-client-routes.js";
291
335
  import { registerPreferencesAutoNameRoutes } from "./routes/preferences-auto-name-routes.js";
292
336
  import { registerPreferencesDisplayRoutes } from "./routes/preferences-display-routes.js";
293
337
  import { registerPreferencesWorktreeInitRoutes } from "./routes/preferences-worktree-init-routes.js";
@@ -300,10 +344,6 @@ import { registerRuntimeRoutes } from "./routes/runtime-routes.js";
300
344
  import { registerSessionRoutes, type ToolResultStats } from "./routes/session-routes.js";
301
345
  import { registerSystemRoutes } from "./routes/system-routes.js";
302
346
  import { registerTlsRoutes } from "./routes/tls-routes.js";
303
- import { registerAcmeRoutes } from "./routes/acme-routes.js";
304
- import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
305
- import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
306
- import { acmeGc } from "./tls/sources/acme/gc.js";
307
347
  import { registerToolRoutes } from "./routes/tool-routes.js";
308
348
  import { registerUserRoutes } from "./routes/user-routes.js";
309
349
  import {
@@ -325,6 +365,7 @@ import { createArchiveSweeper } from "./session/archive-sweeper.js";
325
365
  import { CustomEventGroupMatcher } from "./session/custom-event-group-matcher.js";
326
366
  import { CustomEventGroupResolver } from "./session/custom-event-group-resolver.js";
327
367
  import { deriveEndedAt } from "./session/derive-ended-at.js";
368
+ import { createReplayState } from "./session/hydration-state.js";
328
369
  import { createInFlightToolCalls } from "./session/in-flight-tool-calls.js";
329
370
  import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
330
371
  import { systemRenameUpdates } from "./session/name-provenance.js";
@@ -352,12 +393,16 @@ import { registerSpawnEnvContributorForPlugin, setSpawnEnvPluginEnabledCheck } f
352
393
  import { armSpawnWatchdog } from "./spawn-process/spawn-register-watchdog.js";
353
394
  import { createTerminalGateway } from "./terminal/terminal-gateway.js";
354
395
  import { createTerminalManager, deriveTranscriptCapBytes } from "./terminal/terminal-manager.js";
396
+ import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
397
+ import { acmeGc } from "./tls/sources/acme/gc.js";
398
+ import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
355
399
  import {
356
400
  MAIN_CONNECTION_TIMEOUT_MS,
357
401
  MAIN_KEEP_ALIVE_TIMEOUT_MS,
358
402
  TlsListener,
359
403
  } from "./tls/tls-listener.js";
360
404
  import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, liveTunnelOrigins, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
405
+ import { collectEndpoints } from "./tunnel/tunnel-endpoints.js";
361
406
  import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
362
407
  import { createVaultDeliveryHub } from "./vault/vault-delivery-hub.js";
363
408
  import { createVaultImport, defaultKnownLocations } from "./vault/vault-import.js";
@@ -365,6 +410,7 @@ import { createPluginVaultReader } from "./vault/vault-plugin-read.js";
365
410
  import { createVaultProjects } from "./vault/vault-projects.js";
366
411
  import { createVaultManageGuard, registerVaultRoutes } from "./vault/vault-routes.js";
367
412
  import { createVaultStore } from "./vault/vault-store.js";
413
+ import { createWatchFilesHandler, type WatchFilesMessage } from "./watch-files-handler.js";
368
414
 
369
415
  export interface ServerConfig {
370
416
  port: number;
@@ -441,6 +487,12 @@ export interface ServerConfig {
441
487
  /** Shape of the replay window when one applies (`head-tail` | `tail-only`).
442
488
  * Absent → `head-tail`. See change: add-tail-only-replay-window (D1). */
443
489
  replayWindowMode?: import("@blackbelt-technology/pi-dashboard-shared/memory-limits.js").ReplayWindowMode;
490
+ /**
491
+ * Test seam: shorten the bridge replay fallback exits and the keepalive sent
492
+ * to subscribers waiting on a replay (defaults 5 s idle / 60 s cap / 10 s).
493
+ * See change: fix-large-session-resume-replay (D2).
494
+ */
495
+ replayTimings?: { idleMs?: number; capMs?: number; keepaliveMs?: number };
444
496
  /** OpenSpec polling config (interval, concurrency, change detection, jitter) */
445
497
  openspec?: import("@blackbelt-technology/pi-dashboard-shared/config.js").OpenSpecPollConfig;
446
498
  /** Push notifications. Absent or `enabled !== true` means disabled (no dispatcher,
@@ -582,6 +634,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
582
634
  // the server listens (so no operator write can race it). Never re-derived
583
635
  // from the list afterwards. See change: retire-trusted-networks-bypass (D2).
584
636
  decideBootTrustMode();
637
+ // One-shot rotation of the local token + auth secret that a bare-loopback caller
638
+ // may already have read through the `~/.pi` anchor. Must precede every read of
639
+ // either value (the token below, `config.authConfig.secret`). Failure is closed:
640
+ // exit 1 before listening. See change: close-container-loopback-impersonation (D11).
641
+ try {
642
+ const rotation = await rotateSecretsOnce();
643
+ if (rotation.rotated) {
644
+ console.log("[rotation] local token and auth secret rotated once; existing sessions and proof cookies are invalidated");
645
+ if (rotation.newSecret && config.authConfig) config.authConfig.secret = rotation.newSecret;
646
+ }
647
+ } catch (err) {
648
+ if (err instanceof RotationError) {
649
+ console.error(err.describe());
650
+ process.exit(1);
651
+ }
652
+ throw err;
653
+ }
585
654
  // Ensure bridge extension is registered in pi's global settings
586
655
  // (needed for bundled installs where pi can't discover it from package.json)
587
656
  //
@@ -610,7 +679,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
610
679
  // Seed Windows git/bash source from config so spawn-env augmentation
611
680
  // (ToolResolver.buildSpawnEnv + PTY) picks bundled vs host correctly.
612
681
  // No-op on macOS/Linux. See change: embed-git-bash-on-windows.
613
- setWindowsGitSourceSetting(loadConfig().windowsGitSource);
682
+ seedWindowsSourceSettings();
614
683
 
615
684
  // Run migration from sessions.json + state.json if needed
616
685
  if (needsMigration()) {
@@ -711,7 +780,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
711
780
  let tlsBoundAt = 0;
712
781
  // Strict local-proof context (`requireLocalProof`, live config read). Threaded to
713
782
  // every genuinely-local admission site. See change: harden-trust-and-credential-boundaries (D2).
714
- const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof);
783
+ // The proof cookie is bound to the listener's port; `0` until `listen` runs (inject() in tests).
784
+ let httpListenPort = 0;
785
+ const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof, () => httpListenPort);
715
786
  const localProofCodes = new LocalProofCodeStore();
716
787
  const pairingManager = new PairingManager({
717
788
  registry: pairedDeviceRegistry,
@@ -1220,7 +1291,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1220
1291
  /** This process's place in the per-HOME rendezvous (task 2.0a). */
1221
1292
  let homeRendezvous: import("./lifecycle/home-rendezvous.js").HomeRendezvous | null = null;
1222
1293
 
1294
+ /** Live `tls.enabled && tls.acceptBridges`: the one read behind bridge routing, vault trust and the switch hook. */
1295
+ const tlsBridgesLive = (): boolean => {
1296
+ const live = loadConfig().tls;
1297
+ return live.enabled && live.acceptBridges;
1298
+ };
1299
+ // The vault hub is created further down; the gateway reports routing changes through this late binding.
1300
+ let onVaultRoutingChanged: ((sessionId: string, declared?: { certValidation?: "enforced" }) => void) | undefined;
1223
1301
  const piGateway = createPiGateway(sessionManager, {
1302
+ onRoutingChanged: (sessionId, declared) => onVaultRoutingChanged?.(sessionId, declared),
1224
1303
  ...(config.pingInterval !== undefined ? { pingInterval: config.pingInterval } : {}),
1225
1304
  // The identity a move TARGET announces on `provisional_accepted`, so the
1226
1305
  // mover can prove it reached the instance it named (D14). Unset, every
@@ -1312,8 +1391,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1312
1391
  const fitWorkerPool = createFitWorkerPool({ size: 2 });
1313
1392
 
1314
1393
  // Create terminal manager with exit callback
1394
+ // PTY caps + inline orphan TTL from `terminals.*` (restart to apply).
1395
+ // See change: harden-server-capability-bounds (D3).
1396
+ const terminalsConfig = loadConfig().terminals;
1315
1397
  const terminalManager = createTerminalManager({
1316
1398
  transcriptCapBytes,
1399
+ maxConcurrent: terminalsConfig.maxConcurrent,
1400
+ maxPerOwner: terminalsConfig.maxPerOwner,
1401
+ inlineOrphanTtlMs: terminalsConfig.inlineOrphanTtlMs,
1317
1402
  onExit: (terminalId) => {
1318
1403
  // Find and remove from session order
1319
1404
  const allOrders = sessionOrderManager.getAllOrders();
@@ -1330,7 +1415,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1330
1415
  const terminalGateway = createTerminalGateway(terminalManager);
1331
1416
 
1332
1417
  // Live-server-preview manager (loopback dev-server allowlist + proxy).
1333
- const liveServerManager = createLiveServerManager(preferencesStore);
1418
+ // Ports the dashboard itself listens on are never previewable (a loopback origin is trusted
1419
+ // by its CORS / mutation gates). See change: improve-canvas-html-and-url-ux (D1).
1420
+ const liveServerManager = createLiveServerManager(preferencesStore, {
1421
+ ownPorts: () => {
1422
+ const tls = loadConfig().tls;
1423
+ return [config.port, config.piPort, ...(tls?.enabled ? [tls.port] : [])];
1424
+ },
1425
+ });
1334
1426
 
1335
1427
  // ACP host A (in-process): attach virtual connections to THIS gateway.
1336
1428
  // See change: add-acp-session-driver (D1).
@@ -1347,7 +1439,29 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1347
1439
  questionStore.loadPersisted();
1348
1440
  questionStore.sweepAtBoot((sessionId) => persistedSessionPresence.get(sessionId) ?? "unknown");
1349
1441
 
1350
- const browserGateway = createBrowserGateway(sessionManager, eventStore, piGateway, undefined, pendingForkRegistry, sessionOrderManager, preferencesStore, directoryService, terminalManager, pendingDashboardSpawns, config.maxWsBufferBytes, pendingAttachRegistry, pendingInitialPromptRegistry, pendingResumeIntents, pendingClientCorrelations, pendingWorktreeBaseRegistry, metaPersistence, fitWorkerPool, config.maxReplayEvents, config.replayWindowMode, sessionArchive, pendingArchiveIntents, remoteTranscriptStore, pendingPrincipalOwnerRegistry, identityEnforced, undefined, questionStore);
1442
+ // Shared roots for browse confinement + the remote folder gate (ONE definition).
1443
+ // Project-scope grants only: session-scope grants are transient.
1444
+ // See change: harden-server-capability-bounds (D2).
1445
+ const browseRootSources = buildBrowseRootSources({
1446
+ preferencesStore,
1447
+ sessionManager,
1448
+ worktreeRoots: () => listPersistedWorktreeTrust().map((t) => t.repoRoot),
1449
+ projectGrants: () => listAccessGrants().filter((g) => g.scope === "project").map((g) => g.subject),
1450
+ });
1451
+ // `browse.confineRemote: false` (operator opt-out, read at start) => `null` = unconfined.
1452
+ const confineRemoteBrowse = loadConfig().browse.confineRemote;
1453
+ const browseRoots = () => (confineRemoteBrowse ? resolveBrowseRoots(browseRootSources) : Promise.resolve(null));
1454
+
1455
+ const replayState = createReplayState(config.replayTimings);
1456
+ const browserGateway = createBrowserGateway(sessionManager, eventStore, piGateway, undefined, pendingForkRegistry, sessionOrderManager, preferencesStore, directoryService, terminalManager, pendingDashboardSpawns, config.maxWsBufferBytes, pendingAttachRegistry, pendingInitialPromptRegistry, pendingResumeIntents, pendingClientCorrelations, pendingWorktreeBaseRegistry, metaPersistence, fitWorkerPool, config.maxReplayEvents, config.replayWindowMode, sessionArchive, pendingArchiveIntents, remoteTranscriptStore, pendingPrincipalOwnerRegistry, identityEnforced, undefined, questionStore, browseRoots, replayState);
1457
+ // Transition-only feed behind `GET /api/events/stream` (registry frames + question changes).
1458
+ // See change: add-agent-event-stream.
1459
+ const agentEventHub = createAgentEventHub({
1460
+ listQuestionRows: () => questionStore.listRows(),
1461
+ ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
1462
+ });
1463
+ browserGateway.onRegistryFrame(agentEventHub.onRegistryFrame);
1464
+ questionStore.onChange(agentEventHub.onQuestionChange);
1351
1465
  // App-wide pairing approval dialog: a content-free hint on every pending
1352
1466
  // change; operator browsers refetch the guarded list (D1).
1353
1467
  // See change: add-pairing-approval-dialog.
@@ -1373,21 +1487,6 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1373
1487
  isViewed: (id) => browserGateway.viewedSessionTracker.isViewedByAnyone(id),
1374
1488
  });
1375
1489
 
1376
- // Editor-pane changed-on-disk watch: the browser declares its open files via
1377
- // `watch_files`; the server watches exactly those and pushes `file_changed`.
1378
- // Torn down on disconnect so no fd leaks. See change: split-editor-workspace.
1379
- const fileWatchManager = createFileWatchManager();
1380
- browserGateway.registerHandler("watch_files", (msg: { sessionId?: string; cwd?: string; paths?: unknown }, _ws) => {
1381
- if (!msg?.sessionId || !msg?.cwd) return;
1382
- // Gate: only watch under a known session cwd (mirrors /api/file).
1383
- if (!sessionManager.listAll().some((s) => s.cwd === msg.cwd)) return;
1384
- // Harden against a malformed client payload: keep only string rel-paths.
1385
- const paths = Array.isArray(msg.paths) ? msg.paths.filter((p): p is string => typeof p === "string") : [];
1386
- fileWatchManager.setWatched(_ws, msg.sessionId, msg.cwd, paths, (sessionId, path) =>
1387
- browserGateway.broadcast({ type: "file_changed", sessionId, path }),
1388
- );
1389
- });
1390
- browserGateway.registerDisconnectHandler((ws) => fileWatchManager.clearConnection(ws));
1391
1490
 
1392
1491
  // Resolve package version once at startup
1393
1492
  const __require = createRequire(import.meta.url);
@@ -1501,6 +1600,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1501
1600
  // death signal, even when no terminal pi event was forwarded.
1502
1601
  // See change: finalize-automation-run-on-session-death.
1503
1602
  const pluginSessionEndSubs = new Set<(sessionId: string) => void>();
1603
+ // Post-boot plugin discovery (refreshPluginDiscovery + local-scope detection); built right
1604
+ // after the boot `loadServerEntries` pass. See change: decouple-plugins-from-core (5.5, 5.9).
1605
+ let pluginDiscovery: PluginDiscoveryWiring | undefined;
1504
1606
  // Plugin shutdown subscribers (ServerPluginContext.onShutdown). Dispatched
1505
1607
  // in server stop() at the exact point the goal supervisor disposes today —
1506
1608
  // BEFORE piGateway.stop() tears bridges down — so plugin backoff timers /
@@ -1521,25 +1623,56 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1521
1623
  // loader's topological order guarantees a provider's registerPlugin runs
1522
1624
  // before a dependent's consume. In-process only.
1523
1625
  // See change: register-plugin-automation-events.
1524
- const pluginServiceRegistry = new Map<string, unknown>();
1626
+ // Records the PROVIDER plugin per key and enforces `automation.action.<source>`
1627
+ // key ownership (provider id MUST equal <source>). Host-set entries
1628
+ // (`.set`) carry provider "host". See change: harden-git-terminal-plugin-boundaries (D16).
1629
+ const pluginServiceRegistry = createPluginServiceRegistry();
1630
+ // Manifest `emits` per plugin, recorded at context creation. A plugin's types
1631
+ // count only while it is LOADED (status store, live), so an unloaded or
1632
+ // disabled provider's types leave every allowlist at once.
1633
+ const pluginManifestEmits = new Map<string, readonly string[]>();
1634
+ const loadedManifestEmits = (pluginId: string): readonly string[] | undefined =>
1635
+ getPluginStatusStore().getStatus(pluginId)?.loaded === true ? pluginManifestEmits.get(pluginId) : undefined;
1636
+ // Read-only lookup for the automation action registry's subset check.
1637
+ pluginServiceRegistry.set("host.pluginManifestEmits", loadedManifestEmits);
1525
1638
  // Host-provided known-folder set for plugin cwd validation: session cwds ∪
1526
1639
  // pinned directories, as a LIVE getter (not a boot-time snapshot) so plugins
1527
1640
  // see folders added later. kb-plugin consumes this to guard its /api/kb/*
1528
1641
  // routes against arbitrary-path indexing — a session-less worktree appears
1529
1642
  // only via pinned dirs, unreachable from the plugin sessionManager surface.
1530
1643
  // See change: add-kb-folder-slot.
1531
- pluginServiceRegistry.set("host.knownFolderCwds", (): string[] => {
1532
- const set = new Set<string>();
1533
- for (const s of sessionManager.listAll()) if (s.cwd) set.add(s.cwd);
1534
- for (const d of preferencesStore.getPinnedDirectories()) set.add(d);
1535
- return [...set];
1536
- });
1644
+ // The ONE known-set function: core git/openspec/folder-project route admission uses it
1645
+ // too. See change: core-cwd-admission.
1646
+ const knownFolderCwds = (): string[] => listKnownFolderCwds({ sessionManager, preferencesStore });
1647
+ pluginServiceRegistry.set("host.knownFolderCwds", knownFolderCwds);
1537
1648
  // `indeterminate` plugin cwd admissions (a git probe that did not complete)
1538
1649
  // are worth a log line — today they are invisible — but throttled per cwd and
1539
1650
  // LRU-bounded. Plugins pass this as `admitCwd`'s `onIndeterminate`.
1540
1651
  // See change: harden-plugin-cwd-admission (D7).
1541
1652
  const cwdAdmissionLogger = createIndeterminateLogger({ warn: (m) => console.warn(m) });
1542
1653
  pluginServiceRegistry.set("host.cwdAdmissionOnIndeterminate", cwdAdmissionLogger);
1654
+ // Cwd admission of the file-family routes, live preview and `watch_files`: the same known set and
1655
+ // indeterminate logger as the plugin / git / openspec routes. See change: core-file-cwd-admission.
1656
+ const fileRouteAdmission: RouteAdmissionDeps = {
1657
+ knownCwds: knownFolderCwds,
1658
+ admitOptions: { onIndeterminate: cwdAdmissionLogger },
1659
+ };
1660
+ // Editor-pane changed-on-disk watch: the browser declares its open files via
1661
+ // `watch_files`; the server watches exactly those and pushes `file_changed`.
1662
+ // Torn down on disconnect so no fd leaks. See change: split-editor-workspace.
1663
+ // The cwd is admitted through the shared guard (change: core-file-cwd-admission).
1664
+ const watchFiles = createWatchFilesHandler({
1665
+ routeAdmission: fileRouteAdmission,
1666
+ manager: createFileWatchManager(),
1667
+ onChange: (sessionId, path) => browserGateway.broadcast({ type: "file_changed", sessionId, path }),
1668
+ });
1669
+ browserGateway.registerHandler("watch_files", (msg: WatchFilesMessage, ws) => {
1670
+ // The gateway does not await custom handlers: a rejection must not escape it.
1671
+ watchFiles.handle(msg, ws).catch((err: unknown) => {
1672
+ console.warn(`[watch_files] handler failed: ${(err as Error)?.message ?? err}`);
1673
+ });
1674
+ });
1675
+ browserGateway.registerDisconnectHandler((ws) => watchFiles.onDisconnect(ws));
1543
1676
  // pi's project-trust rule as a SESSION applies it (recorded decision, else
1544
1677
  // `defaultProjectTrust`), consumed by mcp-client to decide whether a
1545
1678
  // folder's `.pi/mcp.json` is active. Resolved once; an unresolvable pi reads
@@ -1547,12 +1680,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1547
1680
  // Durable dashboard trust is mirrored into pi's `project_trust` through a
1548
1681
  // server-written snapshot (rebuilt now from the persisted stores, so a crash
1549
1682
  // between a revoke's two writes heals at boot). See change: mirror-dashboard-trust-to-pi.
1683
+ // Server-lifetime ("live") trust: session worktree trust, session grants, YOLO
1684
+ // roots. Counted into the snapshot as `liveCount` only; the YOLO controller is
1685
+ // constructed further down, so it is read through a late-bound reference.
1686
+ // See change: mirror-dashboard-trust-live-remote.
1687
+ let yoloForLiveTrust: YoloController | undefined;
1688
+ const piTrustLive = createPiTrustLiveProvider({
1689
+ getConfig: () => loadConfig().piTrustMirror,
1690
+ listSessionTrust: listSessionWorktreeTrust,
1691
+ listSessionGrants: () => listAccessGrants().filter((g) => g.scope === "session"),
1692
+ getYolo: () => yoloForLiveTrust,
1693
+ });
1550
1694
  const piTrustMirror = createPiTrustMirrorService({
1551
1695
  getConfig: () => loadConfig().piTrustMirror,
1552
1696
  listPinned: () => preferencesStore.getPinnedDirectories(),
1553
1697
  listWorkspaceFolders: () => preferencesStore.getWorkspaces().flatMap((w) => w.folders),
1554
1698
  listWorktreeTrust: listPersistedWorktreeTrust,
1555
1699
  listPersistedGrants: () => listAccessGrants().filter((g) => g.scope === "project"),
1700
+ live: piTrustLive,
1556
1701
  });
1557
1702
  setPiTrustMirror(piTrustMirror);
1558
1703
  try {
@@ -1575,6 +1720,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1575
1720
  preferencesStore.onWorkspacesChanged(queueMirrorRefresh);
1576
1721
  setGrantsChangedListener(queueMirrorRefresh);
1577
1722
  setTrustChangedListener(queueMirrorRefresh);
1723
+ // Session entries never reach disk, so their listeners recompute the live count
1724
+ // synchronously (the snapshot is rewritten before the action reports success).
1725
+ setSessionGrantsChangedListener(() => piTrustMirror.noteLiveChanged());
1726
+ setSessionTrustChangedListener(() => piTrustMirror.noteLiveChanged());
1578
1727
  const hostProjectTrust = await loadHostProjectTrustService();
1579
1728
  pluginServiceRegistry.set("host.isProjectTrusted", hostProjectTrust.isProjectTrusted);
1580
1729
  pluginServiceRegistry.set("host.projectTrustSource", hostProjectTrust.projectTrustSource);
@@ -1597,9 +1746,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1597
1746
  // `onRequest` hook — `/mcp` deliberately does not trust
1598
1747
  // `request.isAuthenticated`, so it needs the registry directly.
1599
1748
  // See change: add-dashboard-mcp-server.
1749
+ const deviceTokenServices = createDeviceTokenServices(pairedDeviceRegistry);
1600
1750
  pluginServiceRegistry.set(
1601
1751
  "host.verifyDeviceToken",
1602
- (token: string): string | null => pairedDeviceRegistry.verify(token)?.id ?? null,
1752
+ // The request is optional (the plugin host services receive none today): absent → non-proven, fail closed.
1753
+ deviceTokenServices.verifyDeviceToken,
1603
1754
  );
1604
1755
  // Tier-aware service board entry (change: expand-mcp-tiered-surface, D1).
1605
1756
  // A NEW key, not a signature change to the old one: `mcp-server-plugin` is
@@ -1608,7 +1759,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1608
1759
  // `host.verifyDeviceToken` with `tier: "operate"`.
1609
1760
  pluginServiceRegistry.set(
1610
1761
  "host.verifyDeviceTokenTier",
1611
- (token: string) => pairedDeviceRegistry.verify(token),
1762
+ deviceTokenServices.verifyDeviceTokenTier,
1612
1763
  );
1613
1764
  // Prefers the BOUND port, falls back to the CONFIGURED one.
1614
1765
  //
@@ -1657,6 +1808,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1657
1808
  for (const h of pluginSessionEndSubs) {
1658
1809
  try { h(sessionId); } catch (err) { console.error("[plugin-onSessionEnded]", err); }
1659
1810
  }
1811
+ pluginDiscovery?.onSessionEnded();
1812
+ }
1813
+ // A bridge registered: a cwd not yet scanned may carry local-scope plugins. Deferred one tick so the
1814
+ // session is in the manager's active list. See change: decouple-plugins-from-core (task 5.9).
1815
+ function dispatchSessionRegisteredCwd(cwd: string): void {
1816
+ setImmediate(() => pluginDiscovery?.onSessionRegistered(cwd));
1660
1817
  }
1661
1818
  // Notify a resolved session's OWNING plugin only. Routed by ownerId so no
1662
1819
  // plugin sees another's ref. See change: detach-automation-goal-from-core.
@@ -1745,8 +1902,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1745
1902
  isSessionConnected: (sessionId) => piGateway.getConnectedSessionIds().includes(sessionId),
1746
1903
  isDeliveryEnabled: () => loadConfig().vault.deliveryEnabled,
1747
1904
  getGraceHours: () => loadConfig().vault.offlineGraceHours,
1905
+ // What the hub itself observed about each socket, and the registry's view of the device behind it
1906
+ // (prove-vault-bridge-tls D3-D5). A TLS-admitted channel also needs the switch live-on.
1907
+ getChannel: (sessionId) => piGateway.channelOf(sessionId),
1908
+ getDeviceTrust: (deviceId) => pairedDeviceRegistry.deviceTrust(deviceId),
1909
+ isTlsBridgesLive: tlsBridgesLive,
1910
+ exposurePending: () => pairedDeviceRegistry.exposurePending(),
1911
+ });
1912
+ onVaultRoutingChanged = (sessionId, declared) => vaultDelivery.handleRegister(sessionId, declared);
1913
+ // Revoke, rotation, add and a first plaintext exposure withdraw within the push debounce (~150 ms).
1914
+ pairedDeviceRegistry.onChange(() => vaultDelivery.schedulePush());
1915
+ // Time-based expiry has no event: a 30 s sweep pushes only when a device LEFT the active set.
1916
+ const stopDeviceExpirySweep = startDeviceExpirySweep({
1917
+ activeIds: () => pairedDeviceRegistry.activeIds(),
1918
+ onLeft: () => vaultDelivery.schedulePush(),
1748
1919
  });
1749
1920
  wireEvents({
1921
+ replayState,
1750
1922
  inFlightToolCalls,
1751
1923
  vaultDelivery,
1752
1924
  // Lazy: `yolo` is constructed further down; a pre-init call throws and the
@@ -1790,6 +1962,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1790
1962
  dispatchPluginRequest,
1791
1963
  dispatchPluginRawEvent,
1792
1964
  dispatchPluginSessionEnded,
1965
+ dispatchSessionRegisteredCwd,
1793
1966
  metaPersistence,
1794
1967
  liveEpoch,
1795
1968
  commitDraftRelay,
@@ -1981,6 +2154,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
1981
2154
  // which single origin we mint OAuth URIs and set cookies for.
1982
2155
  // See change: add-zrok-custom-reserved-name (D4).
1983
2156
  getLiveTunnelOrigins: liveTunnelOrigins,
2157
+ // Opt-in zrok wildcard for CORS READS only (B19); admission forces it off.
2158
+ allowZrokWildcard: liveCorsAllowZrokWildcard(),
1984
2159
  allowedHosts: liveAllowedHosts(),
1985
2160
  publicBaseUrls: livePublicBaseUrls(),
1986
2161
  bindHost: config.host,
@@ -2015,6 +2190,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2015
2190
  grantPlanes.register(
2016
2191
  createCorsPlane({ readRawCors: () => (readRawConfig().cors ?? {}) as Record<string, unknown>, writeConfigPartial }),
2017
2192
  );
2193
+ // Preview egress: an external https origin a restricted live preview may load, granted per project.
2194
+ // The dashboard's own origins (tunnels, public base URLs, configured CORS origins) are never grantable.
2195
+ // See change: improve-canvas-html-and-url-ux (D7).
2196
+ const previewEgressOwnOrigins = (): string[] =>
2197
+ [getTunnelUrl(), ...liveTunnelOrigins(), ...livePublicBaseUrls(), ...corsAllowedOrigins()].flatMap((u) => {
2198
+ try {
2199
+ return typeof u === "string" && u ? [new URL(u).origin] : [];
2200
+ } catch {
2201
+ return [];
2202
+ }
2203
+ });
2204
+ grantPlanes.register(createPreviewEgressPlane({ ownOrigins: previewEgressOwnOrigins }));
2018
2205
  // YOLO (design D13): consulted at the prompt point; the refusal ledger stops it
2019
2206
  // reversing an explicit deny. Environment activation is attempted once, at
2020
2207
  // boot, and refused outright in report mode or on any unusable root.
@@ -2022,6 +2209,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2022
2209
  hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
2023
2210
  isRefused,
2024
2211
  });
2212
+ yoloForLiveTrust = yolo;
2213
+ yolo.setChangeListener(() => piTrustMirror.noteLiveChanged());
2025
2214
  const yoloBoot = yolo.activateFromEnv(process.env[YOLO_ENV]);
2026
2215
  if (yoloBoot.ok) {
2027
2216
  const s = yoloBoot.session;
@@ -2053,6 +2242,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2053
2242
  console.error(`[access-grant] grant_response failed: ${(err as Error)?.message ?? err}`);
2054
2243
  });
2055
2244
  });
2245
+ // Access provisioning (change: add-access-provisioning): the registry wired to the gateway's
2246
+ // operator sockets (live capability AND operate tier), with its per-request expiry timers.
2247
+ const provisioning = installProvisioning({
2248
+ gateway: browserGateway,
2249
+ deps: {
2250
+ now: Date.now,
2251
+ grants: createDefaultProvisioningGrantStore(),
2252
+ // Same two calls as `storePiTrustChoiceOfVerdict`: store the choice, then refresh the snapshot.
2253
+ mirror: () => ({
2254
+ setChoice: (kind, folder, choice) => {
2255
+ piTrustMirror.setChoice(kind, folder, choice);
2256
+ piTrustMirror.refresh();
2257
+ },
2258
+ }),
2259
+ ladder: {
2260
+ killSwitch: () => isGrantPromptKilled(),
2261
+ promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
2262
+ hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
2263
+ },
2264
+ },
2265
+ });
2266
+ browserGateway.registerHandler("provision_response", provisioning.onResponse);
2267
+ // REST refusals whose only fault is missing local proof: one bounded line per (route, reason) per window.
2268
+ // See change: close-container-loopback-impersonation (D6).
2269
+ const localProofRefusalLog = createLocalProofRefusalLogger();
2270
+ setLocalProofRefusalObserver((request) =>
2271
+ localProofRefusalLog.log({
2272
+ peer: request.ip,
2273
+ host: request.headers.host,
2274
+ method: request.method,
2275
+ route: request.routeOptions?.url,
2276
+ reason: "local_proof_required",
2277
+ }),
2278
+ );
2056
2279
  setNetworkDenialObserver((request) => {
2057
2280
  // `pair`: a network match grants nothing, so a denial is not a trust request
2058
2281
  // — the block event is still recorded (by the guard), but no network prompt
@@ -2126,7 +2349,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2126
2349
  // `PI_DASHBOARD_CSP=enforce` flips to enforcing once report-only is clean.
2127
2350
  // Skips proxied prefixes (/editor, /live) so their own policies stand.
2128
2351
  // See change: improve-content-editor (§7).
2129
- registerCsp(fastify, resolveCspMode(process.env.PI_DASHBOARD_CSP));
2352
+ // Trusted Types rides the same hook under its own `PI_DASHBOARD_TRUSTED_TYPES`
2353
+ // mode (also stamped into index.html as a meta). See change: harden-client-sinks (D7).
2354
+ const cspMode = resolveCspMode(process.env.PI_DASHBOARD_CSP);
2355
+ const trustedTypesMode = resolveTrustedTypesMode(process.env.PI_DASHBOARD_TRUSTED_TYPES, cspMode);
2356
+ registerCsp(fastify, cspMode, trustedTypesMode);
2130
2357
 
2131
2358
  // Register auth plugin if configured (must be before routes)
2132
2359
  // Decorate isAuthenticated once, up front, so both the bearer branch and the
@@ -2147,7 +2374,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2147
2374
  // Liveness is re-checked at every use, so a revoked device, an ended session
2148
2375
  // or a removed target is refused on its next request.
2149
2376
  const liveCapabilities = new LiveCapabilityStore({
2150
- isTargetLive: (id) => liveServerManager.get(id) !== undefined,
2377
+ isTargetLive: (id) => liveServerManager.has(id),
2151
2378
  isPrincipalLive: (p) => {
2152
2379
  if (p.identityExpiresAt !== undefined && p.identityExpiresAt <= Date.now()) return false;
2153
2380
  // Minted on network trust alone: only valid while network trust still authenticates.
@@ -2157,6 +2384,59 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2157
2384
  return true;
2158
2385
  },
2159
2386
  });
2387
+ // An evicted preset / static target takes its tokens with it.
2388
+ liveServerManager.setEvictionListener((id) => liveCapabilities.revokeByTarget(id));
2389
+ // Per-token egress state (markup scan, CSP reports, allow-once, project grants). Project grants are read
2390
+ // from their store on every CSP build, so a grant or revoke applies on the next response with no restart.
2391
+ const previewEgress = createPreviewEgress({
2392
+ getStatic: (id) => liveServerManager.getStatic(id),
2393
+ presetCwdOf: (id) => {
2394
+ const sessionId = liveServerManager.presetSessionOf(id);
2395
+ return sessionId ? sessionManager.get(sessionId)?.cwd : undefined;
2396
+ },
2397
+ projectKeyOf: (cwd) => {
2398
+ let real = cwd;
2399
+ try {
2400
+ real = realpathSync(cwd);
2401
+ } catch {
2402
+ /* keep the stated cwd */
2403
+ }
2404
+ return resolveMainPath(real) ?? real;
2405
+ },
2406
+ projectGrants: projectEgressGrants,
2407
+ allowOnce: (viewerId) => liveCapabilities.getAllowOnce(viewerId),
2408
+ ownOrigins: previewEgressOwnOrigins,
2409
+ });
2410
+ // Preview exposure (is the dashboard reachable from anywhere but this machine?). Drives the
2411
+ // scripts rule on restricted mints; a flip to `exposed` kills restricted scripted local-only
2412
+ // tokens and tells open viewers to re-mint. See change: improve-canvas-html-and-url-ux (D5).
2413
+ const previewExposure = createPreviewExposure({
2414
+ getBindHost: () => config.host,
2415
+ getEndpoints: () =>
2416
+ collectEndpoints({
2417
+ providerEndpoints: [getTunnelUrl(), ...liveTunnelOrigins()]
2418
+ .filter((u): u is string => typeof u === "string" && u.length > 0)
2419
+ .map((url) => ({ kind: "public" as const, url, tls: url.startsWith("https://") })),
2420
+ publicBaseUrls: livePublicBaseUrls(),
2421
+ port: config.port,
2422
+ tlsEndpoints: tlsListener.tlsListenerUrls(),
2423
+ includeLocal: false,
2424
+ }).map((e) => e.url),
2425
+ getConfigOverride: livePreviewExposureOverride,
2426
+ });
2427
+ wirePreviewExposure({
2428
+ exposure: previewExposure,
2429
+ capabilities: liveCapabilities,
2430
+ broadcast: (epoch) => browserGateway.broadcastToAll({ type: "preview_exposure_changed", epoch }),
2431
+ });
2432
+ // Detect the flip even when no request arrives (a tunnel connecting), within the viewers' 2 s budget.
2433
+ const previewExposureTimer = setInterval(() => previewExposure.current(), 1000);
2434
+ previewExposureTimer.unref();
2435
+ fastify.addHook("onClose", async () => clearInterval(previewExposureTimer));
2436
+ // A request carrying a forwarding header pins the exposure to `exposed` until restart (fails closed).
2437
+ fastify.addHook("onRequest", async (request) => {
2438
+ previewExposure.noteRequest(request.headers as Record<string, unknown>);
2439
+ });
2160
2440
  fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities));
2161
2441
  registerBearerAuth(fastify, { registry: pairedDeviceRegistry });
2162
2442
  registerDeviceSessionRoutes(fastify, {
@@ -2438,6 +2718,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2438
2718
  sessionArchive,
2439
2719
  remoteTranscriptStore,
2440
2720
  isResolverActive: identityEnforced,
2721
+ // `uiUrl` / `diffUrl` origin inputs (read live per request).
2722
+ // See change: add-session-ui-deep-links-for-agents (D1).
2723
+ uiLinks: {
2724
+ configuredOrigins: () =>
2725
+ [
2726
+ ...livePublicBaseUrls(),
2727
+ ...[getTunnelUrl(), ...liveTunnelOrigins()].filter((u): u is string => !!u),
2728
+ config.authConfig?.redirectBaseUrl,
2729
+ ].filter((u): u is string => !!u),
2730
+ isAdmitted: (hostHeader) => isHostAdmitted(hostHeader, getHostGateCtx().admission),
2731
+ port: () => config.port,
2732
+ },
2441
2733
  // Transcript-sourced session diffs dispatch through the same pool the
2442
2734
  // hydration path owns; `maxStringSize` is the store's cap so projected
2443
2735
  // tool payloads match store-sourced ones. See change:
@@ -2469,6 +2761,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2469
2761
  return ids.length;
2470
2762
  };
2471
2763
  registerPiRetryRoutes(fastify, { networkGuard, reloadConnectedSessions });
2764
+ // Trusted Types / CSP violation counters (authenticated, rate-limited, counters
2765
+ // only). See change: harden-client-sinks (D8).
2766
+ // The store is built first: the violation route feeds its persisted `ttShadow` aggregate.
2767
+ // See change: add-trusted-types-shadow-enforce (D6).
2768
+ const cspReportStore = new CspReportStore();
2769
+ registerCspViolationRoutes(fastify, {
2770
+ networkGuard,
2771
+ log: { warn: (m) => fastify.log.warn(m) },
2772
+ recordShadow: (outcome, count) => cspReportStore.recordShadow(outcome, count),
2773
+ });
2774
+ // Baseline CSP report sink (`POST /__pi/csp-report/:policy`, public to the OAuth gate), its
2775
+ // persisted counter (`~/.pi/dashboard/csp-reports.json`) and the operator reset
2776
+ // (`POST /api/csp-reports/reset`, operate). See change: harden-cors-and-csp-reporting (D8).
2777
+ registerCspReportSink(fastify, { store: cspReportStore, networkGuard });
2778
+ // Signed navigation intents for operator-opened route-backed overlays
2779
+ // (per-process key: a restart invalidates them). See change: harden-client-sinks (D10).
2780
+ registerNavIntentRoutes(fastify, { networkGuard, intents: new NavIntents() });
2472
2781
  // On-demand AI mermaid repair (opt-in via `mermaidRepair` config; 404 when off).
2473
2782
  // See change: add-mermaid-ai-repair.
2474
2783
  registerMermaidRepairRoutes(fastify, {
@@ -2495,6 +2804,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2495
2804
  // the workspace link) yields `undefined` — the route clamps to the
2496
2805
  // default. The cast is dropped once the branch lands.
2497
2806
  removeBatchCap: (loadConfig() as DashboardConfig & { removeBatchCap?: number }).removeBatchCap,
2807
+ // Core cwd admission against the same known set as plugin routes.
2808
+ // See change: core-cwd-admission.
2809
+ knownCwds: knownFolderCwds,
2810
+ admitOptions: { onIndeterminate: cwdAdmissionLogger },
2498
2811
  });
2499
2812
 
2500
2813
  // Browser channel for worktree-init event subscriptions. The dialog
@@ -2516,9 +2829,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2516
2829
  if (cwd) worktreeInitRegistry.unsubscribeCwd(cwd, ws);
2517
2830
  });
2518
2831
  registerFileRoutes(fastify, {
2832
+ // Remote browse confinement (change: harden-server-capability-bounds, D1/D2):
2833
+ // strict-proof context + the two root sources only this file can read.
2834
+ localTrust,
2835
+ browseConfineRemote: confineRemoteBrowse,
2836
+ browseRootSources: {
2837
+ worktreeRoots: browseRootSources.worktreeRoots,
2838
+ projectGrants: browseRootSources.projectGrants,
2839
+ },
2519
2840
  sessionManager,
2520
2841
  preferencesStore,
2521
2842
  networkGuard,
2843
+ routeAdmission: fileRouteAdmission,
2522
2844
  // Plugin file-handler seams for POST /api/file/write-binary: live claim registry
2523
2845
  // (read at request time: enabled + server entry loaded), registered validators,
2524
2846
  // bounded worker pool. See change: add-editor-pane-file-handlers (D4).
@@ -2544,16 +2866,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2544
2866
  validatorPool: getFileValidatorPool(),
2545
2867
  },
2546
2868
  });
2547
- registerGrepRoutes(fastify, { sessionManager, networkGuard });
2869
+ registerGrepRoutes(fastify, { sessionManager, networkGuard, routeAdmission: fileRouteAdmission });
2548
2870
  // Folder project identity (declared file + plugin marker rules). Rules come
2549
2871
  // only from plugins that are loaded + enabled + fixture-allowed, read per
2550
2872
  // request. See change: add-project-scoped-apps.
2551
2873
  registerFolderProjectRoutes(fastify, {
2552
2874
  networkGuard,
2553
- knownCwds: () => [
2554
- ...sessionManager.listAll().map((s) => s.cwd),
2555
- ...preferencesStore.getPinnedDirectories(),
2556
- ],
2875
+ knownCwds: knownFolderCwds,
2557
2876
  getRuleSources: () => {
2558
2877
  const cfg = loadConfig();
2559
2878
  const store = getPluginStatusStore();
@@ -2568,7 +2887,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2568
2887
  });
2569
2888
  // Settings → Access review surface + the one endpoint that can create a
2570
2889
  // filesystem grant. See change: add-access-grants-and-review.
2571
- registerAccessRoutes(fastify, { networkGuard, preferencesStore, writeConfigPartial });
2890
+ registerAccessRoutes(fastify, {
2891
+ networkGuard,
2892
+ preferencesStore,
2893
+ writeConfigPartial,
2894
+ provisioning: { registry: provisioning.registry, announce: provisioning.announce },
2895
+ });
2572
2896
  // Pending-question stack REST roads (list/detail/answer/summarize); the answer
2573
2897
  // claim is shared with the browser `prompt_response` road.
2574
2898
  // See change: add-pending-question-stack (D8, D9).
@@ -2579,6 +2903,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2579
2903
  isResolverActive: identityEnforced,
2580
2904
  ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
2581
2905
  });
2906
+ // SSE agent-event feed for external controllers. See change: add-agent-event-stream.
2907
+ registerAgentEventStreamRoutes(fastify, { networkGuard, hub: agentEventHub, isResolverActive: identityEnforced });
2582
2908
  registerAccessPromptRoutes(fastify, {
2583
2909
  networkGuard,
2584
2910
  coordinator: grantCoordinator,
@@ -2608,9 +2934,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2608
2934
  piGateway,
2609
2935
  // Live (per-request) config for the workflow-schema gates + new-project default.
2610
2936
  getOpenSpecConfig: () => loadConfig().openspec,
2611
- // Own bounded pool for the workflow-schema `newer`/`conflict` validate: the
2612
- // directory service's semaphore is not exposed. See change: add-pi-spec-driven-schema.
2613
- spawnSemaphore: createSemaphore(loadConfig().openspec.maxConcurrentSpawns),
2937
+ // The directory service's ONE spawn semaphore (cap resizable by
2938
+ // `reconfigurePolling`) bounds the route's `newer`/`conflict` validate too.
2939
+ // See changes: add-pi-spec-driven-schema, move-workflow-schema-status-to-poll-worker.
2940
+ spawnSemaphore: directoryService.semaphore,
2941
+ // Core cwd admission against the same known set as plugin routes.
2942
+ // See change: core-cwd-admission.
2943
+ knownFolderCwds,
2944
+ admitOptions: { onIndeterminate: cwdAdmissionLogger },
2614
2945
  onOpenSpecChanged: (cwd) => {
2615
2946
  const data = directoryService.getOpenSpecData(cwd);
2616
2947
  if (data) browserGateway.broadcastToAll({ type: "openspec_update", cwd, data });
@@ -2639,6 +2970,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2639
2970
  preferencesStore,
2640
2971
  networkGuard,
2641
2972
  store: openspecGroupStore,
2973
+ routeAdmission: fileRouteAdmission,
2642
2974
  });
2643
2975
 
2644
2976
 
@@ -2711,6 +3043,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2711
3043
  const hasProductionBuild = clientDirResolved !== null;
2712
3044
  // ONE snapshot feeds the startup diagnostic, `fastifyStatic`, and
2713
3045
  // `/api/health.clientBuild` (passed to `registerSystemRoutes` below).
3046
+ // Served declaration's `bundledPluginIds` reach discovery BEFORE any server-side discovery call
3047
+ // (D15). See change: decouple-plugins-from-core (task 5.4).
3048
+ setDeclaredBundledPluginIds(readServedBundledPluginIds(clientDirResolved));
2714
3049
  const clientBuild = clientBuildSnapshotFor(clientDirResolved);
2715
3050
  console.log(clientBuildDiagnostic(clientBuild));
2716
3051
  if (!hasProductionBuild) {
@@ -2719,7 +3054,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2719
3054
 
2720
3055
  registerAcpRoutes(fastify);
2721
3056
  registerTlsRoutes(fastify, { networkGuard, listener: tlsListener });
2722
- registerSystemRoutes(fastify, { onVaultConfigChanged: () => void vaultDelivery.pushNow(), tls: tlsListener, sessionManager, preferencesStore, metaPersistence, config, networkGuard, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, clientDir, clientBuild, readTrustedNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []), readAccessGrants: () => snapshotAccessGrantHealth({ coordinator: grantCoordinator, yolo, refusalCount: () => listRefusals().length, promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true, killSwitch: () => isGrantPromptKilled(), hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode, operatorChannels: () => promptChannelCount() }), keeperLogStats: { get: () => getKeeperManager().getKeeperLogStats() }, readPushErrors: pushService ? () => pushService?.errors ?? [] : pushInitError ? () => [pushInitError as string] : undefined });
3057
+ // Live pi-trust query: authenticated one-shot HTTP for the bridge's `project_trust`.
3058
+ // See change: mirror-dashboard-trust-live-remote.
3059
+ const piTrustQuery = registerPiTrustQueryRoutes(fastify, {
3060
+ getConfig: () => loadConfig().piTrustMirror,
3061
+ live: () => piTrustMirror.live,
3062
+ readSnapshot: () => piTrustMirror.readSnapshot(),
3063
+ });
3064
+ registerSystemRoutes(fastify, { onVaultConfigChanged: () => void vaultDelivery.pushNow(), onTlsBridgeSwitchChanged: () => onTlsBridgeSwitchChanged({ acceptBridges: tlsBridgesLive, push: () => void vaultDelivery.pushNow(), gateway: piGateway }), exposureWritePending: () => pairedDeviceRegistry.exposurePending(), tls: tlsListener, sessionManager, preferencesStore, metaPersistence, config, networkGuard, localTrust, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, clientDir, clientBuild, readTrustedNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []), readPiTrustLive: piTrustQuery.counters, readCspReports: () => cspReportStore.snapshot(), readAccessGrants: () => snapshotAccessGrantHealth({ coordinator: grantCoordinator, yolo, refusalCount: () => listRefusals().length, promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true, killSwitch: () => isGrantPromptKilled(), hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode, operatorChannels: () => promptChannelCount(), provisioning: () => provisioning.registry.stats() }), keeperLogStats: { get: () => getKeeperManager().getKeeperLogStats() }, readPushErrors: pushService ? () => pushService?.errors ?? [] : pushInitError ? () => [pushInitError as string] : undefined });
2723
3065
  registerHostGateRoutes(fastify, { getCtx: getHostGateCtx, state: hostGateState, networkGuard });
2724
3066
  // GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
2725
3067
  // Assigned by the runtime-overlay block below; read lazily per request.
@@ -2849,27 +3191,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2849
3191
  let modelProxyMounted = false;
2850
3192
 
2851
3193
  // On completion: broadcast to browsers + invalidate the recommended cache
2852
- packageManagerWrapper.setCompleteListener((result) => {
2853
- browserGateway.broadcastToAll({
2854
- type: "package_operation_complete",
2855
- operationId: result.operationId,
2856
- action: result.action,
2857
- source: result.source,
2858
- scope: result.scope,
2859
- success: result.success,
2860
- error: result.error,
2861
- diagnostics: result.diagnostics,
2862
- sessionsReloaded: (result as OperationResult & { sessionsReloaded?: number }).sessionsReloaded,
2863
- ...(result.moveId ? { moveId: result.moveId } : {}),
2864
- ...(result.partialSuccess ? { partialSuccess: result.partialSuccess } : {}),
2865
- } as PackageOperationCompleteMessage);
2866
- if (result.success) invalidateRecommendedCache();
3194
+ packageManagerWrapper.setCompleteListener(createPackageCompletionHandler<OperationResult>({
3195
+ broadcastComplete: (result) => {
3196
+ browserGateway.broadcastToAll({
3197
+ type: "package_operation_complete",
3198
+ operationId: result.operationId,
3199
+ action: result.action,
3200
+ source: result.source,
3201
+ scope: result.scope,
3202
+ success: result.success,
3203
+ error: result.error,
3204
+ diagnostics: result.diagnostics,
3205
+ sessionsReloaded: (result as OperationResult & { sessionsReloaded?: number }).sessionsReloaded,
3206
+ ...(result.moveId ? { moveId: result.moveId } : {}),
3207
+ ...(result.partialSuccess ? { partialSuccess: result.partialSuccess } : {}),
3208
+ } as PackageOperationCompleteMessage);
3209
+ },
3210
+ invalidateRecommendedCache,
3211
+ // Hot-add: a successful op refreshes plugin discovery (global) or local-scope detection
3212
+ // (local); ONE `plugins_changed` follows the completion broadcast. Never from
3213
+ // `package-routes.ts`. See change: decouple-plugins-from-core (task 5.7, D16).
3214
+ discovery: () => pluginDiscovery,
2867
3215
  // A successful package operation may have changed plugin requirement
2868
3216
  // satisfaction. Refresh probes and broadcast plugin_config_update for
2869
3217
  // any plugin whose `missingRequirements` flipped.
2870
3218
  // See change: add-plugin-activation-ui.
2871
- if (result.success) {
2872
- void refreshRequirementProbesFor(
3219
+ refreshProbes: () =>
3220
+ refreshRequirementProbesFor(
2873
3221
  null,
2874
3222
  {
2875
3223
  listInstalled: () => packageManagerWrapper.listInstalled("global"),
@@ -2885,9 +3233,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2885
3233
  config: status ?? {},
2886
3234
  });
2887
3235
  }
2888
- });
2889
- }
2890
- });
3236
+ }),
3237
+ }));
2891
3238
 
2892
3239
  // Reload all active sessions after a successful package operation
2893
3240
  packageManagerWrapper.setReloadSessions(async () => {
@@ -2902,7 +3249,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2902
3249
  return count;
2903
3250
  });
2904
3251
 
2905
- registerPackageRoutes(fastify, { packageManagerWrapper });
3252
+ registerPackageRoutes(fastify, { packageManagerWrapper, routeAdmission: fileRouteAdmission });
2906
3253
  registerPackageHealthRoutes(fastify, { packageManagerWrapper });
2907
3254
  registerResourceActivationRoutes(fastify, {
2908
3255
  networkGuard,
@@ -2913,6 +3260,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
2913
3260
  browserGateway.headlessPidRegistry
2914
3261
  .listSessions()
2915
3262
  .map((e) => ({ sessionId: e.sessionId, cwd: e.cwd })),
3263
+ routeAdmission: fileRouteAdmission,
2916
3264
  });
2917
3265
  registerRecommendedRoutes(fastify, {
2918
3266
  packageManagerWrapper,
@@ -3029,8 +3377,45 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3029
3377
  ]);
3030
3378
 
3031
3379
  // Live-server-preview routes + reverse proxy (main-origin /live/:id/*).
3032
- registerLiveServerRoutes(fastify, liveServerManager, { networkGuard, capabilities: liveCapabilities });
3033
- registerLiveServerProxy(fastify, liveServerManager, { isDeviceBearer: (token) => pairedDeviceRegistry.verify(token) !== null });
3380
+ registerLiveServerRoutes(fastify, liveServerManager, {
3381
+ networkGuard,
3382
+ capabilities: liveCapabilities,
3383
+ exposure: previewExposure,
3384
+ promptingEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
3385
+ getTrustedNetworks: admissionList,
3386
+ localTrust,
3387
+ egress: previewEgress,
3388
+ requestEgressGrant: createEgressGrantRequester(grantCoordinator),
3389
+ channelOf: (request) => sourceChannel(request.ip),
3390
+ // `start-static`: the SAME gate as a raw file read; a refusal answers with that route's status and body.
3391
+ staticGate: async (cwd, relPath, opts) => {
3392
+ const gate = await gateFilePath(cwd, relPath, fileRouteAdmission, { allowGrant: true, disclosure: opts.disclosure });
3393
+ if ("code" in gate) {
3394
+ return {
3395
+ ok: false,
3396
+ status: gate.code,
3397
+ body: denialBody(gate),
3398
+ // The 503 of an undecidable cwd admission carries `Retry-After` like every file route.
3399
+ ...(gate.code === 503 ? { headers: { "Retry-After": "1" } } : {}),
3400
+ };
3401
+ }
3402
+ return { ok: true, resolved: gate.resolved };
3403
+ },
3404
+ });
3405
+ registerLiveServerProxy(fastify, liveServerManager, {
3406
+ isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
3407
+ isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
3408
+ grantedOrigins: (grant) => previewEgress.grantedFor(grant),
3409
+ onStaticHtmlServed: (grant, real) => previewEgress.noteServed(grant, real),
3410
+ reservedHandler: createReservedHandler({
3411
+ egress: previewEgress,
3412
+ ownOriginsOf: (request) => requestOriginsOf(request),
3413
+ }),
3414
+ // Re-run on EVERY static request, so a revoked grant or pin applies on the next one. Quiet:
3415
+ // a refusal here records no denial and raises no prompt.
3416
+ staticGate: async (cwd, absPath) =>
3417
+ !("code" in (await gateFilePath(cwd, absPath, fileRouteAdmission, { allowGrant: true, quiet: true }))),
3418
+ });
3034
3419
 
3035
3420
  // ONE model runtime for the provider-auth flow listing AND the model proxy,
3036
3421
  // injected so auth/ never imports model-proxy/.
@@ -3077,6 +3462,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3077
3462
  localTrust,
3078
3463
  hostAdmission: () => getHostGateCtx().admission,
3079
3464
  moves: knownServerMoves,
3465
+ ownFingerprint: () => serverIdentity.fingerprint,
3080
3466
  });
3081
3467
  registerLocalProofRoutes(fastify, { codes: localProofCodes, ctx: localTrust });
3082
3468
  registerPairingRoutes(fastify, {
@@ -3091,6 +3477,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3091
3477
  loginAvailable,
3092
3478
  // Public (tunnel + configured public) base URLs, already TLS-gated.
3093
3479
  getReachableUrls: () => pairingManager.reachableUrls(),
3480
+ // Named in a refused bridge-token issue (HTTP → the native HTTPS address).
3481
+ getTlsListenerUrls: () => tlsListener.tlsListenerUrls().map((e) => e.url),
3094
3482
  getPort: () => {
3095
3483
  const addr = fastify.server.address();
3096
3484
  return typeof addr === "object" && addr !== null ? addr.port : config.port;
@@ -3137,7 +3525,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3137
3525
  ip: request.ip,
3138
3526
  headers: request.headers as Record<string, unknown>,
3139
3527
  localTrust,
3140
- verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token),
3528
+ verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token, bearerChannelOf(request.raw)),
3141
3529
  });
3142
3530
  if (!verdict.allow) {
3143
3531
  reply.code(403);
@@ -3147,7 +3535,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3147
3535
  // registers ATTRIBUTABLE sessions (origin gate, #E15).
3148
3536
  return {
3149
3537
  success: true as const,
3150
- data: { ticket: wsTicketStore.mint(scope, verdict.deviceId) },
3538
+ data: {
3539
+ ticket: mintBridgeTicket(wsTicketStore, verdict.deviceId, request.raw),
3540
+ },
3151
3541
  };
3152
3542
  }
3153
3543
  // Non-bridge scope: bind the human principal resolved by the identity
@@ -3178,7 +3568,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3178
3568
  definitions: () => customEventGroupsStore.definitions(),
3179
3569
  });
3180
3570
  // Canvas-type registry read/write (auto-canvas task 5.2).
3181
- registerCanvasTypesRoutes(fastify, { networkGuard });
3571
+ registerCanvasTypesRoutes(fastify, { networkGuard, routeAdmission: fileRouteAdmission });
3182
3572
  // Opt-in worktree auto-init-on-spawn preference (auto-init-worktree-on-spawn).
3183
3573
  registerPreferencesWorktreeInitRoutes(fastify, { preferencesStore, networkGuard });
3184
3574
  // Global auto-session-naming toggle (add-auto-session-naming). Broadcasts
@@ -3188,12 +3578,29 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3188
3578
  networkGuard,
3189
3579
  broadcast: (msg) => browserGateway.broadcast(msg),
3190
3580
  });
3581
+ // Runtime plugin clients: admitted listing, trust grant/revoke, and the content-addressed asset prefix
3582
+ // (outside the network guard's jurisdiction, no auth skip: it behaves exactly like `/assets/*`).
3583
+ // See change: decouple-plugins-from-core (6.10–6.12).
3584
+ registerPluginRuntimeClientRoutes(fastify, {
3585
+ networkGuard,
3586
+ broadcast: (msg) => browserGateway.broadcast(msg),
3587
+ localTrust,
3588
+ // `pluginDiscovery` is built after listen; a trust grant before that point just broadcasts.
3589
+ refreshDiscovery: async () => {
3590
+ if (pluginDiscovery) await pluginDiscovery.refreshPluginDiscovery();
3591
+ else browserGateway.broadcast({ type: "plugins_changed", plugins: getPluginStatusStore().listAll() });
3592
+ },
3593
+ log: { info: (m) => console.log(m) },
3594
+ });
3595
+ registerPluginAssetsRoute(fastify, { getRegistry: getRuntimeClientRegistry });
3191
3596
  // Add-ons hub: feature catalog + combined feature toggle. See change: addons-hub-feature-catalog.
3192
3597
  registerAddonsRoutes(fastify, {
3193
3598
  networkGuard,
3194
3599
  packageManagerWrapper,
3195
3600
  broadcast: (msg) => browserGateway.broadcast(msg),
3196
3601
  knownDirectories: () => directoryService.knownDirectories(),
3602
+ // The shared known set (sessions ∪ pins ∪ workspace folders), like every admitted route.
3603
+ knownCwds: knownFolderCwds,
3197
3604
  lookupNpm: (name) => fetchPackageMeta(name),
3198
3605
  setPluginsEnabled,
3199
3606
  // Fastify here runs with logger:false, so its log would drop every toggle line.
@@ -3266,8 +3673,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3266
3673
  // hooks to routes at `preReady` (verified against fastify@5.12.1 — `addHook`
3267
3674
  // defers through `this.after` and then recurses `_addHook` over `kChildren`),
3268
3675
  // including the encapsulated child scopes plugin routes register into. It does
3269
- // NOT cover a route registered after `ready()`; plugin activation is
3270
- // restart-effective today, so a future hot-load feature would reopen this.
3676
+ // NOT cover a route registered after `ready()` — and none can be: Fastify refuses
3677
+ // it (`route()` → `throwIfAlreadyStarted('Cannot add route!')`, fastify@5.12.1
3678
+ // `lib/route.js:205`), so a plugin hot-load whose entry registers a route fails that
3679
+ // plugin (logged, status row `loaded:false`) and the route is never served. That
3680
+ // refusal IS the enforcement: never serve sensitive-namespace routes from a second
3681
+ // instance / after-start mechanism without this hook, and install the guard on any
3682
+ // future facility that adds routes after start. Pinned by
3683
+ // `__tests__/post-start-route-registration.test.ts`; re-verify after a fastify bump.
3684
+ // See change: harden-git-terminal-plugin-boundaries (S1r).
3271
3685
  fastify.addHook(
3272
3686
  "onRequest",
3273
3687
  createNetworkGuardHook({
@@ -3280,6 +3694,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3280
3694
  getPairingPrefixes: () => PUBLIC_PAIRING_PREFIXES,
3281
3695
  }),
3282
3696
  );
3697
+ // Puts the request's caller in scope for every containment decision made while serving it, so the
3698
+ // dashboard-state guard (token, identity key, config out of reach of path-taking routes) and the
3699
+ // prompt-ineligible rule for an unproven local caller need no per-site plumbing. Callback style on
3700
+ // purpose: `run(store, done)` is what keeps the rest of the lifecycle inside the store.
3701
+ // See change: close-container-loopback-impersonation (D8).
3702
+ fastify.addHook("onRequest", (request, _reply, done) => {
3703
+ runWithStateCaller(stateCallerFor(request, localTrust), done);
3704
+ });
3283
3705
  // Boot-time inert-entry warning (loopback entry in trustedNetworks /
3284
3706
  // bypassHosts). Memoized; the guard re-notes on each reparse.
3285
3707
  // See change: fix-trusted-network-tunnel-bypass (D3).
@@ -3322,6 +3744,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3322
3744
  // some HTTP/2 proxy chains (notably zrok free-tier) occasionally
3323
3745
  // stream-reset as ERR_ABORTED 500 in browsers.
3324
3746
  preCompressed: true,
3747
+ // `index.html` (and its `.gz`) is never served by the static handler: every HTML response
3748
+ // passes `sendIndexWithImportMap`, which inserts the host import map. A direct `/index.html.gz`
3749
+ // falls to the not-found handler (the SPA shell, map included). See change: decouple-plugins-from-core (6.4).
3750
+ index: false,
3751
+ allowedPath: (pathName) => pathName !== "/index.html" && pathName !== "/index.html.gz",
3325
3752
  // @fastify/static v10 hands `setHeaders` a FastifyReply (v8 passed the
3326
3753
  // raw ServerResponse), so the header goes through `.header()`.
3327
3754
  setHeaders: (reply, filePath) => {
@@ -3344,6 +3771,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3344
3771
  return reply.code(404).send({ success: false, error: "not_found", message: `No API route for ${request.method} ${rawPath}` });
3345
3772
  };
3346
3773
 
3774
+ const indexSender = createIndexHtmlSender(clientDir, { trustedTypesMode });
3775
+ // Every HTML shell response carries a per-response nonce on its import map; `registerCsp`'s onSend hook
3776
+ // reads the same memoized nonce for the strict policy header. Off mode emits no strict policy → no nonce.
3777
+ // See change: harden-cors-and-csp-reporting (D9).
3778
+ const indexHtml = {
3779
+ sendIndexWithImportMap: (reply: FastifyReply) =>
3780
+ indexSender.sendIndexWithImportMap(reply, cspMode === "off" ? undefined : { nonce: cspNonceFor(reply) }),
3781
+ };
3782
+
3347
3783
  if (config.dev) {
3348
3784
  // Dev mode: proxy to Vite dev server, fall back to production build
3349
3785
  const VITE_PORTS = [3000, 5173, 5174];
@@ -3361,38 +3797,51 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3361
3797
 
3362
3798
  vitePort = await detectVitePort();
3363
3799
 
3364
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
3800
+ /** Proxy `request.url` to Vite; the reply when Vite answered, `undefined` when it is down (re-probed next time). */
3801
+ const proxyToVite = async (request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply | undefined> => {
3802
+ if (!vitePort) vitePort = await detectVitePort();
3803
+ if (!vitePort) return undefined;
3804
+ try {
3805
+ const viteUrl = `http://localhost:${vitePort}${request.url}`;
3806
+ const res = await fetch(viteUrl);
3807
+ const contentType = res.headers.get("content-type");
3808
+ if (contentType) reply.header("Content-Type", contentType);
3809
+ reply.code(res.status);
3810
+ markViteProxied(reply); // dev response: baseline CSP only, no strict/nonce/report destination (D10)
3811
+ return reply.send(Buffer.from(await res.arrayBuffer()));
3812
+ } catch {
3813
+ vitePort = 0; // Vite stopped — re-probe next time
3814
+ return undefined;
3815
+ }
3816
+ };
3817
+
3818
+ // `/` and `/index.html` keep today's order: Vite first (its HTML carries no injected map), then the
3819
+ // production HTML with the map (D21, R21).
3820
+ if (hasProductionBuild) {
3821
+ const devHtml = async (request: FastifyRequest, reply: FastifyReply) =>
3822
+ (await proxyToVite(request, reply)) ?? indexHtml.sendIndexWithImportMap(reply);
3823
+ fastify.get("/", devHtml);
3824
+ fastify.get("/index.html", devHtml);
3825
+ }
3826
+
3365
3827
  fastify.setNotFoundHandler(async (request, reply) => {
3366
3828
  const apiMiss = replyIfApiNotFound(request, reply);
3367
3829
  if (apiMiss) return apiMiss;
3368
3830
  // Try Vite proxy first
3369
- if (!vitePort) vitePort = await detectVitePort();
3370
- if (vitePort) {
3371
- try {
3372
- const viteUrl = `http://localhost:${vitePort}${request.url}`;
3373
- const res = await fetch(viteUrl);
3374
- const contentType = res.headers.get("content-type");
3375
- if (contentType) reply.header("Content-Type", contentType);
3376
- reply.code(res.status);
3377
- return reply.send(Buffer.from(await res.arrayBuffer()));
3378
- } catch {
3379
- vitePort = 0; // Vite stopped — re-probe next time
3380
- }
3381
- }
3831
+ const proxied = await proxyToVite(request, reply);
3832
+ if (proxied) return proxied;
3382
3833
  // Fallback: serve production build if available
3383
- if (hasProductionBuild) {
3384
- reply.header("Cache-Control", "no-cache, no-store, must-revalidate");
3385
- return reply.sendFile("index.html");
3386
- }
3834
+ if (hasProductionBuild) return indexHtml.sendIndexWithImportMap(reply);
3387
3835
  return reply.code(404).send({ error: "API-only mode: no client build available. Install @blackbelt-technology/pi-dashboard-web or run npm run build." });
3388
3836
  });
3389
3837
  } else if (hasProductionBuild) {
3390
- // Production mode: SPA fallback
3838
+ // Production mode: SPA fallback (and the explicit `/`, `/index.html`) through the import-map sender.
3839
+ fastify.get("/", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
3840
+ fastify.get("/index.html", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
3391
3841
  fastify.setNotFoundHandler(async (request, reply) => {
3392
3842
  const apiMiss = replyIfApiNotFound(request, reply);
3393
3843
  if (apiMiss) return apiMiss;
3394
- reply.header("Cache-Control", "no-cache, no-store, must-revalidate");
3395
- return reply.sendFile("index.html");
3844
+ return indexHtml.sendIndexWithImportMap(reply);
3396
3845
  });
3397
3846
  } else {
3398
3847
  fastify.setNotFoundHandler(async (request, reply) => {
@@ -3602,7 +4051,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3602
4051
  return resolvePluginEnabled(pluginCfg, manifest?.defaultEnabled);
3603
4052
  });
3604
4053
  try {
3605
- await loadServerEntries({
4054
+ // Runtime-client registry: derives `PluginStatus.client` at every status read (live content hash,
4055
+ // trust, config) and serves the admitted-plugin listing. See change: decouple-plugins-from-core (6.7).
4056
+ const runtimeClients = installRuntimeClientRegistry();
4057
+ const pluginLoadDeps: ServerLoadDeps = {
4058
+ // pi-package server entries stay refused until the operator grants server trust (D12, R9).
4059
+ isServerTrusted,
3606
4060
  isEnabled: (pluginId) => {
3607
4061
  const cfg = loadConfig();
3608
4062
  const pluginCfg = getPluginConfigFromFile(cfg, pluginId) as Record<string, unknown>;
@@ -3622,7 +4076,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
3622
4076
  getPluginConfigFromFile(loadConfig(), id) as Record<string, unknown>,
3623
4077
  // Bracket this plugin's activation for route-owner attribution (D24): the
3624
4078
  // next plugin's createContext re-begins; the finally below ends.
3625
- createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), createServerPluginContext(
4079
+ createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), pluginManifestEmits.set(plugin.manifest.id, plugin.manifest.emits ?? []), createServerPluginContext(
3626
4080
  {
3627
4081
  fastify,
3628
4082
  isPiExtensionInstalled,
@@ -4011,22 +4465,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4011
4465
  // this is NOT trust-gated. See change:
4012
4466
  // relocate-goal-product-to-plugin (D1-#7).
4013
4467
  networkGuard,
4014
- // `ctx.serveApp`: trust-gated (bundled plugin dir OR `auth.capabilityRoutePlugins`),
4468
+ // `ctx.serveApp`: trust-gated (bundled plugin dir, `auth.trustedPlugins` OR legacy `auth.capabilityRoutePlugins`),
4015
4469
  // mounts `/apps/<appId>/`. See change: add-plugin-capability-routes (D2, D5).
4016
4470
  serveApp: createHostServeApp({
4017
4471
  fastify,
4018
- plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id },
4472
+ plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id, source: plugin.source },
4019
4473
  readConfiguredIds: () => loadConfig().auth?.capabilityRoutePlugins ?? [],
4020
4474
  }),
4021
4475
  // Emit a configured pi event into a session (relayed as a
4022
4476
  // `plugin_emit_event` control message; the in-session bridge
4023
4477
  // re-emits it on pi.events). Same trust gate as abortSession.
4024
4478
  // See change: automation-emit-configured-event.
4479
+ // Only event types in the plugin's manifest `emits` (live; automation also
4480
+ // gets its accepted action providers' emits) pass.
4481
+ // See change: harden-git-terminal-plugin-boundaries (D16).
4025
4482
  emitEventToSession: (sessionId, eventType, data) =>
4026
4483
  pluginEventSeam.emitEventToSession(
4027
4484
  (plugin.manifest.priority ?? 1000) <= 100,
4028
4485
  (sid, m) => piGateway.sendToSession(sid, m),
4029
4486
  sessionId, eventType, data,
4487
+ {
4488
+ pluginId: plugin.manifest.id,
4489
+ allowed: () =>
4490
+ pluginEventSeam.computeEmitAllowlist(plugin.manifest.id, {
4491
+ manifestEmits: loadedManifestEmits,
4492
+ actionEntries: () => pluginServiceRegistry.entries("automation.action."),
4493
+ }),
4494
+ },
4030
4495
  ),
4031
4496
  // Raw server→extension control message to one session's bridge
4032
4497
  // socket — the `credentials_updated` lane, WITHOUT the
@@ -4040,18 +4505,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4040
4505
  (sid, m) => piGateway.sendToSession(sid, m as Parameters<typeof piGateway.sendToSession>[1]),
4041
4506
  sessionId, msg,
4042
4507
  ),
4043
- provide: (name, value) => { pluginServiceRegistry.set(name, value); },
4508
+ // Attributed to this plugin; `automation.action.<source>` keys are
4509
+ // refused unless `<source>` is this plugin's id (logged, no throw).
4510
+ provide: (name, value) => { pluginServiceRegistry.provide(plugin.manifest.id, name, value); },
4044
4511
  consume: <T = unknown>(name: string) =>
4045
- pluginServiceRegistry.get(name) as T | undefined,
4512
+ pluginServiceRegistry.get<T>(name),
4046
4513
  // Prefix enumeration for publish/collect (in-process only).
4047
4514
  // See change: decouple-automation-action-registry.
4048
- consumeAll: <T = unknown>(prefix: string) => {
4049
- const out: Array<{ key: string; value: T }> = [];
4050
- for (const [key, value] of pluginServiceRegistry) {
4051
- if (key.startsWith(prefix)) out.push({ key, value: value as T });
4052
- }
4053
- return out;
4054
- },
4515
+ consumeAll: <T = unknown>(prefix: string) => pluginServiceRegistry.entries<T>(prefix),
4055
4516
  // plugin_action fans out by pluginId (manifest-authoritative, not
4056
4517
  // self-declared) so multiple plugins coexist; other custom types
4057
4518
  // stay single-owner. See change: fix-plugin-action-fanout-and-handlers.
@@ -4218,7 +4679,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4218
4679
  editClaimIds: plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-file-handler" && c.mode === "edit" && c.id ? [c.id] : [])),
4219
4680
  },
4220
4681
  )),
4682
+ };
4683
+ pluginDiscovery = createPluginDiscoveryWiring({
4684
+ loadDeps: pluginLoadDeps,
4685
+ readDeclaredBundledIds: () => readServedBundledPluginIds(clientDirResolved),
4686
+ clearContentHashCache: () => runtimeClients.clearContentHashCache(),
4687
+ logAdmissions: () => logRuntimeAdmissions({ info: (m) => console.log(m) }, "refresh"),
4688
+ listActiveCwds: () => sessionManager.listActive().map((s) => s.cwd),
4689
+ broadcastPluginsChanged: (plugins) => browserGateway.broadcast({ type: "plugins_changed", plugins }),
4221
4690
  });
4691
+ await loadServerEntries(pluginLoadDeps);
4222
4692
  } catch (err) {
4223
4693
  console.error('[plugin-loader] Unexpected error during pre-listen load:', err);
4224
4694
  } finally {
@@ -4296,7 +4766,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4296
4766
  registration.admitOrigins,
4297
4767
  corsOpts(),
4298
4768
  ) ||
4299
- !isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust)
4769
+ !isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust, {
4770
+ pluginAuthenticatesPeer: registration.peerCredential === "plugin",
4771
+ })
4300
4772
  ) {
4301
4773
  console.error(
4302
4774
  `[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope} peer=${sanitizeHeaderForLog(remoteAddress)}`,
@@ -4338,7 +4810,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4338
4810
  // routed path from an unrouted one. A browser cannot omit or forge
4339
4811
  // `Origin` on a handshake; every non-browser client sends none and is
4340
4812
  // unaffected. See change: fix-ws-origin-cswsh (D1).
4341
- if (!isWsOriginTrusted(request.headers.origin, request.headers.host, scope, corsOpts())) {
4813
+ // A live-scope upgrade may be admitted by a validated capability path
4814
+ // (token read from the path segment only — never query/subprotocol).
4815
+ // Any other scope ignores it entirely. The opaque `Origin: null` is admitted
4816
+ // only WITH a valid capability. See change: retire-trusted-networks-bypass (D5),
4817
+ // improve-canvas-html-and-url-ux (D10).
4818
+ const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
4819
+ const liveCapPrincipal = liveCap
4820
+ ? liveCapabilities.validate(liveCap.targetId, liveCap.token, {
4821
+ genuinelyLocal: isLocallyTrusted({ ip: remoteAddress, headers: request.headers as Record<string, unknown> }),
4822
+ })
4823
+ : null;
4824
+ if (!isWsOriginTrusted(request.headers.origin, request.headers.host, scope, corsOpts(), liveCapPrincipal !== null)) {
4342
4825
  console.error(
4343
4826
  `[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope ?? "none"} peer=${sanitizeHeaderForLog(remoteAddress)}`,
4344
4827
  );
@@ -4352,16 +4835,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4352
4835
  // the dashboard port would silently burn its ticket and see a bare TCP
4353
4836
  // close (@review Audit, minor).
4354
4837
  if (scope === "bridge") {
4355
- wsUpgradeRejectLog.log({
4356
- status: 400,
4357
- scope,
4358
- remoteAddress,
4359
- headers: request.headers as unknown as Record<string, unknown>,
4360
- // Presence only — read from the URL/protocol header, never consumed.
4361
- ticketPresent: extractTicket(request.url, secWsProtocol) !== null,
4362
- });
4363
- socket.write("HTTP/1.1 400 Bad Request\r\n\r\n");
4364
- socket.destroy();
4838
+ // The native TLS listener may admit a paired device's bridge (opt-in `tls.acceptBridges`); every
4839
+ // other case keeps the 400 without consuming the ticket. See change: prove-vault-bridge-tls (D2).
4840
+ routeBridgeUpgrade(
4841
+ {
4842
+ acceptBridges: tlsBridgesLive,
4843
+ gateway: piGateway,
4844
+ rejectLog: ({ status, reason }) =>
4845
+ wsUpgradeRejectLog.log({
4846
+ status,
4847
+ scope,
4848
+ remoteAddress,
4849
+ headers: request.headers as unknown as Record<string, unknown>,
4850
+ // Presence only — read from the URL/protocol header, never consumed.
4851
+ ticketPresent: extractTicket(request.url, secWsProtocol) !== null,
4852
+ ...(reason ? { reason } : {}),
4853
+ }),
4854
+ },
4855
+ request,
4856
+ socket,
4857
+ head,
4858
+ );
4365
4859
  return;
4366
4860
  }
4367
4861
  const ticket = extractTicket(request.url, secWsProtocol);
@@ -4375,11 +4869,6 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4375
4869
  // principal-bearing ticket — they were the legacy loopback / local-token /
4376
4870
  // trusted-network / principal-less-ticket allowances that bypassed it.
4377
4871
  const requireIdentityTicket = (scope === "browser" || scope === "terminal" || scope === "live") && identityEnforced();
4378
- // A live-scope upgrade may be admitted by a validated capability path
4379
- // (token read from the path segment only — never query/subprotocol).
4380
- // Any other scope ignores it entirely. See change: retire-trusted-networks-bypass (D5).
4381
- const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
4382
- const liveCapPrincipal = liveCap ? liveCapabilities.validate(liveCap.targetId, liveCap.token) : null;
4383
4872
  const upgradeAuth = authorizeWsUpgrade({
4384
4873
  cookieHeader: request.headers.cookie,
4385
4874
  remoteAddress,
@@ -4417,7 +4906,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4417
4906
  // 401 when an auth secret is configured (cookie realm), else 403 for
4418
4907
  // the no-auth allowances — preserving the prior status semantics.
4419
4908
  const status = config.authConfig?.secret ? "401 Unauthorized" : "403 Forbidden";
4420
- wsUpgradeRejectLog.log({ status: config.authConfig?.secret ? 401 : 403, scope: scope ?? "none", remoteAddress, headers: wsHeaders, ticketPresent: ticket !== null });
4909
+ wsUpgradeRejectLog.log({
4910
+ status: config.authConfig?.secret ? 401 : 403,
4911
+ scope: scope ?? "none",
4912
+ remoteAddress,
4913
+ headers: wsHeaders,
4914
+ ticketPresent: ticket !== null,
4915
+ // A bare-loopback dial refused only for want of proof: say so (fixed token, no caller input).
4916
+ ...(needsLocalProof({ ip: remoteAddress ?? "", headers: wsHeaders }, localTrust) ? { reason: "local_proof_required" } : {}),
4917
+ });
4421
4918
  socket.write(`HTTP/1.1 ${status}\r\n\r\n`);
4422
4919
  socket.destroy();
4423
4920
  return;
@@ -4479,6 +4976,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4479
4976
  : Object.freeze({ ...upgradeAuth.principal });
4480
4977
  bound.principalExpiresAt = upgradeAuth.principalExpiresAt;
4481
4978
  }
4979
+ // Locality is decided ONCE here, from the upgrade request; handlers read the bit.
4980
+ // See change: harden-server-capability-bounds (D1b).
4981
+ stampSocketLocality(ws, request, localTrust);
4482
4982
  if (grants) (ws as { bootstrapGrants?: BootstrapGrants }).bootstrapGrants = grants;
4483
4983
  if (sessionTierOf) (ws as TieredSocket).sessionTier = sessionTierOf;
4484
4984
  browserGateway.wss.emit("connection", ws, request);
@@ -4527,7 +5027,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4527
5027
  const cancelExpiry = scheduleAtExpiry(upgradeAuth.principalExpiresAt, () => socket.destroy());
4528
5028
  socket.once("close", cancelExpiry);
4529
5029
  handleLiveServerUpgrade(liveServerManager, request, socket, head, {
4530
- isDeviceBearer: (token) => pairedDeviceRegistry.verify(token) !== null,
5030
+ isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
5031
+ isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
4531
5032
  capabilityPrefix: liveCapPrincipal && liveCap ? liveCap.prefix : undefined,
4532
5033
  });
4533
5034
  });
@@ -4567,6 +5068,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4567
5068
 
4568
5069
  // The proof floor is taken after readiness, immediately before the bind.
4569
5070
  await listenWithProofFloor(fastify, (at) => (httpBoundAt = at), { port: config.port, host: config.host });
5071
+ const bound = fastify.server.address();
5072
+ if (bound && typeof bound === "object") httpListenPort = bound.port;
4570
5073
  writePid(process.pid);
4571
5074
  console.log(`Dashboard server running at http://${config.host}:${config.port}`);
4572
5075
  // Optional TLS listener: only after Fastify is ready and the main listen resolved.
@@ -4677,7 +5180,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4677
5180
  if (mdnsDisabled) {
4678
5181
  // skip peer discovery entirely
4679
5182
  } else {
4680
- mdnsBrowser = createBrowser();
5183
+ mdnsBrowser = createBrowser({ ownFingerprint: () => serverIdentity.fingerprint });
4681
5184
  wirePeerServers({
4682
5185
  browser: mdnsBrowser,
4683
5186
  peers: peerServers,
@@ -4778,6 +5281,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4778
5281
  // or they would land in every pi session's tool list.
4779
5282
  // See change: expose-plugin-credential-and-oauth-seams (D8).
4780
5283
  .filter(p => fixtureEntryAllowed(p.manifest))
5284
+ // A pi-package bridge is not auto-registered until the operator grants server trust
5285
+ // (D12, R9). See change: decouple-plugins-from-core (task 5.2).
5286
+ .filter(p => pluginServerAllowed(p, isServerTrusted))
4781
5287
  // A disabled plugin's bridge is deregistered (both registries) and an
4782
5288
  // enabled one registered — same predicate as the server-entry loader.
4783
5289
  // The toggle route answers `restartRequired`, so this boot pass is
@@ -4951,6 +5457,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
4951
5457
  // See change: add-access-grant-dialog.
4952
5458
  installGrantCoordinator(null);
4953
5459
  setNetworkDenialObserver(null);
5460
+ setLocalProofRefusalObserver(null);
4954
5461
  // Stop the event-loop-delay monitor so the libuv timer doesn't linger
4955
5462
  // after teardown. See change: instrument-session-hydration-timing.
4956
5463
  try { eventLoopDelayHistogram.disable(); } catch { /* ignore */ }
@@ -5009,6 +5516,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
5009
5516
  }
5010
5517
  pendingForkRegistry.dispose();
5011
5518
  pairingManager.dispose();
5519
+ stopDeviceExpirySweep();
5012
5520
  vaultDelivery.dispose();
5013
5521
  // Every pending ack holds a timer; a create/stop cycle must not leak them.
5014
5522
  // See change: fix-spawn-correlation-ttl-coupling (D7).
@@ -5033,6 +5541,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
5033
5541
  }
5034
5542
  homeRendezvous = null;
5035
5543
  piGateway.stop();
5544
+ // Await the socket teardown stop() hands off, so stop() never resolves
5545
+ // while it can still touch HOME (and log after a test tore HOME down).
5546
+ await piGateway.stopped();
5036
5547
  // Clears pending on-end archive timers + latches the sweeper; after the
5037
5548
  // gateway so sessions it ends cannot re-arm one.
5038
5549
  // See change: archive-service-sessions-on-end.