@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
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Intake of the device key and companion key that ride a knock or a QR redeem.
|
|
3
|
+
*
|
|
4
|
+
* Verified when the request ARRIVES (the single-use nonce is consumed then,
|
|
5
|
+
* valid or not); the result is held on the pending device and only bound to a
|
|
6
|
+
* device row at operator approval. An invalid, replayed or already-held key is
|
|
7
|
+
* silently dropped — the response never changes — and leaves one throttled
|
|
8
|
+
* `key_ignored` audit line.
|
|
9
|
+
*
|
|
10
|
+
* See change: device-key-mutual-check (D3, D5, D10).
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
companionMessage,
|
|
14
|
+
devbindMessage,
|
|
15
|
+
isCompanionTsFresh,
|
|
16
|
+
isDevicePub,
|
|
17
|
+
isDeviceSig,
|
|
18
|
+
parseCompanionTs,
|
|
19
|
+
validCompanionOrigin,
|
|
20
|
+
} from "@blackbelt-technology/pi-dashboard-shared/device-key-proof.js";
|
|
21
|
+
import { auditKeyEvent } from "../auth/audit-log.js";
|
|
22
|
+
import { type DeviceNonceStore, verifyDeviceSignature, verifyNonceProof } from "../auth/device-proof.js";
|
|
23
|
+
import { keyIdOf, type PairedDeviceRegistry } from "./paired-devices.js";
|
|
24
|
+
|
|
25
|
+
/** What a knock or redeem may carry that survived verification. */
|
|
26
|
+
export interface VerifiedDeviceKeys {
|
|
27
|
+
/** Verified primary device key (raw base64url). */
|
|
28
|
+
deviceKey?: string;
|
|
29
|
+
/** Verified companion; `origin` exactly as sent (stripping is for storage/display only). */
|
|
30
|
+
companion?: { pub: string; origin: string };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** One `key_ignored` line per key id per window, bounded map. */
|
|
34
|
+
const IGNORED_LOG_WINDOW_MS = 10 * 60_000;
|
|
35
|
+
const IGNORED_LOG_MAX_KEYS = 1024;
|
|
36
|
+
|
|
37
|
+
export interface DeviceKeyIntakeDeps {
|
|
38
|
+
nonces: DeviceNonceStore;
|
|
39
|
+
registry: Pick<PairedDeviceRegistry, "isKeyHeld">;
|
|
40
|
+
fingerprint: () => string;
|
|
41
|
+
now?: () => number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createDeviceKeyIntake(deps: DeviceKeyIntakeDeps) {
|
|
45
|
+
const now = deps.now ?? Date.now;
|
|
46
|
+
const lastIgnored = new Map<string, number>();
|
|
47
|
+
|
|
48
|
+
function noteIgnored(pub: unknown): void {
|
|
49
|
+
if (!isDevicePub(pub)) return; // no key id to name
|
|
50
|
+
const id = keyIdOf(pub);
|
|
51
|
+
const t = now();
|
|
52
|
+
const prev = lastIgnored.get(id);
|
|
53
|
+
if (prev !== undefined && t - prev < IGNORED_LOG_WINDOW_MS) return;
|
|
54
|
+
lastIgnored.delete(id);
|
|
55
|
+
lastIgnored.set(id, t);
|
|
56
|
+
while (lastIgnored.size > IGNORED_LOG_MAX_KEYS) {
|
|
57
|
+
const oldest = lastIgnored.keys().next().value;
|
|
58
|
+
if (oldest === undefined) break;
|
|
59
|
+
lastIgnored.delete(oldest);
|
|
60
|
+
}
|
|
61
|
+
auditKeyEvent("key_ignored", undefined, id);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function rawPub(raw: unknown): unknown {
|
|
65
|
+
return raw && typeof raw === "object" ? (raw as Record<string, unknown>).pub : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** `deviceKey: {deviceNonce, pub, sig}` → the verified, not-yet-held public key, else undefined. */
|
|
69
|
+
function acceptDeviceKey(raw: unknown): string | undefined {
|
|
70
|
+
if (raw === undefined || raw === null) return undefined;
|
|
71
|
+
// `verifyNonceProof` consumes the nonce on first presentation even when the rest is malformed.
|
|
72
|
+
const fields = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
|
|
73
|
+
if (!verifyNonceProof(deps.nonces, fields, (n) => devbindMessage(deps.fingerprint(), n))) {
|
|
74
|
+
noteIgnored(rawPub(raw));
|
|
75
|
+
return undefined;
|
|
76
|
+
}
|
|
77
|
+
const pub = fields.pub as string;
|
|
78
|
+
if (deps.registry.isKeyHeld(pub)) {
|
|
79
|
+
noteIgnored(pub);
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
return pub;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** `companion: {pub, ts, sig, origin}` → the verified, fresh, not-yet-held companion, else undefined. */
|
|
86
|
+
function acceptCompanion(raw: unknown): { pub: string; origin: string } | undefined {
|
|
87
|
+
if (raw === undefined || raw === null) return undefined;
|
|
88
|
+
const c = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
|
|
89
|
+
const ts = parseCompanionTs(c.ts);
|
|
90
|
+
if (
|
|
91
|
+
!isDevicePub(c.pub) ||
|
|
92
|
+
!isDeviceSig(c.sig) ||
|
|
93
|
+
ts === null ||
|
|
94
|
+
!isCompanionTsFresh(ts, now()) ||
|
|
95
|
+
!validCompanionOrigin(c.origin) ||
|
|
96
|
+
!verifyDeviceSignature(c.pub, companionMessage(deps.fingerprint(), c.origin, ts), c.sig)
|
|
97
|
+
) {
|
|
98
|
+
noteIgnored(c.pub);
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
if (deps.registry.isKeyHeld(c.pub)) {
|
|
102
|
+
noteIgnored(c.pub);
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
return { pub: c.pub, origin: c.origin };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Verify both; a companion equal to the device key is dropped (the key alone is kept). */
|
|
109
|
+
function accept(body: { deviceKey?: unknown; companion?: unknown } | null | undefined): VerifiedDeviceKeys {
|
|
110
|
+
const deviceKey = acceptDeviceKey(body?.deviceKey);
|
|
111
|
+
const companion = acceptCompanion(body?.companion);
|
|
112
|
+
return {
|
|
113
|
+
...(deviceKey ? { deviceKey } : {}),
|
|
114
|
+
...(companion && companion.pub !== deviceKey ? { companion } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { accept, acceptDeviceKey, acceptCompanion };
|
|
119
|
+
}
|
|
120
|
+
|
|
@@ -11,6 +11,12 @@ import crypto from "node:crypto";
|
|
|
11
11
|
import fs from "node:fs";
|
|
12
12
|
import os from "node:os";
|
|
13
13
|
import path from "node:path";
|
|
14
|
+
import {
|
|
15
|
+
type DeviceStatusReply,
|
|
16
|
+
MAX_COMPANIONS,
|
|
17
|
+
shortKeyIdFromDigest,
|
|
18
|
+
storedCompanionOrigin,
|
|
19
|
+
} from "@blackbelt-technology/pi-dashboard-shared/device-key-proof.js";
|
|
14
20
|
import {
|
|
15
21
|
defaultTierForSource,
|
|
16
22
|
isTier,
|
|
@@ -23,6 +29,9 @@ import { type BearerChannel, isProvenChannel } from "../auth/proven-tls.js";
|
|
|
23
29
|
import { readJsonFile, writeJsonFile } from "../persistence/json-store.js";
|
|
24
30
|
|
|
25
31
|
const REGISTRY_FILENAME = "paired-devices.json";
|
|
32
|
+
const REVOKED_FILENAME = "revoked-devices.json";
|
|
33
|
+
/** A revoked record is deleted for good once its age reaches this (age >= 90 d). See change: device-key-mutual-check (D6). */
|
|
34
|
+
export const REVOKED_RETENTION_MS = 90 * 24 * 60 * 60 * 1000;
|
|
26
35
|
const TOKEN_BYTES = 32; // 256-bit opaque bearer.
|
|
27
36
|
// Throttle last-seen persistence: every authenticated request would otherwise
|
|
28
37
|
// rewrite the registry file (write amplification). Coarse last-seen is fine.
|
|
@@ -38,6 +47,18 @@ const ROTATION_GRACE_MS = 60_000;
|
|
|
38
47
|
const ROTATE_LIMIT = 10;
|
|
39
48
|
const ROTATE_WINDOW_MS = 60_000;
|
|
40
49
|
|
|
50
|
+
/** A status-only key held by a device for another dashboard origin (never authenticates). */
|
|
51
|
+
interface DeviceCompanion {
|
|
52
|
+
/** Short stable id: `dk:` + 12 chars of SHA-256 over the raw key. */
|
|
53
|
+
id: string;
|
|
54
|
+
/** Raw Ed25519 public key, unpadded base64url. */
|
|
55
|
+
pub: string;
|
|
56
|
+
/** Claimed origin of the dashboard that asked; stored via `storedCompanionOrigin` (plain text). */
|
|
57
|
+
origin: string;
|
|
58
|
+
/** ISO timestamp. */
|
|
59
|
+
createdAt: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
41
62
|
export interface PairedDevice {
|
|
42
63
|
/** Stable per-device id. */
|
|
43
64
|
id: string;
|
|
@@ -77,6 +98,18 @@ export interface PairedDevice {
|
|
|
77
98
|
* See change: prove-vault-bridge-tls (D4).
|
|
78
99
|
*/
|
|
79
100
|
exposure?: { trackedSince: string; plaintextSeenAt?: string };
|
|
101
|
+
/** Primary device key (one per row); absent until bound. See change: device-key-mutual-check (D3). */
|
|
102
|
+
keys?: { pub: string; createdAt: string };
|
|
103
|
+
/** Status-only companion keys, at most `MAX_COMPANIONS`. */
|
|
104
|
+
companions?: DeviceCompanion[];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A revoked device held apart from the active registry (D6): the whole row plus who/when. */
|
|
108
|
+
export interface RevokedDevice extends PairedDevice {
|
|
109
|
+
/** Epoch ms of revocation (anchors the 90-day retention). */
|
|
110
|
+
revokedAt: number;
|
|
111
|
+
/** Display-only short actor string (`session:<sub8>` or `local`). */
|
|
112
|
+
revokedBy: string;
|
|
80
113
|
}
|
|
81
114
|
|
|
82
115
|
/** What the vault trust gate may do with a device. See change: prove-vault-bridge-tls (D4). */
|
|
@@ -86,6 +119,10 @@ export type DeviceTrust = "eligible" | "inactive" | "exposed" | "history-unknown
|
|
|
86
119
|
export const BRIDGE_TOKEN_REQUIRES_HTTPS = "bridge_token_requires_https";
|
|
87
120
|
|
|
88
121
|
export interface AddOptions {
|
|
122
|
+
/** Primary device key to bind to the new row; dropped silently when empty or already held anywhere. */
|
|
123
|
+
key?: string;
|
|
124
|
+
/** Companions to store with the new row; invalid/duplicate/over-cap ones are dropped silently. */
|
|
125
|
+
companions?: { pub: string; origin: string }[];
|
|
89
126
|
/** The channel that DELIVERS the token. Absent = no exposure decision (QR `approve()`, collected later by `markDelivered`). */
|
|
90
127
|
channel?: BearerChannel;
|
|
91
128
|
/** `"bridge"` mints a TLS-only `pi_tls_` token and requires a proven channel. */
|
|
@@ -122,6 +159,28 @@ function isValidMs(v: unknown): v is number {
|
|
|
122
159
|
return typeof v === "number" && Number.isFinite(v) && v > 0;
|
|
123
160
|
}
|
|
124
161
|
|
|
162
|
+
/** True while a row's previous bearer (rotation grace) is still honoured. Shared by `resolve` and the device-key check. */
|
|
163
|
+
function previousGraceLive(d: PairedDevice, now: number): boolean {
|
|
164
|
+
return typeof d.previousHash === "string" && isValidMs(d.previousExpiresAt) && now < d.previousExpiresAt;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function newCompanion(pub: string, origin: string, createdAt: string): DeviceCompanion {
|
|
168
|
+
return { id: keyIdOf(pub), pub, origin: storedCompanionOrigin(origin), createdAt };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Minimum shape of a persisted revoked record; anything else sets the whole file aside. */
|
|
172
|
+
function isRevokedShape(v: unknown): v is RevokedDevice {
|
|
173
|
+
if (!v || typeof v !== "object") return false;
|
|
174
|
+
const o = v as Record<string, unknown>;
|
|
175
|
+
return (
|
|
176
|
+
typeof o.id === "string" &&
|
|
177
|
+
typeof o.tokenHash === "string" &&
|
|
178
|
+
typeof o.createdAt === "string" &&
|
|
179
|
+
isValidMs(o.revokedAt) &&
|
|
180
|
+
typeof o.revokedBy === "string"
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
125
184
|
/** Public view of a device (no token material) for Settings / listing. */
|
|
126
185
|
export interface PairedDeviceView {
|
|
127
186
|
id: string;
|
|
@@ -130,6 +189,29 @@ export interface PairedDeviceView {
|
|
|
130
189
|
lastSeen: string | null;
|
|
131
190
|
source: "pairing" | "manual";
|
|
132
191
|
tier: Tier;
|
|
192
|
+
/** Short id of the primary key (`dk:` + 12), absent while no key is bound. */
|
|
193
|
+
keyId?: string;
|
|
194
|
+
/** Companions (id + origin + createdAt, never the key). Absent when none. */
|
|
195
|
+
companions?: { id: string; origin: string; createdAt: string }[];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A revoked device for the operator list (no token material). */
|
|
199
|
+
export interface RevokedDeviceView extends PairedDeviceView {
|
|
200
|
+
revokedAt: number;
|
|
201
|
+
revokedBy: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export type BindKeyResult = "bound" | "replaced" | "held" | "no-device";
|
|
205
|
+
export type AddCompanionResult = "added" | "cap" | "held" | "no-device";
|
|
206
|
+
export type RestoreResult = "restored" | "not-found" | "active";
|
|
207
|
+
export type DeleteRevokedResult = "deleted" | "not-found" | "active";
|
|
208
|
+
|
|
209
|
+
/** Where a public key lives. Active rows are searched before revoked ones. */
|
|
210
|
+
export interface KeyLookup {
|
|
211
|
+
device: PairedDevice;
|
|
212
|
+
kind: "primary" | "companion";
|
|
213
|
+
state: "active" | "revoked";
|
|
214
|
+
companion?: DeviceCompanion;
|
|
133
215
|
}
|
|
134
216
|
|
|
135
217
|
export function defaultRegistryPath(): string {
|
|
@@ -140,6 +222,11 @@ function hashToken(token: string): string {
|
|
|
140
222
|
return crypto.createHash("sha256").update(token).digest("hex");
|
|
141
223
|
}
|
|
142
224
|
|
|
225
|
+
/** Short key id `dk:` + 12 chars; sync twin of the client's `shortKeyId`. */
|
|
226
|
+
export function keyIdOf(pub: string): string {
|
|
227
|
+
return shortKeyIdFromDigest(crypto.createHash("sha256").update(Buffer.from(pub, "base64url")).digest());
|
|
228
|
+
}
|
|
229
|
+
|
|
143
230
|
/** Constant-time compare of two equal-length hex digests. */
|
|
144
231
|
function timingSafeEqualHex(a: string, b: string): boolean {
|
|
145
232
|
if (a.length !== b.length) return false;
|
|
@@ -160,9 +247,15 @@ export class PairedDeviceRegistry {
|
|
|
160
247
|
/** Device ids whose first-exposure mark has not reached the disk yet (in memory only). */
|
|
161
248
|
private pendingExposure = new Set<string>();
|
|
162
249
|
private listeners: Array<() => void> = [];
|
|
250
|
+
private readonly revokedPath: string;
|
|
251
|
+
private revoked: RevokedDevice[] = [];
|
|
252
|
+
/** Set when the revoked file could not be read at start; surfaced by `listRevoked`. */
|
|
253
|
+
private revokedUnreadable = false;
|
|
254
|
+
private revokedListeners: Array<(id: string) => void> = [];
|
|
163
255
|
|
|
164
256
|
constructor(filePath = defaultRegistryPath()) {
|
|
165
257
|
this.filePath = filePath;
|
|
258
|
+
this.revokedPath = path.join(path.dirname(filePath), REVOKED_FILENAME);
|
|
166
259
|
// Loader default, not a migration script (D4): a row written before
|
|
167
260
|
// `source`/`tier` existed reads as `"pairing"` / `"operate"`, and the next
|
|
168
261
|
// write back normalises it in place.
|
|
@@ -171,6 +264,57 @@ export class PairedDeviceRegistry {
|
|
|
171
264
|
source: d.source === "manual" ? "manual" : "pairing",
|
|
172
265
|
tier: isTier(d.tier) ? d.tier : "operate",
|
|
173
266
|
}));
|
|
267
|
+
this.revoked = this.loadRevoked();
|
|
268
|
+
// An id in both files: the revoked record is the truth (crash between the two revoke/restore writes).
|
|
269
|
+
const held = new Set(this.revoked.map((r) => r.id));
|
|
270
|
+
if (this.devices.some((d) => held.has(d.id))) {
|
|
271
|
+
this.devices = this.devices.filter((d) => !held.has(d.id));
|
|
272
|
+
try {
|
|
273
|
+
this.persist();
|
|
274
|
+
} catch (err) {
|
|
275
|
+
console.error(`[pairing] registry rewrite after revoked-wins failed: ${(err as Error)?.name ?? "error"}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
this.purgeExpired();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Read the revoked store. Unparseable or wrong-shape → set aside, error logged, empty + warning. */
|
|
282
|
+
private loadRevoked(): RevokedDevice[] {
|
|
283
|
+
let raw: string;
|
|
284
|
+
try {
|
|
285
|
+
if (!fs.existsSync(this.revokedPath)) return [];
|
|
286
|
+
raw = fs.readFileSync(this.revokedPath, "utf-8");
|
|
287
|
+
} catch {
|
|
288
|
+
return this.quarantineRevoked();
|
|
289
|
+
}
|
|
290
|
+
if (!raw.trim()) return [];
|
|
291
|
+
try {
|
|
292
|
+
const parsed: unknown = JSON.parse(raw);
|
|
293
|
+
if (!Array.isArray(parsed) || !parsed.every(isRevokedShape)) return this.quarantineRevoked();
|
|
294
|
+
return parsed.map((d) => ({
|
|
295
|
+
...d,
|
|
296
|
+
source: d.source === "manual" ? "manual" : "pairing",
|
|
297
|
+
tier: isTier(d.tier) ? d.tier : "operate",
|
|
298
|
+
}));
|
|
299
|
+
} catch {
|
|
300
|
+
return this.quarantineRevoked();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private quarantineRevoked(): RevokedDevice[] {
|
|
305
|
+
this.revokedUnreadable = true;
|
|
306
|
+
const aside = path.join(path.dirname(this.revokedPath), `revoked-devices.corrupt-${Date.now()}.json`);
|
|
307
|
+
try {
|
|
308
|
+
fs.renameSync(this.revokedPath, aside);
|
|
309
|
+
} catch {
|
|
310
|
+
/* best-effort: the list starts empty either way */
|
|
311
|
+
}
|
|
312
|
+
console.error(`[pairing] revoked-devices store unreadable; set aside as ${path.basename(aside)}, starting with an empty revoked list`);
|
|
313
|
+
return [];
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private persistRevoked(list: RevokedDevice[] = this.revoked): void {
|
|
317
|
+
writeJsonFile(this.revokedPath, list, { mode: 0o600 });
|
|
174
318
|
}
|
|
175
319
|
|
|
176
320
|
private persist(): void {
|
|
@@ -193,6 +337,24 @@ export class PairedDeviceRegistry {
|
|
|
193
337
|
};
|
|
194
338
|
}
|
|
195
339
|
|
|
340
|
+
/** Subscribe to revocations: fires with the device id after a successful `revoke`. Returns an unsubscribe. */
|
|
341
|
+
onRevoked(listener: (id: string) => void): () => void {
|
|
342
|
+
this.revokedListeners.push(listener);
|
|
343
|
+
return () => {
|
|
344
|
+
this.revokedListeners = this.revokedListeners.filter((l) => l !== listener);
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
private emitRevoked(id: string): void {
|
|
349
|
+
for (const l of [...this.revokedListeners]) {
|
|
350
|
+
try {
|
|
351
|
+
l(id);
|
|
352
|
+
} catch {
|
|
353
|
+
/* a listener fault never reaches the registry */
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
196
358
|
private emitChange(): void {
|
|
197
359
|
for (const l of [...this.listeners]) {
|
|
198
360
|
try {
|
|
@@ -272,7 +434,7 @@ export class PairedDeviceRegistry {
|
|
|
272
434
|
tier?: Tier,
|
|
273
435
|
holder?: unknown,
|
|
274
436
|
opts: AddOptions = {},
|
|
275
|
-
): { device: PairedDeviceView; token: string; expiresAt?: number } {
|
|
437
|
+
): { device: PairedDeviceView; token: string; expiresAt?: number; keyBound?: boolean; companionsAdded?: number } {
|
|
276
438
|
if (tier !== undefined && !isTier(tier)) {
|
|
277
439
|
throw new Error(`invalid tier: ${String(tier)} (expected one of ${TIERS.join(", ")})`);
|
|
278
440
|
}
|
|
@@ -301,12 +463,23 @@ export class PairedDeviceRegistry {
|
|
|
301
463
|
device.pairedAt = now;
|
|
302
464
|
device.expiresAt = now + BROWSER_BEARER_TTL_MS;
|
|
303
465
|
}
|
|
466
|
+
// Device key / companions (D3): a key held anywhere, or an invalid/over-cap companion, is dropped silently.
|
|
467
|
+
const wantKey = typeof opts.key === "string" && opts.key !== "";
|
|
468
|
+
if (wantKey && !this.keyOwner(opts.key as string)) device.keys = { pub: opts.key as string, createdAt };
|
|
469
|
+
for (const c of opts.companions ?? []) {
|
|
470
|
+
if ((device.companions?.length ?? 0) >= MAX_COMPANIONS) break;
|
|
471
|
+
if (typeof c?.pub !== "string" || c.pub === "" || typeof c.origin !== "string") continue;
|
|
472
|
+
if (this.keyOwner(c.pub) || device.keys?.pub === c.pub || device.companions?.some((x) => x.pub === c.pub)) continue;
|
|
473
|
+
(device.companions ??= []).push(newCompanion(c.pub, c.origin, createdAt));
|
|
474
|
+
}
|
|
304
475
|
this.devices.push(device);
|
|
305
476
|
this.persist();
|
|
306
477
|
this.emitChange();
|
|
307
478
|
return {
|
|
308
479
|
device: this.toView(device),
|
|
309
480
|
token,
|
|
481
|
+
...(wantKey ? { keyBound: !!device.keys } : {}),
|
|
482
|
+
...(opts.companions ? { companionsAdded: device.companions?.length ?? 0 } : {}),
|
|
310
483
|
...(device.expiresAt !== undefined ? { expiresAt: device.expiresAt as number } : {}),
|
|
311
484
|
};
|
|
312
485
|
}
|
|
@@ -350,7 +523,7 @@ export class PairedDeviceRegistry {
|
|
|
350
523
|
return this.currentVerdict(d, now);
|
|
351
524
|
}
|
|
352
525
|
if (typeof d.previousHash === "string" && timingSafeEqualHex(presented, d.previousHash)) {
|
|
353
|
-
if (
|
|
526
|
+
if (previousGraceLive(d, now)) {
|
|
354
527
|
return { status: "ok", id: d.id, tier: d.tier, superseded: true, row: d };
|
|
355
528
|
}
|
|
356
529
|
return { status: "invalid" };
|
|
@@ -474,18 +647,203 @@ export class PairedDeviceRegistry {
|
|
|
474
647
|
return { ok: true, id: row.id, token: newToken, expiresAt };
|
|
475
648
|
}
|
|
476
649
|
|
|
477
|
-
/**
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
650
|
+
/**
|
|
651
|
+
* Revoke = hold (D6): write the whole row + `revokedAt`/`revokedBy` to `revoked-devices.json` FIRST,
|
|
652
|
+
* then drop it from the active registry. Unknown or already-revoked id → false (route: 404), nothing
|
|
653
|
+
* changes. A failed first write throws and the device stays active; a failed second write is logged
|
|
654
|
+
* only (the revoked record wins at next start and in memory the row is already gone).
|
|
655
|
+
*/
|
|
656
|
+
revoke(id: string, by = "local"): boolean {
|
|
657
|
+
const row = this.devices.find((d) => d.id === id);
|
|
658
|
+
if (!row) return false;
|
|
659
|
+
const rec: RevokedDevice = { ...row, revokedAt: Date.now(), revokedBy: auditPrefix(by, 40) || "local" };
|
|
660
|
+
const next = [...this.revoked.filter((r) => r.id !== id), rec];
|
|
661
|
+
this.persistRevoked(next);
|
|
662
|
+
this.revoked = next;
|
|
663
|
+
this.devices = this.devices.filter((d) => d !== row);
|
|
482
664
|
this.rotations.delete(id);
|
|
483
665
|
this.pendingExposure.delete(id);
|
|
484
|
-
|
|
666
|
+
try {
|
|
667
|
+
this.persist();
|
|
668
|
+
} catch (err) {
|
|
669
|
+
console.error(`[pairing] registry rewrite after revoke failed id=${auditPrefix(id)}: ${(err as Error)?.name ?? "error"}`);
|
|
670
|
+
}
|
|
485
671
|
this.emitChange();
|
|
672
|
+
this.emitRevoked(id);
|
|
486
673
|
return true;
|
|
487
674
|
}
|
|
488
675
|
|
|
676
|
+
/**
|
|
677
|
+
* Undo a revoke: active file first, then drop the revoked record. Returns the row exactly as held
|
|
678
|
+
* (never extends expiry or restarts a grace window); `"active"` = id is currently active (409),
|
|
679
|
+
* `"not-found"` = not in the revoked store (404).
|
|
680
|
+
*/
|
|
681
|
+
restore(id: string): RestoreResult {
|
|
682
|
+
this.purgeExpired();
|
|
683
|
+
if (this.devices.some((d) => d.id === id)) return "active";
|
|
684
|
+
const rec = this.revoked.find((r) => r.id === id);
|
|
685
|
+
if (!rec) return "not-found";
|
|
686
|
+
const row: Record<string, unknown> = { ...rec };
|
|
687
|
+
delete row.revokedAt;
|
|
688
|
+
delete row.revokedBy;
|
|
689
|
+
this.devices.push({
|
|
690
|
+
...(row as unknown as PairedDevice),
|
|
691
|
+
source: rec.source === "manual" ? "manual" : "pairing",
|
|
692
|
+
tier: isTier(rec.tier) ? rec.tier : "operate",
|
|
693
|
+
});
|
|
694
|
+
try {
|
|
695
|
+
this.persist();
|
|
696
|
+
} catch (err) {
|
|
697
|
+
this.devices.pop();
|
|
698
|
+
throw err;
|
|
699
|
+
}
|
|
700
|
+
this.revoked = this.revoked.filter((r) => r.id !== id);
|
|
701
|
+
try {
|
|
702
|
+
this.persistRevoked();
|
|
703
|
+
} catch (err) {
|
|
704
|
+
// Both files now name the id; the revoked record wins at next start and the operator restores again.
|
|
705
|
+
console.error(`[pairing] revoked store rewrite after restore failed id=${auditPrefix(id)}: ${(err as Error)?.name ?? "error"}`);
|
|
706
|
+
}
|
|
707
|
+
this.emitChange();
|
|
708
|
+
return "restored";
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** Delete-now: drop a revoked record for good. Same codes as `restore`. */
|
|
712
|
+
deleteRevoked(id: string): DeleteRevokedResult {
|
|
713
|
+
this.purgeExpired();
|
|
714
|
+
if (this.devices.some((d) => d.id === id)) return "active";
|
|
715
|
+
if (!this.revoked.some((r) => r.id === id)) return "not-found";
|
|
716
|
+
const next = this.revoked.filter((r) => r.id !== id);
|
|
717
|
+
this.persistRevoked(next);
|
|
718
|
+
this.revoked = next;
|
|
719
|
+
return "deleted";
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** Revoked devices (after a purge pass) for the operator list, plus `warning` when the store was unreadable. */
|
|
723
|
+
listRevoked(): { devices: RevokedDeviceView[]; warning?: "unreadable" } {
|
|
724
|
+
this.purgeExpired();
|
|
725
|
+
return {
|
|
726
|
+
devices: this.revoked.map((r) => ({ ...this.toView(r), revokedAt: r.revokedAt, revokedBy: r.revokedBy })),
|
|
727
|
+
...(this.revokedUnreadable ? { warning: "unreadable" as const } : {}),
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** Delete revoked records aged >= `REVOKED_RETENTION_MS`; one `purged` audit line each. Returns how many. */
|
|
732
|
+
purgeExpired(): number {
|
|
733
|
+
const now = Date.now();
|
|
734
|
+
const gone = this.revoked.filter((r) => now - r.revokedAt >= REVOKED_RETENTION_MS);
|
|
735
|
+
if (gone.length === 0) return 0;
|
|
736
|
+
this.revoked = this.revoked.filter((r) => !gone.includes(r));
|
|
737
|
+
try {
|
|
738
|
+
this.persistRevoked();
|
|
739
|
+
} catch (err) {
|
|
740
|
+
console.error(`[pairing] revoked store rewrite after purge failed: ${(err as Error)?.name ?? "error"}`);
|
|
741
|
+
}
|
|
742
|
+
for (const r of gone) auditLine("pairing", "purged", { id: auditPrefix(r.id) });
|
|
743
|
+
return gone.length;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
// ── Device keys (D3, D5) ─────────────────────────────────────────
|
|
747
|
+
|
|
748
|
+
/** Active rows first (primary, then companions), then revoked ones. Pure scan; no purge. */
|
|
749
|
+
private scanKey(pub: string): KeyLookup | null {
|
|
750
|
+
for (const [rows, state] of [[this.devices, "active"], [this.revoked, "revoked"]] as const) {
|
|
751
|
+
for (const d of rows) {
|
|
752
|
+
if (d.keys?.pub === pub) return { device: d, kind: "primary", state };
|
|
753
|
+
const companion = (Array.isArray(d.companions) ? d.companions : []).find((c) => c.pub === pub);
|
|
754
|
+
if (companion) return { device: d, kind: "companion", state, companion };
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
private keyOwner(pub: string): KeyLookup | null {
|
|
761
|
+
this.purgeExpired();
|
|
762
|
+
return this.scanKey(pub);
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
/** Which device holds `pub`, as primary or companion, active before revoked. */
|
|
766
|
+
lookupKey(pub: string): KeyLookup | null {
|
|
767
|
+
return typeof pub === "string" && pub !== "" ? this.keyOwner(pub) : null;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Is `pub` held by any active or revoked row (primary or companion)? */
|
|
771
|
+
isKeyHeld(pub: string): boolean {
|
|
772
|
+
return this.lookupKey(pub) !== null;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Apply `fn` to an active row and persist; a failed write restores the row and rethrows. */
|
|
776
|
+
private mutateRow(row: PairedDevice, fn: (r: PairedDevice) => void): void {
|
|
777
|
+
const before = structuredClone(row);
|
|
778
|
+
fn(row);
|
|
779
|
+
try {
|
|
780
|
+
this.persist();
|
|
781
|
+
} catch (err) {
|
|
782
|
+
const i = this.devices.indexOf(row);
|
|
783
|
+
if (i >= 0) this.devices[i] = before;
|
|
784
|
+
throw err;
|
|
785
|
+
}
|
|
786
|
+
this.emitChange();
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Bind (or replace) the primary key of an ACTIVE device. `held` = the key belongs to another row or
|
|
791
|
+
* is a companion (active or revoked); re-binding the same key is an idempotent `bound`.
|
|
792
|
+
*/
|
|
793
|
+
bindKey(deviceId: string, pub: string): BindKeyResult {
|
|
794
|
+
const row = this.devices.find((d) => d.id === deviceId);
|
|
795
|
+
if (!row) return "no-device";
|
|
796
|
+
const owner = this.keyOwner(pub);
|
|
797
|
+
if (owner && !(owner.device.id === deviceId && owner.kind === "primary")) return "held";
|
|
798
|
+
if (row.keys?.pub === pub) return "bound";
|
|
799
|
+
const replaced = !!row.keys;
|
|
800
|
+
this.mutateRow(row, (r) => {
|
|
801
|
+
r.keys = { pub, createdAt: new Date().toISOString() };
|
|
802
|
+
});
|
|
803
|
+
return replaced ? "replaced" : "bound";
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** Add a status-only companion to an active device (cap `MAX_COMPANIONS`, key unique everywhere). */
|
|
807
|
+
addCompanion(deviceId: string, c: { pub: string; origin: string }): AddCompanionResult {
|
|
808
|
+
const row = this.devices.find((d) => d.id === deviceId);
|
|
809
|
+
if (!row) return "no-device";
|
|
810
|
+
if (this.keyOwner(c.pub)) return "held";
|
|
811
|
+
if ((row.companions?.length ?? 0) >= MAX_COMPANIONS) return "cap";
|
|
812
|
+
this.mutateRow(row, (r) => {
|
|
813
|
+
(r.companions ??= []).push(newCompanion(c.pub, c.origin, new Date().toISOString()));
|
|
814
|
+
});
|
|
815
|
+
return "added";
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
/** Remove one companion of an active device by id. True if one was removed. */
|
|
819
|
+
removeCompanion(deviceId: string, companionId: string): boolean {
|
|
820
|
+
const row = this.devices.find((d) => d.id === deviceId);
|
|
821
|
+
if (!row?.companions?.some((c) => c.id === companionId)) return false;
|
|
822
|
+
this.mutateRow(row, (r) => {
|
|
823
|
+
r.companions = (r.companions ?? []).filter((c) => c.id !== companionId);
|
|
824
|
+
});
|
|
825
|
+
return true;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* Answer for a VERIFIED key (the caller checked the signature). `revoked` wins; `expired` uses the
|
|
830
|
+
* same per-row judgement as `verifyDetailed` (`currentVerdict` + the previous-bearer grace), so the
|
|
831
|
+
* check says `expired` exactly when the bearer is refused `bearer_expired`. Companions get
|
|
832
|
+
* `status-only` with no tier; `expired`/`revoked`/`unknown` carry no tier or scope.
|
|
833
|
+
*/
|
|
834
|
+
deviceKeyStatus(pub: string): DeviceStatusReply {
|
|
835
|
+
const hit = this.lookupKey(pub);
|
|
836
|
+
if (!hit) return { status: "unknown" };
|
|
837
|
+
if (hit.state === "revoked") return { status: "revoked" };
|
|
838
|
+
const now = Date.now();
|
|
839
|
+
if (this.currentVerdict(hit.device, now).status !== "ok" && !previousGraceLive(hit.device, now)) {
|
|
840
|
+
return { status: "expired" };
|
|
841
|
+
}
|
|
842
|
+
return hit.kind === "companion"
|
|
843
|
+
? { status: "paired", scope: "status-only" }
|
|
844
|
+
: { status: "paired", scope: "full", tier: hit.device.tier };
|
|
845
|
+
}
|
|
846
|
+
|
|
489
847
|
list(): PairedDeviceView[] {
|
|
490
848
|
return this.devices.map((d) => this.toView(d));
|
|
491
849
|
}
|
|
@@ -498,6 +856,10 @@ export class PairedDeviceRegistry {
|
|
|
498
856
|
lastSeen: d.lastSeen,
|
|
499
857
|
source: d.source,
|
|
500
858
|
tier: d.tier,
|
|
859
|
+
...(d.keys?.pub ? { keyId: keyIdOf(d.keys.pub) } : {}),
|
|
860
|
+
...(Array.isArray(d.companions) && d.companions.length > 0
|
|
861
|
+
? { companions: d.companions.map((c) => ({ id: c.id, origin: c.origin, createdAt: c.createdAt })) }
|
|
862
|
+
: {}),
|
|
501
863
|
};
|
|
502
864
|
}
|
|
503
865
|
}
|