@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.md +85 -11
- package/docs/architecture.md +3020 -116
- package/package.json +31 -18
- package/packages/extension/package.json +10 -8
- package/packages/extension/src/ask-user-tool.ts +65 -3
- package/packages/extension/src/auto-session-namer.ts +190 -50
- package/packages/extension/src/bridge-handlers/dispatch.ts +504 -0
- package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
- package/packages/extension/src/bridge-handlers/instance.ts +229 -0
- package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -0
- package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
- package/packages/extension/src/bridge-identity-log.ts +45 -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 +517 -2534
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +259 -16
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +294 -24
- package/packages/extension/src/dashboard-context-injector.ts +26 -47
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/empty-actionable-guard.ts +8 -3
- package/packages/extension/src/flow-event-wiring.ts +1 -1
- package/packages/extension/src/followup-buffer.ts +1 -1
- package/packages/extension/src/followup-drain.ts +79 -0
- 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 +232 -17
- package/packages/extension/src/message-update-coalescer.ts +3 -1
- package/packages/extension/src/model-refresh.ts +88 -0
- package/packages/extension/src/multiselect-list.ts +6 -2
- package/packages/extension/src/multiselect-polyfill.ts +2 -2
- package/packages/extension/src/openspec-cli-shim.ts +1 -1
- package/packages/extension/src/path-gate/decide.ts +15 -41
- package/packages/extension/src/path-gate/grant-cache.ts +3 -1
- package/packages/extension/src/path-gate/handler.ts +51 -2
- package/packages/extension/src/path-gate/index.ts +12 -1
- package/packages/extension/src/path-gate/resolve.ts +6 -124
- package/packages/extension/src/path-gate/roots.ts +4 -1
- package/packages/extension/src/path-gate/suppression.ts +4 -1
- package/packages/extension/src/path-gate/yolo-link.ts +104 -0
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +258 -25
- package/packages/extension/src/prompt-expander.ts +5 -1
- package/packages/extension/src/prompt-meta.ts +64 -0
- package/packages/extension/src/provider-register.ts +146 -38
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-manager.ts +5 -4
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +13 -6
- package/packages/extension/src/server-launcher.ts +11 -13
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-move.ts +19 -0
- package/packages/extension/src/session-sync.ts +73 -50
- package/packages/extension/src/spawn-token.ts +46 -0
- package/packages/extension/src/stream-forward-buffer.ts +161 -0
- package/packages/extension/src/subagent-frame-buffer.ts +6 -2
- package/packages/extension/src/subagent-tick-throttle.ts +3 -1
- package/packages/extension/src/vault-delivery.ts +404 -0
- package/packages/extension/src/vault-forwarder.ts +128 -0
- package/packages/extension/src/vault-masker.ts +165 -0
- package/packages/extension/src/vault-redaction.ts +181 -0
- package/packages/extension/src/vcs-info.ts +5 -2
- package/packages/server/bin/pi-dashboard.mjs +26 -89
- package/packages/server/package.json +29 -15
- package/packages/server/src/access/access-grants.ts +79 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- package/packages/server/src/access/agent-confirm-registry.ts +31 -13
- package/packages/server/src/access/agent-grant.ts +1 -1
- package/packages/server/src/access/agent-yolo.ts +91 -0
- package/packages/server/src/access/containment-gate.ts +82 -17
- package/packages/server/src/access/cwd-admission-log.ts +46 -0
- package/packages/server/src/access/cwd-verdict.ts +144 -0
- package/packages/server/src/access/grant-coordinator.ts +3 -1
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
- package/packages/server/src/access/planes.ts +116 -2
- 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/refusal-ledger.ts +6 -6
- package/packages/server/src/access/yolo-session.ts +127 -14
- package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
- package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +549 -0
- package/packages/server/src/acp-bridge/child-env.ts +73 -0
- package/packages/server/src/acp-bridge/event-log.ts +194 -0
- package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
- package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
- package/packages/server/src/acp-bridge/local-host.ts +132 -0
- package/packages/server/src/acp-bridge/main.ts +118 -0
- package/packages/server/src/acp-bridge/models.ts +33 -0
- package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
- package/packages/server/src/acp-bridge/server-requests.ts +136 -0
- package/packages/server/src/acp-bridge/session-state.ts +127 -0
- package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
- package/packages/server/src/addons/addons-catalog.ts +408 -0
- package/packages/server/src/addons/addons-folder-service.ts +347 -0
- package/packages/server/src/addons/addons-folder.ts +310 -0
- package/packages/server/src/addons/addons-service.ts +470 -0
- package/packages/server/src/addons/package-contents.ts +99 -0
- package/packages/server/src/addons/settings-entries.ts +120 -0
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
- package/packages/server/src/auth/approval-refusal.ts +87 -0
- package/packages/server/src/auth/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +329 -97
- package/packages/server/src/auth/auth.ts +102 -11
- package/packages/server/src/auth/bearer-auth.ts +74 -12
- package/packages/server/src/auth/cors-origin.ts +86 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -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 +111 -9
- 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/host-admission.ts +26 -0
- package/packages/server/src/auth/host-gate.ts +6 -1
- package/packages/server/src/auth/local-credential.ts +258 -0
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +76 -22
- package/packages/server/src/auth/local-token.ts +16 -0
- package/packages/server/src/auth/localhost-guard.ts +298 -17
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
- package/packages/server/src/auth/node-guard.ts +43 -0
- package/packages/server/src/auth/operate-required.ts +126 -0
- package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
- package/packages/server/src/auth/passkey/passkey-routes.ts +232 -0
- package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
- package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
- package/packages/server/src/auth/passkey/requester.ts +83 -0
- package/packages/server/src/auth/passkey/rp-context.ts +98 -0
- package/packages/server/src/auth/passkey/user-directory.ts +348 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +324 -0
- 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-registry.ts +35 -1
- package/packages/server/src/auth/provider-auth-storage.ts +61 -9
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/radius-override.ts +13 -0
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/route-tier-gate.ts +27 -11
- package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
- package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
- 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 +197 -0
- package/packages/server/src/auth/trust-mode-boot.ts +93 -0
- package/packages/server/src/auth/trust-mode.ts +83 -0
- package/packages/server/src/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/auto-name-outcome-store.ts +4 -1
- package/packages/server/src/browse.ts +114 -2
- package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
- package/packages/server/src/browser-handlers/directory-handler.ts +151 -6
- 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 +138 -63
- package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
- package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
- package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +1063 -106
- package/packages/server/src/config-api.ts +166 -2
- package/packages/server/src/config-snapshot.ts +53 -1
- package/packages/server/src/directory-service.ts +545 -36
- package/packages/server/src/embed-lifecycle/caps.ts +35 -4
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
- package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
- package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
- package/packages/server/src/event-wiring.ts +349 -141
- package/packages/server/src/file-watch-manager.ts +187 -39
- package/packages/server/src/git-worktree/git-operations.ts +60 -15
- 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/worktree-init-trust.ts +91 -6
- package/packages/server/src/git-worktree/worktree-init.ts +7 -56
- package/packages/server/src/identity/host-resources.ts +3 -0
- package/packages/server/src/identity/http-road-classification.ts +31 -1
- package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
- package/packages/server/src/identity/plugin-identity.ts +19 -0
- package/packages/server/src/identity/policy-registry.ts +4 -1
- package/packages/server/src/identity/resolver-registry.ts +12 -3
- package/packages/server/src/identity/ws-message-scope.ts +10 -0
- package/packages/server/src/identity/ws-road-classification.ts +10 -0
- package/packages/server/src/known-server-moves.ts +196 -0
- package/packages/server/src/lib/browse-roots.ts +137 -0
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/digest-gate.ts +82 -0
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/file-write-lock.ts +24 -0
- package/packages/server/src/lib/folder-project.ts +439 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/purify.ts +13 -5
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-handler-target.ts +66 -0
- package/packages/server/src/lib/writable-md-target.ts +16 -1
- package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
- package/packages/server/src/lifecycle/home-lock.ts +344 -130
- package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
- package/packages/server/src/lifecycle/recovery-server.ts +129 -6
- package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +461 -0
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -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 +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +326 -34
- package/packages/server/src/live-server/live-static.ts +228 -0
- package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
- package/packages/server/src/model-proxy/internal-registry.ts +6 -0
- package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
- package/packages/server/src/openspec/openspec-poll-worker.ts +286 -44
- package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
- package/packages/server/src/openspec/readiness.ts +9 -0
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +1002 -0
- package/packages/server/src/package/installed-package-enricher.ts +38 -3
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/package-health-scanner.ts +133 -0
- package/packages/server/src/package/package-manager-wrapper.ts +18 -2
- package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
- package/packages/server/src/package/provider-probe.ts +13 -5
- package/packages/server/src/pairing/browser-gateway.ts +292 -16
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/knock-admission.ts +277 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +188 -31
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
- package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
- package/packages/server/src/peer-servers.ts +77 -0
- package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
- package/packages/server/src/persistence/boot-state.ts +48 -1
- package/packages/server/src/persistence/memory-event-store.ts +216 -237
- package/packages/server/src/persistence/meta-persistence.ts +12 -1
- package/packages/server/src/persistence/preferences-store.ts +125 -7
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
- package/packages/server/src/pi/folder-commands.ts +141 -0
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
- package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
- package/packages/server/src/pi/host-project-trust.ts +166 -33
- package/packages/server/src/pi/pi-gateway.ts +283 -29
- package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
- package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
- package/packages/server/src/pi/session-skill-registry.ts +13 -3
- package/packages/server/src/pi/settings-write-lock.ts +32 -0
- package/packages/server/src/pi/trust-challenges.ts +38 -0
- package/packages/server/src/pi-agent-settings.ts +701 -100
- package/packages/server/src/pi-settings-themes.ts +104 -0
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/questions/brief-generator.ts +138 -0
- package/packages/server/src/questions/brief-model.ts +55 -0
- package/packages/server/src/questions/brief-policy.ts +36 -0
- package/packages/server/src/questions/brief-prompt.ts +92 -0
- package/packages/server/src/questions/brief-runtime.ts +50 -0
- package/packages/server/src/questions/question-answer.ts +55 -0
- package/packages/server/src/questions/question-broadcast.ts +106 -0
- package/packages/server/src/questions/question-files.ts +128 -0
- package/packages/server/src/questions/question-routes.ts +126 -0
- package/packages/server/src/questions/question-snapshot.ts +150 -0
- package/packages/server/src/questions/question-stack.ts +57 -0
- package/packages/server/src/questions/question-store.ts +477 -0
- package/packages/server/src/routes/access-prompt-routes.ts +5 -3
- package/packages/server/src/routes/access-routes.ts +274 -6
- package/packages/server/src/routes/acme-routes.ts +190 -0
- package/packages/server/src/routes/acp-routes.ts +16 -0
- package/packages/server/src/routes/addons-routes.ts +221 -0
- 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 +620 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
- package/packages/server/src/routes/folder-project-routes.ts +105 -0
- package/packages/server/src/routes/git-routes.ts +334 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +433 -55
- package/packages/server/src/routes/live-server-routes.ts +438 -7
- package/packages/server/src/routes/local-proof-routes.ts +26 -7
- package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
- package/packages/server/src/routes/model-proxy-routes.ts +4 -2
- 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 +636 -55
- package/packages/server/src/routes/package-health-routes.ts +140 -0
- package/packages/server/src/routes/package-routes.ts +86 -11
- package/packages/server/src/routes/pairing-routes.ts +303 -33
- package/packages/server/src/routes/pi-retry-routes.ts +18 -2
- package/packages/server/src/routes/pi-settings-routes.ts +264 -0
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +37 -7
- package/packages/server/src/routes/provider-routes.ts +29 -0
- package/packages/server/src/routes/resource-activation-routes.ts +33 -35
- package/packages/server/src/routes/session-routes.ts +100 -9
- package/packages/server/src/routes/system-routes.ts +286 -33
- package/packages/server/src/routes/tls-routes.ts +55 -0
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/routes/user-routes.ts +192 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
- package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
- package/packages/server/src/server.ts +1537 -246
- package/packages/server/src/services/attached-driver.ts +175 -0
- package/packages/server/src/services/change-notifier.ts +55 -0
- package/packages/server/src/services/cli-service.ts +450 -0
- package/packages/server/src/services/command-runner.ts +92 -0
- package/packages/server/src/services/definitions-store.ts +121 -0
- package/packages/server/src/services/driver.ts +112 -0
- package/packages/server/src/services/health.ts +94 -0
- package/packages/server/src/services/leases.ts +117 -0
- package/packages/server/src/services/log-text.ts +97 -0
- package/packages/server/src/services/native-driver.ts +283 -0
- package/packages/server/src/services/oci-driver.ts +590 -0
- package/packages/server/src/services/output-capture.ts +183 -0
- package/packages/server/src/services/paths.ts +82 -0
- package/packages/server/src/services/ports.ts +26 -0
- package/packages/server/src/services/routes.ts +140 -0
- package/packages/server/src/services/runtime-detect.ts +108 -0
- package/packages/server/src/services/secret-delivery.ts +61 -0
- package/packages/server/src/services/secrets-resolver.ts +145 -0
- package/packages/server/src/services/secrets-store.ts +137 -0
- package/packages/server/src/services/service-manager.ts +1565 -0
- package/packages/server/src/services/start-record.ts +66 -0
- package/packages/server/src/services/state-machine.ts +241 -0
- package/packages/server/src/session/archive-sweeper.ts +92 -3
- package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
- package/packages/server/src/session/memory-session-manager.ts +60 -0
- package/packages/server/src/session/name-provenance.ts +102 -0
- package/packages/server/src/session/open-tool-calls.ts +15 -6
- 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/session-api.ts +47 -12
- package/packages/server/src/session/session-archive.ts +56 -4
- package/packages/server/src/session/session-diff-cache.ts +11 -4
- package/packages/server/src/session/session-load-worker-pool.ts +4 -3
- package/packages/server/src/session/session-load-worker.ts +11 -2
- package/packages/server/src/session/session-scanner.ts +73 -3
- package/packages/server/src/session/session-to-meta.ts +15 -0
- package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
- package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
- package/packages/server/src/spawn-process/process-manager.ts +164 -30
- package/packages/server/src/spawn-process/restart-helper.ts +9 -8
- package/packages/server/src/spawn-process/server-pid.ts +16 -7
- package/packages/server/src/spawn-process/session-terminator.ts +218 -0
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
- package/packages/server/src/terminal/terminal-manager.ts +75 -1
- package/packages/server/src/tls/cert-files.ts +228 -0
- package/packages/server/src/tls/cert-manager.ts +703 -0
- package/packages/server/src/tls/cert-store.ts +69 -0
- package/packages/server/src/tls/source-registry.ts +71 -0
- package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
- package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
- package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
- package/packages/server/src/tls/sources/acme/dns.ts +303 -0
- package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
- package/packages/server/src/tls/sources/acme/entry.ts +180 -0
- package/packages/server/src/tls/sources/acme/gc.ts +78 -0
- package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
- package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
- package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
- package/packages/server/src/tls/sources/acme/types.ts +72 -0
- package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +94 -0
- package/packages/server/src/tls/tls-listener.ts +351 -0
- package/packages/server/src/tls/types.ts +80 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
- package/packages/server/src/tunnel/tunnel-core.ts +4 -1
- package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-bindings.ts +101 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +424 -0
- package/packages/server/src/vault/vault-grants.ts +260 -0
- package/packages/server/src/vault/vault-import.ts +161 -0
- package/packages/server/src/vault/vault-permissions.ts +39 -0
- package/packages/server/src/vault/vault-plugin-read.ts +64 -0
- package/packages/server/src/vault/vault-projects.ts +156 -0
- package/packages/server/src/vault/vault-routes.ts +277 -0
- package/packages/server/src/vault/vault-store.ts +371 -0
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/shared/package.json +5 -2
- package/packages/shared/src/acp/acp-config.ts +123 -0
- package/packages/shared/src/acp/normalize-v1.ts +92 -0
- package/packages/shared/src/acp/paths.ts +36 -0
- package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
- package/packages/shared/src/acp/update-model.ts +574 -0
- package/packages/shared/src/anthropic-messages-source.ts +8 -0
- package/packages/shared/src/bind-reachability.ts +21 -2
- package/packages/shared/src/boot-state.ts +6 -0
- package/packages/shared/src/browser-host-identity.ts +49 -0
- package/packages/shared/src/browser-host-ipc.ts +107 -0
- package/packages/shared/src/browser-protocol.ts +533 -73
- package/packages/shared/src/canonical-subject.ts +27 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/card-sections.ts +185 -1
- package/packages/shared/src/chrome-profiles.ts +188 -0
- package/packages/shared/src/config.ts +817 -51
- package/packages/shared/src/containment-guard.ts +35 -0
- package/packages/shared/src/custom-event-groups.ts +5 -2
- package/packages/shared/src/cwd-guard.ts +381 -1
- package/packages/shared/src/dashboard-paths.ts +12 -0
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -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 +9 -3
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
- package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +139 -2
- package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
- package/packages/shared/src/dashboard-starter.ts +30 -0
- package/packages/shared/src/display-name.ts +42 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +119 -134
- package/packages/shared/src/enabled-models-match.ts +47 -0
- package/packages/shared/src/event-forward-declaration.ts +187 -0
- package/packages/shared/src/file-kind.ts +54 -2
- package/packages/shared/src/git-worktree-helpers.ts +8 -4
- package/packages/shared/src/grammar-types.ts +3 -1
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/host-port.ts +34 -0
- package/packages/shared/src/launcher-origin.ts +26 -0
- package/packages/shared/src/live-server.ts +141 -0
- package/packages/shared/src/local-credential-proof.ts +219 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
- package/packages/shared/src/markup-repair/types.ts +13 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/md-table-cell.ts +11 -0
- package/packages/shared/src/mdns-discovery.ts +414 -45
- package/packages/shared/src/models-json-reader.ts +6 -0
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-design-evidence.ts +25 -1
- package/packages/shared/src/openspec-poller.ts +213 -11
- package/packages/shared/src/openspec-status-all.ts +393 -0
- package/packages/shared/src/operate-required.ts +29 -0
- package/packages/shared/src/pairing-knock-client.ts +301 -0
- package/packages/shared/src/pairing-knock.ts +71 -0
- package/packages/shared/src/pairing-refusal.ts +32 -0
- package/packages/shared/src/path-containment-guard-name.ts +8 -0
- package/packages/shared/src/pi-settings-keys.ts +9 -0
- package/packages/shared/src/pi-settings-schema.ts +285 -0
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
- package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
- package/packages/shared/src/pi-trust-mirror.ts +354 -0
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/binary-lookup.ts +2 -194
- 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 +210 -4
- package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
- package/packages/shared/src/platform/native-ts-register.mjs +22 -10
- package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
- package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
- package/packages/shared/src/platform/node-spawn.ts +1 -2
- package/packages/shared/src/platform/openspec.ts +129 -31
- package/packages/shared/src/platform/process-scan.ts +199 -1
- package/packages/shared/src/platform/process.ts +99 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/runner.ts +46 -2
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
- package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
- package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
- package/packages/shared/src/plugin-bridge-register.ts +24 -1
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-name.ts +42 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/prompt-answer.ts +183 -0
- package/packages/shared/src/protocol.ts +172 -8
- package/packages/shared/src/question-types.ts +73 -0
- package/packages/shared/src/recommended-extensions.ts +98 -23
- package/packages/shared/src/recovery-timing.ts +39 -0
- package/packages/shared/src/redaction.ts +50 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +533 -3
- package/packages/shared/src/role-config-disk.ts +23 -0
- package/packages/shared/src/role-schema.ts +79 -0
- package/packages/shared/src/route-tiers.ts +181 -0
- 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/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-identity.ts +51 -15
- package/packages/shared/src/server-launcher.ts +21 -34
- package/packages/shared/src/server-pinning.ts +136 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/services/offers.ts +114 -0
- package/packages/shared/src/services/schema.ts +628 -0
- package/packages/shared/src/services/status.ts +169 -0
- package/packages/shared/src/session-meta.ts +59 -2
- package/packages/shared/src/session-name.ts +8 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/skill-block-parser.ts +14 -0
- package/packages/shared/src/source-matching.ts +5 -1
- package/packages/shared/src/state-replay.ts +19 -0
- package/packages/shared/src/terminal-safe.ts +24 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tls-status.ts +69 -0
- package/packages/shared/src/tool-path-resolve.ts +243 -0
- package/packages/shared/src/tool-registry/definitions.ts +31 -9
- package/packages/shared/src/tool-registry/index.ts +2 -2
- package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
- package/packages/shared/src/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/tunnel-provider.ts +3 -2
- package/packages/shared/src/types.ts +170 -9
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +88 -0
- package/packages/shared/src/vault-origin.ts +51 -0
- package/packages/shared/src/vault-project-key.ts +53 -0
- package/packages/shared/src/worktree-init-hook.ts +69 -0
- package/packages/shared/src/ws-message-tiers.ts +136 -0
- package/tsconfig.base.json +1 -0
|
@@ -2,35 +2,36 @@
|
|
|
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, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, resolvePluginEnabled } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
11
|
+
import { createGatedProviderAuth, createIsPiExtensionInstalled, createPluginServiceRegistry, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginServerAllowed, pluginSpawnToSessionOptions, redactPluginConfigForClient, refreshRequirementProbesFor, registerPluginAssetsRoute, resolvePluginEnabled, type ServerLoadDeps, setDeclaredBundledPluginIds } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
12
|
+
import {
|
|
13
|
+
createMcpClientConfigService,
|
|
14
|
+
createRealConfigIO,
|
|
15
|
+
} from "@blackbelt-technology/pi-dashboard-mcp-core";
|
|
12
16
|
import type { ExitIntent } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
|
|
13
17
|
import { isRecoveryAllowed } from "@blackbelt-technology/pi-dashboard-shared/boot-state.js";
|
|
14
18
|
import { findBundledExtension, registerBridgeExtension } from "@blackbelt-technology/pi-dashboard-shared/bridge-register.js";
|
|
15
19
|
import type { PackageOperationCompleteMessage, ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
|
|
16
20
|
import type { AuthConfig, DashboardConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
17
|
-
import fastifyCookie from "@fastify/cookie";
|
|
18
|
-
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
19
21
|
import { CONFIG_DIR, CONFIG_FILE, getPluginConfig as getPluginConfigFromFile, loadConfig, resolvePublicBaseUrls, writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
20
|
-
import { createPushService, type PushService } from "./push/push-service.js";
|
|
21
|
-
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
22
22
|
import { CustomEventGroupsStore } from "@blackbelt-technology/pi-dashboard-shared/custom-event-groups-store.js";
|
|
23
|
-
import
|
|
23
|
+
import { parseFileHandlerClaimKey } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/file-handler.js";
|
|
24
24
|
import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
|
|
25
|
-
import {
|
|
25
|
+
import type { HostAction, HostResource, Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
|
|
26
|
+
import { advertiseDashboard, createBrowser, type DashboardBrowser, type DiscoveredServer, resolveAdvertisedAddresses, stopAdvertising } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
26
27
|
import { DEFAULT_MEMORY_LIMITS } from "@blackbelt-technology/pi-dashboard-shared/memory-limits.js";
|
|
27
|
-
import { setWindowsGitSourceSetting } from "@blackbelt-technology/pi-dashboard-shared/platform/git-source.js";
|
|
28
28
|
import {
|
|
29
|
-
reconcilePluginBridgePackages,
|
|
30
29
|
deregisterPluginBridge,
|
|
31
|
-
|
|
30
|
+
reconcilePluginBridgePackages,
|
|
31
|
+
syncPluginBridges,
|
|
32
32
|
} from "@blackbelt-technology/pi-dashboard-shared/plugin-bridge-register.js";
|
|
33
|
-
import {
|
|
33
|
+
import type { PluginRequestMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
34
|
+
import { RECOVERY_REATTACH_GRACE_MS, RECOVERY_SHUTDOWN_WINDOW_MS } from "@blackbelt-technology/pi-dashboard-shared/recovery-timing.js";
|
|
34
35
|
import {
|
|
35
36
|
deriveEffectiveSource,
|
|
36
37
|
deriveLocalIdentity,
|
|
@@ -38,47 +39,66 @@ import {
|
|
|
38
39
|
readRuntimeRequest,
|
|
39
40
|
readRuntimeState,
|
|
40
41
|
} from "@blackbelt-technology/pi-dashboard-shared/runtime-overlay/state.js";
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
42
|
+
import { proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
|
|
43
|
+
import { discoverServiceOffers } from "@blackbelt-technology/pi-dashboard-shared/services/offers.js";
|
|
44
|
+
import { isRecoveryCandidate, isShutdownWindowCandidate, mergeSessionMeta, type SessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
|
|
45
|
+
import { rank } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
|
|
46
|
+
import { getDefaultRegistry, resolveInstallRoot } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
|
|
43
47
|
import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
48
|
+
import { LIVE_PREVIEW_TIER, TERMINAL_TIER } from "@blackbelt-technology/pi-dashboard-shared/ws-message-tiers.js";
|
|
44
49
|
import compress from "@fastify/compress";
|
|
50
|
+
import fastifyCookie from "@fastify/cookie";
|
|
45
51
|
import cors from "@fastify/cors";
|
|
46
52
|
import rateLimit from "@fastify/rate-limit";
|
|
47
53
|
import fastifyStatic from "@fastify/static";
|
|
48
|
-
import Fastify from "fastify";
|
|
54
|
+
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
|
|
55
|
+
import { listGrants as listAccessGrants, setGrantsChangedListener, setSessionGrantsChangedListener } from "./access/access-grants.js";
|
|
49
56
|
import { snapshotAccessGrantHealth } from "./access/access-health.js";
|
|
50
57
|
import { AccessPlaneRegistry, isGrantPromptKilled } from "./access/access-plane.js";
|
|
51
58
|
import { shouldIssuePromptCapability } from "./access/capability-issuance.js";
|
|
52
59
|
import { createCorsDenialObserver } from "./access/cors-denial.js";
|
|
60
|
+
import { createIndeterminateLogger } from "./access/cwd-admission-log.js";
|
|
61
|
+
import { createCwdHold } from "./access/cwd-verdict.js";
|
|
53
62
|
import { installGrantCoordinator } from "./access/denial-hold.js";
|
|
54
63
|
import { GrantCoordinator } from "./access/grant-coordinator.js";
|
|
55
64
|
import { ensureGrantStoreId } from "./access/grant-store-id.js";
|
|
56
|
-
import {
|
|
65
|
+
import { createPiTrustLiveProvider } from "./access/pi-trust-live.js";
|
|
66
|
+
import { createPiTrustMirrorService, setPiTrustMirror } from "./access/pi-trust-mirror-service.js";
|
|
67
|
+
import { createCorsPlane, createCwdPlane, createFilesystemPlane, createNetworkPlane, createPreviewEgressPlane } from "./access/planes.js";
|
|
68
|
+
import { projectEgressGrants } from "./access/preview-egress-store.js";
|
|
57
69
|
import { promptChannelCount } from "./access/prompt-channel.js";
|
|
70
|
+
import { createDefaultProvisioningGrantStore } from "./access/provisioning.js";
|
|
71
|
+
import { installProvisioning } from "./access/provisioning-wiring.js";
|
|
58
72
|
import { clearRefusal, isRefused, listRefusals, recordRefusal } from "./access/refusal-ledger.js";
|
|
59
73
|
import { sourceChannel } from "./access/source-channel.js";
|
|
60
74
|
import { YOLO_ENV } from "./access/yolo-env.js";
|
|
61
75
|
import { YoloController } from "./access/yolo-session.js";
|
|
76
|
+
import { scanAcpSessions } from "./acp-bridge/acp-restore.js";
|
|
77
|
+
import { stopAllLocalAcpSessions } from "./acp-bridge/local-host.js";
|
|
62
78
|
import { createFitWorkerPool } from "./attachments/fit-worker-pool.js";
|
|
63
79
|
import { resolveRedirectBase } from "./auth/auth.js";
|
|
64
|
-
import { authorizeWsUpgrade, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
80
|
+
import { authorizeWsUpgrade, buildLoginAvailable, effectiveSessionTier, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
65
81
|
import { registerBearerAuth, registerDeviceSessionRoutes } from "./auth/bearer-auth.js";
|
|
82
|
+
import { beginFlow, pluginFlowProvider } from "./auth/begin-flow.js";
|
|
66
83
|
import {
|
|
67
84
|
computeBindReachability,
|
|
68
85
|
formatBindReachabilityWarning,
|
|
69
86
|
initBindReachability,
|
|
70
87
|
} from "./auth/bind-reachability-service.js";
|
|
71
|
-
import { registerLocalProofRoutes } from "./routes/local-proof-routes.js";
|
|
72
|
-
import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
|
|
73
88
|
import { decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
74
89
|
import {
|
|
90
|
+
CORS_ALLOWED_METHODS,
|
|
75
91
|
type CorsOriginOptions,
|
|
76
92
|
isCorsOriginAllowed,
|
|
77
93
|
isPluginWsOriginAdmitted,
|
|
78
94
|
isWsOriginTrusted,
|
|
79
95
|
sanitizeHeaderForLog,
|
|
80
96
|
} from "./auth/cors-origin.js";
|
|
81
|
-
import { registerCsp, resolveCspMode } from "./auth/csp.js";
|
|
97
|
+
import { cspNonceFor, markViteProxied, registerCsp, resolveCspMode, resolveTrustedTypesMode } from "./auth/csp.js";
|
|
98
|
+
import { registerCspReportSink } from "./auth/csp-report-sink.js";
|
|
99
|
+
import { CspReportStore } from "./auth/csp-report-store.js";
|
|
100
|
+
import { stateCallerFor } from "./auth/dashboard-state-caller.js";
|
|
101
|
+
import { isHostAdmitted } from "./auth/host-admission.js";
|
|
82
102
|
import {
|
|
83
103
|
createHostGate,
|
|
84
104
|
evaluateHostGate,
|
|
@@ -89,28 +109,44 @@ import {
|
|
|
89
109
|
resolveHostGateMode,
|
|
90
110
|
} from "./auth/host-gate.js";
|
|
91
111
|
import { ensureServerIdentity } from "./auth/identity.js";
|
|
92
|
-
import {
|
|
112
|
+
import { createLocalCredentialVerifier, hasLocalCredential, listenWithProofFloor } from "./auth/local-credential.js";
|
|
113
|
+
import { createLocalTrustContext, LocalProofCodeStore } from "./auth/local-proof.js";
|
|
114
|
+
import { createLocalProofRefusalLogger } from "./auth/local-proof-refusal-log.js";
|
|
115
|
+
import { ensureLocalToken } from "./auth/local-token.js";
|
|
93
116
|
import {
|
|
117
|
+
createLanInterfaceProvider,
|
|
94
118
|
createNetworkGuard,
|
|
95
119
|
createNetworkGuardHook,
|
|
120
|
+
isLocallyTrusted,
|
|
96
121
|
isPluginScopePeerLocal,
|
|
122
|
+
needsLocalProof,
|
|
97
123
|
noteTrustedList,
|
|
124
|
+
parseGuardTarget,
|
|
125
|
+
setLocalProofRefusalObserver,
|
|
98
126
|
setNetworkDenialObserver,
|
|
99
127
|
} from "./auth/localhost-guard.js";
|
|
100
128
|
import { createMutationOriginGate } from "./auth/mutation-origin-gate.js";
|
|
129
|
+
import { NavIntents } from "./auth/nav-intent.js";
|
|
130
|
+
import { PasskeyService } from "./auth/passkey/passkey-service.js";
|
|
131
|
+
import { resolveRpContext } from "./auth/passkey/rp-context.js";
|
|
132
|
+
import { UserDirectory } from "./auth/passkey/user-directory.js";
|
|
133
|
+
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
134
|
+
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
135
|
+
import { isServerTrusted } from "./auth/plugin-server-trust.js";
|
|
101
136
|
import { setOAuthRegistryRuntimeSource } from "./auth/provider-auth-registry.js";
|
|
102
137
|
import { readAuthJson } from "./auth/provider-auth-storage.js";
|
|
103
|
-
import {
|
|
104
|
-
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
105
|
-
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
106
|
-
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
107
|
-
import type { PluginRequestMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
|
|
138
|
+
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
108
139
|
import { createRouteTierGate } from "./auth/route-tier-gate.js";
|
|
140
|
+
import { RotationError, rotateSecretsOnce } from "./auth/secret-rotation.js";
|
|
141
|
+
import { createHostServeApp } from "./auth/serve-app-host.js";
|
|
109
142
|
import { mintSpawnToken } from "./auth/spawn-token.js";
|
|
143
|
+
import { admissionTrustedNetworks, effectiveTrustMode } from "./auth/trust-mode.js";
|
|
144
|
+
import { decideBootTrustMode } from "./auth/trust-mode-boot.js";
|
|
110
145
|
import {
|
|
111
146
|
type CoreWsRouteScope,
|
|
112
147
|
extractTicket,
|
|
113
148
|
isCoreWsRouteScope,
|
|
149
|
+
mintBridgeTicket,
|
|
114
150
|
routeScopeForUrl,
|
|
115
151
|
setPluginScopeResolver,
|
|
116
152
|
type WsRouteScope,
|
|
@@ -125,51 +161,79 @@ import {
|
|
|
125
161
|
} from "./browser-handlers/session-action-handler.js";
|
|
126
162
|
import { runLifecycleAction } from "./browser-handlers/session-lifecycle.js";
|
|
127
163
|
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
128
|
-
import { readRawConfig, writeConfigPartial } from "./config-api.js";
|
|
164
|
+
import { readRawConfig, seedWindowsSourceSettings, writeConfigPartial } from "./config-api.js";
|
|
129
165
|
import {
|
|
166
|
+
liveAcceptLanRequests,
|
|
130
167
|
liveAllowedHosts,
|
|
131
168
|
liveCorsAllowedOrigins,
|
|
169
|
+
liveCorsAllowZrokWildcard,
|
|
132
170
|
liveHostGateMode,
|
|
133
|
-
|
|
171
|
+
livePreviewExposureOverride,
|
|
134
172
|
livePublicBaseUrls,
|
|
173
|
+
liveRequireLocalProof,
|
|
135
174
|
liveTrustedNetworks,
|
|
136
175
|
rawConfigHasHostGateMode,
|
|
137
176
|
} from "./config-snapshot.js";
|
|
138
177
|
// pending-load-manager removed — server loads sessions directly via DirectoryService
|
|
139
178
|
import { createDirectoryService, type DirectoryService } from "./directory-service.js";
|
|
140
179
|
import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycle-controller.js";
|
|
180
|
+
import { createPluginSessionCloseApi, createSessionCloserRegistry } from "./embed-lifecycle/plugin-session-close.js";
|
|
141
181
|
import { wireEvents } from "./event-wiring.js";
|
|
142
182
|
import { createFileWatchManager } from "./file-watch-manager.js";
|
|
183
|
+
import { resolveMainPath } from "./git-worktree/git-operations.js";
|
|
143
184
|
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
185
|
+
import {
|
|
186
|
+
listPersistedTrust as listPersistedWorktreeTrust,
|
|
187
|
+
listSessionTrust as listSessionWorktreeTrust,
|
|
188
|
+
setSessionTrustChangedListener,
|
|
189
|
+
setTrustChangedListener,
|
|
190
|
+
} from "./git-worktree/worktree-init-trust.js";
|
|
144
191
|
import { identityDisarmedWarning, isIdentityEnforced } from "./identity/activation.js";
|
|
192
|
+
import { buildAuthContext } from "./identity/auth-context.js";
|
|
193
|
+
import { type BootstrapGrants, DENY_ALL_GRANTS, decideBootstrapGrants } from "./identity/bootstrap-grants.js";
|
|
194
|
+
import { BreakGlass } from "./identity/break-glass.js";
|
|
145
195
|
import { browserLoginAuthStatus } from "./identity/browser-login-auth-status.js";
|
|
146
196
|
import { BrowserLoginConfigRegistry, publicLoginConfig, sanitizeBrowserLoginConfig } from "./identity/browser-login-config-registry.js";
|
|
197
|
+
import { dispatchResolvers } from "./identity/dispatch.js";
|
|
198
|
+
import { HostActions, hostResource } from "./identity/host-resources.js";
|
|
147
199
|
import { identityFloorAllows } from "./identity/identity-floor.js";
|
|
200
|
+
import { identityMe } from "./identity/identity-me.js";
|
|
148
201
|
import { IdentityRegistrationTracker, releaseFailedIdentityRegistrations } from "./identity/identity-registration-tracker.js";
|
|
149
|
-
import { PolicyRegistry } from "./identity/policy-registry.js";
|
|
150
202
|
import { createIdentityRoadGate } from "./identity/identity-road-gate.js";
|
|
151
|
-
import {
|
|
152
|
-
import {
|
|
203
|
+
import { createPluginIdentity } from "./identity/plugin-identity.js";
|
|
204
|
+
import { PolicyRegistry } from "./identity/policy-registry.js";
|
|
153
205
|
import { registerResolverHook } from "./identity/resolver-hook.js";
|
|
154
206
|
import { ResolverRegistry } from "./identity/resolver-registry.js";
|
|
155
|
-
import {
|
|
156
|
-
import {
|
|
157
|
-
import { BreakGlass } from "./identity/break-glass.js";
|
|
158
|
-
import { dispatchResolvers } from "./identity/dispatch.js";
|
|
159
|
-
import { createPluginIdentity } from "./identity/plugin-identity.js";
|
|
207
|
+
import { getRouteOwnerRegistry } from "./identity/route-owner-registry.js";
|
|
208
|
+
import { canAccessSession, isLocalOperator, markLocalOperator, sessionPrincipalOf } from "./identity/session-access.js";
|
|
160
209
|
import { scheduleAtExpiry } from "./identity/socket-lifetime.js";
|
|
161
210
|
import { authorizeRoadUpgrade } from "./identity/upgrade-gate.js";
|
|
162
|
-
import {
|
|
163
|
-
import {
|
|
211
|
+
import { createKnownServerMoves } from "./known-server-moves.js";
|
|
212
|
+
import { buildBrowseRootSources, resolveBrowseRoots } from "./lib/browse-roots.js";
|
|
164
213
|
import {
|
|
165
214
|
clientBuildDiagnostic,
|
|
166
215
|
clientBuildSnapshotFor,
|
|
216
|
+
readServedBundledPluginIds,
|
|
167
217
|
resolveStaticClientDir,
|
|
168
218
|
} from "./lib/client-dist.js";
|
|
219
|
+
import { runWithStateCaller } from "./lib/dashboard-state-guard.js";
|
|
220
|
+
import { collectRuleSources } from "./lib/folder-project.js";
|
|
221
|
+
import { createIndexHtmlSender } from "./lib/index-html.js";
|
|
222
|
+
import { listKnownFolderCwds, type RouteAdmissionDeps } from "./lib/route-admission.js";
|
|
169
223
|
import { bootParentPid, isBootParentProvablyDead } from "./lifecycle/boot-parent-liveness.js";
|
|
170
224
|
import { runBoundedStartup } from "./lifecycle/bounded-startup.js";
|
|
171
225
|
import { startEphemeralParentWatch } from "./lifecycle/ephemeral-parent-watch.js";
|
|
172
226
|
import { ensureInstanceId } from "./lifecycle/instance-id.js";
|
|
227
|
+
import {
|
|
228
|
+
createLiveCapabilityHook,
|
|
229
|
+
LiveCapabilityStore,
|
|
230
|
+
parseCapabilityPath,
|
|
231
|
+
redactCapability,
|
|
232
|
+
sessionKeyOf,
|
|
233
|
+
} from "./live-server/live-capability.js";
|
|
234
|
+
import { createReservedHandler } from "./live-server/live-csp-report.js";
|
|
235
|
+
import { createEgressGrantRequester, createPreviewEgress, requestOriginsOf } from "./live-server/live-egress.js";
|
|
236
|
+
import { createPreviewExposure, wirePreviewExposure } from "./live-server/live-exposure.js";
|
|
173
237
|
import { createLiveServerManager } from "./live-server/live-server-manager.js";
|
|
174
238
|
import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
175
239
|
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
@@ -181,10 +245,20 @@ import { getServerModelRuntime } from "./model-proxy/server-model-runtime.js";
|
|
|
181
245
|
import { callPiAiStreamSimple } from "./model-proxy/streamer.js";
|
|
182
246
|
import { currentGlobalWorkflowSignature } from "./openspec/global-signature.js";
|
|
183
247
|
import { createOpenSpecGroupStore, joinGroupIdsToOpenSpecData } from "./openspec/openspec-group-store.js";
|
|
248
|
+
import { fetchPackageMeta } from "./package/npm-search-proxy.js";
|
|
249
|
+
import { logPackageHealthAtBoot } from "./package/package-health-scanner.js";
|
|
184
250
|
import { type OperationResult, PackageManagerWrapper } from "./package/package-manager-wrapper.js";
|
|
185
251
|
import { type BrowserGateway, createBrowserGateway } from "./pairing/browser-gateway.js";
|
|
252
|
+
import { createRequestAccessAvailable, type KnockPeerDeps } from "./pairing/knock-admission.js";
|
|
253
|
+
import { bearerChannelOf, isProvenTls } from "./auth/proven-tls.js";
|
|
254
|
+
import { createDeviceTokenServices } from "./pairing/device-token-services.js";
|
|
255
|
+
import { onTlsBridgeSwitchChanged, routeBridgeUpgrade } from "./tls/tls-bridge-route.js";
|
|
256
|
+
import { startDeviceExpirySweep } from "./vault/device-expiry-sweep.js";
|
|
186
257
|
import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
|
|
187
258
|
import { PairingManager, wirePendingHint } from "./pairing/pairing.js";
|
|
259
|
+
import { stampSocketLocality } from "./pairing/socket-locality.js";
|
|
260
|
+
import type { TieredSocket } from "./pairing/ws-tier-gate.js";
|
|
261
|
+
import { buildSelfServer, wirePeerServers } from "./peer-servers.js";
|
|
188
262
|
import { createPendingArchiveIntentRegistry } from "./pending/pending-archive-intent-registry.js";
|
|
189
263
|
import { createPendingAttachRegistry } from "./pending/pending-attach-registry.js";
|
|
190
264
|
import { createPendingClientCorrelations } from "./pending/pending-client-correlations.js";
|
|
@@ -195,78 +269,106 @@ import { createPendingPrincipalOwnerRegistry } from "./pending/pending-principal
|
|
|
195
269
|
import { createPendingPromptAcks } from "./pending/pending-prompt-acks.js";
|
|
196
270
|
import { createPendingResumeIntentRegistry } from "./pending/pending-resume-intent-registry.js";
|
|
197
271
|
import { createPendingWorktreeBaseRegistry } from "./pending/pending-worktree-base-registry.js";
|
|
198
|
-
import { recordExitIntent, resolveExitIntent, stampBootStart } from "./persistence/boot-state.js";
|
|
272
|
+
import { recordExitIntent, resolveExitIntent, resolveExitRecord, stampBootStart } from "./persistence/boot-state.js";
|
|
199
273
|
import { createMemoryEventStore, DEFAULT_MAX_EVENT_DATA_SIZE, DEFAULT_MAX_STRING_SIZE, type EventStore } from "./persistence/memory-event-store.js";
|
|
200
274
|
import { createMetaPersistence } from "./persistence/meta-persistence.js";
|
|
201
275
|
import { migrateCustomEntryFallbackOverrides } from "./persistence/migrate-custom-entry-fallback.js";
|
|
202
276
|
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
203
277
|
import { createPreferencesStore } from "./persistence/preferences-store.js";
|
|
204
|
-
import {
|
|
278
|
+
import { loadHostProjectTrustService } from "./pi/host-project-trust.js";
|
|
205
279
|
import { PiCoreChecker } from "./pi/pi-core-checker.js";
|
|
206
280
|
import { PiCoreUpdater } from "./pi/pi-core-updater.js";
|
|
207
281
|
import { createPiGateway } from "./pi/pi-gateway.js";
|
|
282
|
+
import { listGlobalSkills } from "./pi/pi-resource-scanner.js";
|
|
283
|
+
import { createPackageCompletionHandler, createPluginDiscoveryWiring, type PluginDiscoveryWiring } from "./plugin-discovery-wiring.js";
|
|
284
|
+
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
208
285
|
import { pluginIntentCache } from "./plugin-intent-cache.js";
|
|
286
|
+
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
287
|
+
import { getRuntimeClientRegistry, installRuntimeClientRegistry, logRuntimeAdmissions } from "./plugin-runtime-clients.js";
|
|
288
|
+
import { createPushService, type PushService } from "./push/push-service.js";
|
|
289
|
+
import type { SessionPresence } from "./questions/question-files.js";
|
|
290
|
+
import { registerQuestionRoutes } from "./questions/question-routes.js";
|
|
291
|
+
import { createAgentEventHub } from "./agent-events/agent-event-hub.js";
|
|
292
|
+
import { registerAgentEventStreamRoutes } from "./routes/agent-event-stream-routes.js";
|
|
293
|
+
import { createQuestionStack, persistedPresence } from "./questions/question-stack.js";
|
|
209
294
|
import { registerAccessPromptRoutes } from "./routes/access-prompt-routes.js";
|
|
210
295
|
import { registerAccessRoutes } from "./routes/access-routes.js";
|
|
296
|
+
import { registerAcmeRoutes } from "./routes/acme-routes.js";
|
|
297
|
+
import { registerAcpRoutes } from "./routes/acp-routes.js";
|
|
298
|
+
import { registerAddonsRoutes } from "./routes/addons-routes.js";
|
|
211
299
|
import { registerAttachmentRoutes } from "./routes/attachment-routes.js";
|
|
212
300
|
import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
|
|
301
|
+
import { registerCspViolationRoutes } from "./routes/csp-violations-routes.js";
|
|
213
302
|
import { registerCustomEventGroupsRoutes } from "./routes/custom-event-groups-routes.js";
|
|
214
303
|
import { registerDoctorRoutes } from "./routes/doctor-routes.js";
|
|
215
|
-
import { registerFileRoutes } from "./routes/file-routes.js";
|
|
304
|
+
import { denialBody, gateFilePath, registerFileRoutes } from "./routes/file-routes.js";
|
|
305
|
+
import { registerFolderProjectRoutes } from "./routes/folder-project-routes.js";
|
|
216
306
|
import { registerGitRoutes } from "./routes/git-routes.js";
|
|
217
307
|
import { registerGrepRoutes } from "./routes/grep-routes.js";
|
|
218
308
|
import { registerHostGateRoutes } from "./routes/host-gate-routes.js";
|
|
219
309
|
import { registerKnownServersRoutes } from "./routes/known-servers-routes.js";
|
|
220
310
|
import { registerLiveServerRoutes } from "./routes/live-server-routes.js";
|
|
311
|
+
import { registerLocalProofRoutes } from "./routes/local-proof-routes.js";
|
|
221
312
|
import { registerManifestRoute } from "./routes/manifest-route.js";
|
|
313
|
+
import { registerMermaidRepairRoutes } from "./routes/mermaid-repair-routes.js";
|
|
222
314
|
import { registerModelProxyApiKeyRoutes } from "./routes/model-proxy-api-key-routes.js";
|
|
223
315
|
import { registerModelProxyDiagnosticsRoutes } from "./routes/model-proxy-diagnostics-routes.js";
|
|
224
316
|
import { registerModelProxyRefreshRoutes } from "./routes/model-proxy-refresh-routes.js";
|
|
225
317
|
import { registerModelProxyRoutes } from "./routes/model-proxy-routes.js";
|
|
226
318
|
import { registerModelsIntrospectionRoute } from "./routes/models-introspection-routes.js";
|
|
319
|
+
import { registerNavIntentRoutes } from "./routes/nav-intent-routes.js";
|
|
227
320
|
import { registerNodeRuntimeRoutes } from "./routes/node-runtime-routes.js";
|
|
228
321
|
import { registerOpenSpecGroupRoutes } from "./routes/openspec-group-routes.js";
|
|
229
322
|
import { registerOpenSpecRoutes } from "./routes/openspec-routes.js";
|
|
323
|
+
import { registerPackageHealthRoutes } from "./routes/package-health-routes.js";
|
|
230
324
|
import { registerPackageRoutes } from "./routes/package-routes.js";
|
|
231
325
|
import { PUBLIC_PAIRING_PREFIXES, registerPairingRoutes } from "./routes/pairing-routes.js";
|
|
232
326
|
import { registerPiChangelogRoutes } from "./routes/pi-changelog-routes.js";
|
|
233
327
|
import { registerPiCoreRoutes } from "./routes/pi-core-routes.js";
|
|
234
328
|
import { registerPiRetryRoutes } from "./routes/pi-retry-routes.js";
|
|
235
329
|
import { registerPiRuntimeRoutes } from "./routes/pi-runtime-routes.js";
|
|
236
|
-
import {
|
|
330
|
+
import { registerPiSettingsRoutes } from "./routes/pi-settings-routes.js";
|
|
331
|
+
import { registerPiTrustQueryRoutes } from "./routes/pi-trust-query-routes.js";
|
|
332
|
+
import { registerPluginActivationRoutes, setPluginsEnabled } from "./routes/plugin-activation-routes.js";
|
|
237
333
|
import { registerPluginConfigRoutes } from "./routes/plugin-config-routes.js";
|
|
334
|
+
import { registerPluginRuntimeClientRoutes } from "./routes/plugin-runtime-client-routes.js";
|
|
238
335
|
import { registerPreferencesAutoNameRoutes } from "./routes/preferences-auto-name-routes.js";
|
|
239
336
|
import { registerPreferencesDisplayRoutes } from "./routes/preferences-display-routes.js";
|
|
240
337
|
import { registerPreferencesWorktreeInitRoutes } from "./routes/preferences-worktree-init-routes.js";
|
|
241
|
-
import {
|
|
242
|
-
createMcpClientConfigService,
|
|
243
|
-
createRealConfigIO,
|
|
244
|
-
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
245
|
-
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
246
338
|
import { registerProviderAuthRoutes } from "./routes/provider-auth-routes.js";
|
|
247
339
|
import { registerProviderRoutes } from "./routes/provider-routes.js";
|
|
340
|
+
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
248
341
|
import { invalidateRecommendedCache, registerRecommendedRoutes } from "./routes/recommended-routes.js";
|
|
249
342
|
import { registerResourceActivationRoutes } from "./routes/resource-activation-routes.js";
|
|
250
343
|
import { registerRuntimeRoutes } from "./routes/runtime-routes.js";
|
|
251
|
-
import { registerSessionRoutes } from "./routes/session-routes.js";
|
|
344
|
+
import { registerSessionRoutes, type ToolResultStats } from "./routes/session-routes.js";
|
|
252
345
|
import { registerSystemRoutes } from "./routes/system-routes.js";
|
|
346
|
+
import { registerTlsRoutes } from "./routes/tls-routes.js";
|
|
253
347
|
import { registerToolRoutes } from "./routes/tool-routes.js";
|
|
348
|
+
import { registerUserRoutes } from "./routes/user-routes.js";
|
|
254
349
|
import {
|
|
255
350
|
dispatchReload as dispatchReloadRaw,
|
|
256
351
|
reloadTargetSessionIds,
|
|
257
352
|
} from "./rpc-keeper/dispatch-reload.js";
|
|
258
353
|
import { activeExtensionFromEnv, createExtensionReloadGuard } from "./runtime-overlay/extension-reload.js";
|
|
259
|
-
import {
|
|
354
|
+
import { buildRuntimeDoctorCheck, bundledFallbackIntact } from "./runtime-overlay/runtime-doctor.js";
|
|
260
355
|
import { buildRuntimeHealth, type RuntimeHealth } from "./runtime-overlay/runtime-health.js";
|
|
261
356
|
import { createStagerDeps, runtimeReleaseFeeds } from "./runtime-overlay/runtime-io.js";
|
|
262
357
|
import { stageRuntime } from "./runtime-overlay/runtime-stager.js";
|
|
263
358
|
import { RuntimeUpdateChecker } from "./runtime-overlay/runtime-update-checker.js";
|
|
264
359
|
import { startServerHeapTelemetry } from "./server-heap-telemetry.js";
|
|
360
|
+
import { defaultCommandRunner } from "./services/command-runner.js";
|
|
361
|
+
import { servicesPaths } from "./services/paths.js";
|
|
362
|
+
import { registerServiceRoutes } from "./services/routes.js";
|
|
363
|
+
import { ServiceManager } from "./services/service-manager.js";
|
|
265
364
|
import { createArchiveSweeper } from "./session/archive-sweeper.js";
|
|
266
365
|
import { CustomEventGroupMatcher } from "./session/custom-event-group-matcher.js";
|
|
267
366
|
import { CustomEventGroupResolver } from "./session/custom-event-group-resolver.js";
|
|
268
367
|
import { deriveEndedAt } from "./session/derive-ended-at.js";
|
|
368
|
+
import { createReplayState } from "./session/hydration-state.js";
|
|
369
|
+
import { createInFlightToolCalls } from "./session/in-flight-tool-calls.js";
|
|
269
370
|
import { createMemorySessionManager, type SessionManager } from "./session/memory-session-manager.js";
|
|
371
|
+
import { systemRenameUpdates } from "./session/name-provenance.js";
|
|
270
372
|
import { applyPluginRef } from "./session/plugin-refs.js";
|
|
271
373
|
import { applyReattachPolicy } from "./session/reattach-placement.js";
|
|
272
374
|
import { reconcileSessionOrder } from "./session/reconcile-session-order.js";
|
|
@@ -276,18 +378,39 @@ import { registerSessionApi } from "./session/session-api.js";
|
|
|
276
378
|
import { createSessionArchive } from "./session/session-archive.js";
|
|
277
379
|
import { discoverAndBroadcastSessions } from "./session/session-bootstrap.js";
|
|
278
380
|
import { createSessionOrderManager, type SessionOrderManager } from "./session/session-order-manager.js";
|
|
279
|
-
import {
|
|
381
|
+
import { originOf } from "./session/session-origin.js";
|
|
382
|
+
import { bootScanAllSessions } from "./session/session-scanner.js";
|
|
280
383
|
import { sessionToMeta } from "./session/session-to-meta.js";
|
|
384
|
+
import { createAbortSpawnedRun } from "./spawn-process/abort-spawned-run.js";
|
|
385
|
+
import { setLocalAcpHost, spawnAcpSession, validatePluginAcpSpawn } from "./spawn-process/acp-spawn.js";
|
|
281
386
|
import { CwdPolicyRegistry } from "./spawn-process/cwd-policy.js";
|
|
282
387
|
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
283
388
|
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
284
389
|
import { getKeeperManager, setCwdPolicyRegistry, spawnPiSession } from "./spawn-process/process-manager.js";
|
|
285
390
|
import { removePid, writePid } from "./spawn-process/server-pid.js";
|
|
391
|
+
import { createSessionTerminator } from "./spawn-process/session-terminator.js";
|
|
392
|
+
import { registerSpawnEnvContributorForPlugin, setSpawnEnvPluginEnabledCheck } from "./spawn-process/spawn-env-contributors.js";
|
|
286
393
|
import { armSpawnWatchdog } from "./spawn-process/spawn-register-watchdog.js";
|
|
287
394
|
import { createTerminalGateway } from "./terminal/terminal-gateway.js";
|
|
288
395
|
import { createTerminalManager, deriveTranscriptCapBytes } from "./terminal/terminal-manager.js";
|
|
396
|
+
import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
|
|
397
|
+
import { acmeGc } from "./tls/sources/acme/gc.js";
|
|
398
|
+
import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
|
|
399
|
+
import {
|
|
400
|
+
MAIN_CONNECTION_TIMEOUT_MS,
|
|
401
|
+
MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
402
|
+
TlsListener,
|
|
403
|
+
} from "./tls/tls-listener.js";
|
|
289
404
|
import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, liveTunnelOrigins, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
|
|
405
|
+
import { collectEndpoints } from "./tunnel/tunnel-endpoints.js";
|
|
290
406
|
import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
|
|
407
|
+
import { createVaultDeliveryHub } from "./vault/vault-delivery-hub.js";
|
|
408
|
+
import { createVaultImport, defaultKnownLocations } from "./vault/vault-import.js";
|
|
409
|
+
import { createPluginVaultReader } from "./vault/vault-plugin-read.js";
|
|
410
|
+
import { createVaultProjects } from "./vault/vault-projects.js";
|
|
411
|
+
import { createVaultManageGuard, registerVaultRoutes } from "./vault/vault-routes.js";
|
|
412
|
+
import { createVaultStore } from "./vault/vault-store.js";
|
|
413
|
+
import { createWatchFilesHandler, type WatchFilesMessage } from "./watch-files-handler.js";
|
|
291
414
|
|
|
292
415
|
export interface ServerConfig {
|
|
293
416
|
port: number;
|
|
@@ -364,6 +487,12 @@ export interface ServerConfig {
|
|
|
364
487
|
/** Shape of the replay window when one applies (`head-tail` | `tail-only`).
|
|
365
488
|
* Absent → `head-tail`. See change: add-tail-only-replay-window (D1). */
|
|
366
489
|
replayWindowMode?: import("@blackbelt-technology/pi-dashboard-shared/memory-limits.js").ReplayWindowMode;
|
|
490
|
+
/**
|
|
491
|
+
* Test seam: shorten the bridge replay fallback exits and the keepalive sent
|
|
492
|
+
* to subscribers waiting on a replay (defaults 5 s idle / 60 s cap / 10 s).
|
|
493
|
+
* See change: fix-large-session-resume-replay (D2).
|
|
494
|
+
*/
|
|
495
|
+
replayTimings?: { idleMs?: number; capMs?: number; keepaliveMs?: number };
|
|
367
496
|
/** OpenSpec polling config (interval, concurrency, change detection, jitter) */
|
|
368
497
|
openspec?: import("@blackbelt-technology/pi-dashboard-shared/config.js").OpenSpecPollConfig;
|
|
369
498
|
/** Push notifications. Absent or `enabled !== true` means disabled (no dispatcher,
|
|
@@ -423,6 +552,8 @@ export interface DashboardServer {
|
|
|
423
552
|
browserGateway: BrowserGateway;
|
|
424
553
|
/** Resolved HTTP port after start() (useful for port:0 in tests). Returns null if not listening. */
|
|
425
554
|
httpPort(): number | null;
|
|
555
|
+
/** The optional TLS listener (off by default). See change: add-tailscale-cert-tls. */
|
|
556
|
+
readonly tls: TlsListener;
|
|
426
557
|
/** Resolved pi gateway port after start(). Returns null if not listening. */
|
|
427
558
|
piPort(): number | null;
|
|
428
559
|
/**
|
|
@@ -478,7 +609,48 @@ function resolvedPiVersion(): string | undefined {
|
|
|
478
609
|
/** Plugin frames that are NOT domain events: replay-cached UI intents and settings echoes. */
|
|
479
610
|
const NON_DOMAIN_PLUGIN_FRAMES: ReadonlySet<string> = new Set(["plugin_intents", "plugin_config_update"]);
|
|
480
611
|
|
|
612
|
+
/**
|
|
613
|
+
* "Also trust this folder in pi": stored with the entry an allow-always just wrote
|
|
614
|
+
* (filesystem → persisted grant; cwd → pin). Best-effort — the grant itself already
|
|
615
|
+
* stands. See change: mirror-dashboard-trust-to-pi.
|
|
616
|
+
*/
|
|
617
|
+
function storePiTrustChoiceOfVerdict(
|
|
618
|
+
mirror: ReturnType<typeof createPiTrustMirrorService>,
|
|
619
|
+
msg: { verdict: string; plane: string; subject: string; piTrust?: boolean },
|
|
620
|
+
): void {
|
|
621
|
+
if (msg.verdict !== "allow-always" || typeof msg.piTrust !== "boolean") return;
|
|
622
|
+
const kind = msg.plane === "filesystem" ? "accessGrants" : msg.plane === "cwd" ? "pinned" : null;
|
|
623
|
+
if (!kind) return;
|
|
624
|
+
try {
|
|
625
|
+
mirror.setChoice(kind, msg.subject, msg.piTrust);
|
|
626
|
+
mirror.refresh();
|
|
627
|
+
} catch (err) {
|
|
628
|
+
console.warn(`[pi-trust-mirror] could not store the pi-trust choice: ${(err as Error)?.message}`);
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
481
632
|
export async function createServer(config: ServerConfig): Promise<DashboardServer> {
|
|
633
|
+
// Decide the network trust mode ONCE, before any hook is installed and before
|
|
634
|
+
// the server listens (so no operator write can race it). Never re-derived
|
|
635
|
+
// from the list afterwards. See change: retire-trusted-networks-bypass (D2).
|
|
636
|
+
decideBootTrustMode();
|
|
637
|
+
// One-shot rotation of the local token + auth secret that a bare-loopback caller
|
|
638
|
+
// may already have read through the `~/.pi` anchor. Must precede every read of
|
|
639
|
+
// either value (the token below, `config.authConfig.secret`). Failure is closed:
|
|
640
|
+
// exit 1 before listening. See change: close-container-loopback-impersonation (D11).
|
|
641
|
+
try {
|
|
642
|
+
const rotation = await rotateSecretsOnce();
|
|
643
|
+
if (rotation.rotated) {
|
|
644
|
+
console.log("[rotation] local token and auth secret rotated once; existing sessions and proof cookies are invalidated");
|
|
645
|
+
if (rotation.newSecret && config.authConfig) config.authConfig.secret = rotation.newSecret;
|
|
646
|
+
}
|
|
647
|
+
} catch (err) {
|
|
648
|
+
if (err instanceof RotationError) {
|
|
649
|
+
console.error(err.describe());
|
|
650
|
+
process.exit(1);
|
|
651
|
+
}
|
|
652
|
+
throw err;
|
|
653
|
+
}
|
|
482
654
|
// Ensure bridge extension is registered in pi's global settings
|
|
483
655
|
// (needed for bundled installs where pi can't discover it from package.json)
|
|
484
656
|
//
|
|
@@ -507,7 +679,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
507
679
|
// Seed Windows git/bash source from config so spawn-env augmentation
|
|
508
680
|
// (ToolResolver.buildSpawnEnv + PTY) picks bundled vs host correctly.
|
|
509
681
|
// No-op on macOS/Linux. See change: embed-git-bash-on-windows.
|
|
510
|
-
|
|
682
|
+
seedWindowsSourceSettings();
|
|
511
683
|
|
|
512
684
|
// Run migration from sessions.json + state.json if needed
|
|
513
685
|
if (needsMigration()) {
|
|
@@ -595,9 +767,22 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
595
767
|
// Local-IPC allowlist token (D10, narrowed): affirmative genuine-local trust
|
|
596
768
|
// for same-host process callers, independent of the forgeable loopback IP.
|
|
597
769
|
const localToken = ensureLocalToken();
|
|
770
|
+
// Endpoint-bound proof of possession, verified ONCE per request at the listener
|
|
771
|
+
// edge; every exemption site reads the stamped verdict via `hasLocalCredential`.
|
|
772
|
+
// `acceptLegacyToken` keeps the deprecated raw `X-Pi-Local-Token` admitted
|
|
773
|
+
// until the 1.0.0 horizon shared with the D10b grace. See change:
|
|
774
|
+
// loopback-credential-proof (D4, D9).
|
|
775
|
+
const localCredential = createLocalCredentialVerifier({ token: localToken, acceptLegacyToken: true });
|
|
776
|
+
// Taken immediately BEFORE each successful bind: a proof minted earlier cannot
|
|
777
|
+
// be for this listener (D3). 0 until `fastify.listen` runs (inject() in tests).
|
|
778
|
+
let httpBoundAt = 0;
|
|
779
|
+
// Same contract for the optional TLS listener (its own bind, its own floor). See change: add-tailscale-cert-tls.
|
|
780
|
+
let tlsBoundAt = 0;
|
|
598
781
|
// Strict local-proof context (`requireLocalProof`, live config read). Threaded to
|
|
599
782
|
// every genuinely-local admission site. See change: harden-trust-and-credential-boundaries (D2).
|
|
600
|
-
|
|
783
|
+
// The proof cookie is bound to the listener's port; `0` until `listen` runs (inject() in tests).
|
|
784
|
+
let httpListenPort = 0;
|
|
785
|
+
const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof, () => httpListenPort);
|
|
601
786
|
const localProofCodes = new LocalProofCodeStore();
|
|
602
787
|
const pairingManager = new PairingManager({
|
|
603
788
|
registry: pairedDeviceRegistry,
|
|
@@ -607,6 +792,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
607
792
|
const tunnelUrl = getTunnelUrl();
|
|
608
793
|
if (tunnelUrl) urls.push(tunnelUrl);
|
|
609
794
|
urls.push(...resolvePublicBaseUrls(loadConfig()));
|
|
795
|
+
// Certificate-backed names of the TLS listener (https only; the https/wss
|
|
796
|
+
// gate in `reachableUrls()` still applies). See change: add-tailscale-cert-tls (D5).
|
|
797
|
+
urls.push(...tlsListener.tlsListenerUrls().map((e) => e.url));
|
|
610
798
|
// Test-only (PI_E2E_SEED): expose the loopback http origin so the
|
|
611
799
|
// Playwright/Docker harness can pair over http://localhost (a genuine
|
|
612
800
|
// secure context) without TLS. `reachableUrls()` re-gates it behind the
|
|
@@ -638,6 +826,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
638
826
|
sessionManager,
|
|
639
827
|
metaPersistence,
|
|
640
828
|
getPinnedDirs: () => preferencesStore.getPinnedDirectories(),
|
|
829
|
+
// Fileless eviction (manual archive / supersede) has no file to reload the
|
|
830
|
+
// events from. `eventStore` is built later; the closure runs after boot.
|
|
831
|
+
// See change: fix-orphaned-ended-session-archive.
|
|
832
|
+
deleteEvents: (id) => { eventStore.deleteEventsForSession(id); },
|
|
641
833
|
});
|
|
642
834
|
const pendingArchiveIntents = createPendingArchiveIntentRegistry();
|
|
643
835
|
// Stable per-boot id stamped into the liveness marker so cold start can
|
|
@@ -670,7 +862,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
670
862
|
|
|
671
863
|
// Restore sessions from per-session .meta.json files (scans ~/.pi/agent/sessions/)
|
|
672
864
|
const scanStartedAt = Date.now();
|
|
673
|
-
|
|
865
|
+
// Boot scan + the service-session backfill (declared leg every boot,
|
|
866
|
+
// one-shot legacy leg stamped in boot-state.json).
|
|
867
|
+
// See change: archive-service-sessions-on-end.
|
|
868
|
+
const scanResult = bootScanAllSessions();
|
|
869
|
+
// Ended ACP sessions live outside the pi sessions dir; restore them as ended.
|
|
870
|
+
// See change: add-acp-session-driver (D12).
|
|
871
|
+
scanResult.sessions.push(...scanAcpSessions());
|
|
674
872
|
const scanMs = Date.now() - scanStartedAt;
|
|
675
873
|
// Seed the archive index from the boot scan: migrated + already-archived
|
|
676
874
|
// rows are indexed, never restored. The one-shot ended+hidden migration and
|
|
@@ -683,6 +881,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
683
881
|
`${scanResult.migrated} migrated, ${scanResult.agedOut} aged-out (${scanMs} ms)`,
|
|
684
882
|
);
|
|
685
883
|
}
|
|
884
|
+
if (scanResult.serviceArchived > 0) {
|
|
885
|
+
console.info(`[archive] service-end-backfill archived ${scanResult.serviceArchived} session(s)`);
|
|
886
|
+
}
|
|
686
887
|
// Interrupted-session recovery candidates discovered on cold start. A
|
|
687
888
|
// candidate (`live===true && status!=="ended"`, see isRecoveryCandidate)
|
|
688
889
|
// was running when the host died. Candidates are NORMALIZED to `ended` on
|
|
@@ -695,7 +896,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
695
896
|
// See change: fix-recovery-offer-dismiss-and-phantom-reopen.
|
|
696
897
|
const recoveryMode = loadConfig().reopenSessionsAfterShutdown;
|
|
697
898
|
const recoveryCandidates: DashboardSession[] = [];
|
|
899
|
+
// Pre-normalization liveness for the question-file boot sweep (cold start forces
|
|
900
|
+
// `ended` below). See change: add-pending-question-stack (D6).
|
|
901
|
+
const persistedSessionPresence = new Map<string, SessionPresence>();
|
|
698
902
|
for (const session of scanResult.sessions) {
|
|
903
|
+
persistedSessionPresence.set(session.id, persistedPresence(session));
|
|
699
904
|
const restored = { ...session, dataUnavailable: true };
|
|
700
905
|
// Positive `exitIntent` gate: a boot that ended by `/api/restart` or
|
|
701
906
|
// `/api/shutdown` left its sessions RUNNING and told every bridge to stay
|
|
@@ -703,13 +908,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
703
908
|
// reattach — after any window that could retract them. Suppress outright,
|
|
704
909
|
// with no timing dependency. See change: fix-recovery-exit-intent.
|
|
705
910
|
const ownerIntent = resolveExitIntent(session.liveEpoch);
|
|
706
|
-
|
|
911
|
+
// ACP sessions are never recovery candidates: nothing can resume one (D15).
|
|
912
|
+
const isAcp = session.driver === "acp";
|
|
913
|
+
const diskCandidate = !isAcp && recoveryMode !== "off" && isRecoveryCandidate({
|
|
707
914
|
live: session.live,
|
|
708
915
|
status: session.status,
|
|
709
916
|
closedReason: session.closedReason,
|
|
710
917
|
recover: session.recover,
|
|
711
918
|
});
|
|
712
|
-
|
|
919
|
+
// Shutdown-window path: on a host shutdown pi exits gracefully and its
|
|
920
|
+
// bridge unregisters BEFORE this server is signalled, so the session is
|
|
921
|
+
// `live:false` on disk and the path above cannot see it. Evaluated on the
|
|
922
|
+
// scanned (pre-normalization) session; its evidence is consumed right
|
|
923
|
+
// here in EVERY mode, so it qualifies on at most one cold start.
|
|
924
|
+
// See change: fix-recovery-pi-signal-unregister (D3, D5, D6).
|
|
925
|
+
const ownerBoot = session.live === true || isAcp ? undefined : resolveExitRecord(session.liveEpoch);
|
|
926
|
+
const windowMatch = !isAcp && isShutdownWindowCandidate(session, ownerBoot, RECOVERY_SHUTDOWN_WINDOW_MS);
|
|
927
|
+
if (windowMatch && session.sessionFile) {
|
|
928
|
+
metaPersistence.setLiveness(session.sessionFile, { live: false, closedReason: session.closedReason });
|
|
929
|
+
}
|
|
930
|
+
const windowCandidate = windowMatch && recoveryMode !== "off";
|
|
931
|
+
if (windowCandidate && ownerBoot && session.endedAt !== undefined) {
|
|
932
|
+
console.info(
|
|
933
|
+
`[recovery] ${session.id}: shutdown-window (ended ${((ownerBoot.at - session.endedAt) / 1000).toFixed(1)}s ` +
|
|
934
|
+
`before boot ${ownerBoot.bootId} exit via ${ownerBoot.exitIntent})`,
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
const candidate = (diskCandidate && isRecoveryAllowed(ownerIntent)) || windowCandidate;
|
|
713
938
|
if (diskCandidate && !candidate) {
|
|
714
939
|
console.info(
|
|
715
940
|
`[recovery] ${session.id}: suppressed-by-intent (boot ${session.liveEpoch} exited via ${ownerIntent})`,
|
|
@@ -1056,11 +1281,25 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1056
1281
|
// Optional second-port Fastify instance for model proxy (/v1/*)
|
|
1057
1282
|
let secondFastify: Awaited<ReturnType<typeof import("fastify").default>> | null = null;
|
|
1058
1283
|
const peerServers = new Map<string, DiscoveredServer>();
|
|
1284
|
+
// Verified move suggestions for renamed known servers (in memory only).
|
|
1285
|
+
// See change: stabilize-mdns-server-identity.
|
|
1286
|
+
const knownServerMoves = createKnownServerMoves({
|
|
1287
|
+
loadKnown: () => loadConfig().knownServers,
|
|
1288
|
+
prove: (baseUrl) => proveServerIdentity(baseUrl, { timeoutMs: 2000 }),
|
|
1289
|
+
});
|
|
1059
1290
|
|
|
1060
1291
|
/** This process's place in the per-HOME rendezvous (task 2.0a). */
|
|
1061
1292
|
let homeRendezvous: import("./lifecycle/home-rendezvous.js").HomeRendezvous | null = null;
|
|
1062
1293
|
|
|
1294
|
+
/** Live `tls.enabled && tls.acceptBridges`: the one read behind bridge routing, vault trust and the switch hook. */
|
|
1295
|
+
const tlsBridgesLive = (): boolean => {
|
|
1296
|
+
const live = loadConfig().tls;
|
|
1297
|
+
return live.enabled && live.acceptBridges;
|
|
1298
|
+
};
|
|
1299
|
+
// The vault hub is created further down; the gateway reports routing changes through this late binding.
|
|
1300
|
+
let onVaultRoutingChanged: ((sessionId: string, declared?: { certValidation?: "enforced" }) => void) | undefined;
|
|
1063
1301
|
const piGateway = createPiGateway(sessionManager, {
|
|
1302
|
+
onRoutingChanged: (sessionId, declared) => onVaultRoutingChanged?.(sessionId, declared),
|
|
1064
1303
|
...(config.pingInterval !== undefined ? { pingInterval: config.pingInterval } : {}),
|
|
1065
1304
|
// The identity a move TARGET announces on `provisional_accepted`, so the
|
|
1066
1305
|
// mover can prove it reached the instance it named (D14). Unset, every
|
|
@@ -1081,7 +1320,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1081
1320
|
// A loopback bridge that presents the local token is authorised on its
|
|
1082
1321
|
// own credential rather than on the grace — the only local credential
|
|
1083
1322
|
// Windows has, since it gets no unix socket (D6, task 5.3).
|
|
1084
|
-
|
|
1323
|
+
verifyCredential: localCredential,
|
|
1085
1324
|
},
|
|
1086
1325
|
// Bridge-silence verdict. The browser cannot observe silence itself — it
|
|
1087
1326
|
// receives `processMetrics` once, in the connect snapshot, and nothing
|
|
@@ -1152,8 +1391,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1152
1391
|
const fitWorkerPool = createFitWorkerPool({ size: 2 });
|
|
1153
1392
|
|
|
1154
1393
|
// Create terminal manager with exit callback
|
|
1394
|
+
// PTY caps + inline orphan TTL from `terminals.*` (restart to apply).
|
|
1395
|
+
// See change: harden-server-capability-bounds (D3).
|
|
1396
|
+
const terminalsConfig = loadConfig().terminals;
|
|
1155
1397
|
const terminalManager = createTerminalManager({
|
|
1156
1398
|
transcriptCapBytes,
|
|
1399
|
+
maxConcurrent: terminalsConfig.maxConcurrent,
|
|
1400
|
+
maxPerOwner: terminalsConfig.maxPerOwner,
|
|
1401
|
+
inlineOrphanTtlMs: terminalsConfig.inlineOrphanTtlMs,
|
|
1157
1402
|
onExit: (terminalId) => {
|
|
1158
1403
|
// Find and remove from session order
|
|
1159
1404
|
const allOrders = sessionOrderManager.getAllOrders();
|
|
@@ -1170,9 +1415,53 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1170
1415
|
const terminalGateway = createTerminalGateway(terminalManager);
|
|
1171
1416
|
|
|
1172
1417
|
// Live-server-preview manager (loopback dev-server allowlist + proxy).
|
|
1173
|
-
|
|
1418
|
+
// Ports the dashboard itself listens on are never previewable (a loopback origin is trusted
|
|
1419
|
+
// by its CORS / mutation gates). See change: improve-canvas-html-and-url-ux (D1).
|
|
1420
|
+
const liveServerManager = createLiveServerManager(preferencesStore, {
|
|
1421
|
+
ownPorts: () => {
|
|
1422
|
+
const tls = loadConfig().tls;
|
|
1423
|
+
return [config.port, config.piPort, ...(tls?.enabled ? [tls.port] : [])];
|
|
1424
|
+
},
|
|
1425
|
+
});
|
|
1174
1426
|
|
|
1175
|
-
|
|
1427
|
+
// ACP host A (in-process): attach virtual connections to THIS gateway.
|
|
1428
|
+
// See change: add-acp-session-driver (D1).
|
|
1429
|
+
setLocalAcpHost({ attachLocalConnection: (socket) => piGateway.attachLocalConnection(socket), log: (line) => console.error(line) });
|
|
1430
|
+
|
|
1431
|
+
// Pending-question stack: snapshot + brief per open question, durable across restart.
|
|
1432
|
+
// Boot: load persisted question files, then drop those of unknown/ended sessions
|
|
1433
|
+
// (no timer sweep). See change: add-pending-question-stack (D6).
|
|
1434
|
+
const { store: questionStore } = createQuestionStack({
|
|
1435
|
+
eventStore,
|
|
1436
|
+
sessionManager,
|
|
1437
|
+
getConfig: () => loadConfig().questions,
|
|
1438
|
+
});
|
|
1439
|
+
questionStore.loadPersisted();
|
|
1440
|
+
questionStore.sweepAtBoot((sessionId) => persistedSessionPresence.get(sessionId) ?? "unknown");
|
|
1441
|
+
|
|
1442
|
+
// Shared roots for browse confinement + the remote folder gate (ONE definition).
|
|
1443
|
+
// Project-scope grants only: session-scope grants are transient.
|
|
1444
|
+
// See change: harden-server-capability-bounds (D2).
|
|
1445
|
+
const browseRootSources = buildBrowseRootSources({
|
|
1446
|
+
preferencesStore,
|
|
1447
|
+
sessionManager,
|
|
1448
|
+
worktreeRoots: () => listPersistedWorktreeTrust().map((t) => t.repoRoot),
|
|
1449
|
+
projectGrants: () => listAccessGrants().filter((g) => g.scope === "project").map((g) => g.subject),
|
|
1450
|
+
});
|
|
1451
|
+
// `browse.confineRemote: false` (operator opt-out, read at start) => `null` = unconfined.
|
|
1452
|
+
const confineRemoteBrowse = loadConfig().browse.confineRemote;
|
|
1453
|
+
const browseRoots = () => (confineRemoteBrowse ? resolveBrowseRoots(browseRootSources) : Promise.resolve(null));
|
|
1454
|
+
|
|
1455
|
+
const replayState = createReplayState(config.replayTimings);
|
|
1456
|
+
const browserGateway = createBrowserGateway(sessionManager, eventStore, piGateway, undefined, pendingForkRegistry, sessionOrderManager, preferencesStore, directoryService, terminalManager, pendingDashboardSpawns, config.maxWsBufferBytes, pendingAttachRegistry, pendingInitialPromptRegistry, pendingResumeIntents, pendingClientCorrelations, pendingWorktreeBaseRegistry, metaPersistence, fitWorkerPool, config.maxReplayEvents, config.replayWindowMode, sessionArchive, pendingArchiveIntents, remoteTranscriptStore, pendingPrincipalOwnerRegistry, identityEnforced, undefined, questionStore, browseRoots, replayState);
|
|
1457
|
+
// Transition-only feed behind `GET /api/events/stream` (registry frames + question changes).
|
|
1458
|
+
// See change: add-agent-event-stream.
|
|
1459
|
+
const agentEventHub = createAgentEventHub({
|
|
1460
|
+
listQuestionRows: () => questionStore.listRows(),
|
|
1461
|
+
ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
|
|
1462
|
+
});
|
|
1463
|
+
browserGateway.onRegistryFrame(agentEventHub.onRegistryFrame);
|
|
1464
|
+
questionStore.onChange(agentEventHub.onQuestionChange);
|
|
1176
1465
|
// App-wide pairing approval dialog: a content-free hint on every pending
|
|
1177
1466
|
// change; operator browsers refetch the guarded list (D1).
|
|
1178
1467
|
// See change: add-pairing-approval-dialog.
|
|
@@ -1198,21 +1487,6 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1198
1487
|
isViewed: (id) => browserGateway.viewedSessionTracker.isViewedByAnyone(id),
|
|
1199
1488
|
});
|
|
1200
1489
|
|
|
1201
|
-
// Editor-pane changed-on-disk watch: the browser declares its open files via
|
|
1202
|
-
// `watch_files`; the server watches exactly those and pushes `file_changed`.
|
|
1203
|
-
// Torn down on disconnect so no fd leaks. See change: split-editor-workspace.
|
|
1204
|
-
const fileWatchManager = createFileWatchManager();
|
|
1205
|
-
browserGateway.registerHandler("watch_files", (msg: { sessionId?: string; cwd?: string; paths?: unknown }, _ws) => {
|
|
1206
|
-
if (!msg?.sessionId || !msg?.cwd) return;
|
|
1207
|
-
// Gate: only watch under a known session cwd (mirrors /api/file).
|
|
1208
|
-
if (!sessionManager.listAll().some((s) => s.cwd === msg.cwd)) return;
|
|
1209
|
-
// Harden against a malformed client payload: keep only string rel-paths.
|
|
1210
|
-
const paths = Array.isArray(msg.paths) ? msg.paths.filter((p): p is string => typeof p === "string") : [];
|
|
1211
|
-
fileWatchManager.setWatched(_ws, msg.sessionId, msg.cwd, paths, (sessionId, path) =>
|
|
1212
|
-
browserGateway.broadcast({ type: "file_changed", sessionId, path }),
|
|
1213
|
-
);
|
|
1214
|
-
});
|
|
1215
|
-
browserGateway.registerDisconnectHandler((ws) => fileWatchManager.clearConnection(ws));
|
|
1216
1490
|
|
|
1217
1491
|
// Resolve package version once at startup
|
|
1218
1492
|
const __require = createRequire(import.meta.url);
|
|
@@ -1230,15 +1504,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1230
1504
|
|
|
1231
1505
|
// Send this server + discovered peers to new browser connections
|
|
1232
1506
|
browserGateway.onConnect = (ws) => {
|
|
1233
|
-
const selfServer
|
|
1507
|
+
const selfServer = buildSelfServer({
|
|
1234
1508
|
host: selfHostname,
|
|
1235
1509
|
port: config.port,
|
|
1236
1510
|
piPort: config.piPort,
|
|
1237
1511
|
version: pkgVersion,
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
};
|
|
1512
|
+
fingerprint: serverIdentity.fingerprint,
|
|
1513
|
+
name: loadConfig().dashboardName || selfHostname.replace(/\.local$/i, ""),
|
|
1514
|
+
});
|
|
1242
1515
|
const all = [selfServer, ...Array.from(peerServers.values())];
|
|
1243
1516
|
browserGateway.sendToClient(ws, { type: "servers_discovered", servers: all });
|
|
1244
1517
|
if (pendingRecoveryOffer) browserGateway.sendToClient(ws, pendingRecoveryOffer);
|
|
@@ -1327,6 +1600,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1327
1600
|
// death signal, even when no terminal pi event was forwarded.
|
|
1328
1601
|
// See change: finalize-automation-run-on-session-death.
|
|
1329
1602
|
const pluginSessionEndSubs = new Set<(sessionId: string) => void>();
|
|
1603
|
+
// Post-boot plugin discovery (refreshPluginDiscovery + local-scope detection); built right
|
|
1604
|
+
// after the boot `loadServerEntries` pass. See change: decouple-plugins-from-core (5.5, 5.9).
|
|
1605
|
+
let pluginDiscovery: PluginDiscoveryWiring | undefined;
|
|
1330
1606
|
// Plugin shutdown subscribers (ServerPluginContext.onShutdown). Dispatched
|
|
1331
1607
|
// in server stop() at the exact point the goal supervisor disposes today —
|
|
1332
1608
|
// BEFORE piGateway.stop() tears bridges down — so plugin backoff timers /
|
|
@@ -1347,32 +1623,134 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1347
1623
|
// loader's topological order guarantees a provider's registerPlugin runs
|
|
1348
1624
|
// before a dependent's consume. In-process only.
|
|
1349
1625
|
// See change: register-plugin-automation-events.
|
|
1350
|
-
|
|
1626
|
+
// Records the PROVIDER plugin per key and enforces `automation.action.<source>`
|
|
1627
|
+
// key ownership (provider id MUST equal <source>). Host-set entries
|
|
1628
|
+
// (`.set`) carry provider "host". See change: harden-git-terminal-plugin-boundaries (D16).
|
|
1629
|
+
const pluginServiceRegistry = createPluginServiceRegistry();
|
|
1630
|
+
// Manifest `emits` per plugin, recorded at context creation. A plugin's types
|
|
1631
|
+
// count only while it is LOADED (status store, live), so an unloaded or
|
|
1632
|
+
// disabled provider's types leave every allowlist at once.
|
|
1633
|
+
const pluginManifestEmits = new Map<string, readonly string[]>();
|
|
1634
|
+
const loadedManifestEmits = (pluginId: string): readonly string[] | undefined =>
|
|
1635
|
+
getPluginStatusStore().getStatus(pluginId)?.loaded === true ? pluginManifestEmits.get(pluginId) : undefined;
|
|
1636
|
+
// Read-only lookup for the automation action registry's subset check.
|
|
1637
|
+
pluginServiceRegistry.set("host.pluginManifestEmits", loadedManifestEmits);
|
|
1351
1638
|
// Host-provided known-folder set for plugin cwd validation: session cwds ∪
|
|
1352
1639
|
// pinned directories, as a LIVE getter (not a boot-time snapshot) so plugins
|
|
1353
1640
|
// see folders added later. kb-plugin consumes this to guard its /api/kb/*
|
|
1354
1641
|
// routes against arbitrary-path indexing — a session-less worktree appears
|
|
1355
1642
|
// only via pinned dirs, unreachable from the plugin sessionManager surface.
|
|
1356
1643
|
// See change: add-kb-folder-slot.
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1644
|
+
// The ONE known-set function: core git/openspec/folder-project route admission uses it
|
|
1645
|
+
// too. See change: core-cwd-admission.
|
|
1646
|
+
const knownFolderCwds = (): string[] => listKnownFolderCwds({ sessionManager, preferencesStore });
|
|
1647
|
+
pluginServiceRegistry.set("host.knownFolderCwds", knownFolderCwds);
|
|
1648
|
+
// `indeterminate` plugin cwd admissions (a git probe that did not complete)
|
|
1649
|
+
// are worth a log line — today they are invisible — but throttled per cwd and
|
|
1650
|
+
// LRU-bounded. Plugins pass this as `admitCwd`'s `onIndeterminate`.
|
|
1651
|
+
// See change: harden-plugin-cwd-admission (D7).
|
|
1652
|
+
const cwdAdmissionLogger = createIndeterminateLogger({ warn: (m) => console.warn(m) });
|
|
1653
|
+
pluginServiceRegistry.set("host.cwdAdmissionOnIndeterminate", cwdAdmissionLogger);
|
|
1654
|
+
// Cwd admission of the file-family routes, live preview and `watch_files`: the same known set and
|
|
1655
|
+
// indeterminate logger as the plugin / git / openspec routes. See change: core-file-cwd-admission.
|
|
1656
|
+
const fileRouteAdmission: RouteAdmissionDeps = {
|
|
1657
|
+
knownCwds: knownFolderCwds,
|
|
1658
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
1659
|
+
};
|
|
1660
|
+
// Editor-pane changed-on-disk watch: the browser declares its open files via
|
|
1661
|
+
// `watch_files`; the server watches exactly those and pushes `file_changed`.
|
|
1662
|
+
// Torn down on disconnect so no fd leaks. See change: split-editor-workspace.
|
|
1663
|
+
// The cwd is admitted through the shared guard (change: core-file-cwd-admission).
|
|
1664
|
+
const watchFiles = createWatchFilesHandler({
|
|
1665
|
+
routeAdmission: fileRouteAdmission,
|
|
1666
|
+
manager: createFileWatchManager(),
|
|
1667
|
+
onChange: (sessionId, path) => browserGateway.broadcast({ type: "file_changed", sessionId, path }),
|
|
1362
1668
|
});
|
|
1669
|
+
browserGateway.registerHandler("watch_files", (msg: WatchFilesMessage, ws) => {
|
|
1670
|
+
// The gateway does not await custom handlers: a rejection must not escape it.
|
|
1671
|
+
watchFiles.handle(msg, ws).catch((err: unknown) => {
|
|
1672
|
+
console.warn(`[watch_files] handler failed: ${(err as Error)?.message ?? err}`);
|
|
1673
|
+
});
|
|
1674
|
+
});
|
|
1675
|
+
browserGateway.registerDisconnectHandler((ws) => watchFiles.onDisconnect(ws));
|
|
1363
1676
|
// pi's project-trust rule as a SESSION applies it (recorded decision, else
|
|
1364
1677
|
// `defaultProjectTrust`), consumed by mcp-client to decide whether a
|
|
1365
1678
|
// folder's `.pi/mcp.json` is active. Resolved once; an unresolvable pi reads
|
|
1366
1679
|
// every project as untrusted. See change: migrate-mcp-to-pi-builtin (D3).
|
|
1367
|
-
|
|
1680
|
+
// Durable dashboard trust is mirrored into pi's `project_trust` through a
|
|
1681
|
+
// server-written snapshot (rebuilt now from the persisted stores, so a crash
|
|
1682
|
+
// between a revoke's two writes heals at boot). See change: mirror-dashboard-trust-to-pi.
|
|
1683
|
+
// Server-lifetime ("live") trust: session worktree trust, session grants, YOLO
|
|
1684
|
+
// roots. Counted into the snapshot as `liveCount` only; the YOLO controller is
|
|
1685
|
+
// constructed further down, so it is read through a late-bound reference.
|
|
1686
|
+
// See change: mirror-dashboard-trust-live-remote.
|
|
1687
|
+
let yoloForLiveTrust: YoloController | undefined;
|
|
1688
|
+
const piTrustLive = createPiTrustLiveProvider({
|
|
1689
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
1690
|
+
listSessionTrust: listSessionWorktreeTrust,
|
|
1691
|
+
listSessionGrants: () => listAccessGrants().filter((g) => g.scope === "session"),
|
|
1692
|
+
getYolo: () => yoloForLiveTrust,
|
|
1693
|
+
});
|
|
1694
|
+
const piTrustMirror = createPiTrustMirrorService({
|
|
1695
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
1696
|
+
listPinned: () => preferencesStore.getPinnedDirectories(),
|
|
1697
|
+
listWorkspaceFolders: () => preferencesStore.getWorkspaces().flatMap((w) => w.folders),
|
|
1698
|
+
listWorktreeTrust: listPersistedWorktreeTrust,
|
|
1699
|
+
listPersistedGrants: () => listAccessGrants().filter((g) => g.scope === "project"),
|
|
1700
|
+
live: piTrustLive,
|
|
1701
|
+
});
|
|
1702
|
+
setPiTrustMirror(piTrustMirror);
|
|
1703
|
+
try {
|
|
1704
|
+
piTrustMirror.rebuildAtBoot();
|
|
1705
|
+
} catch (err) {
|
|
1706
|
+
console.warn(`[pi-trust-mirror] boot snapshot rebuild failed: ${(err as Error)?.message}`);
|
|
1707
|
+
}
|
|
1708
|
+
// Any source change refreshes the snapshot (coalesced); operator revokes additionally
|
|
1709
|
+
// go through the ordered `revoke` path in their handlers.
|
|
1710
|
+
let mirrorRefreshQueued = false;
|
|
1711
|
+
const queueMirrorRefresh = (): void => {
|
|
1712
|
+
if (mirrorRefreshQueued) return;
|
|
1713
|
+
mirrorRefreshQueued = true;
|
|
1714
|
+
setImmediate(() => {
|
|
1715
|
+
mirrorRefreshQueued = false;
|
|
1716
|
+
piTrustMirror.refresh();
|
|
1717
|
+
});
|
|
1718
|
+
};
|
|
1719
|
+
preferencesStore.onPinsChanged?.(queueMirrorRefresh);
|
|
1720
|
+
preferencesStore.onWorkspacesChanged(queueMirrorRefresh);
|
|
1721
|
+
setGrantsChangedListener(queueMirrorRefresh);
|
|
1722
|
+
setTrustChangedListener(queueMirrorRefresh);
|
|
1723
|
+
// Session entries never reach disk, so their listeners recompute the live count
|
|
1724
|
+
// synchronously (the snapshot is rewritten before the action reports success).
|
|
1725
|
+
setSessionGrantsChangedListener(() => piTrustMirror.noteLiveChanged());
|
|
1726
|
+
setSessionTrustChangedListener(() => piTrustMirror.noteLiveChanged());
|
|
1727
|
+
const hostProjectTrust = await loadHostProjectTrustService();
|
|
1728
|
+
pluginServiceRegistry.set("host.isProjectTrusted", hostProjectTrust.isProjectTrusted);
|
|
1729
|
+
pluginServiceRegistry.set("host.projectTrustSource", hostProjectTrust.projectTrustSource);
|
|
1730
|
+
pluginServiceRegistry.set("host.piTrustCoverInteractive", () => loadConfig().piTrustMirror.coverInteractive);
|
|
1731
|
+
// cwd-policy as the spawn funnel composes it, so the team plugin can refuse a
|
|
1732
|
+
// start whose skill set the policy would narrow. See change: add-team-skill-access (D7).
|
|
1733
|
+
pluginServiceRegistry.set("host.resolveCwdPolicy", (cwd: string) => cwdPolicyRegistry.resolve(cwd));
|
|
1734
|
+
// Operator-visible (global + global-package) skills for the team plugin's
|
|
1735
|
+
// admin skill picker. Never project-local. See change: add-team-skill-access (D11).
|
|
1736
|
+
pluginServiceRegistry.set("host.listOperatorSkills", async () =>
|
|
1737
|
+
listGlobalSkills(path.join(os.homedir(), ".pi", "agent")).map((s) => ({
|
|
1738
|
+
name: s.name,
|
|
1739
|
+
description: s.description ?? "",
|
|
1740
|
+
path: path.dirname(s.filePath),
|
|
1741
|
+
source: "global" as const,
|
|
1742
|
+
})),
|
|
1743
|
+
);
|
|
1368
1744
|
// Host services consumed by mcp-server-plugin. Registered HERE because the
|
|
1369
1745
|
// plugin must verify a device bearer WITHOUT going through the global
|
|
1370
1746
|
// `onRequest` hook — `/mcp` deliberately does not trust
|
|
1371
1747
|
// `request.isAuthenticated`, so it needs the registry directly.
|
|
1372
1748
|
// See change: add-dashboard-mcp-server.
|
|
1749
|
+
const deviceTokenServices = createDeviceTokenServices(pairedDeviceRegistry);
|
|
1373
1750
|
pluginServiceRegistry.set(
|
|
1374
1751
|
"host.verifyDeviceToken",
|
|
1375
|
-
(
|
|
1752
|
+
// The request is optional (the plugin host services receive none today): absent → non-proven, fail closed.
|
|
1753
|
+
deviceTokenServices.verifyDeviceToken,
|
|
1376
1754
|
);
|
|
1377
1755
|
// Tier-aware service board entry (change: expand-mcp-tiered-surface, D1).
|
|
1378
1756
|
// A NEW key, not a signature change to the old one: `mcp-server-plugin` is
|
|
@@ -1381,7 +1759,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1381
1759
|
// `host.verifyDeviceToken` with `tier: "operate"`.
|
|
1382
1760
|
pluginServiceRegistry.set(
|
|
1383
1761
|
"host.verifyDeviceTokenTier",
|
|
1384
|
-
|
|
1762
|
+
deviceTokenServices.verifyDeviceTokenTier,
|
|
1385
1763
|
);
|
|
1386
1764
|
// Prefers the BOUND port, falls back to the CONFIGURED one.
|
|
1387
1765
|
//
|
|
@@ -1430,6 +1808,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1430
1808
|
for (const h of pluginSessionEndSubs) {
|
|
1431
1809
|
try { h(sessionId); } catch (err) { console.error("[plugin-onSessionEnded]", err); }
|
|
1432
1810
|
}
|
|
1811
|
+
pluginDiscovery?.onSessionEnded();
|
|
1812
|
+
}
|
|
1813
|
+
// A bridge registered: a cwd not yet scanned may carry local-scope plugins. Deferred one tick so the
|
|
1814
|
+
// session is in the manager's active list. See change: decouple-plugins-from-core (task 5.9).
|
|
1815
|
+
function dispatchSessionRegisteredCwd(cwd: string): void {
|
|
1816
|
+
setImmediate(() => pluginDiscovery?.onSessionRegistered(cwd));
|
|
1433
1817
|
}
|
|
1434
1818
|
// Notify a resolved session's OWNING plugin only. Routed by ownerId so no
|
|
1435
1819
|
// plugin sees another's ref. See change: detach-automation-goal-from-core.
|
|
@@ -1492,7 +1876,58 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1492
1876
|
// Name the grant store this dashboard writes (exclusive-create, never overwritten);
|
|
1493
1877
|
// announced to each bridge on registration. See change: ask-agent-file-access-in-chat.
|
|
1494
1878
|
ensureGrantStoreId();
|
|
1879
|
+
// Live-only in-flight hint + route answer counters shared by the event wiring,
|
|
1880
|
+
// the tool-result route and `/api/health`. See change:
|
|
1881
|
+
// distinguish-tool-result-pending-vs-gone (D2, D6).
|
|
1882
|
+
const inFlightToolCalls = createInFlightToolCalls();
|
|
1883
|
+
const toolResultStats: ToolResultStats = { pending: 0, gone: 0 };
|
|
1884
|
+
// Credential vault: store + delivery hub. The hub answers bridge sync
|
|
1885
|
+
// requests and pushes on every vault write / config change; values travel only
|
|
1886
|
+
// on the session-private bridge lane. See change: add-credential-vault.
|
|
1887
|
+
const vaultStore = createVaultStore();
|
|
1888
|
+
// ACME DNS-01 certificate source: solver secrets live in this vault (kind `tls-solver`).
|
|
1889
|
+
// GC of orphaned namespaces/account keys runs once at start. See change: add-acme-dns01-certs.
|
|
1890
|
+
configureAcmeRuntime({ credentials: createAcmeCredentials(vaultStore) });
|
|
1891
|
+
acmeGc().catch(() => undefined);
|
|
1892
|
+
// Remembered projects for the vault project picker; a sibling of vault.json, created on the first recorded project.
|
|
1893
|
+
const vaultProjects = createVaultProjects({ file: path.join(path.dirname(vaultStore.filePath), "vault-projects.json") });
|
|
1894
|
+
const vaultDelivery = createVaultDeliveryHub({
|
|
1895
|
+
store: vaultStore,
|
|
1896
|
+
projects: vaultProjects,
|
|
1897
|
+
getOrigin: (sessionId) => {
|
|
1898
|
+
const session = sessionManager.get(sessionId);
|
|
1899
|
+
return session ? originOf(session) : undefined;
|
|
1900
|
+
},
|
|
1901
|
+
send: (sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
1902
|
+
isSessionConnected: (sessionId) => piGateway.getConnectedSessionIds().includes(sessionId),
|
|
1903
|
+
isDeliveryEnabled: () => loadConfig().vault.deliveryEnabled,
|
|
1904
|
+
getGraceHours: () => loadConfig().vault.offlineGraceHours,
|
|
1905
|
+
// What the hub itself observed about each socket, and the registry's view of the device behind it
|
|
1906
|
+
// (prove-vault-bridge-tls D3-D5). A TLS-admitted channel also needs the switch live-on.
|
|
1907
|
+
getChannel: (sessionId) => piGateway.channelOf(sessionId),
|
|
1908
|
+
getDeviceTrust: (deviceId) => pairedDeviceRegistry.deviceTrust(deviceId),
|
|
1909
|
+
isTlsBridgesLive: tlsBridgesLive,
|
|
1910
|
+
exposurePending: () => pairedDeviceRegistry.exposurePending(),
|
|
1911
|
+
});
|
|
1912
|
+
onVaultRoutingChanged = (sessionId, declared) => vaultDelivery.handleRegister(sessionId, declared);
|
|
1913
|
+
// Revoke, rotation, add and a first plaintext exposure withdraw within the push debounce (~150 ms).
|
|
1914
|
+
pairedDeviceRegistry.onChange(() => vaultDelivery.schedulePush());
|
|
1915
|
+
// Time-based expiry has no event: a 30 s sweep pushes only when a device LEFT the active set.
|
|
1916
|
+
const stopDeviceExpirySweep = startDeviceExpirySweep({
|
|
1917
|
+
activeIds: () => pairedDeviceRegistry.activeIds(),
|
|
1918
|
+
onLeft: () => vaultDelivery.schedulePush(),
|
|
1919
|
+
});
|
|
1495
1920
|
wireEvents({
|
|
1921
|
+
replayState,
|
|
1922
|
+
inFlightToolCalls,
|
|
1923
|
+
vaultDelivery,
|
|
1924
|
+
// Lazy: `yolo` is constructed further down; a pre-init call throws and the
|
|
1925
|
+
// handler declines. See change: yolo-covers-agent-path-gate.
|
|
1926
|
+
decideAgentPath: (p) =>
|
|
1927
|
+
yolo.decideAgentPath({
|
|
1928
|
+
path: p,
|
|
1929
|
+
hostGateMode: resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
1930
|
+
}),
|
|
1496
1931
|
onBridgeRegister: (sid, identity) => {
|
|
1497
1932
|
const outcome = extensionReloadGuard.onRegister(sid, identity);
|
|
1498
1933
|
if (outcome !== "skipped") {
|
|
@@ -1527,12 +1962,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1527
1962
|
dispatchPluginRequest,
|
|
1528
1963
|
dispatchPluginRawEvent,
|
|
1529
1964
|
dispatchPluginSessionEnded,
|
|
1965
|
+
dispatchSessionRegisteredCwd,
|
|
1530
1966
|
metaPersistence,
|
|
1531
1967
|
liveEpoch,
|
|
1532
1968
|
commitDraftRelay,
|
|
1533
1969
|
customEventGroupResolver,
|
|
1534
1970
|
sessionArchive,
|
|
1535
1971
|
pendingArchiveIntents,
|
|
1972
|
+
// On-end archive of declared-disposable sessions. See change: archive-service-sessions-on-end.
|
|
1973
|
+
archiveSweeper,
|
|
1536
1974
|
});
|
|
1537
1975
|
|
|
1538
1976
|
// Auto-shutdown idle timer
|
|
@@ -1556,8 +1994,36 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1556
1994
|
|
|
1557
1995
|
const fastify = Fastify({
|
|
1558
1996
|
logger: false,
|
|
1559
|
-
keepAliveTimeout:
|
|
1560
|
-
connectionTimeout:
|
|
1997
|
+
keepAliveTimeout: MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
1998
|
+
connectionTimeout: MAIN_CONNECTION_TIMEOUT_MS,
|
|
1999
|
+
// Add-ons feature ids embed a local package's absolute path (`pkg:local:/…`), which exceeds
|
|
2000
|
+
// find-my-way's default 100-char param limit (414). See change: addons-hub-folder-view.
|
|
2001
|
+
maxParamLength: 1024,
|
|
2002
|
+
});
|
|
2003
|
+
|
|
2004
|
+
// Optional native TLS listener (off by default): a second `https.Server` that
|
|
2005
|
+
// dispatches into THIS Fastify instance — one route table, one gate chain, one
|
|
2006
|
+
// upgrade switch, two transports. Reconciled after `listen`; failure-isolated.
|
|
2007
|
+
// See change: add-tailscale-cert-tls (D1).
|
|
2008
|
+
let tlsUpgrade: ((req: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer) => void) | null = null;
|
|
2009
|
+
const tlsListener = new TlsListener({
|
|
2010
|
+
dataRoot: path.join(os.homedir(), ".pi", "dashboard", "tls"),
|
|
2011
|
+
getTlsConfig: () => loadConfig().tls,
|
|
2012
|
+
beforeBind: (at) => {
|
|
2013
|
+
tlsBoundAt = at;
|
|
2014
|
+
},
|
|
2015
|
+
dispatch: {
|
|
2016
|
+
request: (req, res) => {
|
|
2017
|
+
fastify.server.emit("request", req, res);
|
|
2018
|
+
},
|
|
2019
|
+
upgrade: (req, socket, head) => {
|
|
2020
|
+
if (tlsUpgrade) tlsUpgrade(req, socket, head);
|
|
2021
|
+
else socket.destroy();
|
|
2022
|
+
},
|
|
2023
|
+
clientError: (err, socket) => {
|
|
2024
|
+
fastify.server.emit("clientError", err, socket);
|
|
2025
|
+
},
|
|
2026
|
+
},
|
|
1561
2027
|
});
|
|
1562
2028
|
|
|
1563
2029
|
// Route inventory (test-only): fires as each route registers, before listen,
|
|
@@ -1568,6 +2034,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1568
2034
|
fastify.addHook("onRoute", (route) => collect({ method: route.method, url: route.url }));
|
|
1569
2035
|
}
|
|
1570
2036
|
|
|
2037
|
+
// Local credential edge stamp: registered BEFORE every other hook (including
|
|
2038
|
+
// the rate limiter) so no later hook can read an unverified request.
|
|
2039
|
+
// See change: loopback-credential-proof (D4).
|
|
2040
|
+
fastify.addHook("onRequest", async (request) => {
|
|
2041
|
+
localCredential.stamp(request.raw, {
|
|
2042
|
+
kind: "http",
|
|
2043
|
+
boundAt: (request.raw.socket as import("node:tls").TLSSocket).encrypted ? tlsBoundAt : httpBoundAt,
|
|
2044
|
+
});
|
|
2045
|
+
});
|
|
2046
|
+
|
|
1571
2047
|
// Global rate limiter. Two jobs: a real remote-caller ceiling, and making the
|
|
1572
2048
|
// app recognizable to static analysis (`js/missing-rate-limiting` otherwise
|
|
1573
2049
|
// flags every authenticated route handler). Loopback is allow-listed so
|
|
@@ -1617,6 +2093,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1617
2093
|
// config-override-oauth-redirect-base (D15).
|
|
1618
2094
|
const corsAllowedOrigins = () => liveCorsAllowedOrigins(config.corsAllowedOrigins ?? []);
|
|
1619
2095
|
const corsTrustedNetworks = () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []);
|
|
2096
|
+
// The ONE live, mode-dependent admission list (`[]` under `pair`) every
|
|
2097
|
+
// admission site reads per request — never a boot copy.
|
|
2098
|
+
// See change: retire-trusted-networks-bypass (D1).
|
|
2099
|
+
const admissionList = () => admissionTrustedNetworks(config.resolvedTrustedNetworks ?? []);
|
|
1620
2100
|
// Host-admission gate (issue #637, design D1/D4/D6) — the DNS-rebinding
|
|
1621
2101
|
// defence. Under rebinding the attacker page is SAME-ORIGIN with the
|
|
1622
2102
|
// dashboard, so its GETs carry no Origin and its peer is loopback: every
|
|
@@ -1649,6 +2129,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1649
2129
|
// IP bind is already covered by the IP-literal rule; this matters when
|
|
1650
2130
|
// the bind is a NAME.
|
|
1651
2131
|
bindHost: config.host,
|
|
2132
|
+
// Exact certificate names of the TLS listener (empty unless enabled + bound).
|
|
2133
|
+
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
1652
2134
|
},
|
|
1653
2135
|
...resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()),
|
|
1654
2136
|
});
|
|
@@ -1672,9 +2154,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1672
2154
|
// which single origin we mint OAuth URIs and set cookies for.
|
|
1673
2155
|
// See change: add-zrok-custom-reserved-name (D4).
|
|
1674
2156
|
getLiveTunnelOrigins: liveTunnelOrigins,
|
|
2157
|
+
// Opt-in zrok wildcard for CORS READS only (B19); admission forces it off.
|
|
2158
|
+
allowZrokWildcard: liveCorsAllowZrokWildcard(),
|
|
1675
2159
|
allowedHosts: liveAllowedHosts(),
|
|
1676
2160
|
publicBaseUrls: livePublicBaseUrls(),
|
|
1677
2161
|
bindHost: config.host,
|
|
2162
|
+
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
1678
2163
|
// Env-over-config, resolved the SAME way as the hook (D4): a mixed state
|
|
1679
2164
|
// (env=report + config=enforce) must keep the Origin gate's report-only
|
|
1680
2165
|
// behaviour in step with the hook, else the escape hatch only half-engages.
|
|
@@ -1696,11 +2181,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1696
2181
|
grantPlanes.register(createFilesystemPlane());
|
|
1697
2182
|
grantPlanes.register(createCwdPlane({ pinDirectory: (dir) => preferencesStore.pinDirectory(dir) }));
|
|
1698
2183
|
grantPlanes.register(
|
|
1699
|
-
createNetworkPlane({
|
|
2184
|
+
createNetworkPlane({
|
|
2185
|
+
readTrustedNetworks: () => loadConfig().trustedNetworks ?? [],
|
|
2186
|
+
writeConfigPartial,
|
|
2187
|
+
networkTrustActive: () => effectiveTrustMode().mode === "legacy",
|
|
2188
|
+
}),
|
|
1700
2189
|
);
|
|
1701
2190
|
grantPlanes.register(
|
|
1702
2191
|
createCorsPlane({ readRawCors: () => (readRawConfig().cors ?? {}) as Record<string, unknown>, writeConfigPartial }),
|
|
1703
2192
|
);
|
|
2193
|
+
// Preview egress: an external https origin a restricted live preview may load, granted per project.
|
|
2194
|
+
// The dashboard's own origins (tunnels, public base URLs, configured CORS origins) are never grantable.
|
|
2195
|
+
// See change: improve-canvas-html-and-url-ux (D7).
|
|
2196
|
+
const previewEgressOwnOrigins = (): string[] =>
|
|
2197
|
+
[getTunnelUrl(), ...liveTunnelOrigins(), ...livePublicBaseUrls(), ...corsAllowedOrigins()].flatMap((u) => {
|
|
2198
|
+
try {
|
|
2199
|
+
return typeof u === "string" && u ? [new URL(u).origin] : [];
|
|
2200
|
+
} catch {
|
|
2201
|
+
return [];
|
|
2202
|
+
}
|
|
2203
|
+
});
|
|
2204
|
+
grantPlanes.register(createPreviewEgressPlane({ ownOrigins: previewEgressOwnOrigins }));
|
|
1704
2205
|
// YOLO (design D13): consulted at the prompt point; the refusal ledger stops it
|
|
1705
2206
|
// reversing an explicit deny. Environment activation is attempted once, at
|
|
1706
2207
|
// boot, and refused outright in report mode or on any unusable root.
|
|
@@ -1708,6 +2209,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1708
2209
|
hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
1709
2210
|
isRefused,
|
|
1710
2211
|
});
|
|
2212
|
+
yoloForLiveTrust = yolo;
|
|
2213
|
+
yolo.setChangeListener(() => piTrustMirror.noteLiveChanged());
|
|
1711
2214
|
const yoloBoot = yolo.activateFromEnv(process.env[YOLO_ENV]);
|
|
1712
2215
|
if (yoloBoot.ok) {
|
|
1713
2216
|
const s = yoloBoot.session;
|
|
@@ -1732,11 +2235,53 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1732
2235
|
});
|
|
1733
2236
|
installGrantCoordinator(grantCoordinator);
|
|
1734
2237
|
browserGateway.registerHandler("grant_response", (msg) => {
|
|
1735
|
-
grantCoordinator
|
|
1736
|
-
|
|
1737
|
-
|
|
2238
|
+
grantCoordinator
|
|
2239
|
+
.onResponse(msg)
|
|
2240
|
+
.then(() => storePiTrustChoiceOfVerdict(piTrustMirror, msg))
|
|
2241
|
+
.catch((err: unknown) => {
|
|
2242
|
+
console.error(`[access-grant] grant_response failed: ${(err as Error)?.message ?? err}`);
|
|
2243
|
+
});
|
|
2244
|
+
});
|
|
2245
|
+
// Access provisioning (change: add-access-provisioning): the registry wired to the gateway's
|
|
2246
|
+
// operator sockets (live capability AND operate tier), with its per-request expiry timers.
|
|
2247
|
+
const provisioning = installProvisioning({
|
|
2248
|
+
gateway: browserGateway,
|
|
2249
|
+
deps: {
|
|
2250
|
+
now: Date.now,
|
|
2251
|
+
grants: createDefaultProvisioningGrantStore(),
|
|
2252
|
+
// Same two calls as `storePiTrustChoiceOfVerdict`: store the choice, then refresh the snapshot.
|
|
2253
|
+
mirror: () => ({
|
|
2254
|
+
setChoice: (kind, folder, choice) => {
|
|
2255
|
+
piTrustMirror.setChoice(kind, folder, choice);
|
|
2256
|
+
piTrustMirror.refresh();
|
|
2257
|
+
},
|
|
2258
|
+
}),
|
|
2259
|
+
ladder: {
|
|
2260
|
+
killSwitch: () => isGrantPromptKilled(),
|
|
2261
|
+
promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
|
|
2262
|
+
hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
2263
|
+
},
|
|
2264
|
+
},
|
|
1738
2265
|
});
|
|
2266
|
+
browserGateway.registerHandler("provision_response", provisioning.onResponse);
|
|
2267
|
+
// REST refusals whose only fault is missing local proof: one bounded line per (route, reason) per window.
|
|
2268
|
+
// See change: close-container-loopback-impersonation (D6).
|
|
2269
|
+
const localProofRefusalLog = createLocalProofRefusalLogger();
|
|
2270
|
+
setLocalProofRefusalObserver((request) =>
|
|
2271
|
+
localProofRefusalLog.log({
|
|
2272
|
+
peer: request.ip,
|
|
2273
|
+
host: request.headers.host,
|
|
2274
|
+
method: request.method,
|
|
2275
|
+
route: request.routeOptions?.url,
|
|
2276
|
+
reason: "local_proof_required",
|
|
2277
|
+
}),
|
|
2278
|
+
);
|
|
1739
2279
|
setNetworkDenialObserver((request) => {
|
|
2280
|
+
// `pair`: a network match grants nothing, so a denial is not a trust request
|
|
2281
|
+
// — the block event is still recorded (by the guard), but no network prompt
|
|
2282
|
+
// is raised; the operator is asked when the device knocks.
|
|
2283
|
+
// See change: retire-trusted-networks-bypass (D6).
|
|
2284
|
+
if (effectiveTrustMode().mode === "pair") return;
|
|
1740
2285
|
grantCoordinator.onDenial(
|
|
1741
2286
|
{
|
|
1742
2287
|
plane: "network",
|
|
@@ -1783,6 +2328,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1783
2328
|
cb(null, isCorsOriginAllowed(origin ?? undefined, corsOpts()));
|
|
1784
2329
|
},
|
|
1785
2330
|
credentials: true,
|
|
2331
|
+
methods: CORS_ALLOWED_METHODS,
|
|
1786
2332
|
});
|
|
1787
2333
|
// Close the rate-limiter's log window on a timer so the `suppressed <n>`
|
|
1788
2334
|
// summary lands even when no further refusal arrives (D5). Unref'd: a
|
|
@@ -1803,7 +2349,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1803
2349
|
// `PI_DASHBOARD_CSP=enforce` flips to enforcing once report-only is clean.
|
|
1804
2350
|
// Skips proxied prefixes (/editor, /live) so their own policies stand.
|
|
1805
2351
|
// See change: improve-content-editor (§7).
|
|
1806
|
-
|
|
2352
|
+
// Trusted Types rides the same hook under its own `PI_DASHBOARD_TRUSTED_TYPES`
|
|
2353
|
+
// mode (also stamped into index.html as a meta). See change: harden-client-sinks (D7).
|
|
2354
|
+
const cspMode = resolveCspMode(process.env.PI_DASHBOARD_CSP);
|
|
2355
|
+
const trustedTypesMode = resolveTrustedTypesMode(process.env.PI_DASHBOARD_TRUSTED_TYPES, cspMode);
|
|
2356
|
+
registerCsp(fastify, cspMode, trustedTypesMode);
|
|
1807
2357
|
|
|
1808
2358
|
// Register auth plugin if configured (must be before routes)
|
|
1809
2359
|
// Decorate isAuthenticated once, up front, so both the bearer branch and the
|
|
@@ -1817,6 +2367,77 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1817
2367
|
// Bearer device-auth branch — registered BEFORE the OAuth plugin so its
|
|
1818
2368
|
// onRequest hook runs first and OAuth can early-return when already
|
|
1819
2369
|
// authenticated. Additive (D5/D7); independent of whether OAuth is on.
|
|
2370
|
+
// Live-preview capability paths (change: retire-trusted-networks-bypass, D5).
|
|
2371
|
+
// The hook runs BEFORE the bearer / OAuth / identity hooks: a preview request
|
|
2372
|
+
// carries no cookie (opaque-origin frame), so it would otherwise be refused
|
|
2373
|
+
// there. It admits ONLY a valid `/live/<id>/~c/<token>/…` raw path.
|
|
2374
|
+
// Liveness is re-checked at every use, so a revoked device, an ended session
|
|
2375
|
+
// or a removed target is refused on its next request.
|
|
2376
|
+
const liveCapabilities = new LiveCapabilityStore({
|
|
2377
|
+
isTargetLive: (id) => liveServerManager.has(id),
|
|
2378
|
+
isPrincipalLive: (p) => {
|
|
2379
|
+
if (p.identityExpiresAt !== undefined && p.identityExpiresAt <= Date.now()) return false;
|
|
2380
|
+
// Minted on network trust alone: only valid while network trust still authenticates.
|
|
2381
|
+
if (p.kind === "network") return effectiveTrustMode().mode === "legacy";
|
|
2382
|
+
if (p.kind === "device") return pairedDeviceRegistry.list().some((d) => d.id === p.deviceId);
|
|
2383
|
+
if (p.kind === "session" && p.session) return effectiveSessionTier(p.session, passkeyService) !== null;
|
|
2384
|
+
return true;
|
|
2385
|
+
},
|
|
2386
|
+
});
|
|
2387
|
+
// An evicted preset / static target takes its tokens with it.
|
|
2388
|
+
liveServerManager.setEvictionListener((id) => liveCapabilities.revokeByTarget(id));
|
|
2389
|
+
// Per-token egress state (markup scan, CSP reports, allow-once, project grants). Project grants are read
|
|
2390
|
+
// from their store on every CSP build, so a grant or revoke applies on the next response with no restart.
|
|
2391
|
+
const previewEgress = createPreviewEgress({
|
|
2392
|
+
getStatic: (id) => liveServerManager.getStatic(id),
|
|
2393
|
+
presetCwdOf: (id) => {
|
|
2394
|
+
const sessionId = liveServerManager.presetSessionOf(id);
|
|
2395
|
+
return sessionId ? sessionManager.get(sessionId)?.cwd : undefined;
|
|
2396
|
+
},
|
|
2397
|
+
projectKeyOf: (cwd) => {
|
|
2398
|
+
let real = cwd;
|
|
2399
|
+
try {
|
|
2400
|
+
real = realpathSync(cwd);
|
|
2401
|
+
} catch {
|
|
2402
|
+
/* keep the stated cwd */
|
|
2403
|
+
}
|
|
2404
|
+
return resolveMainPath(real) ?? real;
|
|
2405
|
+
},
|
|
2406
|
+
projectGrants: projectEgressGrants,
|
|
2407
|
+
allowOnce: (viewerId) => liveCapabilities.getAllowOnce(viewerId),
|
|
2408
|
+
ownOrigins: previewEgressOwnOrigins,
|
|
2409
|
+
});
|
|
2410
|
+
// Preview exposure (is the dashboard reachable from anywhere but this machine?). Drives the
|
|
2411
|
+
// scripts rule on restricted mints; a flip to `exposed` kills restricted scripted local-only
|
|
2412
|
+
// tokens and tells open viewers to re-mint. See change: improve-canvas-html-and-url-ux (D5).
|
|
2413
|
+
const previewExposure = createPreviewExposure({
|
|
2414
|
+
getBindHost: () => config.host,
|
|
2415
|
+
getEndpoints: () =>
|
|
2416
|
+
collectEndpoints({
|
|
2417
|
+
providerEndpoints: [getTunnelUrl(), ...liveTunnelOrigins()]
|
|
2418
|
+
.filter((u): u is string => typeof u === "string" && u.length > 0)
|
|
2419
|
+
.map((url) => ({ kind: "public" as const, url, tls: url.startsWith("https://") })),
|
|
2420
|
+
publicBaseUrls: livePublicBaseUrls(),
|
|
2421
|
+
port: config.port,
|
|
2422
|
+
tlsEndpoints: tlsListener.tlsListenerUrls(),
|
|
2423
|
+
includeLocal: false,
|
|
2424
|
+
}).map((e) => e.url),
|
|
2425
|
+
getConfigOverride: livePreviewExposureOverride,
|
|
2426
|
+
});
|
|
2427
|
+
wirePreviewExposure({
|
|
2428
|
+
exposure: previewExposure,
|
|
2429
|
+
capabilities: liveCapabilities,
|
|
2430
|
+
broadcast: (epoch) => browserGateway.broadcastToAll({ type: "preview_exposure_changed", epoch }),
|
|
2431
|
+
});
|
|
2432
|
+
// Detect the flip even when no request arrives (a tunnel connecting), within the viewers' 2 s budget.
|
|
2433
|
+
const previewExposureTimer = setInterval(() => previewExposure.current(), 1000);
|
|
2434
|
+
previewExposureTimer.unref();
|
|
2435
|
+
fastify.addHook("onClose", async () => clearInterval(previewExposureTimer));
|
|
2436
|
+
// A request carrying a forwarding header pins the exposure to `exposed` until restart (fails closed).
|
|
2437
|
+
fastify.addHook("onRequest", async (request) => {
|
|
2438
|
+
previewExposure.noteRequest(request.headers as Record<string, unknown>);
|
|
2439
|
+
});
|
|
2440
|
+
fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities));
|
|
1820
2441
|
registerBearerAuth(fastify, { registry: pairedDeviceRegistry });
|
|
1821
2442
|
registerDeviceSessionRoutes(fastify, {
|
|
1822
2443
|
registry: pairedDeviceRegistry,
|
|
@@ -1881,7 +2502,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1881
2502
|
fastify.addHook("onRequest", async (request, reply) => {
|
|
1882
2503
|
const enforced = identityEnforced();
|
|
1883
2504
|
const hasPrincipal = (request as { principal?: unknown }).principal != null;
|
|
1884
|
-
const hasLocalToken =
|
|
2505
|
+
const hasLocalToken = hasLocalCredential(request.headers);
|
|
1885
2506
|
const allowed = identityFloorAllows({ enforced, path: request.url, method: request.method, hasPrincipal, hasLocalToken });
|
|
1886
2507
|
if (!allowed) return reply.code(401).send({ success: false, error: "sign_in_required" });
|
|
1887
2508
|
// D23 break-glass (local-token part): the host-only token with no
|
|
@@ -1894,15 +2515,35 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1894
2515
|
}
|
|
1895
2516
|
}
|
|
1896
2517
|
});
|
|
2518
|
+
// Native passkey users (user directory + WebAuthn ceremonies). Always
|
|
2519
|
+
// constructed (cheap: one small file read) so `/api/users` can report
|
|
2520
|
+
// "disabled"; inert until `auth.passkeys.enabled`, which the auth plugin
|
|
2521
|
+
// applies at register and on every reload. The RP context is the SAME
|
|
2522
|
+
// redirect-base resolution OAuth uses. See change: add-passkey-user-auth.
|
|
2523
|
+
const passkeyService = new PasskeyService({
|
|
2524
|
+
directory: new UserDirectory(),
|
|
2525
|
+
getRpContext: (override) => resolveRpContext(config.port, override),
|
|
2526
|
+
});
|
|
2527
|
+
passkeyService.configure(config.authConfig);
|
|
2528
|
+
let oauthLoginAccessor: (() => boolean) | null = null;
|
|
1897
2529
|
if (config.authConfig) {
|
|
1898
|
-
await registerAuthPlugin(fastify, {
|
|
2530
|
+
oauthLoginAccessor = (await registerAuthPlugin(fastify, {
|
|
1899
2531
|
authConfig: config.authConfig,
|
|
1900
2532
|
port: config.port,
|
|
1901
2533
|
resolvedTrustedNetworks: config.resolvedTrustedNetworks,
|
|
2534
|
+
readAdmissionTrustedNetworks: admissionList,
|
|
2535
|
+
onSessionEnd: (cookie) => liveCapabilities.revokeBySessionKey(sessionKeyOf(cookie)),
|
|
1902
2536
|
localToken,
|
|
1903
2537
|
localTrust,
|
|
1904
|
-
|
|
2538
|
+
passkeys: passkeyService,
|
|
2539
|
+
})).hasUsableOAuthProvider;
|
|
1905
2540
|
}
|
|
2541
|
+
// Live "is a usable login method configured" (drives the `sign-in` remedy of an
|
|
2542
|
+
// `operate_required` refusal). See change: surface-operate-required-remedy.
|
|
2543
|
+
const loginAvailable = buildLoginAvailable(oauthLoginAccessor, passkeyService, {
|
|
2544
|
+
enforced: identityEnforced,
|
|
2545
|
+
loginConfigs: () => browserLoginConfigRegistry.list(),
|
|
2546
|
+
});
|
|
1906
2547
|
// `/auth/status` is what the client's WS-refusal handler polls to tell
|
|
1907
2548
|
// `auth_required` (→ browser login gate, D16/H5) from a plain `offline`.
|
|
1908
2549
|
// Registered whenever the legacy cookie plugin did not register one — no
|
|
@@ -1938,7 +2579,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1938
2579
|
// prints `http://localhost:<port>/?pi_local=<code>`; the browser exchanges it
|
|
1939
2580
|
// like `#pi_handoff` and keeps the bearer in memory (no cookies, D22).
|
|
1940
2581
|
fastify.post("/api/identity/local-code", async (request, reply) => {
|
|
1941
|
-
if (!
|
|
2582
|
+
if (!hasLocalCredential(request.headers)) {
|
|
1942
2583
|
reply.code(401);
|
|
1943
2584
|
return { success: false as const, error: "local_token_required" };
|
|
1944
2585
|
}
|
|
@@ -1989,7 +2630,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1989
2630
|
fastify.addHook(
|
|
1990
2631
|
"onRequest",
|
|
1991
2632
|
createRouteTierGate({
|
|
1992
|
-
getTrustedNetworks:
|
|
2633
|
+
getTrustedNetworks: admissionList,
|
|
1993
2634
|
localTrust,
|
|
1994
2635
|
}),
|
|
1995
2636
|
);
|
|
@@ -1998,7 +2639,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1998
2639
|
// runtime admits without a restart. Created BEFORE registerSessionApi so the
|
|
1999
2640
|
// new lifecycle/extension-ui routes can carry it as a preHandler.
|
|
2000
2641
|
const networkGuard = createNetworkGuard(
|
|
2001
|
-
|
|
2642
|
+
admissionList,
|
|
2002
2643
|
{ localToken, localTrust },
|
|
2003
2644
|
);
|
|
2004
2645
|
|
|
@@ -2032,7 +2673,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2032
2673
|
metaPersistence,
|
|
2033
2674
|
}),
|
|
2034
2675
|
}, extras ?? {}),
|
|
2035
|
-
getTrustedNetworks:
|
|
2676
|
+
getTrustedNetworks: admissionList,
|
|
2036
2677
|
});
|
|
2037
2678
|
|
|
2038
2679
|
// Register route modules
|
|
@@ -2072,9 +2713,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2072
2713
|
sessionManager,
|
|
2073
2714
|
eventStore,
|
|
2074
2715
|
networkGuard,
|
|
2716
|
+
isToolInFlight: inFlightToolCalls.isInFlight,
|
|
2717
|
+
toolResultStats,
|
|
2075
2718
|
sessionArchive,
|
|
2076
2719
|
remoteTranscriptStore,
|
|
2077
2720
|
isResolverActive: identityEnforced,
|
|
2721
|
+
// `uiUrl` / `diffUrl` origin inputs (read live per request).
|
|
2722
|
+
// See change: add-session-ui-deep-links-for-agents (D1).
|
|
2723
|
+
uiLinks: {
|
|
2724
|
+
configuredOrigins: () =>
|
|
2725
|
+
[
|
|
2726
|
+
...livePublicBaseUrls(),
|
|
2727
|
+
...[getTunnelUrl(), ...liveTunnelOrigins()].filter((u): u is string => !!u),
|
|
2728
|
+
config.authConfig?.redirectBaseUrl,
|
|
2729
|
+
].filter((u): u is string => !!u),
|
|
2730
|
+
isAdmitted: (hostHeader) => isHostAdmitted(hostHeader, getHostGateCtx().admission),
|
|
2731
|
+
port: () => config.port,
|
|
2732
|
+
},
|
|
2078
2733
|
// Transcript-sourced session diffs dispatch through the same pool the
|
|
2079
2734
|
// hydration path owns; `maxStringSize` is the store's cap so projected
|
|
2080
2735
|
// tool payloads match store-sourced ones. See change:
|
|
@@ -2092,22 +2747,54 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2092
2747
|
// connected session so a saved policy applies without a manual restart
|
|
2093
2748
|
// (pi reads its settings only at session construction). See change:
|
|
2094
2749
|
// retry-forever-with-stop-control.
|
|
2095
|
-
|
|
2750
|
+
const reloadConnectedSessions = () => {
|
|
2751
|
+
// Fire-and-forget by contract (the route answers with the target count,
|
|
2752
|
+
// not per-session outcomes), but the rejection is OWNED: `dispatchReload`
|
|
2753
|
+
// reports failures as terminal `command_feedback`, so a throw here is a
|
|
2754
|
+
// bug and must be logged rather than becoming an unhandled rejection.
|
|
2755
|
+
const ids = reloadFanOutTargets();
|
|
2756
|
+
for (const id of ids) {
|
|
2757
|
+
dispatchReload(id).catch((err) => {
|
|
2758
|
+
console.error(`[dashboard] pi-settings reload fan-out failed for ${id}:`, err);
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
return ids.length;
|
|
2762
|
+
};
|
|
2763
|
+
registerPiRetryRoutes(fastify, { networkGuard, reloadConnectedSessions });
|
|
2764
|
+
// Trusted Types / CSP violation counters (authenticated, rate-limited, counters
|
|
2765
|
+
// only). See change: harden-client-sinks (D8).
|
|
2766
|
+
// The store is built first: the violation route feeds its persisted `ttShadow` aggregate.
|
|
2767
|
+
// See change: add-trusted-types-shadow-enforce (D6).
|
|
2768
|
+
const cspReportStore = new CspReportStore();
|
|
2769
|
+
registerCspViolationRoutes(fastify, {
|
|
2096
2770
|
networkGuard,
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2771
|
+
log: { warn: (m) => fastify.log.warn(m) },
|
|
2772
|
+
recordShadow: (outcome, count) => cspReportStore.recordShadow(outcome, count),
|
|
2773
|
+
});
|
|
2774
|
+
// Baseline CSP report sink (`POST /__pi/csp-report/:policy`, public to the OAuth gate), its
|
|
2775
|
+
// persisted counter (`~/.pi/dashboard/csp-reports.json`) and the operator reset
|
|
2776
|
+
// (`POST /api/csp-reports/reset`, operate). See change: harden-cors-and-csp-reporting (D8).
|
|
2777
|
+
registerCspReportSink(fastify, { store: cspReportStore, networkGuard });
|
|
2778
|
+
// Signed navigation intents for operator-opened route-backed overlays
|
|
2779
|
+
// (per-process key: a restart invalidates them). See change: harden-client-sinks (D10).
|
|
2780
|
+
registerNavIntentRoutes(fastify, { networkGuard, intents: new NavIntents() });
|
|
2781
|
+
// On-demand AI mermaid repair (opt-in via `mermaidRepair` config; 404 when off).
|
|
2782
|
+
// See change: add-mermaid-ai-repair.
|
|
2783
|
+
registerMermaidRepairRoutes(fastify, {
|
|
2784
|
+
networkGuard,
|
|
2785
|
+
getConfig: () => loadConfig().mermaidRepair,
|
|
2786
|
+
getRegistry: async () => {
|
|
2787
|
+
try {
|
|
2788
|
+
return await getModelRegistry();
|
|
2789
|
+
} catch {
|
|
2790
|
+
return null;
|
|
2107
2791
|
}
|
|
2108
|
-
return ids.length;
|
|
2109
2792
|
},
|
|
2793
|
+
getStreamSimple: getStreamSimpleFn,
|
|
2110
2794
|
});
|
|
2795
|
+
// pi global settings.json editor (typed form + raw JSON) and the
|
|
2796
|
+
// default-model mirror/drift repair. See change: edit-pi-agent-settings.
|
|
2797
|
+
registerPiSettingsRoutes(fastify, { networkGuard, reloadConnectedSessions, readDashboardConfig: loadConfig });
|
|
2111
2798
|
registerGitRoutes(fastify, {
|
|
2112
2799
|
networkGuard, sessionManager, browserGateway, worktreeInitRegistry,
|
|
2113
2800
|
sendToSession: (id, msg) => piGateway.sendToSession(id, msg),
|
|
@@ -2117,6 +2804,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2117
2804
|
// the workspace link) yields `undefined` — the route clamps to the
|
|
2118
2805
|
// default. The cast is dropped once the branch lands.
|
|
2119
2806
|
removeBatchCap: (loadConfig() as DashboardConfig & { removeBatchCap?: number }).removeBatchCap,
|
|
2807
|
+
// Core cwd admission against the same known set as plugin routes.
|
|
2808
|
+
// See change: core-cwd-admission.
|
|
2809
|
+
knownCwds: knownFolderCwds,
|
|
2810
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2120
2811
|
});
|
|
2121
2812
|
|
|
2122
2813
|
// Browser channel for worktree-init event subscriptions. The dialog
|
|
@@ -2137,11 +2828,83 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2137
2828
|
const cwd = typeof msg?.cwd === "string" ? msg.cwd : undefined;
|
|
2138
2829
|
if (cwd) worktreeInitRegistry.unsubscribeCwd(cwd, ws);
|
|
2139
2830
|
});
|
|
2140
|
-
registerFileRoutes(fastify, {
|
|
2141
|
-
|
|
2831
|
+
registerFileRoutes(fastify, {
|
|
2832
|
+
// Remote browse confinement (change: harden-server-capability-bounds, D1/D2):
|
|
2833
|
+
// strict-proof context + the two root sources only this file can read.
|
|
2834
|
+
localTrust,
|
|
2835
|
+
browseConfineRemote: confineRemoteBrowse,
|
|
2836
|
+
browseRootSources: {
|
|
2837
|
+
worktreeRoots: browseRootSources.worktreeRoots,
|
|
2838
|
+
projectGrants: browseRootSources.projectGrants,
|
|
2839
|
+
},
|
|
2840
|
+
sessionManager,
|
|
2841
|
+
preferencesStore,
|
|
2842
|
+
networkGuard,
|
|
2843
|
+
routeAdmission: fileRouteAdmission,
|
|
2844
|
+
// Plugin file-handler seams for POST /api/file/write-binary: live claim registry
|
|
2845
|
+
// (read at request time: enabled + server entry loaded), registered validators,
|
|
2846
|
+
// bounded worker pool. See change: add-editor-pane-file-handlers (D4).
|
|
2847
|
+
fileHandlers: {
|
|
2848
|
+
resolveClaim: (key) => {
|
|
2849
|
+
const ref = parseFileHandlerClaimKey(key);
|
|
2850
|
+
if (!ref) return undefined;
|
|
2851
|
+
const plugin = discoverPlugins().find((p) => p.manifest.id === ref.pluginId);
|
|
2852
|
+
if (!plugin || !fixtureEntryAllowed(plugin.manifest)) return undefined;
|
|
2853
|
+
const claim = plugin.manifest.claims.find((c) => c.slot === "editor-pane-file-handler" && c.id === ref.claimId);
|
|
2854
|
+
if (!claim) return undefined;
|
|
2855
|
+
return {
|
|
2856
|
+
pluginId: ref.pluginId,
|
|
2857
|
+
claim,
|
|
2858
|
+
enabled: resolvePluginEnabled(
|
|
2859
|
+
getPluginConfigFromFile(loadConfig(), ref.pluginId) as Record<string, unknown>,
|
|
2860
|
+
plugin.manifest.defaultEnabled,
|
|
2861
|
+
),
|
|
2862
|
+
serverLoaded: getPluginStatusStore().getStatus(ref.pluginId)?.loaded === true,
|
|
2863
|
+
};
|
|
2864
|
+
},
|
|
2865
|
+
getValidator: (pluginId, claimId) => getFileValidatorRegistry().get(pluginId, claimId),
|
|
2866
|
+
validatorPool: getFileValidatorPool(),
|
|
2867
|
+
},
|
|
2868
|
+
});
|
|
2869
|
+
registerGrepRoutes(fastify, { sessionManager, networkGuard, routeAdmission: fileRouteAdmission });
|
|
2870
|
+
// Folder project identity (declared file + plugin marker rules). Rules come
|
|
2871
|
+
// only from plugins that are loaded + enabled + fixture-allowed, read per
|
|
2872
|
+
// request. See change: add-project-scoped-apps.
|
|
2873
|
+
registerFolderProjectRoutes(fastify, {
|
|
2874
|
+
networkGuard,
|
|
2875
|
+
knownCwds: knownFolderCwds,
|
|
2876
|
+
getRuleSources: () => {
|
|
2877
|
+
const cfg = loadConfig();
|
|
2878
|
+
const store = getPluginStatusStore();
|
|
2879
|
+
return collectRuleSources(discoverPlugins(), {
|
|
2880
|
+
fixtureAllowed: (m) => fixtureEntryAllowed(m),
|
|
2881
|
+
isLoaded: (id) => store.getStatus(id)?.loaded === true,
|
|
2882
|
+
isEnabled: (m) => resolvePluginEnabled(getPluginConfigFromFile(cfg, m.id), m.defaultEnabled),
|
|
2883
|
+
});
|
|
2884
|
+
},
|
|
2885
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2886
|
+
onTruncated: (cwd) => console.debug(`[folder-project] detection truncated for ${cwd}`),
|
|
2887
|
+
});
|
|
2142
2888
|
// Settings → Access review surface + the one endpoint that can create a
|
|
2143
2889
|
// filesystem grant. See change: add-access-grants-and-review.
|
|
2144
|
-
registerAccessRoutes(fastify, {
|
|
2890
|
+
registerAccessRoutes(fastify, {
|
|
2891
|
+
networkGuard,
|
|
2892
|
+
preferencesStore,
|
|
2893
|
+
writeConfigPartial,
|
|
2894
|
+
provisioning: { registry: provisioning.registry, announce: provisioning.announce },
|
|
2895
|
+
});
|
|
2896
|
+
// Pending-question stack REST roads (list/detail/answer/summarize); the answer
|
|
2897
|
+
// claim is shared with the browser `prompt_response` road.
|
|
2898
|
+
// See change: add-pending-question-stack (D8, D9).
|
|
2899
|
+
registerQuestionRoutes(fastify, {
|
|
2900
|
+
networkGuard,
|
|
2901
|
+
store: questionStore,
|
|
2902
|
+
sendToSession: (sessionId, msg) => piGateway.sendToSession(sessionId, msg as never),
|
|
2903
|
+
isResolverActive: identityEnforced,
|
|
2904
|
+
ownerOf: (sessionId) => sessionManager.get(sessionId)?.principalOwner,
|
|
2905
|
+
});
|
|
2906
|
+
// SSE agent-event feed for external controllers. See change: add-agent-event-stream.
|
|
2907
|
+
registerAgentEventStreamRoutes(fastify, { networkGuard, hub: agentEventHub, isResolverActive: identityEnforced });
|
|
2145
2908
|
registerAccessPromptRoutes(fastify, {
|
|
2146
2909
|
networkGuard,
|
|
2147
2910
|
coordinator: grantCoordinator,
|
|
@@ -2168,6 +2931,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2168
2931
|
preferencesStore,
|
|
2169
2932
|
directoryService,
|
|
2170
2933
|
networkGuard,
|
|
2934
|
+
piGateway,
|
|
2935
|
+
// Live (per-request) config for the workflow-schema gates + new-project default.
|
|
2936
|
+
getOpenSpecConfig: () => loadConfig().openspec,
|
|
2937
|
+
// The directory service's ONE spawn semaphore (cap resizable by
|
|
2938
|
+
// `reconfigurePolling`) bounds the route's `newer`/`conflict` validate too.
|
|
2939
|
+
// See changes: add-pi-spec-driven-schema, move-workflow-schema-status-to-poll-worker.
|
|
2940
|
+
spawnSemaphore: directoryService.semaphore,
|
|
2941
|
+
// Core cwd admission against the same known set as plugin routes.
|
|
2942
|
+
// See change: core-cwd-admission.
|
|
2943
|
+
knownFolderCwds,
|
|
2944
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
2171
2945
|
onOpenSpecChanged: (cwd) => {
|
|
2172
2946
|
const data = directoryService.getOpenSpecData(cwd);
|
|
2173
2947
|
if (data) browserGateway.broadcastToAll({ type: "openspec_update", cwd, data });
|
|
@@ -2196,6 +2970,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2196
2970
|
preferencesStore,
|
|
2197
2971
|
networkGuard,
|
|
2198
2972
|
store: openspecGroupStore,
|
|
2973
|
+
routeAdmission: fileRouteAdmission,
|
|
2199
2974
|
});
|
|
2200
2975
|
|
|
2201
2976
|
|
|
@@ -2205,14 +2980,49 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2205
2980
|
// Reclaims the automation-produced ephemeral sessions #383 is about; the
|
|
2206
2981
|
// acquire registry + caps are shared-layer modules the embed front constructs.
|
|
2207
2982
|
// See change: add-embed-session-lifecycle.
|
|
2983
|
+
// ONE terminator behind every unattended kill (reaper, caps, automation stop):
|
|
2984
|
+
// strategy-agnostic (keys on session.pid, not the headless registry).
|
|
2985
|
+
// See change: fix-session-reclaim-tmux.
|
|
2986
|
+
const sessionTerminator = createSessionTerminator({
|
|
2987
|
+
sessionManager,
|
|
2988
|
+
headlessPidRegistry: browserGateway.headlessPidRegistry,
|
|
2989
|
+
});
|
|
2990
|
+
const abortSpawnedRunImpl = createAbortSpawnedRun({
|
|
2991
|
+
terminate: sessionTerminator.terminate,
|
|
2992
|
+
sendShutdownHint: (sessionId) => piGateway.sendToSession(sessionId, { type: "shutdown", sessionId }),
|
|
2993
|
+
recordReclaimFailure: () => embedLifecycle.metrics.recordReclaimFailure(),
|
|
2994
|
+
});
|
|
2995
|
+
// Plugin session-close hook: closer registry + close requests, shared by
|
|
2996
|
+
// the reaper and every plugin's ctx. See change: add-session-close-plugin-hook.
|
|
2997
|
+
const sessionClosers = createSessionCloserRegistry();
|
|
2998
|
+
const markArchiveOnEnd = (id: string, value = true): void => {
|
|
2999
|
+
sessionManager.update(id, { archiveOnEnd: value });
|
|
3000
|
+
const file = sessionManager.get(id)?.sessionFile;
|
|
3001
|
+
if (file) {
|
|
3002
|
+
try {
|
|
3003
|
+
mergeSessionMeta(file, { archiveOnEnd: value });
|
|
3004
|
+
} catch { /* best-effort */ }
|
|
3005
|
+
}
|
|
3006
|
+
};
|
|
2208
3007
|
const embedLifecycle = createEmbedLifecycleController({
|
|
3008
|
+
closers: sessionClosers,
|
|
3009
|
+
markArchiveOnEnd,
|
|
3010
|
+
// Same enabled predicate as the server-entry loader: a disabled owner's
|
|
3011
|
+
// closer is never consulted (no closer ⇒ close).
|
|
3012
|
+
isPluginEnabled: (pluginId) =>
|
|
3013
|
+
resolvePluginEnabled(
|
|
3014
|
+
getPluginConfigFromFile(loadConfig(), pluginId) as Record<string, unknown>,
|
|
3015
|
+
discoverPlugins().find((p) => p.manifest.id === pluginId)?.manifest.defaultEnabled,
|
|
3016
|
+
),
|
|
2209
3017
|
config: () => loadConfig().embedLifecycle,
|
|
2210
3018
|
listSessions: () => sessionManager.listAll(),
|
|
2211
3019
|
getSubscriberCount: (id) => browserGateway.getSubscriberCount(id),
|
|
2212
3020
|
listTerminalCwds: () => terminalManager.list().map((t) => t.cwd),
|
|
2213
3021
|
hasPendingUiRequest: (id) => browserGateway.hasPendingUiRequest(id),
|
|
2214
3022
|
hasPendingPromptRequests: (id) => browserGateway.hasPendingPromptRequests(id),
|
|
2215
|
-
|
|
3023
|
+
// graceMs 0: killProcess is itself SIGTERM → 2 s → SIGKILL (design D2).
|
|
3024
|
+
terminate: (id) =>
|
|
3025
|
+
sessionTerminator.terminate(id, { graceMs: 0, verifyIdentity: true, stampManualClose: true }),
|
|
2216
3026
|
sendStopAfterTurn: (id) =>
|
|
2217
3027
|
piGateway.sendToSession(id, { type: "stop_after_turn", sessionId: id }),
|
|
2218
3028
|
});
|
|
@@ -2233,13 +3043,25 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2233
3043
|
const hasProductionBuild = clientDirResolved !== null;
|
|
2234
3044
|
// ONE snapshot feeds the startup diagnostic, `fastifyStatic`, and
|
|
2235
3045
|
// `/api/health.clientBuild` (passed to `registerSystemRoutes` below).
|
|
3046
|
+
// Served declaration's `bundledPluginIds` reach discovery BEFORE any server-side discovery call
|
|
3047
|
+
// (D15). See change: decouple-plugins-from-core (task 5.4).
|
|
3048
|
+
setDeclaredBundledPluginIds(readServedBundledPluginIds(clientDirResolved));
|
|
2236
3049
|
const clientBuild = clientBuildSnapshotFor(clientDirResolved);
|
|
2237
3050
|
console.log(clientBuildDiagnostic(clientBuild));
|
|
2238
3051
|
if (!hasProductionBuild) {
|
|
2239
3052
|
console.log("[dashboard] No client build found — running in API-only mode");
|
|
2240
3053
|
}
|
|
2241
3054
|
|
|
2242
|
-
|
|
3055
|
+
registerAcpRoutes(fastify);
|
|
3056
|
+
registerTlsRoutes(fastify, { networkGuard, listener: tlsListener });
|
|
3057
|
+
// Live pi-trust query: authenticated one-shot HTTP for the bridge's `project_trust`.
|
|
3058
|
+
// See change: mirror-dashboard-trust-live-remote.
|
|
3059
|
+
const piTrustQuery = registerPiTrustQueryRoutes(fastify, {
|
|
3060
|
+
getConfig: () => loadConfig().piTrustMirror,
|
|
3061
|
+
live: () => piTrustMirror.live,
|
|
3062
|
+
readSnapshot: () => piTrustMirror.readSnapshot(),
|
|
3063
|
+
});
|
|
3064
|
+
registerSystemRoutes(fastify, { onVaultConfigChanged: () => void vaultDelivery.pushNow(), onTlsBridgeSwitchChanged: () => onTlsBridgeSwitchChanged({ acceptBridges: tlsBridgesLive, push: () => void vaultDelivery.pushNow(), gateway: piGateway }), exposureWritePending: () => pairedDeviceRegistry.exposurePending(), tls: tlsListener, sessionManager, preferencesStore, metaPersistence, config, networkGuard, localTrust, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, clientDir, clientBuild, readTrustedNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []), readPiTrustLive: piTrustQuery.counters, readCspReports: () => cspReportStore.snapshot(), readAccessGrants: () => snapshotAccessGrantHealth({ coordinator: grantCoordinator, yolo, refusalCount: () => listRefusals().length, promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true, killSwitch: () => isGrantPromptKilled(), hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode, operatorChannels: () => promptChannelCount(), provisioning: () => provisioning.registry.stats() }), keeperLogStats: { get: () => getKeeperManager().getKeeperLogStats() }, readPushErrors: pushService ? () => pushService?.errors ?? [] : pushInitError ? () => [pushInitError as string] : undefined });
|
|
2243
3065
|
registerHostGateRoutes(fastify, { getCtx: getHostGateCtx, state: hostGateState, networkGuard });
|
|
2244
3066
|
// GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
|
|
2245
3067
|
// Assigned by the runtime-overlay block below; read lazily per request.
|
|
@@ -2260,6 +3082,72 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2260
3082
|
});
|
|
2261
3083
|
registerPushRoutes(fastify, { getPush: () => pushService });
|
|
2262
3084
|
registerToolRoutes(fastify, { registry: getDefaultRegistry(), networkGuard });
|
|
3085
|
+
// Managed services: definitions + offers + lifecycle + secrets. Boot is
|
|
3086
|
+
// adoption only (no probes, no network I/O), and a no-op without
|
|
3087
|
+
// services.json. See change: add-service-registry-core.
|
|
3088
|
+
const serviceManager = new ServiceManager({
|
|
3089
|
+
paths: servicesPaths(),
|
|
3090
|
+
run: defaultCommandRunner,
|
|
3091
|
+
resolveBinary: (name) => {
|
|
3092
|
+
try {
|
|
3093
|
+
const r = getDefaultRegistry().resolve(name);
|
|
3094
|
+
return r.ok ? r.path : null;
|
|
3095
|
+
} catch {
|
|
3096
|
+
return null;
|
|
3097
|
+
}
|
|
3098
|
+
},
|
|
3099
|
+
discoverOffers: () => discoverServiceOffers(resolveInstallRoot(fileURLToPath(import.meta.url))),
|
|
3100
|
+
// Content-free hint (type only): Settings → Services refetches `GET /api/services`.
|
|
3101
|
+
// The manager coalesces to ≤ 1 per 500 ms. See change: add-services-settings-ui.
|
|
3102
|
+
onChange: () => browserGateway.broadcastToAll({ type: "services_changed" }),
|
|
3103
|
+
});
|
|
3104
|
+
// The knock's pre-switch gate state, built ONCE: the pairing routes and the
|
|
3105
|
+
// `request-access` remedy of vault / services refusals read the same Host
|
|
3106
|
+
// admission and the same cached LAN-interface list, so the remedy cannot drift
|
|
3107
|
+
// from the knock. See change: add-request-access-remedy (D1, D2, D4).
|
|
3108
|
+
const knockPeerDeps: KnockPeerDeps = {
|
|
3109
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
3110
|
+
getLanInterfaces: createLanInterfaceProvider({ bindHost: config.host }),
|
|
3111
|
+
// The RAW configured list (not the admission list): knock eligibility, read
|
|
3112
|
+
// live in both trust modes. See change: retire-trusted-networks-bypass (D7).
|
|
3113
|
+
getKnockEligibleNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []),
|
|
3114
|
+
};
|
|
3115
|
+
const requestAccessAvailable = createRequestAccessAvailable(knockPeerDeps, localTrust);
|
|
3116
|
+
registerServiceRoutes(fastify, {
|
|
3117
|
+
manager: serviceManager,
|
|
3118
|
+
networkGuard,
|
|
3119
|
+
localTrust,
|
|
3120
|
+
loginAvailable,
|
|
3121
|
+
requestAccessAvailable,
|
|
3122
|
+
getTrustedNetworks: admissionList,
|
|
3123
|
+
});
|
|
3124
|
+
// Credential vault: hub-owned accounts, bindings and per-project grants.
|
|
3125
|
+
// Management routes need operate authority or local trust; values never leave
|
|
3126
|
+
// through them. See change: add-credential-vault.
|
|
3127
|
+
registerVaultRoutes(fastify, {
|
|
3128
|
+
store: vaultStore,
|
|
3129
|
+
importer: createVaultImport({ store: vaultStore, candidates: () => defaultKnownLocations() }),
|
|
3130
|
+
networkGuard,
|
|
3131
|
+
localTrust,
|
|
3132
|
+
loginAvailable,
|
|
3133
|
+
requestAccessAvailable,
|
|
3134
|
+
hostPolicy: policyRegistry,
|
|
3135
|
+
listOpenProjects: () => vaultDelivery.listOpenProjects(),
|
|
3136
|
+
projects: vaultProjects,
|
|
3137
|
+
getSessionBindingState: (sessionId) => vaultDelivery.getSessionState(sessionId),
|
|
3138
|
+
getPluginDeclarations: () =>
|
|
3139
|
+
discoverPlugins()
|
|
3140
|
+
.filter((p) => (p.manifest.vaultBindings?.length ?? 0) > 0)
|
|
3141
|
+
.map((p) => ({ pluginId: p.manifest.id, displayName: p.manifest.displayName, declared: p.manifest.vaultBindings ?? [] })),
|
|
3142
|
+
});
|
|
3143
|
+
// ACME certificate sources: per-entry config routes + vault-backed solver credentials
|
|
3144
|
+
// (the credentials route answers exactly like a vault management route).
|
|
3145
|
+
// See change: add-acme-dns01-certs.
|
|
3146
|
+
registerAcmeRoutes(fastify, {
|
|
3147
|
+
networkGuard,
|
|
3148
|
+
manageGuard: createVaultManageGuard({ localTrust, loginAvailable, requestAccessAvailable, hostPolicy: policyRegistry }),
|
|
3149
|
+
listener: tlsListener,
|
|
3150
|
+
});
|
|
2263
3151
|
// Pi runtime discovery + atomic dual selection. See change: select-pi-runtime-install.
|
|
2264
3152
|
registerPiRuntimeRoutes(fastify, { registry: getDefaultRegistry(), networkGuard });
|
|
2265
3153
|
// Node family discovery + atomic triple selection (node+npm+npx).
|
|
@@ -2303,27 +3191,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2303
3191
|
let modelProxyMounted = false;
|
|
2304
3192
|
|
|
2305
3193
|
// On completion: broadcast to browsers + invalidate the recommended cache
|
|
2306
|
-
packageManagerWrapper.setCompleteListener((
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
3194
|
+
packageManagerWrapper.setCompleteListener(createPackageCompletionHandler<OperationResult>({
|
|
3195
|
+
broadcastComplete: (result) => {
|
|
3196
|
+
browserGateway.broadcastToAll({
|
|
3197
|
+
type: "package_operation_complete",
|
|
3198
|
+
operationId: result.operationId,
|
|
3199
|
+
action: result.action,
|
|
3200
|
+
source: result.source,
|
|
3201
|
+
scope: result.scope,
|
|
3202
|
+
success: result.success,
|
|
3203
|
+
error: result.error,
|
|
3204
|
+
diagnostics: result.diagnostics,
|
|
3205
|
+
sessionsReloaded: (result as OperationResult & { sessionsReloaded?: number }).sessionsReloaded,
|
|
3206
|
+
...(result.moveId ? { moveId: result.moveId } : {}),
|
|
3207
|
+
...(result.partialSuccess ? { partialSuccess: result.partialSuccess } : {}),
|
|
3208
|
+
} as PackageOperationCompleteMessage);
|
|
3209
|
+
},
|
|
3210
|
+
invalidateRecommendedCache,
|
|
3211
|
+
// Hot-add: a successful op refreshes plugin discovery (global) or local-scope detection
|
|
3212
|
+
// (local); ONE `plugins_changed` follows the completion broadcast. Never from
|
|
3213
|
+
// `package-routes.ts`. See change: decouple-plugins-from-core (task 5.7, D16).
|
|
3214
|
+
discovery: () => pluginDiscovery,
|
|
2321
3215
|
// A successful package operation may have changed plugin requirement
|
|
2322
3216
|
// satisfaction. Refresh probes and broadcast plugin_config_update for
|
|
2323
3217
|
// any plugin whose `missingRequirements` flipped.
|
|
2324
3218
|
// See change: add-plugin-activation-ui.
|
|
2325
|
-
|
|
2326
|
-
|
|
3219
|
+
refreshProbes: () =>
|
|
3220
|
+
refreshRequirementProbesFor(
|
|
2327
3221
|
null,
|
|
2328
3222
|
{
|
|
2329
3223
|
listInstalled: () => packageManagerWrapper.listInstalled("global"),
|
|
@@ -2339,9 +3233,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2339
3233
|
config: status ?? {},
|
|
2340
3234
|
});
|
|
2341
3235
|
}
|
|
2342
|
-
})
|
|
2343
|
-
|
|
2344
|
-
});
|
|
3236
|
+
}),
|
|
3237
|
+
}));
|
|
2345
3238
|
|
|
2346
3239
|
// Reload all active sessions after a successful package operation
|
|
2347
3240
|
packageManagerWrapper.setReloadSessions(async () => {
|
|
@@ -2356,7 +3249,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2356
3249
|
return count;
|
|
2357
3250
|
});
|
|
2358
3251
|
|
|
2359
|
-
registerPackageRoutes(fastify, { packageManagerWrapper });
|
|
3252
|
+
registerPackageRoutes(fastify, { packageManagerWrapper, routeAdmission: fileRouteAdmission });
|
|
3253
|
+
registerPackageHealthRoutes(fastify, { packageManagerWrapper });
|
|
2360
3254
|
registerResourceActivationRoutes(fastify, {
|
|
2361
3255
|
networkGuard,
|
|
2362
3256
|
piGateway,
|
|
@@ -2366,6 +3260,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2366
3260
|
browserGateway.headlessPidRegistry
|
|
2367
3261
|
.listSessions()
|
|
2368
3262
|
.map((e) => ({ sessionId: e.sessionId, cwd: e.cwd })),
|
|
3263
|
+
routeAdmission: fileRouteAdmission,
|
|
2369
3264
|
});
|
|
2370
3265
|
registerRecommendedRoutes(fastify, {
|
|
2371
3266
|
packageManagerWrapper,
|
|
@@ -2482,8 +3377,45 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2482
3377
|
]);
|
|
2483
3378
|
|
|
2484
3379
|
// Live-server-preview routes + reverse proxy (main-origin /live/:id/*).
|
|
2485
|
-
registerLiveServerRoutes(fastify, liveServerManager, {
|
|
2486
|
-
|
|
3380
|
+
registerLiveServerRoutes(fastify, liveServerManager, {
|
|
3381
|
+
networkGuard,
|
|
3382
|
+
capabilities: liveCapabilities,
|
|
3383
|
+
exposure: previewExposure,
|
|
3384
|
+
promptingEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
|
|
3385
|
+
getTrustedNetworks: admissionList,
|
|
3386
|
+
localTrust,
|
|
3387
|
+
egress: previewEgress,
|
|
3388
|
+
requestEgressGrant: createEgressGrantRequester(grantCoordinator),
|
|
3389
|
+
channelOf: (request) => sourceChannel(request.ip),
|
|
3390
|
+
// `start-static`: the SAME gate as a raw file read; a refusal answers with that route's status and body.
|
|
3391
|
+
staticGate: async (cwd, relPath, opts) => {
|
|
3392
|
+
const gate = await gateFilePath(cwd, relPath, fileRouteAdmission, { allowGrant: true, disclosure: opts.disclosure });
|
|
3393
|
+
if ("code" in gate) {
|
|
3394
|
+
return {
|
|
3395
|
+
ok: false,
|
|
3396
|
+
status: gate.code,
|
|
3397
|
+
body: denialBody(gate),
|
|
3398
|
+
// The 503 of an undecidable cwd admission carries `Retry-After` like every file route.
|
|
3399
|
+
...(gate.code === 503 ? { headers: { "Retry-After": "1" } } : {}),
|
|
3400
|
+
};
|
|
3401
|
+
}
|
|
3402
|
+
return { ok: true, resolved: gate.resolved };
|
|
3403
|
+
},
|
|
3404
|
+
});
|
|
3405
|
+
registerLiveServerProxy(fastify, liveServerManager, {
|
|
3406
|
+
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
3407
|
+
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
3408
|
+
grantedOrigins: (grant) => previewEgress.grantedFor(grant),
|
|
3409
|
+
onStaticHtmlServed: (grant, real) => previewEgress.noteServed(grant, real),
|
|
3410
|
+
reservedHandler: createReservedHandler({
|
|
3411
|
+
egress: previewEgress,
|
|
3412
|
+
ownOriginsOf: (request) => requestOriginsOf(request),
|
|
3413
|
+
}),
|
|
3414
|
+
// Re-run on EVERY static request, so a revoked grant or pin applies on the next one. Quiet:
|
|
3415
|
+
// a refusal here records no denial and raises no prompt.
|
|
3416
|
+
staticGate: async (cwd, absPath) =>
|
|
3417
|
+
!("code" in (await gateFilePath(cwd, absPath, fileRouteAdmission, { allowGrant: true, quiet: true }))),
|
|
3418
|
+
});
|
|
2487
3419
|
|
|
2488
3420
|
// ONE model runtime for the provider-auth flow listing AND the model proxy,
|
|
2489
3421
|
// injected so auth/ never imports model-proxy/.
|
|
@@ -2523,7 +3455,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2523
3455
|
}
|
|
2524
3456
|
},
|
|
2525
3457
|
});
|
|
2526
|
-
registerKnownServersRoutes(fastify, {
|
|
3458
|
+
registerKnownServersRoutes(fastify, {
|
|
3459
|
+
networkGuard,
|
|
3460
|
+
getPeerServers: () => peerServers,
|
|
3461
|
+
localToken,
|
|
3462
|
+
localTrust,
|
|
3463
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
3464
|
+
moves: knownServerMoves,
|
|
3465
|
+
ownFingerprint: () => serverIdentity.fingerprint,
|
|
3466
|
+
});
|
|
2527
3467
|
registerLocalProofRoutes(fastify, { codes: localProofCodes, ctx: localTrust });
|
|
2528
3468
|
registerPairingRoutes(fastify, {
|
|
2529
3469
|
networkGuard,
|
|
@@ -2532,13 +3472,30 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2532
3472
|
registry: pairedDeviceRegistry,
|
|
2533
3473
|
localToken,
|
|
2534
3474
|
localTrust,
|
|
2535
|
-
hostAdmission:
|
|
3475
|
+
hostAdmission: knockPeerDeps.hostAdmission,
|
|
3476
|
+
// Shared "is a login method configured" thunk (same instance as vault/services): drives the `sign-in` remedy.
|
|
3477
|
+
loginAvailable,
|
|
2536
3478
|
// Public (tunnel + configured public) base URLs, already TLS-gated.
|
|
2537
3479
|
getReachableUrls: () => pairingManager.reachableUrls(),
|
|
3480
|
+
// Named in a refused bridge-token issue (HTTP → the native HTTPS address).
|
|
3481
|
+
getTlsListenerUrls: () => tlsListener.tlsListenerUrls().map((e) => e.url),
|
|
2538
3482
|
getPort: () => {
|
|
2539
3483
|
const addr = fastify.server.address();
|
|
2540
3484
|
return typeof addr === "object" && addr !== null ? addr.port : config.port;
|
|
2541
3485
|
},
|
|
3486
|
+
// LAN knock pairing: the switch is read LIVE per request (no restart), and
|
|
3487
|
+
// the on-link gate scores the peer against the interfaces the bind covers.
|
|
3488
|
+
// See change: add-lan-knock-pairing.
|
|
3489
|
+
getAcceptLanRequests: liveAcceptLanRequests,
|
|
3490
|
+
getLanInterfaces: knockPeerDeps.getLanInterfaces,
|
|
3491
|
+
getKnockEligibleNetworks: knockPeerDeps.getKnockEligibleNetworks,
|
|
3492
|
+
});
|
|
3493
|
+
// Operator user directory (passkeys). See change: add-passkey-user-auth.
|
|
3494
|
+
registerUserRoutes(fastify, {
|
|
3495
|
+
service: passkeyService,
|
|
3496
|
+
localToken,
|
|
3497
|
+
localTrust,
|
|
3498
|
+
hostAdmission: () => getHostGateCtx().admission,
|
|
2542
3499
|
});
|
|
2543
3500
|
// Mint a single-use WS ticket (D11). Authenticated (networkGuard: cookie,
|
|
2544
3501
|
// trusted network, or Authorization: Bearer). The ticket is bound to a WS
|
|
@@ -2568,7 +3525,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2568
3525
|
ip: request.ip,
|
|
2569
3526
|
headers: request.headers as Record<string, unknown>,
|
|
2570
3527
|
localTrust,
|
|
2571
|
-
verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token),
|
|
3528
|
+
verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token, bearerChannelOf(request.raw)),
|
|
2572
3529
|
});
|
|
2573
3530
|
if (!verdict.allow) {
|
|
2574
3531
|
reply.code(403);
|
|
@@ -2578,7 +3535,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2578
3535
|
// registers ATTRIBUTABLE sessions (origin gate, #E15).
|
|
2579
3536
|
return {
|
|
2580
3537
|
success: true as const,
|
|
2581
|
-
data: {
|
|
3538
|
+
data: {
|
|
3539
|
+
ticket: mintBridgeTicket(wsTicketStore, verdict.deviceId, request.raw),
|
|
3540
|
+
},
|
|
2582
3541
|
};
|
|
2583
3542
|
}
|
|
2584
3543
|
// Non-bridge scope: bind the human principal resolved by the identity
|
|
@@ -2609,7 +3568,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2609
3568
|
definitions: () => customEventGroupsStore.definitions(),
|
|
2610
3569
|
});
|
|
2611
3570
|
// Canvas-type registry read/write (auto-canvas task 5.2).
|
|
2612
|
-
registerCanvasTypesRoutes(fastify, { networkGuard });
|
|
3571
|
+
registerCanvasTypesRoutes(fastify, { networkGuard, routeAdmission: fileRouteAdmission });
|
|
2613
3572
|
// Opt-in worktree auto-init-on-spawn preference (auto-init-worktree-on-spawn).
|
|
2614
3573
|
registerPreferencesWorktreeInitRoutes(fastify, { preferencesStore, networkGuard });
|
|
2615
3574
|
// Global auto-session-naming toggle (add-auto-session-naming). Broadcasts
|
|
@@ -2619,6 +3578,34 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2619
3578
|
networkGuard,
|
|
2620
3579
|
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
2621
3580
|
});
|
|
3581
|
+
// Runtime plugin clients: admitted listing, trust grant/revoke, and the content-addressed asset prefix
|
|
3582
|
+
// (outside the network guard's jurisdiction, no auth skip: it behaves exactly like `/assets/*`).
|
|
3583
|
+
// See change: decouple-plugins-from-core (6.10–6.12).
|
|
3584
|
+
registerPluginRuntimeClientRoutes(fastify, {
|
|
3585
|
+
networkGuard,
|
|
3586
|
+
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3587
|
+
localTrust,
|
|
3588
|
+
// `pluginDiscovery` is built after listen; a trust grant before that point just broadcasts.
|
|
3589
|
+
refreshDiscovery: async () => {
|
|
3590
|
+
if (pluginDiscovery) await pluginDiscovery.refreshPluginDiscovery();
|
|
3591
|
+
else browserGateway.broadcast({ type: "plugins_changed", plugins: getPluginStatusStore().listAll() });
|
|
3592
|
+
},
|
|
3593
|
+
log: { info: (m) => console.log(m) },
|
|
3594
|
+
});
|
|
3595
|
+
registerPluginAssetsRoute(fastify, { getRegistry: getRuntimeClientRegistry });
|
|
3596
|
+
// Add-ons hub: feature catalog + combined feature toggle. See change: addons-hub-feature-catalog.
|
|
3597
|
+
registerAddonsRoutes(fastify, {
|
|
3598
|
+
networkGuard,
|
|
3599
|
+
packageManagerWrapper,
|
|
3600
|
+
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
3601
|
+
knownDirectories: () => directoryService.knownDirectories(),
|
|
3602
|
+
// The shared known set (sessions ∪ pins ∪ workspace folders), like every admitted route.
|
|
3603
|
+
knownCwds: knownFolderCwds,
|
|
3604
|
+
lookupNpm: (name) => fetchPackageMeta(name),
|
|
3605
|
+
setPluginsEnabled,
|
|
3606
|
+
// Fastify here runs with logger:false, so its log would drop every toggle line.
|
|
3607
|
+
log: { info: (m) => console.log(m), warn: (m) => console.warn(m), error: (m) => console.error(m) },
|
|
3608
|
+
});
|
|
2622
3609
|
registerProviderRoutes(fastify, { networkGuard, piGateway, browserGateway, port: config.port });
|
|
2623
3610
|
|
|
2624
3611
|
// ── Model Proxy ───────────────────────────────────────────────────
|
|
@@ -2686,20 +3673,35 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2686
3673
|
// hooks to routes at `preReady` (verified against fastify@5.12.1 — `addHook`
|
|
2687
3674
|
// defers through `this.after` and then recurses `_addHook` over `kChildren`),
|
|
2688
3675
|
// including the encapsulated child scopes plugin routes register into. It does
|
|
2689
|
-
// NOT cover a route registered after `ready()
|
|
2690
|
-
//
|
|
3676
|
+
// NOT cover a route registered after `ready()` — and none can be: Fastify refuses
|
|
3677
|
+
// it (`route()` → `throwIfAlreadyStarted('Cannot add route!')`, fastify@5.12.1
|
|
3678
|
+
// `lib/route.js:205`), so a plugin hot-load whose entry registers a route fails that
|
|
3679
|
+
// plugin (logged, status row `loaded:false`) and the route is never served. That
|
|
3680
|
+
// refusal IS the enforcement: never serve sensitive-namespace routes from a second
|
|
3681
|
+
// instance / after-start mechanism without this hook, and install the guard on any
|
|
3682
|
+
// future facility that adds routes after start. Pinned by
|
|
3683
|
+
// `__tests__/post-start-route-registration.test.ts`; re-verify after a fastify bump.
|
|
3684
|
+
// See change: harden-git-terminal-plugin-boundaries (S1r).
|
|
2691
3685
|
fastify.addHook(
|
|
2692
3686
|
"onRequest",
|
|
2693
3687
|
createNetworkGuardHook({
|
|
2694
3688
|
// Live thunk, never a boot snapshot: a CIDR added at runtime admits
|
|
2695
3689
|
// without a restart (D15). Mirrors the per-route guard at 1499.
|
|
2696
|
-
trustedNetworks:
|
|
3690
|
+
trustedNetworks: admissionList,
|
|
2697
3691
|
localToken,
|
|
2698
3692
|
localTrust,
|
|
2699
3693
|
getBypassUrls: () => config.authConfig?.bypassUrls ?? [],
|
|
2700
3694
|
getPairingPrefixes: () => PUBLIC_PAIRING_PREFIXES,
|
|
2701
3695
|
}),
|
|
2702
3696
|
);
|
|
3697
|
+
// Puts the request's caller in scope for every containment decision made while serving it, so the
|
|
3698
|
+
// dashboard-state guard (token, identity key, config out of reach of path-taking routes) and the
|
|
3699
|
+
// prompt-ineligible rule for an unproven local caller need no per-site plumbing. Callback style on
|
|
3700
|
+
// purpose: `run(store, done)` is what keeps the rest of the lifecycle inside the store.
|
|
3701
|
+
// See change: close-container-loopback-impersonation (D8).
|
|
3702
|
+
fastify.addHook("onRequest", (request, _reply, done) => {
|
|
3703
|
+
runWithStateCaller(stateCallerFor(request, localTrust), done);
|
|
3704
|
+
});
|
|
2703
3705
|
// Boot-time inert-entry warning (loopback entry in trustedNetworks /
|
|
2704
3706
|
// bypassHosts). Memoized; the guard re-notes on each reparse.
|
|
2705
3707
|
// See change: fix-trusted-network-tunnel-bypass (D3).
|
|
@@ -2742,6 +3744,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2742
3744
|
// some HTTP/2 proxy chains (notably zrok free-tier) occasionally
|
|
2743
3745
|
// stream-reset as ERR_ABORTED 500 in browsers.
|
|
2744
3746
|
preCompressed: true,
|
|
3747
|
+
// `index.html` (and its `.gz`) is never served by the static handler: every HTML response
|
|
3748
|
+
// passes `sendIndexWithImportMap`, which inserts the host import map. A direct `/index.html.gz`
|
|
3749
|
+
// falls to the not-found handler (the SPA shell, map included). See change: decouple-plugins-from-core (6.4).
|
|
3750
|
+
index: false,
|
|
3751
|
+
allowedPath: (pathName) => pathName !== "/index.html" && pathName !== "/index.html.gz",
|
|
2745
3752
|
// @fastify/static v10 hands `setHeaders` a FastifyReply (v8 passed the
|
|
2746
3753
|
// raw ServerResponse), so the header goes through `.header()`.
|
|
2747
3754
|
setHeaders: (reply, filePath) => {
|
|
@@ -2752,6 +3759,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2752
3759
|
});
|
|
2753
3760
|
}
|
|
2754
3761
|
|
|
3762
|
+
// An unmatched `/api` path is a JSON 404 in every mode, never `index.html` (or a
|
|
3763
|
+
// Vite proxy hop: Vite proxies `/api` straight back here). The guard's own two path
|
|
3764
|
+
// views decide, so an encoded or dotted spelling cannot reach the SPA shell either; an
|
|
3765
|
+
// unparseable target gets the same answer. See change: retro-ux-credential-vault (D7).
|
|
3766
|
+
const replyIfApiNotFound = (request: FastifyRequest, reply: FastifyReply): FastifyReply | undefined => {
|
|
3767
|
+
const target = parseGuardTarget(request.url);
|
|
3768
|
+
const underApi = (p: string) => p === "/api" || p.startsWith("/api/");
|
|
3769
|
+
if (target && !underApi(target.raw) && !underApi(target.resolved)) return undefined;
|
|
3770
|
+
const rawPath = request.url.split(/[?#]/, 1)[0].slice(0, 200);
|
|
3771
|
+
return reply.code(404).send({ success: false, error: "not_found", message: `No API route for ${request.method} ${rawPath}` });
|
|
3772
|
+
};
|
|
3773
|
+
|
|
3774
|
+
const indexSender = createIndexHtmlSender(clientDir, { trustedTypesMode });
|
|
3775
|
+
// Every HTML shell response carries a per-response nonce on its import map; `registerCsp`'s onSend hook
|
|
3776
|
+
// reads the same memoized nonce for the strict policy header. Off mode emits no strict policy → no nonce.
|
|
3777
|
+
// See change: harden-cors-and-csp-reporting (D9).
|
|
3778
|
+
const indexHtml = {
|
|
3779
|
+
sendIndexWithImportMap: (reply: FastifyReply) =>
|
|
3780
|
+
indexSender.sendIndexWithImportMap(reply, cspMode === "off" ? undefined : { nonce: cspNonceFor(reply) }),
|
|
3781
|
+
};
|
|
3782
|
+
|
|
2755
3783
|
if (config.dev) {
|
|
2756
3784
|
// Dev mode: proxy to Vite dev server, fall back to production build
|
|
2757
3785
|
const VITE_PORTS = [3000, 5173, 5174];
|
|
@@ -2769,37 +3797,56 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2769
3797
|
|
|
2770
3798
|
vitePort = await detectVitePort();
|
|
2771
3799
|
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
// Try Vite proxy first
|
|
3800
|
+
/** Proxy `request.url` to Vite; the reply when Vite answered, `undefined` when it is down (re-probed next time). */
|
|
3801
|
+
const proxyToVite = async (request: FastifyRequest, reply: FastifyReply): Promise<FastifyReply | undefined> => {
|
|
2775
3802
|
if (!vitePort) vitePort = await detectVitePort();
|
|
2776
|
-
if (vitePort)
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
3803
|
+
if (!vitePort) return undefined;
|
|
3804
|
+
try {
|
|
3805
|
+
const viteUrl = `http://localhost:${vitePort}${request.url}`;
|
|
3806
|
+
const res = await fetch(viteUrl);
|
|
3807
|
+
const contentType = res.headers.get("content-type");
|
|
3808
|
+
if (contentType) reply.header("Content-Type", contentType);
|
|
3809
|
+
reply.code(res.status);
|
|
3810
|
+
markViteProxied(reply); // dev response: baseline CSP only, no strict/nonce/report destination (D10)
|
|
3811
|
+
return reply.send(Buffer.from(await res.arrayBuffer()));
|
|
3812
|
+
} catch {
|
|
3813
|
+
vitePort = 0; // Vite stopped — re-probe next time
|
|
3814
|
+
return undefined;
|
|
2787
3815
|
}
|
|
3816
|
+
};
|
|
3817
|
+
|
|
3818
|
+
// `/` and `/index.html` keep today's order: Vite first (its HTML carries no injected map), then the
|
|
3819
|
+
// production HTML with the map (D21, R21).
|
|
3820
|
+
if (hasProductionBuild) {
|
|
3821
|
+
const devHtml = async (request: FastifyRequest, reply: FastifyReply) =>
|
|
3822
|
+
(await proxyToVite(request, reply)) ?? indexHtml.sendIndexWithImportMap(reply);
|
|
3823
|
+
fastify.get("/", devHtml);
|
|
3824
|
+
fastify.get("/index.html", devHtml);
|
|
3825
|
+
}
|
|
3826
|
+
|
|
3827
|
+
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3828
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3829
|
+
if (apiMiss) return apiMiss;
|
|
3830
|
+
// Try Vite proxy first
|
|
3831
|
+
const proxied = await proxyToVite(request, reply);
|
|
3832
|
+
if (proxied) return proxied;
|
|
2788
3833
|
// Fallback: serve production build if available
|
|
2789
|
-
if (hasProductionBuild)
|
|
2790
|
-
reply.header("Cache-Control", "no-cache, no-store, must-revalidate");
|
|
2791
|
-
return reply.sendFile("index.html");
|
|
2792
|
-
}
|
|
3834
|
+
if (hasProductionBuild) return indexHtml.sendIndexWithImportMap(reply);
|
|
2793
3835
|
return reply.code(404).send({ error: "API-only mode: no client build available. Install @blackbelt-technology/pi-dashboard-web or run npm run build." });
|
|
2794
3836
|
});
|
|
2795
3837
|
} else if (hasProductionBuild) {
|
|
2796
|
-
// Production mode: SPA fallback
|
|
2797
|
-
fastify.
|
|
2798
|
-
|
|
2799
|
-
|
|
3838
|
+
// Production mode: SPA fallback (and the explicit `/`, `/index.html`) through the import-map sender.
|
|
3839
|
+
fastify.get("/", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
|
|
3840
|
+
fastify.get("/index.html", (_request, reply) => indexHtml.sendIndexWithImportMap(reply));
|
|
3841
|
+
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3842
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3843
|
+
if (apiMiss) return apiMiss;
|
|
3844
|
+
return indexHtml.sendIndexWithImportMap(reply);
|
|
2800
3845
|
});
|
|
2801
3846
|
} else {
|
|
2802
|
-
fastify.setNotFoundHandler(async (
|
|
3847
|
+
fastify.setNotFoundHandler(async (request, reply) => {
|
|
3848
|
+
const apiMiss = replyIfApiNotFound(request, reply);
|
|
3849
|
+
if (apiMiss) return apiMiss;
|
|
2803
3850
|
return reply.code(500).send({ error: "No client build found. Run `npm run build` first." });
|
|
2804
3851
|
});
|
|
2805
3852
|
}
|
|
@@ -2822,6 +3869,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2822
3869
|
if (addr && typeof addr === "object") return addr.port;
|
|
2823
3870
|
return null;
|
|
2824
3871
|
},
|
|
3872
|
+
tls: tlsListener,
|
|
2825
3873
|
piPort() {
|
|
2826
3874
|
// TCP only: a UDS listener has no port, and callers of `piPort()` are
|
|
2827
3875
|
// building `ws://host:<port>` URLs. Socket-transport callers read
|
|
@@ -2846,10 +3894,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2846
3894
|
// captured zombie held. `stop()` also clears `pingTimer`, which is
|
|
2847
3895
|
// what actually lets the process exit.
|
|
2848
3896
|
try { piGateway.stop(); } catch { /* ignore */ }
|
|
3897
|
+
// After the gateway: bridge teardown ends sessions (→ schedule);
|
|
3898
|
+
// stop() clears pending grace timers and latches the sweeper.
|
|
3899
|
+
// See change: archive-service-sessions-on-end.
|
|
3900
|
+
archiveSweeper.stop();
|
|
2849
3901
|
if (secondFastify) {
|
|
2850
3902
|
try { await secondFastify.close(); } catch { /* ignore */ }
|
|
2851
3903
|
secondFastify = null;
|
|
2852
3904
|
}
|
|
3905
|
+
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
2853
3906
|
try { await fastify.close(); } catch { /* ignore */ }
|
|
2854
3907
|
},
|
|
2855
3908
|
});
|
|
@@ -2900,6 +3953,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2900
3953
|
// setSpawnDashboardPiPort in process-manager.ts.
|
|
2901
3954
|
{
|
|
2902
3955
|
const { setSpawnDashboardPiPort } = await import("./spawn-process/process-manager.js");
|
|
3956
|
+
// The bind host is supplied below, once the listener policy is known: the
|
|
3957
|
+
// gateway's ACTUAL TCP host is not always `config.host`.
|
|
3958
|
+
// See change: harden-credential-proof-binding.
|
|
2903
3959
|
setSpawnDashboardPiPort(config.piPort);
|
|
2904
3960
|
// Pin spawned sessions to the transport actually served (read lazily,
|
|
2905
3961
|
// after the gateway starts) — never to another instance's socket.
|
|
@@ -2930,6 +3986,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2930
3986
|
piPort: config.piPort,
|
|
2931
3987
|
version: pkgVersion,
|
|
2932
3988
|
identity: ensureInstanceId(undefined, config.piPort),
|
|
3989
|
+
bindHost: config.host,
|
|
2933
3990
|
// NO signal handlers. `installReleaseHandlers` ends in
|
|
2934
3991
|
// `process.exit(0)`, and `cli.ts` already owns SIGTERM/SIGINT
|
|
2935
3992
|
// (`recordExitIntent` → `flush` → exit). A second exit-forcing
|
|
@@ -2955,7 +4012,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2955
4012
|
const { resolveLocalGatewayEndpoint } = await import(
|
|
2956
4013
|
"@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js"
|
|
2957
4014
|
);
|
|
2958
|
-
const { decideGatewayListeners, isTcpOptIn } = await import("./pi/gateway-transport-policy.js");
|
|
4015
|
+
const { decideGatewayListeners, isTcpOptIn, spawnDialHost } = await import("./pi/gateway-transport-policy.js");
|
|
2959
4016
|
const policy = decideGatewayListeners({
|
|
2960
4017
|
local: resolveLocalGatewayEndpoint(undefined, config.piPort),
|
|
2961
4018
|
tcpOptIn: config.gatewayTcp ?? isTcpOptIn(process.env),
|
|
@@ -2963,6 +4020,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2963
4020
|
piPort: config.piPort,
|
|
2964
4021
|
});
|
|
2965
4022
|
console.log(`[pi-gateway] ${policy.reason}`);
|
|
4023
|
+
// Spawned bridges dial — and on a loopback host demand the counter-proof
|
|
4024
|
+
// from — the host the gateway really binds (`policy.tcp.host`; 127.0.0.1 on
|
|
4025
|
+
// the fallback path), never the HTTP bind host.
|
|
4026
|
+
{
|
|
4027
|
+
const { setSpawnDashboardPiPort } = await import("./spawn-process/process-manager.js");
|
|
4028
|
+
setSpawnDashboardPiPort(config.piPort, spawnDialHost(policy));
|
|
4029
|
+
}
|
|
2966
4030
|
const { startGatewayListeners } = await import("./pi/gateway-listeners.js");
|
|
2967
4031
|
await startGatewayListeners(piGateway, policy, { piPort: config.piPort });
|
|
2968
4032
|
}
|
|
@@ -2978,8 +4042,21 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2978
4042
|
// registering during its activation is immediately routable.
|
|
2979
4043
|
const wsRouteRegistry = getWsRouteRegistry();
|
|
2980
4044
|
setPluginScopeResolver((path) => wsRouteRegistry.resolveScope(path));
|
|
4045
|
+
// Spawn-env contributors of a plugin disabled in config are skipped at
|
|
4046
|
+
// each spawn (the loader has no teardown hook). Same predicate as the
|
|
4047
|
+
// loader's `isEnabled` below. See change: add-context-mode-settings-plugin.
|
|
4048
|
+
setSpawnEnvPluginEnabledCheck((pluginId) => {
|
|
4049
|
+
const pluginCfg = getPluginConfigFromFile(loadConfig(), pluginId) as Record<string, unknown>;
|
|
4050
|
+
const manifest = discoverPlugins().find((p) => p.manifest.id === pluginId)?.manifest;
|
|
4051
|
+
return resolvePluginEnabled(pluginCfg, manifest?.defaultEnabled);
|
|
4052
|
+
});
|
|
2981
4053
|
try {
|
|
2982
|
-
|
|
4054
|
+
// Runtime-client registry: derives `PluginStatus.client` at every status read (live content hash,
|
|
4055
|
+
// trust, config) and serves the admitted-plugin listing. See change: decouple-plugins-from-core (6.7).
|
|
4056
|
+
const runtimeClients = installRuntimeClientRegistry();
|
|
4057
|
+
const pluginLoadDeps: ServerLoadDeps = {
|
|
4058
|
+
// pi-package server entries stay refused until the operator grants server trust (D12, R9).
|
|
4059
|
+
isServerTrusted,
|
|
2983
4060
|
isEnabled: (pluginId) => {
|
|
2984
4061
|
const cfg = loadConfig();
|
|
2985
4062
|
const pluginCfg = getPluginConfigFromFile(cfg, pluginId) as Record<string, unknown>;
|
|
@@ -2999,10 +4076,22 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2999
4076
|
getPluginConfigFromFile(loadConfig(), id) as Record<string, unknown>,
|
|
3000
4077
|
// Bracket this plugin's activation for route-owner attribution (D24): the
|
|
3001
4078
|
// next plugin's createContext re-begins; the finally below ends.
|
|
3002
|
-
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), createServerPluginContext(
|
|
4079
|
+
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), pluginManifestEmits.set(plugin.manifest.id, plugin.manifest.emits ?? []), createServerPluginContext(
|
|
3003
4080
|
{
|
|
3004
4081
|
fastify,
|
|
3005
4082
|
isPiExtensionInstalled,
|
|
4083
|
+
// pi-resources seams (design D4/D5). Default read mirrors
|
|
4084
|
+
// `GET /api/pi-resources` (SWR); `fresh` = a scan started after
|
|
4085
|
+
// the call. Raw scan, no provenance join. See change: add-skill-atlas-screen.
|
|
4086
|
+
getPiResources: async (cwd?: string, opts?: { fresh?: boolean }) => {
|
|
4087
|
+
const key = cwd ?? process.cwd();
|
|
4088
|
+
if (opts?.fresh) return directoryService.refreshPiResourcesFresh(key);
|
|
4089
|
+
const cached = directoryService.getPiResources(key);
|
|
4090
|
+
if (cached?.stale) void directoryService.refreshPiResources(key).catch(() => { /* next read retries */ });
|
|
4091
|
+
return cached?.data ?? directoryService.refreshPiResources(key);
|
|
4092
|
+
},
|
|
4093
|
+
onPiResourcesInvalidated: (handler: (cwd: string | undefined) => void) =>
|
|
4094
|
+
directoryService.onPiResourcesInvalidated(handler),
|
|
3006
4095
|
sessionManager: {
|
|
3007
4096
|
listActive: () => sessionManager.listActive(),
|
|
3008
4097
|
listAll: () => sessionManager.listAll(),
|
|
@@ -3099,6 +4188,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3099
4188
|
// the ref below. The mapper is total (never throws) and
|
|
3100
4189
|
// sanitizes untrusted plugin input. See change:
|
|
3101
4190
|
// add-plugin-spawn-scope (D7).
|
|
4191
|
+
// ACP agent spawn: validate BEFORE anything is filed or spawned (pi-only
|
|
4192
|
+
// options rejected, unknown agent rejected). See change: add-acp-session-driver (D14).
|
|
4193
|
+
const acpRejection = validatePluginAcpSpawn(opts);
|
|
4194
|
+
if (acpRejection) return { success: false, message: acpRejection };
|
|
3102
4195
|
const sessionOptions = pluginSpawnToSessionOptions(opts);
|
|
3103
4196
|
// Honour a caller-supplied spawn token VERBATIM (trusted-only
|
|
3104
4197
|
// — this code only runs past the trusted gate). A token
|
|
@@ -3154,7 +4247,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3154
4247
|
);
|
|
3155
4248
|
}
|
|
3156
4249
|
try {
|
|
3157
|
-
const result =
|
|
4250
|
+
const result =
|
|
4251
|
+
typeof opts.agent === "string"
|
|
4252
|
+
? await spawnAcpSession(opts.cwd, { agent: opts.agent, spawnToken })
|
|
4253
|
+
: await spawnPiSession(opts.cwd, { ...sessionOptions, spawnToken });
|
|
3158
4254
|
// Plugin/automation spawn: transport-less, reclaim required.
|
|
3159
4255
|
armSpawnWatchdog(opts.cwd, "headless", result);
|
|
3160
4256
|
if (result.process && result.pid) {
|
|
@@ -3184,6 +4280,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3184
4280
|
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
3185
4281
|
}
|
|
3186
4282
|
},
|
|
4283
|
+
// Spawn-env contributor hook. Trusted-gated like `spawnSession`
|
|
4284
|
+
// (policy, not a sandbox); untrusted plugins get a no-op.
|
|
4285
|
+
// See change: add-context-mode-settings-plugin.
|
|
4286
|
+
registerSpawnEnvContributor: (fn, opts) =>
|
|
4287
|
+
registerSpawnEnvContributorForPlugin(plugin.manifest, fn, opts),
|
|
3187
4288
|
// Session-abort hook. Gated to first-party/trusted plugins
|
|
3188
4289
|
// (priority <= 100), mirroring `spawnSession`. Untrusted plugins
|
|
3189
4290
|
// get a hook that returns false without sending anything.
|
|
@@ -3205,31 +4306,32 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3205
4306
|
return true;
|
|
3206
4307
|
},
|
|
3207
4308
|
// Terminate an automation run's spawned session. Same trust
|
|
3208
|
-
// gate as spawnSession/abortSession.
|
|
3209
|
-
//
|
|
3210
|
-
//
|
|
3211
|
-
//
|
|
3212
|
-
//
|
|
3213
|
-
|
|
3214
|
-
// See change: fix-automation-stop-zombie-runs.
|
|
3215
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
3216
|
-
abortSpawnedRun: async ({ sessionId, spawnToken, graceful }) => {
|
|
4309
|
+
// gate as spawnSession/abortSession. Both branches resolve through
|
|
4310
|
+
// the ONE shared terminator (`createAbortSpawnedRun`): `graceful`
|
|
4311
|
+
// sends a clean-exit hint first; the spawn token reclaims a run
|
|
4312
|
+
// not yet registered.
|
|
4313
|
+
// See change: fix-automation-stop-zombie-runs, fix-session-reclaim-tmux.
|
|
4314
|
+
abortSpawnedRun: async (args) => {
|
|
3217
4315
|
const trusted = (plugin.manifest.priority ?? 1000) <= 100;
|
|
3218
4316
|
if (!trusted) return false;
|
|
3219
|
-
|
|
3220
|
-
if (graceful && sessionId) {
|
|
3221
|
-
piGateway.sendToSession(sessionId, { type: "shutdown", sessionId });
|
|
3222
|
-
return reg.killBySessionId(sessionId);
|
|
3223
|
-
}
|
|
3224
|
-
if (sessionId) {
|
|
3225
|
-
const killed = await reg.killBySessionId(sessionId);
|
|
3226
|
-
if (killed) return true;
|
|
3227
|
-
if (spawnToken) return reg.killByToken(spawnToken);
|
|
3228
|
-
return false;
|
|
3229
|
-
}
|
|
3230
|
-
if (spawnToken) return reg.killByToken(spawnToken);
|
|
3231
|
-
return false;
|
|
4317
|
+
return abortSpawnedRunImpl(args);
|
|
3232
4318
|
},
|
|
4319
|
+
// Plugin session-close hook: closer + close requests for sessions
|
|
4320
|
+
// this plugin declared. Same trust gate as spawnSession.
|
|
4321
|
+
// See change: add-session-close-plugin-hook.
|
|
4322
|
+
...createPluginSessionCloseApi(
|
|
4323
|
+
{
|
|
4324
|
+
registry: sessionClosers,
|
|
4325
|
+
getSession: (id) => sessionManager.get(id),
|
|
4326
|
+
// Same confirmed shutdown-hint + shared-terminator path as a
|
|
4327
|
+
// graceful abortSpawnedRun (failures counted there).
|
|
4328
|
+
closeNow: (id) => abortSpawnedRunImpl({ sessionId: id, graceful: true }),
|
|
4329
|
+
markArchiveOnEnd,
|
|
4330
|
+
onCloseRequest: () => embedLifecycle.metrics.recordPluginCloseRequest(),
|
|
4331
|
+
},
|
|
4332
|
+
plugin.manifest.id,
|
|
4333
|
+
(plugin.manifest.priority ?? 1000) <= 100,
|
|
4334
|
+
),
|
|
3233
4335
|
// Pin a tightening cwd capability floor. Same trust gate as
|
|
3234
4336
|
// spawnSession (priority <= 100). Untrusted plugins get a no-op
|
|
3235
4337
|
// so a forged manifest cannot constrain unrelated sessions.
|
|
@@ -3241,6 +4343,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3241
4343
|
if (!trusted) return;
|
|
3242
4344
|
cwdPolicyRegistry.register(plugin.manifest.id, cwd, policy);
|
|
3243
4345
|
},
|
|
4346
|
+
// Raise the `cwd` access dialog for a user-initiated write whose cwd
|
|
4347
|
+
// the plugin's guard refused. Same trust gate as registerCwdPolicy
|
|
4348
|
+
// (priority <= 100); an untrusted plugin's hook resolves `refuse`
|
|
4349
|
+
// without raising anything. See change: harden-plugin-cwd-admission.
|
|
4350
|
+
holdCwdDenial: createCwdHold({
|
|
4351
|
+
pluginId: plugin.manifest.id,
|
|
4352
|
+
trusted: (plugin.manifest.priority ?? 1000) <= 100,
|
|
4353
|
+
known: pluginServiceRegistry.get("host.knownFolderCwds") as () => string[],
|
|
4354
|
+
logger: { warn: (m) => console.warn(m) },
|
|
4355
|
+
admitOptions: { onIndeterminate: cwdAdmissionLogger },
|
|
4356
|
+
}),
|
|
3244
4357
|
// Remove the caller's own cwd policy (owner-scoped, idempotent).
|
|
3245
4358
|
// No-op for untrusted plugins. See change: add-plugin-spawn-scope.
|
|
3246
4359
|
unregisterCwdPolicy: (cwd) => {
|
|
@@ -3274,10 +4387,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3274
4387
|
// Empty names never reach here (rejected above, E9) — the
|
|
3275
4388
|
// host's old `name || undefined` normalization is dead by
|
|
3276
4389
|
// design; see relocate-goal-product-to-plugin (D1-#4 note).
|
|
3277
|
-
|
|
4390
|
+
// A plugin rename is a SYSTEM rename: it overwrites the name but never
|
|
4391
|
+
// downgrades `user`. See change: investigate-auto-name-provenance-relabel.
|
|
4392
|
+
const updates = systemRenameUpdates(sessionManager.get(sessionId), name);
|
|
3278
4393
|
sessionManager.update(sessionId, updates);
|
|
3279
4394
|
browserGateway.broadcastSessionUpdated(sessionId, updates);
|
|
3280
|
-
piGateway.sendToSession(sessionId, { type: "rename_session", sessionId, name });
|
|
4395
|
+
piGateway.sendToSession(sessionId, { type: "rename_session", sessionId, name, origin: "system" });
|
|
3281
4396
|
return true;
|
|
3282
4397
|
},
|
|
3283
4398
|
// Merge a plugin-owned ref onto a session — post-spawn sibling
|
|
@@ -3350,15 +4465,33 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3350
4465
|
// this is NOT trust-gated. See change:
|
|
3351
4466
|
// relocate-goal-product-to-plugin (D1-#7).
|
|
3352
4467
|
networkGuard,
|
|
4468
|
+
// `ctx.serveApp`: trust-gated (bundled plugin dir, `auth.trustedPlugins` OR legacy `auth.capabilityRoutePlugins`),
|
|
4469
|
+
// mounts `/apps/<appId>/`. See change: add-plugin-capability-routes (D2, D5).
|
|
4470
|
+
serveApp: createHostServeApp({
|
|
4471
|
+
fastify,
|
|
4472
|
+
plugin: { packageDir: plugin.packageDir, manifestId: plugin.manifest.id, source: plugin.source },
|
|
4473
|
+
readConfiguredIds: () => loadConfig().auth?.capabilityRoutePlugins ?? [],
|
|
4474
|
+
}),
|
|
3353
4475
|
// Emit a configured pi event into a session (relayed as a
|
|
3354
4476
|
// `plugin_emit_event` control message; the in-session bridge
|
|
3355
4477
|
// re-emits it on pi.events). Same trust gate as abortSession.
|
|
3356
4478
|
// See change: automation-emit-configured-event.
|
|
4479
|
+
// Only event types in the plugin's manifest `emits` (live; automation also
|
|
4480
|
+
// gets its accepted action providers' emits) pass.
|
|
4481
|
+
// See change: harden-git-terminal-plugin-boundaries (D16).
|
|
3357
4482
|
emitEventToSession: (sessionId, eventType, data) =>
|
|
3358
4483
|
pluginEventSeam.emitEventToSession(
|
|
3359
4484
|
(plugin.manifest.priority ?? 1000) <= 100,
|
|
3360
4485
|
(sid, m) => piGateway.sendToSession(sid, m),
|
|
3361
4486
|
sessionId, eventType, data,
|
|
4487
|
+
{
|
|
4488
|
+
pluginId: plugin.manifest.id,
|
|
4489
|
+
allowed: () =>
|
|
4490
|
+
pluginEventSeam.computeEmitAllowlist(plugin.manifest.id, {
|
|
4491
|
+
manifestEmits: loadedManifestEmits,
|
|
4492
|
+
actionEntries: () => pluginServiceRegistry.entries("automation.action."),
|
|
4493
|
+
}),
|
|
4494
|
+
},
|
|
3362
4495
|
),
|
|
3363
4496
|
// Raw server→extension control message to one session's bridge
|
|
3364
4497
|
// socket — the `credentials_updated` lane, WITHOUT the
|
|
@@ -3372,18 +4505,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3372
4505
|
(sid, m) => piGateway.sendToSession(sid, m as Parameters<typeof piGateway.sendToSession>[1]),
|
|
3373
4506
|
sessionId, msg,
|
|
3374
4507
|
),
|
|
3375
|
-
|
|
4508
|
+
// Attributed to this plugin; `automation.action.<source>` keys are
|
|
4509
|
+
// refused unless `<source>` is this plugin's id (logged, no throw).
|
|
4510
|
+
provide: (name, value) => { pluginServiceRegistry.provide(plugin.manifest.id, name, value); },
|
|
3376
4511
|
consume: <T = unknown>(name: string) =>
|
|
3377
|
-
pluginServiceRegistry.get(name)
|
|
4512
|
+
pluginServiceRegistry.get<T>(name),
|
|
3378
4513
|
// Prefix enumeration for publish/collect (in-process only).
|
|
3379
4514
|
// See change: decouple-automation-action-registry.
|
|
3380
|
-
consumeAll: <T = unknown>(prefix: string) =>
|
|
3381
|
-
const out: Array<{ key: string; value: T }> = [];
|
|
3382
|
-
for (const [key, value] of pluginServiceRegistry) {
|
|
3383
|
-
if (key.startsWith(prefix)) out.push({ key, value: value as T });
|
|
3384
|
-
}
|
|
3385
|
-
return out;
|
|
3386
|
-
},
|
|
4515
|
+
consumeAll: <T = unknown>(prefix: string) => pluginServiceRegistry.entries<T>(prefix),
|
|
3387
4516
|
// plugin_action fans out by pluginId (manifest-authoritative, not
|
|
3388
4517
|
// self-declared) so multiple plugins coexist; other custom types
|
|
3389
4518
|
// stay single-owner. See change: fix-plugin-action-fanout-and-handlers.
|
|
@@ -3444,6 +4573,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3444
4573
|
// the calling plugin's manifest id. See change:
|
|
3445
4574
|
// expose-plugin-credential-and-oauth-seams (D2, D3, D7).
|
|
3446
4575
|
pluginCredentials: (id) => createPluginCredentialStore(id),
|
|
4576
|
+
// Declared + user-approved vault reads, bound to this plugin's manifest.
|
|
4577
|
+
// See change: add-credential-vault (D4).
|
|
4578
|
+
pluginVault: (id) => createPluginVaultReader(vaultStore, id, plugin.manifest.vaultBindings ?? []),
|
|
3447
4579
|
startPluginOAuthFlow: async (id, opts) => {
|
|
3448
4580
|
const res = await beginFlow({
|
|
3449
4581
|
provider: pluginFlowProvider(id, opts.key),
|
|
@@ -3517,6 +4649,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3517
4649
|
resolveUpgrade: resolveUpgradePrincipal,
|
|
3518
4650
|
policy: policyRegistry,
|
|
3519
4651
|
pluginDataRoot: (pid) => path.join(os.homedir(), ".pi", "dashboard", "plugins", pid),
|
|
4652
|
+
localTrust,
|
|
3520
4653
|
}),
|
|
3521
4654
|
registerBrowserLoginConfig: (loginConfig) => {
|
|
3522
4655
|
const id = plugin.manifest.id;
|
|
@@ -3538,8 +4671,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3538
4671
|
},
|
|
3539
4672
|
},
|
|
3540
4673
|
plugin.manifest.id,
|
|
4674
|
+
// Own editor-pane-tab prefixes gate `ctx.openEditorTab`. See change: add-browser-editor-pane-tab (D5).
|
|
4675
|
+
plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-tab" && c.pathPrefix ? [c.pathPrefix] : [])),
|
|
4676
|
+
// Own file-handler edit claims + package dir gate `ctx.registerFileValidator`. See change: add-editor-pane-file-handlers (D4).
|
|
4677
|
+
{
|
|
4678
|
+
packageDir: plugin.packageDir,
|
|
4679
|
+
editClaimIds: plugin.manifest.claims.flatMap((c) => (c.slot === "editor-pane-file-handler" && c.mode === "edit" && c.id ? [c.id] : [])),
|
|
4680
|
+
},
|
|
3541
4681
|
)),
|
|
4682
|
+
};
|
|
4683
|
+
pluginDiscovery = createPluginDiscoveryWiring({
|
|
4684
|
+
loadDeps: pluginLoadDeps,
|
|
4685
|
+
readDeclaredBundledIds: () => readServedBundledPluginIds(clientDirResolved),
|
|
4686
|
+
clearContentHashCache: () => runtimeClients.clearContentHashCache(),
|
|
4687
|
+
logAdmissions: () => logRuntimeAdmissions({ info: (m) => console.log(m) }, "refresh"),
|
|
4688
|
+
listActiveCwds: () => sessionManager.listActive().map((s) => s.cwd),
|
|
4689
|
+
broadcastPluginsChanged: (plugins) => browserGateway.broadcast({ type: "plugins_changed", plugins }),
|
|
3542
4690
|
});
|
|
4691
|
+
await loadServerEntries(pluginLoadDeps);
|
|
3543
4692
|
} catch (err) {
|
|
3544
4693
|
console.error('[plugin-loader] Unexpected error during pre-listen load:', err);
|
|
3545
4694
|
} finally {
|
|
@@ -3547,8 +4696,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3547
4696
|
routeOwners.end();
|
|
3548
4697
|
}
|
|
3549
4698
|
|
|
4699
|
+
// Named so the optional TLS listener shares this exact switch (one upgrade
|
|
4700
|
+
// path, two transports). See change: add-tailscale-cert-tls (D1).
|
|
3550
4701
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
3551
|
-
|
|
4702
|
+
const onUpgrade = (request: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer): void => {
|
|
4703
|
+
// Stamp the local-credential verdict FIRST (before the Host/Origin gates):
|
|
4704
|
+
// everything below reads it via `hasLocalCredential(request.headers)`.
|
|
4705
|
+
// The proof floor is per transport: a TLS socket is stamped against the
|
|
4706
|
+
// TLS listener's own bind time, so a proof for the main port never
|
|
4707
|
+
// verifies here. See change: add-tailscale-cert-tls (D1).
|
|
4708
|
+
localCredential.stamp(request, {
|
|
4709
|
+
kind: "http",
|
|
4710
|
+
boundAt: (socket as import("node:tls").TLSSocket).encrypted ? tlsBoundAt : httpBoundAt,
|
|
4711
|
+
});
|
|
3552
4712
|
// Ephemeral single-use ticket (D11) bound to the requested WS route
|
|
3553
4713
|
// scope. The one cheap read BEFORE the first gate — the host-admission
|
|
3554
4714
|
// log line names the scope.
|
|
@@ -3574,7 +4734,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3574
4734
|
|
|
3575
4735
|
// Access check for WebSocket upgrades
|
|
3576
4736
|
const remoteAddress = request.socket.remoteAddress || "";
|
|
3577
|
-
|
|
4737
|
+
// Live admission list per upgrade (empty under `pair`) — NOT the boot
|
|
4738
|
+
// value. See change: retire-trusted-networks-bypass (D1).
|
|
4739
|
+
const trusted = admissionList();
|
|
3578
4740
|
const secWsProtocol = request.headers["sec-websocket-protocol"] as string | undefined;
|
|
3579
4741
|
|
|
3580
4742
|
// ── Plugin-owned WS routes (change: add-browser-relay D1) ──────────
|
|
@@ -3604,7 +4766,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3604
4766
|
registration.admitOrigins,
|
|
3605
4767
|
corsOpts(),
|
|
3606
4768
|
) ||
|
|
3607
|
-
!isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust
|
|
4769
|
+
!isPluginScopePeerLocal(remoteAddress, request.headers.host, wsReqHeaders, localTrust, {
|
|
4770
|
+
pluginAuthenticatesPeer: registration.peerCredential === "plugin",
|
|
4771
|
+
})
|
|
3608
4772
|
) {
|
|
3609
4773
|
console.error(
|
|
3610
4774
|
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
@@ -3646,7 +4810,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3646
4810
|
// routed path from an unrouted one. A browser cannot omit or forge
|
|
3647
4811
|
// `Origin` on a handshake; every non-browser client sends none and is
|
|
3648
4812
|
// unaffected. See change: fix-ws-origin-cswsh (D1).
|
|
3649
|
-
|
|
4813
|
+
// A live-scope upgrade may be admitted by a validated capability path
|
|
4814
|
+
// (token read from the path segment only — never query/subprotocol).
|
|
4815
|
+
// Any other scope ignores it entirely. The opaque `Origin: null` is admitted
|
|
4816
|
+
// only WITH a valid capability. See change: retire-trusted-networks-bypass (D5),
|
|
4817
|
+
// improve-canvas-html-and-url-ux (D10).
|
|
4818
|
+
const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
|
|
4819
|
+
const liveCapPrincipal = liveCap
|
|
4820
|
+
? liveCapabilities.validate(liveCap.targetId, liveCap.token, {
|
|
4821
|
+
genuinelyLocal: isLocallyTrusted({ ip: remoteAddress, headers: request.headers as Record<string, unknown> }),
|
|
4822
|
+
})
|
|
4823
|
+
: null;
|
|
4824
|
+
if (!isWsOriginTrusted(request.headers.origin, request.headers.host, scope, corsOpts(), liveCapPrincipal !== null)) {
|
|
3650
4825
|
console.error(
|
|
3651
4826
|
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope ?? "none"} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
3652
4827
|
);
|
|
@@ -3660,16 +4835,27 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3660
4835
|
// the dashboard port would silently burn its ticket and see a bare TCP
|
|
3661
4836
|
// close (@review Audit, minor).
|
|
3662
4837
|
if (scope === "bridge") {
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
4838
|
+
// The native TLS listener may admit a paired device's bridge (opt-in `tls.acceptBridges`); every
|
|
4839
|
+
// other case keeps the 400 without consuming the ticket. See change: prove-vault-bridge-tls (D2).
|
|
4840
|
+
routeBridgeUpgrade(
|
|
4841
|
+
{
|
|
4842
|
+
acceptBridges: tlsBridgesLive,
|
|
4843
|
+
gateway: piGateway,
|
|
4844
|
+
rejectLog: ({ status, reason }) =>
|
|
4845
|
+
wsUpgradeRejectLog.log({
|
|
4846
|
+
status,
|
|
4847
|
+
scope,
|
|
4848
|
+
remoteAddress,
|
|
4849
|
+
headers: request.headers as unknown as Record<string, unknown>,
|
|
4850
|
+
// Presence only — read from the URL/protocol header, never consumed.
|
|
4851
|
+
ticketPresent: extractTicket(request.url, secWsProtocol) !== null,
|
|
4852
|
+
...(reason ? { reason } : {}),
|
|
4853
|
+
}),
|
|
4854
|
+
},
|
|
4855
|
+
request,
|
|
4856
|
+
socket,
|
|
4857
|
+
head,
|
|
4858
|
+
);
|
|
3673
4859
|
return;
|
|
3674
4860
|
}
|
|
3675
4861
|
const ticket = extractTicket(request.url, secWsProtocol);
|
|
@@ -3695,12 +4881,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3695
4881
|
localToken,
|
|
3696
4882
|
localTrust,
|
|
3697
4883
|
requireIdentityTicket,
|
|
4884
|
+
liveCapability: liveCapPrincipal
|
|
4885
|
+
? { identity: liveCapPrincipal.identity, identityExpiresAt: liveCapPrincipal.identityExpiresAt }
|
|
4886
|
+
: null,
|
|
4887
|
+
// A revoked / disabled passkey user's cookie opens no socket (D4).
|
|
4888
|
+
isSessionLive: (p) => effectiveSessionTier(p, passkeyService) !== null,
|
|
3698
4889
|
});
|
|
4890
|
+
// Cookie-session sockets carry the session's LIVE tier (passkey users
|
|
4891
|
+
// re-read the directory). Terminals need operate, live previews
|
|
4892
|
+
// control; browser messages are gated per type in the gateway.
|
|
4893
|
+
// See change: add-passkey-user-auth.
|
|
4894
|
+
const sessionPayload = upgradeAuth.ok ? upgradeAuth.session : undefined;
|
|
4895
|
+
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService) : undefined;
|
|
4896
|
+
const roadTier = scope === "terminal" ? TERMINAL_TIER : scope === "live" ? LIVE_PREVIEW_TIER : undefined;
|
|
4897
|
+
if (sessionTierOf && roadTier) {
|
|
4898
|
+
const t = sessionTierOf();
|
|
4899
|
+
if (t === null || rank(t) < rank(roadTier)) {
|
|
4900
|
+
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4901
|
+
socket.destroy();
|
|
4902
|
+
return;
|
|
4903
|
+
}
|
|
4904
|
+
}
|
|
3699
4905
|
if (!upgradeAuth.ok) {
|
|
3700
4906
|
// 401 when an auth secret is configured (cookie realm), else 403 for
|
|
3701
4907
|
// the no-auth allowances — preserving the prior status semantics.
|
|
3702
4908
|
const status = config.authConfig?.secret ? "401 Unauthorized" : "403 Forbidden";
|
|
3703
|
-
wsUpgradeRejectLog.log({
|
|
4909
|
+
wsUpgradeRejectLog.log({
|
|
4910
|
+
status: config.authConfig?.secret ? 401 : 403,
|
|
4911
|
+
scope: scope ?? "none",
|
|
4912
|
+
remoteAddress,
|
|
4913
|
+
headers: wsHeaders,
|
|
4914
|
+
ticketPresent: ticket !== null,
|
|
4915
|
+
// A bare-loopback dial refused only for want of proof: say so (fixed token, no caller input).
|
|
4916
|
+
...(needsLocalProof({ ip: remoteAddress ?? "", headers: wsHeaders }, localTrust) ? { reason: "local_proof_required" } : {}),
|
|
4917
|
+
});
|
|
3704
4918
|
socket.write(`HTTP/1.1 ${status}\r\n\r\n`);
|
|
3705
4919
|
socket.destroy();
|
|
3706
4920
|
return;
|
|
@@ -3762,7 +4976,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3762
4976
|
: Object.freeze({ ...upgradeAuth.principal });
|
|
3763
4977
|
bound.principalExpiresAt = upgradeAuth.principalExpiresAt;
|
|
3764
4978
|
}
|
|
4979
|
+
// Locality is decided ONCE here, from the upgrade request; handlers read the bit.
|
|
4980
|
+
// See change: harden-server-capability-bounds (D1b).
|
|
4981
|
+
stampSocketLocality(ws, request, localTrust);
|
|
3765
4982
|
if (grants) (ws as { bootstrapGrants?: BootstrapGrants }).bootstrapGrants = grants;
|
|
4983
|
+
if (sessionTierOf) (ws as TieredSocket).sessionTier = sessionTierOf;
|
|
3766
4984
|
browserGateway.wss.emit("connection", ws, request);
|
|
3767
4985
|
});
|
|
3768
4986
|
if (identityEnforced() && policyRegistry.hasPolicy()) {
|
|
@@ -3804,18 +5022,24 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3804
5022
|
case "live": {
|
|
3805
5023
|
// Review B2 (policy `live.read` before the upgrade) + B1 (a proxied
|
|
3806
5024
|
// dev-server socket must not outlive the ticket's principal).
|
|
3807
|
-
gateRoadUpgrade(HostActions.liveRead, { kind: "live", route: (request.url ?? "").split("?")[0] }, () => {
|
|
5025
|
+
gateRoadUpgrade(HostActions.liveRead, { kind: "live", route: redactCapability((request.url ?? "").split("?")[0]) }, () => {
|
|
3808
5026
|
// Chunked past the 32-bit timer cap (`scheduleAtExpiry`), released on close.
|
|
3809
5027
|
const cancelExpiry = scheduleAtExpiry(upgradeAuth.principalExpiresAt, () => socket.destroy());
|
|
3810
5028
|
socket.once("close", cancelExpiry);
|
|
3811
|
-
handleLiveServerUpgrade(liveServerManager, request, socket, head
|
|
5029
|
+
handleLiveServerUpgrade(liveServerManager, request, socket, head, {
|
|
5030
|
+
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
5031
|
+
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
5032
|
+
capabilityPrefix: liveCapPrincipal && liveCap ? liveCap.prefix : undefined,
|
|
5033
|
+
});
|
|
3812
5034
|
});
|
|
3813
5035
|
break;
|
|
3814
5036
|
}
|
|
3815
5037
|
default:
|
|
3816
5038
|
socket.destroy();
|
|
3817
5039
|
}
|
|
3818
|
-
}
|
|
5040
|
+
};
|
|
5041
|
+
fastify.server.on("upgrade", onUpgrade);
|
|
5042
|
+
tlsUpgrade = onUpgrade;
|
|
3819
5043
|
|
|
3820
5044
|
// Identity-plane arming (D1/D8/D9/D21). Runs AFTER plugins have loaded
|
|
3821
5045
|
// (outside the loader try, so a loader throw cannot skip it) and BEFORE
|
|
@@ -3842,9 +5066,29 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3842
5066
|
}
|
|
3843
5067
|
}
|
|
3844
5068
|
|
|
3845
|
-
|
|
5069
|
+
// The proof floor is taken after readiness, immediately before the bind.
|
|
5070
|
+
await listenWithProofFloor(fastify, (at) => (httpBoundAt = at), { port: config.port, host: config.host });
|
|
5071
|
+
const bound = fastify.server.address();
|
|
5072
|
+
if (bound && typeof bound === "object") httpListenPort = bound.port;
|
|
3846
5073
|
writePid(process.pid);
|
|
3847
5074
|
console.log(`Dashboard server running at http://${config.host}:${config.port}`);
|
|
5075
|
+
// Optional TLS listener: only after Fastify is ready and the main listen resolved.
|
|
5076
|
+
// Failure-isolated — a TLS problem never affects the main listener.
|
|
5077
|
+
// See change: add-tailscale-cert-tls (D1, D7).
|
|
5078
|
+
void tlsListener.markReady().catch((err: unknown) => {
|
|
5079
|
+
console.warn(`[tls] listener start failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
5080
|
+
});
|
|
5081
|
+
|
|
5082
|
+
// Managed services: adoption + scheduler only once the server really
|
|
5083
|
+
// started (a created-but-never-started server touches nothing). Boot is
|
|
5084
|
+
// adoption only and a no-op without services.json; never blocks startup.
|
|
5085
|
+
// See change: add-service-registry-core.
|
|
5086
|
+
// The scheduler starts whether or not adoption succeeded: lease sweeps,
|
|
5087
|
+
// leased re-probes and idle-stop must run regardless.
|
|
5088
|
+
serviceManager
|
|
5089
|
+
.boot()
|
|
5090
|
+
.catch((err: unknown) => console.warn(`[services] boot adoption failed: ${(err as Error).message}`))
|
|
5091
|
+
.finally(() => serviceManager.startScheduler());
|
|
3848
5092
|
|
|
3849
5093
|
// Bind-vs-trust reachability. A loopback or specific-NIC bind silently
|
|
3850
5094
|
// voids a trusted network outside its range: the TCP connection is
|
|
@@ -3916,12 +5160,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3916
5160
|
// The verdict names skips honestly: a loopback-bound server must not
|
|
3917
5161
|
// log "advertising" when nothing was published. (CodeRabbit review,
|
|
3918
5162
|
// fix-bridge-mdns-migration-hijack.)
|
|
3919
|
-
|
|
3920
|
-
|
|
3921
|
-
|
|
3922
|
-
|
|
3923
|
-
|
|
3924
|
-
|
|
5163
|
+
// advertiseDashboard logs the verdict itself (loopback skip, no
|
|
5164
|
+
// advertisable address, or the derived instance name + addresses).
|
|
5165
|
+
advertiseDashboard(config.port, config.piPort, {
|
|
5166
|
+
bindHost: config.host,
|
|
5167
|
+
addresses: await resolveAdvertisedAddresses(config.host),
|
|
5168
|
+
fingerprint: serverIdentity.fingerprint,
|
|
5169
|
+
version: pkgVersion,
|
|
5170
|
+
name: () => loadConfig().dashboardName || "",
|
|
5171
|
+
resolveAddresses: () => resolveAdvertisedAddresses(config.host),
|
|
5172
|
+
});
|
|
3925
5173
|
}
|
|
3926
5174
|
} catch (err) {
|
|
3927
5175
|
console.warn(`mDNS advertisement failed (will continue without):`, err);
|
|
@@ -3932,16 +5180,20 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3932
5180
|
if (mdnsDisabled) {
|
|
3933
5181
|
// skip peer discovery entirely
|
|
3934
5182
|
} else {
|
|
3935
|
-
mdnsBrowser = createBrowser();
|
|
3936
|
-
|
|
3937
|
-
|
|
3938
|
-
|
|
3939
|
-
|
|
3940
|
-
|
|
3941
|
-
|
|
3942
|
-
|
|
3943
|
-
|
|
3944
|
-
|
|
5183
|
+
mdnsBrowser = createBrowser({ ownFingerprint: () => serverIdentity.fingerprint });
|
|
5184
|
+
wirePeerServers({
|
|
5185
|
+
browser: mdnsBrowser,
|
|
5186
|
+
peers: peerServers,
|
|
5187
|
+
self: () => ({
|
|
5188
|
+
host: selfHostname,
|
|
5189
|
+
port: config.port,
|
|
5190
|
+
piPort: config.piPort,
|
|
5191
|
+
version: pkgVersion,
|
|
5192
|
+
fingerprint: serverIdentity.fingerprint,
|
|
5193
|
+
name: loadConfig().dashboardName || selfHostname.replace(/\.local$/i, ""),
|
|
5194
|
+
}),
|
|
5195
|
+
broadcast: (servers) => browserGateway.broadcast({ type: "servers_updated", servers }),
|
|
5196
|
+
moves: knownServerMoves,
|
|
3945
5197
|
});
|
|
3946
5198
|
}
|
|
3947
5199
|
} catch (err) {
|
|
@@ -4029,9 +5281,23 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4029
5281
|
// or they would land in every pi session's tool list.
|
|
4030
5282
|
// See change: expose-plugin-credential-and-oauth-seams (D8).
|
|
4031
5283
|
.filter(p => fixtureEntryAllowed(p.manifest))
|
|
4032
|
-
|
|
5284
|
+
// A pi-package bridge is not auto-registered until the operator grants server trust
|
|
5285
|
+
// (D12, R9). See change: decouple-plugins-from-core (task 5.2).
|
|
5286
|
+
.filter(p => pluginServerAllowed(p, isServerTrusted))
|
|
5287
|
+
// A disabled plugin's bridge is deregistered (both registries) and an
|
|
5288
|
+
// enabled one registered — same predicate as the server-entry loader.
|
|
5289
|
+
// The toggle route answers `restartRequired`, so this boot pass is
|
|
5290
|
+
// where a toggle lands. See change: add-plugin-bridge-contributions (D13).
|
|
5291
|
+
.map(p => ({
|
|
5292
|
+
pluginId: p.manifest.id,
|
|
5293
|
+
bridgePath: p.bridgeEntryPath!,
|
|
5294
|
+
enabled: resolvePluginEnabled(
|
|
5295
|
+
getPluginConfigFromFile(loadConfig(), p.manifest.id) as Record<string, unknown>,
|
|
5296
|
+
p.manifest.defaultEnabled,
|
|
5297
|
+
),
|
|
5298
|
+
}));
|
|
4033
5299
|
if (pluginsWithBridges.length) {
|
|
4034
|
-
const results =
|
|
5300
|
+
const results = syncPluginBridges(pluginsWithBridges);
|
|
4035
5301
|
for (const [id, result] of Object.entries(results)) {
|
|
4036
5302
|
if (result.type === 'conflict') {
|
|
4037
5303
|
const store = getPluginStatusStore();
|
|
@@ -4064,6 +5330,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4064
5330
|
console.warn("[plugin-bridge] Reconciliation failed (non-fatal):", err);
|
|
4065
5331
|
}
|
|
4066
5332
|
|
|
5333
|
+
// Log-only health scan of settings.json packages[] (never mutates, never
|
|
5334
|
+
// throws). Not awaited: cold listConfiguredPackages can take seconds on
|
|
5335
|
+
// Windows and boot must not wait on a diagnostic. See change: add-package-health-cleanup.
|
|
5336
|
+
logPackageHealthAtBoot({ listInstalled: () => packageManagerWrapper.listInstalled("global") }).catch((err) =>
|
|
5337
|
+
console.warn("[package-health] boot scan failed (non-fatal):", err),
|
|
5338
|
+
);
|
|
5339
|
+
|
|
4067
5340
|
idleTimer.start();
|
|
4068
5341
|
// Arm the ephemeral boot-parent watch (D5) — a no-op unless --ephemeral
|
|
4069
5342
|
// was passed. Its interval IS the stated exit-latency bound.
|
|
@@ -4184,6 +5457,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4184
5457
|
// See change: add-access-grant-dialog.
|
|
4185
5458
|
installGrantCoordinator(null);
|
|
4186
5459
|
setNetworkDenialObserver(null);
|
|
5460
|
+
setLocalProofRefusalObserver(null);
|
|
4187
5461
|
// Stop the event-loop-delay monitor so the libuv timer doesn't linger
|
|
4188
5462
|
// after teardown. See change: instrument-session-hydration-timing.
|
|
4189
5463
|
try { eventLoopDelayHistogram.disable(); } catch { /* ignore */ }
|
|
@@ -4204,6 +5478,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4204
5478
|
// wiring above; unref'd, so this is leak-hygiene not liveness).
|
|
4205
5479
|
clearInterval(hostGateFlushTimer);
|
|
4206
5480
|
directoryService.stopPolling();
|
|
5481
|
+
// ACP host A: end in-process sessions through the gateway (unregister →
|
|
5482
|
+
// ended + persisted with `driver:"acp"`), killing their agents, BEFORE the
|
|
5483
|
+
// headless sweep. See change: add-acp-session-driver (D1).
|
|
5484
|
+
await stopAllLocalAcpSessions();
|
|
5485
|
+
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
4207
5486
|
// SIGTERMs every dashboard-spawned pi: after this the sessions below are
|
|
4208
5487
|
// GONE and can never reattach.
|
|
4209
5488
|
browserGateway.shutdownHeadlessProcesses();
|
|
@@ -4237,6 +5516,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4237
5516
|
}
|
|
4238
5517
|
pendingForkRegistry.dispose();
|
|
4239
5518
|
pairingManager.dispose();
|
|
5519
|
+
stopDeviceExpirySweep();
|
|
5520
|
+
vaultDelivery.dispose();
|
|
4240
5521
|
// Every pending ack holds a timer; a create/stop cycle must not leak them.
|
|
4241
5522
|
// See change: fix-spawn-correlation-ttl-coupling (D7).
|
|
4242
5523
|
pendingPromptAcks.dispose();
|
|
@@ -4260,6 +5541,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4260
5541
|
}
|
|
4261
5542
|
homeRendezvous = null;
|
|
4262
5543
|
piGateway.stop();
|
|
5544
|
+
// Await the socket teardown stop() hands off, so stop() never resolves
|
|
5545
|
+
// while it can still touch HOME (and log after a test tore HOME down).
|
|
5546
|
+
await piGateway.stopped();
|
|
5547
|
+
// Clears pending on-end archive timers + latches the sweeper; after the
|
|
5548
|
+
// gateway so sessions it ends cannot re-arm one.
|
|
5549
|
+
// See change: archive-service-sessions-on-end.
|
|
5550
|
+
archiveSweeper.stop();
|
|
5551
|
+
serviceManager.dispose();
|
|
4263
5552
|
for (const client of browserGateway.wss.clients) {
|
|
4264
5553
|
client.terminate();
|
|
4265
5554
|
}
|
|
@@ -4277,6 +5566,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4277
5566
|
try { await secondFastify.close(); } catch { /* ignore */ }
|
|
4278
5567
|
secondFastify = null;
|
|
4279
5568
|
}
|
|
5569
|
+
// The TLS listener (and its open connections) closes with the server.
|
|
5570
|
+
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
4280
5571
|
await fastify.close();
|
|
4281
5572
|
},
|
|
4282
5573
|
};
|