@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -2
- package/README.md +64 -18
- package/docs/architecture.md +2325 -270
- package/package.json +36 -20
- package/packages/extension/package.json +18 -9
- package/packages/extension/src/bridge-context.ts +6 -0
- package/packages/extension/src/bridge-handlers/dispatch.ts +109 -70
- package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
- package/packages/extension/src/bridge-handlers/instance.ts +31 -13
- package/packages/extension/src/bridge-handlers/lifecycle.ts +149 -66
- package/packages/extension/src/bridge-shutdown.ts +44 -0
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +309 -284
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +106 -37
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +153 -38
- package/packages/extension/src/credential-guard.ts +300 -0
- package/packages/extension/src/custom-entry-forward.ts +27 -18
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/default-model-apply.ts +83 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/flow-event-wiring.ts +19 -95
- package/packages/extension/src/followup-drain.ts +19 -5
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +77 -6
- package/packages/extension/src/model-refresh.ts +69 -0
- package/packages/extension/src/path-gate/decide.ts +68 -5
- package/packages/extension/src/path-gate/handler.ts +16 -8
- package/packages/extension/src/path-gate/index.ts +2 -2
- package/packages/extension/src/path-gate/roots.ts +15 -3
- package/packages/extension/src/path-gate/suppression.ts +3 -0
- package/packages/extension/src/pi-env.d.ts +8 -1
- package/packages/extension/src/pi-retry-settings.ts +11 -2
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
- package/packages/extension/src/preview-path-link.ts +151 -0
- package/packages/extension/src/project-init/scaffold.ts +98 -35
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +178 -30
- package/packages/extension/src/provider-model-cache.ts +118 -0
- package/packages/extension/src/provider-register.ts +487 -46
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/retry-tracker.ts +90 -7
- package/packages/extension/src/role-manager.ts +4 -2
- package/packages/extension/src/role-model-tools.ts +68 -10
- package/packages/extension/src/server-auto-start.ts +69 -3
- package/packages/extension/src/server-launcher.ts +26 -8
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-sync.ts +53 -24
- package/packages/extension/src/spawn-new-session.ts +22 -0
- package/packages/extension/src/steer-buffer.ts +164 -0
- package/packages/extension/src/stream-forward-buffer.ts +64 -15
- package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
- package/packages/extension/src/sudo-askpass/controller.ts +405 -0
- package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
- package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
- package/packages/extension/src/sudo-askpass/index.ts +11 -0
- package/packages/extension/src/sudo-askpass/install.ts +143 -0
- package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
- package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
- package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
- package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
- package/packages/extension/src/terminal-reload.ts +19 -5
- package/packages/extension/src/tool-update-filter-registry.ts +210 -0
- package/packages/extension/src/vault-delivery.ts +11 -1
- package/packages/extension/src/vault-redaction.ts +4 -3
- package/packages/server/package.json +17 -14
- package/packages/server/src/access/access-denials.ts +8 -0
- package/packages/server/src/access/access-grants.ts +303 -64
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +12 -1
- package/packages/server/src/access/containment-gate.ts +113 -30
- package/packages/server/src/access/cwd-verdict.ts +3 -3
- package/packages/server/src/access/denial-hold.ts +3 -0
- package/packages/server/src/access/grant-coordinator.ts +17 -1
- package/packages/server/src/access/named-grant.ts +3 -0
- package/packages/server/src/access/pending-grant-registry.ts +32 -5
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +50 -11
- package/packages/server/src/access/planes.ts +107 -1
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/verified-read.ts +24 -7
- package/packages/server/src/access/yolo-session.ts +54 -2
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +18 -5
- package/packages/server/src/acp-bridge/server-requests.ts +10 -4
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/auth/audit-log.ts +108 -0
- package/packages/server/src/auth/auth-plugin.ts +230 -38
- package/packages/server/src/auth/auth.ts +104 -4
- package/packages/server/src/auth/bearer-auth.ts +52 -12
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
- package/packages/server/src/auth/cors-origin.ts +90 -30
- package/packages/server/src/auth/credential-envelope.ts +233 -0
- package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
- package/packages/server/src/auth/credential-key-worker.mjs +108 -0
- package/packages/server/src/auth/credential-key.ts +479 -0
- package/packages/server/src/auth/credential-migration.ts +162 -0
- package/packages/server/src/auth/csp-report-paths.ts +26 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +145 -11
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/device-proof.ts +202 -0
- package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
- package/packages/server/src/auth/host-admission.ts +7 -0
- package/packages/server/src/auth/host-gate.ts +13 -2
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +69 -18
- package/packages/server/src/auth/localhost-guard.ts +98 -33
- package/packages/server/src/auth/locked-json-file.ts +68 -6
- package/packages/server/src/auth/models-json-store.ts +269 -0
- package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/node-guard.ts +36 -49
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
- package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
- package/packages/server/src/auth/plugin-credential-store.ts +81 -10
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-storage.ts +214 -12
- package/packages/server/src/auth/provider-block-checks.ts +321 -0
- package/packages/server/src/auth/provider-host-detect.ts +151 -0
- package/packages/server/src/auth/provider-key-file.ts +71 -0
- package/packages/server/src/auth/provider-readiness.ts +91 -0
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/route-tier-gate.ts +3 -2
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +111 -11
- package/packages/server/src/auth/vertex-key-check.ts +140 -0
- package/packages/server/src/auth/ws-ticket.ts +40 -2
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/browse.ts +73 -20
- package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
- package/packages/server/src/browser-handlers/directory-handler.ts +34 -24
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +167 -63
- package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +146 -3
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/build-plugin-send-prompt.ts +18 -0
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli/credentials-command.ts +555 -0
- package/packages/server/src/cli.ts +229 -53
- package/packages/server/src/config-api.ts +53 -35
- package/packages/server/src/config-snapshot.ts +197 -1
- package/packages/server/src/directory-service.ts +193 -68
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
- package/packages/server/src/event-wiring.ts +322 -207
- package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
- package/packages/server/src/git-worktree/git-operations.ts +45 -11
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/repo-lock.ts +42 -0
- package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
- package/packages/server/src/git-worktree/worktree-init.ts +5 -1
- package/packages/server/src/identity/http-road-classification.ts +18 -2
- package/packages/server/src/identity/identity-floor.ts +5 -2
- package/packages/server/src/identity/ws-message-scope.ts +11 -3
- package/packages/server/src/identity/ws-road-classification.ts +3 -1
- package/packages/server/src/known-server-moves.ts +36 -15
- package/packages/server/src/lib/browse-roots.ts +129 -17
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/content-disposition.ts +20 -0
- package/packages/server/src/lib/dashboard-state-guard.ts +513 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/eml.ts +5 -10
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/frame-policy-probe.ts +308 -0
- package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
- package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +96 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
- package/packages/server/src/lib/office-preview.ts +49 -13
- package/packages/server/src/lib/path-containment.ts +50 -10
- package/packages/server/src/lib/resolve-file-mention.ts +234 -40
- package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-handler-target.ts +4 -0
- package/packages/server/src/lib/writable-md-target.ts +26 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
- package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
- package/packages/server/src/lifecycle/exit-signal.ts +43 -0
- package/packages/server/src/lifecycle/recovery-server.ts +65 -18
- package/packages/server/src/live-server/capability-redact.ts +31 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +615 -44
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +141 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +25 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +220 -33
- package/packages/server/src/live-server/live-server-proxy.ts +411 -50
- package/packages/server/src/live-server/live-static.ts +231 -0
- package/packages/server/src/live-server/preview-dispatch.ts +286 -0
- package/packages/server/src/live-server/preview-observe.ts +53 -0
- package/packages/server/src/live-server/preview-origin.ts +182 -0
- package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
- package/packages/server/src/live-server/preview-path-store.ts +420 -0
- package/packages/server/src/live-server/preview-path.ts +40 -0
- package/packages/server/src/live-server/preview-pool.ts +385 -0
- package/packages/server/src/live-server/preview-preflight.ts +41 -0
- package/packages/server/src/live-server/preview-reserve.ts +44 -0
- package/packages/server/src/live-server/preview-tier.ts +217 -0
- package/packages/server/src/live-server/preview-viewers.ts +54 -0
- package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
- package/packages/server/src/model-proxy/internal-registry.ts +283 -21
- package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
- package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
- package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
- package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
- package/packages/server/src/openspec/readiness.ts +1 -1
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +141 -267
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/provider-probe.ts +202 -7
- package/packages/server/src/pairing/browser-gateway.ts +325 -51
- package/packages/server/src/pairing/device-key-intake.ts +120 -0
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/paired-devices.ts +702 -27
- package/packages/server/src/pairing/pairing.ts +103 -11
- package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
- package/packages/server/src/pending/pending-attach-registry.ts +15 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
- package/packages/server/src/persistence/memory-event-store.ts +251 -296
- package/packages/server/src/persistence/preferences-store.ts +61 -2
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-contention.ts +84 -2
- package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/host-project-trust.ts +29 -15
- package/packages/server/src/pi/pi-gateway.ts +398 -41
- package/packages/server/src/pi/provisional-registration.ts +4 -1
- package/packages/server/src/pi/resource-toggle-trust.ts +18 -7
- package/packages/server/src/pi-agent-settings.ts +95 -301
- package/packages/server/src/pi-default-remirror.ts +89 -0
- package/packages/server/src/plugin-append-event.ts +35 -0
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-entry-stats.ts +61 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-local-request.ts +207 -0
- package/packages/server/src/plugin-ownership.ts +111 -0
- package/packages/server/src/plugin-policy-registry.ts +297 -0
- package/packages/server/src/plugin-request-lane.ts +92 -16
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/preferences-relay.ts +20 -0
- package/packages/server/src/project-seed.ts +347 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
- package/packages/server/src/questions/question-store.ts +3 -2
- package/packages/server/src/routes/access-routes.ts +182 -15
- package/packages/server/src/routes/acme-routes.ts +14 -4
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +640 -279
- package/packages/server/src/routes/file-write-binary-routes.ts +97 -24
- package/packages/server/src/routes/folder-project-routes.ts +18 -12
- package/packages/server/src/routes/frame-policy-routes.ts +215 -0
- package/packages/server/src/routes/git-routes.ts +340 -273
- package/packages/server/src/routes/grep-routes.ts +64 -14
- package/packages/server/src/routes/known-servers-routes.ts +189 -91
- package/packages/server/src/routes/live-server-routes.ts +572 -15
- package/packages/server/src/routes/local-proof-routes.ts +14 -0
- package/packages/server/src/routes/models-introspection-routes.ts +1 -1
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +396 -31
- package/packages/server/src/routes/package-routes.ts +58 -10
- package/packages/server/src/routes/pairing-routes.ts +342 -17
- package/packages/server/src/routes/pi-settings-routes.ts +2 -0
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
- package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
- package/packages/server/src/routes/provider-auth-routes.ts +181 -10
- package/packages/server/src/routes/provider-override-routes.ts +158 -0
- package/packages/server/src/routes/provider-routes.ts +348 -86
- package/packages/server/src/routes/resource-activation-routes.ts +18 -4
- package/packages/server/src/routes/session-routes.ts +75 -25
- package/packages/server/src/routes/system-routes.ts +169 -52
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
- package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
- package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
- package/packages/server/src/server.ts +1139 -291
- package/packages/server/src/services/cli-service.ts +59 -10
- package/packages/server/src/services/secrets-resolver.ts +46 -30
- package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
- package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
- package/packages/server/src/session/death-reason.ts +11 -7
- package/packages/server/src/session/event-status-extraction.ts +5 -1
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/memory-session-manager.ts +31 -2
- package/packages/server/src/session/open-tool-calls.ts +81 -47
- package/packages/server/src/session/pid-target.ts +127 -0
- package/packages/server/src/session/replay-compaction.ts +18 -5
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/seed-discovered-history.ts +85 -0
- package/packages/server/src/session/server-pid-context.ts +14 -0
- package/packages/server/src/session/session-api.ts +78 -29
- package/packages/server/src/session/session-archive.ts +7 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -54
- package/packages/server/src/session/session-load-worker-pool.ts +11 -1
- package/packages/server/src/session/session-load-worker.ts +32 -4
- package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
- package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +393 -77
- package/packages/server/src/spawn-process/link-register.ts +42 -0
- package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
- package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
- package/packages/server/src/spawn-process/process-classifier.ts +8 -3
- package/packages/server/src/spawn-process/process-manager.ts +61 -6
- package/packages/server/src/spawn-process/restored-identity.ts +112 -0
- package/packages/server/src/spawn-process/session-terminator.ts +179 -18
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
- package/packages/server/src/sudo-credential/relay.ts +337 -0
- package/packages/server/src/terminal/terminal-gateway.ts +10 -0
- package/packages/server/src/terminal/terminal-manager.ts +54 -46
- package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
- package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +2 -0
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +172 -26
- package/packages/server/src/vault/vault-routes.ts +9 -2
- package/packages/server/src/vault/vault-store.ts +87 -24
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/server/vendor/xlsx/LICENSE +201 -0
- package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
- package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
- package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
- package/packages/shared/package.json +4 -2
- package/packages/shared/src/agent-credential-files.ts +32 -0
- package/packages/shared/src/browser-protocol.ts +285 -59
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/canvas-detect.ts +1 -1
- package/packages/shared/src/canvas-types.ts +2 -2
- package/packages/shared/src/config.ts +443 -187
- package/packages/shared/src/containment-guard.ts +45 -0
- package/packages/shared/src/credential-encryption.ts +87 -0
- package/packages/shared/src/custom-event-groups.ts +2 -0
- package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +2 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +100 -1
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +58 -3
- package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +47 -3
- package/packages/shared/src/dashboard-plugin/slot-types.ts +9 -1
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +39 -3
- package/packages/shared/src/device-key-proof.ts +309 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +94 -27
- package/packages/shared/src/event-forward-declaration.ts +85 -12
- package/packages/shared/src/forbidden-subjects.ts +126 -14
- package/packages/shared/src/heap-limits.ts +0 -30
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/index.ts +7 -6
- package/packages/shared/src/live-server.ts +161 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +176 -0
- package/packages/shared/src/mdns-discovery.ts +25 -6
- package/packages/shared/src/models-json-reader.ts +41 -0
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/network-denial-signal.ts +15 -0
- package/packages/shared/src/node-version.ts +63 -60
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-poller.ts +3 -2
- package/packages/shared/src/pairing-knock-client.ts +135 -11
- package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
- package/packages/shared/src/pi-path-compare.ts +31 -0
- package/packages/shared/src/pi-settings-schema.ts +52 -9
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +21 -11
- package/packages/shared/src/pi-trust-mirror-types.ts +38 -3
- package/packages/shared/src/pi-trust-mirror.ts +47 -11
- package/packages/shared/src/pi-trust-resource-digest.ts +261 -0
- package/packages/shared/src/pid-namespace.ts +86 -0
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +14 -8
- package/packages/shared/src/platform/native-ts-register.mjs +1 -1
- package/packages/shared/src/platform/process.ts +452 -5
- package/packages/shared/src/platform/resolve-pi-shell.ts +105 -0
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/platform/spawn-runtime.ts +193 -7
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +192 -0
- package/packages/shared/src/preview-origins.ts +398 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/prompt-answer.ts +9 -5
- package/packages/shared/src/protocol.ts +187 -86
- package/packages/shared/src/provider-env-catalog.ts +413 -0
- package/packages/shared/src/provider-overrides.ts +112 -0
- package/packages/shared/src/question-types.ts +6 -0
- package/packages/shared/src/recommended-extensions.ts +97 -26
- package/packages/shared/src/recovery-timing.ts +27 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/renderer-by-ext.ts +5 -2
- package/packages/shared/src/rest-api.ts +148 -11
- package/packages/shared/src/role-schema.ts +24 -0
- package/packages/shared/src/route-tiers.ts +149 -4
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/compat.ts +70 -6
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/secret-patterns.ts +49 -0
- package/packages/shared/src/server-launcher.ts +9 -1
- package/packages/shared/src/server-pinning.ts +55 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/source-matching.ts +2 -2
- package/packages/shared/src/state-replay.ts +40 -24
- package/packages/shared/src/sudo-credential.ts +71 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tool-path-resolve.ts +16 -1
- package/packages/shared/src/tool-registry/definitions.ts +5 -5
- package/packages/shared/src/tool-registry/strategies.ts +13 -12
- package/packages/shared/src/tool-workdir.ts +56 -0
- package/packages/shared/src/trusted-types-mode.ts +72 -0
- package/packages/shared/src/types.ts +134 -109
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +15 -0
- package/packages/shared/src/vertex-regions.ts +81 -0
- package/packages/shared/src/ws-message-tiers.ts +11 -3
- package/packages/extension/src/subagent-fanout-admission.ts +0 -234
- package/packages/extension/src/subagent-forward-sites.ts +0 -69
- package/packages/extension/src/subagent-frame-buffer.ts +0 -245
- package/packages/extension/src/subagent-frame-strip.ts +0 -109
- package/packages/extension/src/subagent-saturation.ts +0 -196
- package/packages/extension/src/subagent-tick-throttle.ts +0 -252
- package/packages/shared/src/anthropic-messages-source.ts +0 -8
|
@@ -20,10 +20,14 @@
|
|
|
20
20
|
* (see `ws-ticket.ts`).
|
|
21
21
|
*/
|
|
22
22
|
import type { TLSSocket } from "node:tls";
|
|
23
|
-
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
23
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
|
24
|
+
import { TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
|
|
24
25
|
import type { PairedDeviceRegistry } from "../pairing/paired-devices.js";
|
|
26
|
+
import { auditLine, auditPrefix } from "./audit-log.js";
|
|
25
27
|
import { hasProxyForwardingHeaders } from "./localhost-guard.js";
|
|
26
28
|
import { isLoopbackRange } from "./loopback.js";
|
|
29
|
+
import { bearerChannelOf } from "./proven-tls.js";
|
|
30
|
+
import { isSecureOrigin } from "./secure-origin.js";
|
|
27
31
|
|
|
28
32
|
/** Extract a `Bearer` token from an Authorization header, or null. */
|
|
29
33
|
export function parseBearerHeader(authorization: string | undefined): string | null {
|
|
@@ -39,6 +43,16 @@ export function parseBearerHeader(authorization: string | undefined): string | n
|
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
export const DEVICE_COOKIE = "pi_dash_device";
|
|
46
|
+
/** Route pattern of the browser-bearer rotation (the one route whose refusals are audited, D2). */
|
|
47
|
+
export const ROTATE_ROUTE = "/api/paired-devices/rotate";
|
|
48
|
+
/** 401 body for an expired browser bearer (distinct from revoked/unknown, which carry no `code`). */
|
|
49
|
+
/** 401 body for a `pi_tls_` bearer presented off a proven channel (a named cause, not "unpaired or revoked"). */
|
|
50
|
+
const TLS_ONLY_UNTRUSTED_BODY = {
|
|
51
|
+
success: false as const,
|
|
52
|
+
error: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
|
|
53
|
+
code: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
|
|
54
|
+
};
|
|
55
|
+
const BEARER_EXPIRED_BODY = { success: false as const, error: "bearer_expired", code: "bearer_expired" as const };
|
|
42
56
|
/** 400 days — `PairedDeviceRegistry` rows carry no expiry; revocation is the kill switch. */
|
|
43
57
|
const DEVICE_COOKIE_MAX_AGE_S = 400 * 24 * 60 * 60;
|
|
44
58
|
|
|
@@ -58,7 +72,10 @@ function deviceCookieSecure(request: FastifyRequest, globalSecure: () => boolean
|
|
|
58
72
|
// DIRECT only: a request carrying proxy-forwarding headers came through a TLS-terminating
|
|
59
73
|
// proxy that may sit on another host/container (peer 172.x), and keeps the global rule.
|
|
60
74
|
if (peer && !isLoopbackRange(peer) && !hasProxyForwardingHeaders(request.headers)) return false;
|
|
61
|
-
|
|
75
|
+
// The global rule is the ONE predicate shared with the OAuth state + session cookies:
|
|
76
|
+
// https base || loopback socket peer + Host equal to a live https tunnel origin.
|
|
77
|
+
// See change: harden-auth-credentials (D3).
|
|
78
|
+
return isSecureOrigin(request, globalSecure());
|
|
62
79
|
}
|
|
63
80
|
|
|
64
81
|
/** Pathname of a request URL (no query/fragment). */
|
|
@@ -67,6 +84,23 @@ function pathnameOf(url: string): string {
|
|
|
67
84
|
return q < 0 ? url : url.slice(0, q);
|
|
68
85
|
}
|
|
69
86
|
|
|
87
|
+
/**
|
|
88
|
+
* The device cookie's bearer. Authorization wins: the cookie is a fallback for
|
|
89
|
+
* `/api/*` URLs only and is never consulted when an Authorization header is present.
|
|
90
|
+
*/
|
|
91
|
+
function deviceCookieToken(request: FastifyRequest): string | null {
|
|
92
|
+
if (request.headers.authorization || !pathnameOf(request.url).startsWith("/api/")) return null;
|
|
93
|
+
return (request.cookies as Record<string, string | undefined> | undefined)?.[DEVICE_COOKIE] ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 401 `bearer_expired`; a refused ROTATION of a known device is also audited (A-G4): id prefix, reason, socket peer only. */
|
|
97
|
+
function refuseExpired(request: FastifyRequest, reply: FastifyReply, deviceId: string): FastifyReply {
|
|
98
|
+
if (request.method === "POST" && request.routeOptions?.url === ROTATE_ROUTE) {
|
|
99
|
+
auditLine("pairing", "rotate_refused", { id: auditPrefix(deviceId), reason: "bearer_expired", ip: request.ip });
|
|
100
|
+
}
|
|
101
|
+
return reply.code(401).send(BEARER_EXPIRED_BODY);
|
|
102
|
+
}
|
|
103
|
+
|
|
70
104
|
/** Register the REST bearer onRequest branch. */
|
|
71
105
|
export function registerBearerAuth(
|
|
72
106
|
fastify: FastifyInstance,
|
|
@@ -80,17 +114,23 @@ export function registerBearerAuth(
|
|
|
80
114
|
/* already decorated by another plugin */
|
|
81
115
|
}
|
|
82
116
|
}
|
|
83
|
-
fastify.addHook("onRequest", async (request: FastifyRequest) => {
|
|
117
|
+
fastify.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
|
|
84
118
|
if ((request as any).isAuthenticated) return;
|
|
85
119
|
const headerToken = parseBearerHeader(request.headers.authorization);
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
120
|
+
const token = headerToken ?? deviceCookieToken(request);
|
|
121
|
+
// The channel is judged from the request itself and the registry records any off-channel use.
|
|
122
|
+
const verdict = token ? deps.registry.verifyDetailed(token, bearerChannelOf(request.raw)) : null;
|
|
123
|
+
// A TLS-only bearer off a proven channel is marked, then refused with a distinct, named cause.
|
|
124
|
+
// See change: prove-vault-bridge-tls (D4, D9).
|
|
125
|
+
if (verdict?.status === "tls_only_refused") return reply.code(401).send(TLS_ONLY_UNTRUSTED_BODY);
|
|
126
|
+
// A PRESENTED Authorization bearer is always judged, before any network
|
|
127
|
+
// trust: an expired browser bearer is a distinct 401 the client re-pairs
|
|
128
|
+
// on, even from a loopback / trusted peer. (A cookie-carried bearer that
|
|
129
|
+
// expired falls through unauthenticated, like a revoked one.) Revoked,
|
|
130
|
+
// unknown and superseded-after-grace bearers stay a plain denial.
|
|
131
|
+
// See change: harden-auth-credentials (D5, A-G12).
|
|
132
|
+
if (verdict?.status === "expired" && headerToken) return refuseExpired(request, reply, verdict.id);
|
|
133
|
+
const verified = verdict?.status === "ok" ? verdict : null;
|
|
94
134
|
if (verified) {
|
|
95
135
|
(request as any).isAuthenticated = true;
|
|
96
136
|
// Additive marker: HOW the request authenticated. `operatorGuard` on the
|
|
@@ -117,7 +157,7 @@ export function registerDeviceSessionRoutes(
|
|
|
117
157
|
): void {
|
|
118
158
|
fastify.post("/api/device-session", async (request, reply) => {
|
|
119
159
|
const bearer = parseBearerHeader(request.headers.authorization);
|
|
120
|
-
if (!bearer || !deps.registry.verify(bearer)) {
|
|
160
|
+
if (!bearer || !deps.registry.verify(bearer, bearerChannelOf(request.raw))) {
|
|
121
161
|
reply.code(401);
|
|
122
162
|
return { success: false as const, error: "device bearer required" };
|
|
123
163
|
}
|
|
@@ -13,9 +13,16 @@
|
|
|
13
13
|
* or a genuinely-local caller on this host (which could have used the unix
|
|
14
14
|
* socket and needs no ticket at all on POSIX, but does on Windows — D6).
|
|
15
15
|
*
|
|
16
|
-
*
|
|
16
|
+
* The mint enforces `operate` ITSELF (the `/api/ws-ticket` route is `operate`, but the
|
|
17
|
+
* route-tier gate is exempt for a `legacy`-mode trusted-network peer and a
|
|
18
|
+
* genuinely-local caller, so the decider cannot rely on it). A below-operate bearer
|
|
19
|
+
* falls through to the genuinely-local branch (a deviceless local ticket) or is refused.
|
|
20
|
+
*
|
|
21
|
+
* See change: add-pi-gateway-transport-identity (task 6.2),
|
|
22
|
+
* harden-bridge-session-claim (D2).
|
|
17
23
|
*/
|
|
18
24
|
|
|
25
|
+
import { rank, type Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
|
|
19
26
|
import type { LocalTrustContext } from "./local-proof.js";
|
|
20
27
|
import { isLocallyTrusted } from "./localhost-guard.js";
|
|
21
28
|
|
|
@@ -32,9 +39,10 @@ export interface BridgeMintInput {
|
|
|
32
39
|
* minted it: a session registered over that ticket is then attributable,
|
|
33
40
|
* which is what the origin gate needs to refuse local file reads for a
|
|
34
41
|
* remote session (#E15). Takes the object the registry now returns
|
|
35
|
-
* (`{ id, tier }`; change: expand-mcp-tiered-surface)
|
|
42
|
+
* (`{ id, tier }`; change: expand-mcp-tiered-surface); the mint reads `tier` too:
|
|
43
|
+
* only `operate` may mint a bridge ticket as a device.
|
|
36
44
|
*/
|
|
37
|
-
verifyDeviceBearer: (token: string) => { id: string } | null;
|
|
45
|
+
verifyDeviceBearer: (token: string) => { id: string; tier: Tier } | null;
|
|
38
46
|
}
|
|
39
47
|
|
|
40
48
|
export interface BridgeMintDecision {
|
|
@@ -42,6 +50,13 @@ export interface BridgeMintDecision {
|
|
|
42
50
|
reason: string;
|
|
43
51
|
/** Set when the caller authenticated AS a paired device. */
|
|
44
52
|
deviceId?: string;
|
|
53
|
+
/** Set when a valid paired-device bearer was refused for being below `operate` (for the audit line). */
|
|
54
|
+
belowOperate?: { tier: Tier; deviceId: string };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The refusal audit line: tier + an 8-char device prefix, never the full id or the token. */
|
|
58
|
+
export function formatBridgeTicketRefusalLine(tier: Tier, devicePrefix: string): string {
|
|
59
|
+
return `[auth] bridge ticket refused: tier=${tier} device=${devicePrefix}`;
|
|
45
60
|
}
|
|
46
61
|
|
|
47
62
|
/**
|
|
@@ -64,19 +79,47 @@ function bearerFrom(authorization: string | undefined): string | null {
|
|
|
64
79
|
return token.length > 0 ? token : null;
|
|
65
80
|
}
|
|
66
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Rate-limited audit logger for below-operate refusals: one line per device per `windowMs`
|
|
84
|
+
* (the contention window), keyed by the full device id but logging only an 8-char prefix.
|
|
85
|
+
* A `verdict` without `belowOperate`, or an allowed one, logs nothing.
|
|
86
|
+
*/
|
|
87
|
+
export function createTicketRefusalLog(opts: {
|
|
88
|
+
windowMs: number;
|
|
89
|
+
prefix: (deviceId: string) => string;
|
|
90
|
+
now?: () => number;
|
|
91
|
+
log?: (line: string) => void;
|
|
92
|
+
}): (verdict: BridgeMintDecision) => void {
|
|
93
|
+
const last = new Map<string, number>();
|
|
94
|
+
const now = opts.now ?? Date.now;
|
|
95
|
+
const log = opts.log ?? ((line: string) => console.error(line));
|
|
96
|
+
return (verdict) => {
|
|
97
|
+
if (!verdict.belowOperate || verdict.allow) return;
|
|
98
|
+
const { tier, deviceId } = verdict.belowOperate;
|
|
99
|
+
const t = now();
|
|
100
|
+
const prev = last.get(deviceId);
|
|
101
|
+
if (prev !== undefined && t - prev < opts.windowMs) return;
|
|
102
|
+
last.set(deviceId, t);
|
|
103
|
+
log(formatBridgeTicketRefusalLine(tier, opts.prefix(deviceId)));
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
67
107
|
export function decideBridgeTicketMint(input: BridgeMintInput): BridgeMintDecision {
|
|
68
108
|
const bearer = bearerFrom(input.authorization);
|
|
69
|
-
const
|
|
70
|
-
if (
|
|
71
|
-
return { allow: true, reason: "paired device bearer", deviceId };
|
|
109
|
+
const device = bearer ? input.verifyDeviceBearer(bearer) : null;
|
|
110
|
+
if (device && rank(device.tier) >= rank("operate")) {
|
|
111
|
+
return { allow: true, reason: "paired device bearer", deviceId: device.id };
|
|
72
112
|
}
|
|
113
|
+
const belowOperate = device ? { tier: device.tier, deviceId: device.id } : undefined;
|
|
73
114
|
if (isLocallyTrusted({ ip: input.ip, headers: input.headers }, input.localTrust)) {
|
|
74
|
-
return { allow: true, reason: "genuinely-local caller" };
|
|
115
|
+
return { allow: true, reason: "genuinely-local caller", belowOperate };
|
|
75
116
|
}
|
|
76
117
|
return {
|
|
77
118
|
allow: false,
|
|
78
|
-
reason:
|
|
79
|
-
"bridge tickets require a paired
|
|
80
|
-
"
|
|
119
|
+
reason: device
|
|
120
|
+
? "bridge tickets require a paired device at the operate tier; this device's tier is lower"
|
|
121
|
+
: "bridge tickets require an operate-tier paired-device bearer or a genuinely-local caller; " +
|
|
122
|
+
"a cookie session or trusted-network host is not sufficient",
|
|
123
|
+
belowOperate,
|
|
81
124
|
};
|
|
82
125
|
}
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* See change: fix-remote-connect-cors-gates.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { isPreviewShapedOriginUrl } from "../live-server/preview-origin.js";
|
|
13
14
|
import { isHostAdmitted } from "./host-admission.js";
|
|
14
15
|
import { isBypassedHost } from "./localhost-guard.js";
|
|
15
16
|
import type { WsRouteScope } from "./ws-ticket.js";
|
|
@@ -44,13 +45,14 @@ export interface CorsOriginOptions {
|
|
|
44
45
|
/**
|
|
45
46
|
* Allow ANY `*.share.zrok.io` / `*.shares.zrok.io` host (branch 5).
|
|
46
47
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* tunnel origins (branch
|
|
53
|
-
*
|
|
48
|
+
* Opt-in: only the boolean `true` enables it (`cors.allowZrokWildcard`,
|
|
49
|
+
* default `false`). Zrok shares are free and self-service, so a stranger
|
|
50
|
+
* share is very likely same-site to the victim's tunnel; the wildcard would
|
|
51
|
+
* let it read responses (CORS) and, for admission (WS upgrade, mutating
|
|
52
|
+
* REST), defeat even the OAuth'd gate — admission therefore ALWAYS forces it
|
|
53
|
+
* off. Tunnels the dashboard itself runs are live tunnel origins (branch
|
|
54
|
+
* 4/4b) and stay allowed with the wildcard off.
|
|
55
|
+
* See change: fix-ws-origin-cswsh (D1 rule 2), harden-cors-and-csp-reporting (B19).
|
|
54
56
|
*/
|
|
55
57
|
allowZrokWildcard?: boolean;
|
|
56
58
|
/** Top-level `allowedHosts` (live) — host-admission only. */
|
|
@@ -71,6 +73,41 @@ export interface CorsOriginOptions {
|
|
|
71
73
|
hostGateMode?: "report" | "enforce";
|
|
72
74
|
}
|
|
73
75
|
|
|
76
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: detecting them is the point.
|
|
77
|
+
const HAS_CONTROL = /[\u0000-\u001f\u007f]/;
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Canonical form of an origin or URL for tunnel comparison: lowercase scheme
|
|
81
|
+
* and host, default port elided, ONE trailing hostname dot stripped, path /
|
|
82
|
+
* query dropped. `null` for anything that is not a well-formed http(s) origin
|
|
83
|
+
* (padding, control characters, bad port, other schemes).
|
|
84
|
+
*
|
|
85
|
+
* A trailing-dot origin equals its dotless form, matching host admission.
|
|
86
|
+
* See change: harden-cors-and-csp-reporting (R2).
|
|
87
|
+
*/
|
|
88
|
+
export function canonicalOrigin(raw: string): string | null {
|
|
89
|
+
if (typeof raw !== "string" || raw !== raw.trim() || HAS_CONTROL.test(raw)) return null;
|
|
90
|
+
try {
|
|
91
|
+
const u = new URL(raw);
|
|
92
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
|
93
|
+
const host = u.hostname.endsWith(".") ? u.hostname.slice(0, -1) : u.hostname;
|
|
94
|
+
if (host === "") return null;
|
|
95
|
+
return `${u.protocol}//${host}${u.port ? `:${u.port}` : ""}`;
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Run a dynamic getter; a throwing getter means "nothing live", never a 500. */
|
|
102
|
+
function safely<T>(read: (() => T) | undefined, fallback: T): T {
|
|
103
|
+
if (!read) return fallback;
|
|
104
|
+
try {
|
|
105
|
+
return read() ?? fallback;
|
|
106
|
+
} catch {
|
|
107
|
+
return fallback;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
74
111
|
/**
|
|
75
112
|
* Why a CORS origin decision came out the way it did.
|
|
76
113
|
*
|
|
@@ -92,6 +129,7 @@ export type CorsAllowanceKind =
|
|
|
92
129
|
| "pwa-shell"
|
|
93
130
|
| "trusted-network"
|
|
94
131
|
| "configured"
|
|
132
|
+
| "preview"
|
|
95
133
|
| "denied";
|
|
96
134
|
|
|
97
135
|
export interface CorsAllowance {
|
|
@@ -111,7 +149,8 @@ export interface CorsAllowance {
|
|
|
111
149
|
* 3. Loopback host (any port) → allow.
|
|
112
150
|
* 4. Active zrok tunnel URL → allow.
|
|
113
151
|
* 4b. Any CURRENTLY connected tunnel origin (any provider) → allow.
|
|
114
|
-
* 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow
|
|
152
|
+
* 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow, ONLY
|
|
153
|
+
* when `allowZrokWildcard === true` (opt-in, default off).
|
|
115
154
|
* 6. Neutral static PWA shell `https://pi-dashboard.dev` → allow.
|
|
116
155
|
* 7. Explicitly configured origin → allow.
|
|
117
156
|
* 8. Origin host matches a trusted network (CIDR / wildcard / exact) → allow.
|
|
@@ -130,6 +169,15 @@ export function classifyCorsOrigin(
|
|
|
130
169
|
// 2. Opaque-origin document. Never echo an ACAO for it, so an embedded
|
|
131
170
|
// untrusted app cannot call dashboard APIs even cross-origin.
|
|
132
171
|
if (origin === "null") return { allowed: false, revocable: false, kind: "opaque" };
|
|
172
|
+
// Padding / control characters are never sent by a browser; `new URL()`
|
|
173
|
+
// silently strips them, so do not normalize them into a trusted value.
|
|
174
|
+
if (origin !== origin.trim() || HAS_CONTROL.test(origin)) return { allowed: false, revocable: false, kind: "denied" };
|
|
175
|
+
// 2b. A live-preview origin (`<label>.localhost`, a configured suffix, `<ip>:<pool port>`) is another
|
|
176
|
+
// app's origin: it never gains dashboard trust — not through loopback, a trusted network, a live
|
|
177
|
+
// tunnel nor an explicit `cors.allowedOrigins` entry. Evaluated BEFORE all of them, so the
|
|
178
|
+
// static `ip-address` admission of an IP-literal pool origin can never exempt it.
|
|
179
|
+
// See change: serve-live-previews-on-capability-origin (D4).
|
|
180
|
+
if (isPreviewShapedOriginUrl(origin)) return { allowed: false, revocable: false, kind: "preview" };
|
|
133
181
|
try {
|
|
134
182
|
const u = new URL(origin);
|
|
135
183
|
const host = u.hostname;
|
|
@@ -137,26 +185,25 @@ export function classifyCorsOrigin(
|
|
|
137
185
|
if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1") {
|
|
138
186
|
return allow("loopback");
|
|
139
187
|
}
|
|
188
|
+
// Tunnel branches compare CANONICAL origins (case, default port, one
|
|
189
|
+
// trailing dot, path), so the recorded URL and the browser's Origin agree.
|
|
190
|
+
const requestOrigin = canonicalOrigin(origin);
|
|
140
191
|
// 4. Active zrok tunnel URL (dynamic — rotation without restart).
|
|
141
|
-
const tunnelUrl = opts.getTunnelUrl
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
for (const raw of opts.getLiveTunnelOrigins
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
candidate = new URL(raw).origin;
|
|
151
|
-
} catch {
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
if (candidate === u.origin) return allow("live-tunnel");
|
|
192
|
+
const tunnelUrl = safely(opts.getTunnelUrl, null);
|
|
193
|
+
const canonicalTunnel = tunnelUrl ? canonicalOrigin(tunnelUrl) : null;
|
|
194
|
+
if (requestOrigin && canonicalTunnel && requestOrigin === canonicalTunnel) return allow("active-tunnel");
|
|
195
|
+
// 4b. Any live tunnel's origin, for every provider. Compared as canonical
|
|
196
|
+
// ORIGINS, not URLs: a provider reports `https://host/path`, and a
|
|
197
|
+
// browser sends `https://host`. Malformed entries are skipped.
|
|
198
|
+
for (const raw of safely(opts.getLiveTunnelOrigins, [] as string[])) {
|
|
199
|
+
const candidate = canonicalOrigin(raw);
|
|
200
|
+
if (candidate && requestOrigin && candidate === requestOrigin) return allow("live-tunnel");
|
|
155
201
|
}
|
|
156
|
-
// 5.
|
|
202
|
+
// 5. Opt-in only: any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
|
|
203
|
+
const bareHost = host.endsWith(".") ? host.slice(0, -1) : host;
|
|
157
204
|
if (
|
|
158
|
-
opts.allowZrokWildcard
|
|
159
|
-
(
|
|
205
|
+
opts.allowZrokWildcard === true &&
|
|
206
|
+
(bareHost.endsWith(".share.zrok.io") || bareHost.endsWith(".shares.zrok.io"))
|
|
160
207
|
) {
|
|
161
208
|
return allow("zrok-wildcard");
|
|
162
209
|
}
|
|
@@ -227,7 +274,11 @@ export function isSameOriginByHost(
|
|
|
227
274
|
try {
|
|
228
275
|
const o = new URL(origin);
|
|
229
276
|
const h = new URL(`${o.protocol}//${hostHeader}`);
|
|
230
|
-
if (h.host === ""
|
|
277
|
+
if (h.host === "") return false;
|
|
278
|
+
// Canonical compare: case, default port and one trailing dot all agree.
|
|
279
|
+
const co = canonicalOrigin(origin);
|
|
280
|
+
const ch = canonicalOrigin(`${o.protocol}//${hostHeader}`);
|
|
281
|
+
if (!co || !ch || co !== ch) return false;
|
|
231
282
|
} catch {
|
|
232
283
|
return false;
|
|
233
284
|
}
|
|
@@ -257,6 +308,8 @@ export function isOriginAdmitted(
|
|
|
257
308
|
// would normalize into a loopback match. No browser sends padding — deny it
|
|
258
309
|
// rather than normalize an attacker-shaped value into a trusted one.
|
|
259
310
|
if (origin !== origin.trim()) return false;
|
|
311
|
+
// A preview origin never acts on the dashboard: not via the same-origin-by-Host rule, nor any list (D4).
|
|
312
|
+
if (isPreviewShapedOriginUrl(origin)) return false;
|
|
260
313
|
if (isSameOriginByHost(origin, hostHeader, opts)) return true;
|
|
261
314
|
return isCorsOriginAllowed(origin, { ...opts, allowZrokWildcard: false });
|
|
262
315
|
}
|
|
@@ -265,16 +318,20 @@ export function isOriginAdmitted(
|
|
|
265
318
|
* WS upgrade admission, per route scope.
|
|
266
319
|
*
|
|
267
320
|
* `live` admits the opaque `Origin: null` — the sandboxed preview iframe is its
|
|
268
|
-
* only intended client and rejecting it would silently break HMR (D3)
|
|
269
|
-
*
|
|
321
|
+
* only intended client and rejecting it would silently break HMR (D3) — but ONLY
|
|
322
|
+
* for an upgrade that carries a VALID capability (`liveCapabilityValid`): an
|
|
323
|
+
* opaque frame without one would otherwise reach any port target. Every other
|
|
324
|
+
* scope (including `bridge` and the unrouted `null` scope) is strict.
|
|
325
|
+
* See change: improve-canvas-html-and-url-ux (design D10).
|
|
270
326
|
*/
|
|
271
327
|
export function isWsOriginTrusted(
|
|
272
328
|
origin: string | undefined,
|
|
273
329
|
hostHeader: string | undefined,
|
|
274
330
|
scope: WsRouteScope | null,
|
|
275
331
|
opts: CorsOriginOptions,
|
|
332
|
+
liveCapabilityValid = false,
|
|
276
333
|
): boolean {
|
|
277
|
-
if (scope === "live" && origin === "null") return
|
|
334
|
+
if (scope === "live" && origin === "null") return liveCapabilityValid;
|
|
278
335
|
return isOriginAdmitted(origin, hostHeader, opts);
|
|
279
336
|
}
|
|
280
337
|
|
|
@@ -295,7 +352,10 @@ export function isPluginWsOriginAdmitted(
|
|
|
295
352
|
admitOrigins: readonly string[],
|
|
296
353
|
opts: CorsOriginOptions,
|
|
297
354
|
): boolean {
|
|
298
|
-
if (admitOrigins.length > 0)
|
|
355
|
+
if (admitOrigins.length > 0) {
|
|
356
|
+
// A plugin's own allow-list cannot re-admit a preview origin either (D4).
|
|
357
|
+
return origin !== undefined && !isPreviewShapedOriginUrl(origin) && admitOrigins.includes(origin);
|
|
358
|
+
}
|
|
299
359
|
return isWsOriginTrusted(origin, hostHeader, null, opts);
|
|
300
360
|
}
|
|
301
361
|
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whole-file AES-256-GCM envelope for the two credential files, plus the
|
|
3
|
+
* `JsonFileCodec` that plugs it into `locked-json-file` (opt-in `codec`).
|
|
4
|
+
*
|
|
5
|
+
* Format (D2): a magic first line, then ONE JSON line:
|
|
6
|
+
*
|
|
7
|
+
* pi-dashboard-encrypted:v1
|
|
8
|
+
* {"alg":"A256GCM","kid":"<16 hex>","iv":"<b64 12 B>","tag":"<b64 16 B>","ct":"<b64>"}
|
|
9
|
+
*
|
|
10
|
+
* Pure module: no key resolution, no keychain, no logging. Key material never
|
|
11
|
+
* appears in a return value, an error or a message here.
|
|
12
|
+
*
|
|
13
|
+
* Classification contract (D3): any file whose first line starts with
|
|
14
|
+
* `pi-dashboard-encrypted:` is an envelope and is NEVER `corrupt`: an unknown
|
|
15
|
+
* version is `unsupported`, a bad v1 header is `damaged`.
|
|
16
|
+
*
|
|
17
|
+
* See change: encrypt-credentials-at-rest (D1, D2, D3).
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
|
21
|
+
import {
|
|
22
|
+
type CredentialFileId,
|
|
23
|
+
type CredentialKeyFailureReason,
|
|
24
|
+
type CredentialLockReason,
|
|
25
|
+
credentialRemedy,
|
|
26
|
+
ENVELOPE_MAGIC_PREFIX,
|
|
27
|
+
ENVELOPE_MAGIC_V1,
|
|
28
|
+
} from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
|
|
29
|
+
import type { JsonFileCodec } from "./locked-json-file.js";
|
|
30
|
+
|
|
31
|
+
export type EnvelopeClass = "absent" | "envelope" | "plaintext" | "unsupported" | "damaged" | "corrupt";
|
|
32
|
+
|
|
33
|
+
export type EnvelopeDecodeResult =
|
|
34
|
+
| { kind: "document"; doc: Record<string, unknown>; kid: string }
|
|
35
|
+
| { kind: "locked"; reason: Extract<CredentialLockReason, "key_mismatch" | "unsupported_format" | "envelope_damaged"> }
|
|
36
|
+
| { kind: "not-envelope"; class: "absent" | "plaintext" | "corrupt"; doc?: Record<string, unknown> };
|
|
37
|
+
|
|
38
|
+
export type KeyAvailability = { ok: true; key: Buffer } | { ok: false; reason: CredentialKeyFailureReason };
|
|
39
|
+
|
|
40
|
+
const KEY_BYTES = 32;
|
|
41
|
+
const IV_BYTES = 12;
|
|
42
|
+
const TAG_BYTES = 16;
|
|
43
|
+
const ALG = "A256GCM";
|
|
44
|
+
const KID_PREFIX = Buffer.from("pi-dashboard-kid\0");
|
|
45
|
+
const KID_RE = /^[0-9a-f]{16}$/;
|
|
46
|
+
|
|
47
|
+
/** First 8 bytes of SHA-256("pi-dashboard-kid\0" ‖ key), hex. One-way: tells keys apart without revealing one. */
|
|
48
|
+
export function deriveKid(key: Buffer): string {
|
|
49
|
+
return createHash("sha256").update(KID_PREFIX).update(key).digest("hex").slice(0, 16);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const aadFor = (fileId: CredentialFileId) => Buffer.from(`pi-dashboard:v1:${fileId}`);
|
|
53
|
+
|
|
54
|
+
function assertKey(key: Buffer): void {
|
|
55
|
+
if (!Buffer.isBuffer(key) || key.length !== KEY_BYTES) throw new TypeError("credential key must be 32 bytes");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Strict standard base64: canonical padding, canonical round trip. Returns undefined when invalid. */
|
|
59
|
+
function strictBase64(value: unknown): Buffer | undefined {
|
|
60
|
+
if (typeof value !== "string" || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value)) return undefined;
|
|
61
|
+
const buf = Buffer.from(value, "base64");
|
|
62
|
+
return buf.toString("base64") === value ? buf : undefined;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
interface ParsedHeader {
|
|
66
|
+
kid: string;
|
|
67
|
+
iv: Buffer;
|
|
68
|
+
tag: Buffer;
|
|
69
|
+
ct: Buffer;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
type Analysis =
|
|
73
|
+
| { kind: "absent" }
|
|
74
|
+
| { kind: "plaintext"; doc: Record<string, unknown> }
|
|
75
|
+
| { kind: "corrupt" }
|
|
76
|
+
| { kind: "unsupported" }
|
|
77
|
+
| { kind: "damaged" }
|
|
78
|
+
| { kind: "envelope"; header: ParsedHeader };
|
|
79
|
+
|
|
80
|
+
type BytesLike = Buffer | Uint8Array | string | null | undefined;
|
|
81
|
+
|
|
82
|
+
function parseEnvelopeFile(text: string): Analysis {
|
|
83
|
+
const lines = text.split(/\r?\n/);
|
|
84
|
+
if (lines[0] !== ENVELOPE_MAGIC_V1) return { kind: "unsupported" };
|
|
85
|
+
// Anything but whitespace after the envelope line is damage; a trailing newline is not.
|
|
86
|
+
if (lines.slice(2).some((l) => l.trim().length > 0)) return { kind: "damaged" };
|
|
87
|
+
let raw: unknown;
|
|
88
|
+
try {
|
|
89
|
+
raw = JSON.parse(lines[1] ?? "");
|
|
90
|
+
} catch {
|
|
91
|
+
return { kind: "damaged" };
|
|
92
|
+
}
|
|
93
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return { kind: "damaged" };
|
|
94
|
+
const h = raw as Record<string, unknown>;
|
|
95
|
+
if (h.alg !== ALG || typeof h.kid !== "string" || !KID_RE.test(h.kid)) return { kind: "damaged" };
|
|
96
|
+
const iv = strictBase64(h.iv);
|
|
97
|
+
const tag = strictBase64(h.tag);
|
|
98
|
+
const ct = strictBase64(h.ct);
|
|
99
|
+
if (!iv || iv.length !== IV_BYTES || !tag || tag.length !== TAG_BYTES || !ct || ct.length === 0) {
|
|
100
|
+
return { kind: "damaged" };
|
|
101
|
+
}
|
|
102
|
+
return { kind: "envelope", header: { kid: h.kid, iv, tag, ct } };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function parsePlainFile(text: string): Analysis {
|
|
106
|
+
try {
|
|
107
|
+
const parsed: unknown = JSON.parse(text);
|
|
108
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
109
|
+
return { kind: "plaintext", doc: parsed as Record<string, unknown> };
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
/* corrupt below */
|
|
113
|
+
}
|
|
114
|
+
return { kind: "corrupt" };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function analyze(bytes: BytesLike): Analysis {
|
|
118
|
+
if (bytes === null || bytes === undefined) return { kind: "absent" };
|
|
119
|
+
let text = typeof bytes === "string" ? bytes : Buffer.from(bytes).toString("utf8");
|
|
120
|
+
if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); // one leading BOM
|
|
121
|
+
// The magic prefix decides: such a file is never "corrupt".
|
|
122
|
+
return text.startsWith(ENVELOPE_MAGIC_PREFIX) ? parseEnvelopeFile(text) : parsePlainFile(text);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** Classify raw file bytes (`null`/`undefined` = the file is absent). */
|
|
126
|
+
export function classify(bytes: BytesLike): EnvelopeClass {
|
|
127
|
+
return analyze(bytes).kind;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Encrypt `doc` as a v1 envelope file for `fileId`. A fresh random IV per call. */
|
|
131
|
+
export function encodeEnvelope(doc: unknown, key: Buffer, fileId: CredentialFileId): Buffer {
|
|
132
|
+
assertKey(key);
|
|
133
|
+
const iv = randomBytes(IV_BYTES);
|
|
134
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
135
|
+
cipher.setAAD(aadFor(fileId));
|
|
136
|
+
const ct = Buffer.concat([cipher.update(Buffer.from(JSON.stringify(doc), "utf8")), cipher.final()]);
|
|
137
|
+
const header = { alg: ALG, kid: deriveKid(key), iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), ct: ct.toString("base64") };
|
|
138
|
+
return Buffer.from(`${ENVELOPE_MAGIC_V1}\n${JSON.stringify(header)}\n`, "utf8");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Authenticate and decrypt a well-formed header. Any failure is `locked`, never a partial document. */
|
|
142
|
+
function decryptHeader(header: ParsedHeader, key: Buffer, fileId: CredentialFileId): EnvelopeDecodeResult {
|
|
143
|
+
if (header.kid !== deriveKid(key)) return { kind: "locked", reason: "key_mismatch" };
|
|
144
|
+
let plain: Buffer;
|
|
145
|
+
try {
|
|
146
|
+
const decipher = createDecipheriv("aes-256-gcm", key, header.iv);
|
|
147
|
+
decipher.setAAD(aadFor(fileId));
|
|
148
|
+
decipher.setAuthTag(header.tag);
|
|
149
|
+
plain = Buffer.concat([decipher.update(header.ct), decipher.final()]);
|
|
150
|
+
} catch {
|
|
151
|
+
return { kind: "locked", reason: "key_mismatch" };
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const doc: unknown = JSON.parse(plain.toString("utf8"));
|
|
155
|
+
if (doc !== null && typeof doc === "object" && !Array.isArray(doc)) {
|
|
156
|
+
return { kind: "document", doc: doc as Record<string, unknown>, kid: header.kid };
|
|
157
|
+
}
|
|
158
|
+
} catch {
|
|
159
|
+
/* authenticated but not a JSON object: damaged */
|
|
160
|
+
}
|
|
161
|
+
return { kind: "locked", reason: "envelope_damaged" };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The result for analyses that need no key. */
|
|
165
|
+
function withoutKey(a: Exclude<Analysis, { kind: "envelope" }>): EnvelopeDecodeResult {
|
|
166
|
+
if (a.kind === "unsupported") return { kind: "locked", reason: "unsupported_format" };
|
|
167
|
+
if (a.kind === "damaged") return { kind: "locked", reason: "envelope_damaged" };
|
|
168
|
+
if (a.kind === "plaintext") return { kind: "not-envelope", class: "plaintext", doc: a.doc };
|
|
169
|
+
return { kind: "not-envelope", class: a.kind };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Decode an envelope. Never returns a partial document: any failure is a
|
|
174
|
+
* `locked` result with exactly one reason. Non-envelope bytes are reported as
|
|
175
|
+
* `not-envelope` (plaintext carries its parsed document).
|
|
176
|
+
*/
|
|
177
|
+
export function decodeEnvelope(bytes: BytesLike, key: Buffer, fileId: CredentialFileId): EnvelopeDecodeResult {
|
|
178
|
+
assertKey(key);
|
|
179
|
+
const a = analyze(bytes);
|
|
180
|
+
return a.kind === "envelope" ? decryptHeader(a.header, key, fileId) : withoutKey(a);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Thrown when a credential write is refused. Carries a non-secret reason and the fixed remedy text. */
|
|
184
|
+
export class CredentialLockedError extends Error {
|
|
185
|
+
readonly code = "credential_locked";
|
|
186
|
+
readonly reason: CredentialLockReason;
|
|
187
|
+
constructor(reason: CredentialLockReason) {
|
|
188
|
+
super(`Credential write refused (${reason}). ${credentialRemedy(reason)}`);
|
|
189
|
+
this.name = "CredentialLockedError";
|
|
190
|
+
this.reason = reason;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Codec over a key getter. `getKey` is called on every decode/encode, so a
|
|
196
|
+
* singleton can answer "not ready" until the key has been resolved.
|
|
197
|
+
*/
|
|
198
|
+
export function createEnvelopeCodec(fileId: CredentialFileId, getKey: () => KeyAvailability): JsonFileCodec {
|
|
199
|
+
const decode: JsonFileCodec["decode"] = (bytes) => {
|
|
200
|
+
const a = analyze(bytes);
|
|
201
|
+
let out: EnvelopeDecodeResult;
|
|
202
|
+
if (a.kind === "envelope") {
|
|
203
|
+
const k = getKey();
|
|
204
|
+
if (!k.ok) return { kind: "locked", reason: k.reason };
|
|
205
|
+
out = decryptHeader(a.header, k.key, fileId);
|
|
206
|
+
} else {
|
|
207
|
+
if (a.kind === "absent") return { kind: "absent" };
|
|
208
|
+
out = withoutKey(a);
|
|
209
|
+
}
|
|
210
|
+
if (out.kind === "document") return { kind: "document", data: out.doc, encrypted: true };
|
|
211
|
+
if (out.kind === "locked") return { kind: "locked", reason: out.reason };
|
|
212
|
+
if (out.class === "plaintext" && out.doc) return { kind: "document", data: out.doc, encrypted: false };
|
|
213
|
+
return { kind: "corrupt" };
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
fileId,
|
|
217
|
+
decode,
|
|
218
|
+
unavailableReason: () => {
|
|
219
|
+
const k = getKey();
|
|
220
|
+
return k.ok ? undefined : k.reason;
|
|
221
|
+
},
|
|
222
|
+
encode: (data, existing) => {
|
|
223
|
+
// Never overwrite an envelope this process cannot read.
|
|
224
|
+
if (existing) {
|
|
225
|
+
const cur = decode(existing);
|
|
226
|
+
if (cur.kind === "locked") throw new CredentialLockedError(cur.reason);
|
|
227
|
+
}
|
|
228
|
+
const k = getKey();
|
|
229
|
+
if (!k.ok) throw new CredentialLockedError(k.reason);
|
|
230
|
+
return encodeEnvelope(data, k.key, fileId);
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|