@blackbelt-technology/pi-agent-dashboard 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -0
- package/README.md +17 -12
- package/docs/architecture.md +973 -224
- package/package.json +29 -18
- package/packages/extension/package.json +16 -9
- package/packages/extension/src/bridge-context.ts +6 -0
- package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
- package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
- package/packages/extension/src/bridge-handlers/instance.ts +21 -12
- package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
- package/packages/extension/src/bridge-shutdown.ts +44 -0
- package/packages/extension/src/bridge.ts +272 -260
- package/packages/extension/src/command-handler.ts +26 -31
- package/packages/extension/src/connection.ts +123 -31
- package/packages/extension/src/credential-guard.ts +300 -0
- package/packages/extension/src/custom-entry-forward.ts +27 -18
- package/packages/extension/src/default-model-apply.ts +83 -0
- package/packages/extension/src/flow-event-wiring.ts +19 -95
- package/packages/extension/src/followup-drain.ts +19 -5
- package/packages/extension/src/path-gate/decide.ts +68 -5
- package/packages/extension/src/path-gate/handler.ts +16 -8
- package/packages/extension/src/path-gate/index.ts +2 -2
- package/packages/extension/src/path-gate/roots.ts +15 -3
- package/packages/extension/src/path-gate/suppression.ts +3 -0
- package/packages/extension/src/pi-env.d.ts +8 -1
- package/packages/extension/src/pi-retry-settings.ts +11 -2
- package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
- package/packages/extension/src/preview-path-link.ts +151 -0
- package/packages/extension/src/project-init/scaffold.ts +98 -35
- package/packages/extension/src/project-trust.ts +24 -15
- package/packages/extension/src/provider-model-cache.ts +118 -0
- package/packages/extension/src/provider-register.ts +428 -28
- package/packages/extension/src/retry-tracker.ts +90 -7
- package/packages/extension/src/role-manager.ts +4 -2
- package/packages/extension/src/role-model-tools.ts +21 -4
- package/packages/extension/src/server-auto-start.ts +68 -2
- package/packages/extension/src/server-launcher.ts +26 -8
- package/packages/extension/src/session-sync.ts +11 -12
- package/packages/extension/src/spawn-new-session.ts +22 -0
- package/packages/extension/src/steer-buffer.ts +164 -0
- package/packages/extension/src/stream-forward-buffer.ts +64 -15
- package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
- package/packages/extension/src/sudo-askpass/controller.ts +405 -0
- package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
- package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
- package/packages/extension/src/sudo-askpass/index.ts +11 -0
- package/packages/extension/src/sudo-askpass/install.ts +143 -0
- package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
- package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
- package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
- package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
- package/packages/extension/src/terminal-reload.ts +19 -5
- package/packages/extension/src/tool-update-filter-registry.ts +210 -0
- package/packages/extension/src/vault-redaction.ts +4 -3
- package/packages/server/package.json +17 -14
- package/packages/server/src/access/access-denials.ts +8 -0
- package/packages/server/src/access/access-grants.ts +244 -58
- package/packages/server/src/access/access-plane.ts +7 -0
- package/packages/server/src/access/containment-gate.ts +66 -21
- package/packages/server/src/access/denial-hold.ts +3 -0
- package/packages/server/src/access/grant-coordinator.ts +17 -1
- package/packages/server/src/access/named-grant.ts +3 -0
- package/packages/server/src/access/pending-grant-registry.ts +32 -5
- package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
- package/packages/server/src/access/planes.ts +1 -0
- package/packages/server/src/access/verified-read.ts +24 -7
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
- package/packages/server/src/acp-bridge/server-requests.ts +10 -4
- package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
- package/packages/server/src/auth/audit-log.ts +28 -0
- package/packages/server/src/auth/auth-plugin.ts +188 -15
- package/packages/server/src/auth/auth.ts +80 -0
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
- package/packages/server/src/auth/cors-origin.ts +14 -1
- package/packages/server/src/auth/credential-envelope.ts +233 -0
- package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
- package/packages/server/src/auth/credential-key-worker.mjs +108 -0
- package/packages/server/src/auth/credential-key.ts +479 -0
- package/packages/server/src/auth/credential-migration.ts +162 -0
- package/packages/server/src/auth/csp-report-paths.ts +0 -5
- package/packages/server/src/auth/csp.ts +74 -36
- package/packages/server/src/auth/device-proof.ts +202 -0
- package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
- package/packages/server/src/auth/host-admission.ts +7 -0
- package/packages/server/src/auth/host-gate.ts +13 -2
- package/packages/server/src/auth/localhost-guard.ts +50 -23
- package/packages/server/src/auth/locked-json-file.ts +68 -6
- package/packages/server/src/auth/models-json-store.ts +269 -0
- package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
- package/packages/server/src/auth/node-guard.ts +36 -49
- package/packages/server/src/auth/plugin-credential-store.ts +81 -10
- package/packages/server/src/auth/provider-auth-storage.ts +208 -11
- package/packages/server/src/auth/provider-block-checks.ts +321 -0
- package/packages/server/src/auth/provider-host-detect.ts +151 -0
- package/packages/server/src/auth/provider-key-file.ts +71 -0
- package/packages/server/src/auth/provider-readiness.ts +91 -0
- package/packages/server/src/auth/route-tier-gate.ts +3 -2
- package/packages/server/src/auth/vertex-key-check.ts +140 -0
- package/packages/server/src/auth/ws-ticket.ts +1 -1
- package/packages/server/src/browse.ts +73 -20
- package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
- package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
- package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
- package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
- package/packages/server/src/build-plugin-send-prompt.ts +18 -0
- package/packages/server/src/cli/credentials-command.ts +555 -0
- package/packages/server/src/cli.ts +21 -16
- package/packages/server/src/config-api.ts +34 -38
- package/packages/server/src/config-snapshot.ts +149 -0
- package/packages/server/src/directory-service.ts +33 -14
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
- package/packages/server/src/event-wiring.ts +181 -101
- package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
- package/packages/server/src/git-worktree/git-operations.ts +1 -1
- package/packages/server/src/git-worktree/repo-lock.ts +42 -0
- package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
- package/packages/server/src/git-worktree/worktree-init.ts +5 -1
- package/packages/server/src/identity/http-road-classification.ts +5 -1
- package/packages/server/src/identity/identity-floor.ts +5 -2
- package/packages/server/src/identity/ws-message-scope.ts +10 -3
- package/packages/server/src/identity/ws-road-classification.ts +2 -1
- package/packages/server/src/lib/browse-roots.ts +13 -2
- package/packages/server/src/lib/content-disposition.ts +20 -0
- package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
- package/packages/server/src/lib/eml.ts +2 -2
- package/packages/server/src/lib/frame-policy-probe.ts +308 -0
- package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
- package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
- package/packages/server/src/lib/grep.ts +4 -1
- package/packages/server/src/lib/index-html.ts +2 -2
- package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
- package/packages/server/src/lib/office-preview.ts +47 -10
- package/packages/server/src/lib/path-containment.ts +45 -12
- package/packages/server/src/lib/resolve-file-mention.ts +230 -38
- package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
- package/packages/server/src/lib/writable-handler-target.ts +4 -0
- package/packages/server/src/lib/writable-md-target.ts +22 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
- package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
- package/packages/server/src/lifecycle/exit-signal.ts +43 -0
- package/packages/server/src/live-server/capability-redact.ts +21 -5
- package/packages/server/src/live-server/live-capability.ts +416 -52
- package/packages/server/src/live-server/live-csp-report.ts +1 -1
- package/packages/server/src/live-server/live-csp.ts +64 -16
- package/packages/server/src/live-server/live-log.ts +5 -1
- package/packages/server/src/live-server/live-server-manager.ts +11 -0
- package/packages/server/src/live-server/live-server-proxy.ts +268 -52
- package/packages/server/src/live-server/live-static.ts +4 -1
- package/packages/server/src/live-server/preview-dispatch.ts +286 -0
- package/packages/server/src/live-server/preview-observe.ts +53 -0
- package/packages/server/src/live-server/preview-origin.ts +182 -0
- package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
- package/packages/server/src/live-server/preview-path-store.ts +420 -0
- package/packages/server/src/live-server/preview-path.ts +40 -0
- package/packages/server/src/live-server/preview-pool.ts +385 -0
- package/packages/server/src/live-server/preview-preflight.ts +41 -0
- package/packages/server/src/live-server/preview-reserve.ts +44 -0
- package/packages/server/src/live-server/preview-tier.ts +217 -0
- package/packages/server/src/live-server/preview-viewers.ts +54 -0
- package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
- package/packages/server/src/model-proxy/internal-registry.ts +283 -21
- package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
- package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
- package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
- package/packages/server/src/openspec/readiness.ts +1 -1
- package/packages/server/src/package/provider-probe.ts +194 -5
- package/packages/server/src/pairing/browser-gateway.ts +140 -42
- package/packages/server/src/pairing/device-key-intake.ts +120 -0
- package/packages/server/src/pairing/paired-devices.ts +370 -8
- package/packages/server/src/pairing/pairing.ts +69 -7
- package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
- package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
- package/packages/server/src/pending/pending-attach-registry.ts +15 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
- package/packages/server/src/persistence/memory-event-store.ts +251 -296
- package/packages/server/src/persistence/preferences-store.ts +52 -2
- package/packages/server/src/pi/bridge-contention.ts +84 -2
- package/packages/server/src/pi/host-project-trust.ts +15 -9
- package/packages/server/src/pi/pi-gateway.ts +208 -21
- package/packages/server/src/pi/provisional-registration.ts +4 -1
- package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
- package/packages/server/src/pi-agent-settings.ts +95 -301
- package/packages/server/src/pi-default-remirror.ts +89 -0
- package/packages/server/src/plugin-append-event.ts +35 -0
- package/packages/server/src/plugin-entry-stats.ts +61 -0
- package/packages/server/src/plugin-local-request.ts +207 -0
- package/packages/server/src/plugin-ownership.ts +111 -0
- package/packages/server/src/plugin-policy-registry.ts +297 -0
- package/packages/server/src/plugin-request-lane.ts +92 -16
- package/packages/server/src/preferences-relay.ts +20 -0
- package/packages/server/src/project-seed.ts +347 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
- package/packages/server/src/questions/question-store.ts +3 -2
- package/packages/server/src/routes/access-routes.ts +23 -6
- package/packages/server/src/routes/acme-routes.ts +14 -4
- package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
- package/packages/server/src/routes/file-routes.ts +327 -86
- package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
- package/packages/server/src/routes/frame-policy-routes.ts +215 -0
- package/packages/server/src/routes/git-routes.ts +29 -78
- package/packages/server/src/routes/grep-routes.ts +26 -0
- package/packages/server/src/routes/live-server-routes.ts +198 -4
- package/packages/server/src/routes/models-introspection-routes.ts +1 -1
- package/packages/server/src/routes/openspec-routes.ts +17 -3
- package/packages/server/src/routes/pairing-routes.ts +200 -11
- package/packages/server/src/routes/pi-settings-routes.ts +2 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
- package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
- package/packages/server/src/routes/provider-auth-routes.ts +167 -9
- package/packages/server/src/routes/provider-override-routes.ts +158 -0
- package/packages/server/src/routes/provider-routes.ts +348 -86
- package/packages/server/src/routes/session-routes.ts +25 -22
- package/packages/server/src/routes/system-routes.ts +87 -39
- package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
- package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
- package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
- package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
- package/packages/server/src/server.ts +512 -175
- package/packages/server/src/services/cli-service.ts +59 -10
- package/packages/server/src/services/secrets-resolver.ts +46 -30
- package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
- package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
- package/packages/server/src/session/death-reason.ts +11 -7
- package/packages/server/src/session/event-status-extraction.ts +5 -1
- package/packages/server/src/session/memory-session-manager.ts +24 -2
- package/packages/server/src/session/open-tool-calls.ts +81 -47
- package/packages/server/src/session/pid-target.ts +127 -0
- package/packages/server/src/session/replay-compaction.ts +18 -5
- package/packages/server/src/session/seed-discovered-history.ts +85 -0
- package/packages/server/src/session/server-pid-context.ts +14 -0
- package/packages/server/src/session/session-api.ts +78 -29
- package/packages/server/src/session/session-archive.ts +7 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -54
- package/packages/server/src/session/session-load-worker-pool.ts +11 -1
- package/packages/server/src/session/session-load-worker.ts +22 -3
- package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
- package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
- package/packages/server/src/spawn-process/link-register.ts +42 -0
- package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
- package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
- package/packages/server/src/spawn-process/process-classifier.ts +8 -3
- package/packages/server/src/spawn-process/process-manager.ts +61 -6
- package/packages/server/src/spawn-process/restored-identity.ts +112 -0
- package/packages/server/src/spawn-process/session-terminator.ts +179 -18
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
- package/packages/server/src/sudo-credential/relay.ts +337 -0
- package/packages/server/src/terminal/terminal-gateway.ts +10 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
- package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
- package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
- package/packages/server/src/vault/vault-routes.ts +9 -2
- package/packages/server/src/vault/vault-store.ts +87 -24
- package/packages/server/vendor/xlsx/LICENSE +201 -0
- package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
- package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
- package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
- package/packages/shared/package.json +4 -2
- package/packages/shared/src/agent-credential-files.ts +32 -0
- package/packages/shared/src/browser-protocol.ts +137 -57
- package/packages/shared/src/canvas-detect.ts +1 -1
- package/packages/shared/src/canvas-types.ts +2 -2
- package/packages/shared/src/config.ts +73 -136
- package/packages/shared/src/containment-guard.ts +14 -4
- package/packages/shared/src/credential-encryption.ts +87 -0
- package/packages/shared/src/custom-event-groups.ts +2 -0
- package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
- package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
- package/packages/shared/src/device-key-proof.ts +309 -0
- package/packages/shared/src/event-forward-declaration.ts +85 -12
- package/packages/shared/src/forbidden-subjects.ts +126 -14
- package/packages/shared/src/heap-limits.ts +0 -30
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/index.ts +7 -6
- package/packages/shared/src/live-server.ts +20 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
- package/packages/shared/src/models-json-reader.ts +41 -0
- package/packages/shared/src/network-denial-signal.ts +15 -0
- package/packages/shared/src/node-version.ts +63 -60
- package/packages/shared/src/pairing-knock-client.ts +92 -8
- package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
- package/packages/shared/src/pi-path-compare.ts +31 -0
- package/packages/shared/src/pi-settings-schema.ts +52 -9
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
- package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
- package/packages/shared/src/pi-trust-mirror.ts +18 -8
- package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
- package/packages/shared/src/pid-namespace.ts +86 -0
- package/packages/shared/src/platform/native-ts-register.mjs +1 -1
- package/packages/shared/src/platform/process.ts +404 -1
- package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
- package/packages/shared/src/platform/spawn-runtime.ts +193 -7
- package/packages/shared/src/preview-egress.ts +56 -2
- package/packages/shared/src/preview-origins.ts +398 -0
- package/packages/shared/src/prompt-answer.ts +9 -5
- package/packages/shared/src/protocol.ts +147 -85
- package/packages/shared/src/provider-env-catalog.ts +413 -0
- package/packages/shared/src/provider-overrides.ts +112 -0
- package/packages/shared/src/question-types.ts +6 -0
- package/packages/shared/src/recommended-extensions.ts +79 -26
- package/packages/shared/src/renderer-by-ext.ts +5 -2
- package/packages/shared/src/rest-api.ts +93 -3
- package/packages/shared/src/role-schema.ts +24 -0
- package/packages/shared/src/route-tiers.ts +94 -3
- package/packages/shared/src/runtime-overlay/compat.ts +70 -6
- package/packages/shared/src/secret-patterns.ts +49 -0
- package/packages/shared/src/source-matching.ts +2 -2
- package/packages/shared/src/state-replay.ts +40 -24
- package/packages/shared/src/sudo-credential.ts +71 -0
- package/packages/shared/src/tool-path-resolve.ts +16 -1
- package/packages/shared/src/tool-registry/strategies.ts +1 -1
- package/packages/shared/src/tool-workdir.ts +56 -0
- package/packages/shared/src/trusted-types-mode.ts +72 -0
- package/packages/shared/src/types.ts +68 -109
- package/packages/shared/src/vertex-regions.ts +81 -0
- package/packages/shared/src/ws-message-tiers.ts +10 -3
- package/packages/extension/src/subagent-fanout-admission.ts +0 -234
- package/packages/extension/src/subagent-forward-sites.ts +0 -69
- package/packages/extension/src/subagent-frame-buffer.ts +0 -245
- package/packages/extension/src/subagent-frame-strip.ts +0 -109
- package/packages/extension/src/subagent-saturation.ts +0 -196
- package/packages/extension/src/subagent-tick-throttle.ts +0 -252
- package/packages/shared/src/anthropic-messages-source.ts +0 -8
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
|
@@ -8,7 +8,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, createPluginServiceRegistry, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginServerAllowed,
|
|
11
|
+
import { createGatedProviderAuth, createIsPiExtensionInstalled, createPluginServiceRegistry, createPluginSessionManager, createServerPluginContext, discoverPlugins, fixtureEntryAllowed, getFileValidatorPool, getFileValidatorRegistry, getPluginStatusStore, getWsRouteRegistry, loadServerEntries, pluginServerAllowed, redactPluginConfigForClient, refreshRequirementProbesFor, registerPluginAssetsRoute, resolvePluginEnabled, type ServerLoadDeps, setDeclaredBundledPluginIds } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
12
12
|
import {
|
|
13
13
|
createMcpClientConfigService,
|
|
14
14
|
createRealConfigIO,
|
|
@@ -21,6 +21,7 @@ import type { AuthConfig, DashboardConfig } from "@blackbelt-technology/pi-dashb
|
|
|
21
21
|
import { CONFIG_DIR, CONFIG_FILE, getPluginConfig as getPluginConfigFromFile, loadConfig, resolvePublicBaseUrls, writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
|
|
22
22
|
import { CustomEventGroupsStore } from "@blackbelt-technology/pi-dashboard-shared/custom-event-groups-store.js";
|
|
23
23
|
import { parseFileHandlerClaimKey } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/file-handler.js";
|
|
24
|
+
import { computeReplayEntryTypes } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/replay-entry-types.js";
|
|
24
25
|
import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
|
|
25
26
|
import type { HostAction, HostResource, Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
|
|
26
27
|
import { advertiseDashboard, createBrowser, type DashboardBrowser, type DiscoveredServer, resolveAdvertisedAddresses, stopAdvertising } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
|
|
@@ -51,7 +52,7 @@ import fastifyCookie from "@fastify/cookie";
|
|
|
51
52
|
import cors from "@fastify/cors";
|
|
52
53
|
import rateLimit from "@fastify/rate-limit";
|
|
53
54
|
import fastifyStatic from "@fastify/static";
|
|
54
|
-
import Fastify, { type FastifyReply, type FastifyRequest } from "fastify";
|
|
55
|
+
import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
|
|
55
56
|
import { listGrants as listAccessGrants, setGrantsChangedListener, setSessionGrantsChangedListener } from "./access/access-grants.js";
|
|
56
57
|
import { snapshotAccessGrantHealth } from "./access/access-health.js";
|
|
57
58
|
import { AccessPlaneRegistry, isGrantPromptKilled } from "./access/access-plane.js";
|
|
@@ -75,7 +76,9 @@ import { YOLO_ENV } from "./access/yolo-env.js";
|
|
|
75
76
|
import { YoloController } from "./access/yolo-session.js";
|
|
76
77
|
import { scanAcpSessions } from "./acp-bridge/acp-restore.js";
|
|
77
78
|
import { stopAllLocalAcpSessions } from "./acp-bridge/local-host.js";
|
|
79
|
+
import { createAgentEventHub } from "./agent-events/agent-event-hub.js";
|
|
78
80
|
import { createFitWorkerPool } from "./attachments/fit-worker-pool.js";
|
|
81
|
+
import { auditPrefix } from "./auth/audit-log.js";
|
|
79
82
|
import { resolveRedirectBase } from "./auth/auth.js";
|
|
80
83
|
import { authorizeWsUpgrade, buildLoginAvailable, effectiveSessionTier, registerAuthPlugin } from "./auth/auth-plugin.js";
|
|
81
84
|
import { registerBearerAuth, registerDeviceSessionRoutes } from "./auth/bearer-auth.js";
|
|
@@ -85,7 +88,7 @@ import {
|
|
|
85
88
|
formatBindReachabilityWarning,
|
|
86
89
|
initBindReachability,
|
|
87
90
|
} from "./auth/bind-reachability-service.js";
|
|
88
|
-
import { decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
91
|
+
import { createTicketRefusalLog, decideBridgeTicketMint } from "./auth/bridge-ticket-eligibility.js";
|
|
89
92
|
import {
|
|
90
93
|
CORS_ALLOWED_METHODS,
|
|
91
94
|
type CorsOriginOptions,
|
|
@@ -94,11 +97,14 @@ import {
|
|
|
94
97
|
isWsOriginTrusted,
|
|
95
98
|
sanitizeHeaderForLog,
|
|
96
99
|
} from "./auth/cors-origin.js";
|
|
100
|
+
import { getCredentialCodec, type InitCredentialKeyOptions, initCredentialKey } from "./auth/credential-key.js";
|
|
101
|
+
import { migrateCredentialFiles } from "./auth/credential-migration.js";
|
|
97
102
|
import { cspNonceFor, markViteProxied, registerCsp, resolveCspMode, resolveTrustedTypesMode } from "./auth/csp.js";
|
|
98
103
|
import { registerCspReportSink } from "./auth/csp-report-sink.js";
|
|
99
104
|
import { CspReportStore } from "./auth/csp-report-store.js";
|
|
100
105
|
import { stateCallerFor } from "./auth/dashboard-state-caller.js";
|
|
101
|
-
import {
|
|
106
|
+
import { createDuplicateCookieGate, refuseDuplicateCookieUpgrade } from "./auth/duplicate-cookie-gate.js";
|
|
107
|
+
import { classifyAdmittedHostname, isHostAdmitted } from "./auth/host-admission.js";
|
|
102
108
|
import {
|
|
103
109
|
createHostGate,
|
|
104
110
|
evaluateHostGate,
|
|
@@ -117,6 +123,7 @@ import {
|
|
|
117
123
|
createLanInterfaceProvider,
|
|
118
124
|
createNetworkGuard,
|
|
119
125
|
createNetworkGuardHook,
|
|
126
|
+
evaluateNetworkPass,
|
|
120
127
|
isLocallyTrusted,
|
|
121
128
|
isPluginScopePeerLocal,
|
|
122
129
|
needsLocalProof,
|
|
@@ -133,8 +140,9 @@ import { UserDirectory } from "./auth/passkey/user-directory.js";
|
|
|
133
140
|
import type { OAuthLoginFlow } from "./auth/pi-oauth-types.js";
|
|
134
141
|
import { createPluginCredentialStore } from "./auth/plugin-credential-store.js";
|
|
135
142
|
import { isServerTrusted } from "./auth/plugin-server-trust.js";
|
|
143
|
+
import { bearerChannelOf, isProvenTls } from "./auth/proven-tls.js";
|
|
136
144
|
import { setOAuthRegistryRuntimeSource } from "./auth/provider-auth-registry.js";
|
|
137
|
-
import { readAuthJson } from "./auth/provider-auth-storage.js";
|
|
145
|
+
import { hasAnthropicCredential, readAuthJson } from "./auth/provider-auth-storage.js";
|
|
138
146
|
import { countReloads, type RadiusMcpService } from "./auth/radius-mcp.js";
|
|
139
147
|
import { createRouteTierGate } from "./auth/route-tier-gate.js";
|
|
140
148
|
import { RotationError, rotateSecretsOnce } from "./auth/secret-rotation.js";
|
|
@@ -160,9 +168,11 @@ import {
|
|
|
160
168
|
respawnForRuntimeSwap,
|
|
161
169
|
} from "./browser-handlers/session-action-handler.js";
|
|
162
170
|
import { runLifecycleAction } from "./browser-handlers/session-lifecycle.js";
|
|
171
|
+
import { buildPluginSendPrompt } from "./build-plugin-send-prompt.js";
|
|
163
172
|
import { createCommitDraftRelay } from "./commit-draft-relay.js";
|
|
164
173
|
import { readRawConfig, seedWindowsSourceSettings, writeConfigPartial } from "./config-api.js";
|
|
165
174
|
import {
|
|
175
|
+
getResolvedPreviewOrigins,
|
|
166
176
|
liveAcceptLanRequests,
|
|
167
177
|
liveAllowedHosts,
|
|
168
178
|
liveCorsAllowedOrigins,
|
|
@@ -173,6 +183,7 @@ import {
|
|
|
173
183
|
liveRequireLocalProof,
|
|
174
184
|
liveTrustedNetworks,
|
|
175
185
|
rawConfigHasHostGateMode,
|
|
186
|
+
setPreviewOriginsRuntime,
|
|
176
187
|
} from "./config-snapshot.js";
|
|
177
188
|
// pending-load-manager removed — server loads sessions directly via DirectoryService
|
|
178
189
|
import { createDirectoryService, type DirectoryService } from "./directory-service.js";
|
|
@@ -180,7 +191,9 @@ import { createEmbedLifecycleController } from "./embed-lifecycle/embed-lifecycl
|
|
|
180
191
|
import { createPluginSessionCloseApi, createSessionCloserRegistry } from "./embed-lifecycle/plugin-session-close.js";
|
|
181
192
|
import { wireEvents } from "./event-wiring.js";
|
|
182
193
|
import { createFileWatchManager } from "./file-watch-manager.js";
|
|
194
|
+
import { ensureWorktree } from "./git-worktree/ensure-worktree.js";
|
|
183
195
|
import { resolveMainPath } from "./git-worktree/git-operations.js";
|
|
196
|
+
import { awaitInitRun, startWorktreeInit } from "./git-worktree/start-worktree-init.js";
|
|
184
197
|
import { createWorktreeInitRegistry } from "./git-worktree/worktree-init-registry.js";
|
|
185
198
|
import {
|
|
186
199
|
listPersistedTrust as listPersistedWorktreeTrust,
|
|
@@ -216,12 +229,14 @@ import {
|
|
|
216
229
|
readServedBundledPluginIds,
|
|
217
230
|
resolveStaticClientDir,
|
|
218
231
|
} from "./lib/client-dist.js";
|
|
219
|
-
import { runWithStateCaller } from "./lib/dashboard-state-guard.js";
|
|
232
|
+
import { readFileGuarded as guardedReadFile, runWithStateCaller } from "./lib/dashboard-state-guard.js";
|
|
220
233
|
import { collectRuleSources } from "./lib/folder-project.js";
|
|
234
|
+
import { resolveFramePolicyTestSeam } from "./lib/frame-policy-test-seam.js";
|
|
221
235
|
import { createIndexHtmlSender } from "./lib/index-html.js";
|
|
222
236
|
import { listKnownFolderCwds, type RouteAdmissionDeps } from "./lib/route-admission.js";
|
|
223
237
|
import { bootParentPid, isBootParentProvablyDead } from "./lifecycle/boot-parent-liveness.js";
|
|
224
238
|
import { runBoundedStartup } from "./lifecycle/bounded-startup.js";
|
|
239
|
+
import { exitBarrier } from "./lifecycle/credential-exit-barrier.js";
|
|
225
240
|
import { startEphemeralParentWatch } from "./lifecycle/ephemeral-parent-watch.js";
|
|
226
241
|
import { ensureInstanceId } from "./lifecycle/instance-id.js";
|
|
227
242
|
import {
|
|
@@ -234,8 +249,18 @@ import {
|
|
|
234
249
|
import { createReservedHandler } from "./live-server/live-csp-report.js";
|
|
235
250
|
import { createEgressGrantRequester, createPreviewEgress, requestOriginsOf } from "./live-server/live-egress.js";
|
|
236
251
|
import { createPreviewExposure, wirePreviewExposure } from "./live-server/live-exposure.js";
|
|
252
|
+
import { liveLog } from "./live-server/live-log.js";
|
|
237
253
|
import { createLiveServerManager } from "./live-server/live-server-manager.js";
|
|
238
|
-
import { handleLiveServerUpgrade, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
254
|
+
import { handleLiveServerUpgrade, type LiveProxyDeps, registerLiveServerProxy } from "./live-server/live-server-proxy.js";
|
|
255
|
+
import { createPreviewDispatch, type PreviewDispatch, previewServerFactory, routePreviewUpgrade } from "./live-server/preview-dispatch.js";
|
|
256
|
+
import { createPreviewObserver, type PreviewObserver } from "./live-server/preview-observe.js";
|
|
257
|
+
import { isPreviewShapedOriginUrl, previewLogHash } from "./live-server/preview-origin.js";
|
|
258
|
+
import { parsePreviewPath } from "./live-server/preview-path.js";
|
|
259
|
+
import { PreviewPathStore } from "./live-server/preview-path-store.js";
|
|
260
|
+
import { createPreviewPool, type PreviewPool } from "./live-server/preview-pool.js";
|
|
261
|
+
import { createPreviewPreflight } from "./live-server/preview-preflight.js";
|
|
262
|
+
import { hasTier5Viewer, stampPreviewViewer } from "./live-server/preview-viewers.js";
|
|
263
|
+
import { createPreviewWsRegistry } from "./live-server/preview-ws-registry.js";
|
|
239
264
|
import { startEventLoopSampler } from "./metrics/eventloop-sampler.js";
|
|
240
265
|
import { createEventLoopSpikeMetrics } from "./metrics/eventloop-spike-metrics.js";
|
|
241
266
|
import { createHydrationMetrics } from "./metrics/hydration-metrics.js";
|
|
@@ -248,54 +273,59 @@ import { createOpenSpecGroupStore, joinGroupIdsToOpenSpecData } from "./openspec
|
|
|
248
273
|
import { fetchPackageMeta } from "./package/npm-search-proxy.js";
|
|
249
274
|
import { logPackageHealthAtBoot } from "./package/package-health-scanner.js";
|
|
250
275
|
import { type OperationResult, PackageManagerWrapper } from "./package/package-manager-wrapper.js";
|
|
276
|
+
import { setProbeSelfPort } from "./package/provider-probe.js";
|
|
251
277
|
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
278
|
import { createDeviceTokenServices } from "./pairing/device-token-services.js";
|
|
255
|
-
import {
|
|
256
|
-
import { startDeviceExpirySweep } from "./vault/device-expiry-sweep.js";
|
|
279
|
+
import { createRequestAccessAvailable, type KnockPeerDeps } from "./pairing/knock-admission.js";
|
|
257
280
|
import { PairedDeviceRegistry } from "./pairing/paired-devices.js";
|
|
258
281
|
import { PairingManager, wirePendingHint } from "./pairing/pairing.js";
|
|
259
282
|
import { stampSocketLocality } from "./pairing/socket-locality.js";
|
|
260
|
-
import type
|
|
283
|
+
import { closeDeviceSockets, sweepRevokedSockets, type TieredSocket } from "./pairing/ws-tier-gate.js";
|
|
261
284
|
import { buildSelfServer, wirePeerServers } from "./peer-servers.js";
|
|
262
285
|
import { createPendingArchiveIntentRegistry } from "./pending/pending-archive-intent-registry.js";
|
|
263
286
|
import { createPendingAttachRegistry } from "./pending/pending-attach-registry.js";
|
|
264
287
|
import { createPendingClientCorrelations } from "./pending/pending-client-correlations.js";
|
|
265
288
|
import { createPendingForkRegistry } from "./pending/pending-fork-registry.js";
|
|
266
|
-
import { createPendingInitialPromptRegistry } from "./pending/pending-initial-prompt-registry.js";
|
|
289
|
+
import { createPendingInitialPromptRegistry, type PendingInitialPromptRegistry } from "./pending/pending-initial-prompt-registry.js";
|
|
267
290
|
import { createPendingPluginRefRegistry } from "./pending/pending-plugin-ref-registry.js";
|
|
268
291
|
import { createPendingPrincipalOwnerRegistry } from "./pending/pending-principal-owner-registry.js";
|
|
269
292
|
import { createPendingPromptAcks } from "./pending/pending-prompt-acks.js";
|
|
270
293
|
import { createPendingResumeIntentRegistry } from "./pending/pending-resume-intent-registry.js";
|
|
271
294
|
import { createPendingWorktreeBaseRegistry } from "./pending/pending-worktree-base-registry.js";
|
|
272
295
|
import { recordExitIntent, resolveExitIntent, resolveExitRecord, stampBootStart } from "./persistence/boot-state.js";
|
|
296
|
+
import { createPluginEventAppender } from "./plugin-append-event.js";
|
|
297
|
+
import { buildPluginOwnership, createPluginOwnership } from "./plugin-ownership.js";
|
|
298
|
+
import { getPluginPolicyRegistry } from "./plugin-policy-registry.js";
|
|
273
299
|
import { createMemoryEventStore, DEFAULT_MAX_EVENT_DATA_SIZE, DEFAULT_MAX_STRING_SIZE, type EventStore } from "./persistence/memory-event-store.js";
|
|
274
300
|
import { createMetaPersistence } from "./persistence/meta-persistence.js";
|
|
275
301
|
import { migrateCustomEntryFallbackOverrides } from "./persistence/migrate-custom-entry-fallback.js";
|
|
276
302
|
import { needsMigration, runMigration } from "./persistence/migrate-persistence.js";
|
|
277
303
|
import { createPreferencesStore } from "./persistence/preferences-store.js";
|
|
304
|
+
import { CONTENTION_RATE_LIMIT } from "./pi/bridge-contention.js";
|
|
278
305
|
import { loadHostProjectTrustService } from "./pi/host-project-trust.js";
|
|
279
306
|
import { PiCoreChecker } from "./pi/pi-core-checker.js";
|
|
280
307
|
import { PiCoreUpdater } from "./pi/pi-core-updater.js";
|
|
281
|
-
import { createPiGateway } from "./pi/pi-gateway.js";
|
|
308
|
+
import { createPiGateway, type GatewayConn } from "./pi/pi-gateway.js";
|
|
282
309
|
import { listGlobalSkills } from "./pi/pi-resource-scanner.js";
|
|
310
|
+
import { createPiDefaultRemirror, setActivePiDefaultRemirror } from "./pi-default-remirror.js";
|
|
283
311
|
import { createPackageCompletionHandler, createPluginDiscoveryWiring, type PluginDiscoveryWiring } from "./plugin-discovery-wiring.js";
|
|
312
|
+
import { getReplayEntryTypes, recordRejectedPluginAction, setReplayEntryTypesProvider } from "./plugin-entry-stats.js";
|
|
284
313
|
import * as pluginEventSeam from "./plugin-event-seam.js";
|
|
285
314
|
import { pluginIntentCache } from "./plugin-intent-cache.js";
|
|
315
|
+
import { createHostLocalRequest, HOST_LOCAL_REQUEST_KEY } from "./plugin-local-request.js";
|
|
286
316
|
import { createPluginRequestLane } from "./plugin-request-lane.js";
|
|
287
317
|
import { getRuntimeClientRegistry, installRuntimeClientRegistry, logRuntimeAdmissions } from "./plugin-runtime-clients.js";
|
|
318
|
+
import { configureProjectSeed, resolveAutoSeedEnabled, sweepKnownProjects } from "./project-seed.js";
|
|
288
319
|
import { createPushService, type PushService } from "./push/push-service.js";
|
|
289
320
|
import type { SessionPresence } from "./questions/question-files.js";
|
|
290
321
|
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
322
|
import { createQuestionStack, persistedPresence } from "./questions/question-stack.js";
|
|
294
323
|
import { registerAccessPromptRoutes } from "./routes/access-prompt-routes.js";
|
|
295
324
|
import { registerAccessRoutes } from "./routes/access-routes.js";
|
|
296
325
|
import { registerAcmeRoutes } from "./routes/acme-routes.js";
|
|
297
326
|
import { registerAcpRoutes } from "./routes/acp-routes.js";
|
|
298
327
|
import { registerAddonsRoutes } from "./routes/addons-routes.js";
|
|
328
|
+
import { registerAgentEventStreamRoutes } from "./routes/agent-event-stream-routes.js";
|
|
299
329
|
import { registerAttachmentRoutes } from "./routes/attachment-routes.js";
|
|
300
330
|
import { registerCanvasTypesRoutes } from "./routes/canvas-types-routes.js";
|
|
301
331
|
import { registerCspViolationRoutes } from "./routes/csp-violations-routes.js";
|
|
@@ -303,6 +333,7 @@ import { registerCustomEventGroupsRoutes } from "./routes/custom-event-groups-ro
|
|
|
303
333
|
import { registerDoctorRoutes } from "./routes/doctor-routes.js";
|
|
304
334
|
import { denialBody, gateFilePath, registerFileRoutes } from "./routes/file-routes.js";
|
|
305
335
|
import { registerFolderProjectRoutes } from "./routes/folder-project-routes.js";
|
|
336
|
+
import { registerFramePolicyRoutes } from "./routes/frame-policy-routes.js";
|
|
306
337
|
import { registerGitRoutes } from "./routes/git-routes.js";
|
|
307
338
|
import { registerGrepRoutes } from "./routes/grep-routes.js";
|
|
308
339
|
import { registerHostGateRoutes } from "./routes/host-gate-routes.js";
|
|
@@ -333,9 +364,11 @@ import { registerPluginActivationRoutes, setPluginsEnabled } from "./routes/plug
|
|
|
333
364
|
import { registerPluginConfigRoutes } from "./routes/plugin-config-routes.js";
|
|
334
365
|
import { registerPluginRuntimeClientRoutes } from "./routes/plugin-runtime-client-routes.js";
|
|
335
366
|
import { registerPreferencesAutoNameRoutes } from "./routes/preferences-auto-name-routes.js";
|
|
367
|
+
import { registerPreferencesClaudeCompatRoutes } from "./routes/preferences-claude-compat-routes.js";
|
|
336
368
|
import { registerPreferencesDisplayRoutes } from "./routes/preferences-display-routes.js";
|
|
337
369
|
import { registerPreferencesWorktreeInitRoutes } from "./routes/preferences-worktree-init-routes.js";
|
|
338
370
|
import { registerProviderAuthRoutes } from "./routes/provider-auth-routes.js";
|
|
371
|
+
import { registerProviderOverrideRoutes } from "./routes/provider-override-routes.js";
|
|
339
372
|
import { registerProviderRoutes } from "./routes/provider-routes.js";
|
|
340
373
|
import { registerPushRoutes } from "./routes/push-routes.js";
|
|
341
374
|
import { invalidateRecommendedCache, registerRecommendedRoutes } from "./routes/recommended-routes.js";
|
|
@@ -386,16 +419,19 @@ import { setLocalAcpHost, spawnAcpSession, validatePluginAcpSpawn } from "./spaw
|
|
|
386
419
|
import { CwdPolicyRegistry } from "./spawn-process/cwd-policy.js";
|
|
387
420
|
import { keeperOptsFromSpawnResult } from "./spawn-process/headless-pid-registry.js";
|
|
388
421
|
import { createIdleTimer } from "./spawn-process/idle-timer.js";
|
|
422
|
+
import { createPluginSpawnHook } from "./spawn-process/plugin-spawn-worktree.js";
|
|
389
423
|
import { getKeeperManager, setCwdPolicyRegistry, spawnPiSession } from "./spawn-process/process-manager.js";
|
|
390
424
|
import { removePid, writePid } from "./spawn-process/server-pid.js";
|
|
391
425
|
import { createSessionTerminator } from "./spawn-process/session-terminator.js";
|
|
392
426
|
import { registerSpawnEnvContributorForPlugin, setSpawnEnvPluginEnabledCheck } from "./spawn-process/spawn-env-contributors.js";
|
|
393
427
|
import { armSpawnWatchdog } from "./spawn-process/spawn-register-watchdog.js";
|
|
428
|
+
import { createSudoCredentialRelay } from "./sudo-credential/relay.js";
|
|
394
429
|
import { createTerminalGateway } from "./terminal/terminal-gateway.js";
|
|
395
430
|
import { createTerminalManager, deriveTranscriptCapBytes } from "./terminal/terminal-manager.js";
|
|
396
431
|
import { createAcmeCredentials } from "./tls/sources/acme/credentials.js";
|
|
397
432
|
import { acmeGc } from "./tls/sources/acme/gc.js";
|
|
398
433
|
import { configureAcmeRuntime } from "./tls/sources/acme/runtime.js";
|
|
434
|
+
import { onTlsBridgeSwitchChanged, routeBridgeUpgrade } from "./tls/tls-bridge-route.js";
|
|
399
435
|
import {
|
|
400
436
|
MAIN_CONNECTION_TIMEOUT_MS,
|
|
401
437
|
MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
@@ -404,6 +440,7 @@ import {
|
|
|
404
440
|
import { cleanupStaleZrok, createTunnel, deleteTunnel, detectZrokBinary, ensureReservedName, getTunnelUrl, liveTunnelOrigins, scavengeOrphanZrokProcesses } from "./tunnel/tunnel.js";
|
|
405
441
|
import { collectEndpoints } from "./tunnel/tunnel-endpoints.js";
|
|
406
442
|
import { startTunnelWatchdog, stopTunnelWatchdog } from "./tunnel/tunnel-watchdog.js";
|
|
443
|
+
import { startDeviceExpirySweep } from "./vault/device-expiry-sweep.js";
|
|
407
444
|
import { createVaultDeliveryHub } from "./vault/vault-delivery-hub.js";
|
|
408
445
|
import { createVaultImport, defaultKnownLocations } from "./vault/vault-import.js";
|
|
409
446
|
import { createPluginVaultReader } from "./vault/vault-plugin-read.js";
|
|
@@ -413,6 +450,12 @@ import { createVaultStore } from "./vault/vault-store.js";
|
|
|
413
450
|
import { createWatchFilesHandler, type WatchFilesMessage } from "./watch-files-handler.js";
|
|
414
451
|
|
|
415
452
|
export interface ServerConfig {
|
|
453
|
+
/**
|
|
454
|
+
* Test seam for the credential data key (key file env, stub keychain, log sink, home dir).
|
|
455
|
+
* Production leaves it unset: `initCredentialKey()` then reads `process.env` and the real home.
|
|
456
|
+
* See change: encrypt-credentials-at-rest (D4, D9).
|
|
457
|
+
*/
|
|
458
|
+
credentialKey?: InitCredentialKeyOptions;
|
|
416
459
|
port: number;
|
|
417
460
|
piPort: number;
|
|
418
461
|
/**
|
|
@@ -552,6 +595,8 @@ export interface DashboardServer {
|
|
|
552
595
|
browserGateway: BrowserGateway;
|
|
553
596
|
/** Resolved HTTP port after start() (useful for port:0 in tests). Returns null if not listening. */
|
|
554
597
|
httpPort(): number | null;
|
|
598
|
+
/** @internal Tests only: `fastify.inject` on the wired app, so a test can present a non-loopback peer (`remoteAddress`). See change: surface-network-denial-on-health. */
|
|
599
|
+
inject: FastifyInstance["inject"];
|
|
555
600
|
/** The optional TLS listener (off by default). See change: add-tailscale-cert-tls. */
|
|
556
601
|
readonly tls: TlsListener;
|
|
557
602
|
/** Resolved pi gateway port after start(). Returns null if not listening. */
|
|
@@ -564,6 +609,13 @@ export interface DashboardServer {
|
|
|
564
609
|
* See change: fix-dashboard-spawn-correlation-by-token.
|
|
565
610
|
*/
|
|
566
611
|
pendingDashboardSpawns: Map<string, number>;
|
|
612
|
+
/**
|
|
613
|
+
* Pending initial-prompt intents per cwd. Exposed for in-process tests that
|
|
614
|
+
* pin register-time ordering (preferences snapshot before `send_prompt`).
|
|
615
|
+
* Not part of the public API — do not depend on this from production code.
|
|
616
|
+
* See change: retire-anthropic-messages-bridge.
|
|
617
|
+
*/
|
|
618
|
+
pendingInitialPromptRegistry: PendingInitialPromptRegistry;
|
|
567
619
|
/**
|
|
568
620
|
* In-process OpenSpec poll cache + discovery service. Exposed for tests
|
|
569
621
|
* that need to stub `getOpenSpecData` (e.g. the deleted-proposal bypass).
|
|
@@ -634,6 +686,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
634
686
|
// the server listens (so no operator write can race it). Never re-derived
|
|
635
687
|
// from the list afterwards. See change: retire-trusted-networks-bypass (D2).
|
|
636
688
|
decideBootTrustMode();
|
|
689
|
+
// The exit barrier is a module singleton: a new server must never inherit a
|
|
690
|
+
// gate closed by a previous create/stop cycle in this process (tests, embeds).
|
|
691
|
+
// Cycles are strictly sequential. See change: settle-server-credential-writes-on-exit.
|
|
692
|
+
exitBarrier.reopen();
|
|
637
693
|
// One-shot rotation of the local token + auth secret that a bare-loopback caller
|
|
638
694
|
// may already have read through the `~/.pi` anchor. Must precede every read of
|
|
639
695
|
// either value (the token below, `config.authConfig.secret`). Failure is closed:
|
|
@@ -651,6 +707,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
651
707
|
}
|
|
652
708
|
throw err;
|
|
653
709
|
}
|
|
710
|
+
// Resolve the credential data key BEFORE anything builds or reads a credential store
|
|
711
|
+
// (vault, ACME runtime, plugin load) and before `listen`, then migrate plaintext
|
|
712
|
+
// credential files to envelopes. One 10 s total deadline bounds init; a keychain failure
|
|
713
|
+
// only leaves the stores locked, it never stops the server from booting. Neither call throws.
|
|
714
|
+
// See change: encrypt-credentials-at-rest (D4, D7, D11).
|
|
715
|
+
await initCredentialKey(config.credentialKey);
|
|
716
|
+
await migrateCredentialFiles({ home: config.credentialKey?.homeDir, log: config.credentialKey?.log });
|
|
654
717
|
// Ensure bridge extension is registered in pi's global settings
|
|
655
718
|
// (needed for bundled installs where pi can't discover it from package.json)
|
|
656
719
|
//
|
|
@@ -694,6 +757,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
694
757
|
const customEventGroupResolver = new CustomEventGroupResolver(
|
|
695
758
|
customEventGroupsStore.list(),
|
|
696
759
|
customEventGroupMatcher,
|
|
760
|
+
// Plugin-declared entry types are never grouped. See change: update-flows-plugin (D3).
|
|
761
|
+
{ isPluginEntryType: (t) => getReplayEntryTypes().hidden.includes(t) },
|
|
697
762
|
);
|
|
698
763
|
|
|
699
764
|
migrateCustomEntryFallbackOverrides(undefined, undefined, Object.fromEntries(
|
|
@@ -708,6 +773,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
708
773
|
customEventGroupDefaults: Object.fromEntries(
|
|
709
774
|
customEventGroupsStore.definitions().map((g) => [g.id, g.default]),
|
|
710
775
|
),
|
|
776
|
+
// One-time compat-switch seed for upgraders with an anthropic sign-in.
|
|
777
|
+
// See change: seed-claude-compat-on-upgrade (design D2).
|
|
778
|
+
hasAnthropicCredential,
|
|
711
779
|
});
|
|
712
780
|
// Single cwd-policy registry (Part B — host-cwd-policy). Recognized workspace
|
|
713
781
|
// roots = pinned directories + every folder in a folder-workspace, evaluated
|
|
@@ -721,6 +789,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
721
789
|
],
|
|
722
790
|
});
|
|
723
791
|
setCwdPolicyRegistry(cwdPolicyRegistry);
|
|
792
|
+
// Auto-seed pi project defaults (change: auto-seed-project-defaults). The
|
|
793
|
+
// boot sweep covers folders the dashboard ALREADY knows about — pinned dirs +
|
|
794
|
+
// workspace folders, the same set `recognizedRoots` spans; folders learned
|
|
795
|
+
// later are covered by the pin handler and bridge registration. Each dir is
|
|
796
|
+
// deferred onto its own tick, so a large pin list never stalls startup.
|
|
797
|
+
configureProjectSeed(resolveAutoSeedEnabled(loadConfig(), CONFIG_FILE));
|
|
798
|
+
sweepKnownProjects([
|
|
799
|
+
...preferencesStore.getPinnedDirectories(),
|
|
800
|
+
...preferencesStore.getWorkspaces().flatMap((w) => w.folders),
|
|
801
|
+
]);
|
|
724
802
|
// Server identity + device pairing (D2/D5/D6). Additive; independent of OAuth.
|
|
725
803
|
const serverIdentity = ensureServerIdentity();
|
|
726
804
|
const pairedDeviceRegistry = new PairedDeviceRegistry();
|
|
@@ -782,6 +860,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
782
860
|
// every genuinely-local admission site. See change: harden-trust-and-credential-boundaries (D2).
|
|
783
861
|
// The proof cookie is bound to the listener's port; `0` until `listen` runs (inject() in tests).
|
|
784
862
|
let httpListenPort = 0;
|
|
863
|
+
/** Rate-limited (per device) below-operate bridge-ticket refusal line (D2). */
|
|
864
|
+
const logTicketRefusal = createTicketRefusalLog({ windowMs: CONTENTION_RATE_LIMIT, prefix: (id) => auditPrefix(id) });
|
|
785
865
|
const localTrust = createLocalTrustContext(localToken, liveRequireLocalProof, () => httpListenPort);
|
|
786
866
|
const localProofCodes = new LocalProofCodeStore();
|
|
787
867
|
const pairingManager = new PairingManager({
|
|
@@ -859,6 +939,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
859
939
|
// so `worktree_init_*` events stream only to the dialog that
|
|
860
940
|
// initiated the run. See change: generalize-worktree-init-hook.
|
|
861
941
|
const worktreeInitRegistry = createWorktreeInitRegistry();
|
|
942
|
+
// Latched at the top of `stop()`: the plugin spawn hook refuses a launch that resumes after it
|
|
943
|
+
// (its child would escape the shutdown sweeps). See change: add-plugin-spawn-worktree.
|
|
944
|
+
let serverStopping = false;
|
|
862
945
|
|
|
863
946
|
// Restore sessions from per-session .meta.json files (scans ~/.pi/agent/sessions/)
|
|
864
947
|
const scanStartedAt = Date.now();
|
|
@@ -1006,7 +1089,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1006
1089
|
// (heartbeat tail, click-induced state sync, late bridge events) do
|
|
1007
1090
|
// NOT re-fire it.
|
|
1008
1091
|
// See changes: pin-and-search-sessions, simplify-session-card-ordering.
|
|
1009
|
-
|
|
1092
|
+
// `priorStatus === "ended"` covers an ended record `restore()`d after the
|
|
1093
|
+
// boot snapshot (on-demand discovery seed, unarchive, late boot seed),
|
|
1094
|
+
// which the set never saw. See change: fix-discovery-resurrects-archived.
|
|
1095
|
+
const wasEnded = endedSessionIds.has(sessionId) || ctx?.priorStatus === "ended";
|
|
1010
1096
|
const isEnded = session.status === "ended";
|
|
1011
1097
|
if (isEnded && !wasEnded) {
|
|
1012
1098
|
// Just transitioned alive→ended. The id STAYS in the order map
|
|
@@ -1108,9 +1194,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1108
1194
|
}
|
|
1109
1195
|
}
|
|
1110
1196
|
};
|
|
1111
|
-
//
|
|
1112
|
-
//
|
|
1113
|
-
//
|
|
1197
|
+
// Ids seen as ended: the boot snapshot plus every alive→ended `onChange`,
|
|
1198
|
+
// so the hook can tell a real alive→ended transition from a re-emit of the
|
|
1199
|
+
// ended state. Ended records `restore()`d after this snapshot are NOT in
|
|
1200
|
+
// it; their ended→alive register is detected via `ctx.priorStatus`.
|
|
1201
|
+
// See change: fix-discovery-resurrects-archived.
|
|
1114
1202
|
const endedSessionIds = new Set<string>(
|
|
1115
1203
|
sessionManager.listAll().filter((s) => s.status === "ended").map((s) => s.id),
|
|
1116
1204
|
);
|
|
@@ -1417,10 +1505,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1417
1505
|
// Live-server-preview manager (loopback dev-server allowlist + proxy).
|
|
1418
1506
|
// Ports the dashboard itself listens on are never previewable (a loopback origin is trusted
|
|
1419
1507
|
// by its CORS / mutation gates). See change: improve-canvas-html-and-url-ux (D1).
|
|
1508
|
+
// Tier 3 pool (D5) + the proxy deps it forwards through: both late-bound (the manager's `ownPorts` reads the pool at seed time).
|
|
1509
|
+
let previewPool: PreviewPool | undefined;
|
|
1510
|
+
// Late-bound like `previewPool`: the observer is built with the dispatcher, after the store whose `onDelete` feeds it.
|
|
1511
|
+
let previewObserver: PreviewObserver | undefined;
|
|
1512
|
+
let liveProxyDepsRef: LiveProxyDeps | undefined;
|
|
1420
1513
|
const liveServerManager = createLiveServerManager(preferencesStore, {
|
|
1421
1514
|
ownPorts: () => {
|
|
1422
1515
|
const tls = loadConfig().tls;
|
|
1423
|
-
|
|
1516
|
+
// Pool ports (tier 3) are the dashboard's own: no target may point at one (D5).
|
|
1517
|
+
return [config.port, config.piPort, ...(tls?.enabled ? [tls.port] : []), ...(previewPool?.poolPorts() ?? [])];
|
|
1424
1518
|
},
|
|
1425
1519
|
});
|
|
1426
1520
|
|
|
@@ -1454,6 +1548,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1454
1548
|
|
|
1455
1549
|
const replayState = createReplayState(config.replayTimings);
|
|
1456
1550
|
const browserGateway = createBrowserGateway(sessionManager, eventStore, piGateway, undefined, pendingForkRegistry, sessionOrderManager, preferencesStore, directoryService, terminalManager, pendingDashboardSpawns, config.maxWsBufferBytes, pendingAttachRegistry, pendingInitialPromptRegistry, pendingResumeIntents, pendingClientCorrelations, pendingWorktreeBaseRegistry, metaPersistence, fitWorkerPool, config.maxReplayEvents, config.replayWindowMode, sessionArchive, pendingArchiveIntents, remoteTranscriptStore, pendingPrincipalOwnerRegistry, identityEnforced, undefined, questionStore, browseRoots, replayState);
|
|
1551
|
+
// A revoke closes every open socket of that device (4401 / `device revoked`): browser sockets (tagged at
|
|
1552
|
+
// upgrade from the ticket) and bridge sockets. See change: device-key-mutual-check (D7).
|
|
1553
|
+
pairedDeviceRegistry.onRevoked((deviceId) => {
|
|
1554
|
+
const closed = closeDeviceSockets(browserGateway.wss.clients, deviceId) + piGateway.closeDeviceSockets(deviceId);
|
|
1555
|
+
if (closed > 0) console.log(`[ws-gate] device revoke closed ${closed} socket(s)`);
|
|
1556
|
+
});
|
|
1457
1557
|
// Transition-only feed behind `GET /api/events/stream` (registry frames + question changes).
|
|
1458
1558
|
// See change: add-agent-event-stream.
|
|
1459
1559
|
const agentEventHub = createAgentEventHub({
|
|
@@ -1600,6 +1700,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1600
1700
|
// death signal, even when no terminal pi event was forwarded.
|
|
1601
1701
|
// See change: finalize-automation-run-on-session-death.
|
|
1602
1702
|
const pluginSessionEndSubs = new Set<(sessionId: string) => void>();
|
|
1703
|
+
// Plugin status-ended subscribers (ServerPluginContext.onSessionStatusEnded). Fired
|
|
1704
|
+
// from sessionManager.onEnded via wireEvents on EVERY end transition (unregister,
|
|
1705
|
+
// status set to ended, end-reason re-fire; not a relocation). Handlers are idempotent.
|
|
1706
|
+
// See change: move-subagents-to-plugin (D4).
|
|
1707
|
+
const pluginSessionStatusEndSubs = new Set<(sessionId: string) => void>();
|
|
1603
1708
|
// Post-boot plugin discovery (refreshPluginDiscovery + local-scope detection); built right
|
|
1604
1709
|
// after the boot `loadServerEntries` pass. See change: decouple-plugins-from-core (5.5, 5.9).
|
|
1605
1710
|
let pluginDiscovery: PluginDiscoveryWiring | undefined;
|
|
@@ -1731,6 +1836,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1731
1836
|
// cwd-policy as the spawn funnel composes it, so the team plugin can refuse a
|
|
1732
1837
|
// start whose skill set the policy would narrow. See change: add-team-skill-access (D7).
|
|
1733
1838
|
pluginServiceRegistry.set("host.resolveCwdPolicy", (cwd: string) => cwdPolicyRegistry.resolve(cwd));
|
|
1839
|
+
// Authenticated loopback REST for plugins (fixed allowlist; per-request local proof, token never exposed).
|
|
1840
|
+
// See change: add-agent-teams-openspec (D4/D8).
|
|
1841
|
+
pluginServiceRegistry.set(HOST_LOCAL_REQUEST_KEY, createHostLocalRequest({ getToken: () => localToken, host: config.host, getPort: () => httpListenPort }));
|
|
1842
|
+
// `@role` default model: re-mirror into pi when its resolution moves (roles
|
|
1843
|
+
// watcher calls this), and expose the ref for the Roles "used by" list.
|
|
1844
|
+
// See change: default-model-follows-role (D4, D5).
|
|
1845
|
+
const piDefaultRemirror = createPiDefaultRemirror({ readDashboardConfig: loadConfig });
|
|
1846
|
+
piDefaultRemirror.seed();
|
|
1847
|
+
setActivePiDefaultRemirror(piDefaultRemirror);
|
|
1848
|
+
pluginServiceRegistry.set("host.remirrorPiDefaults", () => piDefaultRemirror.remirror());
|
|
1849
|
+
pluginServiceRegistry.set("host.defaultModelRef", () => piDefaultRemirror.defaultModelRef());
|
|
1734
1850
|
// Operator-visible (global + global-package) skills for the team plugin's
|
|
1735
1851
|
// admin skill picker. Never project-local. See change: add-team-skill-access (D11).
|
|
1736
1852
|
pluginServiceRegistry.set("host.listOperatorSkills", async () =>
|
|
@@ -1789,11 +1905,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1789
1905
|
// Private plugin request/reply lane: one handler per (pluginId, type), reply
|
|
1790
1906
|
// sent host-internally on the requesting socket (not the priority-gated
|
|
1791
1907
|
// sendExtensionMessage). See change: expose-plugin-credential-and-oauth-seams (D7).
|
|
1792
|
-
const pluginRequestLane = createPluginRequestLane(
|
|
1793
|
-
piGateway.sendToSession(sessionId, msg),
|
|
1908
|
+
const pluginRequestLane = createPluginRequestLane(
|
|
1909
|
+
(sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
1910
|
+
// A hub-local-only reply is delivered only to the socket that passed the gate (see the lane).
|
|
1911
|
+
{ currentChannel: (sessionId) => piGateway.channelOf(sessionId) },
|
|
1794
1912
|
);
|
|
1795
|
-
|
|
1796
|
-
|
|
1913
|
+
// Forward the SENDING socket's own origin + channel (never `originOf(sessionManager.get(id))` /
|
|
1914
|
+
// `channelOf(id)`, which follow the routing entry and the recorded session, not the sender).
|
|
1915
|
+
// See change: harden-bridge-session-claim (D3).
|
|
1916
|
+
function dispatchPluginRequest(sessionId: string, msg: PluginRequestMessage, conn?: GatewayConn): void {
|
|
1917
|
+
pluginRequestLane.handle(sessionId, msg, conn).catch((err) => {
|
|
1797
1918
|
console.error("[plugin-request]", err);
|
|
1798
1919
|
});
|
|
1799
1920
|
}
|
|
@@ -1810,6 +1931,31 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1810
1931
|
}
|
|
1811
1932
|
pluginDiscovery?.onSessionEnded();
|
|
1812
1933
|
}
|
|
1934
|
+
// Record what a loaded plugin owns (manifest `eventTypes`, tool-renderer claims) so the
|
|
1935
|
+
// store/delivery policies it registers apply to its own types and claimed tools only.
|
|
1936
|
+
// Reuses the bridge ownership table builder. See change: move-subagents-to-plugin (D1, D3).
|
|
1937
|
+
function recordPluginPolicyOwnership(plugin: Parameters<typeof buildPluginOwnership>[0][number]): void {
|
|
1938
|
+
const own = buildPluginOwnership([plugin]);
|
|
1939
|
+
getPluginPolicyRegistry().setOwnership(plugin.manifest.id, {
|
|
1940
|
+
eventTypes: Object.keys(own.eventTypes),
|
|
1941
|
+
tools: Object.keys(own.toolClaims),
|
|
1942
|
+
});
|
|
1943
|
+
}
|
|
1944
|
+
function dispatchPluginSessionStatusEnded(sessionId: string): void {
|
|
1945
|
+
for (const h of pluginSessionStatusEndSubs) {
|
|
1946
|
+
try { h(sessionId); } catch (err) { console.error("[plugin-onSessionStatusEnded]", err); }
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
// ctx.appendEvent: store + broadcast an event of a type the calling plugin owns
|
|
1950
|
+
// (manifest `eventTypes`); store WITHOUT broadcast while the session replays,
|
|
1951
|
+
// like the core tool-call heal. Anything else is refused and counted, never thrown.
|
|
1952
|
+
// See change: move-subagents-to-plugin (D4).
|
|
1953
|
+
const appendPluginOwnedEvent = createPluginEventAppender({
|
|
1954
|
+
registry: getPluginPolicyRegistry,
|
|
1955
|
+
eventStore,
|
|
1956
|
+
isReplaying: (sessionId) => replayState.controller.replayingSessions.has(sessionId),
|
|
1957
|
+
broadcastEvent: (sessionId, seq, event) => browserGateway.broadcastEvent(sessionId, seq, event),
|
|
1958
|
+
});
|
|
1813
1959
|
// A bridge registered: a cwd not yet scanned may carry local-scope plugins. Deferred one tick so the
|
|
1814
1960
|
// session is in the manager's active list. See change: decouple-plugins-from-core (task 5.9).
|
|
1815
1961
|
function dispatchSessionRegisteredCwd(cwd: string): void {
|
|
@@ -1884,7 +2030,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1884
2030
|
// Credential vault: store + delivery hub. The hub answers bridge sync
|
|
1885
2031
|
// requests and pushes on every vault write / config change; values travel only
|
|
1886
2032
|
// on the session-private bridge lane. See change: add-credential-vault.
|
|
1887
|
-
const vaultStore = createVaultStore();
|
|
2033
|
+
const vaultStore = createVaultStore({ codec: getCredentialCodec("vault") });
|
|
1888
2034
|
// ACME DNS-01 certificate source: solver secrets live in this vault (kind `tls-solver`).
|
|
1889
2035
|
// GC of orphaned namespaces/account keys runs once at start. See change: add-acme-dns01-certs.
|
|
1890
2036
|
configureAcmeRuntime({ credentials: createAcmeCredentials(vaultStore) });
|
|
@@ -1909,6 +2055,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1909
2055
|
isTlsBridgesLive: tlsBridgesLive,
|
|
1910
2056
|
exposurePending: () => pairedDeviceRegistry.exposurePending(),
|
|
1911
2057
|
});
|
|
2058
|
+
// Sudo credential prompt: in-memory relay (never persists a password); the bridge must also pass the
|
|
2059
|
+
// vault trust predicate. See change: add-sudo-credential-prompt.
|
|
2060
|
+
const sudoCredential = createSudoCredentialRelay({
|
|
2061
|
+
browsers: browserGateway.sudoSeam,
|
|
2062
|
+
sendToBridge: (sessionId, msg) => piGateway.sendToSession(sessionId, msg),
|
|
2063
|
+
isBridgeTrusted: (sessionId) => vaultDelivery.isBridgeTrusted(sessionId),
|
|
2064
|
+
});
|
|
2065
|
+
browserGateway.setSudoCredentialRelay(sudoCredential);
|
|
1912
2066
|
onVaultRoutingChanged = (sessionId, declared) => vaultDelivery.handleRegister(sessionId, declared);
|
|
1913
2067
|
// Revoke, rotation, add and a first plaintext exposure withdraw within the push debounce (~150 ms).
|
|
1914
2068
|
pairedDeviceRegistry.onChange(() => vaultDelivery.schedulePush());
|
|
@@ -1917,10 +2071,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1917
2071
|
activeIds: () => pairedDeviceRegistry.activeIds(),
|
|
1918
2072
|
onLeft: () => vaultDelivery.schedulePush(),
|
|
1919
2073
|
});
|
|
2074
|
+
// Manifest ownership sent to every bridge on register + checked on event_forward ingest.
|
|
2075
|
+
// Built eagerly once: the first discovery is a synchronous scan the register path must not pay.
|
|
2076
|
+
// See change: move-subagents-to-plugin (D1).
|
|
2077
|
+
const pluginOwnership = createPluginOwnership(() => discoverPlugins());
|
|
2078
|
+
pluginOwnership.table();
|
|
1920
2079
|
wireEvents({
|
|
2080
|
+
pluginOwnership,
|
|
1921
2081
|
replayState,
|
|
1922
2082
|
inFlightToolCalls,
|
|
1923
2083
|
vaultDelivery,
|
|
2084
|
+
sudoCredential,
|
|
1924
2085
|
// Lazy: `yolo` is constructed further down; a pre-init call throws and the
|
|
1925
2086
|
// handler declines. See change: yolo-covers-agent-path-gate.
|
|
1926
2087
|
decideAgentPath: (p) =>
|
|
@@ -1928,8 +2089,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1928
2089
|
path: p,
|
|
1929
2090
|
hostGateMode: resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode,
|
|
1930
2091
|
}),
|
|
1931
|
-
onBridgeRegister: (sid, identity) => {
|
|
1932
|
-
const outcome = extensionReloadGuard.onRegister(sid, identity);
|
|
2092
|
+
onBridgeRegister: (sid, identity, sessionFile) => {
|
|
2093
|
+
const outcome = extensionReloadGuard.onRegister(sid, identity, sessionFile);
|
|
1933
2094
|
if (outcome !== "skipped") {
|
|
1934
2095
|
console.log(`[runtime-overlay] bridge register session=${sid} extension=${identity?.dir ?? "(none)"} outcome=${outcome}`);
|
|
1935
2096
|
}
|
|
@@ -1960,8 +2121,22 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1960
2121
|
pendingPromptAcks,
|
|
1961
2122
|
dispatchPluginPiMessage,
|
|
1962
2123
|
dispatchPluginRequest,
|
|
2124
|
+
// D9: the bridge reserve-path pair; late-bound (the stores are built after `wireEvents`).
|
|
2125
|
+
previewPathBridge: () =>
|
|
2126
|
+
previewPaths
|
|
2127
|
+
? {
|
|
2128
|
+
reserve: {
|
|
2129
|
+
store: previewPaths,
|
|
2130
|
+
hasTier5Viewer: () => hasTier5Viewer(browserGateway.wss.clients),
|
|
2131
|
+
portRefusal: (port) => liveServerManager.portRefusal(port),
|
|
2132
|
+
},
|
|
2133
|
+
deviceTier: (deviceId) => pairedDeviceRegistry.list().find((d) => d.id === deviceId)?.tier,
|
|
2134
|
+
isSessionLive: (id) => piGateway.getConnectedSessionIds().includes(id),
|
|
2135
|
+
}
|
|
2136
|
+
: undefined,
|
|
1963
2137
|
dispatchPluginRawEvent,
|
|
1964
2138
|
dispatchPluginSessionEnded,
|
|
2139
|
+
dispatchPluginSessionStatusEnded,
|
|
1965
2140
|
dispatchSessionRegisteredCwd,
|
|
1966
2141
|
metaPersistence,
|
|
1967
2142
|
liveEpoch,
|
|
@@ -1992,8 +2167,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
1992
2167
|
onParentDead: () => server.stop({ exitIntent: "ephemeral" }),
|
|
1993
2168
|
});
|
|
1994
2169
|
|
|
2170
|
+
// Preview-shaped Hosts are answered by the route-less `previewApp` and never enter the dashboard app (D3).
|
|
2171
|
+
// Late-bound: the capability store the dispatch needs is built further down, before `listen`.
|
|
2172
|
+
// See change: serve-live-previews-on-capability-origin.
|
|
2173
|
+
let previewDispatch: PreviewDispatch | undefined;
|
|
2174
|
+
// Tier-5 pid store; late-bound like `previewDispatch` (the preflight hook is registered before the store exists).
|
|
2175
|
+
let previewPaths: PreviewPathStore | undefined;
|
|
1995
2176
|
const fastify = Fastify({
|
|
1996
2177
|
logger: false,
|
|
2178
|
+
serverFactory: previewServerFactory(() => previewDispatch) as never,
|
|
1997
2179
|
keepAliveTimeout: MAIN_KEEP_ALIVE_TIMEOUT_MS,
|
|
1998
2180
|
connectionTimeout: MAIN_CONNECTION_TIMEOUT_MS,
|
|
1999
2181
|
// Add-ons feature ids embed a local package's absolute path (`pkg:local:/…`), which exceeds
|
|
@@ -2131,9 +2313,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2131
2313
|
bindHost: config.host,
|
|
2132
2314
|
// Exact certificate names of the TLS listener (empty unless enabled + bound).
|
|
2133
2315
|
tlsListenerNames: () => tlsListener.tlsListenerNames(),
|
|
2316
|
+
// The `live preview capability hosts` pattern row (D3): present whenever previews are on.
|
|
2317
|
+
livePreviewEnabled: () => getResolvedPreviewOrigins().enabled,
|
|
2134
2318
|
},
|
|
2135
2319
|
...resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()),
|
|
2136
2320
|
});
|
|
2321
|
+
// Inputs of the preview-origin overlap checks (D12): live tunnels, TLS names and the static
|
|
2322
|
+
// admission classifier, so a label-shaped host that is already admitted is never shaped as a preview.
|
|
2323
|
+
setPreviewOriginsRuntime({
|
|
2324
|
+
tunnelOrigins: liveTunnelOrigins,
|
|
2325
|
+
tlsNames: () => tlsListener.tlsListenerNames(),
|
|
2326
|
+
classifyAdmittedHostname: (hostname) => classifyAdmittedHostname(hostname, getHostGateCtx().admission),
|
|
2327
|
+
});
|
|
2137
2328
|
/**
|
|
2138
2329
|
* The ONE origin-policy input, shared by the CORS plugin, the WS upgrade gate
|
|
2139
2330
|
* and the mutating-REST gate. Built per decision (never captured) so tunnel
|
|
@@ -2298,6 +2489,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2298
2489
|
// Origin at all). Report-only default; `PI_DASHBOARD_HOST_GATE=enforce`
|
|
2299
2490
|
// or `hostGate.mode` flips it. See change: add-host-allowlist-admission (D1).
|
|
2300
2491
|
fastify.addHook("onRequest", createHostGate(getHostGateCtx, hostGateState, () => config.port));
|
|
2492
|
+
// Duplicate `pi_dash_*` cookie names → self-healing 400, directly after the host gate and before the CORS
|
|
2493
|
+
// observer / `@fastify/cors`, so the refusal carries no ACAO and precedes every origin gate. previewApp is exempt
|
|
2494
|
+
// by construction (own Fastify instance). See change: serve-live-previews-on-capability-origin (D10).
|
|
2495
|
+
fastify.addHook("onRequest", createDuplicateCookieGate());
|
|
2496
|
+
// Tier-5 opaque-origin preflight: answered for a VALID `/preview/<pid>/` before `@fastify/cors` denies `null` (D8, P6).
|
|
2497
|
+
fastify.addHook("onRequest", createPreviewPreflight(() => previewPaths));
|
|
2301
2498
|
// A denied cross-origin Origin may raise a DEFERRED cors-plane prompt; after
|
|
2302
2499
|
// the host gate so a host-refused request never prompts. Never alters the
|
|
2303
2500
|
// response. See change: add-access-grant-dialog.
|
|
@@ -2352,7 +2549,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2352
2549
|
// Trusted Types rides the same hook under its own `PI_DASHBOARD_TRUSTED_TYPES`
|
|
2353
2550
|
// mode (also stamped into index.html as a meta). See change: harden-client-sinks (D7).
|
|
2354
2551
|
const cspMode = resolveCspMode(process.env.PI_DASHBOARD_CSP);
|
|
2355
|
-
|
|
2552
|
+
// Resolved ONCE (env → config `security.trustedTypes` → default); the same value feeds the headers and the
|
|
2553
|
+
// index.html meta. Each bad source warns once here, never per request. See change: enforce-trusted-types-default.
|
|
2554
|
+
const ttResolution = resolveTrustedTypesMode({
|
|
2555
|
+
env: process.env.PI_DASHBOARD_TRUSTED_TYPES,
|
|
2556
|
+
config: loadConfig().security?.trustedTypes,
|
|
2557
|
+
cspMode,
|
|
2558
|
+
});
|
|
2559
|
+
for (const w of ttResolution.warnings) console.warn(`[csp] Trusted Types: ${w.message}`);
|
|
2560
|
+
const trustedTypesMode = ttResolution.mode;
|
|
2356
2561
|
registerCsp(fastify, cspMode, trustedTypesMode);
|
|
2357
2562
|
|
|
2358
2563
|
// Register auth plugin if configured (must be before routes)
|
|
@@ -2373,19 +2578,62 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2373
2578
|
// there. It admits ONLY a valid `/live/<id>/~c/<token>/…` raw path.
|
|
2374
2579
|
// Liveness is re-checked at every use, so a revoked device, an ended session
|
|
2375
2580
|
// or a removed target is refused on its next request.
|
|
2581
|
+
// Late-bound live accessor from the auth plugin handle (built below): an OAuth session of a
|
|
2582
|
+
// removed / refused-public-IdP provider is not live. See change: close-security-map-high-findings (D3).
|
|
2583
|
+
let sessionProviderRejectedAccessor: ((provider: unknown) => boolean) | null = null;
|
|
2584
|
+
const sessionProviderRejected = (provider: unknown): boolean => sessionProviderRejectedAccessor?.(provider) ?? false;
|
|
2585
|
+
const capabilityPrincipalLive = (p: import("./live-server/live-capability.js").CapabilityPrincipal): boolean => {
|
|
2586
|
+
if (p.identityExpiresAt !== undefined && p.identityExpiresAt <= Date.now()) return false;
|
|
2587
|
+
// Minted on network trust alone: only valid while network trust still authenticates.
|
|
2588
|
+
if (p.kind === "network") return effectiveTrustMode().mode === "legacy";
|
|
2589
|
+
if (p.kind === "device") return pairedDeviceRegistry.list().some((d) => d.id === p.deviceId);
|
|
2590
|
+
if (p.kind === "session" && p.session) return effectiveSessionTier(p.session, passkeyService, sessionProviderRejected) !== null;
|
|
2591
|
+
return true;
|
|
2592
|
+
};
|
|
2593
|
+
// Tier 3 pool (D5): the store's `onDelete` closes the listener of a deleted entry on EVERY deletion path.
|
|
2594
|
+
// Late-bound (`previewPool` is built just below the store it reads).
|
|
2376
2595
|
const liveCapabilities = new LiveCapabilityStore({
|
|
2377
2596
|
isTargetLive: (id) => liveServerManager.has(id),
|
|
2378
|
-
isPrincipalLive:
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
if (
|
|
2383
|
-
|
|
2384
|
-
|
|
2597
|
+
isPrincipalLive: capabilityPrincipalLive,
|
|
2598
|
+
onDelete: (entry, reason) => {
|
|
2599
|
+
previewPool?.onDelete(entry, reason);
|
|
2600
|
+
// The entry is gone: drop its "first admit" bookkeeping so observer state tracks live entries (D13, no leak across churn).
|
|
2601
|
+
if (entry.label) previewObserver?.forget(previewLogHash(entry.label));
|
|
2602
|
+
},
|
|
2603
|
+
getPreviewConfig: () => getResolvedPreviewOrigins(),
|
|
2604
|
+
});
|
|
2605
|
+
previewPool = createPreviewPool({
|
|
2606
|
+
range: () => {
|
|
2607
|
+
const r = getResolvedPreviewOrigins();
|
|
2608
|
+
return r.enabled ? r.pool : undefined;
|
|
2609
|
+
},
|
|
2610
|
+
bindHost: () => config.host,
|
|
2611
|
+
findByPoolPort: (port) => liveCapabilities.findByPoolPort(port),
|
|
2612
|
+
revokeByPoolPort: (port, reason) => liveCapabilities.revokeByPoolPort(port, reason),
|
|
2613
|
+
touch: (grant) => void liveCapabilities.touch(grant.tokenId, grant.minterKey),
|
|
2614
|
+
manager: liveServerManager,
|
|
2615
|
+
proxyDeps: () => liveProxyDepsRef,
|
|
2616
|
+
});
|
|
2617
|
+
// Tier 5 (`/preview/<pid>/`, D8): one current pid per port target; liveness is re-checked at every use, so a revoked
|
|
2618
|
+
// holder / removed target / disabled previews drops the pid on its next request or sweep.
|
|
2619
|
+
const previewWs = createPreviewWsRegistry();
|
|
2620
|
+
previewPaths = new PreviewPathStore({
|
|
2621
|
+
onDrop: (reason, pid) => {
|
|
2622
|
+
liveLog(undefined, "pid dropped", { reason, h: previewLogHash(pid) });
|
|
2623
|
+
previewWs.closePid(pid); // in-flight HMR sockets die with the pid
|
|
2385
2624
|
},
|
|
2625
|
+
targetIdForPort: (port) => liveServerManager.getByPort(port)?.id,
|
|
2626
|
+
isPortAllowed: (port) => liveServerManager.portRefusal(port) === null,
|
|
2627
|
+
isTargetLive: (id) => liveServerManager.has(id),
|
|
2628
|
+
isPrincipalLive: capabilityPrincipalLive,
|
|
2629
|
+
isEnabled: () => getResolvedPreviewOrigins().enabled,
|
|
2386
2630
|
});
|
|
2631
|
+
previewPaths.start();
|
|
2387
2632
|
// An evicted preset / static target takes its tokens with it.
|
|
2388
|
-
liveServerManager.setEvictionListener((id) =>
|
|
2633
|
+
liveServerManager.setEvictionListener((id) => {
|
|
2634
|
+
liveCapabilities.revokeByTarget(id);
|
|
2635
|
+
previewPaths?.revokeByTarget(id);
|
|
2636
|
+
});
|
|
2389
2637
|
// Per-token egress state (markup scan, CSP reports, allow-once, project grants). Project grants are read
|
|
2390
2638
|
// from their store on every CSP build, so a grant or revoke applies on the next response with no restart.
|
|
2391
2639
|
const previewEgress = createPreviewEgress({
|
|
@@ -2437,7 +2685,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2437
2685
|
fastify.addHook("onRequest", async (request) => {
|
|
2438
2686
|
previewExposure.noteRequest(request.headers as Record<string, unknown>);
|
|
2439
2687
|
});
|
|
2440
|
-
fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities));
|
|
2688
|
+
fastify.addHook("onRequest", createLiveCapabilityHook(liveCapabilities, previewPaths));
|
|
2441
2689
|
registerBearerAuth(fastify, { registry: pairedDeviceRegistry });
|
|
2442
2690
|
registerDeviceSessionRoutes(fastify, {
|
|
2443
2691
|
registry: pairedDeviceRegistry,
|
|
@@ -2527,7 +2775,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2527
2775
|
passkeyService.configure(config.authConfig);
|
|
2528
2776
|
let oauthLoginAccessor: (() => boolean) | null = null;
|
|
2529
2777
|
if (config.authConfig) {
|
|
2530
|
-
|
|
2778
|
+
const authHandle = await registerAuthPlugin(fastify, {
|
|
2531
2779
|
authConfig: config.authConfig,
|
|
2532
2780
|
port: config.port,
|
|
2533
2781
|
resolvedTrustedNetworks: config.resolvedTrustedNetworks,
|
|
@@ -2536,7 +2784,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2536
2784
|
localToken,
|
|
2537
2785
|
localTrust,
|
|
2538
2786
|
passkeys: passkeyService,
|
|
2539
|
-
|
|
2787
|
+
// Close open browser + terminal sockets whose session the reload revoked (D3, G7-G10).
|
|
2788
|
+
onAuthReloaded: () => {
|
|
2789
|
+
sweepRevokedSockets({ browser: browserGateway.wss, terminal: terminalGateway.wss });
|
|
2790
|
+
},
|
|
2791
|
+
});
|
|
2792
|
+
oauthLoginAccessor = authHandle.hasUsableOAuthProvider;
|
|
2793
|
+
sessionProviderRejectedAccessor = authHandle.isSessionProviderRejected;
|
|
2540
2794
|
}
|
|
2541
2795
|
// Live "is a usable login method configured" (drives the `sign-in` remedy of an
|
|
2542
2796
|
// `operate_required` refusal). See change: surface-operate-required-remedy.
|
|
@@ -2643,6 +2897,21 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2643
2897
|
{ localToken, localTrust },
|
|
2644
2898
|
);
|
|
2645
2899
|
|
|
2900
|
+
// `/api/health` `networkAccess` verdict: the REST pass predicate evaluated purely
|
|
2901
|
+
// (no telemetry / block events). The admission list goes through a 1 s TTL memo so
|
|
2902
|
+
// attacker-paced health requests cost at most one config `statSync` per second.
|
|
2903
|
+
// See change: surface-network-denial-on-health (D2).
|
|
2904
|
+
let verdictList: { at: number; list: string[] } | undefined;
|
|
2905
|
+
const memoAdmissionList = (): string[] => {
|
|
2906
|
+
const now = Date.now();
|
|
2907
|
+
if (!verdictList || now - verdictList.at >= 1000 || now < verdictList.at) {
|
|
2908
|
+
verdictList = { at: now, list: admissionList() };
|
|
2909
|
+
}
|
|
2910
|
+
return verdictList.list;
|
|
2911
|
+
};
|
|
2912
|
+
const readNetworkVerdict = (request: FastifyRequest): boolean =>
|
|
2913
|
+
evaluateNetworkPass(request, { readTrusted: memoAdmissionList, localToken, localTrust }).passed === null;
|
|
2914
|
+
|
|
2646
2915
|
// Session control REST API (wraps WebSocket-only operations)
|
|
2647
2916
|
registerSessionApi(fastify, {
|
|
2648
2917
|
sessionManager,
|
|
@@ -2654,6 +2923,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2654
2923
|
pendingPrincipalOwnerRegistry,
|
|
2655
2924
|
pendingResumeIntents,
|
|
2656
2925
|
pendingAttachRegistry,
|
|
2926
|
+
pendingInitialPromptRegistry,
|
|
2657
2927
|
pendingPromptAcks,
|
|
2658
2928
|
sessionArchive,
|
|
2659
2929
|
pendingArchiveIntents,
|
|
@@ -2778,6 +3048,19 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
2778
3048
|
// Signed navigation intents for operator-opened route-backed overlays
|
|
2779
3049
|
// (per-process key: a restart invalidates them). See change: harden-client-sinks (D10).
|
|
2780
3050
|
registerNavIntentRoutes(fastify, { networkGuard, intents: new NavIntents() });
|
|
3051
|
+
// Framing probe for web-link previews: operator click → one SSRF-hardened outbound HEAD, verdict only
|
|
3052
|
+
// (control tier; own browser Origin required). See change: rich-chat-links (D12).
|
|
3053
|
+
registerFramePolicyRoutes(fastify, {
|
|
3054
|
+
networkGuard,
|
|
3055
|
+
corsOpts,
|
|
3056
|
+
ownOrigins: previewEgressOwnOrigins,
|
|
3057
|
+
ownPorts: () => {
|
|
3058
|
+
const tls = loadConfig().tls;
|
|
3059
|
+
return [config.port, ...(tls?.enabled ? [tls.port] : [])];
|
|
3060
|
+
},
|
|
3061
|
+
// Test-only verdict seam (PI_E2E_SEED + PI_E2E_FRAME_POLICY_VERDICTS, refused in production): undefined = real probe.
|
|
3062
|
+
probe: resolveFramePolicyTestSeam(process.env, console),
|
|
3063
|
+
});
|
|
2781
3064
|
// On-demand AI mermaid repair (opt-in via `mermaidRepair` config; 404 when off).
|
|
2782
3065
|
// See change: add-mermaid-ai-repair.
|
|
2783
3066
|
registerMermaidRepairRoutes(fastify, {
|
|
@@ -3004,6 +3287,29 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3004
3287
|
} catch { /* best-effort */ }
|
|
3005
3288
|
}
|
|
3006
3289
|
};
|
|
3290
|
+
// Plugin-declared replay entry types (manifest `replayEntryTypes`): enabled
|
|
3291
|
+
// plugins replay, every declaring plugin hides. Read by each session replay;
|
|
3292
|
+
// short-TTL cache so a toggle lands without a per-load disk scan.
|
|
3293
|
+
// See change: update-flows-plugin (D3, G5).
|
|
3294
|
+
{
|
|
3295
|
+
let cached: { at: number; sets: ReturnType<typeof computeReplayEntryTypes> } | undefined;
|
|
3296
|
+
setReplayEntryTypesProvider(() => {
|
|
3297
|
+
const now = Date.now();
|
|
3298
|
+
if (cached && now - cached.at < 5_000) return cached.sets;
|
|
3299
|
+
const config = loadConfig();
|
|
3300
|
+
const sets = computeReplayEntryTypes(
|
|
3301
|
+
discoverPlugins().map((p) => ({
|
|
3302
|
+
replayEntryTypes: p.manifest.replayEntryTypes,
|
|
3303
|
+
enabled: resolvePluginEnabled(
|
|
3304
|
+
getPluginConfigFromFile(config, p.manifest.id) as Record<string, unknown>,
|
|
3305
|
+
p.manifest.defaultEnabled,
|
|
3306
|
+
),
|
|
3307
|
+
})),
|
|
3308
|
+
);
|
|
3309
|
+
cached = { at: now, sets };
|
|
3310
|
+
return sets;
|
|
3311
|
+
});
|
|
3312
|
+
}
|
|
3007
3313
|
const embedLifecycle = createEmbedLifecycleController({
|
|
3008
3314
|
closers: sessionClosers,
|
|
3009
3315
|
markArchiveOnEnd,
|
|
@@ -3061,7 +3367,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3061
3367
|
live: () => piTrustMirror.live,
|
|
3062
3368
|
readSnapshot: () => piTrustMirror.readSnapshot(),
|
|
3063
3369
|
});
|
|
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 });
|
|
3370
|
+
registerSystemRoutes(fastify, { readNetworkVerdict, onVaultConfigChanged: () => void vaultDelivery.pushNow(), onTlsBridgeSwitchChanged: () => onTlsBridgeSwitchChanged({ acceptBridges: tlsBridgesLive, push: () => void vaultDelivery.pushNow(), gateway: piGateway }), exposureWritePending: () => pairedDeviceRegistry.exposurePending(), tls: tlsListener, sessionManager, preferencesStore, metaPersistence, config, networkGuard, localTrust, version: pkgVersion, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, clientDir, clientBuild, readTrustedNetworks: () => liveTrustedNetworks(config.resolvedTrustedNetworks ?? []), readPiTrustLive: piTrustQuery.counters, readCspReports: () => cspReportStore.snapshot(), readAccessGrants: () => snapshotAccessGrantHealth({ coordinator: grantCoordinator, yolo, refusalCount: () => listRefusals().length, promptEnabled: () => loadConfig().accessGrants?.promptEnabled === true, killSwitch: () => isGrantPromptKilled(), hostGateMode: () => resolveHostGateMode(process.env.PI_DASHBOARD_HOST_GATE, liveHostGateMode()).mode, operatorChannels: () => promptChannelCount(), provisioning: () => provisioning.registry.stats() }), keeperLogStats: { get: () => getKeeperManager().getKeeperLogStats() }, readPushErrors: pushService ? () => pushService?.errors ?? [] : pushInitError ? () => [pushInitError as string] : undefined });
|
|
3065
3371
|
registerHostGateRoutes(fastify, { getCtx: getHostGateCtx, state: hostGateState, networkGuard });
|
|
3066
3372
|
// GET /api/doctor — see change: doctor-rich-output (task 4.2). Auth-gated identically to /api/config.
|
|
3067
3373
|
// Assigned by the runtime-overlay block below; read lazily per request.
|
|
@@ -3380,6 +3686,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3380
3686
|
registerLiveServerRoutes(fastify, liveServerManager, {
|
|
3381
3687
|
networkGuard,
|
|
3382
3688
|
capabilities: liveCapabilities,
|
|
3689
|
+
pool: previewPool,
|
|
3690
|
+
previewPaths,
|
|
3691
|
+
hasTier5Viewer: () => hasTier5Viewer(browserGateway.wss.clients),
|
|
3383
3692
|
exposure: previewExposure,
|
|
3384
3693
|
promptingEnabled: () => loadConfig().accessGrants?.promptEnabled === true,
|
|
3385
3694
|
getTrustedNetworks: admissionList,
|
|
@@ -3402,11 +3711,22 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3402
3711
|
return { ok: true, resolved: gate.resolved };
|
|
3403
3712
|
},
|
|
3404
3713
|
});
|
|
3405
|
-
|
|
3714
|
+
const liveProxyDeps: LiveProxyDeps = {
|
|
3406
3715
|
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
3407
3716
|
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
3408
3717
|
grantedOrigins: (grant) => previewEgress.grantedFor(grant),
|
|
3718
|
+
// D3(c): a tier 1-4 upstream `Location` / `Refresh` aimed at the dashboard app is contained (dropped / rewritten onto the preview).
|
|
3719
|
+
isDashboardUrl: (url) => {
|
|
3720
|
+
const tls = loadConfig().tls;
|
|
3721
|
+
const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
|
|
3722
|
+
return (
|
|
3723
|
+
(port === config.port || (tls?.enabled === true && port === tls.port)) &&
|
|
3724
|
+
!isPreviewShapedOriginUrl(url.origin) &&
|
|
3725
|
+
isHostAdmitted(url.host, getHostGateCtx().admission)
|
|
3726
|
+
);
|
|
3727
|
+
},
|
|
3409
3728
|
onStaticHtmlServed: (grant, real) => previewEgress.noteServed(grant, real),
|
|
3729
|
+
trackPreviewResponse: (pid, res) => previewWs.track(pid, res),
|
|
3410
3730
|
reservedHandler: createReservedHandler({
|
|
3411
3731
|
egress: previewEgress,
|
|
3412
3732
|
ownOriginsOf: (request) => requestOriginsOf(request),
|
|
@@ -3415,6 +3735,18 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3415
3735
|
// a refusal here records no denial and raises no prompt.
|
|
3416
3736
|
staticGate: async (cwd, absPath) =>
|
|
3417
3737
|
!("code" in (await gateFilePath(cwd, absPath, fileRouteAdmission, { allowGrant: true, quiet: true }))),
|
|
3738
|
+
};
|
|
3739
|
+
liveProxyDepsRef = liveProxyDeps;
|
|
3740
|
+
registerLiveServerProxy(fastify, liveServerManager, liveProxyDeps);
|
|
3741
|
+
previewObserver = createPreviewObserver();
|
|
3742
|
+
previewDispatch = createPreviewDispatch({
|
|
3743
|
+
onRefused: (reason, h) => previewObserver?.refused(reason, h),
|
|
3744
|
+
onAdmitted: (h, tier) => previewObserver?.admitted(h, tier),
|
|
3745
|
+
store: liveCapabilities,
|
|
3746
|
+
manager: liveServerManager,
|
|
3747
|
+
proxyDeps: liveProxyDeps,
|
|
3748
|
+
isPeerLocal: (request) =>
|
|
3749
|
+
isLocallyTrusted({ ip: request.socket.remoteAddress ?? "", headers: request.headers as Record<string, unknown> }),
|
|
3418
3750
|
});
|
|
3419
3751
|
|
|
3420
3752
|
// ONE model runtime for the provider-auth flow listing AND the model proxy,
|
|
@@ -3430,6 +3762,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3430
3762
|
registerProviderAuthRoutes(fastify, {
|
|
3431
3763
|
piGateway,
|
|
3432
3764
|
browserGateway,
|
|
3765
|
+
// Key-file inspection reads only inside the browse confinement a remote
|
|
3766
|
+
// request gets. See change: add-provider-env-config (D7).
|
|
3767
|
+
browseConfine: (request) =>
|
|
3768
|
+
isLocallyTrusted({ ip: request.ip, headers: request.headers }, localTrust) ? Promise.resolve(null) : browseRoots(),
|
|
3433
3769
|
radiusMcp: {
|
|
3434
3770
|
service: () => {
|
|
3435
3771
|
radiusMcpService ??= createMcpClientConfigService({
|
|
@@ -3527,6 +3863,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3527
3863
|
localTrust,
|
|
3528
3864
|
verifyDeviceBearer: (token) => pairedDeviceRegistry.verify(token, bearerChannelOf(request.raw)),
|
|
3529
3865
|
});
|
|
3866
|
+
logTicketRefusal(verdict);
|
|
3530
3867
|
if (!verdict.allow) {
|
|
3531
3868
|
reply.code(403);
|
|
3532
3869
|
return { success: false as const, error: verdict.reason };
|
|
@@ -3549,7 +3886,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3549
3886
|
const identity = authed.principal
|
|
3550
3887
|
? { principal: authed.principal, principalExpiresAt: authed.principalExpiresAt }
|
|
3551
3888
|
: undefined;
|
|
3552
|
-
|
|
3889
|
+
// A device-bearer caller's id rides the ticket (like a bridge ticket), so the socket it opens is
|
|
3890
|
+
// tagged with it, a revoke closes it, and a pre-revoke ticket is refused at upgrade.
|
|
3891
|
+
// See change: device-key-mutual-check (D7).
|
|
3892
|
+
const deviceId = (request as { principalDeviceId?: string }).principalDeviceId;
|
|
3893
|
+
return { success: true as const, data: { ticket: wsTicketStore.mint(scope, deviceId, identity) } };
|
|
3553
3894
|
},
|
|
3554
3895
|
);
|
|
3555
3896
|
registerPluginConfigRoutes(fastify, {
|
|
@@ -3574,6 +3915,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3574
3915
|
// Global auto-session-naming toggle (add-auto-session-naming). Broadcasts
|
|
3575
3916
|
// `preferences_update` to bridges on change.
|
|
3576
3917
|
registerPreferencesAutoNameRoutes(fastify, { preferencesStore, piGateway, networkGuard });
|
|
3918
|
+
registerPreferencesClaudeCompatRoutes(fastify, { preferencesStore, piGateway, networkGuard });
|
|
3577
3919
|
registerPluginActivationRoutes(fastify, {
|
|
3578
3920
|
networkGuard,
|
|
3579
3921
|
broadcast: (msg) => browserGateway.broadcast(msg),
|
|
@@ -3606,7 +3948,17 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3606
3948
|
// Fastify here runs with logger:false, so its log would drop every toggle line.
|
|
3607
3949
|
log: { info: (m) => console.log(m), warn: (m) => console.warn(m), error: (m) => console.error(m) },
|
|
3608
3950
|
});
|
|
3951
|
+
// Egress vet for provider probes refuses the dashboard's own port on a local
|
|
3952
|
+
// address. See change: close-local-listener-and-egress-gaps (NET-04).
|
|
3953
|
+
setProbeSelfPort(() => {
|
|
3954
|
+
const addr = fastify.server.address();
|
|
3955
|
+
const ports = addr && typeof addr === "object" ? [addr.port] : [];
|
|
3956
|
+
const tls = loadConfig().tls; // the TLS listener is the dashboard too (same idiom as `ownPorts` above)
|
|
3957
|
+
if (tls?.enabled) ports.push(tls.port);
|
|
3958
|
+
return ports.length ? ports : null;
|
|
3959
|
+
});
|
|
3609
3960
|
registerProviderRoutes(fastify, { networkGuard, piGateway, browserGateway, port: config.port });
|
|
3961
|
+
registerProviderOverrideRoutes(fastify, { networkGuard, piGateway, port: config.port });
|
|
3610
3962
|
|
|
3611
3963
|
// ── Model Proxy ───────────────────────────────────────────────────
|
|
3612
3964
|
{
|
|
@@ -3852,10 +4204,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3852
4204
|
}
|
|
3853
4205
|
|
|
3854
4206
|
const server: DashboardServer = {
|
|
4207
|
+
inject: fastify.inject.bind(fastify) as FastifyInstance["inject"],
|
|
3855
4208
|
sessionManager,
|
|
3856
4209
|
eventStore,
|
|
3857
4210
|
browserGateway,
|
|
3858
4211
|
pendingDashboardSpawns,
|
|
4212
|
+
pendingInitialPromptRegistry,
|
|
3859
4213
|
directoryService,
|
|
3860
4214
|
sessionOrderManager,
|
|
3861
4215
|
|
|
@@ -3903,6 +4257,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
3903
4257
|
secondFastify = null;
|
|
3904
4258
|
}
|
|
3905
4259
|
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
4260
|
+
try { await previewDispatch?.close(); } catch { /* ignore */ }
|
|
4261
|
+
try { liveCapabilities.close(); } catch { /* ignore */ }
|
|
4262
|
+
try { await previewPool?.close(); } catch { /* ignore */ }
|
|
3906
4263
|
try { await fastify.close(); } catch { /* ignore */ }
|
|
3907
4264
|
},
|
|
3908
4265
|
});
|
|
@@ -4076,7 +4433,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4076
4433
|
getPluginConfigFromFile(loadConfig(), id) as Record<string, unknown>,
|
|
4077
4434
|
// Bracket this plugin's activation for route-owner attribution (D24): the
|
|
4078
4435
|
// next plugin's createContext re-begins; the finally below ends.
|
|
4079
|
-
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), pluginManifestEmits.set(plugin.manifest.id, plugin.manifest.emits ?? []), createServerPluginContext(
|
|
4436
|
+
createContext: (plugin) => (routeOwners.begin(plugin.manifest.id), pluginManifestEmits.set(plugin.manifest.id, plugin.manifest.emits ?? []), recordPluginPolicyOwnership(plugin), createServerPluginContext(
|
|
4080
4437
|
{
|
|
4081
4438
|
fastify,
|
|
4082
4439
|
isPiExtensionInstalled,
|
|
@@ -4092,11 +4449,15 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4092
4449
|
},
|
|
4093
4450
|
onPiResourcesInvalidated: (handler: (cwd: string | undefined) => void) =>
|
|
4094
4451
|
directoryService.onPiResourcesInvalidated(handler),
|
|
4095
|
-
|
|
4452
|
+
// `isConnected` = open bridge socket, trusted plugins only (same
|
|
4453
|
+
// gate as abortSpawnedRun). See change: polish-automation-board.
|
|
4454
|
+
sessionManager: createPluginSessionManager({
|
|
4096
4455
|
listActive: () => sessionManager.listActive(),
|
|
4097
4456
|
listAll: () => sessionManager.listAll(),
|
|
4098
4457
|
getSession: (id: string) => sessionManager.get(id),
|
|
4099
|
-
|
|
4458
|
+
isSessionConnected: (id: string) => piGateway.isSessionConnected(id),
|
|
4459
|
+
trusted: (plugin.manifest.priority ?? 1000) <= 100,
|
|
4460
|
+
}),
|
|
4100
4461
|
eventStore: {
|
|
4101
4462
|
getEvents: (sessionId) => eventStore.getEvents(sessionId, 0),
|
|
4102
4463
|
getLatestEvent: (sessionId) => {
|
|
@@ -4153,6 +4514,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4153
4514
|
pluginSessionEndSubs.add(handler);
|
|
4154
4515
|
return () => pluginSessionEndSubs.delete(handler);
|
|
4155
4516
|
},
|
|
4517
|
+
onSessionStatusEnded: (handler) => {
|
|
4518
|
+
pluginSessionStatusEndSubs.add(handler);
|
|
4519
|
+
return () => pluginSessionStatusEndSubs.delete(handler);
|
|
4520
|
+
},
|
|
4521
|
+
appendEvent: (sessionId, event) => appendPluginOwnedEvent(plugin.manifest.id, sessionId, event),
|
|
4522
|
+
registerStorePolicy: (policy) => getPluginPolicyRegistry().registerStorePolicy(plugin.manifest.id, policy),
|
|
4523
|
+
registerDeliveryPolicy: (policy) => getPluginPolicyRegistry().registerDeliveryPolicy(plugin.manifest.id, policy),
|
|
4524
|
+
registerReplayCarry: (handler) => getPluginPolicyRegistry().registerReplayCarry(plugin.manifest.id, handler),
|
|
4156
4525
|
onSessionResolved: (handler) => {
|
|
4157
4526
|
const id = plugin.manifest.id;
|
|
4158
4527
|
let set = pluginSessionResolvedSubs.get(id);
|
|
@@ -4163,123 +4532,40 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4163
4532
|
set.add(handler);
|
|
4164
4533
|
return () => set.delete(handler);
|
|
4165
4534
|
},
|
|
4166
|
-
sendToSession: (sessionId, text) =>
|
|
4167
|
-
piGateway.sendToSession(sessionId,
|
|
4535
|
+
sendToSession: (sessionId, text, opts) =>
|
|
4536
|
+
piGateway.sendToSession(sessionId, buildPluginSendPrompt(sessionId, text, opts)),
|
|
4168
4537
|
// Session-spawn hook. Gated to first-party/trusted plugins
|
|
4169
4538
|
// (priority <= 100 by convention). Untrusted plugins get a
|
|
4170
|
-
// hook that always rejects.
|
|
4171
|
-
//
|
|
4172
|
-
|
|
4173
|
-
|
|
4174
|
-
|
|
4175
|
-
|
|
4176
|
-
|
|
4177
|
-
|
|
4178
|
-
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
4184
|
-
|
|
4185
|
-
|
|
4186
|
-
|
|
4187
|
-
|
|
4188
|
-
|
|
4189
|
-
|
|
4190
|
-
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
4194
|
-
|
|
4195
|
-
|
|
4196
|
-
|
|
4197
|
-
|
|
4198
|
-
|
|
4199
|
-
|
|
4200
|
-
// entry untouched. Otherwise mint up front so the ownership
|
|
4201
|
-
// ref is filed against it BEFORE the `spawnPiSession` await
|
|
4202
|
-
// (unchanged), closing the register-in-the-gap miss. See
|
|
4203
|
-
// change: detach-automation-goal-from-core,
|
|
4204
|
-
// relocate-goal-product-to-plugin (D1-#1).
|
|
4205
|
-
const requested = typeof opts.spawnToken === "string" ? opts.spawnToken : "";
|
|
4206
|
-
if (requested?.includes("\0")) {
|
|
4207
|
-
// A NUL cannot survive argv/registry round-trips — honouring
|
|
4208
|
-
// "used verbatim" means refusing, not silently re-minting a
|
|
4209
|
-
// token the caller's persisted state would never match.
|
|
4210
|
-
return { success: false, message: "spawnToken must not contain NUL" };
|
|
4211
|
-
}
|
|
4212
|
-
const spawnToken = requested || mintSpawnToken();
|
|
4213
|
-
if (requested && pendingPluginRefRegistry.has(spawnToken)) {
|
|
4214
|
-
return {
|
|
4215
|
-
success: false,
|
|
4216
|
-
message: `spawnToken "${spawnToken}" is already pending for another spawn`,
|
|
4217
|
-
};
|
|
4218
|
-
}
|
|
4219
|
-
pendingPluginRefRegistry.file(
|
|
4220
|
-
spawnToken,
|
|
4221
|
-
opts.pluginRef,
|
|
4222
|
-
plugin.manifest.id,
|
|
4223
|
-
opts.lifecycle,
|
|
4224
|
-
);
|
|
4225
|
-
// Fresh-spawn reprime rides the per-cwd pending-initial-prompt
|
|
4226
|
-
// FIFO exactly as core's own respawn path does: enqueue BEFORE
|
|
4227
|
-
// the spawn await, consume on failure/throw so a dead spawn
|
|
4228
|
-
// leaves no stale intent for an unrelated later register in
|
|
4229
|
-
// the same cwd. See change:
|
|
4230
|
-
// relocate-goal-product-to-plugin (D1-#3).
|
|
4231
|
-
const initialPrompt =
|
|
4232
|
-
typeof opts.initialPrompt === "string" && opts.initialPrompt.length > 0
|
|
4233
|
-
? opts.initialPrompt
|
|
4234
|
-
: undefined;
|
|
4235
|
-
if (initialPrompt) pendingInitialPromptRegistry.enqueue(opts.cwd, initialPrompt);
|
|
4236
|
-
// mode/sandbox threading (change: redesign-automation-editor-and-board).
|
|
4237
|
-
// DOCUMENTED LIMITATION (task 4.2): the host hook does not yet
|
|
4238
|
-
// enforce these. `worktree` would need ephemeral worktree
|
|
4239
|
-
// create+cleanup wired to run-end correlation (discard/merge
|
|
4240
|
-
// policy unspecified); pi exposes no `--sandbox` flag so the
|
|
4241
|
-
// sandbox level cannot be applied at spawn. Both fall back to
|
|
4242
|
-
// running in-place at `opts.cwd`. Log non-default requests so
|
|
4243
|
-
// the gap is visible until the host gains support.
|
|
4244
|
-
if (opts.mode === "worktree" || (opts.sandbox && opts.sandbox !== "workspace-write")) {
|
|
4245
|
-
console.warn(
|
|
4246
|
-
`[plugin-spawn] mode=${opts.mode ?? "local"} sandbox=${opts.sandbox ?? "(default)"} requested but not yet enforced by the host hook; running in-place at ${opts.cwd}`,
|
|
4247
|
-
);
|
|
4248
|
-
}
|
|
4249
|
-
try {
|
|
4250
|
-
const result =
|
|
4251
|
-
typeof opts.agent === "string"
|
|
4252
|
-
? await spawnAcpSession(opts.cwd, { agent: opts.agent, spawnToken })
|
|
4253
|
-
: await spawnPiSession(opts.cwd, { ...sessionOptions, spawnToken });
|
|
4254
|
-
// Plugin/automation spawn: transport-less, reclaim required.
|
|
4255
|
-
armSpawnWatchdog(opts.cwd, "headless", result);
|
|
4256
|
-
if (result.process && result.pid) {
|
|
4257
|
-
browserGateway.headlessPidRegistry.register(
|
|
4258
|
-
result.pid,
|
|
4259
|
-
opts.cwd,
|
|
4260
|
-
result.process,
|
|
4261
|
-
result.spawnToken ?? spawnToken,
|
|
4262
|
-
keeperOptsFromSpawnResult(result),
|
|
4263
|
-
);
|
|
4264
|
-
}
|
|
4265
|
-
// Token-keyed, idempotent rollback on failure so no later
|
|
4266
|
-
// session resolves a stale ref; the queued initial prompt
|
|
4267
|
-
// is consumed with it.
|
|
4268
|
-
if (!result.success) {
|
|
4269
|
-
pendingPluginRefRegistry.remove(spawnToken);
|
|
4270
|
-
if (initialPrompt) pendingInitialPromptRegistry.consume(opts.cwd);
|
|
4271
|
-
}
|
|
4272
|
-
return {
|
|
4273
|
-
success: result.success,
|
|
4274
|
-
message: result.message,
|
|
4275
|
-
...(result.spawnToken ? { spawnToken: result.spawnToken } : { spawnToken }),
|
|
4276
|
-
};
|
|
4277
|
-
} catch (err) {
|
|
4278
|
-
pendingPluginRefRegistry.remove(spawnToken);
|
|
4279
|
-
if (initialPrompt) pendingInitialPromptRegistry.consume(opts.cwd);
|
|
4280
|
-
return { success: false, message: err instanceof Error ? err.message : String(err) };
|
|
4281
|
-
}
|
|
4282
|
-
},
|
|
4539
|
+
// hook that always rejects. The flow (incl. the optional `worktree`
|
|
4540
|
+
// block) lives in `createPluginSpawnHook`.
|
|
4541
|
+
// See change: add-automation-plugin, add-plugin-spawn-worktree.
|
|
4542
|
+
spawnSession: createPluginSpawnHook({
|
|
4543
|
+
plugin: { id: plugin.manifest.id, priority: plugin.manifest.priority },
|
|
4544
|
+
defaultModel: () => loadConfig().defaultModel,
|
|
4545
|
+
mintSpawnToken,
|
|
4546
|
+
validateAcp: validatePluginAcpSpawn,
|
|
4547
|
+
pendingPluginRefRegistry,
|
|
4548
|
+
pendingInitialPromptRegistry,
|
|
4549
|
+
pendingAttachRegistry,
|
|
4550
|
+
spawnPi: (cwd, o) => spawnPiSession(cwd, o as Parameters<typeof spawnPiSession>[1]),
|
|
4551
|
+
spawnAcp: spawnAcpSession,
|
|
4552
|
+
armWatchdog: (cwd, result) => armSpawnWatchdog(cwd, "headless", result),
|
|
4553
|
+
registerHeadlessPid: (pid, cwd, child, token, result) =>
|
|
4554
|
+
browserGateway.headlessPidRegistry.register(
|
|
4555
|
+
pid,
|
|
4556
|
+
cwd,
|
|
4557
|
+
child as Parameters<typeof browserGateway.headlessPidRegistry.register>[2],
|
|
4558
|
+
token,
|
|
4559
|
+
keeperOptsFromSpawnResult(result),
|
|
4560
|
+
),
|
|
4561
|
+
ensureWorktree: (o) =>
|
|
4562
|
+
ensureWorktree({ ...o, knownCwds: knownFolderCwds, admitOptions: { onIndeterminate: cwdAdmissionLogger } }),
|
|
4563
|
+
resolveCwdPolicy: (cwd) => cwdPolicyRegistry.resolve(cwd),
|
|
4564
|
+
autoInitEnabled: () => preferencesStore.getAutoInitWorktreeOnSpawn(),
|
|
4565
|
+
startWorktreeInit: (cwd, o) => startWorktreeInit(cwd, { ...o, registry: worktreeInitRegistry }),
|
|
4566
|
+
awaitInitRun: (cwd) => awaitInitRun(worktreeInitRegistry, cwd),
|
|
4567
|
+
isStopping: () => serverStopping,
|
|
4568
|
+
}),
|
|
4283
4569
|
// Spawn-env contributor hook. Trusted-gated like `spawnSession`
|
|
4284
4570
|
// (policy, not a sandbox); untrusted plugins get a no-op.
|
|
4285
4571
|
// See change: add-context-mode-settings-plugin.
|
|
@@ -4374,6 +4660,14 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4374
4660
|
}
|
|
4375
4661
|
return mintSpawnToken();
|
|
4376
4662
|
},
|
|
4663
|
+
// Guarded UTF-8 file read for plugin routes that return file CONTENT: `null` when the
|
|
4664
|
+
// dashboard-state / pi-agent-credential guard refuses the real path (caller from the
|
|
4665
|
+
// `onRequest` scope) or the opened handle. Not trust-gated (it only narrows).
|
|
4666
|
+
// See change: close-security-map-high-findings (D1, H1).
|
|
4667
|
+
readFileGuarded: guardedReadFile,
|
|
4668
|
+
// Public base for plugin OAuth return URLs: same resolution as the dashboard login redirect.
|
|
4669
|
+
// See change: add-google-connect.
|
|
4670
|
+
getDashboardBaseUrl: () => resolveRedirectBase(config.port, config.authConfig?.redirectBaseUrl).base,
|
|
4377
4671
|
// Rename a live session: in-memory + `session_updated` broadcast
|
|
4378
4672
|
// + `rename_session` to pi — the host's own rename block, lifted
|
|
4379
4673
|
// verbatim (the broadcast carries `{ name: name || undefined }`).
|
|
@@ -4479,6 +4773,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4479
4773
|
// Only event types in the plugin's manifest `emits` (live; automation also
|
|
4480
4774
|
// gets its accepted action providers' emits) pass.
|
|
4481
4775
|
// See change: harden-git-terminal-plugin-boundaries (D16).
|
|
4776
|
+
// Rejected plugin_action / plugin-route command counter (/api/health).
|
|
4777
|
+
// See change: update-flows-plugin (task 2.4).
|
|
4778
|
+
recordRejectedPluginAction: () => recordRejectedPluginAction(),
|
|
4482
4779
|
emitEventToSession: (sessionId, eventType, data) =>
|
|
4483
4780
|
pluginEventSeam.emitEventToSession(
|
|
4484
4781
|
(plugin.manifest.priority ?? 1000) <= 100,
|
|
@@ -4572,7 +4869,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4572
4869
|
// the private request lane. Not trust-gated: each is scoped to
|
|
4573
4870
|
// the calling plugin's manifest id. See change:
|
|
4574
4871
|
// expose-plugin-credential-and-oauth-seams (D2, D3, D7).
|
|
4575
|
-
pluginCredentials: (id) =>
|
|
4872
|
+
pluginCredentials: (id) =>
|
|
4873
|
+
createPluginCredentialStore(id, { codec: getCredentialCodec("plugin-credentials") }),
|
|
4576
4874
|
// Declared + user-approved vault reads, bound to this plugin's manifest.
|
|
4577
4875
|
// See change: add-credential-vault (D4).
|
|
4578
4876
|
pluginVault: (id) => createPluginVaultReader(vaultStore, id, plugin.manifest.vaultBindings ?? []),
|
|
@@ -4589,8 +4887,8 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4589
4887
|
});
|
|
4590
4888
|
return res.ok ? { ok: true, flowId: res.flow.id } : res;
|
|
4591
4889
|
},
|
|
4592
|
-
registerPiRequestHandler: (id, type, handler) =>
|
|
4593
|
-
pluginRequestLane.register(id, type, handler),
|
|
4890
|
+
registerPiRequestHandler: (id, type, handler, opts) =>
|
|
4891
|
+
pluginRequestLane.register(id, type, handler, opts),
|
|
4594
4892
|
// First-party scope gate shared with the `/api/plugins` `firstParty`
|
|
4595
4893
|
// projection. See change: promote-model-roles-settings.
|
|
4596
4894
|
providerAuth: createGatedProviderAuth(plugin.packageName, readAuthJson),
|
|
@@ -4700,6 +4998,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4700
4998
|
// path, two transports). See change: add-tailscale-cert-tls (D1).
|
|
4701
4999
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
4702
5000
|
const onUpgrade = (request: import("node:http").IncomingMessage, socket: import("node:stream").Duplex, head: Buffer): void => {
|
|
5001
|
+
// FIRST branch (D3): a preview-shaped Host is served — or refused — by the preview dispatcher, ahead of
|
|
5002
|
+
// the dashboard host gate, Origin gate and ticket. It never reaches the switch below.
|
|
5003
|
+
if (routePreviewUpgrade(previewDispatch, request, socket, head)) return;
|
|
4703
5004
|
// Stamp the local-credential verdict FIRST (before the Host/Origin gates):
|
|
4704
5005
|
// everything below reads it via `hasLocalCredential(request.headers)`.
|
|
4705
5006
|
// The proof floor is per transport: a TLS socket is stamped against the
|
|
@@ -4732,6 +5033,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4732
5033
|
return;
|
|
4733
5034
|
}
|
|
4734
5035
|
|
|
5036
|
+
// Duplicate `pi_dash_*` cookie names: 400 + expiry lines before any Origin gate or ticket (D10).
|
|
5037
|
+
if (refuseDuplicateCookieUpgrade(request, socket)) return;
|
|
5038
|
+
|
|
4735
5039
|
// Access check for WebSocket upgrades
|
|
4736
5040
|
const remoteAddress = request.socket.remoteAddress || "";
|
|
4737
5041
|
// Live admission list per upgrade (empty under `pair`) — NOT the boot
|
|
@@ -4771,7 +5075,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4771
5075
|
})
|
|
4772
5076
|
) {
|
|
4773
5077
|
console.error(
|
|
4774
|
-
|
|
5078
|
+
redactCapability(
|
|
5079
|
+
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
5080
|
+
),
|
|
4775
5081
|
);
|
|
4776
5082
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4777
5083
|
socket.destroy();
|
|
@@ -4816,14 +5122,20 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4816
5122
|
// only WITH a valid capability. See change: retire-trusted-networks-bypass (D5),
|
|
4817
5123
|
// improve-canvas-html-and-url-ux (D10).
|
|
4818
5124
|
const liveCap = scope === "live" ? parseCapabilityPath(request.url) : null;
|
|
4819
|
-
const
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
5125
|
+
const wsLocal = isLocallyTrusted({ ip: remoteAddress, headers: request.headers as Record<string, unknown> });
|
|
5126
|
+
// Tier 5: the same `live` scope, admitted by a valid `/preview/<pid>/` (full path forwarded). D8.
|
|
5127
|
+
const previewWsPath = scope === "live" ? parsePreviewPath(request.url) : null;
|
|
5128
|
+
const previewWsGrant = previewWsPath ? (previewPaths?.validate(previewWsPath.pid, { genuinelyLocal: wsLocal }) ?? null) : null;
|
|
5129
|
+
const liveCapPrincipal = previewWsGrant
|
|
5130
|
+
? previewWsGrant.principal
|
|
5131
|
+
: liveCap
|
|
5132
|
+
? liveCapabilities.validate(liveCap.targetId, liveCap.token, { genuinelyLocal: wsLocal })
|
|
5133
|
+
: null;
|
|
4824
5134
|
if (!isWsOriginTrusted(request.headers.origin, request.headers.host, scope, corsOpts(), liveCapPrincipal !== null)) {
|
|
4825
5135
|
console.error(
|
|
4826
|
-
|
|
5136
|
+
redactCapability(
|
|
5137
|
+
`[ws-gate] rejected upgrade origin=${sanitizeHeaderForLog(request.headers.origin)} scope=${scope ?? "none"} peer=${sanitizeHeaderForLog(remoteAddress)}`,
|
|
5138
|
+
),
|
|
4827
5139
|
);
|
|
4828
5140
|
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
|
|
4829
5141
|
socket.destroy();
|
|
@@ -4885,14 +5197,16 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4885
5197
|
? { identity: liveCapPrincipal.identity, identityExpiresAt: liveCapPrincipal.identityExpiresAt }
|
|
4886
5198
|
: null,
|
|
4887
5199
|
// A revoked / disabled passkey user's cookie opens no socket (D4).
|
|
4888
|
-
isSessionLive: (p) => effectiveSessionTier(p, passkeyService) !== null,
|
|
5200
|
+
isSessionLive: (p) => effectiveSessionTier(p, passkeyService, sessionProviderRejected) !== null,
|
|
5201
|
+
// A ticket minted before its device was revoked opens nothing (D7).
|
|
5202
|
+
isDeviceActive: (id) => pairedDeviceRegistry.activeIds().has(id),
|
|
4889
5203
|
});
|
|
4890
5204
|
// Cookie-session sockets carry the session's LIVE tier (passkey users
|
|
4891
5205
|
// re-read the directory). Terminals need operate, live previews
|
|
4892
5206
|
// control; browser messages are gated per type in the gateway.
|
|
4893
5207
|
// See change: add-passkey-user-auth.
|
|
4894
5208
|
const sessionPayload = upgradeAuth.ok ? upgradeAuth.session : undefined;
|
|
4895
|
-
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService) : undefined;
|
|
5209
|
+
const sessionTierOf = sessionPayload ? () => effectiveSessionTier(sessionPayload, passkeyService, sessionProviderRejected) : undefined;
|
|
4896
5210
|
const roadTier = scope === "terminal" ? TERMINAL_TIER : scope === "live" ? LIVE_PREVIEW_TIER : undefined;
|
|
4897
5211
|
if (sessionTierOf && roadTier) {
|
|
4898
5212
|
const t = sessionTierOf();
|
|
@@ -4978,9 +5292,13 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
4978
5292
|
}
|
|
4979
5293
|
// Locality is decided ONCE here, from the upgrade request; handlers read the bit.
|
|
4980
5294
|
// See change: harden-server-capability-bounds (D1b).
|
|
4981
|
-
stampSocketLocality(ws, request, localTrust);
|
|
5295
|
+
const socketLocal = stampSocketLocality(ws, request, localTrust);
|
|
5296
|
+
// D9: does this socket classify to tier 5? (counted only after the tab's `live_preview_accept`)
|
|
5297
|
+
stampPreviewViewer(ws, request, { genuinelyLocal: socketLocal, resolved: getResolvedPreviewOrigins() });
|
|
4982
5298
|
if (grants) (ws as { bootstrapGrants?: BootstrapGrants }).bootstrapGrants = grants;
|
|
4983
5299
|
if (sessionTierOf) (ws as TieredSocket).sessionTier = sessionTierOf;
|
|
5300
|
+
// Tag with the minting device so `closeDeviceSockets` can find it on revoke (D7).
|
|
5301
|
+
if (upgradeAuth.deviceId) (ws as { deviceId?: string }).deviceId = upgradeAuth.deviceId;
|
|
4984
5302
|
browserGateway.wss.emit("connection", ws, request);
|
|
4985
5303
|
});
|
|
4986
5304
|
if (identityEnforced() && policyRegistry.hasPolicy()) {
|
|
@@ -5015,6 +5333,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5015
5333
|
})
|
|
5016
5334
|
: undefined,
|
|
5017
5335
|
upgradeAuth.principalExpiresAt,
|
|
5336
|
+
sessionTierOf,
|
|
5018
5337
|
),
|
|
5019
5338
|
);
|
|
5020
5339
|
break;
|
|
@@ -5026,10 +5345,12 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5026
5345
|
// Chunked past the 32-bit timer cap (`scheduleAtExpiry`), released on close.
|
|
5027
5346
|
const cancelExpiry = scheduleAtExpiry(upgradeAuth.principalExpiresAt, () => socket.destroy());
|
|
5028
5347
|
socket.once("close", cancelExpiry);
|
|
5348
|
+
if (previewWsGrant && previewWsPath) previewWs.track(previewWsPath.pid, socket);
|
|
5029
5349
|
handleLiveServerUpgrade(liveServerManager, request, socket, head, {
|
|
5030
5350
|
isDeviceBearer: (token, req) => pairedDeviceRegistry.verify(token, bearerChannelOf(req)) !== null,
|
|
5031
5351
|
isKnownBearer: (token) => pairedDeviceRegistry.isKnownBearer(token),
|
|
5032
5352
|
capabilityPrefix: liveCapPrincipal && liveCap ? liveCap.prefix : undefined,
|
|
5353
|
+
...(previewWsGrant ? { previewTargetId: previewWsGrant.targetId } : {}),
|
|
5033
5354
|
});
|
|
5034
5355
|
});
|
|
5035
5356
|
break;
|
|
@@ -5067,6 +5388,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5067
5388
|
}
|
|
5068
5389
|
|
|
5069
5390
|
// The proof floor is taken after readiness, immediately before the bind.
|
|
5391
|
+
await previewDispatch?.ready();
|
|
5070
5392
|
await listenWithProofFloor(fastify, (at) => (httpBoundAt = at), { port: config.port, host: config.host });
|
|
5071
5393
|
const bound = fastify.server.address();
|
|
5072
5394
|
if (bound && typeof bound === "object") httpListenPort = bound.port;
|
|
@@ -5448,6 +5770,11 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5448
5770
|
|
|
5449
5771
|
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: legacy server wiring, grandfathered; decompose in a dedicated refactor, not piecemeal
|
|
5450
5772
|
async stop(opts: { exitIntent?: ExitIntent } = {}) {
|
|
5773
|
+
serverStopping = true;
|
|
5774
|
+
// Committal: refuse new credential work (an OAuth refresh spends a
|
|
5775
|
+
// single-use token) while teardown runs; waited for below.
|
|
5776
|
+
// See change: settle-server-credential-writes-on-exit.
|
|
5777
|
+
exitBarrier.closeGate();
|
|
5451
5778
|
// A clean stop must also disarm the ephemeral watch so a
|
|
5452
5779
|
// create/stop cycle in one process leaves no ticking timer.
|
|
5453
5780
|
ephemeralParentWatch.stop();
|
|
@@ -5485,7 +5812,10 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5485
5812
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
5486
5813
|
// SIGTERMs every dashboard-spawned pi: after this the sessions below are
|
|
5487
5814
|
// GONE and can never reattach.
|
|
5488
|
-
|
|
5815
|
+
// Awaited: restored entries are verified first (bounded 5 s). The stop's
|
|
5816
|
+
// intent decides whether an unverifiable restored pid may be signalled.
|
|
5817
|
+
// See change: guard-restored-headless-identity (D7).
|
|
5818
|
+
await browserGateway.shutdownHeadlessProcesses({ exitIntent: opts.exitIntent ?? "idle" });
|
|
5489
5819
|
// Record `exitIntent` (default "idle") instead of erasing the evidence.
|
|
5490
5820
|
// `stop()` reaches here from the idle timer — the server chose to stop,
|
|
5491
5821
|
// the user closed nothing — so the sessions it just killed stay
|
|
@@ -5518,6 +5848,7 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5518
5848
|
pairingManager.dispose();
|
|
5519
5849
|
stopDeviceExpirySweep();
|
|
5520
5850
|
vaultDelivery.dispose();
|
|
5851
|
+
sudoCredential.dispose();
|
|
5521
5852
|
// Every pending ack holds a timer; a create/stop cycle must not leak them.
|
|
5522
5853
|
// See change: fix-spawn-correlation-ttl-coupling (D7).
|
|
5523
5854
|
pendingPromptAcks.dispose();
|
|
@@ -5558,6 +5889,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5558
5889
|
for (const t of terminalManager.list()) {
|
|
5559
5890
|
try { terminalManager.kill(t.id); } catch {}
|
|
5560
5891
|
}
|
|
5892
|
+
// Wait (bounded, never throws) for in-flight credential writes before the
|
|
5893
|
+
// flows and listeners go away. Adds no delay when nothing is pending.
|
|
5894
|
+
await exitBarrier.settle();
|
|
5561
5895
|
// Abort every in-flight provider OAuth flow (releases callback ports,
|
|
5562
5896
|
// stops device-code polls).
|
|
5563
5897
|
try { const { abortAllFlows } = await import("./auth/provider-auth-adapter.js"); abortAllFlows(); } catch {}
|
|
@@ -5568,6 +5902,9 @@ export async function createServer(config: ServerConfig): Promise<DashboardServe
|
|
|
5568
5902
|
}
|
|
5569
5903
|
// The TLS listener (and its open connections) closes with the server.
|
|
5570
5904
|
try { await tlsListener.stop(); } catch { /* ignore */ }
|
|
5905
|
+
try { await previewDispatch?.close(); } catch { /* ignore */ }
|
|
5906
|
+
try { liveCapabilities.close(); } catch { /* ignore */ }
|
|
5907
|
+
try { await previewPool?.close(); } catch { /* ignore */ }
|
|
5571
5908
|
await fastify.close();
|
|
5572
5909
|
},
|
|
5573
5910
|
};
|