@blackbelt-technology/pi-agent-dashboard 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -0
- package/README.md +17 -12
- package/docs/architecture.md +973 -224
- package/package.json +29 -18
- package/packages/extension/package.json +16 -9
- package/packages/extension/src/bridge-context.ts +6 -0
- package/packages/extension/src/bridge-handlers/dispatch.ts +54 -69
- package/packages/extension/src/bridge-handlers/forwarders.ts +19 -42
- package/packages/extension/src/bridge-handlers/instance.ts +21 -12
- package/packages/extension/src/bridge-handlers/lifecycle.ts +84 -40
- package/packages/extension/src/bridge-shutdown.ts +44 -0
- package/packages/extension/src/bridge.ts +272 -260
- package/packages/extension/src/command-handler.ts +26 -31
- package/packages/extension/src/connection.ts +123 -31
- package/packages/extension/src/credential-guard.ts +300 -0
- package/packages/extension/src/custom-entry-forward.ts +27 -18
- package/packages/extension/src/default-model-apply.ts +83 -0
- package/packages/extension/src/flow-event-wiring.ts +19 -95
- package/packages/extension/src/followup-drain.ts +19 -5
- package/packages/extension/src/path-gate/decide.ts +68 -5
- package/packages/extension/src/path-gate/handler.ts +16 -8
- package/packages/extension/src/path-gate/index.ts +2 -2
- package/packages/extension/src/path-gate/roots.ts +15 -3
- package/packages/extension/src/path-gate/suppression.ts +3 -0
- package/packages/extension/src/pi-env.d.ts +8 -1
- package/packages/extension/src/pi-retry-settings.ts +11 -2
- package/packages/extension/src/plugin-event-forward-registry.ts +90 -14
- package/packages/extension/src/preview-path-link.ts +151 -0
- package/packages/extension/src/project-init/scaffold.ts +98 -35
- package/packages/extension/src/project-trust.ts +24 -15
- package/packages/extension/src/provider-model-cache.ts +118 -0
- package/packages/extension/src/provider-register.ts +428 -28
- package/packages/extension/src/retry-tracker.ts +90 -7
- package/packages/extension/src/role-manager.ts +4 -2
- package/packages/extension/src/role-model-tools.ts +21 -4
- package/packages/extension/src/server-auto-start.ts +68 -2
- package/packages/extension/src/server-launcher.ts +26 -8
- package/packages/extension/src/session-sync.ts +11 -12
- package/packages/extension/src/spawn-new-session.ts +22 -0
- package/packages/extension/src/steer-buffer.ts +164 -0
- package/packages/extension/src/stream-forward-buffer.ts +64 -15
- package/packages/extension/src/sudo-askpass/config-reader.ts +32 -0
- package/packages/extension/src/sudo-askpass/controller.ts +405 -0
- package/packages/extension/src/sudo-askpass/helper-script.ts +69 -0
- package/packages/extension/src/sudo-askpass/in-flight.ts +79 -0
- package/packages/extension/src/sudo-askpass/index.ts +11 -0
- package/packages/extension/src/sudo-askpass/install.ts +143 -0
- package/packages/extension/src/sudo-askpass/password-cache.ts +118 -0
- package/packages/extension/src/sudo-askpass/prompt-text.ts +55 -0
- package/packages/extension/src/sudo-askpass/protocol.ts +18 -0
- package/packages/extension/src/sudo-askpass/sudo-mask-registry.ts +52 -0
- package/packages/extension/src/terminal-reload.ts +19 -5
- package/packages/extension/src/tool-update-filter-registry.ts +210 -0
- package/packages/extension/src/vault-redaction.ts +4 -3
- package/packages/server/package.json +17 -14
- package/packages/server/src/access/access-denials.ts +8 -0
- package/packages/server/src/access/access-grants.ts +244 -58
- package/packages/server/src/access/access-plane.ts +7 -0
- package/packages/server/src/access/containment-gate.ts +66 -21
- package/packages/server/src/access/denial-hold.ts +3 -0
- package/packages/server/src/access/grant-coordinator.ts +17 -1
- package/packages/server/src/access/named-grant.ts +3 -0
- package/packages/server/src/access/pending-grant-registry.ts +32 -5
- package/packages/server/src/access/pi-trust-mirror-service.ts +7 -1
- package/packages/server/src/access/planes.ts +1 -0
- package/packages/server/src/access/verified-read.ts +24 -7
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +10 -2
- package/packages/server/src/acp-bridge/server-requests.ts +10 -4
- package/packages/server/src/agent-events/agent-event-hub.ts +1 -1
- package/packages/server/src/auth/audit-log.ts +28 -0
- package/packages/server/src/auth/auth-plugin.ts +188 -15
- package/packages/server/src/auth/auth.ts +80 -0
- package/packages/server/src/auth/bridge-ticket-eligibility.ts +53 -10
- package/packages/server/src/auth/cors-origin.ts +14 -1
- package/packages/server/src/auth/credential-envelope.ts +233 -0
- package/packages/server/src/auth/credential-key-worker.d.mts +16 -0
- package/packages/server/src/auth/credential-key-worker.mjs +108 -0
- package/packages/server/src/auth/credential-key.ts +479 -0
- package/packages/server/src/auth/credential-migration.ts +162 -0
- package/packages/server/src/auth/csp-report-paths.ts +0 -5
- package/packages/server/src/auth/csp.ts +74 -36
- package/packages/server/src/auth/device-proof.ts +202 -0
- package/packages/server/src/auth/duplicate-cookie-gate.ts +271 -0
- package/packages/server/src/auth/host-admission.ts +7 -0
- package/packages/server/src/auth/host-gate.ts +13 -2
- package/packages/server/src/auth/localhost-guard.ts +50 -23
- package/packages/server/src/auth/locked-json-file.ts +68 -6
- package/packages/server/src/auth/models-json-store.ts +269 -0
- package/packages/server/src/auth/mutation-origin-gate.ts +5 -2
- package/packages/server/src/auth/node-guard.ts +36 -49
- package/packages/server/src/auth/plugin-credential-store.ts +81 -10
- package/packages/server/src/auth/provider-auth-storage.ts +208 -11
- package/packages/server/src/auth/provider-block-checks.ts +321 -0
- package/packages/server/src/auth/provider-host-detect.ts +151 -0
- package/packages/server/src/auth/provider-key-file.ts +71 -0
- package/packages/server/src/auth/provider-readiness.ts +91 -0
- package/packages/server/src/auth/route-tier-gate.ts +3 -2
- package/packages/server/src/auth/vertex-key-check.ts +140 -0
- package/packages/server/src/auth/ws-ticket.ts +1 -1
- package/packages/server/src/browse.ts +73 -20
- package/packages/server/src/browser-handlers/acp-guard.ts +1 -4
- package/packages/server/src/browser-handlers/directory-handler.ts +11 -24
- package/packages/server/src/browser-handlers/session-action-handler.ts +158 -62
- package/packages/server/src/browser-handlers/spawn-choice.ts +138 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +46 -1
- package/packages/server/src/build-plugin-send-prompt.ts +18 -0
- package/packages/server/src/cli/credentials-command.ts +555 -0
- package/packages/server/src/cli.ts +21 -16
- package/packages/server/src/config-api.ts +34 -38
- package/packages/server/src/config-snapshot.ts +149 -0
- package/packages/server/src/directory-service.ts +33 -14
- package/packages/server/src/embed-lifecycle/idle-reaper.ts +13 -3
- package/packages/server/src/event-wiring.ts +181 -101
- package/packages/server/src/git-worktree/ensure-worktree.ts +185 -0
- package/packages/server/src/git-worktree/git-operations.ts +1 -1
- package/packages/server/src/git-worktree/repo-lock.ts +42 -0
- package/packages/server/src/git-worktree/start-worktree-init.ts +151 -0
- package/packages/server/src/git-worktree/worktree-init.ts +5 -1
- package/packages/server/src/identity/http-road-classification.ts +5 -1
- package/packages/server/src/identity/identity-floor.ts +5 -2
- package/packages/server/src/identity/ws-message-scope.ts +10 -3
- package/packages/server/src/identity/ws-road-classification.ts +2 -1
- package/packages/server/src/lib/browse-roots.ts +13 -2
- package/packages/server/src/lib/content-disposition.ts +20 -0
- package/packages/server/src/lib/dashboard-state-guard.ts +304 -21
- package/packages/server/src/lib/eml.ts +2 -2
- package/packages/server/src/lib/frame-policy-probe.ts +308 -0
- package/packages/server/src/lib/frame-policy-test-seam.ts +99 -0
- package/packages/server/src/lib/frame-policy-verdict.ts +125 -0
- package/packages/server/src/lib/grep.ts +4 -1
- package/packages/server/src/lib/index-html.ts +2 -2
- package/packages/server/src/lib/mention-fuzzy-index.ts +263 -0
- package/packages/server/src/lib/office-preview.ts +47 -10
- package/packages/server/src/lib/path-containment.ts +45 -12
- package/packages/server/src/lib/resolve-file-mention.ts +230 -38
- package/packages/server/src/lib/resolve-mentions-batch.ts +143 -0
- package/packages/server/src/lib/writable-handler-target.ts +4 -0
- package/packages/server/src/lib/writable-md-target.ts +22 -0
- package/packages/server/src/lifecycle/boot-parent-liveness.ts +10 -25
- package/packages/server/src/lifecycle/credential-exit-barrier.ts +207 -0
- package/packages/server/src/lifecycle/exit-signal.ts +43 -0
- package/packages/server/src/live-server/capability-redact.ts +21 -5
- package/packages/server/src/live-server/live-capability.ts +416 -52
- package/packages/server/src/live-server/live-csp-report.ts +1 -1
- package/packages/server/src/live-server/live-csp.ts +64 -16
- package/packages/server/src/live-server/live-log.ts +5 -1
- package/packages/server/src/live-server/live-server-manager.ts +11 -0
- package/packages/server/src/live-server/live-server-proxy.ts +268 -52
- package/packages/server/src/live-server/live-static.ts +4 -1
- package/packages/server/src/live-server/preview-dispatch.ts +286 -0
- package/packages/server/src/live-server/preview-observe.ts +53 -0
- package/packages/server/src/live-server/preview-origin.ts +182 -0
- package/packages/server/src/live-server/preview-path-bridge.ts +70 -0
- package/packages/server/src/live-server/preview-path-store.ts +420 -0
- package/packages/server/src/live-server/preview-path.ts +40 -0
- package/packages/server/src/live-server/preview-pool.ts +385 -0
- package/packages/server/src/live-server/preview-preflight.ts +41 -0
- package/packages/server/src/live-server/preview-reserve.ts +44 -0
- package/packages/server/src/live-server/preview-tier.ts +217 -0
- package/packages/server/src/live-server/preview-viewers.ts +54 -0
- package/packages/server/src/live-server/preview-ws-registry.ts +43 -0
- package/packages/server/src/model-proxy/custom-provider-discovery.ts +4 -2
- package/packages/server/src/model-proxy/internal-auth-storage.ts +5 -1
- package/packages/server/src/model-proxy/internal-registry.ts +283 -21
- package/packages/server/src/model-proxy/models-block-apply.ts +291 -0
- package/packages/server/src/model-proxy/pi-models-validator.ts +164 -0
- package/packages/server/src/model-proxy/registry-singleton.ts +44 -9
- package/packages/server/src/model-proxy/server-model-runtime.ts +17 -0
- package/packages/server/src/openspec/readiness.ts +1 -1
- package/packages/server/src/package/provider-probe.ts +194 -5
- package/packages/server/src/pairing/browser-gateway.ts +140 -42
- package/packages/server/src/pairing/device-key-intake.ts +120 -0
- package/packages/server/src/pairing/paired-devices.ts +370 -8
- package/packages/server/src/pairing/pairing.ts +69 -7
- package/packages/server/src/pairing/{subagent-resync-routing.ts → resync-requester-registry.ts} +6 -10
- package/packages/server/src/pairing/ws-tier-gate.ts +74 -0
- package/packages/server/src/pending/pending-attach-registry.ts +15 -0
- package/packages/server/src/pending/pending-initial-prompt-registry.ts +15 -0
- package/packages/server/src/persistence/memory-event-store.ts +251 -296
- package/packages/server/src/persistence/preferences-store.ts +52 -2
- package/packages/server/src/pi/bridge-contention.ts +84 -2
- package/packages/server/src/pi/host-project-trust.ts +15 -9
- package/packages/server/src/pi/pi-gateway.ts +208 -21
- package/packages/server/src/pi/provisional-registration.ts +4 -1
- package/packages/server/src/pi/resource-toggle-trust.ts +17 -6
- package/packages/server/src/pi-agent-settings.ts +95 -301
- package/packages/server/src/pi-default-remirror.ts +89 -0
- package/packages/server/src/plugin-append-event.ts +35 -0
- package/packages/server/src/plugin-entry-stats.ts +61 -0
- package/packages/server/src/plugin-local-request.ts +207 -0
- package/packages/server/src/plugin-ownership.ts +111 -0
- package/packages/server/src/plugin-policy-registry.ts +297 -0
- package/packages/server/src/plugin-request-lane.ts +92 -16
- package/packages/server/src/preferences-relay.ts +20 -0
- package/packages/server/src/project-seed.ts +347 -0
- package/packages/server/src/push/push-transports/webhook-url.ts +8 -5
- package/packages/server/src/questions/question-store.ts +3 -2
- package/packages/server/src/routes/access-routes.ts +23 -6
- package/packages/server/src/routes/acme-routes.ts +14 -4
- package/packages/server/src/routes/agent-event-stream-routes.ts +1 -1
- package/packages/server/src/routes/file-routes.ts +327 -86
- package/packages/server/src/routes/file-write-binary-routes.ts +20 -4
- package/packages/server/src/routes/frame-policy-routes.ts +215 -0
- package/packages/server/src/routes/git-routes.ts +29 -78
- package/packages/server/src/routes/grep-routes.ts +26 -0
- package/packages/server/src/routes/live-server-routes.ts +198 -4
- package/packages/server/src/routes/models-introspection-routes.ts +1 -1
- package/packages/server/src/routes/openspec-routes.ts +17 -3
- package/packages/server/src/routes/pairing-routes.ts +200 -11
- package/packages/server/src/routes/pi-settings-routes.ts +2 -0
- package/packages/server/src/routes/preferences-auto-name-routes.ts +5 -2
- package/packages/server/src/routes/preferences-claude-compat-routes.ts +49 -0
- package/packages/server/src/routes/provider-auth-routes.ts +167 -9
- package/packages/server/src/routes/provider-override-routes.ts +158 -0
- package/packages/server/src/routes/provider-routes.ts +348 -86
- package/packages/server/src/routes/session-routes.ts +25 -22
- package/packages/server/src/routes/system-routes.ts +87 -39
- package/packages/server/src/rpc-keeper/keeper-manager.ts +196 -25
- package/packages/server/src/rpc-keeper/keeper.cjs +37 -23
- package/packages/server/src/runtime-overlay/extension-reload.ts +16 -10
- package/packages/server/src/runtime-overlay/runtime-stager.ts +4 -2
- package/packages/server/src/server.ts +512 -175
- package/packages/server/src/services/cli-service.ts +59 -10
- package/packages/server/src/services/secrets-resolver.ts +46 -30
- package/packages/server/src/session/custom-event-group-annotation.ts +3 -3
- package/packages/server/src/session/custom-event-group-resolver.ts +10 -5
- package/packages/server/src/session/death-reason.ts +11 -7
- package/packages/server/src/session/event-status-extraction.ts +5 -1
- package/packages/server/src/session/memory-session-manager.ts +24 -2
- package/packages/server/src/session/open-tool-calls.ts +81 -47
- package/packages/server/src/session/pid-target.ts +127 -0
- package/packages/server/src/session/replay-compaction.ts +18 -5
- package/packages/server/src/session/seed-discovered-history.ts +85 -0
- package/packages/server/src/session/server-pid-context.ts +14 -0
- package/packages/server/src/session/session-api.ts +78 -29
- package/packages/server/src/session/session-archive.ts +7 -0
- package/packages/server/src/session/session-bootstrap.ts +9 -54
- package/packages/server/src/session/session-load-worker-pool.ts +11 -1
- package/packages/server/src/session/session-load-worker.ts +22 -3
- package/packages/server/src/spawn-process/abort-spawned-run.ts +28 -9
- package/packages/server/src/spawn-process/acp-spawn.ts +8 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +383 -72
- package/packages/server/src/spawn-process/link-register.ts +42 -0
- package/packages/server/src/spawn-process/plugin-spawn-choice.ts +48 -0
- package/packages/server/src/spawn-process/plugin-spawn-worktree.ts +290 -0
- package/packages/server/src/spawn-process/process-classifier.ts +8 -3
- package/packages/server/src/spawn-process/process-manager.ts +61 -6
- package/packages/server/src/spawn-process/restored-identity.ts +112 -0
- package/packages/server/src/spawn-process/session-terminator.ts +179 -18
- package/packages/server/src/spawn-process/spawn-env-contributors.ts +2 -1
- package/packages/server/src/spawn-process/spawn-failure-log.ts +9 -0
- package/packages/server/src/spawn-process/spawn-register-watchdog.ts +44 -19
- package/packages/server/src/sudo-credential/relay.ts +337 -0
- package/packages/server/src/terminal/terminal-gateway.ts +10 -0
- package/packages/server/src/tls/sources/acme/credentials.ts +3 -2
- package/packages/server/src/tls/sources/acme/runtime.ts +2 -1
- package/packages/server/src/vault/vault-delivery-hub.ts +17 -1
- package/packages/server/src/vault/vault-routes.ts +9 -2
- package/packages/server/src/vault/vault-store.ts +87 -24
- package/packages/server/vendor/xlsx/LICENSE +201 -0
- package/packages/server/vendor/xlsx/PROVENANCE.json +13 -0
- package/packages/server/vendor/xlsx/xlsx.d.mts +1065 -0
- package/packages/server/vendor/xlsx/xlsx.mjs +28228 -0
- package/packages/shared/package.json +4 -2
- package/packages/shared/src/agent-credential-files.ts +32 -0
- package/packages/shared/src/browser-protocol.ts +137 -57
- package/packages/shared/src/canvas-detect.ts +1 -1
- package/packages/shared/src/canvas-types.ts +2 -2
- package/packages/shared/src/config.ts +73 -136
- package/packages/shared/src/containment-guard.ts +14 -4
- package/packages/shared/src/credential-encryption.ts +87 -0
- package/packages/shared/src/custom-event-groups.ts +2 -0
- package/packages/shared/src/dashboard-plugin/claude-compat.ts +159 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +1 -1
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +4 -3
- package/packages/shared/src/dashboard-plugin/replay-entry-types.ts +46 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +2 -0
- package/packages/shared/src/dashboard-plugin/slot-types.ts +1 -1
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +11 -3
- package/packages/shared/src/device-key-proof.ts +309 -0
- package/packages/shared/src/event-forward-declaration.ts +85 -12
- package/packages/shared/src/forbidden-subjects.ts +126 -14
- package/packages/shared/src/heap-limits.ts +0 -30
- package/packages/shared/src/host-admission.ts +2 -1
- package/packages/shared/src/index.ts +7 -6
- package/packages/shared/src/live-server.ts +20 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +1 -3
- package/packages/shared/src/models-json-reader.ts +41 -0
- package/packages/shared/src/network-denial-signal.ts +15 -0
- package/packages/shared/src/node-version.ts +63 -60
- package/packages/shared/src/pairing-knock-client.ts +92 -8
- package/packages/shared/src/pi-agent-settings-lock.ts +311 -0
- package/packages/shared/src/pi-path-compare.ts +31 -0
- package/packages/shared/src/pi-settings-schema.ts +52 -9
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +16 -4
- package/packages/shared/src/pi-trust-mirror-types.ts +2 -0
- package/packages/shared/src/pi-trust-mirror.ts +18 -8
- package/packages/shared/src/pi-trust-resource-digest.ts +18 -12
- package/packages/shared/src/pid-namespace.ts +86 -0
- package/packages/shared/src/platform/native-ts-register.mjs +1 -1
- package/packages/shared/src/platform/process.ts +404 -1
- package/packages/shared/src/platform/resolve-pi-shell.ts +38 -9
- package/packages/shared/src/platform/spawn-runtime.ts +193 -7
- package/packages/shared/src/preview-egress.ts +56 -2
- package/packages/shared/src/preview-origins.ts +398 -0
- package/packages/shared/src/prompt-answer.ts +9 -5
- package/packages/shared/src/protocol.ts +147 -85
- package/packages/shared/src/provider-env-catalog.ts +413 -0
- package/packages/shared/src/provider-overrides.ts +112 -0
- package/packages/shared/src/question-types.ts +6 -0
- package/packages/shared/src/recommended-extensions.ts +79 -26
- package/packages/shared/src/renderer-by-ext.ts +5 -2
- package/packages/shared/src/rest-api.ts +93 -3
- package/packages/shared/src/role-schema.ts +24 -0
- package/packages/shared/src/route-tiers.ts +94 -3
- package/packages/shared/src/runtime-overlay/compat.ts +70 -6
- package/packages/shared/src/secret-patterns.ts +49 -0
- package/packages/shared/src/source-matching.ts +2 -2
- package/packages/shared/src/state-replay.ts +40 -24
- package/packages/shared/src/sudo-credential.ts +71 -0
- package/packages/shared/src/tool-path-resolve.ts +16 -1
- package/packages/shared/src/tool-registry/strategies.ts +1 -1
- package/packages/shared/src/tool-workdir.ts +56 -0
- package/packages/shared/src/trusted-types-mode.ts +72 -0
- package/packages/shared/src/types.ts +68 -109
- package/packages/shared/src/vertex-regions.ts +81 -0
- package/packages/shared/src/ws-message-tiers.ts +10 -3
- package/packages/extension/src/subagent-fanout-admission.ts +0 -234
- package/packages/extension/src/subagent-forward-sites.ts +0 -69
- package/packages/extension/src/subagent-frame-buffer.ts +0 -245
- package/packages/extension/src/subagent-frame-strip.ts +0 -109
- package/packages/extension/src/subagent-saturation.ts +0 -196
- package/packages/extension/src/subagent-tick-throttle.ts +0 -252
- package/packages/shared/src/anthropic-messages-source.ts +0 -8
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +0 -9
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +0 -219
|
@@ -18,10 +18,13 @@
|
|
|
18
18
|
*/
|
|
19
19
|
import crypto from "node:crypto";
|
|
20
20
|
import type { Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
|
|
21
|
+
import type { ResolvedPreviewOrigins } from "@blackbelt-technology/pi-dashboard-shared/preview-origins.js";
|
|
21
22
|
import type { Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
|
|
22
23
|
import type { TokenPayload } from "../auth/auth.js";
|
|
23
24
|
import { isLocallyTrusted } from "../auth/localhost-guard.js";
|
|
24
25
|
import { CAPABILITY_SEGMENT, redactCapability } from "./capability-redact.js";
|
|
26
|
+
import { generatePreviewLabel, hashPreviewKey, splitCanonicalHost } from "./preview-origin.js";
|
|
27
|
+
import { parsePreviewPath } from "./preview-path.js";
|
|
25
28
|
|
|
26
29
|
// Lifetime note: a capability's life is bounded by its own idle/absolute limits and
|
|
27
30
|
// by revocation (target removed, device revoked, logout / passkey revoke, restart).
|
|
@@ -39,6 +42,26 @@ const MAX_TOKENS = 1024;
|
|
|
39
42
|
/** Live tokens per minting principal: one caller's mint loop evicts only ITS OWN oldest tokens. */
|
|
40
43
|
const MAX_TOKENS_PER_PRINCIPAL = 64;
|
|
41
44
|
const TOKEN_SHAPE = /^[A-Za-z0-9_-]{22,}$/;
|
|
45
|
+
/** A mint for tiers 1-4 returns the live entry only while MORE than this remains: twice the 10-minute client re-mint lead (D2). */
|
|
46
|
+
const REUSE_MIN_REMAINING_MS = 20 * 60_000;
|
|
47
|
+
/** The store owns an `unref()`'d sweep so idle entries (and their pool ports) release without waiting for a mint (Q12). */
|
|
48
|
+
const SWEEP_INTERVAL_MS = 60_000;
|
|
49
|
+
/** Attempts to find a label not already in the index before the mint fails. */
|
|
50
|
+
const LABEL_RETRIES = 8;
|
|
51
|
+
|
|
52
|
+
/** Capability tier: 1-4 are origin-bound previews (D1), 5 the stable `/preview/<pid>/` path (D8, `PreviewPathStore`); `legacy` is the `/live/<id>/~c/<token>/` path. */
|
|
53
|
+
export type CapabilityTier = 1 | 2 | 3 | 4 | 5 | "legacy";
|
|
54
|
+
|
|
55
|
+
/** Why an entry left the store — the `onDelete` reason (D5, D13). */
|
|
56
|
+
export type CapabilityDeleteReason =
|
|
57
|
+
| "idle"
|
|
58
|
+
| "max"
|
|
59
|
+
| "revoked"
|
|
60
|
+
| "evicted"
|
|
61
|
+
| "disabled"
|
|
62
|
+
| "shutdown"
|
|
63
|
+
| "config-changed"
|
|
64
|
+
| "listener-error";
|
|
42
65
|
|
|
43
66
|
/** Who minted a capability — the identity and tier an accepted request carries. */
|
|
44
67
|
export interface CapabilityPrincipal {
|
|
@@ -76,7 +99,7 @@ export type LiveExposure = "local-only" | "exposed";
|
|
|
76
99
|
const VIEWER_ID_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
|
|
77
100
|
export const isViewerId = (v: unknown): v is string => typeof v === "string" && VIEWER_ID_SHAPE.test(v);
|
|
78
101
|
|
|
79
|
-
interface
|
|
102
|
+
export interface LiveCapabilityEntry {
|
|
80
103
|
targetId: string;
|
|
81
104
|
principal: CapabilityPrincipal;
|
|
82
105
|
mintedAt: number;
|
|
@@ -94,7 +117,20 @@ interface Entry {
|
|
|
94
117
|
localBound: boolean;
|
|
95
118
|
idleMs: number;
|
|
96
119
|
maxMs: number;
|
|
120
|
+
/** `legacy` for a `/live/<id>/~c/<token>/` path; 1-4 for an origin-bound preview (D2). */
|
|
121
|
+
tier: CapabilityTier;
|
|
122
|
+
/** Canonical `host[:port]` of the preview origin (tiers 1-4). Lookup key together with the label hash. */
|
|
123
|
+
originHost?: string;
|
|
124
|
+
/** Full origin (`scheme://originHost`). CSP sources come from here, never from the request (D6). Memory only. */
|
|
125
|
+
origin?: string;
|
|
126
|
+
/** Plaintext label (tiers 1, 2, 4). Memory only: never persisted, never logged unredacted. */
|
|
127
|
+
label?: string;
|
|
128
|
+
/** Canonical `Origin` of the mint request (fallback `scheme://Host`): who may frame this origin. */
|
|
129
|
+
ancestors: string[];
|
|
130
|
+
/** Tier 3: the pool port the listener is bound to. */
|
|
131
|
+
poolPort?: number;
|
|
97
132
|
}
|
|
133
|
+
type Entry = LiveCapabilityEntry;
|
|
98
134
|
|
|
99
135
|
/** What the capability hook / proxy learn about a validated token. Never contains the secret. */
|
|
100
136
|
export interface LiveCapabilityGrant {
|
|
@@ -105,9 +141,27 @@ export interface LiveCapabilityGrant {
|
|
|
105
141
|
viewerId?: string;
|
|
106
142
|
minterKey: string;
|
|
107
143
|
principal: CapabilityPrincipal;
|
|
144
|
+
tier: CapabilityTier;
|
|
145
|
+
origin?: string;
|
|
146
|
+
originHost?: string;
|
|
147
|
+
poolPort?: number;
|
|
148
|
+
ancestors: string[];
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Origin binding of a mint for tiers 1-4 (D1, D2). */
|
|
152
|
+
interface PreviewMintBinding {
|
|
153
|
+
tier: 1 | 2 | 3 | 4;
|
|
154
|
+
/** Canonical `Origin` of the mint request (fallback `scheme://Host`). */
|
|
155
|
+
ancestors: string[];
|
|
156
|
+
/** Tiers 1, 2, 4: builds the origin from a freshly generated label. */
|
|
157
|
+
buildOrigin?: (label: string) => { origin: string; originHost: string };
|
|
158
|
+
/** Tier 3: the bound listener's origin (`http://<ip>:<port>`), `host:port`, and port. */
|
|
159
|
+
fixed?: { origin: string; originHost: string; poolPort: number };
|
|
108
160
|
}
|
|
109
161
|
|
|
110
162
|
export interface MintOptions {
|
|
163
|
+
/** Origin binding for tiers 1-4; absent = legacy path token. */
|
|
164
|
+
preview?: PreviewMintBinding;
|
|
111
165
|
kind?: LiveTargetKind;
|
|
112
166
|
policy?: Partial<LivePolicy>;
|
|
113
167
|
viewerId?: string;
|
|
@@ -133,8 +187,25 @@ export interface LiveCapabilityStoreOptions {
|
|
|
133
187
|
isPrincipalLive?: (principal: CapabilityPrincipal) => boolean;
|
|
134
188
|
/** Is the target still registered? */
|
|
135
189
|
isTargetLive?: (targetId: string) => boolean;
|
|
190
|
+
/**
|
|
191
|
+
* Called ONCE per entry, after it has left every index, on every deletion path
|
|
192
|
+
* (idle/max, revoke, eviction, `enabled` flip, shutdown, listener error). Closes pool listeners.
|
|
193
|
+
* A throwing hook is logged (redacted) and never blocks the other deletions.
|
|
194
|
+
*/
|
|
195
|
+
onDelete?: (entry: Readonly<LiveCapabilityEntry>, reason: CapabilityDeleteReason) => void;
|
|
196
|
+
/** Resolved preview-origin config; entries it no longer covers are revoked on every sweep (D12, Q8). */
|
|
197
|
+
getPreviewConfig?: () => ResolvedPreviewOrigins | undefined;
|
|
198
|
+
/** Random bytes source for labels (tests inject collisions). */
|
|
199
|
+
labelBytes?: (n: number) => Buffer;
|
|
200
|
+
/** Sweep interval; default 60 s (tests drive it with fake timers). */
|
|
201
|
+
sweepIntervalMs?: number;
|
|
136
202
|
}
|
|
137
203
|
|
|
204
|
+
/** A host-keyed lookup result. Refusals carry the ONLY detail logs may show; the HTTP answer is identical for all. */
|
|
205
|
+
export type HostLookup =
|
|
206
|
+
| { ok: true; grant: LiveCapabilityGrant }
|
|
207
|
+
| { ok: false; reason: "unknown" | "expired" | "wrong-host" | "wrong-port" };
|
|
208
|
+
|
|
138
209
|
/** Stable identity of a minting principal (device id, session key, else the shared "local"/"network" bucket). */
|
|
139
210
|
const principalKey = (p: CapabilityPrincipal): string =>
|
|
140
211
|
p.deviceId ? `device:${p.deviceId}` : p.sessionKey ? `session:${p.sessionKey}` : p.kind;
|
|
@@ -142,41 +213,134 @@ const principalKey = (p: CapabilityPrincipal): string =>
|
|
|
142
213
|
/** Stable identity of a minting principal; the egress / touch / allow-once routes compare it. */
|
|
143
214
|
export const principalKeyOf = principalKey;
|
|
144
215
|
|
|
145
|
-
const hash =
|
|
216
|
+
const hash = hashPreviewKey;
|
|
146
217
|
|
|
147
218
|
/** sha256 of a session cookie value, for {@link CapabilityPrincipal.sessionKey}. */
|
|
148
219
|
export function sessionKeyOf(cookieValue: string): string {
|
|
149
220
|
return hash(cookieValue);
|
|
150
221
|
}
|
|
151
222
|
|
|
223
|
+
const sameList = (a: readonly string[], b: readonly string[]): boolean =>
|
|
224
|
+
a.length === b.length && a.every((v, i) => v === b[i]);
|
|
225
|
+
|
|
226
|
+
/** Does `entry` still fall under the tier's CURRENT resolved config? (Tier 1 needs none.) */
|
|
227
|
+
function entryMatchesConfig(e: Entry, cfg: ResolvedPreviewOrigins): boolean {
|
|
228
|
+
if (e.tier === "legacy" || e.tier === 1) return true;
|
|
229
|
+
if (e.tier === 3) return !!cfg.pool && e.poolPort !== undefined && e.poolPort >= cfg.pool.from && e.poolPort <= cfg.pool.to;
|
|
230
|
+
const host = e.originHost ? splitCanonicalHost(e.originHost) : undefined;
|
|
231
|
+
if (!host) return false;
|
|
232
|
+
if (e.tier === 2) {
|
|
233
|
+
const w = cfg.wildcard;
|
|
234
|
+
if (!w || !e.label) return false;
|
|
235
|
+
return host.hostname === `${e.label}.${w.suffix}` && host.port === w.port && !!e.origin?.startsWith(`${w.scheme}://`);
|
|
236
|
+
}
|
|
237
|
+
// tier 4
|
|
238
|
+
return !!cfg.ipDnsSuffix && host.hostname.endsWith(`.${cfg.ipDnsSuffix}`);
|
|
239
|
+
}
|
|
240
|
+
|
|
152
241
|
export class LiveCapabilityStore {
|
|
242
|
+
/** `hash(secret)` → entry. The secret is the label (tiers 1, 2, 4) or a random token (tier 3, legacy). */
|
|
153
243
|
private readonly entries = new Map<string, Entry>();
|
|
244
|
+
/** `hash(originHost)` → entry key (tiers 1-4): the dynamic admission set; holds no plaintext label. */
|
|
245
|
+
private readonly byOriginHost = new Map<string, string>();
|
|
154
246
|
/** viewerId → allow-once origins (insertion-ordered, bounded). */
|
|
155
247
|
private readonly allowOnce = new Map<string, Set<string>>();
|
|
156
248
|
private readonly now: () => number;
|
|
157
249
|
private readonly isPrincipalLive: (p: CapabilityPrincipal) => boolean;
|
|
158
250
|
private readonly isTargetLive: (id: string) => boolean;
|
|
251
|
+
private readonly onDelete?: LiveCapabilityStoreOptions["onDelete"];
|
|
252
|
+
private readonly getPreviewConfig?: () => ResolvedPreviewOrigins | undefined;
|
|
253
|
+
private readonly labelBytes?: (n: number) => Buffer;
|
|
254
|
+
private readonly sweepIntervalMs: number;
|
|
255
|
+
private sweeper: ReturnType<typeof setInterval> | undefined;
|
|
159
256
|
|
|
160
257
|
constructor(opts: LiveCapabilityStoreOptions = {}) {
|
|
161
258
|
this.now = opts.now ?? Date.now;
|
|
162
259
|
this.isPrincipalLive = opts.isPrincipalLive ?? (() => true);
|
|
163
260
|
this.isTargetLive = opts.isTargetLive ?? (() => true);
|
|
261
|
+
this.onDelete = opts.onDelete;
|
|
262
|
+
this.getPreviewConfig = opts.getPreviewConfig;
|
|
263
|
+
this.labelBytes = opts.labelBytes;
|
|
264
|
+
this.sweepIntervalMs = opts.sweepIntervalMs ?? SWEEP_INTERVAL_MS;
|
|
164
265
|
}
|
|
165
266
|
|
|
166
267
|
/**
|
|
167
|
-
*
|
|
268
|
+
* A live entry a new mint for tiers 1-4 may be answered with (D2 re-mint reuse): same target, minter,
|
|
269
|
+
* policy, tier and ancestors (never `viewerId`: the viewer mints a fresh id per mount), with MORE than
|
|
270
|
+
* 20 minutes of absolute lifetime left. Never resurrects an expired / revoked entry. Tier 3 callers
|
|
271
|
+
* check this BEFORE allocating a pool port.
|
|
272
|
+
*/
|
|
273
|
+
findReusable(
|
|
274
|
+
targetId: string,
|
|
275
|
+
principal: CapabilityPrincipal,
|
|
276
|
+
opts: MintOptions,
|
|
277
|
+
): { entry: Readonly<Entry>; grant: LiveCapabilityGrant } | null {
|
|
278
|
+
const b = opts.preview;
|
|
279
|
+
if (!b) return null;
|
|
280
|
+
const now = this.now();
|
|
281
|
+
const kind: LiveTargetKind = opts.kind === "static" ? "static" : "port";
|
|
282
|
+
const egress = opts.policy?.egress === "open" ? "open" : "restricted";
|
|
283
|
+
const scripts = opts.policy?.scripts === true;
|
|
284
|
+
const who = principalKey(principal);
|
|
285
|
+
for (const [key, e] of this.entries) {
|
|
286
|
+
if (e.tier !== b.tier || e.targetId !== targetId || e.minterKey !== who || e.kind !== kind) continue;
|
|
287
|
+
if (e.policy.egress !== egress || e.policy.scripts !== scripts) continue;
|
|
288
|
+
if (e.localBound !== (opts.localBound === true) || e.mintExposure !== (opts.exposure ?? "exposed")) continue;
|
|
289
|
+
if (!sameList(e.ancestors, b.ancestors)) continue;
|
|
290
|
+
if (this.expiryReason(e, now)) continue;
|
|
291
|
+
if (e.mintedAt + e.maxMs - now <= REUSE_MIN_REMAINING_MS) continue;
|
|
292
|
+
if (!this.isTargetLive(e.targetId) || !this.isPrincipalLive(e.principal)) {
|
|
293
|
+
this.remove(key, "revoked");
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
return { entry: e, grant: grantOf(e) };
|
|
297
|
+
}
|
|
298
|
+
return null;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Mint a capability for `targetId`. Only a hash is kept. The policy is fail-closed
|
|
168
303
|
* (`restricted`, scripts off) unless the caller states otherwise; static targets
|
|
169
304
|
* get the shorter 10 min / 2 h lifetime.
|
|
305
|
+
*
|
|
306
|
+
* With `opts.preview` (tiers 1-4) the entry is bound to its origin: tiers 1, 2, 4 generate a
|
|
307
|
+
* 128-bit label (re-drawn on a collision) and `token` is that label; a mint that matches a live
|
|
308
|
+
* entry (see {@link findReusable}) returns it with `reused: true`.
|
|
170
309
|
*/
|
|
171
310
|
mint(
|
|
172
311
|
targetId: string,
|
|
173
312
|
principal: CapabilityPrincipal,
|
|
174
313
|
opts: MintOptions = {},
|
|
175
|
-
): {
|
|
314
|
+
): {
|
|
315
|
+
token: string;
|
|
316
|
+
tokenId: string;
|
|
317
|
+
expiresAt: number;
|
|
318
|
+
policy: LivePolicy;
|
|
319
|
+
tier: CapabilityTier;
|
|
320
|
+
origin?: string;
|
|
321
|
+
originHost?: string;
|
|
322
|
+
poolPort?: number;
|
|
323
|
+
reused: boolean;
|
|
324
|
+
} {
|
|
176
325
|
const now = this.now();
|
|
177
326
|
this.sweep(now);
|
|
178
|
-
const
|
|
179
|
-
const
|
|
327
|
+
const binding = opts.preview;
|
|
328
|
+
const reusable = this.findReusable(targetId, principal, opts);
|
|
329
|
+
if (reusable) {
|
|
330
|
+
const e = reusable.entry as Entry;
|
|
331
|
+
e.lastUsedAt = now;
|
|
332
|
+
return {
|
|
333
|
+
token: e.label ?? "",
|
|
334
|
+
tokenId: e.tokenId,
|
|
335
|
+
expiresAt: e.mintedAt + e.maxMs,
|
|
336
|
+
policy: { ...e.policy },
|
|
337
|
+
tier: e.tier,
|
|
338
|
+
origin: e.origin,
|
|
339
|
+
originHost: e.originHost,
|
|
340
|
+
poolPort: e.poolPort,
|
|
341
|
+
reused: true,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
180
344
|
const kind: LiveTargetKind = opts.kind === "static" ? "static" : "port";
|
|
181
345
|
const policy: LivePolicy = {
|
|
182
346
|
egress: opts.policy?.egress === "open" ? "open" : "restricted",
|
|
@@ -184,7 +348,35 @@ export class LiveCapabilityStore {
|
|
|
184
348
|
};
|
|
185
349
|
const idleMs = kind === "static" ? STATIC_CAPABILITY_IDLE_MS : CAPABILITY_IDLE_MS;
|
|
186
350
|
const maxMs = kind === "static" ? STATIC_CAPABILITY_MAX_MS : CAPABILITY_MAX_MS;
|
|
187
|
-
|
|
351
|
+
const tokenId = crypto.randomBytes(16).toString("base64url");
|
|
352
|
+
|
|
353
|
+
let secret: string;
|
|
354
|
+
let preview: Pick<Entry, "tier" | "originHost" | "origin" | "label" | "poolPort" | "ancestors"> = {
|
|
355
|
+
tier: "legacy",
|
|
356
|
+
ancestors: [],
|
|
357
|
+
};
|
|
358
|
+
if (!binding) {
|
|
359
|
+
secret = crypto.randomBytes(32).toString("base64url");
|
|
360
|
+
} else if (binding.tier === 3) {
|
|
361
|
+
if (!binding.fixed) throw new Error("tier 3 mint needs the bound listener");
|
|
362
|
+
secret = crypto.randomBytes(32).toString("base64url");
|
|
363
|
+
preview = { tier: 3, ...binding.fixed, ancestors: [...binding.ancestors] };
|
|
364
|
+
} else {
|
|
365
|
+
if (!binding.buildOrigin) throw new Error(`tier ${binding.tier} mint needs buildOrigin`);
|
|
366
|
+
let label = "";
|
|
367
|
+
for (let i = 0; i < LABEL_RETRIES; i++) {
|
|
368
|
+
label = generatePreviewLabel(this.labelBytes);
|
|
369
|
+
if (!this.entries.has(hash(label))) break;
|
|
370
|
+
label = "";
|
|
371
|
+
}
|
|
372
|
+
if (!label) throw new Error("could not allocate a unique preview label");
|
|
373
|
+
secret = label;
|
|
374
|
+
const built = binding.buildOrigin(label);
|
|
375
|
+
preview = { tier: binding.tier, ...built, label, ancestors: [...binding.ancestors] };
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const key = hash(secret);
|
|
379
|
+
const entry: Entry = {
|
|
188
380
|
targetId,
|
|
189
381
|
principal,
|
|
190
382
|
mintedAt: now,
|
|
@@ -198,27 +390,39 @@ export class LiveCapabilityStore {
|
|
|
198
390
|
localBound: opts.localBound === true,
|
|
199
391
|
idleMs,
|
|
200
392
|
maxMs,
|
|
201
|
-
|
|
393
|
+
...preview,
|
|
394
|
+
};
|
|
395
|
+
this.entries.set(key, entry);
|
|
396
|
+
if (entry.originHost) this.byOriginHost.set(hash(entry.originHost), key);
|
|
397
|
+
this.ensureSweeper();
|
|
202
398
|
// Evict within the minting principal first, so a mint loop cannot push out
|
|
203
|
-
// another user's active preview
|
|
204
|
-
const who =
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
this.entries.delete(mine[0][0]);
|
|
208
|
-
mine = mine.slice(1);
|
|
209
|
-
}
|
|
399
|
+
// another user's active preview capabilities.
|
|
400
|
+
const who = entry.minterKey;
|
|
401
|
+
const mine = [...this.entries].filter(([, e]) => e.minterKey === who);
|
|
402
|
+
for (let i = 0; i < mine.length - MAX_TOKENS_PER_PRINCIPAL; i++) this.remove(mine[i][0], "evicted");
|
|
210
403
|
while (this.entries.size > MAX_TOKENS) {
|
|
211
404
|
const oldest = this.entries.keys().next().value;
|
|
212
405
|
if (oldest === undefined) break;
|
|
213
|
-
this.
|
|
406
|
+
this.remove(oldest, "evicted");
|
|
214
407
|
}
|
|
215
|
-
return {
|
|
408
|
+
return {
|
|
409
|
+
token: secret,
|
|
410
|
+
tokenId,
|
|
411
|
+
expiresAt: now + maxMs,
|
|
412
|
+
policy,
|
|
413
|
+
tier: entry.tier,
|
|
414
|
+
origin: entry.origin,
|
|
415
|
+
originHost: entry.originHost,
|
|
416
|
+
poolPort: entry.poolPort,
|
|
417
|
+
reused: false,
|
|
418
|
+
};
|
|
216
419
|
}
|
|
217
420
|
|
|
218
421
|
/**
|
|
219
|
-
* Validate
|
|
220
|
-
* unknown, wrong-target, expired or no-longer-live token returns `null` — the
|
|
221
|
-
* caller cannot tell which.
|
|
422
|
+
* Validate a LEGACY `/live/<id>/~c/<token>/` token for `targetId`. A hit extends the idle expiry.
|
|
423
|
+
* A missing, unknown, wrong-target, expired or no-longer-live token returns `null` — the
|
|
424
|
+
* caller cannot tell which. Origin-bound entries (tiers 1-4) never validate here: their label has
|
|
425
|
+
* the token's shape but must not open a `/live/` path.
|
|
222
426
|
*
|
|
223
427
|
* `ctx` carries request-boundary facts: a token minted by a genuinely local
|
|
224
428
|
* caller is refused when `ctx.genuinelyLocal` is false. Every request-facing
|
|
@@ -233,14 +437,15 @@ export class LiveCapabilityStore {
|
|
|
233
437
|
if (!TOKEN_SHAPE.test(token)) return null;
|
|
234
438
|
const key = hash(token);
|
|
235
439
|
const entry = this.entries.get(key);
|
|
236
|
-
if (!entry || entry.targetId !== targetId) return null;
|
|
440
|
+
if (!entry || entry.tier !== "legacy" || entry.targetId !== targetId) return null;
|
|
237
441
|
const now = this.now();
|
|
238
|
-
|
|
239
|
-
|
|
442
|
+
const expired = this.expiryReason(entry, now);
|
|
443
|
+
if (expired) {
|
|
444
|
+
this.remove(key, expired);
|
|
240
445
|
return null;
|
|
241
446
|
}
|
|
242
447
|
if (!this.isTargetLive(entry.targetId) || !this.isPrincipalLive(entry.principal)) {
|
|
243
|
-
this.
|
|
448
|
+
this.remove(key, "revoked");
|
|
244
449
|
return null;
|
|
245
450
|
}
|
|
246
451
|
// Bound to the local machine: a leaked local token is useless from anywhere else.
|
|
@@ -250,13 +455,66 @@ export class LiveCapabilityStore {
|
|
|
250
455
|
return grantOf(entry);
|
|
251
456
|
}
|
|
252
457
|
|
|
253
|
-
/**
|
|
458
|
+
/**
|
|
459
|
+
* Look an origin-bound entry up by `hash(label)` and the request's canonical Host (D2, D3).
|
|
460
|
+
* The Host must equal `entry.originHost` exactly (no tier crossing, no port crossing); a tier-1
|
|
461
|
+
* or local-bound entry is served only to a genuinely local peer (`peerLocal`). A hit extends the
|
|
462
|
+
* idle expiry. `expired` is reported only while the entry still exists between expiry and sweep;
|
|
463
|
+
* afterwards the entry is gone and the answer is `unknown` (no tombstones, Q25).
|
|
464
|
+
*/
|
|
465
|
+
lookupByHost(labelHash: string, canonicalHost: string, peerLocal: boolean): HostLookup {
|
|
466
|
+
const entry = this.entries.get(labelHash);
|
|
467
|
+
if (!entry || entry.tier === "legacy" || entry.tier === 3 || !entry.originHost) return { ok: false, reason: "unknown" };
|
|
468
|
+
const now = this.now();
|
|
469
|
+
const expired = this.expiryReason(entry, now);
|
|
470
|
+
if (expired) {
|
|
471
|
+
this.remove(labelHash, expired);
|
|
472
|
+
return { ok: false, reason: "expired" };
|
|
473
|
+
}
|
|
474
|
+
if (!this.isTargetLive(entry.targetId) || !this.isPrincipalLive(entry.principal)) {
|
|
475
|
+
this.remove(labelHash, "revoked");
|
|
476
|
+
return { ok: false, reason: "unknown" };
|
|
477
|
+
}
|
|
478
|
+
if (canonicalHost !== entry.originHost) {
|
|
479
|
+
const want = splitCanonicalHost(entry.originHost);
|
|
480
|
+
const got = splitCanonicalHost(canonicalHost);
|
|
481
|
+
return { ok: false, reason: want.hostname === got.hostname ? "wrong-port" : "wrong-host" };
|
|
482
|
+
}
|
|
483
|
+
if ((entry.tier === 1 || entry.localBound) && !peerLocal) return { ok: false, reason: "wrong-host" };
|
|
484
|
+
entry.lastUsedAt = now;
|
|
485
|
+
return { ok: true, grant: grantOf(entry) };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Tier 3: the live entry bound to pool `port`, or `null`. Does not touch. */
|
|
489
|
+
findByPoolPort(port: number): LiveCapabilityGrant | null {
|
|
490
|
+
const now = this.now();
|
|
491
|
+
for (const [key, e] of this.entries) {
|
|
492
|
+
if (e.tier !== 3 || e.poolPort !== port) continue;
|
|
493
|
+
const expired = this.expiryReason(e, now);
|
|
494
|
+
if (expired) {
|
|
495
|
+
this.remove(key, expired);
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
return grantOf(e);
|
|
499
|
+
}
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/** Is `canonicalHost` the origin host of a live (unexpired) entry? The dynamic admission set; never enumerates labels. */
|
|
504
|
+
isAdmittedHost(canonicalHost: string): boolean {
|
|
505
|
+
const key = this.byOriginHost.get(hash(canonicalHost));
|
|
506
|
+
const e = key ? this.entries.get(key) : undefined;
|
|
507
|
+
return !!e && !this.expiryReason(e, this.now());
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** The live capability behind a non-secret `tokenId`, or `null` (expired / unknown). Does not extend idle. */
|
|
254
511
|
findByTokenId(tokenId: string): LiveCapabilityGrant | null {
|
|
255
512
|
const now = this.now();
|
|
256
513
|
for (const [key, e] of this.entries) {
|
|
257
514
|
if (e.tokenId !== tokenId) continue;
|
|
258
|
-
|
|
259
|
-
|
|
515
|
+
const expired = this.expiryReason(e, now);
|
|
516
|
+
if (expired) {
|
|
517
|
+
this.remove(key, expired);
|
|
260
518
|
return null;
|
|
261
519
|
}
|
|
262
520
|
return grantOf(e);
|
|
@@ -265,21 +523,22 @@ export class LiveCapabilityStore {
|
|
|
265
523
|
}
|
|
266
524
|
|
|
267
525
|
/**
|
|
268
|
-
* Extend a
|
|
526
|
+
* Extend a capability's idle expiry (keepalive) without a request through its path.
|
|
269
527
|
* Only the minting principal may: `minterKey` must equal the entry's. Never
|
|
270
|
-
* extends past the absolute lifetime. Returns whether a live
|
|
528
|
+
* extends past the absolute lifetime. Returns whether a live capability was touched.
|
|
271
529
|
*/
|
|
272
530
|
touch(tokenId: string, minterKey: string): boolean {
|
|
273
531
|
const now = this.now();
|
|
274
532
|
for (const [key, e] of this.entries) {
|
|
275
533
|
if (e.tokenId !== tokenId) continue;
|
|
276
534
|
if (e.minterKey !== minterKey) return false;
|
|
277
|
-
|
|
278
|
-
|
|
535
|
+
const expired = this.expiryReason(e, now);
|
|
536
|
+
if (expired) {
|
|
537
|
+
this.remove(key, expired);
|
|
279
538
|
return false;
|
|
280
539
|
}
|
|
281
540
|
if (!this.isTargetLive(e.targetId) || !this.isPrincipalLive(e.principal)) {
|
|
282
|
-
this.
|
|
541
|
+
this.remove(key, "revoked");
|
|
283
542
|
return false;
|
|
284
543
|
}
|
|
285
544
|
e.lastUsedAt = now;
|
|
@@ -314,12 +573,15 @@ export class LiveCapabilityStore {
|
|
|
314
573
|
return viewerId ? [...(this.allowOnce.get(viewerId) ?? [])] : [];
|
|
315
574
|
}
|
|
316
575
|
|
|
317
|
-
/** Revoke every
|
|
318
|
-
revokeWhere(
|
|
576
|
+
/** Revoke every capability whose record matches `pred`. Returns how many died. Never exposes a secret. */
|
|
577
|
+
revokeWhere(
|
|
578
|
+
pred: (e: Readonly<{ kind: LiveTargetKind; policy: LivePolicy; mintExposure: LiveExposure; targetId: string }>) => boolean,
|
|
579
|
+
reason: CapabilityDeleteReason = "revoked",
|
|
580
|
+
): number {
|
|
319
581
|
let n = 0;
|
|
320
|
-
for (const [key, e] of this.entries) {
|
|
582
|
+
for (const [key, e] of [...this.entries]) {
|
|
321
583
|
if (pred(e)) {
|
|
322
|
-
this.
|
|
584
|
+
this.remove(key, reason);
|
|
323
585
|
n++;
|
|
324
586
|
}
|
|
325
587
|
}
|
|
@@ -327,31 +589,117 @@ export class LiveCapabilityStore {
|
|
|
327
589
|
}
|
|
328
590
|
|
|
329
591
|
revokeByTarget(targetId: string): void {
|
|
330
|
-
for (const [key, e] of this.entries) if (e.targetId === targetId) this.
|
|
592
|
+
for (const [key, e] of [...this.entries]) if (e.targetId === targetId) this.remove(key, "revoked");
|
|
331
593
|
}
|
|
332
594
|
|
|
333
595
|
revokeByDevice(deviceId: string): void {
|
|
334
|
-
for (const [key, e] of this.entries) if (e.principal.deviceId === deviceId) this.
|
|
596
|
+
for (const [key, e] of [...this.entries]) if (e.principal.deviceId === deviceId) this.remove(key, "revoked");
|
|
335
597
|
}
|
|
336
598
|
|
|
337
599
|
revokeBySessionKey(sessionKey: string): void {
|
|
338
|
-
for (const [key, e] of this.entries) if (e.principal.sessionKey === sessionKey) this.
|
|
600
|
+
for (const [key, e] of [...this.entries]) if (e.principal.sessionKey === sessionKey) this.remove(key, "revoked");
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Delete the entry bound to pool `port` (its listener errored or closed outside the store's control,
|
|
605
|
+
* Q36). The next mint reallocates; no rebind, so no zombie entry holds a listener-cap slot.
|
|
606
|
+
*/
|
|
607
|
+
revokeByPoolPort(port: number, reason: CapabilityDeleteReason = "listener-error"): void {
|
|
608
|
+
for (const [key, e] of [...this.entries]) if (e.tier === 3 && e.poolPort === port) this.remove(key, reason);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Reconcile with the resolved preview-origin config (D12, Q8): `enabled:false` revokes every
|
|
613
|
+
* origin-bound entry (`disabled`); otherwise an entry whose `originHost` no longer matches its
|
|
614
|
+
* tier's current resolved config is revoked (`config-changed`). Legacy entries are untouched.
|
|
615
|
+
*/
|
|
616
|
+
reconcilePreviewConfig(cfg: ResolvedPreviewOrigins): number {
|
|
617
|
+
let n = 0;
|
|
618
|
+
for (const [key, e] of [...this.entries]) {
|
|
619
|
+
if (e.tier === "legacy") continue;
|
|
620
|
+
if (!cfg.enabled) {
|
|
621
|
+
this.remove(key, "disabled");
|
|
622
|
+
n++;
|
|
623
|
+
} else if (!entryMatchesConfig(e, cfg)) {
|
|
624
|
+
this.remove(key, "config-changed");
|
|
625
|
+
n++;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
return n;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Delete everything (dashboard close) and stop the sweeper. */
|
|
632
|
+
close(reason: CapabilityDeleteReason = "shutdown"): void {
|
|
633
|
+
for (const key of [...this.entries.keys()]) this.remove(key, reason);
|
|
634
|
+
this.stopSweeper();
|
|
339
635
|
}
|
|
340
636
|
|
|
341
|
-
/** Count of live
|
|
637
|
+
/** Count of live capabilities (tests, diagnostics). Never exposes a secret or its hash. */
|
|
342
638
|
size(): number {
|
|
343
639
|
return this.entries.size;
|
|
344
640
|
}
|
|
345
641
|
|
|
346
|
-
/**
|
|
642
|
+
/** Size of the dynamic admission index (tests, leak soak). */
|
|
643
|
+
admittedHostCount(): number {
|
|
644
|
+
return this.byOriginHost.size;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/** Live per-viewer allow-once sets (tests, leak soak). */
|
|
648
|
+
allowOnceSize(): number {
|
|
649
|
+
return this.allowOnce.size;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** True when no stored key equals the plaintext secret (hash-only storage check). */
|
|
347
653
|
holdsPlaintext(token: string): boolean {
|
|
348
|
-
return this.entries.has(token);
|
|
654
|
+
return this.entries.has(token) || this.byOriginHost.has(token);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** `max` / `idle` when the entry's lifetime is over, else `null`. */
|
|
658
|
+
private expiryReason(e: Entry, now: number): "max" | "idle" | null {
|
|
659
|
+
if (now - e.mintedAt >= e.maxMs) return "max";
|
|
660
|
+
if (now - e.lastUsedAt >= e.idleMs) return "idle";
|
|
661
|
+
return null;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* Delete one entry from every index, THEN run the hook: a hook that throws or mints leaves a
|
|
666
|
+
* consistent store (X6). Exactly once per entry.
|
|
667
|
+
*/
|
|
668
|
+
private remove(key: string, reason: CapabilityDeleteReason): void {
|
|
669
|
+
const e = this.entries.get(key);
|
|
670
|
+
if (!e) return;
|
|
671
|
+
this.entries.delete(key);
|
|
672
|
+
if (e.originHost) {
|
|
673
|
+
const hk = hash(e.originHost);
|
|
674
|
+
if (this.byOriginHost.get(hk) === key) this.byOriginHost.delete(hk);
|
|
675
|
+
}
|
|
676
|
+
try {
|
|
677
|
+
this.onDelete?.(e, reason);
|
|
678
|
+
} catch (err) {
|
|
679
|
+
console.error(redactCapability(`[live-preview] onDelete hook failed reason=${reason}: ${err instanceof Error ? err.message : String(err)}`));
|
|
680
|
+
}
|
|
681
|
+
if (this.entries.size === 0) this.stopSweeper();
|
|
349
682
|
}
|
|
350
683
|
|
|
351
684
|
private sweep(now: number): void {
|
|
352
|
-
for (const [key, e] of this.entries) {
|
|
353
|
-
|
|
685
|
+
for (const [key, e] of [...this.entries]) {
|
|
686
|
+
const reason = this.expiryReason(e, now);
|
|
687
|
+
if (reason) this.remove(key, reason);
|
|
354
688
|
}
|
|
689
|
+
const cfg = this.getPreviewConfig?.();
|
|
690
|
+
if (cfg) this.reconcilePreviewConfig(cfg);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
private ensureSweeper(): void {
|
|
694
|
+
if (this.sweeper) return;
|
|
695
|
+
this.sweeper = setInterval(() => this.sweep(this.now()), this.sweepIntervalMs);
|
|
696
|
+
this.sweeper.unref?.();
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
private stopSweeper(): void {
|
|
700
|
+
if (!this.sweeper) return;
|
|
701
|
+
clearInterval(this.sweeper);
|
|
702
|
+
this.sweeper = undefined;
|
|
355
703
|
}
|
|
356
704
|
}
|
|
357
705
|
|
|
@@ -363,6 +711,11 @@ const grantOf = (e: Entry): LiveCapabilityGrant => ({
|
|
|
363
711
|
...(e.viewerId ? { viewerId: e.viewerId } : {}),
|
|
364
712
|
minterKey: e.minterKey,
|
|
365
713
|
principal: e.principal,
|
|
714
|
+
tier: e.tier,
|
|
715
|
+
...(e.origin ? { origin: e.origin } : {}),
|
|
716
|
+
...(e.originHost ? { originHost: e.originHost } : {}),
|
|
717
|
+
...(e.poolPort !== undefined ? { poolPort: e.poolPort } : {}),
|
|
718
|
+
ancestors: [...e.ancestors],
|
|
366
719
|
});
|
|
367
720
|
|
|
368
721
|
/** A parsed capability URL. `rest` starts with `/` (or is `/`); `prefix` is `/live/<id>/~c/<token>`. */
|
|
@@ -431,20 +784,31 @@ interface CapabilityRequestState {
|
|
|
431
784
|
* left untouched — the normal admission rules decide, and cannot tell a bad
|
|
432
785
|
* token from none.
|
|
433
786
|
*/
|
|
434
|
-
export function createLiveCapabilityHook(
|
|
787
|
+
export function createLiveCapabilityHook(
|
|
788
|
+
store: LiveCapabilityStore,
|
|
789
|
+
previewPaths?: { validate: (pid: string, ctx: { genuinelyLocal: boolean }) => LiveCapabilityGrant | null },
|
|
790
|
+
) {
|
|
435
791
|
return async function liveCapabilityHook(request: {
|
|
436
792
|
url: string;
|
|
437
793
|
ip?: string;
|
|
438
794
|
headers?: Record<string, unknown>;
|
|
439
795
|
}): Promise<void> {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
if (!cap) return;
|
|
796
|
+
const isPreview = request.url.startsWith("/preview/");
|
|
797
|
+
if (!isPreview && !request.url.startsWith("/live/")) return;
|
|
443
798
|
// A token minted by a genuinely local caller works only from genuinely local requests.
|
|
444
|
-
const
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
799
|
+
const ctx = { genuinelyLocal: isLocallyTrusted({ ip: request.ip ?? "", headers: request.headers ?? {} }) };
|
|
800
|
+
let cap: { prefix: string; grant: LiveCapabilityGrant } | null = null;
|
|
801
|
+
if (isPreview) {
|
|
802
|
+
const path = previewPaths ? parsePreviewPath(request.url) : null;
|
|
803
|
+
const g = path && previewPaths ? previewPaths.validate(path.pid, ctx) : null;
|
|
804
|
+
cap = path && g ? { prefix: path.prefix, grant: g } : null;
|
|
805
|
+
} else {
|
|
806
|
+
const parsed = parseCapabilityPath(request.url);
|
|
807
|
+
const g = parsed ? store.validateGrant(parsed.targetId, parsed.token, ctx) : null;
|
|
808
|
+
cap = parsed && g ? { prefix: parsed.prefix, grant: g } : null;
|
|
809
|
+
}
|
|
810
|
+
if (!cap) return;
|
|
811
|
+
const grant = cap.grant;
|
|
448
812
|
const principal = grant.principal;
|
|
449
813
|
const r = request as unknown as CapabilityRequestState;
|
|
450
814
|
r.isAuthenticated = true;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The reserved `/__pi/csp-report` endpoint under a capability prefix: the sink the
|
|
3
|
-
* restricted-preview CSP's `report-uri`
|
|
3
|
+
* restricted-preview CSP's `report-uri` points at (never `report-to`: undeliverable on plain http).
|
|
4
4
|
*
|
|
5
5
|
* Capability-required (the proxy only dispatches a VALID capability here), `POST`
|
|
6
6
|
* only, both report media types, 64 KiB (413 above), rate limited per token (429,
|