@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -2
- package/README.md +64 -18
- package/docs/architecture.md +2325 -270
- package/package.json +36 -20
- package/packages/extension/package.json +18 -9
- package/packages/extension/src/bridge-context.ts +6 -0
- package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
- package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
- package/packages/extension/src/bridge-handlers/instance.ts +31 -13
- package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
- package/packages/extension/src/bridge-shutdown.ts +44 -0
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +309 -284
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +106 -37
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +153 -38
- package/packages/extension/src/credential-guard.ts +300 -0
- package/packages/extension/src/custom-entry-forward.ts +27 -18
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/default-model-apply.ts +83 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/flow-event-wiring.ts +19 -95
- package/packages/extension/src/followup-drain.ts +19 -5
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +77 -6
- package/packages/extension/src/model-refresh.ts +69 -0
- package/packages/extension/src/path-gate/decide.ts +68 -5
- package/packages/extension/src/path-gate/handler.ts +16 -8
- package/packages/extension/src/path-gate/index.ts +2 -2
- package/packages/extension/src/path-gate/roots.ts +15 -3
- package/packages/extension/src/path-gate/suppression.ts +3 -0
- package/packages/extension/src/pi-env.d.ts +8 -1
- package/packages/extension/src/pi-retry-settings.ts +11 -2
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
- package/packages/extension/src/preview-path-link.ts +151 -0
- package/packages/extension/src/project-init/scaffold.ts +98 -35
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +178 -30
- package/packages/extension/src/provider-model-cache.ts +118 -0
- package/packages/extension/src/provider-register.ts +487 -46
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/retry-tracker.ts +90 -7
- package/packages/extension/src/role-manager.ts +4 -2
- package/packages/extension/src/role-model-tools.ts +68 -10
- package/packages/extension/src/server-auto-start.ts +69 -3
- package/packages/extension/src/server-launcher.ts +26 -8
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-sync.ts +53 -24
- package/packages/extension/src/spawn-new-session.ts +22 -0
- package/packages/extension/src/steer-buffer.ts +164 -0
- package/packages/extension/src/stream-forward-buffer.ts +64 -15
- package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
- package/packages/extension/src/sudo-askpass/controller.ts +405 -0
- package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
- package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
- package/packages/extension/src/sudo-askpass/index.ts +11 -0
- package/packages/extension/src/sudo-askpass/install.ts +143 -0
- package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
- package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
- package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
- package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
- package/packages/extension/src/terminal-reload.ts +19 -5
- package/packages/extension/src/tool-update-filter-registry.ts +210 -0
- package/packages/extension/src/vault-delivery.ts +11 -1
- package/packages/extension/src/vault-redaction.ts +4 -3
- package/packages/server/package.json +17 -14
- package/packages/server/src/access/access-denials.ts +8 -0
- package/packages/server/src/access/access-grants.ts +303 -64
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +12 -1
- package/packages/server/src/access/containment-gate.ts +113 -30
- package/packages/server/src/access/cwd-verdict.ts +3 -3
- package/packages/server/src/access/denial-hold.ts +3 -0
- package/packages/server/src/access/grant-coordinator.ts +17 -1
- package/packages/server/src/access/named-grant.ts +3 -0
- package/packages/server/src/access/pending-grant-registry.ts +32 -5
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
- package/packages/server/src/access/planes.ts +107 -1
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/verified-read.ts +24 -7
- package/packages/server/src/access/yolo-session.ts +54 -2
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
- package/packages/server/src/acp-bridge/server-requests.ts +10 -4
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/auth/audit-log.ts +108 -0
- package/packages/server/src/auth/auth-plugin.ts +230 -38
- package/packages/server/src/auth/auth.ts +104 -4
- package/packages/server/src/auth/bearer-auth.ts +52 -12
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
- package/packages/server/src/auth/cors-origin.ts +90 -30
- package/packages/server/src/auth/credential-envelope.ts +233 -0
- package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
- package/packages/server/src/auth/credential-key-worker.mjs +108 -0
- package/packages/server/src/auth/credential-key.ts +479 -0
- package/packages/server/src/auth/credential-migration.ts +162 -0
- package/packages/server/src/auth/csp-report-paths.ts +26 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +145 -11
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/device-proof.ts +202 -0
- package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
- package/packages/server/src/auth/host-admission.ts +7 -0
- package/packages/server/src/auth/host-gate.ts +13 -2
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +69 -18
- package/packages/server/src/auth/localhost-guard.ts +98 -33
- package/packages/server/src/auth/locked-json-file.ts +68 -6
- package/packages/server/src/auth/models-json-store.ts +269 -0
- package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/node-guard.ts +36 -49
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
- package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
- package/packages/server/src/auth/plugin-credential-store.ts +81 -10
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-storage.ts +214 -12
- package/packages/server/src/auth/provider-block-checks.ts +321 -0
- package/packages/server/src/auth/provider-host-detect.ts +151 -0
- package/packages/server/src/auth/provider-key-file.ts +71 -0
- package/packages/server/src/auth/provider-readiness.ts +91 -0
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/route-tier-gate.ts +3 -2
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +111 -11
- package/packages/server/src/auth/vertex-key-check.ts +140 -0
- package/packages/server/src/auth/ws-ticket.ts +40 -2
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/browse.ts +73 -20
- package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
- package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
- package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/build-plugin-send-prompt.ts +18 -0
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli/credentials-command.ts +555 -0
- package/packages/server/src/cli.ts +229 -53
- package/packages/server/src/config-api.ts +53 -35
- package/packages/server/src/config-snapshot.ts +197 -1
- package/packages/server/src/directory-service.ts +193 -68
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
- package/packages/server/src/event-wiring.ts +322 -207
- package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
- package/packages/server/src/git-worktree/git-operations.ts +45 -11
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/repo-lock.ts +42 -0
- package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
- package/packages/server/src/git-worktree/worktree-init.ts +5 -1
- package/packages/server/src/identity/http-road-classification.ts +18 -2
- package/packages/server/src/identity/identity-floor.ts +5 -2
- package/packages/server/src/identity/ws-message-scope.ts +11 -3
- package/packages/server/src/identity/ws-road-classification.ts +3 -1
- package/packages/server/src/known-server-moves.ts +36 -15
- package/packages/server/src/lib/browse-roots.ts +129 -17
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/content-disposition.ts +20 -0
- package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/eml.ts +5 -10
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/frame-policy-probe.ts +308 -0
- package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
- package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +96 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
- package/packages/server/src/lib/office-preview.ts +49 -13
- package/packages/server/src/lib/path-containment.ts +50 -10
- package/packages/server/src/lib/resolve-file-mention.ts +234 -40
- package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-handler-target.ts +4 -0
- package/packages/server/src/lib/writable-md-target.ts +26 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
- package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
- package/packages/server/src/lifecycle/exit-signal.ts +43 -0
- package/packages/server/src/lifecycle/recovery-server.ts +65 -18
- package/packages/server/src/live-server/capability-redact.ts +31 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +615 -44
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +141 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +25 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +220 -33
- package/packages/server/src/live-server/live-server-proxy.ts +411 -50
- package/packages/server/src/live-server/live-static.ts +231 -0
- package/packages/server/src/live-server/preview-dispatch.ts +286 -0
- package/packages/server/src/live-server/preview-observe.ts +53 -0
- package/packages/server/src/live-server/preview-origin.ts +182 -0
- package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
- package/packages/server/src/live-server/preview-path-store.ts +420 -0
- package/packages/server/src/live-server/preview-path.ts +40 -0
- package/packages/server/src/live-server/preview-pool.ts +385 -0
- package/packages/server/src/live-server/preview-preflight.ts +41 -0
- package/packages/server/src/live-server/preview-reserve.ts +44 -0
- package/packages/server/src/live-server/preview-tier.ts +217 -0
- package/packages/server/src/live-server/preview-viewers.ts +54 -0
- package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
- package/packages/server/src/model-proxy/internal-registry.ts +283 -21
- package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
- package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
- package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
- package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
- package/packages/server/src/openspec/readiness.ts +1 -1
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +141 -267
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/provider-probe.ts +202 -7
- package/packages/server/src/pairing/browser-gateway.ts +325 -51
- package/packages/server/src/pairing/device-key-intake.ts +120 -0
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/paired-devices.ts +702 -27
- package/packages/server/src/pairing/pairing.ts +103 -11
- package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
- package/packages/server/src/pending/pending-attach-registry.ts +15 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
- package/packages/server/src/persistence/memory-event-store.ts +251 -296
- package/packages/server/src/persistence/preferences-store.ts +61 -2
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-contention.ts +84 -2
- package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/host-project-trust.ts +29 -15
- package/packages/server/src/pi/pi-gateway.ts +398 -41
- package/packages/server/src/pi/provisional-registration.ts +4 -1
- package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
- package/packages/server/src/pi-agent-settings.ts +95 -301
- package/packages/server/src/pi-default-remirror.ts +89 -0
- package/packages/server/src/plugin-append-event.ts +35 -0
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-entry-stats.ts +61 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-local-request.ts +207 -0
- package/packages/server/src/plugin-ownership.ts +111 -0
- package/packages/server/src/plugin-policy-registry.ts +297 -0
- package/packages/server/src/plugin-request-lane.ts +92 -16
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/preferences-relay.ts +20 -0
- package/packages/server/src/project-seed.ts +347 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
- package/packages/server/src/questions/question-store.ts +3 -2
- package/packages/server/src/routes/access-routes.ts +182 -15
- package/packages/server/src/routes/acme-routes.ts +14 -4
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +640 -279
- package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
- package/packages/server/src/routes/folder-project-routes.ts +18 -12
- package/packages/server/src/routes/frame-policy-routes.ts +215 -0
- package/packages/server/src/routes/git-routes.ts +340 -273
- package/packages/server/src/routes/grep-routes.ts +64 -14
- package/packages/server/src/routes/known-servers-routes.ts +189 -91
- package/packages/server/src/routes/live-server-routes.ts +572 -15
- package/packages/server/src/routes/local-proof-routes.ts +14 -0
- package/packages/server/src/routes/models-introspection-routes.ts +1 -1
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +396 -31
- package/packages/server/src/routes/package-routes.ts +58 -10
- package/packages/server/src/routes/pairing-routes.ts +342 -17
- package/packages/server/src/routes/pi-settings-routes.ts +2 -0
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
- package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
- package/packages/server/src/routes/provider-auth-routes.ts +181 -10
- package/packages/server/src/routes/provider-override-routes.ts +158 -0
- package/packages/server/src/routes/provider-routes.ts +348 -86
- package/packages/server/src/routes/resource-activation-routes.ts +18 -4
- package/packages/server/src/routes/session-routes.ts +75 -25
- package/packages/server/src/routes/system-routes.ts +169 -52
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
- package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
- package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
- package/packages/server/src/server.ts +1139 -291
- package/packages/server/src/services/cli-service.ts +59 -10
- package/packages/server/src/services/secrets-resolver.ts +46 -30
- package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
- package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
- package/packages/server/src/session/death-reason.ts +11 -7
- package/packages/server/src/session/event-status-extraction.ts +5 -1
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/memory-session-manager.ts +31 -2
- package/packages/server/src/session/open-tool-calls.ts +81 -47
- package/packages/server/src/session/pid-target.ts +127 -0
- package/packages/server/src/session/replay-compaction.ts +18 -5
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/seed-discovered-history.ts +85 -0
- package/packages/server/src/session/server-pid-context.ts +14 -0
- package/packages/server/src/session/session-api.ts +78 -29
- package/packages/server/src/session/session-archive.ts +7 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -54
- package/packages/server/src/session/session-load-worker-pool.ts +11 -1
- package/packages/server/src/session/session-load-worker.ts +32 -4
- package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
- package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
- package/packages/server/src/spawn-process/link-register.ts +42 -0
- package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
- package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
- package/packages/server/src/spawn-process/process-classifier.ts +8 -3
- package/packages/server/src/spawn-process/process-manager.ts +61 -6
- package/packages/server/src/spawn-process/restored-identity.ts +112 -0
- package/packages/server/src/spawn-process/session-terminator.ts +179 -18
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
- package/packages/server/src/sudo-credential/relay.ts +337 -0
- package/packages/server/src/terminal/terminal-gateway.ts +10 -0
- package/packages/server/src/terminal/terminal-manager.ts +54 -46
- package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
- package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +2 -0
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
- package/packages/server/src/vault/vault-routes.ts +9 -2
- package/packages/server/src/vault/vault-store.ts +87 -24
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/server/vendor/xlsx/LICENSE +201 -0
- package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
- package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
- package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
- package/packages/shared/package.json +4 -2
- package/packages/shared/src/agent-credential-files.ts +32 -0
- package/packages/shared/src/browser-protocol.ts +285 -59
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/canvas-detect.ts +1 -1
- package/packages/shared/src/canvas-types.ts +2 -2
- package/packages/shared/src/config.ts +443 -187
- package/packages/shared/src/containment-guard.ts +45 -0
- package/packages/shared/src/credential-encryption.ts +87 -0
- package/packages/shared/src/custom-event-groups.ts +2 -0
- package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +2 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
- package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
- package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
- package/packages/shared/src/device-key-proof.ts +309 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +94 -27
- package/packages/shared/src/event-forward-declaration.ts +85 -12
- package/packages/shared/src/forbidden-subjects.ts +126 -14
- package/packages/shared/src/heap-limits.ts +0 -30
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/index.ts +7 -6
- package/packages/shared/src/live-server.ts +161 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
- package/packages/shared/src/mdns-discovery.ts +25 -6
- package/packages/shared/src/models-json-reader.ts +41 -0
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/network-denial-signal.ts +15 -0
- package/packages/shared/src/node-version.ts +63 -60
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-poller.ts +3 -2
- package/packages/shared/src/pairing-knock-client.ts +135 -11
- package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
- package/packages/shared/src/pi-path-compare.ts +31 -0
- package/packages/shared/src/pi-settings-schema.ts +52 -9
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
- package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
- package/packages/shared/src/pi-trust-mirror.ts +47 -11
- package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
- package/packages/shared/src/pid-namespace.ts +86 -0
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +14 -8
- package/packages/shared/src/platform/native-ts-register.mjs +1 -1
- package/packages/shared/src/platform/process.ts +452 -5
- package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/platform/spawn-runtime.ts +193 -7
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +192 -0
- package/packages/shared/src/preview-origins.ts +398 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/prompt-answer.ts +9 -5
- package/packages/shared/src/protocol.ts +187 -86
- package/packages/shared/src/provider-env-catalog.ts +413 -0
- package/packages/shared/src/provider-overrides.ts +112 -0
- package/packages/shared/src/question-types.ts +6 -0
- package/packages/shared/src/recommended-extensions.ts +97 -26
- package/packages/shared/src/recovery-timing.ts +27 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/renderer-by-ext.ts +5 -2
- package/packages/shared/src/rest-api.ts +148 -11
- package/packages/shared/src/role-schema.ts +24 -0
- package/packages/shared/src/route-tiers.ts +149 -4
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/compat.ts +70 -6
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/secret-patterns.ts +49 -0
- package/packages/shared/src/server-launcher.ts +9 -1
- package/packages/shared/src/server-pinning.ts +55 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/source-matching.ts +2 -2
- package/packages/shared/src/state-replay.ts +40 -24
- package/packages/shared/src/sudo-credential.ts +71 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tool-path-resolve.ts +16 -1
- package/packages/shared/src/tool-registry/definitions.ts +5 -5
- package/packages/shared/src/tool-registry/strategies.ts +13 -12
- package/packages/shared/src/tool-workdir.ts +56 -0
- package/packages/shared/src/trusted-types-mode.ts +72 -0
- package/packages/shared/src/types.ts +134 -109
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +15 -0
- package/packages/shared/src/vertex-regions.ts +81 -0
- package/packages/shared/src/ws-message-tiers.ts +11 -3
- package/packages/extension/src/subagent-fanout-admission.ts +0 -234
- package/packages/extension/src/subagent-forward-sites.ts +0 -69
- package/packages/extension/src/subagent-frame-buffer.ts +0 -245
- package/packages/extension/src/subagent-frame-strip.ts +0 -109
- package/packages/extension/src/subagent-saturation.ts +0 -196
- package/packages/extension/src/subagent-tick-throttle.ts +0 -252
- package/packages/shared/src/anthropic-messages-source.ts +0 -8
|
@@ -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,
|
|
11
|
+
import { createGatedProviderAuth, createIsPiExtensionInstalled, createPluginServiceRegistry, createPluginSessionManager, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginServerAllowed, 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-
|
|
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";
|
|
@@ -21,11 +21,11 @@ import type { AuthConfig, DashboardConfig } from "@blackbelt-technology/pi-dashb
|
|
|
21
21
|
import { CONFIG_DIR, CONFIG_FILE, getPluginConfig as getPluginConfigFromFile, loadConfig, resolvePublicBaseUrls, writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
22
22
|
import { CustomEventGroupsStore } from "@blackbelt-technology/pi-dashboard-shared/custom-event-groups-store.js";
|
|
23
23
|
import { parseFileHandlerClaimKey } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/file-handler.js";
|
|
24
|
+
import { computeReplayEntryTypes } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/replay-entry-types.js";
|
|
24
25
|
import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
|
|
25
26
|
import type { HostAction, HostResource, Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
|
|
26
27
|
import { advertiseDashboard, createBrowser, type DashboardBrowser, type DiscoveredServer, resolveAdvertisedAddresses, stopAdvertising } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
27
28
|
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
29
|
import {
|
|
30
30
|
deregisterPluginBridge,
|
|
31
31
|
reconcilePluginBridgePackages,
|
|
@@ -40,7 +40,6 @@ import {
|
|
|
40
40
|
readRuntimeRequest,
|
|
41
41
|
readRuntimeState,
|
|
42
42
|
} from "@blackbelt-technology/pi-dashboard-shared/runtime-overlay/state.js";
|
|
43
|
-
import { createSemaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
|
|
44
43
|
import { proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
|
|
45
44
|
import { discoverServiceOffers } from "@blackbelt-technology/pi-dashboard-shared/services/offers.js";
|
|
46
45
|
import { isRecoveryCandidate, isShutdownWindowCandidate, mergeSessionMeta, type SessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
|
|
@@ -53,8 +52,8 @@ import fastifyCookie from "@fastify/cookie";
|
|
|
53
52
|
import cors from "@fastify/cors";
|
|
54
53
|
import rateLimit from "@fastify/rate-limit";
|
|
55
54
|
import fastifyStatic from "@fastify/static";
|
|
56
|
-
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
|
|
57
|
-
import { listGrants as listAccessGrants, setGrantsChangedListener } from "./access/access-grants.js";
|
|
55
|
+
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
|
|
56
|
+
import { listGrants as listAccessGrants, setGrantsChangedListener, setSessionGrantsChangedListener } from "./access/access-grants.js";
|
|
58
57
|
import { snapshotAccessGrantHealth } from "./access/access-health.js";
|
|
59
58
|
import { AccessPlaneRegistry, isGrantPromptKilled } from "./access/access-plane.js";
|
|
60
59
|
import { shouldIssuePromptCapability } from "./access/capability-issuance.js";
|
|
@@ -64,16 +63,22 @@ import { createCwdHold } from "./access/cwd-verdict.js";
|
|
|
64
63
|
import { installGrantCoordinator } from "./access/denial-hold.js";
|
|
65
64
|
import { GrantCoordinator } from "./access/grant-coordinator.js";
|
|
66
65
|
import { ensureGrantStoreId } from "./access/grant-store-id.js";
|
|
66
|
+
import { createPiTrustLiveProvider } from "./access/pi-trust-live.js";
|
|
67
67
|
import { createPiTrustMirrorService, setPiTrustMirror } from "./access/pi-trust-mirror-service.js";
|
|
68
|
-
import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane } from "./access/planes.js";
|
|
68
|
+
import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane, createPreviewEgressPlane } from "./access/planes.js";
|
|
69
|
+
import { projectEgressGrants } from "./access/preview-egress-store.js";
|
|
69
70
|
import { promptChannelCount } from "./access/prompt-channel.js";
|
|
71
|
+
import { createDefaultProvisioningGrantStore } from "./access/provisioning.js";
|
|
72
|
+
import { installProvisioning } from "./access/provisioning-wiring.js";
|
|
70
73
|
import { clearRefusal, isRefused, listRefusals, recordRefusal } from "./access/refusal-ledger.js";
|
|
71
74
|
import { sourceChannel } from "./access/source-channel.js";
|
|
72
75
|
import { YOLO_ENV } from "./access/yolo-env.js";
|
|
73
76
|
import { YoloController } from "./access/yolo-session.js";
|
|
74
77
|
import { scanAcpSessions } from "./acp-bridge/acp-restore.js";
|
|
75
78
|
import { stopAllLocalAcpSessions } from "./acp-bridge/local-host.js";
|
|
79
|
+
import { createAgentEventHub } from "./agent-events/agent-event-hub.js";
|
|
76
80
|
import { createFitWorkerPool } from "./attachments/fit-worker-pool.js";
|
|
81
|
+
import { auditPrefix } from "./auth/audit-log.js";
|
|
77
82
|
import { resolveRedirectBase } from "./auth/auth.js";
|
|
78
83
|
import { authorizeWsUpgrade, buildLoginAvailable, effectiveSessionTier, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
79
84
|
import { registerBearerAuth, registerDeviceSessionRoutes } from "./auth/bearer-auth.js";
|
|
@@ -83,7 +88,7 @@ import {
|
|
|
83
88
|
formatBindReachabilityWarning,
|
|
84
89
|
initBindReachability,
|
|
85
90
|
} from "./auth/bind-reachability-service.js";
|
|
86
|
-
import { decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
91
|
+
import { createTicketRefusalLog, decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
87
92
|
import {
|
|
88
93
|
CORS_ALLOWED_METHODS,
|
|
89
94
|
type CorsOriginOptions,
|
|
@@ -92,7 +97,14 @@ import {
|
|
|
92
97
|
isWsOriginTrusted,
|
|
93
98
|
sanitizeHeaderForLog,
|
|
94
99
|
} from "./auth/cors-origin.js";
|
|
95
|
-
import {
|
|
100
|
+
import { getCredentialCodec, type InitCredentialKeyOptions, initCredentialKey } from "./auth/credential-key.js";
|
|
101
|
+
import { migrateCredentialFiles } from "./auth/credential-migration.js";
|
|
102
|
+
import { cspNonceFor, markViteProxied, registerCsp, resolveCspMode, resolveTrustedTypesMode } from "./auth/csp.js";
|
|
103
|
+
import { registerCspReportSink } from "./auth/csp-report-sink.js";
|
|
104
|
+
import { CspReportStore } from "./auth/csp-report-store.js";
|
|
105
|
+
import { stateCallerFor } from "./auth/dashboard-state-caller.js";
|
|
106
|
+
import { createDuplicateCookieGate, refuseDuplicateCookieUpgrade } from "./auth/duplicate-cookie-gate.js";
|
|
107
|
+
import { classifyAdmittedHostname, isHostAdmitted } from "./auth/host-admission.js";
|
|
96
108
|
import {
|
|
97
109
|
createHostGate,
|
|
98
110
|
evaluateHostGate,
|
|
@@ -105,26 +117,35 @@ import {
|
|
|
105
117
|
import { ensureServerIdentity } from "./auth/identity.js";
|
|
106
118
|
import { createLocalCredentialVerifier, hasLocalCredential, listenWithProofFloor } from "./auth/local-credential.js";
|
|
107
119
|
import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
|
|
120
|
+
import { createLocalProofRefusalLogger } from "./auth/local-proof-refusal-log.js";
|
|
108
121
|
import { ensureLocalToken } from "./auth/local-token.js";
|
|
109
122
|
import {
|
|
110
123
|
createLanInterfaceProvider,
|
|
111
124
|
createNetworkGuard,
|
|
112
125
|
createNetworkGuardHook,
|
|
126
|
+
evaluateNetworkPass,
|
|
127
|
+
isLocallyTrusted,
|
|
113
128
|
isPluginScopePeerLocal,
|
|
129
|
+
needsLocalProof,
|
|
114
130
|
noteTrustedList,
|
|
115
131
|
parseGuardTarget,
|
|
132
|
+
setLocalProofRefusalObserver,
|
|
116
133
|
setNetworkDenialObserver,
|
|
117
134
|
} from "./auth/localhost-guard.js";
|
|
118
135
|
import { createMutationOriginGate } from "./auth/mutation-origin-gate.js";
|
|
136
|
+
import { NavIntents } from "./auth/nav-intent.js";
|
|
119
137
|
import { PasskeyService } from "./auth/passkey/passkey-service.js";
|
|
120
138
|
import { resolveRpContext } from "./auth/passkey/rp-context.js";
|
|
121
139
|
import { UserDirectory } from "./auth/passkey/user-directory.js";
|
|
122
140
|
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
123
141
|
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
142
|
+
import { isServerTrusted } from "./auth/plugin-server-trust.js";
|
|
143
|
+
import { bearerChannelOf, isProvenTls } from "./auth/proven-tls.js";
|
|
124
144
|
import { setOAuthRegistryRuntimeSource } from "./auth/provider-auth-registry.js";
|
|
125
|
-
import { readAuthJson } from "./auth/provider-auth-storage.js";
|
|
145
|
+
import { hasAnthropicCredential, readAuthJson } from "./auth/provider-auth-storage.js";
|
|
126
146
|
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
127
147
|
import { createRouteTierGate } from "./auth/route-tier-gate.js";
|
|
148
|
+
import { RotationError, rotateSecretsOnce } from "./auth/secret-rotation.js";
|
|
128
149
|
import { createHostServeApp } from "./auth/serve-app-host.js";
|
|
129
150
|
import { mintSpawnToken } from "./auth/spawn-token.js";
|
|
130
151
|
import { admissionTrustedNetworks, effectiveTrustMode } from "./auth/trust-mode.js";
|
|
@@ -133,6 +154,7 @@ import {
|
|
|
133
154
|
type CoreWsRouteScope,
|
|
134
155
|
extractTicket,
|
|
135
156
|
isCoreWsRouteScope,
|
|
157
|
+
mintBridgeTicket,
|
|
136
158
|
routeScopeForUrl,
|
|
137
159
|
setPluginScopeResolver,
|
|
138
160
|
type WsRouteScope,
|
|
@@ -146,17 +168,22 @@ import {
|
|
|
146
168
|
respawnForRuntimeSwap,
|
|
147
169
|
} from "./browser-handlers/session-action-handler.js";
|
|
148
170
|
import { runLifecycleAction } from "./browser-handlers/session-lifecycle.js";
|
|
171
|
+
import { buildPluginSendPrompt } from "./build-plugin-send-prompt.js";
|
|
149
172
|
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
150
|
-
import { readRawConfig, writeConfigPartial } from "./config-api.js";
|
|
173
|
+
import { readRawConfig, seedWindowsSourceSettings, writeConfigPartial } from "./config-api.js";
|
|
151
174
|
import {
|
|
175
|
+
getResolvedPreviewOrigins,
|
|
152
176
|
liveAcceptLanRequests,
|
|
153
177
|
liveAllowedHosts,
|
|
154
178
|
liveCorsAllowedOrigins,
|
|
179
|
+
liveCorsAllowZrokWildcard,
|
|
155
180
|
liveHostGateMode,
|
|
181
|
+
livePreviewExposureOverride,
|
|
156
182
|
livePublicBaseUrls,
|
|
157
183
|
liveRequireLocalProof,
|
|
158
184
|
liveTrustedNetworks,
|
|
159
185
|
rawConfigHasHostGateMode,
|
|
186
|
+
setPreviewOriginsRuntime,
|
|
160
187
|
} from "./config-snapshot.js";
|
|
161
188
|
// pending-load-manager removed — server loads sessions directly via DirectoryService
|
|
162
189
|
import { createDirectoryService, type DirectoryService } from "./directory-service.js";
|
|
@@ -164,8 +191,16 @@ import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycl
|
|
|
164
191
|
import { createPluginSessionCloseApi, createSessionCloserRegistry } from "./embed-lifecycle/plugin-session-close.js";
|
|
165
192
|
import { wireEvents } from "./event-wiring.js";
|
|
166
193
|
import { createFileWatchManager } from "./file-watch-manager.js";
|
|
194
|
+
import { ensureWorktree } from "./git-worktree/ensure-worktree.js";
|
|
195
|
+
import { resolveMainPath } from "./git-worktree/git-operations.js";
|
|
196
|
+
import { awaitInitRun, startWorktreeInit } from "./git-worktree/start-worktree-init.js";
|
|
167
197
|
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
168
|
-
import {
|
|
198
|
+
import {
|
|
199
|
+
listPersistedTrust as listPersistedWorktreeTrust,
|
|
200
|
+
listSessionTrust as listSessionWorktreeTrust,
|
|
201
|
+
setSessionTrustChangedListener,
|
|
202
|
+
setTrustChangedListener,
|
|
203
|
+
} from "./git-worktree/worktree-init-trust.js";
|
|
169
204
|
import { identityDisarmedWarning, isIdentityEnforced } from "./identity/activation.js";
|
|
170
205
|
import { buildAuthContext } from "./identity/auth-context.js";
|
|
171
206
|
import { type BootstrapGrants, DENY_ALL_GRANTS, decideBootstrapGrants } from "./identity/bootstrap-grants.js";
|
|
@@ -187,14 +222,21 @@ import { canAccessSession, isLocalOperator, markLocalOperator, sessionPrincipalO
|
|
|
187
222
|
import { scheduleAtExpiry } from "./identity/socket-lifetime.js";
|
|
188
223
|
import { authorizeRoadUpgrade } from "./identity/upgrade-gate.js";
|
|
189
224
|
import { createKnownServerMoves } from "./known-server-moves.js";
|
|
225
|
+
import { buildBrowseRootSources, resolveBrowseRoots } from "./lib/browse-roots.js";
|
|
190
226
|
import {
|
|
191
227
|
clientBuildDiagnostic,
|
|
192
228
|
clientBuildSnapshotFor,
|
|
229
|
+
readServedBundledPluginIds,
|
|
193
230
|
resolveStaticClientDir,
|
|
194
231
|
} from "./lib/client-dist.js";
|
|
232
|
+
import { readFileGuarded as guardedReadFile, runWithStateCaller } from "./lib/dashboard-state-guard.js";
|
|
195
233
|
import { collectRuleSources } from "./lib/folder-project.js";
|
|
234
|
+
import { resolveFramePolicyTestSeam } from "./lib/frame-policy-test-seam.js";
|
|
235
|
+
import { createIndexHtmlSender } from "./lib/index-html.js";
|
|
236
|
+
import { listKnownFolderCwds, type RouteAdmissionDeps } from "./lib/route-admission.js";
|
|
196
237
|
import { bootParentPid, isBootParentProvablyDead } from "./lifecycle/boot-parent-liveness.js";
|
|
197
238
|
import { runBoundedStartup } from "./lifecycle/bounded-startup.js";
|
|
239
|
+
import { exitBarrier } from "./lifecycle/credential-exit-barrier.js";
|
|
198
240
|
import { startEphemeralParentWatch } from "./lifecycle/ephemeral-parent-watch.js";
|
|
199
241
|
import { ensureInstanceId } from "./lifecycle/instance-id.js";
|
|
200
242
|
import {
|
|
@@ -204,8 +246,21 @@ import {
|
|
|
204
246
|
redactCapability,
|
|
205
247
|
sessionKeyOf,
|
|
206
248
|
} from "./live-server/live-capability.js";
|
|
249
|
+
import { createReservedHandler } from "./live-server/live-csp-report.js";
|
|
250
|
+
import { createEgressGrantRequester, createPreviewEgress, requestOriginsOf } from "./live-server/live-egress.js";
|
|
251
|
+
import { createPreviewExposure, wirePreviewExposure } from "./live-server/live-exposure.js";
|
|
252
|
+
import { liveLog } from "./live-server/live-log.js";
|
|
207
253
|
import { createLiveServerManager } from "./live-server/live-server-manager.js";
|
|
208
|
-
import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
254
|
+
import { handleLiveServerUpgrade, type LiveProxyDeps, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
255
|
+
import { createPreviewDispatch, type PreviewDispatch, previewServerFactory, routePreviewUpgrade } from "./live-server/preview-dispatch.js";
|
|
256
|
+
import { createPreviewObserver, type PreviewObserver } from "./live-server/preview-observe.js";
|
|
257
|
+
import { isPreviewShapedOriginUrl, previewLogHash } from "./live-server/preview-origin.js";
|
|
258
|
+
import { parsePreviewPath } from "./live-server/preview-path.js";
|
|
259
|
+
import { PreviewPathStore } from "./live-server/preview-path-store.js";
|
|
260
|
+
import { createPreviewPool, type PreviewPool } from "./live-server/preview-pool.js";
|
|
261
|
+
import { createPreviewPreflight } from "./live-server/preview-preflight.js";
|
|
262
|
+
import { hasTier5Viewer, stampPreviewViewer } from "./live-server/preview-viewers.js";
|
|
263
|
+
import { createPreviewWsRegistry } from "./live-server/preview-ws-registry.js";
|
|
209
264
|
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
210
265
|
import { createEventLoopSpikeMetrics } from "./metrics/eventloop-spike-metrics.js";
|
|
211
266
|
import { createHydrationMetrics } from "./metrics/hydration-metrics.js";
|
|
@@ -218,50 +273,67 @@ import { createOpenSpecGroupStore, joinGroupIdsToOpenSpecData } from "./openspec
|
|
|
218
273
|
import { fetchPackageMeta } from "./package/npm-search-proxy.js";
|
|
219
274
|
import { logPackageHealthAtBoot } from "./package/package-health-scanner.js";
|
|
220
275
|
import { type OperationResult, PackageManagerWrapper } from "./package/package-manager-wrapper.js";
|
|
276
|
+
import { setProbeSelfPort } from "./package/provider-probe.js";
|
|
221
277
|
import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
|
|
278
|
+
import { createDeviceTokenServices } from "./pairing/device-token-services.js";
|
|
222
279
|
import { createRequestAccessAvailable, type KnockPeerDeps } from "./pairing/knock-admission.js";
|
|
223
280
|
import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
|
|
224
281
|
import { PairingManager, wirePendingHint } from "./pairing/pairing.js";
|
|
225
|
-
import
|
|
282
|
+
import { stampSocketLocality } from "./pairing/socket-locality.js";
|
|
283
|
+
import { closeDeviceSockets, sweepRevokedSockets, type TieredSocket } from "./pairing/ws-tier-gate.js";
|
|
226
284
|
import { buildSelfServer, wirePeerServers } from "./peer-servers.js";
|
|
227
285
|
import { createPendingArchiveIntentRegistry } from "./pending/pending-archive-intent-registry.js";
|
|
228
286
|
import { createPendingAttachRegistry } from "./pending/pending-attach-registry.js";
|
|
229
287
|
import { createPendingClientCorrelations } from "./pending/pending-client-correlations.js";
|
|
230
288
|
import { createPendingForkRegistry } from "./pending/pending-fork-registry.js";
|
|
231
|
-
import { createPendingInitialPromptRegistry } from "./pending/pending-initial-prompt-registry.js";
|
|
289
|
+
import { createPendingInitialPromptRegistry, type PendingInitialPromptRegistry } from "./pending/pending-initial-prompt-registry.js";
|
|
232
290
|
import { createPendingPluginRefRegistry } from "./pending/pending-plugin-ref-registry.js";
|
|
233
291
|
import { createPendingPrincipalOwnerRegistry } from "./pending/pending-principal-owner-registry.js";
|
|
234
292
|
import { createPendingPromptAcks } from "./pending/pending-prompt-acks.js";
|
|
235
293
|
import { createPendingResumeIntentRegistry } from "./pending/pending-resume-intent-registry.js";
|
|
236
294
|
import { createPendingWorktreeBaseRegistry } from "./pending/pending-worktree-base-registry.js";
|
|
237
295
|
import { recordExitIntent, resolveExitIntent, resolveExitRecord, stampBootStart } from "./persistence/boot-state.js";
|
|
296
|
+
import { createPluginEventAppender } from "./plugin-append-event.js";
|
|
297
|
+
import { buildPluginOwnership, createPluginOwnership } from "./plugin-ownership.js";
|
|
298
|
+
import { getPluginPolicyRegistry } from "./plugin-policy-registry.js";
|
|
238
299
|
import { createMemoryEventStore, DEFAULT_MAX_EVENT_DATA_SIZE, DEFAULT_MAX_STRING_SIZE, type EventStore } from "./persistence/memory-event-store.js";
|
|
239
300
|
import { createMetaPersistence } from "./persistence/meta-persistence.js";
|
|
240
301
|
import { migrateCustomEntryFallbackOverrides } from "./persistence/migrate-custom-entry-fallback.js";
|
|
241
302
|
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
242
303
|
import { createPreferencesStore } from "./persistence/preferences-store.js";
|
|
304
|
+
import { CONTENTION_RATE_LIMIT } from "./pi/bridge-contention.js";
|
|
243
305
|
import { loadHostProjectTrustService } from "./pi/host-project-trust.js";
|
|
244
306
|
import { PiCoreChecker } from "./pi/pi-core-checker.js";
|
|
245
307
|
import { PiCoreUpdater } from "./pi/pi-core-updater.js";
|
|
246
|
-
import { createPiGateway } from "./pi/pi-gateway.js";
|
|
308
|
+
import { createPiGateway, type GatewayConn } from "./pi/pi-gateway.js";
|
|
247
309
|
import { listGlobalSkills } from "./pi/pi-resource-scanner.js";
|
|
310
|
+
import { createPiDefaultRemirror, setActivePiDefaultRemirror } from "./pi-default-remirror.js";
|
|
311
|
+
import { createPackageCompletionHandler, createPluginDiscoveryWiring, type PluginDiscoveryWiring } from "./plugin-discovery-wiring.js";
|
|
312
|
+
import { getReplayEntryTypes, recordRejectedPluginAction, setReplayEntryTypesProvider } from "./plugin-entry-stats.js";
|
|
248
313
|
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
249
314
|
import { pluginIntentCache } from "./plugin-intent-cache.js";
|
|
315
|
+
import { createHostLocalRequest, HOST_LOCAL_REQUEST_KEY } from "./plugin-local-request.js";
|
|
250
316
|
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
317
|
+
import { getRuntimeClientRegistry, installRuntimeClientRegistry, logRuntimeAdmissions } from "./plugin-runtime-clients.js";
|
|
318
|
+
import { configureProjectSeed, resolveAutoSeedEnabled, sweepKnownProjects } from "./project-seed.js";
|
|
251
319
|
import { createPushService, type PushService } from "./push/push-service.js";
|
|
252
320
|
import type { SessionPresence } from "./questions/question-files.js";
|
|
253
321
|
import { registerQuestionRoutes } from "./questions/question-routes.js";
|
|
254
322
|
import { createQuestionStack, persistedPresence } from "./questions/question-stack.js";
|
|
255
323
|
import { registerAccessPromptRoutes } from "./routes/access-prompt-routes.js";
|
|
256
324
|
import { registerAccessRoutes } from "./routes/access-routes.js";
|
|
325
|
+
import { registerAcmeRoutes } from "./routes/acme-routes.js";
|
|
257
326
|
import { registerAcpRoutes } from "./routes/acp-routes.js";
|
|
258
327
|
import { registerAddonsRoutes } from "./routes/addons-routes.js";
|
|
328
|
+
import { registerAgentEventStreamRoutes } from "./routes/agent-event-stream-routes.js";
|
|
259
329
|
import { registerAttachmentRoutes } from "./routes/attachment-routes.js";
|
|
260
330
|
import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
|
|
331
|
+
import { registerCspViolationRoutes } from "./routes/csp-violations-routes.js";
|
|
261
332
|
import { registerCustomEventGroupsRoutes } from "./routes/custom-event-groups-routes.js";
|
|
262
333
|
import { registerDoctorRoutes } from "./routes/doctor-routes.js";
|
|
263
|
-
import { registerFileRoutes } from "./routes/file-routes.js";
|
|
334
|
+
import { denialBody, gateFilePath, registerFileRoutes } from "./routes/file-routes.js";
|
|
264
335
|
import { registerFolderProjectRoutes } from "./routes/folder-project-routes.js";
|
|
336
|
+
import { registerFramePolicyRoutes } from "./routes/frame-policy-routes.js";
|
|
265
337
|
import { registerGitRoutes } from "./routes/git-routes.js";
|
|
266
338
|
import { registerGrepRoutes } from "./routes/grep-routes.js";
|
|
267
339
|
import { registerHostGateRoutes } from "./routes/host-gate-routes.js";
|
|
@@ -275,6 +347,7 @@ import { registerModelProxyDiagnosticsRoutes } from "./routes/model-proxy-diagno
|
|
|
275
347
|
import { registerModelProxyRefreshRoutes } from "./routes/model-proxy-refresh-routes.js";
|
|
276
348
|
import { registerModelProxyRoutes } from "./routes/model-proxy-routes.js";
|
|
277
349
|
import { registerModelsIntrospectionRoute } from "./routes/models-introspection-routes.js";
|
|
350
|
+
import { registerNavIntentRoutes } from "./routes/nav-intent-routes.js";
|
|
278
351
|
import { registerNodeRuntimeRoutes } from "./routes/node-runtime-routes.js";
|
|
279
352
|
import { registerOpenSpecGroupRoutes } from "./routes/openspec-group-routes.js";
|
|
280
353
|
import { registerOpenSpecRoutes } from "./routes/openspec-routes.js";
|
|
@@ -286,12 +359,16 @@ import { registerPiCoreRoutes } from "./routes/pi-core-routes.js";
|
|
|
286
359
|
import { registerPiRetryRoutes } from "./routes/pi-retry-routes.js";
|
|
287
360
|
import { registerPiRuntimeRoutes } from "./routes/pi-runtime-routes.js";
|
|
288
361
|
import { registerPiSettingsRoutes } from "./routes/pi-settings-routes.js";
|
|
362
|
+
import { registerPiTrustQueryRoutes } from "./routes/pi-trust-query-routes.js";
|
|
289
363
|
import { registerPluginActivationRoutes, setPluginsEnabled } from "./routes/plugin-activation-routes.js";
|
|
290
364
|
import { registerPluginConfigRoutes } from "./routes/plugin-config-routes.js";
|
|
365
|
+
import { registerPluginRuntimeClientRoutes } from "./routes/plugin-runtime-client-routes.js";
|
|
291
366
|
import { registerPreferencesAutoNameRoutes } from "./routes/preferences-auto-name-routes.js";
|
|
367
|
+
import { registerPreferencesClaudeCompatRoutes } from "./routes/preferences-claude-compat-routes.js";
|
|
292
368
|
import { registerPreferencesDisplayRoutes } from "./routes/preferences-display-routes.js";
|
|
293
369
|
import { registerPreferencesWorktreeInitRoutes } from "./routes/preferences-worktree-init-routes.js";
|
|
294
370
|
import { registerProviderAuthRoutes } from "./routes/provider-auth-routes.js";
|
|
371
|
+
import { registerProviderOverrideRoutes } from "./routes/provider-override-routes.js";
|
|
295
372
|
import { registerProviderRoutes } from "./routes/provider-routes.js";
|
|
296
373
|
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
297
374
|
import { invalidateRecommendedCache, registerRecommendedRoutes } from "./routes/recommended-routes.js";
|
|
@@ -300,10 +377,6 @@ import { registerRuntimeRoutes } from "./routes/runtime-routes.js";
|
|
|
300
377
|
import { registerSessionRoutes, type ToolResultStats } from "./routes/session-routes.js";
|
|
301
378
|
import { registerSystemRoutes } from "./routes/system-routes.js";
|
|
302
379
|
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
380
|
import { registerToolRoutes } from "./routes/tool-routes.js";
|
|
308
381
|
import { registerUserRoutes } from "./routes/user-routes.js";
|
|
309
382
|
import {
|
|
@@ -325,6 +398,7 @@ import { createArchiveSweeper } from "./session/archive-sweeper.js";
|
|
|
325
398
|
import { CustomEventGroupMatcher } from "./session/custom-event-group-matcher.js";
|
|
326
399
|
import { CustomEventGroupResolver } from "./session/custom-event-group-resolver.js";
|
|
327
400
|
import { deriveEndedAt } from "./session/derive-ended-at.js";
|
|
401
|
+
import { createReplayState } from "./session/hydration-state.js";
|
|
328
402
|
import { createInFlightToolCalls } from "./session/in-flight-tool-calls.js";
|
|
329
403
|
import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
|
|
330
404
|
import { systemRenameUpdates } from "./session/name-provenance.js";
|
|
@@ -345,28 +419,43 @@ import { setLocalAcpHost, spawnAcpSession, validatePluginAcpSpawn } from "./spaw
|
|
|
345
419
|
import { CwdPolicyRegistry } from "./spawn-process/cwd-policy.js";
|
|
346
420
|
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
347
421
|
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
422
|
+
import { createPluginSpawnHook } from "./spawn-process/plugin-spawn-worktree.js";
|
|
348
423
|
import { getKeeperManager, setCwdPolicyRegistry, spawnPiSession } from "./spawn-process/process-manager.js";
|
|
349
424
|
import { removePid, writePid } from "./spawn-process/server-pid.js";
|
|
350
425
|
import { createSessionTerminator } from "./spawn-process/session-terminator.js";
|
|
351
426
|
import { registerSpawnEnvContributorForPlugin, setSpawnEnvPluginEnabledCheck } from "./spawn-process/spawn-env-contributors.js";
|
|
352
427
|
import { armSpawnWatchdog } from "./spawn-process/spawn-register-watchdog.js";
|
|
428
|
+
import { createSudoCredentialRelay } from "./sudo-credential/relay.js";
|
|
353
429
|
import { createTerminalGateway } from "./terminal/terminal-gateway.js";
|
|
354
430
|
import { createTerminalManager, deriveTranscriptCapBytes } from "./terminal/terminal-manager.js";
|
|
431
|
+
import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
|
|
432
|
+
import { acmeGc } from "./tls/sources/acme/gc.js";
|
|
433
|
+
import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
|
|
434
|
+
import { onTlsBridgeSwitchChanged, routeBridgeUpgrade } from "./tls/tls-bridge-route.js";
|
|
355
435
|
import {
|
|
356
436
|
MAIN_CONNECTION_TIMEOUT_MS,
|
|
357
437
|
MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
358
438
|
TlsListener,
|
|
359
439
|
} from "./tls/tls-listener.js";
|
|
360
440
|
import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, liveTunnelOrigins, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
|
|
441
|
+
import { collectEndpoints } from "./tunnel/tunnel-endpoints.js";
|
|
361
442
|
import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
|
|
443
|
+
import { startDeviceExpirySweep } from "./vault/device-expiry-sweep.js";
|
|
362
444
|
import { createVaultDeliveryHub } from "./vault/vault-delivery-hub.js";
|
|
363
445
|
import { createVaultImport, defaultKnownLocations } from "./vault/vault-import.js";
|
|
364
446
|
import { createPluginVaultReader } from "./vault/vault-plugin-read.js";
|
|
365
447
|
import { createVaultProjects } from "./vault/vault-projects.js";
|
|
366
448
|
import { createVaultManageGuard, registerVaultRoutes } from "./vault/vault-routes.js";
|
|
367
449
|
import { createVaultStore } from "./vault/vault-store.js";
|
|
450
|
+
import { createWatchFilesHandler, type WatchFilesMessage } from "./watch-files-handler.js";
|
|
368
451
|
|
|
369
452
|
export interface ServerConfig {
|
|
453
|
+
/**
|
|
454
|
+
* Test seam for the credential data key (key file env, stub keychain, log sink, home dir).
|
|
455
|
+
* Production leaves it unset: `initCredentialKey()` then reads `process.env` and the real home.
|
|
456
|
+
* See change: encrypt-credentials-at-rest (D4, D9).
|
|
457
|
+
*/
|
|
458
|
+
credentialKey?: InitCredentialKeyOptions;
|
|
370
459
|
port: number;
|
|
371
460
|
piPort: number;
|
|
372
461
|
/**
|
|
@@ -441,6 +530,12 @@ export interface ServerConfig {
|
|
|
441
530
|
/** Shape of the replay window when one applies (`head-tail` | `tail-only`).
|
|
442
531
|
* Absent → `head-tail`. See change: add-tail-only-replay-window (D1). */
|
|
443
532
|
replayWindowMode?: import("@blackbelt-technology/pi-dashboard-shared/memory-limits.js").ReplayWindowMode;
|
|
533
|
+
/**
|
|
534
|
+
* Test seam: shorten the bridge replay fallback exits and the keepalive sent
|
|
535
|
+
* to subscribers waiting on a replay (defaults 5 s idle / 60 s cap / 10 s).
|
|
536
|
+
* See change: fix-large-session-resume-replay (D2).
|
|
537
|
+
*/
|
|
538
|
+
replayTimings?: { idleMs?: number; capMs?: number; keepaliveMs?: number };
|
|
444
539
|
/** OpenSpec polling config (interval, concurrency, change detection, jitter) */
|
|
445
540
|
openspec?: import("@blackbelt-technology/pi-dashboard-shared/config.js").OpenSpecPollConfig;
|
|
446
541
|
/** Push notifications. Absent or `enabled !== true` means disabled (no dispatcher,
|
|
@@ -500,6 +595,8 @@ export interface DashboardServer {
|
|
|
500
595
|
browserGateway: BrowserGateway;
|
|
501
596
|
/** Resolved HTTP port after start() (useful for port:0 in tests). Returns null if not listening. */
|
|
502
597
|
httpPort(): number | null;
|
|
598
|
+
/** @internal Tests only: `fastify.inject` on the wired app, so a test can present a non-loopback peer (`remoteAddress`). See change: surface-network-denial-on-health. */
|
|
599
|
+
inject: FastifyInstance["inject"];
|
|
503
600
|
/** The optional TLS listener (off by default). See change: add-tailscale-cert-tls. */
|
|
504
601
|
readonly tls: TlsListener;
|
|
505
602
|
/** Resolved pi gateway port after start(). Returns null if not listening. */
|
|
@@ -512,6 +609,13 @@ export interface DashboardServer {
|
|
|
512
609
|
* See change: fix-dashboard-spawn-correlation-by-token.
|
|
513
610
|
*/
|
|
514
611
|
pendingDashboardSpawns: Map<string, number>;
|
|
612
|
+
/**
|
|
613
|
+
* Pending initial-prompt intents per cwd. Exposed for in-process tests that
|
|
614
|
+
* pin register-time ordering (preferences snapshot before `send_prompt`).
|
|
615
|
+
* Not part of the public API — do not depend on this from production code.
|
|
616
|
+
* See change: retire-anthropic-messages-bridge.
|
|
617
|
+
*/
|
|
618
|
+
pendingInitialPromptRegistry: PendingInitialPromptRegistry;
|
|
515
619
|
/**
|
|
516
620
|
* In-process OpenSpec poll cache + discovery service. Exposed for tests
|
|
517
621
|
* that need to stub `getOpenSpecData` (e.g. the deleted-proposal bypass).
|
|
@@ -582,6 +686,34 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
582
686
|
// the server listens (so no operator write can race it). Never re-derived
|
|
583
687
|
// from the list afterwards. See change: retire-trusted-networks-bypass (D2).
|
|
584
688
|
decideBootTrustMode();
|
|
689
|
+
// The exit barrier is a module singleton: a new server must never inherit a
|
|
690
|
+
// gate closed by a previous create/stop cycle in this process (tests, embeds).
|
|
691
|
+
// Cycles are strictly sequential. See change: settle-server-credential-writes-on-exit.
|
|
692
|
+
exitBarrier.reopen();
|
|
693
|
+
// One-shot rotation of the local token + auth secret that a bare-loopback caller
|
|
694
|
+
// may already have read through the `~/.pi` anchor. Must precede every read of
|
|
695
|
+
// either value (the token below, `config.authConfig.secret`). Failure is closed:
|
|
696
|
+
// exit 1 before listening. See change: close-container-loopback-impersonation (D11).
|
|
697
|
+
try {
|
|
698
|
+
const rotation = await rotateSecretsOnce();
|
|
699
|
+
if (rotation.rotated) {
|
|
700
|
+
console.log("[rotation] local token and auth secret rotated once; existing sessions and proof cookies are invalidated");
|
|
701
|
+
if (rotation.newSecret && config.authConfig) config.authConfig.secret = rotation.newSecret;
|
|
702
|
+
}
|
|
703
|
+
} catch (err) {
|
|
704
|
+
if (err instanceof RotationError) {
|
|
705
|
+
console.error(err.describe());
|
|
706
|
+
process.exit(1);
|
|
707
|
+
}
|
|
708
|
+
throw err;
|
|
709
|
+
}
|
|
710
|
+
// Resolve the credential data key BEFORE anything builds or reads a credential store
|
|
711
|
+
// (vault, ACME runtime, plugin load) and before `listen`, then migrate plaintext
|
|
712
|
+
// credential files to envelopes. One 10 s total deadline bounds init; a keychain failure
|
|
713
|
+
// only leaves the stores locked, it never stops the server from booting. Neither call throws.
|
|
714
|
+
// See change: encrypt-credentials-at-rest (D4, D7, D11).
|
|
715
|
+
await initCredentialKey(config.credentialKey);
|
|
716
|
+
await migrateCredentialFiles({ home: config.credentialKey?.homeDir, log: config.credentialKey?.log });
|
|
585
717
|
// Ensure bridge extension is registered in pi's global settings
|
|
586
718
|
// (needed for bundled installs where pi can't discover it from package.json)
|
|
587
719
|
//
|
|
@@ -610,7 +742,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
610
742
|
// Seed Windows git/bash source from config so spawn-env augmentation
|
|
611
743
|
// (ToolResolver.buildSpawnEnv + PTY) picks bundled vs host correctly.
|
|
612
744
|
// No-op on macOS/Linux. See change: embed-git-bash-on-windows.
|
|
613
|
-
|
|
745
|
+
seedWindowsSourceSettings();
|
|
614
746
|
|
|
615
747
|
// Run migration from sessions.json + state.json if needed
|
|
616
748
|
if (needsMigration()) {
|
|
@@ -625,6 +757,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
625
757
|
const customEventGroupResolver = new CustomEventGroupResolver(
|
|
626
758
|
customEventGroupsStore.list(),
|
|
627
759
|
customEventGroupMatcher,
|
|
760
|
+
// Plugin-declared entry types are never grouped. See change: update-flows-plugin (D3).
|
|
761
|
+
{ isPluginEntryType: (t) => getReplayEntryTypes().hidden.includes(t) },
|
|
628
762
|
);
|
|
629
763
|
|
|
630
764
|
migrateCustomEntryFallbackOverrides(undefined, undefined, Object.fromEntries(
|
|
@@ -639,6 +773,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
639
773
|
customEventGroupDefaults: Object.fromEntries(
|
|
640
774
|
customEventGroupsStore.definitions().map((g) => [g.id, g.default]),
|
|
641
775
|
),
|
|
776
|
+
// One-time compat-switch seed for upgraders with an anthropic sign-in.
|
|
777
|
+
// See change: seed-claude-compat-on-upgrade (design D2).
|
|
778
|
+
hasAnthropicCredential,
|
|
642
779
|
});
|
|
643
780
|
// Single cwd-policy registry (Part B — host-cwd-policy). Recognized workspace
|
|
644
781
|
// roots = pinned directories + every folder in a folder-workspace, evaluated
|
|
@@ -652,6 +789,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
652
789
|
],
|
|
653
790
|
});
|
|
654
791
|
setCwdPolicyRegistry(cwdPolicyRegistry);
|
|
792
|
+
// Auto-seed pi project defaults (change: auto-seed-project-defaults). The
|
|
793
|
+
// boot sweep covers folders the dashboard ALREADY knows about — pinned dirs +
|
|
794
|
+
// workspace folders, the same set `recognizedRoots` spans; folders learned
|
|
795
|
+
// later are covered by the pin handler and bridge registration. Each dir is
|
|
796
|
+
// deferred onto its own tick, so a large pin list never stalls startup.
|
|
797
|
+
configureProjectSeed(resolveAutoSeedEnabled(loadConfig(), CONFIG_FILE));
|
|
798
|
+
sweepKnownProjects([
|
|
799
|
+
...preferencesStore.getPinnedDirectories(),
|
|
800
|
+
...preferencesStore.getWorkspaces().flatMap((w) => w.folders),
|
|
801
|
+
]);
|
|
655
802
|
// Server identity + device pairing (D2/D5/D6). Additive; independent of OAuth.
|
|
656
803
|
const serverIdentity = ensureServerIdentity();
|
|
657
804
|
const pairedDeviceRegistry = new PairedDeviceRegistry();
|
|
@@ -711,7 +858,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
711
858
|
let tlsBoundAt = 0;
|
|
712
859
|
// Strict local-proof context (`requireLocalProof`, live config read). Threaded to
|
|
713
860
|
// every genuinely-local admission site. See change: harden-trust-and-credential-boundaries (D2).
|
|
714
|
-
|
|
861
|
+
// The proof cookie is bound to the listener's port; `0` until `listen` runs (inject() in tests).
|
|
862
|
+
let httpListenPort = 0;
|
|
863
|
+
/** Rate-limited (per device) below-operate bridge-ticket refusal line (D2). */
|
|
864
|
+
const logTicketRefusal = createTicketRefusalLog({ windowMs: CONTENTION_RATE_LIMIT, prefix: (id) => auditPrefix(id) });
|
|
865
|
+
const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof, () => httpListenPort);
|
|
715
866
|
const localProofCodes = new LocalProofCodeStore();
|
|
716
867
|
const pairingManager = new PairingManager({
|
|
717
868
|
registry: pairedDeviceRegistry,
|
|
@@ -788,6 +939,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
788
939
|
// so `worktree_init_*` events stream only to the dialog that
|
|
789
940
|
// initiated the run. See change: generalize-worktree-init-hook.
|
|
790
941
|
const worktreeInitRegistry = createWorktreeInitRegistry();
|
|
942
|
+
// Latched at the top of `stop()`: the plugin spawn hook refuses a launch that resumes after it
|
|
943
|
+
// (its child would escape the shutdown sweeps). See change: add-plugin-spawn-worktree.
|
|
944
|
+
let serverStopping = false;
|
|
791
945
|
|
|
792
946
|
// Restore sessions from per-session .meta.json files (scans ~/.pi/agent/sessions/)
|
|
793
947
|
const scanStartedAt = Date.now();
|
|
@@ -935,7 +1089,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
935
1089
|
// (heartbeat tail, click-induced state sync, late bridge events) do
|
|
936
1090
|
// NOT re-fire it.
|
|
937
1091
|
// See changes: pin-and-search-sessions, simplify-session-card-ordering.
|
|
938
|
-
|
|
1092
|
+
// `priorStatus === "ended"` covers an ended record `restore()`d after the
|
|
1093
|
+
// boot snapshot (on-demand discovery seed, unarchive, late boot seed),
|
|
1094
|
+
// which the set never saw. See change: fix-discovery-resurrects-archived.
|
|
1095
|
+
const wasEnded = endedSessionIds.has(sessionId) || ctx?.priorStatus === "ended";
|
|
939
1096
|
const isEnded = session.status === "ended";
|
|
940
1097
|
if (isEnded && !wasEnded) {
|
|
941
1098
|
// Just transitioned alive→ended. The id STAYS in the order map
|
|
@@ -1037,9 +1194,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1037
1194
|
}
|
|
1038
1195
|
}
|
|
1039
1196
|
};
|
|
1040
|
-
//
|
|
1041
|
-
//
|
|
1042
|
-
//
|
|
1197
|
+
// Ids seen as ended: the boot snapshot plus every alive→ended `onChange`,
|
|
1198
|
+
// so the hook can tell a real alive→ended transition from a re-emit of the
|
|
1199
|
+
// ended state. Ended records `restore()`d after this snapshot are NOT in
|
|
1200
|
+
// it; their ended→alive register is detected via `ctx.priorStatus`.
|
|
1201
|
+
// See change: fix-discovery-resurrects-archived.
|
|
1043
1202
|
const endedSessionIds = new Set<string>(
|
|
1044
1203
|
sessionManager.listAll().filter((s) => s.status === "ended").map((s) => s.id),
|
|
1045
1204
|
);
|
|
@@ -1220,7 +1379,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1220
1379
|
/** This process's place in the per-HOME rendezvous (task 2.0a). */
|
|
1221
1380
|
let homeRendezvous: import("./lifecycle/home-rendezvous.js").HomeRendezvous | null = null;
|
|
1222
1381
|
|
|
1382
|
+
/** Live `tls.enabled && tls.acceptBridges`: the one read behind bridge routing, vault trust and the switch hook. */
|
|
1383
|
+
const tlsBridgesLive = (): boolean => {
|
|
1384
|
+
const live = loadConfig().tls;
|
|
1385
|
+
return live.enabled && live.acceptBridges;
|
|
1386
|
+
};
|
|
1387
|
+
// The vault hub is created further down; the gateway reports routing changes through this late binding.
|
|
1388
|
+
let onVaultRoutingChanged: ((sessionId: string, declared?: { certValidation?: "enforced" }) => void) | undefined;
|
|
1223
1389
|
const piGateway = createPiGateway(sessionManager, {
|
|
1390
|
+
onRoutingChanged: (sessionId, declared) => onVaultRoutingChanged?.(sessionId, declared),
|
|
1224
1391
|
...(config.pingInterval !== undefined ? { pingInterval: config.pingInterval } : {}),
|
|
1225
1392
|
// The identity a move TARGET announces on `provisional_accepted`, so the
|
|
1226
1393
|
// mover can prove it reached the instance it named (D14). Unset, every
|
|
@@ -1312,8 +1479,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1312
1479
|
const fitWorkerPool = createFitWorkerPool({ size: 2 });
|
|
1313
1480
|
|
|
1314
1481
|
// Create terminal manager with exit callback
|
|
1482
|
+
// PTY caps + inline orphan TTL from `terminals.*` (restart to apply).
|
|
1483
|
+
// See change: harden-server-capability-bounds (D3).
|
|
1484
|
+
const terminalsConfig = loadConfig().terminals;
|
|
1315
1485
|
const terminalManager = createTerminalManager({
|
|
1316
1486
|
transcriptCapBytes,
|
|
1487
|
+
maxConcurrent: terminalsConfig.maxConcurrent,
|
|
1488
|
+
maxPerOwner: terminalsConfig.maxPerOwner,
|
|
1489
|
+
inlineOrphanTtlMs: terminalsConfig.inlineOrphanTtlMs,
|
|
1317
1490
|
onExit: (terminalId) => {
|
|
1318
1491
|
// Find and remove from session order
|
|
1319
1492
|
const allOrders = sessionOrderManager.getAllOrders();
|
|
@@ -1330,7 +1503,20 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1330
1503
|
const terminalGateway = createTerminalGateway(terminalManager);
|
|
1331
1504
|
|
|
1332
1505
|
// Live-server-preview manager (loopback dev-server allowlist + proxy).
|
|
1333
|
-
|
|
1506
|
+
// Ports the dashboard itself listens on are never previewable (a loopback origin is trusted
|
|
1507
|
+
// by its CORS / mutation gates). See change: improve-canvas-html-and-url-ux (D1).
|
|
1508
|
+
// Tier 3 pool (D5) + the proxy deps it forwards through: both late-bound (the manager's `ownPorts` reads the pool at seed time).
|
|
1509
|
+
let previewPool: PreviewPool | undefined;
|
|
1510
|
+
// Late-bound like `previewPool`: the observer is built with the dispatcher, after the store whose `onDelete` feeds it.
|
|
1511
|
+
let previewObserver: PreviewObserver | undefined;
|
|
1512
|
+
let liveProxyDepsRef: LiveProxyDeps | undefined;
|
|
1513
|
+
const liveServerManager = createLiveServerManager(preferencesStore, {
|
|
1514
|
+
ownPorts: () => {
|
|
1515
|
+
const tls = loadConfig().tls;
|
|
1516
|
+
// Pool ports (tier 3) are the dashboard's own: no target may point at one (D5).
|
|
1517
|
+
return [config.port, config.piPort, ...(tls?.enabled ? [tls.port] : []), ...(previewPool?.poolPorts() ?? [])];
|
|
1518
|
+
},
|
|
1519
|
+
});
|
|
1334
1520
|
|
|
1335
1521
|
// ACP host A (in-process): attach virtual connections to THIS gateway.
|
|
1336
1522
|
// See change: add-acp-session-driver (D1).
|
|
@@ -1347,7 +1533,35 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1347
1533
|
questionStore.loadPersisted();
|
|
1348
1534
|
questionStore.sweepAtBoot((sessionId) => persistedSessionPresence.get(sessionId) ?? "unknown");
|
|
1349
1535
|
|
|
1350
|
-
|
|
1536
|
+
// Shared roots for browse confinement + the remote folder gate (ONE definition).
|
|
1537
|
+
// Project-scope grants only: session-scope grants are transient.
|
|
1538
|
+
// See change: harden-server-capability-bounds (D2).
|
|
1539
|
+
const browseRootSources = buildBrowseRootSources({
|
|
1540
|
+
preferencesStore,
|
|
1541
|
+
sessionManager,
|
|
1542
|
+
worktreeRoots: () => listPersistedWorktreeTrust().map((t) => t.repoRoot),
|
|
1543
|
+
projectGrants: () => listAccessGrants().filter((g) => g.scope === "project").map((g) => g.subject),
|
|
1544
|
+
});
|
|
1545
|
+
// `browse.confineRemote: false` (operator opt-out, read at start) => `null` = unconfined.
|
|
1546
|
+
const confineRemoteBrowse = loadConfig().browse.confineRemote;
|
|
1547
|
+
const browseRoots = () => (confineRemoteBrowse ? resolveBrowseRoots(browseRootSources) : Promise.resolve(null));
|
|
1548
|
+
|
|
1549
|
+
const replayState = createReplayState(config.replayTimings);
|
|
1550
|
+
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);
|
|
1551
|
+
// A revoke closes every open socket of that device (4401 / `device revoked`): browser sockets (tagged at
|
|
1552
|
+
// upgrade from the ticket) and bridge sockets. See change: device-key-mutual-check (D7).
|
|
1553
|
+
pairedDeviceRegistry.onRevoked((deviceId) => {
|
|
1554
|
+
const closed = closeDeviceSockets(browserGateway.wss.clients, deviceId) + piGateway.closeDeviceSockets(deviceId);
|
|
1555
|
+
if (closed > 0) console.log(`[ws-gate] device revoke closed ${closed} socket(s)`);
|
|
1556
|
+
});
|
|
1557
|
+
// Transition-only feed behind `GET /api/events/stream` (registry frames + question changes).
|
|
1558
|
+
// See change: add-agent-event-stream.
|
|
1559
|
+
const agentEventHub = createAgentEventHub({
|
|
1560
|
+
listQuestionRows: () => questionStore.listRows(),
|
|
1561
|
+
ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
|
|
1562
|
+
});
|
|
1563
|
+
browserGateway.onRegistryFrame(agentEventHub.onRegistryFrame);
|
|
1564
|
+
questionStore.onChange(agentEventHub.onQuestionChange);
|
|
1351
1565
|
// App-wide pairing approval dialog: a content-free hint on every pending
|
|
1352
1566
|
// change; operator browsers refetch the guarded list (D1).
|
|
1353
1567
|
// See change: add-pairing-approval-dialog.
|
|
@@ -1373,21 +1587,6 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1373
1587
|
isViewed: (id) => browserGateway.viewedSessionTracker.isViewedByAnyone(id),
|
|
1374
1588
|
});
|
|
1375
1589
|
|
|
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
1590
|
|
|
1392
1591
|
// Resolve package version once at startup
|
|
1393
1592
|
const __require = createRequire(import.meta.url);
|
|
@@ -1501,6 +1700,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1501
1700
|
// death signal, even when no terminal pi event was forwarded.
|
|
1502
1701
|
// See change: finalize-automation-run-on-session-death.
|
|
1503
1702
|
const pluginSessionEndSubs = new Set<(sessionId: string) => void>();
|
|
1703
|
+
// Plugin status-ended subscribers (ServerPluginContext.onSessionStatusEnded). Fired
|
|
1704
|
+
// from sessionManager.onEnded via wireEvents on EVERY end transition (unregister,
|
|
1705
|
+
// status set to ended, end-reason re-fire; not a relocation). Handlers are idempotent.
|
|
1706
|
+
// See change: move-subagents-to-plugin (D4).
|
|
1707
|
+
const pluginSessionStatusEndSubs = new Set<(sessionId: string) => void>();
|
|
1708
|
+
// Post-boot plugin discovery (refreshPluginDiscovery + local-scope detection); built right
|
|
1709
|
+
// after the boot `loadServerEntries` pass. See change: decouple-plugins-from-core (5.5, 5.9).
|
|
1710
|
+
let pluginDiscovery: PluginDiscoveryWiring | undefined;
|
|
1504
1711
|
// Plugin shutdown subscribers (ServerPluginContext.onShutdown). Dispatched
|
|
1505
1712
|
// in server stop() at the exact point the goal supervisor disposes today —
|
|
1506
1713
|
// BEFORE piGateway.stop() tears bridges down — so plugin backoff timers /
|
|
@@ -1521,25 +1728,56 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1521
1728
|
// loader's topological order guarantees a provider's registerPlugin runs
|
|
1522
1729
|
// before a dependent's consume. In-process only.
|
|
1523
1730
|
// See change: register-plugin-automation-events.
|
|
1524
|
-
|
|
1731
|
+
// Records the PROVIDER plugin per key and enforces `automation.action.<source>`
|
|
1732
|
+
// key ownership (provider id MUST equal <source>). Host-set entries
|
|
1733
|
+
// (`.set`) carry provider "host". See change: harden-git-terminal-plugin-boundaries (D16).
|
|
1734
|
+
const pluginServiceRegistry = createPluginServiceRegistry();
|
|
1735
|
+
// Manifest `emits` per plugin, recorded at context creation. A plugin's types
|
|
1736
|
+
// count only while it is LOADED (status store, live), so an unloaded or
|
|
1737
|
+
// disabled provider's types leave every allowlist at once.
|
|
1738
|
+
const pluginManifestEmits = new Map<string, readonly string[]>();
|
|
1739
|
+
const loadedManifestEmits = (pluginId: string): readonly string[] | undefined =>
|
|
1740
|
+
getPluginStatusStore().getStatus(pluginId)?.loaded === true ? pluginManifestEmits.get(pluginId) : undefined;
|
|
1741
|
+
// Read-only lookup for the automation action registry's subset check.
|
|
1742
|
+
pluginServiceRegistry.set("host.pluginManifestEmits", loadedManifestEmits);
|
|
1525
1743
|
// Host-provided known-folder set for plugin cwd validation: session cwds ∪
|
|
1526
1744
|
// pinned directories, as a LIVE getter (not a boot-time snapshot) so plugins
|
|
1527
1745
|
// see folders added later. kb-plugin consumes this to guard its /api/kb/*
|
|
1528
1746
|
// routes against arbitrary-path indexing — a session-less worktree appears
|
|
1529
1747
|
// only via pinned dirs, unreachable from the plugin sessionManager surface.
|
|
1530
1748
|
// See change: add-kb-folder-slot.
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
return [...set];
|
|
1536
|
-
});
|
|
1749
|
+
// The ONE known-set function: core git/openspec/folder-project route admission uses it
|
|
1750
|
+
// too. See change: core-cwd-admission.
|
|
1751
|
+
const knownFolderCwds = (): string[] => listKnownFolderCwds({ sessionManager, preferencesStore });
|
|
1752
|
+
pluginServiceRegistry.set("host.knownFolderCwds", knownFolderCwds);
|
|
1537
1753
|
// `indeterminate` plugin cwd admissions (a git probe that did not complete)
|
|
1538
1754
|
// are worth a log line — today they are invisible — but throttled per cwd and
|
|
1539
1755
|
// LRU-bounded. Plugins pass this as `admitCwd`'s `onIndeterminate`.
|
|
1540
1756
|
// See change: harden-plugin-cwd-admission (D7).
|
|
1541
1757
|
const cwdAdmissionLogger = createIndeterminateLogger({ warn: (m) => console.warn(m) });
|
|
1542
1758
|
pluginServiceRegistry.set("host.cwdAdmissionOnIndeterminate", cwdAdmissionLogger);
|
|
1759
|
+
// Cwd admission of the file-family routes, live preview and `watch_files`: the same known set and
|
|
1760
|
+
// indeterminate logger as the plugin / git / openspec routes. See change: core-file-cwd-admission.
|
|
1761
|
+
const fileRouteAdmission: RouteAdmissionDeps = {
|
|
1762
|
+
knownCwds: knownFolderCwds,
|
|
1763
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
1764
|
+
};
|
|
1765
|
+
// Editor-pane changed-on-disk watch: the browser declares its open files via
|
|
1766
|
+
// `watch_files`; the server watches exactly those and pushes `file_changed`.
|
|
1767
|
+
// Torn down on disconnect so no fd leaks. See change: split-editor-workspace.
|
|
1768
|
+
// The cwd is admitted through the shared guard (change: core-file-cwd-admission).
|
|
1769
|
+
const watchFiles = createWatchFilesHandler({
|
|
1770
|
+
routeAdmission: fileRouteAdmission,
|
|
1771
|
+
manager: createFileWatchManager(),
|
|
1772
|
+
onChange: (sessionId, path) => browserGateway.broadcast({ type: "file_changed", sessionId, path }),
|
|
1773
|
+
});
|
|
1774
|
+
browserGateway.registerHandler("watch_files", (msg: WatchFilesMessage, ws) => {
|
|
1775
|
+
// The gateway does not await custom handlers: a rejection must not escape it.
|
|
1776
|
+
watchFiles.handle(msg, ws).catch((err: unknown) => {
|
|
1777
|
+
console.warn(`[watch_files] handler failed: ${(err as Error)?.message ?? err}`);
|
|
1778
|
+
});
|
|
1779
|
+
});
|
|
1780
|
+
browserGateway.registerDisconnectHandler((ws) => watchFiles.onDisconnect(ws));
|
|
1543
1781
|
// pi's project-trust rule as a SESSION applies it (recorded decision, else
|
|
1544
1782
|
// `defaultProjectTrust`), consumed by mcp-client to decide whether a
|
|
1545
1783
|
// folder's `.pi/mcp.json` is active. Resolved once; an unresolvable pi reads
|
|
@@ -1547,12 +1785,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1547
1785
|
// Durable dashboard trust is mirrored into pi's `project_trust` through a
|
|
1548
1786
|
// server-written snapshot (rebuilt now from the persisted stores, so a crash
|
|
1549
1787
|
// between a revoke's two writes heals at boot). See change: mirror-dashboard-trust-to-pi.
|
|
1788
|
+
// Server-lifetime ("live") trust: session worktree trust, session grants, YOLO
|
|
1789
|
+
// roots. Counted into the snapshot as `liveCount` only; the YOLO controller is
|
|
1790
|
+
// constructed further down, so it is read through a late-bound reference.
|
|
1791
|
+
// See change: mirror-dashboard-trust-live-remote.
|
|
1792
|
+
let yoloForLiveTrust: YoloController | undefined;
|
|
1793
|
+
const piTrustLive = createPiTrustLiveProvider({
|
|
1794
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
1795
|
+
listSessionTrust: listSessionWorktreeTrust,
|
|
1796
|
+
listSessionGrants: () => listAccessGrants().filter((g) => g.scope === "session"),
|
|
1797
|
+
getYolo: () => yoloForLiveTrust,
|
|
1798
|
+
});
|
|
1550
1799
|
const piTrustMirror = createPiTrustMirrorService({
|
|
1551
1800
|
getConfig: () => loadConfig().piTrustMirror,
|
|
1552
1801
|
listPinned: () => preferencesStore.getPinnedDirectories(),
|
|
1553
1802
|
listWorkspaceFolders: () => preferencesStore.getWorkspaces().flatMap((w) => w.folders),
|
|
1554
1803
|
listWorktreeTrust: listPersistedWorktreeTrust,
|
|
1555
1804
|
listPersistedGrants: () => listAccessGrants().filter((g) => g.scope === "project"),
|
|
1805
|
+
live: piTrustLive,
|
|
1556
1806
|
});
|
|
1557
1807
|
setPiTrustMirror(piTrustMirror);
|
|
1558
1808
|
try {
|
|
@@ -1575,6 +1825,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1575
1825
|
preferencesStore.onWorkspacesChanged(queueMirrorRefresh);
|
|
1576
1826
|
setGrantsChangedListener(queueMirrorRefresh);
|
|
1577
1827
|
setTrustChangedListener(queueMirrorRefresh);
|
|
1828
|
+
// Session entries never reach disk, so their listeners recompute the live count
|
|
1829
|
+
// synchronously (the snapshot is rewritten before the action reports success).
|
|
1830
|
+
setSessionGrantsChangedListener(() => piTrustMirror.noteLiveChanged());
|
|
1831
|
+
setSessionTrustChangedListener(() => piTrustMirror.noteLiveChanged());
|
|
1578
1832
|
const hostProjectTrust = await loadHostProjectTrustService();
|
|
1579
1833
|
pluginServiceRegistry.set("host.isProjectTrusted", hostProjectTrust.isProjectTrusted);
|
|
1580
1834
|
pluginServiceRegistry.set("host.projectTrustSource", hostProjectTrust.projectTrustSource);
|
|
@@ -1582,6 +1836,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1582
1836
|
// cwd-policy as the spawn funnel composes it, so the team plugin can refuse a
|
|
1583
1837
|
// start whose skill set the policy would narrow. See change: add-team-skill-access (D7).
|
|
1584
1838
|
pluginServiceRegistry.set("host.resolveCwdPolicy", (cwd: string) => cwdPolicyRegistry.resolve(cwd));
|
|
1839
|
+
// Authenticated loopback REST for plugins (fixed allowlist; per-request local proof, token never exposed).
|
|
1840
|
+
// See change: add-agent-teams-openspec (D4/D8).
|
|
1841
|
+
pluginServiceRegistry.set(HOST_LOCAL_REQUEST_KEY, createHostLocalRequest({ getToken: () => localToken, host: config.host, getPort: () => httpListenPort }));
|
|
1842
|
+
// `@role` default model: re-mirror into pi when its resolution moves (roles
|
|
1843
|
+
// watcher calls this), and expose the ref for the Roles "used by" list.
|
|
1844
|
+
// See change: default-model-follows-role (D4, D5).
|
|
1845
|
+
const piDefaultRemirror = createPiDefaultRemirror({ readDashboardConfig: loadConfig });
|
|
1846
|
+
piDefaultRemirror.seed();
|
|
1847
|
+
setActivePiDefaultRemirror(piDefaultRemirror);
|
|
1848
|
+
pluginServiceRegistry.set("host.remirrorPiDefaults", () => piDefaultRemirror.remirror());
|
|
1849
|
+
pluginServiceRegistry.set("host.defaultModelRef", () => piDefaultRemirror.defaultModelRef());
|
|
1585
1850
|
// Operator-visible (global + global-package) skills for the team plugin's
|
|
1586
1851
|
// admin skill picker. Never project-local. See change: add-team-skill-access (D11).
|
|
1587
1852
|
pluginServiceRegistry.set("host.listOperatorSkills", async () =>
|
|
@@ -1597,9 +1862,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1597
1862
|
// `onRequest` hook — `/mcp` deliberately does not trust
|
|
1598
1863
|
// `request.isAuthenticated`, so it needs the registry directly.
|
|
1599
1864
|
// See change: add-dashboard-mcp-server.
|
|
1865
|
+
const deviceTokenServices = createDeviceTokenServices(pairedDeviceRegistry);
|
|
1600
1866
|
pluginServiceRegistry.set(
|
|
1601
1867
|
"host.verifyDeviceToken",
|
|
1602
|
-
(
|
|
1868
|
+
// The request is optional (the plugin host services receive none today): absent → non-proven, fail closed.
|
|
1869
|
+
deviceTokenServices.verifyDeviceToken,
|
|
1603
1870
|
);
|
|
1604
1871
|
// Tier-aware service board entry (change: expand-mcp-tiered-surface, D1).
|
|
1605
1872
|
// A NEW key, not a signature change to the old one: `mcp-server-plugin` is
|
|
@@ -1608,7 +1875,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1608
1875
|
// `host.verifyDeviceToken` with `tier: "operate"`.
|
|
1609
1876
|
pluginServiceRegistry.set(
|
|
1610
1877
|
"host.verifyDeviceTokenTier",
|
|
1611
|
-
|
|
1878
|
+
deviceTokenServices.verifyDeviceTokenTier,
|
|
1612
1879
|
);
|
|
1613
1880
|
// Prefers the BOUND port, falls back to the CONFIGURED one.
|
|
1614
1881
|
//
|
|
@@ -1638,11 +1905,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1638
1905
|
// Private plugin request/reply lane: one handler per (pluginId, type), reply
|
|
1639
1906
|
// sent host-internally on the requesting socket (not the priority-gated
|
|
1640
1907
|
// sendExtensionMessage). See change: expose-plugin-credential-and-oauth-seams (D7).
|
|
1641
|
-
const pluginRequestLane = createPluginRequestLane(
|
|
1642
|
-
piGateway.sendToSession(sessionId, msg),
|
|
1908
|
+
const pluginRequestLane = createPluginRequestLane(
|
|
1909
|
+
(sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
1910
|
+
// A hub-local-only reply is delivered only to the socket that passed the gate (see the lane).
|
|
1911
|
+
{ currentChannel: (sessionId) => piGateway.channelOf(sessionId) },
|
|
1643
1912
|
);
|
|
1644
|
-
|
|
1645
|
-
|
|
1913
|
+
// Forward the SENDING socket's own origin + channel (never `originOf(sessionManager.get(id))` /
|
|
1914
|
+
// `channelOf(id)`, which follow the routing entry and the recorded session, not the sender).
|
|
1915
|
+
// See change: harden-bridge-session-claim (D3).
|
|
1916
|
+
function dispatchPluginRequest(sessionId: string, msg: PluginRequestMessage, conn?: GatewayConn): void {
|
|
1917
|
+
pluginRequestLane.handle(sessionId, msg, conn).catch((err) => {
|
|
1646
1918
|
console.error("[plugin-request]", err);
|
|
1647
1919
|
});
|
|
1648
1920
|
}
|
|
@@ -1657,6 +1929,37 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1657
1929
|
for (const h of pluginSessionEndSubs) {
|
|
1658
1930
|
try { h(sessionId); } catch (err) { console.error("[plugin-onSessionEnded]", err); }
|
|
1659
1931
|
}
|
|
1932
|
+
pluginDiscovery?.onSessionEnded();
|
|
1933
|
+
}
|
|
1934
|
+
// Record what a loaded plugin owns (manifest `eventTypes`, tool-renderer claims) so the
|
|
1935
|
+
// store/delivery policies it registers apply to its own types and claimed tools only.
|
|
1936
|
+
// Reuses the bridge ownership table builder. See change: move-subagents-to-plugin (D1, D3).
|
|
1937
|
+
function recordPluginPolicyOwnership(plugin: Parameters<typeof buildPluginOwnership>[0][number]): void {
|
|
1938
|
+
const own = buildPluginOwnership([plugin]);
|
|
1939
|
+
getPluginPolicyRegistry().setOwnership(plugin.manifest.id, {
|
|
1940
|
+
eventTypes: Object.keys(own.eventTypes),
|
|
1941
|
+
tools: Object.keys(own.toolClaims),
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
function dispatchPluginSessionStatusEnded(sessionId: string): void {
|
|
1945
|
+
for (const h of pluginSessionStatusEndSubs) {
|
|
1946
|
+
try { h(sessionId); } catch (err) { console.error("[plugin-onSessionStatusEnded]", err); }
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
// ctx.appendEvent: store + broadcast an event of a type the calling plugin owns
|
|
1950
|
+
// (manifest `eventTypes`); store WITHOUT broadcast while the session replays,
|
|
1951
|
+
// like the core tool-call heal. Anything else is refused and counted, never thrown.
|
|
1952
|
+
// See change: move-subagents-to-plugin (D4).
|
|
1953
|
+
const appendPluginOwnedEvent = createPluginEventAppender({
|
|
1954
|
+
registry: getPluginPolicyRegistry,
|
|
1955
|
+
eventStore,
|
|
1956
|
+
isReplaying: (sessionId) => replayState.controller.replayingSessions.has(sessionId),
|
|
1957
|
+
broadcastEvent: (sessionId, seq, event) => browserGateway.broadcastEvent(sessionId, seq, event),
|
|
1958
|
+
});
|
|
1959
|
+
// A bridge registered: a cwd not yet scanned may carry local-scope plugins. Deferred one tick so the
|
|
1960
|
+
// session is in the manager's active list. See change: decouple-plugins-from-core (task 5.9).
|
|
1961
|
+
function dispatchSessionRegisteredCwd(cwd: string): void {
|
|
1962
|
+
setImmediate(() => pluginDiscovery?.onSessionRegistered(cwd));
|
|
1660
1963
|
}
|
|
1661
1964
|
// Notify a resolved session's OWNING plugin only. Routed by ownerId so no
|
|
1662
1965
|
// plugin sees another's ref. See change: detach-automation-goal-from-core.
|
|
@@ -1727,7 +2030,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1727
2030
|
// Credential vault: store + delivery hub. The hub answers bridge sync
|
|
1728
2031
|
// requests and pushes on every vault write / config change; values travel only
|
|
1729
2032
|
// on the session-private bridge lane. See change: add-credential-vault.
|
|
1730
|
-
const vaultStore = createVaultStore();
|
|
2033
|
+
const vaultStore = createVaultStore({ codec: getCredentialCodec("vault") });
|
|
1731
2034
|
// ACME DNS-01 certificate source: solver secrets live in this vault (kind `tls-solver`).
|
|
1732
2035
|
// GC of orphaned namespaces/account keys runs once at start. See change: add-acme-dns01-certs.
|
|
1733
2036
|
configureAcmeRuntime({ credentials: createAcmeCredentials(vaultStore) });
|
|
@@ -1745,10 +2048,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1745
2048
|
isSessionConnected: (sessionId) => piGateway.getConnectedSessionIds().includes(sessionId),
|
|
1746
2049
|
isDeliveryEnabled: () => loadConfig().vault.deliveryEnabled,
|
|
1747
2050
|
getGraceHours: () => loadConfig().vault.offlineGraceHours,
|
|
2051
|
+
// What the hub itself observed about each socket, and the registry's view of the device behind it
|
|
2052
|
+
// (prove-vault-bridge-tls D3-D5). A TLS-admitted channel also needs the switch live-on.
|
|
2053
|
+
getChannel: (sessionId) => piGateway.channelOf(sessionId),
|
|
2054
|
+
getDeviceTrust: (deviceId) => pairedDeviceRegistry.deviceTrust(deviceId),
|
|
2055
|
+
isTlsBridgesLive: tlsBridgesLive,
|
|
2056
|
+
exposurePending: () => pairedDeviceRegistry.exposurePending(),
|
|
1748
2057
|
});
|
|
2058
|
+
// Sudo credential prompt: in-memory relay (never persists a password); the bridge must also pass the
|
|
2059
|
+
// vault trust predicate. See change: add-sudo-credential-prompt.
|
|
2060
|
+
const sudoCredential = createSudoCredentialRelay({
|
|
2061
|
+
browsers: browserGateway.sudoSeam,
|
|
2062
|
+
sendToBridge: (sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
2063
|
+
isBridgeTrusted: (sessionId) => vaultDelivery.isBridgeTrusted(sessionId),
|
|
2064
|
+
});
|
|
2065
|
+
browserGateway.setSudoCredentialRelay(sudoCredential);
|
|
2066
|
+
onVaultRoutingChanged = (sessionId, declared) => vaultDelivery.handleRegister(sessionId, declared);
|
|
2067
|
+
// Revoke, rotation, add and a first plaintext exposure withdraw within the push debounce (~150 ms).
|
|
2068
|
+
pairedDeviceRegistry.onChange(() => vaultDelivery.schedulePush());
|
|
2069
|
+
// Time-based expiry has no event: a 30 s sweep pushes only when a device LEFT the active set.
|
|
2070
|
+
const stopDeviceExpirySweep = startDeviceExpirySweep({
|
|
2071
|
+
activeIds: () => pairedDeviceRegistry.activeIds(),
|
|
2072
|
+
onLeft: () => vaultDelivery.schedulePush(),
|
|
2073
|
+
});
|
|
2074
|
+
// Manifest ownership sent to every bridge on register + checked on event_forward ingest.
|
|
2075
|
+
// Built eagerly once: the first discovery is a synchronous scan the register path must not pay.
|
|
2076
|
+
// See change: move-subagents-to-plugin (D1).
|
|
2077
|
+
const pluginOwnership = createPluginOwnership(() => discoverPlugins());
|
|
2078
|
+
pluginOwnership.table();
|
|
1749
2079
|
wireEvents({
|
|
2080
|
+
pluginOwnership,
|
|
2081
|
+
replayState,
|
|
1750
2082
|
inFlightToolCalls,
|
|
1751
2083
|
vaultDelivery,
|
|
2084
|
+
sudoCredential,
|
|
1752
2085
|
// Lazy: `yolo` is constructed further down; a pre-init call throws and the
|
|
1753
2086
|
// handler declines. See change: yolo-covers-agent-path-gate.
|
|
1754
2087
|
decideAgentPath: (p) =>
|
|
@@ -1756,8 +2089,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1756
2089
|
path: p,
|
|
1757
2090
|
hostGateMode: resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
1758
2091
|
}),
|
|
1759
|
-
onBridgeRegister: (sid, identity) => {
|
|
1760
|
-
const outcome = extensionReloadGuard.onRegister(sid, identity);
|
|
2092
|
+
onBridgeRegister: (sid, identity, sessionFile) => {
|
|
2093
|
+
const outcome = extensionReloadGuard.onRegister(sid, identity, sessionFile);
|
|
1761
2094
|
if (outcome !== "skipped") {
|
|
1762
2095
|
console.log(`[runtime-overlay] bridge register session=${sid} extension=${identity?.dir ?? "(none)"} outcome=${outcome}`);
|
|
1763
2096
|
}
|
|
@@ -1788,8 +2121,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1788
2121
|
pendingPromptAcks,
|
|
1789
2122
|
dispatchPluginPiMessage,
|
|
1790
2123
|
dispatchPluginRequest,
|
|
2124
|
+
// D9: the bridge reserve-path pair; late-bound (the stores are built after `wireEvents`).
|
|
2125
|
+
previewPathBridge: () =>
|
|
2126
|
+
previewPaths
|
|
2127
|
+
? {
|
|
2128
|
+
reserve: {
|
|
2129
|
+
store: previewPaths,
|
|
2130
|
+
hasTier5Viewer: () => hasTier5Viewer(browserGateway.wss.clients),
|
|
2131
|
+
portRefusal: (port) => liveServerManager.portRefusal(port),
|
|
2132
|
+
},
|
|
2133
|
+
deviceTier: (deviceId) => pairedDeviceRegistry.list().find((d) => d.id === deviceId)?.tier,
|
|
2134
|
+
isSessionLive: (id) => piGateway.getConnectedSessionIds().includes(id),
|
|
2135
|
+
}
|
|
2136
|
+
: undefined,
|
|
1791
2137
|
dispatchPluginRawEvent,
|
|
1792
2138
|
dispatchPluginSessionEnded,
|
|
2139
|
+
dispatchPluginSessionStatusEnded,
|
|
2140
|
+
dispatchSessionRegisteredCwd,
|
|
1793
2141
|
metaPersistence,
|
|
1794
2142
|
liveEpoch,
|
|
1795
2143
|
commitDraftRelay,
|
|
@@ -1819,8 +2167,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1819
2167
|
onParentDead: () => server.stop({ exitIntent: "ephemeral" }),
|
|
1820
2168
|
});
|
|
1821
2169
|
|
|
2170
|
+
// Preview-shaped Hosts are answered by the route-less `previewApp` and never enter the dashboard app (D3).
|
|
2171
|
+
// Late-bound: the capability store the dispatch needs is built further down, before `listen`.
|
|
2172
|
+
// See change: serve-live-previews-on-capability-origin.
|
|
2173
|
+
let previewDispatch: PreviewDispatch | undefined;
|
|
2174
|
+
// Tier-5 pid store; late-bound like `previewDispatch` (the preflight hook is registered before the store exists).
|
|
2175
|
+
let previewPaths: PreviewPathStore | undefined;
|
|
1822
2176
|
const fastify = Fastify({
|
|
1823
2177
|
logger: false,
|
|
2178
|
+
serverFactory: previewServerFactory(() => previewDispatch) as never,
|
|
1824
2179
|
keepAliveTimeout: MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
1825
2180
|
connectionTimeout: MAIN_CONNECTION_TIMEOUT_MS,
|
|
1826
2181
|
// Add-ons feature ids embed a local package's absolute path (`pkg:local:/…`), which exceeds
|
|
@@ -1958,9 +2313,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1958
2313
|
bindHost: config.host,
|
|
1959
2314
|
// Exact certificate names of the TLS listener (empty unless enabled + bound).
|
|
1960
2315
|
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
2316
|
+
// The `live preview capability hosts` pattern row (D3): present whenever previews are on.
|
|
2317
|
+
livePreviewEnabled: () => getResolvedPreviewOrigins().enabled,
|
|
1961
2318
|
},
|
|
1962
2319
|
...resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()),
|
|
1963
2320
|
});
|
|
2321
|
+
// Inputs of the preview-origin overlap checks (D12): live tunnels, TLS names and the static
|
|
2322
|
+
// admission classifier, so a label-shaped host that is already admitted is never shaped as a preview.
|
|
2323
|
+
setPreviewOriginsRuntime({
|
|
2324
|
+
tunnelOrigins: liveTunnelOrigins,
|
|
2325
|
+
tlsNames: () => tlsListener.tlsListenerNames(),
|
|
2326
|
+
classifyAdmittedHostname: (hostname) => classifyAdmittedHostname(hostname, getHostGateCtx().admission),
|
|
2327
|
+
});
|
|
1964
2328
|
/**
|
|
1965
2329
|
* The ONE origin-policy input, shared by the CORS plugin, the WS upgrade gate
|
|
1966
2330
|
* and the mutating-REST gate. Built per decision (never captured) so tunnel
|
|
@@ -1981,6 +2345,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1981
2345
|
// which single origin we mint OAuth URIs and set cookies for.
|
|
1982
2346
|
// See change: add-zrok-custom-reserved-name (D4).
|
|
1983
2347
|
getLiveTunnelOrigins: liveTunnelOrigins,
|
|
2348
|
+
// Opt-in zrok wildcard for CORS READS only (B19); admission forces it off.
|
|
2349
|
+
allowZrokWildcard: liveCorsAllowZrokWildcard(),
|
|
1984
2350
|
allowedHosts: liveAllowedHosts(),
|
|
1985
2351
|
publicBaseUrls: livePublicBaseUrls(),
|
|
1986
2352
|
bindHost: config.host,
|
|
@@ -2015,6 +2381,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2015
2381
|
grantPlanes.register(
|
|
2016
2382
|
createCorsPlane({ readRawCors: () => (readRawConfig().cors ?? {}) as Record<string, unknown>, writeConfigPartial }),
|
|
2017
2383
|
);
|
|
2384
|
+
// Preview egress: an external https origin a restricted live preview may load, granted per project.
|
|
2385
|
+
// The dashboard's own origins (tunnels, public base URLs, configured CORS origins) are never grantable.
|
|
2386
|
+
// See change: improve-canvas-html-and-url-ux (D7).
|
|
2387
|
+
const previewEgressOwnOrigins = (): string[] =>
|
|
2388
|
+
[getTunnelUrl(), ...liveTunnelOrigins(), ...livePublicBaseUrls(), ...corsAllowedOrigins()].flatMap((u) => {
|
|
2389
|
+
try {
|
|
2390
|
+
return typeof u === "string" && u ? [new URL(u).origin] : [];
|
|
2391
|
+
} catch {
|
|
2392
|
+
return [];
|
|
2393
|
+
}
|
|
2394
|
+
});
|
|
2395
|
+
grantPlanes.register(createPreviewEgressPlane({ ownOrigins: previewEgressOwnOrigins }));
|
|
2018
2396
|
// YOLO (design D13): consulted at the prompt point; the refusal ledger stops it
|
|
2019
2397
|
// reversing an explicit deny. Environment activation is attempted once, at
|
|
2020
2398
|
// boot, and refused outright in report mode or on any unusable root.
|
|
@@ -2022,6 +2400,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2022
2400
|
hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
2023
2401
|
isRefused,
|
|
2024
2402
|
});
|
|
2403
|
+
yoloForLiveTrust = yolo;
|
|
2404
|
+
yolo.setChangeListener(() => piTrustMirror.noteLiveChanged());
|
|
2025
2405
|
const yoloBoot = yolo.activateFromEnv(process.env[YOLO_ENV]);
|
|
2026
2406
|
if (yoloBoot.ok) {
|
|
2027
2407
|
const s = yoloBoot.session;
|
|
@@ -2053,6 +2433,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2053
2433
|
console.error(`[access-grant] grant_response failed: ${(err as Error)?.message ?? err}`);
|
|
2054
2434
|
});
|
|
2055
2435
|
});
|
|
2436
|
+
// Access provisioning (change: add-access-provisioning): the registry wired to the gateway's
|
|
2437
|
+
// operator sockets (live capability AND operate tier), with its per-request expiry timers.
|
|
2438
|
+
const provisioning = installProvisioning({
|
|
2439
|
+
gateway: browserGateway,
|
|
2440
|
+
deps: {
|
|
2441
|
+
now: Date.now,
|
|
2442
|
+
grants: createDefaultProvisioningGrantStore(),
|
|
2443
|
+
// Same two calls as `storePiTrustChoiceOfVerdict`: store the choice, then refresh the snapshot.
|
|
2444
|
+
mirror: () => ({
|
|
2445
|
+
setChoice: (kind, folder, choice) => {
|
|
2446
|
+
piTrustMirror.setChoice(kind, folder, choice);
|
|
2447
|
+
piTrustMirror.refresh();
|
|
2448
|
+
},
|
|
2449
|
+
}),
|
|
2450
|
+
ladder: {
|
|
2451
|
+
killSwitch: () => isGrantPromptKilled(),
|
|
2452
|
+
promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
|
|
2453
|
+
hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
2454
|
+
},
|
|
2455
|
+
},
|
|
2456
|
+
});
|
|
2457
|
+
browserGateway.registerHandler("provision_response", provisioning.onResponse);
|
|
2458
|
+
// REST refusals whose only fault is missing local proof: one bounded line per (route, reason) per window.
|
|
2459
|
+
// See change: close-container-loopback-impersonation (D6).
|
|
2460
|
+
const localProofRefusalLog = createLocalProofRefusalLogger();
|
|
2461
|
+
setLocalProofRefusalObserver((request) =>
|
|
2462
|
+
localProofRefusalLog.log({
|
|
2463
|
+
peer: request.ip,
|
|
2464
|
+
host: request.headers.host,
|
|
2465
|
+
method: request.method,
|
|
2466
|
+
route: request.routeOptions?.url,
|
|
2467
|
+
reason: "local_proof_required",
|
|
2468
|
+
}),
|
|
2469
|
+
);
|
|
2056
2470
|
setNetworkDenialObserver((request) => {
|
|
2057
2471
|
// `pair`: a network match grants nothing, so a denial is not a trust request
|
|
2058
2472
|
// — the block event is still recorded (by the guard), but no network prompt
|
|
@@ -2075,6 +2489,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2075
2489
|
// Origin at all). Report-only default; `PI_DASHBOARD_HOST_GATE=enforce`
|
|
2076
2490
|
// or `hostGate.mode` flips it. See change: add-host-allowlist-admission (D1).
|
|
2077
2491
|
fastify.addHook("onRequest", createHostGate(getHostGateCtx, hostGateState, () => config.port));
|
|
2492
|
+
// Duplicate `pi_dash_*` cookie names → self-healing 400, directly after the host gate and before the CORS
|
|
2493
|
+
// observer / `@fastify/cors`, so the refusal carries no ACAO and precedes every origin gate. previewApp is exempt
|
|
2494
|
+
// by construction (own Fastify instance). See change: serve-live-previews-on-capability-origin (D10).
|
|
2495
|
+
fastify.addHook("onRequest", createDuplicateCookieGate());
|
|
2496
|
+
// Tier-5 opaque-origin preflight: answered for a VALID `/preview/<pid>/` before `@fastify/cors` denies `null` (D8, P6).
|
|
2497
|
+
fastify.addHook("onRequest", createPreviewPreflight(() => previewPaths));
|
|
2078
2498
|
// A denied cross-origin Origin may raise a DEFERRED cors-plane prompt; after
|
|
2079
2499
|
// the host gate so a host-refused request never prompts. Never alters the
|
|
2080
2500
|
// response. See change: add-access-grant-dialog.
|
|
@@ -2126,7 +2546,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2126
2546
|
// `PI_DASHBOARD_CSP=enforce` flips to enforcing once report-only is clean.
|
|
2127
2547
|
// Skips proxied prefixes (/editor, /live) so their own policies stand.
|
|
2128
2548
|
// See change: improve-content-editor (§7).
|
|
2129
|
-
|
|
2549
|
+
// Trusted Types rides the same hook under its own `PI_DASHBOARD_TRUSTED_TYPES`
|
|
2550
|
+
// mode (also stamped into index.html as a meta). See change: harden-client-sinks (D7).
|
|
2551
|
+
const cspMode = resolveCspMode(process.env.PI_DASHBOARD_CSP);
|
|
2552
|
+
// Resolved ONCE (env → config `security.trustedTypes` → default); the same value feeds the headers and the
|
|
2553
|
+
// index.html meta. Each bad source warns once here, never per request. See change: enforce-trusted-types-default.
|
|
2554
|
+
const ttResolution = resolveTrustedTypesMode({
|
|
2555
|
+
env: process.env.PI_DASHBOARD_TRUSTED_TYPES,
|
|
2556
|
+
config: loadConfig().security?.trustedTypes,
|
|
2557
|
+
cspMode,
|
|
2558
|
+
});
|
|
2559
|
+
for (const w of ttResolution.warnings) console.warn(`[csp] Trusted Types: ${w.message}`);
|
|
2560
|
+
const trustedTypesMode = ttResolution.mode;
|
|
2561
|
+
registerCsp(fastify, cspMode, trustedTypesMode);
|
|
2130
2562
|
|
|
2131
2563
|
// Register auth plugin if configured (must be before routes)
|
|
2132
2564
|
// Decorate isAuthenticated once, up front, so both the bearer branch and the
|
|
@@ -2146,18 +2578,114 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2146
2578
|
// there. It admits ONLY a valid `/live/<id>/~c/<token>/…` raw path.
|
|
2147
2579
|
// Liveness is re-checked at every use, so a revoked device, an ended session
|
|
2148
2580
|
// or a removed target is refused on its next request.
|
|
2581
|
+
// Late-bound live accessor from the auth plugin handle (built below): an OAuth session of a
|
|
2582
|
+
// removed / refused-public-IdP provider is not live. See change: close-security-map-high-findings (D3).
|
|
2583
|
+
let sessionProviderRejectedAccessor: ((provider: unknown) => boolean) | null = null;
|
|
2584
|
+
const sessionProviderRejected = (provider: unknown): boolean => sessionProviderRejectedAccessor?.(provider) ?? false;
|
|
2585
|
+
const capabilityPrincipalLive = (p: import("./live-server/live-capability.js").CapabilityPrincipal): boolean => {
|
|
2586
|
+
if (p.identityExpiresAt !== undefined && p.identityExpiresAt <= Date.now()) return false;
|
|
2587
|
+
// Minted on network trust alone: only valid while network trust still authenticates.
|
|
2588
|
+
if (p.kind === "network") return effectiveTrustMode().mode === "legacy";
|
|
2589
|
+
if (p.kind === "device") return pairedDeviceRegistry.list().some((d) => d.id === p.deviceId);
|
|
2590
|
+
if (p.kind === "session" && p.session) return effectiveSessionTier(p.session, passkeyService, sessionProviderRejected) !== null;
|
|
2591
|
+
return true;
|
|
2592
|
+
};
|
|
2593
|
+
// Tier 3 pool (D5): the store's `onDelete` closes the listener of a deleted entry on EVERY deletion path.
|
|
2594
|
+
// Late-bound (`previewPool` is built just below the store it reads).
|
|
2149
2595
|
const liveCapabilities = new LiveCapabilityStore({
|
|
2150
|
-
isTargetLive: (id) => liveServerManager.
|
|
2151
|
-
isPrincipalLive:
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
if (
|
|
2156
|
-
|
|
2157
|
-
|
|
2596
|
+
isTargetLive: (id) => liveServerManager.has(id),
|
|
2597
|
+
isPrincipalLive: capabilityPrincipalLive,
|
|
2598
|
+
onDelete: (entry, reason) => {
|
|
2599
|
+
previewPool?.onDelete(entry, reason);
|
|
2600
|
+
// The entry is gone: drop its "first admit" bookkeeping so observer state tracks live entries (D13, no leak across churn).
|
|
2601
|
+
if (entry.label) previewObserver?.forget(previewLogHash(entry.label));
|
|
2602
|
+
},
|
|
2603
|
+
getPreviewConfig: () => getResolvedPreviewOrigins(),
|
|
2604
|
+
});
|
|
2605
|
+
previewPool = createPreviewPool({
|
|
2606
|
+
range: () => {
|
|
2607
|
+
const r = getResolvedPreviewOrigins();
|
|
2608
|
+
return r.enabled ? r.pool : undefined;
|
|
2158
2609
|
},
|
|
2610
|
+
bindHost: () => config.host,
|
|
2611
|
+
findByPoolPort: (port) => liveCapabilities.findByPoolPort(port),
|
|
2612
|
+
revokeByPoolPort: (port, reason) => liveCapabilities.revokeByPoolPort(port, reason),
|
|
2613
|
+
touch: (grant) => void liveCapabilities.touch(grant.tokenId, grant.minterKey),
|
|
2614
|
+
manager: liveServerManager,
|
|
2615
|
+
proxyDeps: () => liveProxyDepsRef,
|
|
2159
2616
|
});
|
|
2160
|
-
|
|
2617
|
+
// Tier 5 (`/preview/<pid>/`, D8): one current pid per port target; liveness is re-checked at every use, so a revoked
|
|
2618
|
+
// holder / removed target / disabled previews drops the pid on its next request or sweep.
|
|
2619
|
+
const previewWs = createPreviewWsRegistry();
|
|
2620
|
+
previewPaths = new PreviewPathStore({
|
|
2621
|
+
onDrop: (reason, pid) => {
|
|
2622
|
+
liveLog(undefined, "pid dropped", { reason, h: previewLogHash(pid) });
|
|
2623
|
+
previewWs.closePid(pid); // in-flight HMR sockets die with the pid
|
|
2624
|
+
},
|
|
2625
|
+
targetIdForPort: (port) => liveServerManager.getByPort(port)?.id,
|
|
2626
|
+
isPortAllowed: (port) => liveServerManager.portRefusal(port) === null,
|
|
2627
|
+
isTargetLive: (id) => liveServerManager.has(id),
|
|
2628
|
+
isPrincipalLive: capabilityPrincipalLive,
|
|
2629
|
+
isEnabled: () => getResolvedPreviewOrigins().enabled,
|
|
2630
|
+
});
|
|
2631
|
+
previewPaths.start();
|
|
2632
|
+
// An evicted preset / static target takes its tokens with it.
|
|
2633
|
+
liveServerManager.setEvictionListener((id) => {
|
|
2634
|
+
liveCapabilities.revokeByTarget(id);
|
|
2635
|
+
previewPaths?.revokeByTarget(id);
|
|
2636
|
+
});
|
|
2637
|
+
// Per-token egress state (markup scan, CSP reports, allow-once, project grants). Project grants are read
|
|
2638
|
+
// from their store on every CSP build, so a grant or revoke applies on the next response with no restart.
|
|
2639
|
+
const previewEgress = createPreviewEgress({
|
|
2640
|
+
getStatic: (id) => liveServerManager.getStatic(id),
|
|
2641
|
+
presetCwdOf: (id) => {
|
|
2642
|
+
const sessionId = liveServerManager.presetSessionOf(id);
|
|
2643
|
+
return sessionId ? sessionManager.get(sessionId)?.cwd : undefined;
|
|
2644
|
+
},
|
|
2645
|
+
projectKeyOf: (cwd) => {
|
|
2646
|
+
let real = cwd;
|
|
2647
|
+
try {
|
|
2648
|
+
real = realpathSync(cwd);
|
|
2649
|
+
} catch {
|
|
2650
|
+
/* keep the stated cwd */
|
|
2651
|
+
}
|
|
2652
|
+
return resolveMainPath(real) ?? real;
|
|
2653
|
+
},
|
|
2654
|
+
projectGrants: projectEgressGrants,
|
|
2655
|
+
allowOnce: (viewerId) => liveCapabilities.getAllowOnce(viewerId),
|
|
2656
|
+
ownOrigins: previewEgressOwnOrigins,
|
|
2657
|
+
});
|
|
2658
|
+
// Preview exposure (is the dashboard reachable from anywhere but this machine?). Drives the
|
|
2659
|
+
// scripts rule on restricted mints; a flip to `exposed` kills restricted scripted local-only
|
|
2660
|
+
// tokens and tells open viewers to re-mint. See change: improve-canvas-html-and-url-ux (D5).
|
|
2661
|
+
const previewExposure = createPreviewExposure({
|
|
2662
|
+
getBindHost: () => config.host,
|
|
2663
|
+
getEndpoints: () =>
|
|
2664
|
+
collectEndpoints({
|
|
2665
|
+
providerEndpoints: [getTunnelUrl(), ...liveTunnelOrigins()]
|
|
2666
|
+
.filter((u): u is string => typeof u === "string" && u.length > 0)
|
|
2667
|
+
.map((url) => ({ kind: "public" as const, url, tls: url.startsWith("https://") })),
|
|
2668
|
+
publicBaseUrls: livePublicBaseUrls(),
|
|
2669
|
+
port: config.port,
|
|
2670
|
+
tlsEndpoints: tlsListener.tlsListenerUrls(),
|
|
2671
|
+
includeLocal: false,
|
|
2672
|
+
}).map((e) => e.url),
|
|
2673
|
+
getConfigOverride: livePreviewExposureOverride,
|
|
2674
|
+
});
|
|
2675
|
+
wirePreviewExposure({
|
|
2676
|
+
exposure: previewExposure,
|
|
2677
|
+
capabilities: liveCapabilities,
|
|
2678
|
+
broadcast: (epoch) => browserGateway.broadcastToAll({ type: "preview_exposure_changed", epoch }),
|
|
2679
|
+
});
|
|
2680
|
+
// Detect the flip even when no request arrives (a tunnel connecting), within the viewers' 2 s budget.
|
|
2681
|
+
const previewExposureTimer = setInterval(() => previewExposure.current(), 1000);
|
|
2682
|
+
previewExposureTimer.unref();
|
|
2683
|
+
fastify.addHook("onClose", async () => clearInterval(previewExposureTimer));
|
|
2684
|
+
// A request carrying a forwarding header pins the exposure to `exposed` until restart (fails closed).
|
|
2685
|
+
fastify.addHook("onRequest", async (request) => {
|
|
2686
|
+
previewExposure.noteRequest(request.headers as Record<string, unknown>);
|
|
2687
|
+
});
|
|
2688
|
+
fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities, previewPaths));
|
|
2161
2689
|
registerBearerAuth(fastify, { registry: pairedDeviceRegistry });
|
|
2162
2690
|
registerDeviceSessionRoutes(fastify, {
|
|
2163
2691
|
registry: pairedDeviceRegistry,
|
|
@@ -2247,7 +2775,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2247
2775
|
passkeyService.configure(config.authConfig);
|
|
2248
2776
|
let oauthLoginAccessor: (() => boolean) | null = null;
|
|
2249
2777
|
if (config.authConfig) {
|
|
2250
|
-
|
|
2778
|
+
const authHandle = await registerAuthPlugin(fastify, {
|
|
2251
2779
|
authConfig: config.authConfig,
|
|
2252
2780
|
port: config.port,
|
|
2253
2781
|
resolvedTrustedNetworks: config.resolvedTrustedNetworks,
|
|
@@ -2256,7 +2784,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2256
2784
|
localToken,
|
|
2257
2785
|
localTrust,
|
|
2258
2786
|
passkeys: passkeyService,
|
|
2259
|
-
|
|
2787
|
+
// Close open browser + terminal sockets whose session the reload revoked (D3, G7-G10).
|
|
2788
|
+
onAuthReloaded: () => {
|
|
2789
|
+
sweepRevokedSockets({ browser: browserGateway.wss, terminal: terminalGateway.wss });
|
|
2790
|
+
},
|
|
2791
|
+
});
|
|
2792
|
+
oauthLoginAccessor = authHandle.hasUsableOAuthProvider;
|
|
2793
|
+
sessionProviderRejectedAccessor = authHandle.isSessionProviderRejected;
|
|
2260
2794
|
}
|
|
2261
2795
|
// Live "is a usable login method configured" (drives the `sign-in` remedy of an
|
|
2262
2796
|
// `operate_required` refusal). See change: surface-operate-required-remedy.
|
|
@@ -2363,6 +2897,21 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2363
2897
|
{ localToken, localTrust },
|
|
2364
2898
|
);
|
|
2365
2899
|
|
|
2900
|
+
// `/api/health` `networkAccess` verdict: the REST pass predicate evaluated purely
|
|
2901
|
+
// (no telemetry / block events). The admission list goes through a 1 s TTL memo so
|
|
2902
|
+
// attacker-paced health requests cost at most one config `statSync` per second.
|
|
2903
|
+
// See change: surface-network-denial-on-health (D2).
|
|
2904
|
+
let verdictList: { at: number; list: string[] } | undefined;
|
|
2905
|
+
const memoAdmissionList = (): string[] => {
|
|
2906
|
+
const now = Date.now();
|
|
2907
|
+
if (!verdictList || now - verdictList.at >= 1000 || now < verdictList.at) {
|
|
2908
|
+
verdictList = { at: now, list: admissionList() };
|
|
2909
|
+
}
|
|
2910
|
+
return verdictList.list;
|
|
2911
|
+
};
|
|
2912
|
+
const readNetworkVerdict = (request: FastifyRequest): boolean =>
|
|
2913
|
+
evaluateNetworkPass(request, { readTrusted: memoAdmissionList, localToken, localTrust }).passed === null;
|
|
2914
|
+
|
|
2366
2915
|
// Session control REST API (wraps WebSocket-only operations)
|
|
2367
2916
|
registerSessionApi(fastify, {
|
|
2368
2917
|
sessionManager,
|
|
@@ -2374,6 +2923,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2374
2923
|
pendingPrincipalOwnerRegistry,
|
|
2375
2924
|
pendingResumeIntents,
|
|
2376
2925
|
pendingAttachRegistry,
|
|
2926
|
+
pendingInitialPromptRegistry,
|
|
2377
2927
|
pendingPromptAcks,
|
|
2378
2928
|
sessionArchive,
|
|
2379
2929
|
pendingArchiveIntents,
|
|
@@ -2438,6 +2988,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2438
2988
|
sessionArchive,
|
|
2439
2989
|
remoteTranscriptStore,
|
|
2440
2990
|
isResolverActive: identityEnforced,
|
|
2991
|
+
// `uiUrl` / `diffUrl` origin inputs (read live per request).
|
|
2992
|
+
// See change: add-session-ui-deep-links-for-agents (D1).
|
|
2993
|
+
uiLinks: {
|
|
2994
|
+
configuredOrigins: () =>
|
|
2995
|
+
[
|
|
2996
|
+
...livePublicBaseUrls(),
|
|
2997
|
+
...[getTunnelUrl(), ...liveTunnelOrigins()].filter((u): u is string => !!u),
|
|
2998
|
+
config.authConfig?.redirectBaseUrl,
|
|
2999
|
+
].filter((u): u is string => !!u),
|
|
3000
|
+
isAdmitted: (hostHeader) => isHostAdmitted(hostHeader, getHostGateCtx().admission),
|
|
3001
|
+
port: () => config.port,
|
|
3002
|
+
},
|
|
2441
3003
|
// Transcript-sourced session diffs dispatch through the same pool the
|
|
2442
3004
|
// hydration path owns; `maxStringSize` is the store's cap so projected
|
|
2443
3005
|
// tool payloads match store-sourced ones. See change:
|
|
@@ -2469,6 +3031,36 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2469
3031
|
return ids.length;
|
|
2470
3032
|
};
|
|
2471
3033
|
registerPiRetryRoutes(fastify, { networkGuard, reloadConnectedSessions });
|
|
3034
|
+
// Trusted Types / CSP violation counters (authenticated, rate-limited, counters
|
|
3035
|
+
// only). See change: harden-client-sinks (D8).
|
|
3036
|
+
// The store is built first: the violation route feeds its persisted `ttShadow` aggregate.
|
|
3037
|
+
// See change: add-trusted-types-shadow-enforce (D6).
|
|
3038
|
+
const cspReportStore = new CspReportStore();
|
|
3039
|
+
registerCspViolationRoutes(fastify, {
|
|
3040
|
+
networkGuard,
|
|
3041
|
+
log: { warn: (m) => fastify.log.warn(m) },
|
|
3042
|
+
recordShadow: (outcome, count) => cspReportStore.recordShadow(outcome, count),
|
|
3043
|
+
});
|
|
3044
|
+
// Baseline CSP report sink (`POST /__pi/csp-report/:policy`, public to the OAuth gate), its
|
|
3045
|
+
// persisted counter (`~/.pi/dashboard/csp-reports.json`) and the operator reset
|
|
3046
|
+
// (`POST /api/csp-reports/reset`, operate). See change: harden-cors-and-csp-reporting (D8).
|
|
3047
|
+
registerCspReportSink(fastify, { store: cspReportStore, networkGuard });
|
|
3048
|
+
// Signed navigation intents for operator-opened route-backed overlays
|
|
3049
|
+
// (per-process key: a restart invalidates them). See change: harden-client-sinks (D10).
|
|
3050
|
+
registerNavIntentRoutes(fastify, { networkGuard, intents: new NavIntents() });
|
|
3051
|
+
// Framing probe for web-link previews: operator click → one SSRF-hardened outbound HEAD, verdict only
|
|
3052
|
+
// (control tier; own browser Origin required). See change: rich-chat-links (D12).
|
|
3053
|
+
registerFramePolicyRoutes(fastify, {
|
|
3054
|
+
networkGuard,
|
|
3055
|
+
corsOpts,
|
|
3056
|
+
ownOrigins: previewEgressOwnOrigins,
|
|
3057
|
+
ownPorts: () => {
|
|
3058
|
+
const tls = loadConfig().tls;
|
|
3059
|
+
return [config.port, ...(tls?.enabled ? [tls.port] : [])];
|
|
3060
|
+
},
|
|
3061
|
+
// Test-only verdict seam (PI_E2E_SEED + PI_E2E_FRAME_POLICY_VERDICTS, refused in production): undefined = real probe.
|
|
3062
|
+
probe: resolveFramePolicyTestSeam(process.env, console),
|
|
3063
|
+
});
|
|
2472
3064
|
// On-demand AI mermaid repair (opt-in via `mermaidRepair` config; 404 when off).
|
|
2473
3065
|
// See change: add-mermaid-ai-repair.
|
|
2474
3066
|
registerMermaidRepairRoutes(fastify, {
|
|
@@ -2495,6 +3087,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2495
3087
|
// the workspace link) yields `undefined` — the route clamps to the
|
|
2496
3088
|
// default. The cast is dropped once the branch lands.
|
|
2497
3089
|
removeBatchCap: (loadConfig() as DashboardConfig & { removeBatchCap?: number }).removeBatchCap,
|
|
3090
|
+
// Core cwd admission against the same known set as plugin routes.
|
|
3091
|
+
// See change: core-cwd-admission.
|
|
3092
|
+
knownCwds: knownFolderCwds,
|
|
3093
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2498
3094
|
});
|
|
2499
3095
|
|
|
2500
3096
|
// Browser channel for worktree-init event subscriptions. The dialog
|
|
@@ -2516,9 +3112,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2516
3112
|
if (cwd) worktreeInitRegistry.unsubscribeCwd(cwd, ws);
|
|
2517
3113
|
});
|
|
2518
3114
|
registerFileRoutes(fastify, {
|
|
3115
|
+
// Remote browse confinement (change: harden-server-capability-bounds, D1/D2):
|
|
3116
|
+
// strict-proof context + the two root sources only this file can read.
|
|
3117
|
+
localTrust,
|
|
3118
|
+
browseConfineRemote: confineRemoteBrowse,
|
|
3119
|
+
browseRootSources: {
|
|
3120
|
+
worktreeRoots: browseRootSources.worktreeRoots,
|
|
3121
|
+
projectGrants: browseRootSources.projectGrants,
|
|
3122
|
+
},
|
|
2519
3123
|
sessionManager,
|
|
2520
3124
|
preferencesStore,
|
|
2521
3125
|
networkGuard,
|
|
3126
|
+
routeAdmission: fileRouteAdmission,
|
|
2522
3127
|
// Plugin file-handler seams for POST /api/file/write-binary: live claim registry
|
|
2523
3128
|
// (read at request time: enabled + server entry loaded), registered validators,
|
|
2524
3129
|
// bounded worker pool. See change: add-editor-pane-file-handlers (D4).
|
|
@@ -2544,16 +3149,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2544
3149
|
validatorPool: getFileValidatorPool(),
|
|
2545
3150
|
},
|
|
2546
3151
|
});
|
|
2547
|
-
registerGrepRoutes(fastify, { sessionManager, networkGuard });
|
|
3152
|
+
registerGrepRoutes(fastify, { sessionManager, networkGuard, routeAdmission: fileRouteAdmission });
|
|
2548
3153
|
// Folder project identity (declared file + plugin marker rules). Rules come
|
|
2549
3154
|
// only from plugins that are loaded + enabled + fixture-allowed, read per
|
|
2550
3155
|
// request. See change: add-project-scoped-apps.
|
|
2551
3156
|
registerFolderProjectRoutes(fastify, {
|
|
2552
3157
|
networkGuard,
|
|
2553
|
-
knownCwds:
|
|
2554
|
-
...sessionManager.listAll().map((s) => s.cwd),
|
|
2555
|
-
...preferencesStore.getPinnedDirectories(),
|
|
2556
|
-
],
|
|
3158
|
+
knownCwds: knownFolderCwds,
|
|
2557
3159
|
getRuleSources: () => {
|
|
2558
3160
|
const cfg = loadConfig();
|
|
2559
3161
|
const store = getPluginStatusStore();
|
|
@@ -2568,7 +3170,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2568
3170
|
});
|
|
2569
3171
|
// Settings → Access review surface + the one endpoint that can create a
|
|
2570
3172
|
// filesystem grant. See change: add-access-grants-and-review.
|
|
2571
|
-
registerAccessRoutes(fastify, {
|
|
3173
|
+
registerAccessRoutes(fastify, {
|
|
3174
|
+
networkGuard,
|
|
3175
|
+
preferencesStore,
|
|
3176
|
+
writeConfigPartial,
|
|
3177
|
+
provisioning: { registry: provisioning.registry, announce: provisioning.announce },
|
|
3178
|
+
});
|
|
2572
3179
|
// Pending-question stack REST roads (list/detail/answer/summarize); the answer
|
|
2573
3180
|
// claim is shared with the browser `prompt_response` road.
|
|
2574
3181
|
// See change: add-pending-question-stack (D8, D9).
|
|
@@ -2579,6 +3186,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2579
3186
|
isResolverActive: identityEnforced,
|
|
2580
3187
|
ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
|
|
2581
3188
|
});
|
|
3189
|
+
// SSE agent-event feed for external controllers. See change: add-agent-event-stream.
|
|
3190
|
+
registerAgentEventStreamRoutes(fastify, { networkGuard, hub: agentEventHub, isResolverActive: identityEnforced });
|
|
2582
3191
|
registerAccessPromptRoutes(fastify, {
|
|
2583
3192
|
networkGuard,
|
|
2584
3193
|
coordinator: grantCoordinator,
|
|
@@ -2608,9 +3217,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2608
3217
|
piGateway,
|
|
2609
3218
|
// Live (per-request) config for the workflow-schema gates + new-project default.
|
|
2610
3219
|
getOpenSpecConfig: () => loadConfig().openspec,
|
|
2611
|
-
//
|
|
2612
|
-
//
|
|
2613
|
-
|
|
3220
|
+
// The directory service's ONE spawn semaphore (cap resizable by
|
|
3221
|
+
// `reconfigurePolling`) bounds the route's `newer`/`conflict` validate too.
|
|
3222
|
+
// See changes: add-pi-spec-driven-schema, move-workflow-schema-status-to-poll-worker.
|
|
3223
|
+
spawnSemaphore: directoryService.semaphore,
|
|
3224
|
+
// Core cwd admission against the same known set as plugin routes.
|
|
3225
|
+
// See change: core-cwd-admission.
|
|
3226
|
+
knownFolderCwds,
|
|
3227
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2614
3228
|
onOpenSpecChanged: (cwd) => {
|
|
2615
3229
|
const data = directoryService.getOpenSpecData(cwd);
|
|
2616
3230
|
if (data) browserGateway.broadcastToAll({ type: "openspec_update", cwd, data });
|
|
@@ -2639,6 +3253,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2639
3253
|
preferencesStore,
|
|
2640
3254
|
networkGuard,
|
|
2641
3255
|
store: openspecGroupStore,
|
|
3256
|
+
routeAdmission: fileRouteAdmission,
|
|
2642
3257
|
});
|
|
2643
3258
|
|
|
2644
3259
|
|
|
@@ -2672,6 +3287,29 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2672
3287
|
} catch { /* best-effort */ }
|
|
2673
3288
|
}
|
|
2674
3289
|
};
|
|
3290
|
+
// Plugin-declared replay entry types (manifest `replayEntryTypes`): enabled
|
|
3291
|
+
// plugins replay, every declaring plugin hides. Read by each session replay;
|
|
3292
|
+
// short-TTL cache so a toggle lands without a per-load disk scan.
|
|
3293
|
+
// See change: update-flows-plugin (D3, G5).
|
|
3294
|
+
{
|
|
3295
|
+
let cached: { at: number; sets: ReturnType<typeof computeReplayEntryTypes> } | undefined;
|
|
3296
|
+
setReplayEntryTypesProvider(() => {
|
|
3297
|
+
const now = Date.now();
|
|
3298
|
+
if (cached && now - cached.at < 5_000) return cached.sets;
|
|
3299
|
+
const config = loadConfig();
|
|
3300
|
+
const sets = computeReplayEntryTypes(
|
|
3301
|
+
discoverPlugins().map((p) => ({
|
|
3302
|
+
replayEntryTypes: p.manifest.replayEntryTypes,
|
|
3303
|
+
enabled: resolvePluginEnabled(
|
|
3304
|
+
getPluginConfigFromFile(config, p.manifest.id) as Record<string, unknown>,
|
|
3305
|
+
p.manifest.defaultEnabled,
|
|
3306
|
+
),
|
|
3307
|
+
})),
|
|
3308
|
+
);
|
|
3309
|
+
cached = { at: now, sets };
|
|
3310
|
+
return sets;
|
|
3311
|
+
});
|
|
3312
|
+
}
|
|
2675
3313
|
const embedLifecycle = createEmbedLifecycleController({
|
|
2676
3314
|
closers: sessionClosers,
|
|
2677
3315
|
markArchiveOnEnd,
|
|
@@ -2711,6 +3349,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2711
3349
|
const hasProductionBuild = clientDirResolved !== null;
|
|
2712
3350
|
// ONE snapshot feeds the startup diagnostic, `fastifyStatic`, and
|
|
2713
3351
|
// `/api/health.clientBuild` (passed to `registerSystemRoutes` below).
|
|
3352
|
+
// Served declaration's `bundledPluginIds` reach discovery BEFORE any server-side discovery call
|
|
3353
|
+
// (D15). See change: decouple-plugins-from-core (task 5.4).
|
|
3354
|
+
setDeclaredBundledPluginIds(readServedBundledPluginIds(clientDirResolved));
|
|
2714
3355
|
const clientBuild = clientBuildSnapshotFor(clientDirResolved);
|
|
2715
3356
|
console.log(clientBuildDiagnostic(clientBuild));
|
|
2716
3357
|
if (!hasProductionBuild) {
|
|
@@ -2719,7 +3360,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2719
3360
|
|
|
2720
3361
|
registerAcpRoutes(fastify);
|
|
2721
3362
|
registerTlsRoutes(fastify, { networkGuard, listener: tlsListener });
|
|
2722
|
-
|
|
3363
|
+
// Live pi-trust query: authenticated one-shot HTTP for the bridge's `project_trust`.
|
|
3364
|
+
// See change: mirror-dashboard-trust-live-remote.
|
|
3365
|
+
const piTrustQuery = registerPiTrustQueryRoutes(fastify, {
|
|
3366
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
3367
|
+
live: () => piTrustMirror.live,
|
|
3368
|
+
readSnapshot: () => piTrustMirror.readSnapshot(),
|
|
3369
|
+
});
|
|
3370
|
+
registerSystemRoutes(fastify, { readNetworkVerdict, 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
3371
|
registerHostGateRoutes(fastify, { getCtx: getHostGateCtx, state: hostGateState, networkGuard });
|
|
2724
3372
|
// GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
|
|
2725
3373
|
// Assigned by the runtime-overlay block below; read lazily per request.
|
|
@@ -2849,27 +3497,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2849
3497
|
let modelProxyMounted = false;
|
|
2850
3498
|
|
|
2851
3499
|
// On completion: broadcast to browsers + invalidate the recommended cache
|
|
2852
|
-
packageManagerWrapper.setCompleteListener((
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
3500
|
+
packageManagerWrapper.setCompleteListener(createPackageCompletionHandler<OperationResult>({
|
|
3501
|
+
broadcastComplete: (result) => {
|
|
3502
|
+
browserGateway.broadcastToAll({
|
|
3503
|
+
type: "package_operation_complete",
|
|
3504
|
+
operationId: result.operationId,
|
|
3505
|
+
action: result.action,
|
|
3506
|
+
source: result.source,
|
|
3507
|
+
scope: result.scope,
|
|
3508
|
+
success: result.success,
|
|
3509
|
+
error: result.error,
|
|
3510
|
+
diagnostics: result.diagnostics,
|
|
3511
|
+
sessionsReloaded: (result as OperationResult & { sessionsReloaded?: number }).sessionsReloaded,
|
|
3512
|
+
...(result.moveId ? { moveId: result.moveId } : {}),
|
|
3513
|
+
...(result.partialSuccess ? { partialSuccess: result.partialSuccess } : {}),
|
|
3514
|
+
} as PackageOperationCompleteMessage);
|
|
3515
|
+
},
|
|
3516
|
+
invalidateRecommendedCache,
|
|
3517
|
+
// Hot-add: a successful op refreshes plugin discovery (global) or local-scope detection
|
|
3518
|
+
// (local); ONE `plugins_changed` follows the completion broadcast. Never from
|
|
3519
|
+
// `package-routes.ts`. See change: decouple-plugins-from-core (task 5.7, D16).
|
|
3520
|
+
discovery: () => pluginDiscovery,
|
|
2867
3521
|
// A successful package operation may have changed plugin requirement
|
|
2868
3522
|
// satisfaction. Refresh probes and broadcast plugin_config_update for
|
|
2869
3523
|
// any plugin whose `missingRequirements` flipped.
|
|
2870
3524
|
// See change: add-plugin-activation-ui.
|
|
2871
|
-
|
|
2872
|
-
|
|
3525
|
+
refreshProbes: () =>
|
|
3526
|
+
refreshRequirementProbesFor(
|
|
2873
3527
|
null,
|
|
2874
3528
|
{
|
|
2875
3529
|
listInstalled: () => packageManagerWrapper.listInstalled("global"),
|
|
@@ -2885,9 +3539,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2885
3539
|
config: status ?? {},
|
|
2886
3540
|
});
|
|
2887
3541
|
}
|
|
2888
|
-
})
|
|
2889
|
-
|
|
2890
|
-
});
|
|
3542
|
+
}),
|
|
3543
|
+
}));
|
|
2891
3544
|
|
|
2892
3545
|
// Reload all active sessions after a successful package operation
|
|
2893
3546
|
packageManagerWrapper.setReloadSessions(async () => {
|
|
@@ -2902,7 +3555,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2902
3555
|
return count;
|
|
2903
3556
|
});
|
|
2904
3557
|
|
|
2905
|
-
registerPackageRoutes(fastify, { packageManagerWrapper });
|
|
3558
|
+
registerPackageRoutes(fastify, { packageManagerWrapper, routeAdmission: fileRouteAdmission });
|
|
2906
3559
|
registerPackageHealthRoutes(fastify, { packageManagerWrapper });
|
|
2907
3560
|
registerResourceActivationRoutes(fastify, {
|
|
2908
3561
|
networkGuard,
|
|
@@ -2913,6 +3566,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2913
3566
|
browserGateway.headlessPidRegistry
|
|
2914
3567
|
.listSessions()
|
|
2915
3568
|
.map((e) => ({ sessionId: e.sessionId, cwd: e.cwd })),
|
|
3569
|
+
routeAdmission: fileRouteAdmission,
|
|
2916
3570
|
});
|
|
2917
3571
|
registerRecommendedRoutes(fastify, {
|
|
2918
3572
|
packageManagerWrapper,
|
|
@@ -3029,8 +3683,71 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3029
3683
|
]);
|
|
3030
3684
|
|
|
3031
3685
|
// Live-server-preview routes + reverse proxy (main-origin /live/:id/*).
|
|
3032
|
-
registerLiveServerRoutes(fastify, liveServerManager, {
|
|
3033
|
-
|
|
3686
|
+
registerLiveServerRoutes(fastify, liveServerManager, {
|
|
3687
|
+
networkGuard,
|
|
3688
|
+
capabilities: liveCapabilities,
|
|
3689
|
+
pool: previewPool,
|
|
3690
|
+
previewPaths,
|
|
3691
|
+
hasTier5Viewer: () => hasTier5Viewer(browserGateway.wss.clients),
|
|
3692
|
+
exposure: previewExposure,
|
|
3693
|
+
promptingEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
|
|
3694
|
+
getTrustedNetworks: admissionList,
|
|
3695
|
+
localTrust,
|
|
3696
|
+
egress: previewEgress,
|
|
3697
|
+
requestEgressGrant: createEgressGrantRequester(grantCoordinator),
|
|
3698
|
+
channelOf: (request) => sourceChannel(request.ip),
|
|
3699
|
+
// `start-static`: the SAME gate as a raw file read; a refusal answers with that route's status and body.
|
|
3700
|
+
staticGate: async (cwd, relPath, opts) => {
|
|
3701
|
+
const gate = await gateFilePath(cwd, relPath, fileRouteAdmission, { allowGrant: true, disclosure: opts.disclosure });
|
|
3702
|
+
if ("code" in gate) {
|
|
3703
|
+
return {
|
|
3704
|
+
ok: false,
|
|
3705
|
+
status: gate.code,
|
|
3706
|
+
body: denialBody(gate),
|
|
3707
|
+
// The 503 of an undecidable cwd admission carries `Retry-After` like every file route.
|
|
3708
|
+
...(gate.code === 503 ? { headers: { "Retry-After": "1" } } : {}),
|
|
3709
|
+
};
|
|
3710
|
+
}
|
|
3711
|
+
return { ok: true, resolved: gate.resolved };
|
|
3712
|
+
},
|
|
3713
|
+
});
|
|
3714
|
+
const liveProxyDeps: LiveProxyDeps = {
|
|
3715
|
+
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
3716
|
+
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
3717
|
+
grantedOrigins: (grant) => previewEgress.grantedFor(grant),
|
|
3718
|
+
// D3(c): a tier 1-4 upstream `Location` / `Refresh` aimed at the dashboard app is contained (dropped / rewritten onto the preview).
|
|
3719
|
+
isDashboardUrl: (url) => {
|
|
3720
|
+
const tls = loadConfig().tls;
|
|
3721
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
3722
|
+
return (
|
|
3723
|
+
(port === config.port || (tls?.enabled === true && port === tls.port)) &&
|
|
3724
|
+
!isPreviewShapedOriginUrl(url.origin) &&
|
|
3725
|
+
isHostAdmitted(url.host, getHostGateCtx().admission)
|
|
3726
|
+
);
|
|
3727
|
+
},
|
|
3728
|
+
onStaticHtmlServed: (grant, real) => previewEgress.noteServed(grant, real),
|
|
3729
|
+
trackPreviewResponse: (pid, res) => previewWs.track(pid, res),
|
|
3730
|
+
reservedHandler: createReservedHandler({
|
|
3731
|
+
egress: previewEgress,
|
|
3732
|
+
ownOriginsOf: (request) => requestOriginsOf(request),
|
|
3733
|
+
}),
|
|
3734
|
+
// Re-run on EVERY static request, so a revoked grant or pin applies on the next one. Quiet:
|
|
3735
|
+
// a refusal here records no denial and raises no prompt.
|
|
3736
|
+
staticGate: async (cwd, absPath) =>
|
|
3737
|
+
!("code" in (await gateFilePath(cwd, absPath, fileRouteAdmission, { allowGrant: true, quiet: true }))),
|
|
3738
|
+
};
|
|
3739
|
+
liveProxyDepsRef = liveProxyDeps;
|
|
3740
|
+
registerLiveServerProxy(fastify, liveServerManager, liveProxyDeps);
|
|
3741
|
+
previewObserver = createPreviewObserver();
|
|
3742
|
+
previewDispatch = createPreviewDispatch({
|
|
3743
|
+
onRefused: (reason, h) => previewObserver?.refused(reason, h),
|
|
3744
|
+
onAdmitted: (h, tier) => previewObserver?.admitted(h, tier),
|
|
3745
|
+
store: liveCapabilities,
|
|
3746
|
+
manager: liveServerManager,
|
|
3747
|
+
proxyDeps: liveProxyDeps,
|
|
3748
|
+
isPeerLocal: (request) =>
|
|
3749
|
+
isLocallyTrusted({ ip: request.socket.remoteAddress ?? "", headers: request.headers as Record<string, unknown> }),
|
|
3750
|
+
});
|
|
3034
3751
|
|
|
3035
3752
|
// ONE model runtime for the provider-auth flow listing AND the model proxy,
|
|
3036
3753
|
// injected so auth/ never imports model-proxy/.
|
|
@@ -3045,6 +3762,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3045
3762
|
registerProviderAuthRoutes(fastify, {
|
|
3046
3763
|
piGateway,
|
|
3047
3764
|
browserGateway,
|
|
3765
|
+
// Key-file inspection reads only inside the browse confinement a remote
|
|
3766
|
+
// request gets. See change: add-provider-env-config (D7).
|
|
3767
|
+
browseConfine: (request) =>
|
|
3768
|
+
isLocallyTrusted({ ip: request.ip, headers: request.headers }, localTrust) ? Promise.resolve(null) : browseRoots(),
|
|
3048
3769
|
radiusMcp: {
|
|
3049
3770
|
service: () => {
|
|
3050
3771
|
radiusMcpService ??= createMcpClientConfigService({
|
|
@@ -3077,6 +3798,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3077
3798
|
localTrust,
|
|
3078
3799
|
hostAdmission: () => getHostGateCtx().admission,
|
|
3079
3800
|
moves: knownServerMoves,
|
|
3801
|
+
ownFingerprint: () => serverIdentity.fingerprint,
|
|
3080
3802
|
});
|
|
3081
3803
|
registerLocalProofRoutes(fastify, { codes: localProofCodes, ctx: localTrust });
|
|
3082
3804
|
registerPairingRoutes(fastify, {
|
|
@@ -3091,6 +3813,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3091
3813
|
loginAvailable,
|
|
3092
3814
|
// Public (tunnel + configured public) base URLs, already TLS-gated.
|
|
3093
3815
|
getReachableUrls: () => pairingManager.reachableUrls(),
|
|
3816
|
+
// Named in a refused bridge-token issue (HTTP → the native HTTPS address).
|
|
3817
|
+
getTlsListenerUrls: () => tlsListener.tlsListenerUrls().map((e) => e.url),
|
|
3094
3818
|
getPort: () => {
|
|
3095
3819
|
const addr = fastify.server.address();
|
|
3096
3820
|
return typeof addr === "object" && addr !== null ? addr.port : config.port;
|
|
@@ -3137,8 +3861,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3137
3861
|
ip: request.ip,
|
|
3138
3862
|
headers: request.headers as Record<string, unknown>,
|
|
3139
3863
|
localTrust,
|
|
3140
|
-
verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token),
|
|
3864
|
+
verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token, bearerChannelOf(request.raw)),
|
|
3141
3865
|
});
|
|
3866
|
+
logTicketRefusal(verdict);
|
|
3142
3867
|
if (!verdict.allow) {
|
|
3143
3868
|
reply.code(403);
|
|
3144
3869
|
return { success: false as const, error: verdict.reason };
|
|
@@ -3147,7 +3872,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3147
3872
|
// registers ATTRIBUTABLE sessions (origin gate, #E15).
|
|
3148
3873
|
return {
|
|
3149
3874
|
success: true as const,
|
|
3150
|
-
data: {
|
|
3875
|
+
data: {
|
|
3876
|
+
ticket: mintBridgeTicket(wsTicketStore, verdict.deviceId, request.raw),
|
|
3877
|
+
},
|
|
3151
3878
|
};
|
|
3152
3879
|
}
|
|
3153
3880
|
// Non-bridge scope: bind the human principal resolved by the identity
|
|
@@ -3159,7 +3886,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3159
3886
|
const identity = authed.principal
|
|
3160
3887
|
? { principal: authed.principal, principalExpiresAt: authed.principalExpiresAt }
|
|
3161
3888
|
: undefined;
|
|
3162
|
-
|
|
3889
|
+
// A device-bearer caller's id rides the ticket (like a bridge ticket), so the socket it opens is
|
|
3890
|
+
// tagged with it, a revoke closes it, and a pre-revoke ticket is refused at upgrade.
|
|
3891
|
+
// See change: device-key-mutual-check (D7).
|
|
3892
|
+
const deviceId = (request as { principalDeviceId?: string }).principalDeviceId;
|
|
3893
|
+
return { success: true as const, data: { ticket: wsTicketStore.mint(scope, deviceId, identity) } };
|
|
3163
3894
|
},
|
|
3164
3895
|
);
|
|
3165
3896
|
registerPluginConfigRoutes(fastify, {
|
|
@@ -3178,28 +3909,56 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3178
3909
|
definitions: () => customEventGroupsStore.definitions(),
|
|
3179
3910
|
});
|
|
3180
3911
|
// Canvas-type registry read/write (auto-canvas task 5.2).
|
|
3181
|
-
registerCanvasTypesRoutes(fastify, { networkGuard });
|
|
3912
|
+
registerCanvasTypesRoutes(fastify, { networkGuard, routeAdmission: fileRouteAdmission });
|
|
3182
3913
|
// Opt-in worktree auto-init-on-spawn preference (auto-init-worktree-on-spawn).
|
|
3183
3914
|
registerPreferencesWorktreeInitRoutes(fastify, { preferencesStore, networkGuard });
|
|
3184
3915
|
// Global auto-session-naming toggle (add-auto-session-naming). Broadcasts
|
|
3185
3916
|
// `preferences_update` to bridges on change.
|
|
3186
3917
|
registerPreferencesAutoNameRoutes(fastify, { preferencesStore, piGateway, networkGuard });
|
|
3918
|
+
registerPreferencesClaudeCompatRoutes(fastify, { preferencesStore, piGateway, networkGuard });
|
|
3187
3919
|
registerPluginActivationRoutes(fastify, {
|
|
3188
3920
|
networkGuard,
|
|
3189
3921
|
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3190
3922
|
});
|
|
3923
|
+
// Runtime plugin clients: admitted listing, trust grant/revoke, and the content-addressed asset prefix
|
|
3924
|
+
// (outside the network guard's jurisdiction, no auth skip: it behaves exactly like `/assets/*`).
|
|
3925
|
+
// See change: decouple-plugins-from-core (6.10–6.12).
|
|
3926
|
+
registerPluginRuntimeClientRoutes(fastify, {
|
|
3927
|
+
networkGuard,
|
|
3928
|
+
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3929
|
+
localTrust,
|
|
3930
|
+
// `pluginDiscovery` is built after listen; a trust grant before that point just broadcasts.
|
|
3931
|
+
refreshDiscovery: async () => {
|
|
3932
|
+
if (pluginDiscovery) await pluginDiscovery.refreshPluginDiscovery();
|
|
3933
|
+
else browserGateway.broadcast({ type: "plugins_changed", plugins: getPluginStatusStore().listAll() });
|
|
3934
|
+
},
|
|
3935
|
+
log: { info: (m) => console.log(m) },
|
|
3936
|
+
});
|
|
3937
|
+
registerPluginAssetsRoute(fastify, { getRegistry: getRuntimeClientRegistry });
|
|
3191
3938
|
// Add-ons hub: feature catalog + combined feature toggle. See change: addons-hub-feature-catalog.
|
|
3192
3939
|
registerAddonsRoutes(fastify, {
|
|
3193
3940
|
networkGuard,
|
|
3194
3941
|
packageManagerWrapper,
|
|
3195
3942
|
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3196
3943
|
knownDirectories: () => directoryService.knownDirectories(),
|
|
3944
|
+
// The shared known set (sessions ∪ pins ∪ workspace folders), like every admitted route.
|
|
3945
|
+
knownCwds: knownFolderCwds,
|
|
3197
3946
|
lookupNpm: (name) => fetchPackageMeta(name),
|
|
3198
3947
|
setPluginsEnabled,
|
|
3199
3948
|
// Fastify here runs with logger:false, so its log would drop every toggle line.
|
|
3200
3949
|
log: { info: (m) => console.log(m), warn: (m) => console.warn(m), error: (m) => console.error(m) },
|
|
3201
3950
|
});
|
|
3951
|
+
// Egress vet for provider probes refuses the dashboard's own port on a local
|
|
3952
|
+
// address. See change: close-local-listener-and-egress-gaps (NET-04).
|
|
3953
|
+
setProbeSelfPort(() => {
|
|
3954
|
+
const addr = fastify.server.address();
|
|
3955
|
+
const ports = addr && typeof addr === "object" ? [addr.port] : [];
|
|
3956
|
+
const tls = loadConfig().tls; // the TLS listener is the dashboard too (same idiom as `ownPorts` above)
|
|
3957
|
+
if (tls?.enabled) ports.push(tls.port);
|
|
3958
|
+
return ports.length ? ports : null;
|
|
3959
|
+
});
|
|
3202
3960
|
registerProviderRoutes(fastify, { networkGuard, piGateway, browserGateway, port: config.port });
|
|
3961
|
+
registerProviderOverrideRoutes(fastify, { networkGuard, piGateway, port: config.port });
|
|
3203
3962
|
|
|
3204
3963
|
// ── Model Proxy ───────────────────────────────────────────────────
|
|
3205
3964
|
{
|
|
@@ -3266,8 +4025,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3266
4025
|
// hooks to routes at `preReady` (verified against fastify@5.12.1 — `addHook`
|
|
3267
4026
|
// defers through `this.after` and then recurses `_addHook` over `kChildren`),
|
|
3268
4027
|
// including the encapsulated child scopes plugin routes register into. It does
|
|
3269
|
-
// NOT cover a route registered after `ready()
|
|
3270
|
-
//
|
|
4028
|
+
// NOT cover a route registered after `ready()` — and none can be: Fastify refuses
|
|
4029
|
+
// it (`route()` → `throwIfAlreadyStarted('Cannot add route!')`, fastify@5.12.1
|
|
4030
|
+
// `lib/route.js:205`), so a plugin hot-load whose entry registers a route fails that
|
|
4031
|
+
// plugin (logged, status row `loaded:false`) and the route is never served. That
|
|
4032
|
+
// refusal IS the enforcement: never serve sensitive-namespace routes from a second
|
|
4033
|
+
// instance / after-start mechanism without this hook, and install the guard on any
|
|
4034
|
+
// future facility that adds routes after start. Pinned by
|
|
4035
|
+
// `__tests__/post-start-route-registration.test.ts`; re-verify after a fastify bump.
|
|
4036
|
+
// See change: harden-git-terminal-plugin-boundaries (S1r).
|
|
3271
4037
|
fastify.addHook(
|
|
3272
4038
|
"onRequest",
|
|
3273
4039
|
createNetworkGuardHook({
|
|
@@ -3280,6 +4046,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3280
4046
|
getPairingPrefixes: () => PUBLIC_PAIRING_PREFIXES,
|
|
3281
4047
|
}),
|
|
3282
4048
|
);
|
|
4049
|
+
// Puts the request's caller in scope for every containment decision made while serving it, so the
|
|
4050
|
+
// dashboard-state guard (token, identity key, config out of reach of path-taking routes) and the
|
|
4051
|
+
// prompt-ineligible rule for an unproven local caller need no per-site plumbing. Callback style on
|
|
4052
|
+
// purpose: `run(store, done)` is what keeps the rest of the lifecycle inside the store.
|
|
4053
|
+
// See change: close-container-loopback-impersonation (D8).
|
|
4054
|
+
fastify.addHook("onRequest", (request, _reply, done) => {
|
|
4055
|
+
runWithStateCaller(stateCallerFor(request, localTrust), done);
|
|
4056
|
+
});
|
|
3283
4057
|
// Boot-time inert-entry warning (loopback entry in trustedNetworks /
|
|
3284
4058
|
// bypassHosts). Memoized; the guard re-notes on each reparse.
|
|
3285
4059
|
// See change: fix-trusted-network-tunnel-bypass (D3).
|
|
@@ -3322,6 +4096,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3322
4096
|
// some HTTP/2 proxy chains (notably zrok free-tier) occasionally
|
|
3323
4097
|
// stream-reset as ERR_ABORTED 500 in browsers.
|
|
3324
4098
|
preCompressed: true,
|
|
4099
|
+
// `index.html` (and its `.gz`) is never served by the static handler: every HTML response
|
|
4100
|
+
// passes `sendIndexWithImportMap`, which inserts the host import map. A direct `/index.html.gz`
|
|
4101
|
+
// falls to the not-found handler (the SPA shell, map included). See change: decouple-plugins-from-core (6.4).
|
|
4102
|
+
index: false,
|
|
4103
|
+
allowedPath: (pathName) => pathName !== "/index.html" && pathName !== "/index.html.gz",
|
|
3325
4104
|
// @fastify/static v10 hands `setHeaders` a FastifyReply (v8 passed the
|
|
3326
4105
|
// raw ServerResponse), so the header goes through `.header()`.
|
|
3327
4106
|
setHeaders: (reply, filePath) => {
|
|
@@ -3344,6 +4123,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3344
4123
|
return reply.code(404).send({ success: false, error: "not_found", message: `No API route for ${request.method} ${rawPath}` });
|
|
3345
4124
|
};
|
|
3346
4125
|
|
|
4126
|
+
const indexSender = createIndexHtmlSender(clientDir, { trustedTypesMode });
|
|
4127
|
+
// Every HTML shell response carries a per-response nonce on its import map; `registerCsp`'s onSend hook
|
|
4128
|
+
// reads the same memoized nonce for the strict policy header. Off mode emits no strict policy → no nonce.
|
|
4129
|
+
// See change: harden-cors-and-csp-reporting (D9).
|
|
4130
|
+
const indexHtml = {
|
|
4131
|
+
sendIndexWithImportMap: (reply: FastifyReply) =>
|
|
4132
|
+
indexSender.sendIndexWithImportMap(reply, cspMode === "off" ? undefined : { nonce: cspNonceFor(reply) }),
|
|
4133
|
+
};
|
|
4134
|
+
|
|
3347
4135
|
if (config.dev) {
|
|
3348
4136
|
// Dev mode: proxy to Vite dev server, fall back to production build
|
|
3349
4137
|
const VITE_PORTS = [3000, 5173, 5174];
|
|
@@ -3361,38 +4149,51 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3361
4149
|
|
|
3362
4150
|
vitePort = await detectVitePort();
|
|
3363
4151
|
|
|
3364
|
-
|
|
4152
|
+
/** Proxy `request.url` to Vite; the reply when Vite answered, `undefined` when it is down (re-probed next time). */
|
|
4153
|
+
const proxyToVite = async (request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply | undefined> => {
|
|
4154
|
+
if (!vitePort) vitePort = await detectVitePort();
|
|
4155
|
+
if (!vitePort) return undefined;
|
|
4156
|
+
try {
|
|
4157
|
+
const viteUrl = `http://localhost:${vitePort}${request.url}`;
|
|
4158
|
+
const res = await fetch(viteUrl);
|
|
4159
|
+
const contentType = res.headers.get("content-type");
|
|
4160
|
+
if (contentType) reply.header("Content-Type", contentType);
|
|
4161
|
+
reply.code(res.status);
|
|
4162
|
+
markViteProxied(reply); // dev response: baseline CSP only, no strict/nonce/report destination (D10)
|
|
4163
|
+
return reply.send(Buffer.from(await res.arrayBuffer()));
|
|
4164
|
+
} catch {
|
|
4165
|
+
vitePort = 0; // Vite stopped — re-probe next time
|
|
4166
|
+
return undefined;
|
|
4167
|
+
}
|
|
4168
|
+
};
|
|
4169
|
+
|
|
4170
|
+
// `/` and `/index.html` keep today's order: Vite first (its HTML carries no injected map), then the
|
|
4171
|
+
// production HTML with the map (D21, R21).
|
|
4172
|
+
if (hasProductionBuild) {
|
|
4173
|
+
const devHtml = async (request: FastifyRequest, reply: FastifyReply) =>
|
|
4174
|
+
(await proxyToVite(request, reply)) ?? indexHtml.sendIndexWithImportMap(reply);
|
|
4175
|
+
fastify.get("/", devHtml);
|
|
4176
|
+
fastify.get("/index.html", devHtml);
|
|
4177
|
+
}
|
|
4178
|
+
|
|
3365
4179
|
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3366
4180
|
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3367
4181
|
if (apiMiss) return apiMiss;
|
|
3368
4182
|
// Try Vite proxy first
|
|
3369
|
-
|
|
3370
|
-
if (
|
|
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
|
-
}
|
|
4183
|
+
const proxied = await proxyToVite(request, reply);
|
|
4184
|
+
if (proxied) return proxied;
|
|
3382
4185
|
// 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
|
-
}
|
|
4186
|
+
if (hasProductionBuild) return indexHtml.sendIndexWithImportMap(reply);
|
|
3387
4187
|
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
4188
|
});
|
|
3389
4189
|
} else if (hasProductionBuild) {
|
|
3390
|
-
// Production mode: SPA fallback
|
|
4190
|
+
// Production mode: SPA fallback (and the explicit `/`, `/index.html`) through the import-map sender.
|
|
4191
|
+
fastify.get("/", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
|
|
4192
|
+
fastify.get("/index.html", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
|
|
3391
4193
|
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3392
4194
|
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3393
4195
|
if (apiMiss) return apiMiss;
|
|
3394
|
-
|
|
3395
|
-
return reply.sendFile("index.html");
|
|
4196
|
+
return indexHtml.sendIndexWithImportMap(reply);
|
|
3396
4197
|
});
|
|
3397
4198
|
} else {
|
|
3398
4199
|
fastify.setNotFoundHandler(async (request, reply) => {
|
|
@@ -3403,10 +4204,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3403
4204
|
}
|
|
3404
4205
|
|
|
3405
4206
|
const server: DashboardServer = {
|
|
4207
|
+
inject: fastify.inject.bind(fastify) as FastifyInstance["inject"],
|
|
3406
4208
|
sessionManager,
|
|
3407
4209
|
eventStore,
|
|
3408
4210
|
browserGateway,
|
|
3409
4211
|
pendingDashboardSpawns,
|
|
4212
|
+
pendingInitialPromptRegistry,
|
|
3410
4213
|
directoryService,
|
|
3411
4214
|
sessionOrderManager,
|
|
3412
4215
|
|
|
@@ -3454,6 +4257,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3454
4257
|
secondFastify = null;
|
|
3455
4258
|
}
|
|
3456
4259
|
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
4260
|
+
try { await previewDispatch?.close(); } catch { /* ignore */ }
|
|
4261
|
+
try { liveCapabilities.close(); } catch { /* ignore */ }
|
|
4262
|
+
try { await previewPool?.close(); } catch { /* ignore */ }
|
|
3457
4263
|
try { await fastify.close(); } catch { /* ignore */ }
|
|
3458
4264
|
},
|
|
3459
4265
|
});
|
|
@@ -3602,7 +4408,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3602
4408
|
return resolvePluginEnabled(pluginCfg, manifest?.defaultEnabled);
|
|
3603
4409
|
});
|
|
3604
4410
|
try {
|
|
3605
|
-
|
|
4411
|
+
// Runtime-client registry: derives `PluginStatus.client` at every status read (live content hash,
|
|
4412
|
+
// trust, config) and serves the admitted-plugin listing. See change: decouple-plugins-from-core (6.7).
|
|
4413
|
+
const runtimeClients = installRuntimeClientRegistry();
|
|
4414
|
+
const pluginLoadDeps: ServerLoadDeps = {
|
|
4415
|
+
// pi-package server entries stay refused until the operator grants server trust (D12, R9).
|
|
4416
|
+
isServerTrusted,
|
|
3606
4417
|
isEnabled: (pluginId) => {
|
|
3607
4418
|
const cfg = loadConfig();
|
|
3608
4419
|
const pluginCfg = getPluginConfigFromFile(cfg, pluginId) as Record<string, unknown>;
|
|
@@ -3622,7 +4433,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3622
4433
|
getPluginConfigFromFile(loadConfig(), id) as Record<string, unknown>,
|
|
3623
4434
|
// Bracket this plugin's activation for route-owner attribution (D24): the
|
|
3624
4435
|
// next plugin's createContext re-begins; the finally below ends.
|
|
3625
|
-
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), createServerPluginContext(
|
|
4436
|
+
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), pluginManifestEmits.set(plugin.manifest.id, plugin.manifest.emits ?? []), recordPluginPolicyOwnership(plugin), createServerPluginContext(
|
|
3626
4437
|
{
|
|
3627
4438
|
fastify,
|
|
3628
4439
|
isPiExtensionInstalled,
|
|
@@ -3638,11 +4449,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3638
4449
|
},
|
|
3639
4450
|
onPiResourcesInvalidated: (handler: (cwd: string | undefined) => void) =>
|
|
3640
4451
|
directoryService.onPiResourcesInvalidated(handler),
|
|
3641
|
-
|
|
4452
|
+
// `isConnected` = open bridge socket, trusted plugins only (same
|
|
4453
|
+
// gate as abortSpawnedRun). See change: polish-automation-board.
|
|
4454
|
+
sessionManager: createPluginSessionManager({
|
|
3642
4455
|
listActive: () => sessionManager.listActive(),
|
|
3643
4456
|
listAll: () => sessionManager.listAll(),
|
|
3644
4457
|
getSession: (id: string) => sessionManager.get(id),
|
|
3645
|
-
|
|
4458
|
+
isSessionConnected: (id: string) => piGateway.isSessionConnected(id),
|
|
4459
|
+
trusted: (plugin.manifest.priority ?? 1000) <= 100,
|
|
4460
|
+
}),
|
|
3646
4461
|
eventStore: {
|
|
3647
4462
|
getEvents: (sessionId) => eventStore.getEvents(sessionId, 0),
|
|
3648
4463
|
getLatestEvent: (sessionId) => {
|
|
@@ -3699,6 +4514,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3699
4514
|
pluginSessionEndSubs.add(handler);
|
|
3700
4515
|
return () => pluginSessionEndSubs.delete(handler);
|
|
3701
4516
|
},
|
|
4517
|
+
onSessionStatusEnded: (handler) => {
|
|
4518
|
+
pluginSessionStatusEndSubs.add(handler);
|
|
4519
|
+
return () => pluginSessionStatusEndSubs.delete(handler);
|
|
4520
|
+
},
|
|
4521
|
+
appendEvent: (sessionId, event) => appendPluginOwnedEvent(plugin.manifest.id, sessionId, event),
|
|
4522
|
+
registerStorePolicy: (policy) => getPluginPolicyRegistry().registerStorePolicy(plugin.manifest.id, policy),
|
|
4523
|
+
registerDeliveryPolicy: (policy) => getPluginPolicyRegistry().registerDeliveryPolicy(plugin.manifest.id, policy),
|
|
4524
|
+
registerReplayCarry: (handler) => getPluginPolicyRegistry().registerReplayCarry(plugin.manifest.id, handler),
|
|
3702
4525
|
onSessionResolved: (handler) => {
|
|
3703
4526
|
const id = plugin.manifest.id;
|
|
3704
4527
|
let set = pluginSessionResolvedSubs.get(id);
|
|
@@ -3709,123 +4532,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3709
4532
|
set.add(handler);
|
|
3710
4533
|
return () => set.delete(handler);
|
|
3711
4534
|
},
|
|
3712
|
-
sendToSession: (sessionId, text) =>
|
|
3713
|
-
piGateway.sendToSession(sessionId,
|
|
4535
|
+
sendToSession: (sessionId, text, opts) =>
|
|
4536
|
+
piGateway.sendToSession(sessionId, buildPluginSendPrompt(sessionId, text, opts)),
|
|
3714
4537
|
// Session-spawn hook. Gated to first-party/trusted plugins
|
|
3715
4538
|
// (priority <= 100 by convention). Untrusted plugins get a
|
|
3716
|
-
// hook that always rejects.
|
|
3717
|
-
//
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
|
|
3725
|
-
|
|
3726
|
-
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
3743
|
-
|
|
3744
|
-
|
|
3745
|
-
|
|
3746
|
-
// entry untouched. Otherwise mint up front so the ownership
|
|
3747
|
-
// ref is filed against it BEFORE the `spawnPiSession` await
|
|
3748
|
-
// (unchanged), closing the register-in-the-gap miss. See
|
|
3749
|
-
// change: detach-automation-goal-from-core,
|
|
3750
|
-
// relocate-goal-product-to-plugin (D1-#1).
|
|
3751
|
-
const requested = typeof opts.spawnToken === "string" ? opts.spawnToken : "";
|
|
3752
|
-
if (requested?.includes("\0")) {
|
|
3753
|
-
// A NUL cannot survive argv/registry round-trips — honouring
|
|
3754
|
-
// "used verbatim" means refusing, not silently re-minting a
|
|
3755
|
-
// token the caller's persisted state would never match.
|
|
3756
|
-
return { success: false, message: "spawnToken must not contain NUL" };
|
|
3757
|
-
}
|
|
3758
|
-
const spawnToken = requested || mintSpawnToken();
|
|
3759
|
-
if (requested && pendingPluginRefRegistry.has(spawnToken)) {
|
|
3760
|
-
return {
|
|
3761
|
-
success: false,
|
|
3762
|
-
message: `spawnToken "${spawnToken}" is already pending for another spawn`,
|
|
3763
|
-
};
|
|
3764
|
-
}
|
|
3765
|
-
pendingPluginRefRegistry.file(
|
|
3766
|
-
spawnToken,
|
|
3767
|
-
opts.pluginRef,
|
|
3768
|
-
plugin.manifest.id,
|
|
3769
|
-
opts.lifecycle,
|
|
3770
|
-
);
|
|
3771
|
-
// Fresh-spawn reprime rides the per-cwd pending-initial-prompt
|
|
3772
|
-
// FIFO exactly as core's own respawn path does: enqueue BEFORE
|
|
3773
|
-
// the spawn await, consume on failure/throw so a dead spawn
|
|
3774
|
-
// leaves no stale intent for an unrelated later register in
|
|
3775
|
-
// the same cwd. See change:
|
|
3776
|
-
// relocate-goal-product-to-plugin (D1-#3).
|
|
3777
|
-
const initialPrompt =
|
|
3778
|
-
typeof opts.initialPrompt === "string" && opts.initialPrompt.length > 0
|
|
3779
|
-
? opts.initialPrompt
|
|
3780
|
-
: undefined;
|
|
3781
|
-
if (initialPrompt) pendingInitialPromptRegistry.enqueue(opts.cwd, initialPrompt);
|
|
3782
|
-
// mode/sandbox threading (change: redesign-automation-editor-and-board).
|
|
3783
|
-
// DOCUMENTED LIMITATION (task 4.2): the host hook does not yet
|
|
3784
|
-
// enforce these. `worktree` would need ephemeral worktree
|
|
3785
|
-
// create+cleanup wired to run-end correlation (discard/merge
|
|
3786
|
-
// policy unspecified); pi exposes no `--sandbox` flag so the
|
|
3787
|
-
// sandbox level cannot be applied at spawn. Both fall back to
|
|
3788
|
-
// running in-place at `opts.cwd`. Log non-default requests so
|
|
3789
|
-
// the gap is visible until the host gains support.
|
|
3790
|
-
if (opts.mode === "worktree" || (opts.sandbox && opts.sandbox !== "workspace-write")) {
|
|
3791
|
-
console.warn(
|
|
3792
|
-
`[plugin-spawn] mode=${opts.mode ?? "local"} sandbox=${opts.sandbox ?? "(default)"} requested but not yet enforced by the host hook; running in-place at ${opts.cwd}`,
|
|
3793
|
-
);
|
|
3794
|
-
}
|
|
3795
|
-
try {
|
|
3796
|
-
const result =
|
|
3797
|
-
typeof opts.agent === "string"
|
|
3798
|
-
? await spawnAcpSession(opts.cwd, { agent: opts.agent, spawnToken })
|
|
3799
|
-
: await spawnPiSession(opts.cwd, { ...sessionOptions, spawnToken });
|
|
3800
|
-
// Plugin/automation spawn: transport-less, reclaim required.
|
|
3801
|
-
armSpawnWatchdog(opts.cwd, "headless", result);
|
|
3802
|
-
if (result.process && result.pid) {
|
|
3803
|
-
browserGateway.headlessPidRegistry.register(
|
|
3804
|
-
result.pid,
|
|
3805
|
-
opts.cwd,
|
|
3806
|
-
result.process,
|
|
3807
|
-
result.spawnToken ?? spawnToken,
|
|
3808
|
-
keeperOptsFromSpawnResult(result),
|
|
3809
|
-
);
|
|
3810
|
-
}
|
|
3811
|
-
// Token-keyed, idempotent rollback on failure so no later
|
|
3812
|
-
// session resolves a stale ref; the queued initial prompt
|
|
3813
|
-
// is consumed with it.
|
|
3814
|
-
if (!result.success) {
|
|
3815
|
-
pendingPluginRefRegistry.remove(spawnToken);
|
|
3816
|
-
if (initialPrompt) pendingInitialPromptRegistry.consume(opts.cwd);
|
|
3817
|
-
}
|
|
3818
|
-
return {
|
|
3819
|
-
success: result.success,
|
|
3820
|
-
message: result.message,
|
|
3821
|
-
...(result.spawnToken ? { spawnToken: result.spawnToken } : { spawnToken }),
|
|
3822
|
-
};
|
|
3823
|
-
} catch (err) {
|
|
3824
|
-
pendingPluginRefRegistry.remove(spawnToken);
|
|
3825
|
-
if (initialPrompt) pendingInitialPromptRegistry.consume(opts.cwd);
|
|
3826
|
-
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
3827
|
-
}
|
|
3828
|
-
},
|
|
4539
|
+
// hook that always rejects. The flow (incl. the optional `worktree`
|
|
4540
|
+
// block) lives in `createPluginSpawnHook`.
|
|
4541
|
+
// See change: add-automation-plugin, add-plugin-spawn-worktree.
|
|
4542
|
+
spawnSession: createPluginSpawnHook({
|
|
4543
|
+
plugin: { id: plugin.manifest.id, priority: plugin.manifest.priority },
|
|
4544
|
+
defaultModel: () => loadConfig().defaultModel,
|
|
4545
|
+
mintSpawnToken,
|
|
4546
|
+
validateAcp: validatePluginAcpSpawn,
|
|
4547
|
+
pendingPluginRefRegistry,
|
|
4548
|
+
pendingInitialPromptRegistry,
|
|
4549
|
+
pendingAttachRegistry,
|
|
4550
|
+
spawnPi: (cwd, o) => spawnPiSession(cwd, o as Parameters<typeof spawnPiSession>[1]),
|
|
4551
|
+
spawnAcp: spawnAcpSession,
|
|
4552
|
+
armWatchdog: (cwd, result) => armSpawnWatchdog(cwd, "headless", result),
|
|
4553
|
+
registerHeadlessPid: (pid, cwd, child, token, result) =>
|
|
4554
|
+
browserGateway.headlessPidRegistry.register(
|
|
4555
|
+
pid,
|
|
4556
|
+
cwd,
|
|
4557
|
+
child as Parameters<typeof browserGateway.headlessPidRegistry.register>[2],
|
|
4558
|
+
token,
|
|
4559
|
+
keeperOptsFromSpawnResult(result),
|
|
4560
|
+
),
|
|
4561
|
+
ensureWorktree: (o) =>
|
|
4562
|
+
ensureWorktree({ ...o, knownCwds: knownFolderCwds, admitOptions: { onIndeterminate: cwdAdmissionLogger } }),
|
|
4563
|
+
resolveCwdPolicy: (cwd) => cwdPolicyRegistry.resolve(cwd),
|
|
4564
|
+
autoInitEnabled: () => preferencesStore.getAutoInitWorktreeOnSpawn(),
|
|
4565
|
+
startWorktreeInit: (cwd, o) => startWorktreeInit(cwd, { ...o, registry: worktreeInitRegistry }),
|
|
4566
|
+
awaitInitRun: (cwd) => awaitInitRun(worktreeInitRegistry, cwd),
|
|
4567
|
+
isStopping: () => serverStopping,
|
|
4568
|
+
}),
|
|
3829
4569
|
// Spawn-env contributor hook. Trusted-gated like `spawnSession`
|
|
3830
4570
|
// (policy, not a sandbox); untrusted plugins get a no-op.
|
|
3831
4571
|
// See change: add-context-mode-settings-plugin.
|
|
@@ -3920,6 +4660,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3920
4660
|
}
|
|
3921
4661
|
return mintSpawnToken();
|
|
3922
4662
|
},
|
|
4663
|
+
// Guarded UTF-8 file read for plugin routes that return file CONTENT: `null` when the
|
|
4664
|
+
// dashboard-state / pi-agent-credential guard refuses the real path (caller from the
|
|
4665
|
+
// `onRequest` scope) or the opened handle. Not trust-gated (it only narrows).
|
|
4666
|
+
// See change: close-security-map-high-findings (D1, H1).
|
|
4667
|
+
readFileGuarded: guardedReadFile,
|
|
4668
|
+
// Public base for plugin OAuth return URLs: same resolution as the dashboard login redirect.
|
|
4669
|
+
// See change: add-google-connect.
|
|
4670
|
+
getDashboardBaseUrl: () => resolveRedirectBase(config.port, config.authConfig?.redirectBaseUrl).base,
|
|
3923
4671
|
// Rename a live session: in-memory + `session_updated` broadcast
|
|
3924
4672
|
// + `rename_session` to pi — the host's own rename block, lifted
|
|
3925
4673
|
// verbatim (the broadcast carries `{ name: name || undefined }`).
|
|
@@ -4011,22 +4759,36 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4011
4759
|
// this is NOT trust-gated. See change:
|
|
4012
4760
|
// relocate-goal-product-to-plugin (D1-#7).
|
|
4013
4761
|
networkGuard,
|
|
4014
|
-
// `ctx.serveApp`: trust-gated (bundled plugin dir OR `auth.capabilityRoutePlugins`),
|
|
4762
|
+
// `ctx.serveApp`: trust-gated (bundled plugin dir, `auth.trustedPlugins` OR legacy `auth.capabilityRoutePlugins`),
|
|
4015
4763
|
// mounts `/apps/<appId>/`. See change: add-plugin-capability-routes (D2, D5).
|
|
4016
4764
|
serveApp: createHostServeApp({
|
|
4017
4765
|
fastify,
|
|
4018
|
-
plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id },
|
|
4766
|
+
plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id, source: plugin.source },
|
|
4019
4767
|
readConfiguredIds: () => loadConfig().auth?.capabilityRoutePlugins ?? [],
|
|
4020
4768
|
}),
|
|
4021
4769
|
// Emit a configured pi event into a session (relayed as a
|
|
4022
4770
|
// `plugin_emit_event` control message; the in-session bridge
|
|
4023
4771
|
// re-emits it on pi.events). Same trust gate as abortSession.
|
|
4024
4772
|
// See change: automation-emit-configured-event.
|
|
4773
|
+
// Only event types in the plugin's manifest `emits` (live; automation also
|
|
4774
|
+
// gets its accepted action providers' emits) pass.
|
|
4775
|
+
// See change: harden-git-terminal-plugin-boundaries (D16).
|
|
4776
|
+
// Rejected plugin_action / plugin-route command counter (/api/health).
|
|
4777
|
+
// See change: update-flows-plugin (task 2.4).
|
|
4778
|
+
recordRejectedPluginAction: () => recordRejectedPluginAction(),
|
|
4025
4779
|
emitEventToSession: (sessionId, eventType, data) =>
|
|
4026
4780
|
pluginEventSeam.emitEventToSession(
|
|
4027
4781
|
(plugin.manifest.priority ?? 1000) <= 100,
|
|
4028
4782
|
(sid, m) => piGateway.sendToSession(sid, m),
|
|
4029
4783
|
sessionId, eventType, data,
|
|
4784
|
+
{
|
|
4785
|
+
pluginId: plugin.manifest.id,
|
|
4786
|
+
allowed: () =>
|
|
4787
|
+
pluginEventSeam.computeEmitAllowlist(plugin.manifest.id, {
|
|
4788
|
+
manifestEmits: loadedManifestEmits,
|
|
4789
|
+
actionEntries: () => pluginServiceRegistry.entries("automation.action."),
|
|
4790
|
+
}),
|
|
4791
|
+
},
|
|
4030
4792
|
),
|
|
4031
4793
|
// Raw server→extension control message to one session's bridge
|
|
4032
4794
|
// socket — the `credentials_updated` lane, WITHOUT the
|
|
@@ -4040,18 +4802,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4040
4802
|
(sid, m) => piGateway.sendToSession(sid, m as Parameters<typeof piGateway.sendToSession>[1]),
|
|
4041
4803
|
sessionId, msg,
|
|
4042
4804
|
),
|
|
4043
|
-
|
|
4805
|
+
// Attributed to this plugin; `automation.action.<source>` keys are
|
|
4806
|
+
// refused unless `<source>` is this plugin's id (logged, no throw).
|
|
4807
|
+
provide: (name, value) => { pluginServiceRegistry.provide(plugin.manifest.id, name, value); },
|
|
4044
4808
|
consume: <T = unknown>(name: string) =>
|
|
4045
|
-
pluginServiceRegistry.get(name)
|
|
4809
|
+
pluginServiceRegistry.get<T>(name),
|
|
4046
4810
|
// Prefix enumeration for publish/collect (in-process only).
|
|
4047
4811
|
// 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
|
-
},
|
|
4812
|
+
consumeAll: <T = unknown>(prefix: string) => pluginServiceRegistry.entries<T>(prefix),
|
|
4055
4813
|
// plugin_action fans out by pluginId (manifest-authoritative, not
|
|
4056
4814
|
// self-declared) so multiple plugins coexist; other custom types
|
|
4057
4815
|
// stay single-owner. See change: fix-plugin-action-fanout-and-handlers.
|
|
@@ -4111,7 +4869,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4111
4869
|
// the private request lane. Not trust-gated: each is scoped to
|
|
4112
4870
|
// the calling plugin's manifest id. See change:
|
|
4113
4871
|
// expose-plugin-credential-and-oauth-seams (D2, D3, D7).
|
|
4114
|
-
pluginCredentials: (id) =>
|
|
4872
|
+
pluginCredentials: (id) =>
|
|
4873
|
+
createPluginCredentialStore(id, { codec: getCredentialCodec("plugin-credentials") }),
|
|
4115
4874
|
// Declared + user-approved vault reads, bound to this plugin's manifest.
|
|
4116
4875
|
// See change: add-credential-vault (D4).
|
|
4117
4876
|
pluginVault: (id) => createPluginVaultReader(vaultStore, id, plugin.manifest.vaultBindings ?? []),
|
|
@@ -4128,8 +4887,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4128
4887
|
});
|
|
4129
4888
|
return res.ok ? { ok: true, flowId: res.flow.id } : res;
|
|
4130
4889
|
},
|
|
4131
|
-
registerPiRequestHandler: (id, type, handler) =>
|
|
4132
|
-
pluginRequestLane.register(id, type, handler),
|
|
4890
|
+
registerPiRequestHandler: (id, type, handler, opts) =>
|
|
4891
|
+
pluginRequestLane.register(id, type, handler, opts),
|
|
4133
4892
|
// First-party scope gate shared with the `/api/plugins` `firstParty`
|
|
4134
4893
|
// projection. See change: promote-model-roles-settings.
|
|
4135
4894
|
providerAuth: createGatedProviderAuth(plugin.packageName, readAuthJson),
|
|
@@ -4218,7 +4977,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4218
4977
|
editClaimIds: plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-file-handler" && c.mode === "edit" && c.id ? [c.id] : [])),
|
|
4219
4978
|
},
|
|
4220
4979
|
)),
|
|
4980
|
+
};
|
|
4981
|
+
pluginDiscovery = createPluginDiscoveryWiring({
|
|
4982
|
+
loadDeps: pluginLoadDeps,
|
|
4983
|
+
readDeclaredBundledIds: () => readServedBundledPluginIds(clientDirResolved),
|
|
4984
|
+
clearContentHashCache: () => runtimeClients.clearContentHashCache(),
|
|
4985
|
+
logAdmissions: () => logRuntimeAdmissions({ info: (m) => console.log(m) }, "refresh"),
|
|
4986
|
+
listActiveCwds: () => sessionManager.listActive().map((s) => s.cwd),
|
|
4987
|
+
broadcastPluginsChanged: (plugins) => browserGateway.broadcast({ type: "plugins_changed", plugins }),
|
|
4221
4988
|
});
|
|
4989
|
+
await loadServerEntries(pluginLoadDeps);
|
|
4222
4990
|
} catch (err) {
|
|
4223
4991
|
console.error('[plugin-loader] Unexpected error during pre-listen load:', err);
|
|
4224
4992
|
} finally {
|
|
@@ -4230,6 +4998,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4230
4998
|
// path, two transports). See change: add-tailscale-cert-tls (D1).
|
|
4231
4999
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
4232
5000
|
const onUpgrade = (request: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer): void => {
|
|
5001
|
+
// FIRST branch (D3): a preview-shaped Host is served — or refused — by the preview dispatcher, ahead of
|
|
5002
|
+
// the dashboard host gate, Origin gate and ticket. It never reaches the switch below.
|
|
5003
|
+
if (routePreviewUpgrade(previewDispatch, request, socket, head)) return;
|
|
4233
5004
|
// Stamp the local-credential verdict FIRST (before the Host/Origin gates):
|
|
4234
5005
|
// everything below reads it via `hasLocalCredential(request.headers)`.
|
|
4235
5006
|
// The proof floor is per transport: a TLS socket is stamped against the
|
|
@@ -4262,6 +5033,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4262
5033
|
return;
|
|
4263
5034
|
}
|
|
4264
5035
|
|
|
5036
|
+
// Duplicate `pi_dash_*` cookie names: 400 + expiry lines before any Origin gate or ticket (D10).
|
|
5037
|
+
if (refuseDuplicateCookieUpgrade(request, socket)) return;
|
|
5038
|
+
|
|
4265
5039
|
// Access check for WebSocket upgrades
|
|
4266
5040
|
const remoteAddress = request.socket.remoteAddress || "";
|
|
4267
5041
|
// Live admission list per upgrade (empty under `pair`) — NOT the boot
|
|
@@ -4296,10 +5070,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4296
5070
|
registration.admitOrigins,
|
|
4297
5071
|
corsOpts(),
|
|
4298
5072
|
) ||
|
|
4299
|
-
!isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust
|
|
5073
|
+
!isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust, {
|
|
5074
|
+
pluginAuthenticatesPeer: registration.peerCredential === "plugin",
|
|
5075
|
+
})
|
|
4300
5076
|
) {
|
|
4301
5077
|
console.error(
|
|
4302
|
-
|
|
5078
|
+
redactCapability(
|
|
5079
|
+
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
5080
|
+
),
|
|
4303
5081
|
);
|
|
4304
5082
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4305
5083
|
socket.destroy();
|
|
@@ -4338,9 +5116,26 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4338
5116
|
// routed path from an unrouted one. A browser cannot omit or forge
|
|
4339
5117
|
// `Origin` on a handshake; every non-browser client sends none and is
|
|
4340
5118
|
// unaffected. See change: fix-ws-origin-cswsh (D1).
|
|
4341
|
-
|
|
5119
|
+
// A live-scope upgrade may be admitted by a validated capability path
|
|
5120
|
+
// (token read from the path segment only — never query/subprotocol).
|
|
5121
|
+
// Any other scope ignores it entirely. The opaque `Origin: null` is admitted
|
|
5122
|
+
// only WITH a valid capability. See change: retire-trusted-networks-bypass (D5),
|
|
5123
|
+
// improve-canvas-html-and-url-ux (D10).
|
|
5124
|
+
const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
|
|
5125
|
+
const wsLocal = isLocallyTrusted({ ip: remoteAddress, headers: request.headers as Record<string, unknown> });
|
|
5126
|
+
// Tier 5: the same `live` scope, admitted by a valid `/preview/<pid>/` (full path forwarded). D8.
|
|
5127
|
+
const previewWsPath = scope === "live" ? parsePreviewPath(request.url) : null;
|
|
5128
|
+
const previewWsGrant = previewWsPath ? (previewPaths?.validate(previewWsPath.pid, { genuinelyLocal: wsLocal }) ?? null) : null;
|
|
5129
|
+
const liveCapPrincipal = previewWsGrant
|
|
5130
|
+
? previewWsGrant.principal
|
|
5131
|
+
: liveCap
|
|
5132
|
+
? liveCapabilities.validate(liveCap.targetId, liveCap.token, { genuinelyLocal: wsLocal })
|
|
5133
|
+
: null;
|
|
5134
|
+
if (!isWsOriginTrusted(request.headers.origin, request.headers.host, scope, corsOpts(), liveCapPrincipal !== null)) {
|
|
4342
5135
|
console.error(
|
|
4343
|
-
|
|
5136
|
+
redactCapability(
|
|
5137
|
+
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope ?? "none"} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
5138
|
+
),
|
|
4344
5139
|
);
|
|
4345
5140
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4346
5141
|
socket.destroy();
|
|
@@ -4352,16 +5147,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4352
5147
|
// the dashboard port would silently burn its ticket and see a bare TCP
|
|
4353
5148
|
// close (@review Audit, minor).
|
|
4354
5149
|
if (scope === "bridge") {
|
|
4355
|
-
|
|
4356
|
-
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
|
|
4360
|
-
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
5150
|
+
// The native TLS listener may admit a paired device's bridge (opt-in `tls.acceptBridges`); every
|
|
5151
|
+
// other case keeps the 400 without consuming the ticket. See change: prove-vault-bridge-tls (D2).
|
|
5152
|
+
routeBridgeUpgrade(
|
|
5153
|
+
{
|
|
5154
|
+
acceptBridges: tlsBridgesLive,
|
|
5155
|
+
gateway: piGateway,
|
|
5156
|
+
rejectLog: ({ status, reason }) =>
|
|
5157
|
+
wsUpgradeRejectLog.log({
|
|
5158
|
+
status,
|
|
5159
|
+
scope,
|
|
5160
|
+
remoteAddress,
|
|
5161
|
+
headers: request.headers as unknown as Record<string, unknown>,
|
|
5162
|
+
// Presence only — read from the URL/protocol header, never consumed.
|
|
5163
|
+
ticketPresent: extractTicket(request.url, secWsProtocol) !== null,
|
|
5164
|
+
...(reason ? { reason } : {}),
|
|
5165
|
+
}),
|
|
5166
|
+
},
|
|
5167
|
+
request,
|
|
5168
|
+
socket,
|
|
5169
|
+
head,
|
|
5170
|
+
);
|
|
4365
5171
|
return;
|
|
4366
5172
|
}
|
|
4367
5173
|
const ticket = extractTicket(request.url, secWsProtocol);
|
|
@@ -4375,11 +5181,6 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4375
5181
|
// principal-bearing ticket — they were the legacy loopback / local-token /
|
|
4376
5182
|
// trusted-network / principal-less-ticket allowances that bypassed it.
|
|
4377
5183
|
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
5184
|
const upgradeAuth = authorizeWsUpgrade({
|
|
4384
5185
|
cookieHeader: request.headers.cookie,
|
|
4385
5186
|
remoteAddress,
|
|
@@ -4396,14 +5197,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4396
5197
|
? { identity: liveCapPrincipal.identity, identityExpiresAt: liveCapPrincipal.identityExpiresAt }
|
|
4397
5198
|
: null,
|
|
4398
5199
|
// A revoked / disabled passkey user's cookie opens no socket (D4).
|
|
4399
|
-
isSessionLive: (p) => effectiveSessionTier(p, passkeyService) !== null,
|
|
5200
|
+
isSessionLive: (p) => effectiveSessionTier(p, passkeyService, sessionProviderRejected) !== null,
|
|
5201
|
+
// A ticket minted before its device was revoked opens nothing (D7).
|
|
5202
|
+
isDeviceActive: (id) => pairedDeviceRegistry.activeIds().has(id),
|
|
4400
5203
|
});
|
|
4401
5204
|
// Cookie-session sockets carry the session's LIVE tier (passkey users
|
|
4402
5205
|
// re-read the directory). Terminals need operate, live previews
|
|
4403
5206
|
// control; browser messages are gated per type in the gateway.
|
|
4404
5207
|
// See change: add-passkey-user-auth.
|
|
4405
5208
|
const sessionPayload = upgradeAuth.ok ? upgradeAuth.session : undefined;
|
|
4406
|
-
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService) : undefined;
|
|
5209
|
+
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService, sessionProviderRejected) : undefined;
|
|
4407
5210
|
const roadTier = scope === "terminal" ? TERMINAL_TIER : scope === "live" ? LIVE_PREVIEW_TIER : undefined;
|
|
4408
5211
|
if (sessionTierOf && roadTier) {
|
|
4409
5212
|
const t = sessionTierOf();
|
|
@@ -4417,7 +5220,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4417
5220
|
// 401 when an auth secret is configured (cookie realm), else 403 for
|
|
4418
5221
|
// the no-auth allowances — preserving the prior status semantics.
|
|
4419
5222
|
const status = config.authConfig?.secret ? "401 Unauthorized" : "403 Forbidden";
|
|
4420
|
-
wsUpgradeRejectLog.log({
|
|
5223
|
+
wsUpgradeRejectLog.log({
|
|
5224
|
+
status: config.authConfig?.secret ? 401 : 403,
|
|
5225
|
+
scope: scope ?? "none",
|
|
5226
|
+
remoteAddress,
|
|
5227
|
+
headers: wsHeaders,
|
|
5228
|
+
ticketPresent: ticket !== null,
|
|
5229
|
+
// A bare-loopback dial refused only for want of proof: say so (fixed token, no caller input).
|
|
5230
|
+
...(needsLocalProof({ ip: remoteAddress ?? "", headers: wsHeaders }, localTrust) ? { reason: "local_proof_required" } : {}),
|
|
5231
|
+
});
|
|
4421
5232
|
socket.write(`HTTP/1.1 ${status}\r\n\r\n`);
|
|
4422
5233
|
socket.destroy();
|
|
4423
5234
|
return;
|
|
@@ -4479,8 +5290,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4479
5290
|
: Object.freeze({ ...upgradeAuth.principal });
|
|
4480
5291
|
bound.principalExpiresAt = upgradeAuth.principalExpiresAt;
|
|
4481
5292
|
}
|
|
5293
|
+
// Locality is decided ONCE here, from the upgrade request; handlers read the bit.
|
|
5294
|
+
// See change: harden-server-capability-bounds (D1b).
|
|
5295
|
+
const socketLocal = stampSocketLocality(ws, request, localTrust);
|
|
5296
|
+
// D9: does this socket classify to tier 5? (counted only after the tab's `live_preview_accept`)
|
|
5297
|
+
stampPreviewViewer(ws, request, { genuinelyLocal: socketLocal, resolved: getResolvedPreviewOrigins() });
|
|
4482
5298
|
if (grants) (ws as { bootstrapGrants?: BootstrapGrants }).bootstrapGrants = grants;
|
|
4483
5299
|
if (sessionTierOf) (ws as TieredSocket).sessionTier = sessionTierOf;
|
|
5300
|
+
// Tag with the minting device so `closeDeviceSockets` can find it on revoke (D7).
|
|
5301
|
+
if (upgradeAuth.deviceId) (ws as { deviceId?: string }).deviceId = upgradeAuth.deviceId;
|
|
4484
5302
|
browserGateway.wss.emit("connection", ws, request);
|
|
4485
5303
|
});
|
|
4486
5304
|
if (identityEnforced() && policyRegistry.hasPolicy()) {
|
|
@@ -4515,6 +5333,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4515
5333
|
})
|
|
4516
5334
|
: undefined,
|
|
4517
5335
|
upgradeAuth.principalExpiresAt,
|
|
5336
|
+
sessionTierOf,
|
|
4518
5337
|
),
|
|
4519
5338
|
);
|
|
4520
5339
|
break;
|
|
@@ -4526,9 +5345,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4526
5345
|
// Chunked past the 32-bit timer cap (`scheduleAtExpiry`), released on close.
|
|
4527
5346
|
const cancelExpiry = scheduleAtExpiry(upgradeAuth.principalExpiresAt, () => socket.destroy());
|
|
4528
5347
|
socket.once("close", cancelExpiry);
|
|
5348
|
+
if (previewWsGrant && previewWsPath) previewWs.track(previewWsPath.pid, socket);
|
|
4529
5349
|
handleLiveServerUpgrade(liveServerManager, request, socket, head, {
|
|
4530
|
-
isDeviceBearer: (token) => pairedDeviceRegistry.verify(token) !== null,
|
|
5350
|
+
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
5351
|
+
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
4531
5352
|
capabilityPrefix: liveCapPrincipal && liveCap ? liveCap.prefix : undefined,
|
|
5353
|
+
...(previewWsGrant ? { previewTargetId: previewWsGrant.targetId } : {}),
|
|
4532
5354
|
});
|
|
4533
5355
|
});
|
|
4534
5356
|
break;
|
|
@@ -4566,7 +5388,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4566
5388
|
}
|
|
4567
5389
|
|
|
4568
5390
|
// The proof floor is taken after readiness, immediately before the bind.
|
|
5391
|
+
await previewDispatch?.ready();
|
|
4569
5392
|
await listenWithProofFloor(fastify, (at) => (httpBoundAt = at), { port: config.port, host: config.host });
|
|
5393
|
+
const bound = fastify.server.address();
|
|
5394
|
+
if (bound && typeof bound === "object") httpListenPort = bound.port;
|
|
4570
5395
|
writePid(process.pid);
|
|
4571
5396
|
console.log(`Dashboard server running at http://${config.host}:${config.port}`);
|
|
4572
5397
|
// Optional TLS listener: only after Fastify is ready and the main listen resolved.
|
|
@@ -4677,7 +5502,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4677
5502
|
if (mdnsDisabled) {
|
|
4678
5503
|
// skip peer discovery entirely
|
|
4679
5504
|
} else {
|
|
4680
|
-
mdnsBrowser = createBrowser();
|
|
5505
|
+
mdnsBrowser = createBrowser({ ownFingerprint: () => serverIdentity.fingerprint });
|
|
4681
5506
|
wirePeerServers({
|
|
4682
5507
|
browser: mdnsBrowser,
|
|
4683
5508
|
peers: peerServers,
|
|
@@ -4778,6 +5603,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4778
5603
|
// or they would land in every pi session's tool list.
|
|
4779
5604
|
// See change: expose-plugin-credential-and-oauth-seams (D8).
|
|
4780
5605
|
.filter(p => fixtureEntryAllowed(p.manifest))
|
|
5606
|
+
// A pi-package bridge is not auto-registered until the operator grants server trust
|
|
5607
|
+
// (D12, R9). See change: decouple-plugins-from-core (task 5.2).
|
|
5608
|
+
.filter(p => pluginServerAllowed(p, isServerTrusted))
|
|
4781
5609
|
// A disabled plugin's bridge is deregistered (both registries) and an
|
|
4782
5610
|
// enabled one registered — same predicate as the server-entry loader.
|
|
4783
5611
|
// The toggle route answers `restartRequired`, so this boot pass is
|
|
@@ -4942,6 +5770,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4942
5770
|
|
|
4943
5771
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
4944
5772
|
async stop(opts: { exitIntent?: ExitIntent } = {}) {
|
|
5773
|
+
serverStopping = true;
|
|
5774
|
+
// Committal: refuse new credential work (an OAuth refresh spends a
|
|
5775
|
+
// single-use token) while teardown runs; waited for below.
|
|
5776
|
+
// See change: settle-server-credential-writes-on-exit.
|
|
5777
|
+
exitBarrier.closeGate();
|
|
4945
5778
|
// A clean stop must also disarm the ephemeral watch so a
|
|
4946
5779
|
// create/stop cycle in one process leaves no ticking timer.
|
|
4947
5780
|
ephemeralParentWatch.stop();
|
|
@@ -4951,6 +5784,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4951
5784
|
// See change: add-access-grant-dialog.
|
|
4952
5785
|
installGrantCoordinator(null);
|
|
4953
5786
|
setNetworkDenialObserver(null);
|
|
5787
|
+
setLocalProofRefusalObserver(null);
|
|
4954
5788
|
// Stop the event-loop-delay monitor so the libuv timer doesn't linger
|
|
4955
5789
|
// after teardown. See change: instrument-session-hydration-timing.
|
|
4956
5790
|
try { eventLoopDelayHistogram.disable(); } catch { /* ignore */ }
|
|
@@ -4978,7 +5812,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4978
5812
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
4979
5813
|
// SIGTERMs every dashboard-spawned pi: after this the sessions below are
|
|
4980
5814
|
// GONE and can never reattach.
|
|
4981
|
-
|
|
5815
|
+
// Awaited: restored entries are verified first (bounded 5 s). The stop's
|
|
5816
|
+
// intent decides whether an unverifiable restored pid may be signalled.
|
|
5817
|
+
// See change: guard-restored-headless-identity (D7).
|
|
5818
|
+
await browserGateway.shutdownHeadlessProcesses({ exitIntent: opts.exitIntent ?? "idle" });
|
|
4982
5819
|
// Record `exitIntent` (default "idle") instead of erasing the evidence.
|
|
4983
5820
|
// `stop()` reaches here from the idle timer — the server chose to stop,
|
|
4984
5821
|
// the user closed nothing — so the sessions it just killed stay
|
|
@@ -5009,7 +5846,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5009
5846
|
}
|
|
5010
5847
|
pendingForkRegistry.dispose();
|
|
5011
5848
|
pairingManager.dispose();
|
|
5849
|
+
stopDeviceExpirySweep();
|
|
5012
5850
|
vaultDelivery.dispose();
|
|
5851
|
+
sudoCredential.dispose();
|
|
5013
5852
|
// Every pending ack holds a timer; a create/stop cycle must not leak them.
|
|
5014
5853
|
// See change: fix-spawn-correlation-ttl-coupling (D7).
|
|
5015
5854
|
pendingPromptAcks.dispose();
|
|
@@ -5033,6 +5872,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5033
5872
|
}
|
|
5034
5873
|
homeRendezvous = null;
|
|
5035
5874
|
piGateway.stop();
|
|
5875
|
+
// Await the socket teardown stop() hands off, so stop() never resolves
|
|
5876
|
+
// while it can still touch HOME (and log after a test tore HOME down).
|
|
5877
|
+
await piGateway.stopped();
|
|
5036
5878
|
// Clears pending on-end archive timers + latches the sweeper; after the
|
|
5037
5879
|
// gateway so sessions it ends cannot re-arm one.
|
|
5038
5880
|
// See change: archive-service-sessions-on-end.
|
|
@@ -5047,6 +5889,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5047
5889
|
for (const t of terminalManager.list()) {
|
|
5048
5890
|
try { terminalManager.kill(t.id); } catch {}
|
|
5049
5891
|
}
|
|
5892
|
+
// Wait (bounded, never throws) for in-flight credential writes before the
|
|
5893
|
+
// flows and listeners go away. Adds no delay when nothing is pending.
|
|
5894
|
+
await exitBarrier.settle();
|
|
5050
5895
|
// Abort every in-flight provider OAuth flow (releases callback ports,
|
|
5051
5896
|
// stops device-code polls).
|
|
5052
5897
|
try { const { abortAllFlows } = await import("./auth/provider-auth-adapter.js"); abortAllFlows(); } catch {}
|
|
@@ -5057,6 +5902,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5057
5902
|
}
|
|
5058
5903
|
// The TLS listener (and its open connections) closes with the server.
|
|
5059
5904
|
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
5905
|
+
try { await previewDispatch?.close(); } catch { /* ignore */ }
|
|
5906
|
+
try { liveCapabilities.close(); } catch { /* ignore */ }
|
|
5907
|
+
try { await previewPool?.close(); } catch { /* ignore */ }
|
|
5060
5908
|
await fastify.close();
|
|
5061
5909
|
},
|
|
5062
5910
|
};
|