@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.md +85 -11
- package/docs/architecture.md +3020 -116
- package/package.json +31 -18
- package/packages/extension/package.json +10 -8
- package/packages/extension/src/ask-user-tool.ts +65 -3
- package/packages/extension/src/auto-session-namer.ts +190 -50
- package/packages/extension/src/bridge-handlers/dispatch.ts +504 -0
- package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
- package/packages/extension/src/bridge-handlers/instance.ts +229 -0
- package/packages/extension/src/bridge-handlers/lifecycle.ts +1069 -0
- package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
- package/packages/extension/src/bridge-identity-log.ts +45 -0
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +517 -2534
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +259 -16
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +294 -24
- package/packages/extension/src/dashboard-context-injector.ts +26 -47
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/empty-actionable-guard.ts +8 -3
- package/packages/extension/src/flow-event-wiring.ts +1 -1
- package/packages/extension/src/followup-buffer.ts +1 -1
- package/packages/extension/src/followup-drain.ts +79 -0
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +232 -17
- package/packages/extension/src/message-update-coalescer.ts +3 -1
- package/packages/extension/src/model-refresh.ts +88 -0
- package/packages/extension/src/multiselect-list.ts +6 -2
- package/packages/extension/src/multiselect-polyfill.ts +2 -2
- package/packages/extension/src/openspec-cli-shim.ts +1 -1
- package/packages/extension/src/path-gate/decide.ts +15 -41
- package/packages/extension/src/path-gate/grant-cache.ts +3 -1
- package/packages/extension/src/path-gate/handler.ts +51 -2
- package/packages/extension/src/path-gate/index.ts +12 -1
- package/packages/extension/src/path-gate/resolve.ts +6 -124
- package/packages/extension/src/path-gate/roots.ts +4 -1
- package/packages/extension/src/path-gate/suppression.ts +4 -1
- package/packages/extension/src/path-gate/yolo-link.ts +104 -0
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +258 -25
- package/packages/extension/src/prompt-expander.ts +5 -1
- package/packages/extension/src/prompt-meta.ts +64 -0
- package/packages/extension/src/provider-register.ts +146 -38
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-manager.ts +5 -4
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +13 -6
- package/packages/extension/src/server-launcher.ts +11 -13
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-move.ts +19 -0
- package/packages/extension/src/session-sync.ts +73 -50
- package/packages/extension/src/spawn-token.ts +46 -0
- package/packages/extension/src/stream-forward-buffer.ts +161 -0
- package/packages/extension/src/subagent-frame-buffer.ts +6 -2
- package/packages/extension/src/subagent-tick-throttle.ts +3 -1
- package/packages/extension/src/vault-delivery.ts +404 -0
- package/packages/extension/src/vault-forwarder.ts +128 -0
- package/packages/extension/src/vault-masker.ts +165 -0
- package/packages/extension/src/vault-redaction.ts +181 -0
- package/packages/extension/src/vcs-info.ts +5 -2
- package/packages/server/bin/pi-dashboard.mjs +26 -89
- package/packages/server/package.json +29 -15
- package/packages/server/src/access/access-grants.ts +79 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- package/packages/server/src/access/agent-confirm-registry.ts +31 -13
- package/packages/server/src/access/agent-grant.ts +1 -1
- package/packages/server/src/access/agent-yolo.ts +91 -0
- package/packages/server/src/access/containment-gate.ts +82 -17
- package/packages/server/src/access/cwd-admission-log.ts +46 -0
- package/packages/server/src/access/cwd-verdict.ts +144 -0
- package/packages/server/src/access/grant-coordinator.ts +3 -1
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +407 -0
- package/packages/server/src/access/planes.ts +116 -2
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/refusal-ledger.ts +6 -6
- package/packages/server/src/access/yolo-session.ts +127 -14
- package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
- package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +549 -0
- package/packages/server/src/acp-bridge/child-env.ts +73 -0
- package/packages/server/src/acp-bridge/event-log.ts +194 -0
- package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
- package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
- package/packages/server/src/acp-bridge/local-host.ts +132 -0
- package/packages/server/src/acp-bridge/main.ts +118 -0
- package/packages/server/src/acp-bridge/models.ts +33 -0
- package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
- package/packages/server/src/acp-bridge/server-requests.ts +136 -0
- package/packages/server/src/acp-bridge/session-state.ts +127 -0
- package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
- package/packages/server/src/addons/addons-catalog.ts +408 -0
- package/packages/server/src/addons/addons-folder-service.ts +347 -0
- package/packages/server/src/addons/addons-folder.ts +310 -0
- package/packages/server/src/addons/addons-service.ts +470 -0
- package/packages/server/src/addons/package-contents.ts +99 -0
- package/packages/server/src/addons/settings-entries.ts +120 -0
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
- package/packages/server/src/auth/approval-refusal.ts +87 -0
- package/packages/server/src/auth/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +329 -97
- package/packages/server/src/auth/auth.ts +102 -11
- package/packages/server/src/auth/bearer-auth.ts +74 -12
- package/packages/server/src/auth/cors-origin.ts +86 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +111 -9
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/host-admission.ts +26 -0
- package/packages/server/src/auth/host-gate.ts +6 -1
- package/packages/server/src/auth/local-credential.ts +258 -0
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +76 -22
- package/packages/server/src/auth/local-token.ts +16 -0
- package/packages/server/src/auth/localhost-guard.ts +298 -17
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
- package/packages/server/src/auth/node-guard.ts +43 -0
- package/packages/server/src/auth/operate-required.ts +126 -0
- package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +109 -0
- package/packages/server/src/auth/passkey/passkey-routes.ts +232 -0
- package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
- package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
- package/packages/server/src/auth/passkey/requester.ts +83 -0
- package/packages/server/src/auth/passkey/rp-context.ts +98 -0
- package/packages/server/src/auth/passkey/user-directory.ts +348 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +324 -0
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-registry.ts +35 -1
- package/packages/server/src/auth/provider-auth-storage.ts +61 -9
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/radius-override.ts +13 -0
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/route-tier-gate.ts +27 -11
- package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
- package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +197 -0
- package/packages/server/src/auth/trust-mode-boot.ts +93 -0
- package/packages/server/src/auth/trust-mode.ts +83 -0
- package/packages/server/src/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/auto-name-outcome-store.ts +4 -1
- package/packages/server/src/browse.ts +114 -2
- package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
- package/packages/server/src/browser-handlers/directory-handler.ts +151 -6
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +138 -63
- package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
- package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
- package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +1063 -106
- package/packages/server/src/config-api.ts +166 -2
- package/packages/server/src/config-snapshot.ts +53 -1
- package/packages/server/src/directory-service.ts +545 -36
- package/packages/server/src/embed-lifecycle/caps.ts +35 -4
- package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
- package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
- package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
- package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
- package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
- package/packages/server/src/event-wiring.ts +349 -141
- package/packages/server/src/file-watch-manager.ts +187 -39
- package/packages/server/src/git-worktree/git-operations.ts +60 -15
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +91 -6
- package/packages/server/src/git-worktree/worktree-init.ts +7 -56
- package/packages/server/src/identity/host-resources.ts +3 -0
- package/packages/server/src/identity/http-road-classification.ts +31 -1
- package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
- package/packages/server/src/identity/plugin-identity.ts +19 -0
- package/packages/server/src/identity/policy-registry.ts +4 -1
- package/packages/server/src/identity/resolver-registry.ts +12 -3
- package/packages/server/src/identity/ws-message-scope.ts +10 -0
- package/packages/server/src/identity/ws-road-classification.ts +10 -0
- package/packages/server/src/known-server-moves.ts +196 -0
- package/packages/server/src/lib/browse-roots.ts +137 -0
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/digest-gate.ts +82 -0
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/file-write-lock.ts +24 -0
- package/packages/server/src/lib/folder-project.ts +439 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/purify.ts +13 -5
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-handler-target.ts +66 -0
- package/packages/server/src/lib/writable-md-target.ts +16 -1
- package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
- package/packages/server/src/lifecycle/home-lock.ts +344 -130
- package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
- package/packages/server/src/lifecycle/recovery-server.ts +129 -6
- package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +461 -0
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +326 -34
- package/packages/server/src/live-server/live-static.ts +228 -0
- package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
- package/packages/server/src/model-proxy/internal-registry.ts +6 -0
- package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +111 -16
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +189 -11
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +126 -35
- package/packages/server/src/openspec/openspec-poll-worker.ts +286 -44
- package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
- package/packages/server/src/openspec/readiness.ts +9 -0
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +1002 -0
- package/packages/server/src/package/installed-package-enricher.ts +38 -3
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/package-health-scanner.ts +133 -0
- package/packages/server/src/package/package-manager-wrapper.ts +18 -2
- package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
- package/packages/server/src/package/provider-probe.ts +13 -5
- package/packages/server/src/pairing/browser-gateway.ts +292 -16
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/knock-admission.ts +277 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +188 -31
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
- package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
- package/packages/server/src/peer-servers.ts +77 -0
- package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
- package/packages/server/src/persistence/boot-state.ts +48 -1
- package/packages/server/src/persistence/memory-event-store.ts +216 -237
- package/packages/server/src/persistence/meta-persistence.ts +12 -1
- package/packages/server/src/persistence/preferences-store.ts +125 -7
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +48 -22
- package/packages/server/src/pi/folder-commands.ts +141 -0
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
- package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
- package/packages/server/src/pi/host-project-trust.ts +166 -33
- package/packages/server/src/pi/pi-gateway.ts +283 -29
- package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
- package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
- package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
- package/packages/server/src/pi/session-skill-registry.ts +13 -3
- package/packages/server/src/pi/settings-write-lock.ts +32 -0
- package/packages/server/src/pi/trust-challenges.ts +38 -0
- package/packages/server/src/pi-agent-settings.ts +701 -100
- package/packages/server/src/pi-settings-themes.ts +104 -0
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/questions/brief-generator.ts +138 -0
- package/packages/server/src/questions/brief-model.ts +55 -0
- package/packages/server/src/questions/brief-policy.ts +36 -0
- package/packages/server/src/questions/brief-prompt.ts +92 -0
- package/packages/server/src/questions/brief-runtime.ts +50 -0
- package/packages/server/src/questions/question-answer.ts +55 -0
- package/packages/server/src/questions/question-broadcast.ts +106 -0
- package/packages/server/src/questions/question-files.ts +128 -0
- package/packages/server/src/questions/question-routes.ts +126 -0
- package/packages/server/src/questions/question-snapshot.ts +150 -0
- package/packages/server/src/questions/question-stack.ts +57 -0
- package/packages/server/src/questions/question-store.ts +477 -0
- package/packages/server/src/routes/access-prompt-routes.ts +5 -3
- package/packages/server/src/routes/access-routes.ts +274 -6
- package/packages/server/src/routes/acme-routes.ts +190 -0
- package/packages/server/src/routes/acp-routes.ts +16 -0
- package/packages/server/src/routes/addons-routes.ts +221 -0
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +620 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +530 -0
- package/packages/server/src/routes/folder-project-routes.ts +105 -0
- package/packages/server/src/routes/git-routes.ts +334 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +433 -55
- package/packages/server/src/routes/live-server-routes.ts +438 -7
- package/packages/server/src/routes/local-proof-routes.ts +26 -7
- package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
- package/packages/server/src/routes/model-proxy-routes.ts +4 -2
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +636 -55
- package/packages/server/src/routes/package-health-routes.ts +140 -0
- package/packages/server/src/routes/package-routes.ts +86 -11
- package/packages/server/src/routes/pairing-routes.ts +303 -33
- package/packages/server/src/routes/pi-retry-routes.ts +18 -2
- package/packages/server/src/routes/pi-settings-routes.ts +264 -0
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +146 -27
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +37 -7
- package/packages/server/src/routes/provider-routes.ts +29 -0
- package/packages/server/src/routes/resource-activation-routes.ts +33 -35
- package/packages/server/src/routes/session-routes.ts +100 -9
- package/packages/server/src/routes/system-routes.ts +286 -33
- package/packages/server/src/routes/tls-routes.ts +55 -0
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/routes/user-routes.ts +192 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
- package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
- package/packages/server/src/server.ts +1537 -246
- package/packages/server/src/services/attached-driver.ts +175 -0
- package/packages/server/src/services/change-notifier.ts +55 -0
- package/packages/server/src/services/cli-service.ts +450 -0
- package/packages/server/src/services/command-runner.ts +92 -0
- package/packages/server/src/services/definitions-store.ts +121 -0
- package/packages/server/src/services/driver.ts +112 -0
- package/packages/server/src/services/health.ts +94 -0
- package/packages/server/src/services/leases.ts +117 -0
- package/packages/server/src/services/log-text.ts +97 -0
- package/packages/server/src/services/native-driver.ts +283 -0
- package/packages/server/src/services/oci-driver.ts +590 -0
- package/packages/server/src/services/output-capture.ts +183 -0
- package/packages/server/src/services/paths.ts +82 -0
- package/packages/server/src/services/ports.ts +26 -0
- package/packages/server/src/services/routes.ts +140 -0
- package/packages/server/src/services/runtime-detect.ts +108 -0
- package/packages/server/src/services/secret-delivery.ts +61 -0
- package/packages/server/src/services/secrets-resolver.ts +145 -0
- package/packages/server/src/services/secrets-store.ts +137 -0
- package/packages/server/src/services/service-manager.ts +1565 -0
- package/packages/server/src/services/start-record.ts +66 -0
- package/packages/server/src/services/state-machine.ts +241 -0
- package/packages/server/src/session/archive-sweeper.ts +92 -3
- package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
- package/packages/server/src/session/memory-session-manager.ts +60 -0
- package/packages/server/src/session/name-provenance.ts +102 -0
- package/packages/server/src/session/open-tool-calls.ts +15 -6
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/session-api.ts +47 -12
- package/packages/server/src/session/session-archive.ts +56 -4
- package/packages/server/src/session/session-diff-cache.ts +11 -4
- package/packages/server/src/session/session-load-worker-pool.ts +4 -3
- package/packages/server/src/session/session-load-worker.ts +11 -2
- package/packages/server/src/session/session-scanner.ts +73 -3
- package/packages/server/src/session/session-to-meta.ts +15 -0
- package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
- package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
- package/packages/server/src/spawn-process/process-manager.ts +164 -30
- package/packages/server/src/spawn-process/restart-helper.ts +9 -8
- package/packages/server/src/spawn-process/server-pid.ts +16 -7
- package/packages/server/src/spawn-process/session-terminator.ts +218 -0
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
- package/packages/server/src/terminal/terminal-manager.ts +75 -1
- package/packages/server/src/tls/cert-files.ts +228 -0
- package/packages/server/src/tls/cert-manager.ts +703 -0
- package/packages/server/src/tls/cert-store.ts +69 -0
- package/packages/server/src/tls/source-registry.ts +71 -0
- package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
- package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
- package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
- package/packages/server/src/tls/sources/acme/dns.ts +303 -0
- package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
- package/packages/server/src/tls/sources/acme/entry.ts +180 -0
- package/packages/server/src/tls/sources/acme/gc.ts +78 -0
- package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
- package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
- package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
- package/packages/server/src/tls/sources/acme/types.ts +72 -0
- package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +94 -0
- package/packages/server/src/tls/tls-listener.ts +351 -0
- package/packages/server/src/tls/types.ts +80 -0
- package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
- package/packages/server/src/tunnel/tunnel-core.ts +4 -1
- package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
- package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-bindings.ts +101 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +424 -0
- package/packages/server/src/vault/vault-grants.ts +260 -0
- package/packages/server/src/vault/vault-import.ts +161 -0
- package/packages/server/src/vault/vault-permissions.ts +39 -0
- package/packages/server/src/vault/vault-plugin-read.ts +64 -0
- package/packages/server/src/vault/vault-projects.ts +156 -0
- package/packages/server/src/vault/vault-routes.ts +277 -0
- package/packages/server/src/vault/vault-store.ts +371 -0
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/shared/package.json +5 -2
- package/packages/shared/src/acp/acp-config.ts +123 -0
- package/packages/shared/src/acp/normalize-v1.ts +92 -0
- package/packages/shared/src/acp/paths.ts +36 -0
- package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
- package/packages/shared/src/acp/update-model.ts +574 -0
- package/packages/shared/src/anthropic-messages-source.ts +8 -0
- package/packages/shared/src/bind-reachability.ts +21 -2
- package/packages/shared/src/boot-state.ts +6 -0
- package/packages/shared/src/browser-host-identity.ts +49 -0
- package/packages/shared/src/browser-host-ipc.ts +107 -0
- package/packages/shared/src/browser-protocol.ts +533 -73
- package/packages/shared/src/canonical-subject.ts +27 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/card-sections.ts +185 -1
- package/packages/shared/src/chrome-profiles.ts +188 -0
- package/packages/shared/src/config.ts +817 -51
- package/packages/shared/src/containment-guard.ts +35 -0
- package/packages/shared/src/custom-event-groups.ts +5 -2
- package/packages/shared/src/cwd-guard.ts +381 -1
- package/packages/shared/src/dashboard-paths.ts +12 -0
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +73 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +9 -3
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +160 -3
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
- package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +139 -2
- package/packages/shared/src/dashboard-plugin/slot-types.ts +72 -4
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +50 -3
- package/packages/shared/src/dashboard-starter.ts +30 -0
- package/packages/shared/src/display-name.ts +42 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +119 -134
- package/packages/shared/src/enabled-models-match.ts +47 -0
- package/packages/shared/src/event-forward-declaration.ts +187 -0
- package/packages/shared/src/file-kind.ts +54 -2
- package/packages/shared/src/git-worktree-helpers.ts +8 -4
- package/packages/shared/src/grammar-types.ts +3 -1
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/host-port.ts +34 -0
- package/packages/shared/src/launcher-origin.ts +26 -0
- package/packages/shared/src/live-server.ts +141 -0
- package/packages/shared/src/local-credential-proof.ts +219 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
- package/packages/shared/src/markup-repair/types.ts +13 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/md-table-cell.ts +11 -0
- package/packages/shared/src/mdns-discovery.ts +414 -45
- package/packages/shared/src/models-json-reader.ts +6 -0
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-design-evidence.ts +25 -1
- package/packages/shared/src/openspec-poller.ts +213 -11
- package/packages/shared/src/openspec-status-all.ts +393 -0
- package/packages/shared/src/operate-required.ts +29 -0
- package/packages/shared/src/pairing-knock-client.ts +301 -0
- package/packages/shared/src/pairing-knock.ts +71 -0
- package/packages/shared/src/pairing-refusal.ts +32 -0
- package/packages/shared/src/path-containment-guard-name.ts +8 -0
- package/packages/shared/src/pi-settings-keys.ts +9 -0
- package/packages/shared/src/pi-settings-schema.ts +285 -0
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +198 -0
- package/packages/shared/src/pi-trust-mirror-types.ts +90 -0
- package/packages/shared/src/pi-trust-mirror.ts +354 -0
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/binary-lookup.ts +2 -194
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +210 -4
- package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
- package/packages/shared/src/platform/native-ts-register.mjs +22 -10
- package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
- package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
- package/packages/shared/src/platform/node-spawn.ts +1 -2
- package/packages/shared/src/platform/openspec.ts +129 -31
- package/packages/shared/src/platform/process-scan.ts +199 -1
- package/packages/shared/src/platform/process.ts +99 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/runner.ts +46 -2
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
- package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
- package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
- package/packages/shared/src/plugin-bridge-register.ts +24 -1
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-name.ts +42 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/prompt-answer.ts +183 -0
- package/packages/shared/src/protocol.ts +172 -8
- package/packages/shared/src/question-types.ts +73 -0
- package/packages/shared/src/recommended-extensions.ts +98 -23
- package/packages/shared/src/recovery-timing.ts +39 -0
- package/packages/shared/src/redaction.ts +50 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +533 -3
- package/packages/shared/src/role-config-disk.ts +23 -0
- package/packages/shared/src/role-schema.ts +79 -0
- package/packages/shared/src/route-tiers.ts +181 -0
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
- package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-identity.ts +51 -15
- package/packages/shared/src/server-launcher.ts +21 -34
- package/packages/shared/src/server-pinning.ts +136 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/services/offers.ts +114 -0
- package/packages/shared/src/services/schema.ts +628 -0
- package/packages/shared/src/services/status.ts +169 -0
- package/packages/shared/src/session-meta.ts +59 -2
- package/packages/shared/src/session-name.ts +8 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/skill-block-parser.ts +14 -0
- package/packages/shared/src/source-matching.ts +5 -1
- package/packages/shared/src/state-replay.ts +19 -0
- package/packages/shared/src/terminal-safe.ts +24 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tls-status.ts +69 -0
- package/packages/shared/src/tool-path-resolve.ts +243 -0
- package/packages/shared/src/tool-registry/definitions.ts +31 -9
- package/packages/shared/src/tool-registry/index.ts +2 -2
- package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
- package/packages/shared/src/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/tunnel-provider.ts +3 -2
- package/packages/shared/src/types.ts +170 -9
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +88 -0
- package/packages/shared/src/vault-origin.ts +51 -0
- package/packages/shared/src/vault-project-key.ts +53 -0
- package/packages/shared/src/worktree-init-hook.ts +69 -0
- package/packages/shared/src/ws-message-tiers.ts +136 -0
- package/tsconfig.base.json +1 -0
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* Reverse proxy for live-server-preview targets, on the MAIN origin at
|
|
3
3
|
* `/live/:id/*` (mirrors `editor-proxy`'s `/editor/:id/*`). Same-origin path
|
|
4
4
|
* proxy so it survives the single-port remote tunnel (zrok). The client frames
|
|
5
|
-
* it with `sandbox="allow-scripts
|
|
6
|
-
* D7), so the embedded app cannot
|
|
5
|
+
* it with `sandbox="allow-scripts allow-forms allow-popups allow-downloads"`
|
|
6
|
+
* and NO `allow-same-origin` (opaque origin, D7), so the embedded app cannot
|
|
7
|
+
* read the dashboard token or call its APIs.
|
|
7
8
|
*
|
|
8
9
|
* The proxy ONLY forwards to targets the manager already validated as loopback
|
|
9
10
|
* (SSRF gate lives in `validateLiveTarget`); an unregistered id → 404.
|
|
@@ -11,15 +12,180 @@
|
|
|
11
12
|
* See change: improve-content-editor (live-server-preview §6).
|
|
12
13
|
*/
|
|
13
14
|
import net from "node:net";
|
|
14
|
-
import type {
|
|
15
|
+
import type { LiveServerTarget, StaticTarget } from "@blackbelt-technology/pi-dashboard-shared/live-server.js";
|
|
16
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
|
17
|
+
import { isBrowserOriginated } from "./live-browser-gate.js";
|
|
18
|
+
import { type LiveCapabilityGrant, stripCapabilitySegment } from "./live-capability.js";
|
|
19
|
+
import { buildLiveCsp, type LiveCspResult } from "./live-csp.js";
|
|
20
|
+
import { registerCspReportParsers } from "./live-csp-report.js";
|
|
15
21
|
import type { LiveServerManager } from "./live-server-manager.js";
|
|
22
|
+
import { serveStatic } from "./live-static.js";
|
|
23
|
+
|
|
24
|
+
/** Dashboard cookie namespace (`pi_dash_token`, `pi_dash_device`, `pi_dash_local`, …). */
|
|
25
|
+
const DASHBOARD_COOKIE_PREFIX = "pi_dash_";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Remove every dashboard cookie from a `Cookie` header value. Returns `undefined`
|
|
29
|
+
* when nothing remains (the header is then dropped), otherwise the remaining
|
|
30
|
+
* pairs byte-for-byte so the previewed app keeps its own session.
|
|
31
|
+
*/
|
|
32
|
+
function stripDashboardCookies(cookie: string): string | undefined {
|
|
33
|
+
const kept = cookie
|
|
34
|
+
.split(";")
|
|
35
|
+
.map((pair) => pair.trim())
|
|
36
|
+
.filter((pair) => pair.length > 0 && !pair.toLowerCase().startsWith(DASHBOARD_COOKIE_PREFIX));
|
|
37
|
+
return kept.length > 0 ? kept.join("; ") : undefined;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Drop upstream `Set-Cookie` lines that name a dashboard cookie (no planting/overwriting). */
|
|
41
|
+
function filterSetCookie(value: string | string[] | undefined): string[] | undefined {
|
|
42
|
+
if (value === undefined) return undefined;
|
|
43
|
+
const list = Array.isArray(value) ? value : [value];
|
|
44
|
+
const kept = list.filter((line) => !line.trim().toLowerCase().startsWith(DASHBOARD_COOKIE_PREFIX));
|
|
45
|
+
return kept.length === 0 ? undefined : kept;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** A request/upgrade header bag the credential stripper edits in place. */
|
|
49
|
+
type HeaderBag = Record<string, unknown>;
|
|
50
|
+
|
|
51
|
+
/** The request shape the channel classifier reads (`socket.encrypted` + headers). */
|
|
52
|
+
type ProxyRequestLike = Pick<import("node:http").IncomingMessage, "socket" | "headers">;
|
|
53
|
+
type DeviceBearerCheck = (token: string, req: ProxyRequestLike | undefined) => boolean;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Strip dashboard credentials from headers bound for the preview upstream:
|
|
57
|
+
* every `pi_dash_*` cookie, and an `Authorization` header that verifies as a
|
|
58
|
+
* dashboard device bearer. Everything else is kept (the app's own session).
|
|
59
|
+
*/
|
|
60
|
+
function stripDashboardCredentials(
|
|
61
|
+
headers: HeaderBag,
|
|
62
|
+
isDeviceBearer: DeviceBearerCheck,
|
|
63
|
+
req: ProxyRequestLike | undefined,
|
|
64
|
+
isKnownBearer: (token: string) => boolean,
|
|
65
|
+
): HeaderBag {
|
|
66
|
+
const cookie = headers.cookie;
|
|
67
|
+
if (typeof cookie === "string") {
|
|
68
|
+
const remaining = stripDashboardCookies(cookie);
|
|
69
|
+
if (remaining === undefined) delete headers.cookie;
|
|
70
|
+
else headers.cookie = remaining;
|
|
71
|
+
}
|
|
72
|
+
const authz = headers.authorization;
|
|
73
|
+
if (typeof authz === "string") {
|
|
74
|
+
const m = /^Bearer\s+(.+)$/i.exec(authz.trim());
|
|
75
|
+
// Device bearers and the host's own operator (`pi_op_`) bearer are dashboard credentials.
|
|
76
|
+
// `isDeviceBearer` judges (and records the channel of) the request; `isKnownBearer` then strips EVERY
|
|
77
|
+
// registry-known bearer, so a refused `pi_tls_` bearer is never forwarded off-hub.
|
|
78
|
+
// See change: prove-vault-bridge-tls (D4).
|
|
79
|
+
if (m && (isDeviceBearer(m[1], req) || isKnownBearer(m[1]) || m[1].startsWith("pi_op_"))) delete headers.authorization;
|
|
80
|
+
}
|
|
81
|
+
return headers;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Keep an upstream redirect inside the proxied prefix (`/live/<id>` or the
|
|
86
|
+
* capability prefix). A relative or root-relative `Location` is prefixed; an
|
|
87
|
+
* absolute redirect back to the SAME upstream (`http://127.0.0.1:<port>/…`) is
|
|
88
|
+
* rewritten into the prefix so the browser stays on the dashboard origin and the
|
|
89
|
+
* single-port tunnel keeps working. Foreign absolute redirects are untouched.
|
|
90
|
+
*/
|
|
91
|
+
function rewriteLocation(location: string, prefix: string, host: string, port: number): string {
|
|
92
|
+
const relative = location.startsWith("./") ? `${prefix}/${location.slice(2)}` : location.startsWith("/") ? `${prefix}${location}` : null;
|
|
93
|
+
if (relative !== null) return staysInside(relative, prefix) ? relative : `${prefix}/`;
|
|
94
|
+
try {
|
|
95
|
+
const u = new URL(location);
|
|
96
|
+
if (u.hostname === host && u.port === String(port)) {
|
|
97
|
+
const rewritten = `${prefix}${u.pathname}${u.search}`;
|
|
98
|
+
return staysInside(rewritten, prefix) ? rewritten : `${prefix}/`;
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
/* not an absolute URL — leave as-is */
|
|
102
|
+
}
|
|
103
|
+
return location;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Does `path` still resolve inside `prefix` once a browser applies RFC 3986
|
|
108
|
+
* dot-segment removal (WHATWG `URL` does, including `%2e`)? A redirect that
|
|
109
|
+
* climbs out (`./../x`, `/%2e%2e/api`) must not leave the capability/target prefix.
|
|
110
|
+
*/
|
|
111
|
+
function staysInside(path: string, prefix: string): boolean {
|
|
112
|
+
try {
|
|
113
|
+
const resolved = new URL(path.replace(/\\/g, "/"), "http://x").pathname;
|
|
114
|
+
return resolved === prefix || resolved.startsWith(`${prefix}/`);
|
|
115
|
+
} catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface LiveProxyDeps {
|
|
121
|
+
/**
|
|
122
|
+
* Does this token verify as a dashboard device bearer on THIS request's channel? Absent ⇒ never
|
|
123
|
+
* strip `Authorization`. Receives the request so the registry can record a non-proven channel.
|
|
124
|
+
*/
|
|
125
|
+
isDeviceBearer?: DeviceBearerCheck;
|
|
126
|
+
/** Is this token ANY bearer the registry knows (valid, expired or refused)? Always stripped. */
|
|
127
|
+
isKnownBearer?: (token: string) => boolean;
|
|
128
|
+
/**
|
|
129
|
+
* The raw file-read gate for a static target's real path, re-run on EVERY static
|
|
130
|
+
* request. Absent ⇒ static targets serve nothing (fail closed).
|
|
131
|
+
*/
|
|
132
|
+
staticGate?: (cwd: string, absPath: string) => Promise<boolean>;
|
|
133
|
+
/**
|
|
134
|
+
* Granted egress origins `<G>` for a token's CSP: project grants ∪ the viewer's
|
|
135
|
+
* allow-once set. Absent ⇒ none.
|
|
136
|
+
*/
|
|
137
|
+
grantedOrigins?: (grant: LiveCapabilityGrant) => readonly string[];
|
|
138
|
+
/** An HTML document of a static target was served under this token (feeds the lazy origin scan). */
|
|
139
|
+
onStaticHtmlServed?: (grant: LiveCapabilityGrant, realPath: string) => void;
|
|
140
|
+
/**
|
|
141
|
+
* Handler for the reserved `/__pi/…` namespace under a valid capability prefix
|
|
142
|
+
* (CSP reports, …). It is never forwarded upstream and never served from disk;
|
|
143
|
+
* absent ⇒ 404. Return the reply you sent.
|
|
144
|
+
*/
|
|
145
|
+
reservedHandler?: (
|
|
146
|
+
request: FastifyRequest,
|
|
147
|
+
reply: FastifyReply,
|
|
148
|
+
ctx: { grant: LiveCapabilityGrant; subPath: string },
|
|
149
|
+
) => Promise<FastifyReply> | FastifyReply;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** `/__pi` as a whole path segment (the reserved namespace under a capability prefix). */
|
|
153
|
+
const isReservedPath = (subPath: string): boolean => {
|
|
154
|
+
const q = subPath.search(/[?#]/);
|
|
155
|
+
const p = q >= 0 ? subPath.slice(0, q) : subPath;
|
|
156
|
+
return p === "/__pi" || p.startsWith("/__pi/");
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** The scheme the dashboard is reached on, as far as this hop can tell. `http` is the safe default (`http://` matches https too). */
|
|
160
|
+
const schemeOf = (request: FastifyRequest): "http" | "https" => (request.protocol === "https" ? "https" : "http");
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* APPEND our CSP (and `Reporting-Endpoints` entry) to the upstream's response headers —
|
|
164
|
+
* never replacing or stripping the upstream's: browsers enforce every header, so the
|
|
165
|
+
* result is the stricter intersection.
|
|
166
|
+
*/
|
|
167
|
+
function appendCsp(headers: Record<string, unknown>, csp: LiveCspResult): void {
|
|
168
|
+
const upstreamCsp = headers["content-security-policy"];
|
|
169
|
+
const existing = upstreamCsp === undefined ? [] : Array.isArray(upstreamCsp) ? upstreamCsp : [upstreamCsp];
|
|
170
|
+
headers["content-security-policy"] = [...existing, csp.csp];
|
|
171
|
+
if (!csp.reportingEndpoints) return;
|
|
172
|
+
const re = headers["reporting-endpoints"];
|
|
173
|
+
headers["reporting-endpoints"] =
|
|
174
|
+
typeof re === "string" && re.length > 0 ? `${re}, ${csp.reportingEndpoints}` : csp.reportingEndpoints;
|
|
175
|
+
}
|
|
16
176
|
|
|
17
177
|
/** localhost/::1 resolve to 127.0.0.1 for the upstream TCP connect. */
|
|
18
178
|
function upstreamHost(host: string): string {
|
|
19
179
|
return host === "::1" ? "::1" : "127.0.0.1";
|
|
20
180
|
}
|
|
21
181
|
|
|
22
|
-
export function registerLiveServerProxy(
|
|
182
|
+
export function registerLiveServerProxy(
|
|
183
|
+
fastify: FastifyInstance,
|
|
184
|
+
manager: LiveServerManager,
|
|
185
|
+
deps: LiveProxyDeps = {},
|
|
186
|
+
) {
|
|
187
|
+
const isDeviceBearer = deps.isDeviceBearer ?? (() => false);
|
|
188
|
+
const isKnownBearer = deps.isKnownBearer ?? (() => false);
|
|
23
189
|
// Register the `@fastify/reply-from` proxy plugin. live-server-proxy is now
|
|
24
190
|
// the SOLE consumer of the `from` decorator — the editor proxy that used to
|
|
25
191
|
// provide it was deleted in change: remove-external-editor-integration, which
|
|
@@ -27,85 +193,211 @@ export function registerLiveServerProxy(fastify: FastifyInstance, manager: LiveS
|
|
|
27
193
|
// `/live/:id/*`. Owning the dependency here keeps the proxy self-contained.
|
|
28
194
|
// See change: improve-content-editor, fix-live-server-proxy-reply-from.
|
|
29
195
|
fastify.register(import("@fastify/reply-from"));
|
|
196
|
+
// CSP reports arrive as `application/csp-report` / `application/reports+json`.
|
|
197
|
+
if (deps.reservedHandler) registerCspReportParsers(fastify);
|
|
30
198
|
|
|
31
|
-
|
|
199
|
+
/**
|
|
200
|
+
* `capabilityPrefix` is set (by the capability hook, only after the token
|
|
201
|
+
* validated) when the request arrived under `/live/<id>/~c/<token>/`: that
|
|
202
|
+
* exact segment is removed from the upstream path and kept in redirects.
|
|
203
|
+
*/
|
|
204
|
+
function resolve(url: string, capabilityPrefix?: string) {
|
|
32
205
|
const match = url.match(/^\/live\/([^/?]+)(.*)$/);
|
|
33
206
|
if (!match) return null;
|
|
34
|
-
|
|
35
|
-
if (
|
|
36
|
-
const rest = match[2] || "";
|
|
207
|
+
let rest = match[2] || "";
|
|
208
|
+
if (capabilityPrefix && url.startsWith(capabilityPrefix)) rest = url.slice(capabilityPrefix.length);
|
|
37
209
|
const subPath = rest.startsWith("?") ? `/${rest}` : rest.startsWith("/") ? rest : "/";
|
|
38
|
-
return {
|
|
210
|
+
return { id: match[1], subPath };
|
|
39
211
|
}
|
|
40
212
|
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
213
|
+
/** CSP for a capability response, or `null` (fail closed) when no safe header can be built. */
|
|
214
|
+
function cspFor(request: FastifyRequest, grant: LiveCapabilityGrant, prefix: string): LiveCspResult | null {
|
|
215
|
+
const host = request.headers.host;
|
|
216
|
+
if (typeof host !== "string") return null;
|
|
217
|
+
let granted: readonly string[] = [];
|
|
218
|
+
try {
|
|
219
|
+
granted = deps.grantedOrigins?.(grant) ?? [];
|
|
220
|
+
} catch {
|
|
221
|
+
granted = []; // a failing grant lookup must not widen the policy
|
|
45
222
|
}
|
|
46
|
-
|
|
47
|
-
|
|
223
|
+
return buildLiveCsp({ policy: grant.policy, host, scheme: schemeOf(request), prefix, granted });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const notFoundReply = (reply: FastifyReply) => reply.code(404).send({ error: "live-server target not found" });
|
|
227
|
+
|
|
228
|
+
/** A static target, reachable ONLY through a valid capability, by any caller. */
|
|
229
|
+
const forwardStatic = (
|
|
230
|
+
request: FastifyRequest,
|
|
231
|
+
reply: FastifyReply,
|
|
232
|
+
target: StaticTarget,
|
|
233
|
+
subPath: string,
|
|
234
|
+
grant: LiveCapabilityGrant | undefined,
|
|
235
|
+
capabilityPrefix: string | undefined,
|
|
236
|
+
) => {
|
|
237
|
+
if (!grant || !capabilityPrefix) return notFoundReply(reply);
|
|
238
|
+
if (isReservedPath(subPath)) return reservedOr404(request, reply, grant, subPath);
|
|
239
|
+
const csp = cspFor(request, grant, capabilityPrefix);
|
|
240
|
+
if (!csp) return notFoundReply(reply);
|
|
241
|
+
manager.use(target.id);
|
|
242
|
+
const extra: Record<string, string> = { "content-security-policy": csp.csp };
|
|
243
|
+
if (csp.reportingEndpoints) extra["reporting-endpoints"] = csp.reportingEndpoints;
|
|
244
|
+
return serveStatic(request, reply, target, subPath, extra, {
|
|
245
|
+
gate: deps.staticGate ?? (async () => false),
|
|
246
|
+
onHtmlServed: (real) => deps.onStaticHtmlServed?.(grant, real),
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const forwardPort = (
|
|
251
|
+
request: FastifyRequest,
|
|
252
|
+
reply: FastifyReply,
|
|
253
|
+
target: LiveServerTarget,
|
|
254
|
+
subPath: string,
|
|
255
|
+
grant: LiveCapabilityGrant | undefined,
|
|
256
|
+
capabilityPrefix: string | undefined,
|
|
257
|
+
) => {
|
|
258
|
+
if (grant && isReservedPath(subPath)) return reservedOr404(request, reply, grant, subPath);
|
|
259
|
+
const csp = grant && capabilityPrefix ? cspFor(request, grant, capabilityPrefix) : null;
|
|
260
|
+
// A capability response without a buildable CSP would be less isolated than promised.
|
|
261
|
+
if (grant && !csp) return notFoundReply(reply);
|
|
262
|
+
manager.use(target.id);
|
|
263
|
+
// Redirects stay inside the capability prefix when the request used one.
|
|
264
|
+
const prefix = capabilityPrefix ?? `/live/${target.id}`;
|
|
48
265
|
const host = upstreamHost(target.host);
|
|
49
266
|
reply.from(`http://${host}:${target.port}${subPath}`, {
|
|
50
267
|
rewriteRequestHeaders: (_req, headers) => {
|
|
51
268
|
headers.host = `${host}:${target.port}`;
|
|
269
|
+
// Dashboard credentials never reach the previewed app; its own cookies
|
|
270
|
+
// and bearer pass through. See change: retire-trusted-networks-bypass (D5).
|
|
271
|
+
stripDashboardCredentials(headers as HeaderBag, isDeviceBearer, request.raw, isKnownBearer);
|
|
272
|
+
// The hop to the loopback upstream is a PROXIED hop: mark it so nothing the
|
|
273
|
+
// upstream does with this request can pass for "genuinely local".
|
|
274
|
+
headers["x-forwarded-for"] = [headers["x-forwarded-for"], request.ip].filter(Boolean).join(", ");
|
|
275
|
+
// A forwarded Referer must not carry the capability token upstream.
|
|
276
|
+
if (typeof headers.referer === "string") headers.referer = stripCapabilitySegment(headers.referer);
|
|
52
277
|
return headers;
|
|
53
278
|
},
|
|
54
279
|
rewriteHeaders: (headers) => {
|
|
280
|
+
// An upstream may not plant or overwrite a dashboard credential.
|
|
281
|
+
const setCookie = filterSetCookie(headers["set-cookie"] as string | string[] | undefined);
|
|
282
|
+
if (setCookie === undefined) delete headers["set-cookie"];
|
|
283
|
+
else headers["set-cookie"] = setCookie;
|
|
284
|
+
// The token is in this page's URL: keep it out of Referer headers the
|
|
285
|
+
// page sends to third parties unless the app set its own policy.
|
|
286
|
+
if (capabilityPrefix && headers["referrer-policy"] === undefined) {
|
|
287
|
+
headers["referrer-policy"] = "no-referrer";
|
|
288
|
+
}
|
|
289
|
+
if (csp) appendCsp(headers, csp);
|
|
55
290
|
const location = headers.location;
|
|
56
291
|
if (typeof location === "string") {
|
|
57
|
-
|
|
58
|
-
else if (location.startsWith("/")) headers.location = `${prefix}${location}`;
|
|
59
|
-
else {
|
|
60
|
-
// Rewrite an absolute redirect back to the SAME upstream
|
|
61
|
-
// (`http://127.0.0.1:<port>/…`) into the proxied prefix so the
|
|
62
|
-
// browser stays on the dashboard origin and the single-port tunnel
|
|
63
|
-
// keeps working. Foreign absolute redirects are left untouched.
|
|
64
|
-
try {
|
|
65
|
-
const u = new URL(location);
|
|
66
|
-
if (u.hostname === host && u.port === String(target.port)) {
|
|
67
|
-
headers.location = `${prefix}${u.pathname}${u.search}`;
|
|
68
|
-
}
|
|
69
|
-
} catch {
|
|
70
|
-
/* not an absolute URL — leave as-is */
|
|
71
|
-
}
|
|
72
|
-
}
|
|
292
|
+
headers.location = rewriteLocation(location, prefix, host, target.port);
|
|
73
293
|
}
|
|
74
294
|
return headers;
|
|
75
295
|
},
|
|
76
296
|
});
|
|
77
297
|
};
|
|
78
298
|
|
|
299
|
+
const forward = (request: FastifyRequest, reply: FastifyReply) => {
|
|
300
|
+
const capabilityPrefix = (request as { liveCapabilityPrefix?: string }).liveCapabilityPrefix;
|
|
301
|
+
const grant = (request as { liveCapability?: LiveCapabilityGrant }).liveCapability;
|
|
302
|
+
// A browser-originated request (opaque `Origin: null` / `Sec-Fetch-*`) needs a capability.
|
|
303
|
+
if (!grant && isBrowserOriginated(request.headers as Record<string, unknown>)) return notFoundReply(reply);
|
|
304
|
+
const resolved = resolve(request.url, capabilityPrefix);
|
|
305
|
+
if (!resolved) return notFoundReply(reply);
|
|
306
|
+
const { id, subPath } = resolved;
|
|
307
|
+
const staticTarget = manager.getStatic(id);
|
|
308
|
+
if (staticTarget) return forwardStatic(request, reply, staticTarget, subPath, grant, capabilityPrefix);
|
|
309
|
+
const target = manager.get(id);
|
|
310
|
+
if (!target) return notFoundReply(reply);
|
|
311
|
+
return forwardPort(request, reply, target, subPath, grant, capabilityPrefix);
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const reservedOr404 = (request: FastifyRequest, reply: FastifyReply, grant: LiveCapabilityGrant, subPath: string) =>
|
|
315
|
+
deps.reservedHandler
|
|
316
|
+
? deps.reservedHandler(request, reply, { grant, subPath })
|
|
317
|
+
: notFoundReply(reply);
|
|
318
|
+
|
|
79
319
|
fastify.all("/live/:id/*", forward);
|
|
80
320
|
fastify.all("/live/:id", forward);
|
|
81
321
|
}
|
|
82
322
|
|
|
323
|
+
/** Longest upstream 101 head we will buffer before giving up. */
|
|
324
|
+
const MAX_HANDSHAKE_BYTES = 16 * 1024;
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Pipe the upstream's upgrade response to the browser, dropping any
|
|
328
|
+
* `Set-Cookie` that names a dashboard cookie from the 101 head (a previewed app
|
|
329
|
+
* must not plant or overwrite a dashboard credential over the WS handshake
|
|
330
|
+
* either); the frames after the head are piped untouched.
|
|
331
|
+
*/
|
|
332
|
+
function forwardHandshakeFiltered(upstream: net.Socket, socket: import("node:stream").Duplex): void {
|
|
333
|
+
let buf = Buffer.alloc(0);
|
|
334
|
+
const onData = (chunk: Buffer) => {
|
|
335
|
+
buf = Buffer.concat([buf, chunk]);
|
|
336
|
+
const end = buf.indexOf("\r\n\r\n");
|
|
337
|
+
if (end < 0) {
|
|
338
|
+
if (buf.length > MAX_HANDSHAKE_BYTES) upstream.destroy();
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
upstream.off("data", onData);
|
|
342
|
+
const headText = buf.subarray(0, end).toString("latin1");
|
|
343
|
+
const filtered = headText
|
|
344
|
+
.split("\r\n")
|
|
345
|
+
.filter((line) => !/^set-cookie:\s*pi_dash_/i.test(line))
|
|
346
|
+
.join("\r\n");
|
|
347
|
+
socket.write(Buffer.concat([Buffer.from(`${filtered}\r\n\r\n`, "latin1"), buf.subarray(end + 4)]));
|
|
348
|
+
upstream.pipe(socket);
|
|
349
|
+
};
|
|
350
|
+
upstream.on("data", onData);
|
|
351
|
+
}
|
|
352
|
+
|
|
83
353
|
/** WebSocket upgrade forwarding (HMR / dev-server sockets). */
|
|
84
354
|
export function handleLiveServerUpgrade(
|
|
85
355
|
manager: LiveServerManager,
|
|
86
356
|
request: import("node:http").IncomingMessage,
|
|
87
357
|
socket: import("node:stream").Duplex,
|
|
88
358
|
head: Buffer,
|
|
359
|
+
deps: LiveProxyDeps & {
|
|
360
|
+
/** `/live/<id>/~c/<token>` when the upgrade was admitted by a validated capability. */
|
|
361
|
+
capabilityPrefix?: string;
|
|
362
|
+
} = {},
|
|
89
363
|
) {
|
|
90
364
|
const match = request.url?.match(/^\/live\/([^/?]+)(.*)$/);
|
|
91
365
|
if (!match) {
|
|
92
366
|
socket.destroy();
|
|
93
367
|
return;
|
|
94
368
|
}
|
|
369
|
+
// A browser-originated upgrade (opaque `Origin: null` / `Sec-Fetch-*`) needs a capability.
|
|
370
|
+
if (!deps.capabilityPrefix && isBrowserOriginated(request.headers as Record<string, unknown>)) {
|
|
371
|
+
socket.destroy();
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
95
374
|
const target = manager.get(match[1]);
|
|
96
375
|
if (!target) {
|
|
97
376
|
socket.destroy();
|
|
98
377
|
return;
|
|
99
378
|
}
|
|
100
|
-
|
|
379
|
+
manager.use(target.id);
|
|
380
|
+
const capabilityPrefix = deps.capabilityPrefix;
|
|
381
|
+
let rest = match[2] || "";
|
|
382
|
+
if (capabilityPrefix && request.url?.startsWith(capabilityPrefix)) rest = request.url.slice(capabilityPrefix.length);
|
|
101
383
|
const subPath = rest.startsWith("?") ? `/${rest}` : rest.startsWith("/") ? rest : "/";
|
|
102
384
|
const host = upstreamHost(target.host);
|
|
385
|
+
const isDeviceBearer = deps.isDeviceBearer ?? (() => false);
|
|
386
|
+
const isKnownBearer = deps.isKnownBearer ?? (() => false);
|
|
103
387
|
|
|
104
388
|
const upstream = net.connect(target.port, host, () => {
|
|
105
389
|
// Clear the connect-phase timeout once the socket is established; the pipe
|
|
106
390
|
// below owns the socket lifetime thereafter.
|
|
107
391
|
upstream.setTimeout(0);
|
|
108
|
-
|
|
392
|
+
// Dashboard credentials never reach the previewed app (same rule as the
|
|
393
|
+
// HTTP path); a forwarded Referer loses any capability segment.
|
|
394
|
+
const forwarded = stripDashboardCredentials({ ...request.headers } as HeaderBag, isDeviceBearer, request, isKnownBearer);
|
|
395
|
+
// A proxied hop: the upstream must never see this upgrade as genuinely local.
|
|
396
|
+
forwarded["x-forwarded-for"] = [forwarded["x-forwarded-for"], request.socket?.remoteAddress]
|
|
397
|
+
.filter(Boolean)
|
|
398
|
+
.join(", ");
|
|
399
|
+
if (typeof forwarded.referer === "string") forwarded.referer = stripCapabilitySegment(forwarded.referer);
|
|
400
|
+
const headers = Object.entries(forwarded)
|
|
109
401
|
.filter(([k]) => !["host", "origin"].includes(k.toLowerCase()))
|
|
110
402
|
.map(([k, v]) => `${k}: ${v}`)
|
|
111
403
|
.join("\r\n");
|
|
@@ -115,7 +407,7 @@ export function handleLiveServerUpgrade(
|
|
|
115
407
|
`${headers}\r\n\r\n`,
|
|
116
408
|
);
|
|
117
409
|
if (head.length > 0) upstream.write(head);
|
|
118
|
-
upstream
|
|
410
|
+
forwardHandshakeFiltered(upstream, socket);
|
|
119
411
|
socket.pipe(upstream);
|
|
120
412
|
});
|
|
121
413
|
// Bound the connect/upgrade handshake: a target that accepts TCP but never
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static-target serving for `/live/<id>/~c/<token>/<path>`.
|
|
3
|
+
*
|
|
4
|
+
* Every refusal is a bare 404 (a caller cannot tell "missing" from "forbidden").
|
|
5
|
+
* The checks, in order, follow the `harden-path-matcher-vs-router` checklist:
|
|
6
|
+
*
|
|
7
|
+
* 1. the path is decoded exactly ONCE; a decoded segment that still carries an
|
|
8
|
+
* encoded `/`, `.` or `\` (double encoding), a NUL / control character, a
|
|
9
|
+
* backslash, an empty / `.` / `..` segment is refused;
|
|
10
|
+
* 2. dot segments (`.git`, `.env`, …), `node_modules` and secret-like names
|
|
11
|
+
* (`isCredentialName`) are refused in every segment;
|
|
12
|
+
* 3. only the web-asset allowlist (`isStaticWebAsset`) is served — no `.map`,
|
|
13
|
+
* no `.txt`, no databases;
|
|
14
|
+
* 4. the REAL path (symlinks resolved) must lie inside the REAL root, and its
|
|
15
|
+
* own segments pass the same name checks — a symlink out of the root is a 404;
|
|
16
|
+
* 5. the raw file-read gate (`gate`) is re-run on the real path for EVERY
|
|
17
|
+
* request, so a revoked grant or pin takes effect on the next request;
|
|
18
|
+
* 6. the opened handle must be a regular file (checked on the handle itself).
|
|
19
|
+
*
|
|
20
|
+
* Streams from the file handle with single-`Range` support, never buffering a
|
|
21
|
+
* file. See change: improve-canvas-html-and-url-ux (design D1, D2).
|
|
22
|
+
*/
|
|
23
|
+
import fs from "node:fs";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
import {
|
|
26
|
+
isCredentialName,
|
|
27
|
+
isStaticWebAsset,
|
|
28
|
+
type StaticTarget,
|
|
29
|
+
} from "@blackbelt-technology/pi-dashboard-shared/live-server.js";
|
|
30
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
31
|
+
|
|
32
|
+
export interface StaticServeDeps {
|
|
33
|
+
/** The raw file-read gate for an absolute real path under `cwd`. `true` = admitted. */
|
|
34
|
+
gate: (cwd: string, absPath: string) => Promise<boolean>;
|
|
35
|
+
/** Called with the real path of an HTML document about to be served in full (the origin scan reads it later). */
|
|
36
|
+
onHtmlServed?: (realPath: string) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const MIME: Readonly<Record<string, string>> = {
|
|
40
|
+
html: "text/html; charset=utf-8",
|
|
41
|
+
htm: "text/html; charset=utf-8",
|
|
42
|
+
css: "text/css; charset=utf-8",
|
|
43
|
+
js: "text/javascript; charset=utf-8",
|
|
44
|
+
mjs: "text/javascript; charset=utf-8",
|
|
45
|
+
json: "application/json; charset=utf-8",
|
|
46
|
+
svg: "image/svg+xml",
|
|
47
|
+
png: "image/png",
|
|
48
|
+
jpg: "image/jpeg",
|
|
49
|
+
jpeg: "image/jpeg",
|
|
50
|
+
gif: "image/gif",
|
|
51
|
+
webp: "image/webp",
|
|
52
|
+
avif: "image/avif",
|
|
53
|
+
ico: "image/x-icon",
|
|
54
|
+
woff: "font/woff",
|
|
55
|
+
woff2: "font/woff2",
|
|
56
|
+
ttf: "font/ttf",
|
|
57
|
+
otf: "font/otf",
|
|
58
|
+
mp4: "video/mp4",
|
|
59
|
+
webm: "video/webm",
|
|
60
|
+
ogg: "audio/ogg",
|
|
61
|
+
mp3: "audio/mpeg",
|
|
62
|
+
wav: "audio/wav",
|
|
63
|
+
m4a: "audio/mp4",
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Content type for a served file name (`application/octet-stream` for the unreachable fallthrough). */
|
|
67
|
+
function mimeOf(name: string): string {
|
|
68
|
+
const i = name.lastIndexOf(".");
|
|
69
|
+
return (i >= 0 ? MIME[name.slice(i + 1).toLowerCase()] : undefined) ?? "application/octet-stream";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
73
|
+
const DOUBLE_ENCODED = /%(?:2e|2f|5c|00)/i;
|
|
74
|
+
|
|
75
|
+
/** A single name that a static target must never serve (dot, dependency dir, credential-like). */
|
|
76
|
+
function isForbiddenName(name: string): boolean {
|
|
77
|
+
if (name.startsWith(".")) return true;
|
|
78
|
+
if (name.toLowerCase() === "node_modules") return true;
|
|
79
|
+
return isCredentialName(name);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Is one DECODED request segment unsafe (empty, dot, backslash, control, double-encoded, drive-like)? */
|
|
83
|
+
function isUnsafeSegment(seg: string): boolean {
|
|
84
|
+
if (seg === "" || seg === "." || seg === "..") return true;
|
|
85
|
+
if (seg.includes("\\") || CONTROL.test(seg) || DOUBLE_ENCODED.test(seg)) return true;
|
|
86
|
+
return process.platform === "win32" && seg.includes(":"); // platform-branch-ok: reject NTFS drive/ADS segments on Windows only
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Decode the request path once and split it into safe segments, or `null`.
|
|
91
|
+
* `pathname` is the raw pathname after the capability prefix (leading `/`, no query).
|
|
92
|
+
* A path ending in `/` (or the root) maps to `index.html`.
|
|
93
|
+
*/
|
|
94
|
+
export function safeSegments(pathname: string): string[] | null {
|
|
95
|
+
let decoded: string;
|
|
96
|
+
try {
|
|
97
|
+
decoded = decodeURIComponent(pathname);
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
if (!decoded.startsWith("/")) return null;
|
|
102
|
+
const trailingSlash = decoded.endsWith("/");
|
|
103
|
+
const segments = decoded.slice(1).split("/");
|
|
104
|
+
if (trailingSlash) segments.pop();
|
|
105
|
+
if (segments.some(isUnsafeSegment)) return null;
|
|
106
|
+
if (trailingSlash || segments.length === 0) segments.push("index.html");
|
|
107
|
+
if (segments.some(isForbiddenName)) return null;
|
|
108
|
+
return isStaticWebAsset(segments[segments.length - 1]) ? segments : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const isInside = (child: string, parent: string): boolean => {
|
|
112
|
+
const rel = path.relative(parent, child);
|
|
113
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
type RangeResult = { kind: "full" } | { kind: "range"; start: number; end: number } | { kind: "unsatisfiable" };
|
|
117
|
+
|
|
118
|
+
/** Parse a single `bytes=` range; anything else (multi-range, bad syntax) serves the full body. */
|
|
119
|
+
function parseRange(header: string | undefined, size: number): RangeResult {
|
|
120
|
+
if (!header || size === 0) return { kind: "full" };
|
|
121
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
122
|
+
if (!m) return { kind: "full" };
|
|
123
|
+
const [, a, b] = m;
|
|
124
|
+
if (a === "" && b === "") return { kind: "full" };
|
|
125
|
+
if (a === "") {
|
|
126
|
+
const n = Number(b);
|
|
127
|
+
if (n === 0) return { kind: "unsatisfiable" };
|
|
128
|
+
return { kind: "range", start: Math.max(0, size - n), end: size - 1 };
|
|
129
|
+
}
|
|
130
|
+
const start = Number(a);
|
|
131
|
+
const end = b === "" ? size - 1 : Math.min(Number(b), size - 1);
|
|
132
|
+
if (!Number.isSafeInteger(start) || start >= size) return { kind: "unsatisfiable" };
|
|
133
|
+
if (end < start) return { kind: "full" };
|
|
134
|
+
return { kind: "range", start, end };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Resolve the request to the REAL path of a servable file, or `null`: realpath containment
|
|
139
|
+
* inside the real root, name checks on the resolved name, then the raw-read gate.
|
|
140
|
+
*/
|
|
141
|
+
async function locateFile(target: StaticTarget, segments: string[], deps: StaticServeDeps): Promise<string | null> {
|
|
142
|
+
let realRoot: string;
|
|
143
|
+
let real: string;
|
|
144
|
+
try {
|
|
145
|
+
realRoot = await fs.promises.realpath(target.root);
|
|
146
|
+
real = await fs.promises.realpath(path.join(realRoot, ...segments));
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
if (!isInside(real, realRoot)) return null;
|
|
151
|
+
// The symlink-resolved name must be servable too (`ok.html -> .env` is not).
|
|
152
|
+
const realSegments = path.relative(realRoot, real).split(path.sep);
|
|
153
|
+
if (realSegments.some(isForbiddenName) || !isStaticWebAsset(realSegments[realSegments.length - 1])) return null;
|
|
154
|
+
return (await deps.gate(target.cwd, real)) ? real : null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Open `real` and verify, on the handle itself, that it is a regular file. */
|
|
158
|
+
async function openRegular(real: string): Promise<{ fh: fs.promises.FileHandle; size: number } | null> {
|
|
159
|
+
let fh: fs.promises.FileHandle;
|
|
160
|
+
try {
|
|
161
|
+
fh = await fs.promises.open(real, "r");
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const st = await fh.stat();
|
|
167
|
+
if (st.isFile()) return { fh, size: st.size };
|
|
168
|
+
} catch {
|
|
169
|
+
/* fall through to close */
|
|
170
|
+
}
|
|
171
|
+
await fh.close().catch(() => undefined);
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Tell the origin scan which HTML document is about to be served in full. */
|
|
176
|
+
function noteHtmlServed(deps: StaticServeDeps, method: string, real: string): void {
|
|
177
|
+
if (method === "GET" && /\.html?$/i.test(real)) deps.onHtmlServed?.(real);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Serve `rest` (the path + query after the capability prefix) from `target`.
|
|
182
|
+
* `extraHeaders` carries the CSP set built from the token's policy.
|
|
183
|
+
*/
|
|
184
|
+
export async function serveStatic(
|
|
185
|
+
request: FastifyRequest,
|
|
186
|
+
reply: FastifyReply,
|
|
187
|
+
target: StaticTarget,
|
|
188
|
+
rest: string,
|
|
189
|
+
extraHeaders: Record<string, string>,
|
|
190
|
+
deps: StaticServeDeps,
|
|
191
|
+
): Promise<FastifyReply> {
|
|
192
|
+
const notFound = () => reply.code(404).send({ error: "live-server target not found" });
|
|
193
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
194
|
+
return reply.code(405).header("allow", "GET, HEAD").send({ error: "method not allowed" });
|
|
195
|
+
}
|
|
196
|
+
const q = rest.search(/[?#]/);
|
|
197
|
+
const segments = safeSegments(q >= 0 ? rest.slice(0, q) : rest);
|
|
198
|
+
const real = segments ? await locateFile(target, segments, deps) : null;
|
|
199
|
+
const opened = real ? await openRegular(real) : null;
|
|
200
|
+
if (!real || !opened) return notFound();
|
|
201
|
+
const { fh, size } = opened;
|
|
202
|
+
noteHtmlServed(deps, request.method, real);
|
|
203
|
+
|
|
204
|
+
const headers: Record<string, string> = {
|
|
205
|
+
...extraHeaders,
|
|
206
|
+
"content-type": mimeOf(real),
|
|
207
|
+
"cache-control": "no-store",
|
|
208
|
+
"x-content-type-options": "nosniff",
|
|
209
|
+
"referrer-policy": "no-referrer",
|
|
210
|
+
"accept-ranges": "bytes",
|
|
211
|
+
};
|
|
212
|
+
const range = parseRange(request.headers.range, size);
|
|
213
|
+
if (range.kind === "unsatisfiable") {
|
|
214
|
+
await fh.close();
|
|
215
|
+
return reply.code(416).headers({ ...headers, "content-range": `bytes */${size}` }).send();
|
|
216
|
+
}
|
|
217
|
+
const start = range.kind === "range" ? range.start : 0;
|
|
218
|
+
const end = range.kind === "range" ? range.end : size - 1;
|
|
219
|
+
headers["content-length"] = String(size === 0 ? 0 : end - start + 1);
|
|
220
|
+
if (range.kind === "range") headers["content-range"] = `bytes ${start}-${end}/${size}`;
|
|
221
|
+
reply.code(range.kind === "range" ? 206 : 200).headers(headers);
|
|
222
|
+
if (request.method === "HEAD" || size === 0) {
|
|
223
|
+
await fh.close();
|
|
224
|
+
return reply.send();
|
|
225
|
+
}
|
|
226
|
+
// The stream owns the handle and closes it on end / error / client abort.
|
|
227
|
+
return reply.send(fh.createReadStream({ start, end, autoClose: true }));
|
|
228
|
+
}
|