@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
|
@@ -35,6 +35,13 @@ export interface HostAdmissionOptions {
|
|
|
35
35
|
* See change: add-tailscale-cert-tls (D6).
|
|
36
36
|
*/
|
|
37
37
|
tlsListenerNames?: () => string[];
|
|
38
|
+
/**
|
|
39
|
+
* Are live previews on? Adds the operator-visible pattern row `live preview capability hosts`
|
|
40
|
+
* to `GET /api/host-gate`. Preview hosts themselves are NEVER statically admitted: `previewApp`
|
|
41
|
+
* admits the exact `originHost` of a live capability, so a wildcard never admits a host.
|
|
42
|
+
* See change: serve-live-previews-on-capability-origin (D3).
|
|
43
|
+
*/
|
|
44
|
+
livePreviewEnabled?: () => boolean;
|
|
38
45
|
}
|
|
39
46
|
|
|
40
47
|
/** The source labels the operator UI renders, in first-match order (D1). */
|
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
parseHostname,
|
|
22
22
|
} from "@blackbelt-technology/pi-dashboard-shared/host-admission.js";
|
|
23
23
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
24
|
+
import { redactCapability } from "../live-server/capability-redact.js";
|
|
24
25
|
import { sanitizeHeaderForLog } from "./cors-origin.js";
|
|
25
26
|
import {
|
|
26
27
|
type AdmittedSource,
|
|
@@ -160,7 +161,8 @@ export class HostGateState {
|
|
|
160
161
|
this.suppressed += 1;
|
|
161
162
|
return;
|
|
162
163
|
}
|
|
163
|
-
|
|
164
|
+
// The line echoes the Origin and the request URL: a preview label, a tier-5 pid or a tier-3 `?k=` must not reach the log (D2).
|
|
165
|
+
this.emit(redactCapability(`[host-gate] ${outcome} host=${sanitizeHeaderForLog(host)} ${detail}`));
|
|
164
166
|
this.windowCount += 1;
|
|
165
167
|
this.logHosts.delete(host);
|
|
166
168
|
this.logHosts.set(host, ts);
|
|
@@ -256,7 +258,7 @@ function escapeHtml(value: string): string {
|
|
|
256
258
|
}
|
|
257
259
|
|
|
258
260
|
/** The JSON 403 body (D4), same self-describing shape as `network_not_allowed`. */
|
|
259
|
-
|
|
261
|
+
function hostGateRefusalBody(): {
|
|
260
262
|
success: false;
|
|
261
263
|
error: string;
|
|
262
264
|
reason: string;
|
|
@@ -351,6 +353,15 @@ export function admittedHostRows(
|
|
|
351
353
|
for (const raw of safeLiveTunnelOrigins(opts)) add(hostnameFromUrl(raw), "live-tunnel");
|
|
352
354
|
for (const name of safeTlsListenerNames(opts)) add(normalizeName(name), "tls-listener");
|
|
353
355
|
for (const raw of opts.allowedHosts ?? []) add(normalizeName(raw), "allowed-host");
|
|
356
|
+
// One pattern row, never an enumeration: `admitted` is readable by every `GET /api/config` caller,
|
|
357
|
+
// and a label is a secret (D2). Present whenever previews are enabled, even with zero live entries.
|
|
358
|
+
let previewsOn = false;
|
|
359
|
+
try {
|
|
360
|
+
previewsOn = opts.livePreviewEnabled?.() === true;
|
|
361
|
+
} catch {
|
|
362
|
+
/* fail-empty, like the other dynamic sources */
|
|
363
|
+
}
|
|
364
|
+
if (previewsOn) add("live preview capability hosts", "live-preview");
|
|
354
365
|
return rows;
|
|
355
366
|
}
|
|
356
367
|
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { isIPv4, isIPv6 } from "node:net";
|
|
7
7
|
import os from "node:os";
|
|
8
|
+
import { GENERIC_NETWORK_DENIED_HINT, NETWORK_NOT_ALLOWED } from "@blackbelt-technology/pi-dashboard-shared/network-denial-signal.js";
|
|
8
9
|
import { routeTier } from "@blackbelt-technology/pi-dashboard-shared/route-tiers.js";
|
|
9
10
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
10
11
|
import { redactCapability } from "../live-server/capability-redact.js";
|
|
@@ -407,11 +408,11 @@ function sendNetworkDenied(request: FastifyRequest, reply: FastifyReply, localTr
|
|
|
407
408
|
// distinguish-offline-from-network-denied.
|
|
408
409
|
reply.code(403).send({
|
|
409
410
|
success: false,
|
|
410
|
-
error:
|
|
411
|
+
error: NETWORK_NOT_ALLOWED,
|
|
411
412
|
// Identical in every trust mode: this body goes to credential-less callers
|
|
412
413
|
// and must not disclose the mode or point at a trusted list.
|
|
413
414
|
reason: "Source IP is not loopback and the request is not authenticated.",
|
|
414
|
-
hint:
|
|
415
|
+
hint: GENERIC_NETWORK_DENIED_HINT,
|
|
415
416
|
});
|
|
416
417
|
}
|
|
417
418
|
|
|
@@ -433,36 +434,50 @@ function hasNetworkPassCondition(
|
|
|
433
434
|
request: FastifyRequest,
|
|
434
435
|
opts: { readTrusted: () => string[]; localToken?: string; localTrust?: LocalTrustContext },
|
|
435
436
|
): boolean {
|
|
437
|
+
const { passed, trustedList } = evaluateNetworkPass(request, opts);
|
|
438
|
+
// Telemetry stays on the guard paths: refusals included, so the loopback-entry
|
|
439
|
+
// warning keeps firing.
|
|
440
|
+
if (trustedList) noteTrustedList(trustedList);
|
|
441
|
+
// Admitted by the network match alone — counted once per request (the
|
|
442
|
+
// per-route guard and the universal hook both evaluate it).
|
|
443
|
+
if (passed === "trusted") noteNetworkOnlyAdmission(request as unknown as NetworkOnlySource);
|
|
444
|
+
return passed !== null;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Which arm of the network pass predicate admitted a request (`null` = refused). */
|
|
448
|
+
export type NetworkPassArm = "local" | "strict-exception" | "token" | "auth" | "trusted";
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* PURE network-pass core: same ordered arms as the guards, but no telemetry and
|
|
452
|
+
* no request mutation. `trustedList` is set iff the core read the admission list.
|
|
453
|
+
* Shared by the guards (via `hasNetworkPassCondition`) and `GET /api/health`'s
|
|
454
|
+
* `networkAccess` verdict so the two cannot drift.
|
|
455
|
+
* See change: surface-network-denial-on-health (D2).
|
|
456
|
+
*/
|
|
457
|
+
export function evaluateNetworkPass(
|
|
458
|
+
request: FastifyRequest,
|
|
459
|
+
opts: { readTrusted: () => string[]; localToken?: string; localTrust?: LocalTrustContext },
|
|
460
|
+
): { passed: NetworkPassArm | null; trustedList?: string[] } {
|
|
436
461
|
const headers = request.headers as Record<string, unknown>;
|
|
437
|
-
// Genuine same-
|
|
438
|
-
|
|
439
|
-
// (D10, narrowed). Under `requireLocalProof` it additionally needs proof.
|
|
440
|
-
if (isLocallyTrusted({ ip: request.ip, headers }, opts.localTrust)) return true;
|
|
462
|
+
// Genuine same-origin (loopback AND no proxy-forwarding header). Under `requireLocalProof` it additionally needs proof.
|
|
463
|
+
if (isLocallyTrusted({ ip: request.ip, headers }, opts.localTrust)) return { passed: "local" };
|
|
441
464
|
// Strict exceptions for a bare local caller: READ observe-tier REST routes, and
|
|
442
|
-
// the `/v1/*` model proxy (
|
|
443
|
-
// unchanged by design — a documented trade-off).
|
|
465
|
+
// the `/v1/*` model proxy (admission unchanged by design — a documented trade-off).
|
|
444
466
|
if (
|
|
445
467
|
opts.localTrust?.strict() &&
|
|
446
468
|
isGenuinelyLocal(request.ip, headers) &&
|
|
447
469
|
(isObserveApiRequest(request) || isModelProxyRequest(request))
|
|
448
470
|
) {
|
|
449
|
-
return
|
|
471
|
+
return { passed: "strict-exception" };
|
|
450
472
|
}
|
|
451
473
|
// Affirmative local-IPC token.
|
|
452
|
-
if (opts.localToken && hasLocalCredential(headers)) return
|
|
474
|
+
if (opts.localToken && hasLocalCredential(headers)) return { passed: "token" };
|
|
453
475
|
// Credentials BEFORE the network match, so a request that holds one is never
|
|
454
|
-
// classified
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
if (isTrustedSource(request.ip, headers, trusted, opts.localTrust)) {
|
|
460
|
-
// Admitted by the network match alone — counted once per request (the
|
|
461
|
-
// per-route guard and the universal hook both evaluate it).
|
|
462
|
-
noteNetworkOnlyAdmission(request as unknown as NetworkOnlySource);
|
|
463
|
-
return true;
|
|
464
|
-
}
|
|
465
|
-
return false;
|
|
476
|
+
// classified as network-only. See change: retire-trusted-networks-bypass (D3).
|
|
477
|
+
if ((request as any).isAuthenticated) return { passed: "auth" };
|
|
478
|
+
const trustedList = opts.readTrusted();
|
|
479
|
+
if (isTrustedSource(request.ip, headers, trustedList, opts.localTrust)) return { passed: "trusted", trustedList };
|
|
480
|
+
return { passed: null, trustedList };
|
|
466
481
|
}
|
|
467
482
|
|
|
468
483
|
/**
|
|
@@ -514,7 +529,7 @@ export function createNetworkGuard(
|
|
|
514
529
|
* Every dangerous route in the server lives under one of these; the
|
|
515
530
|
* namespace-coverage test enforces that. See change: add-universal-network-guard.
|
|
516
531
|
*/
|
|
517
|
-
const GUARD_JURISDICTION_PREFIXES = ["/api/", "/v1/", "/editor/", "/live/"] as const;
|
|
532
|
+
const GUARD_JURISDICTION_PREFIXES = ["/api/", "/v1/", "/editor/", "/live/", "/preview/"] as const;
|
|
518
533
|
|
|
519
534
|
/**
|
|
520
535
|
* Fixed in-namespace public endpoints, compared against the EXACT pathname.
|
|
@@ -531,6 +546,17 @@ const PUBLIC_IN_NAMESPACE_PATHS: ReadonlySet<string> = new Set([
|
|
|
531
546
|
"/api/identity/login-config",
|
|
532
547
|
]);
|
|
533
548
|
|
|
549
|
+
/**
|
|
550
|
+
* Plugin OAuth return endpoints reachable WITHOUT a dashboard session, network pass condition or signed-in
|
|
551
|
+
* principal (GET only). The browser that completes a Google consent may be the system browser or another
|
|
552
|
+
* device with no dashboard cookie. The route accepts a code only for a pending sign-in whose unguessable
|
|
553
|
+
* `state` this dashboard issued (one-shot, 300 s) — the state is the credential, exactly like the login
|
|
554
|
+
* `/auth/callback/*`. Exact paths only; no prefix match. See change: add-google-connect (D12b).
|
|
555
|
+
*/
|
|
556
|
+
export const PUBLIC_PLUGIN_CALLBACK_PATHS: ReadonlySet<string> = new Set([
|
|
557
|
+
"/api/plugins/google/oauth/remote-callback",
|
|
558
|
+
]);
|
|
559
|
+
|
|
534
560
|
/**
|
|
535
561
|
* Resolve `.` / `..` segments (RFC 3986 "remove_dot_segments") in an already
|
|
536
562
|
* decoded absolute path. `..` above the root is clamped, as RFC 3986 requires.
|
|
@@ -814,6 +840,7 @@ export function createNetworkGuardHook(opts: NetworkGuardHookOptions) {
|
|
|
814
840
|
const bypassUrls = opts.getBypassUrls?.() ?? [];
|
|
815
841
|
const isPublicInNamespace = (path: string): boolean =>
|
|
816
842
|
(PUBLIC_IN_NAMESPACE_PATHS.has(path) && methodAllowsHealth) ||
|
|
843
|
+
(PUBLIC_PLUGIN_CALLBACK_PATHS.has(path) && methodAllowsHealth) ||
|
|
817
844
|
pairingPrefixes.some((prefix) => path.startsWith(prefix)) ||
|
|
818
845
|
isBypassed(path, bypassUrls);
|
|
819
846
|
if (isPublicInNamespace(target.raw) && isPublicInNamespace(target.resolved)) return;
|
|
@@ -14,6 +14,10 @@ import { createHash } from "node:crypto";
|
|
|
14
14
|
import fs from "node:fs";
|
|
15
15
|
import { createRequire } from "node:module";
|
|
16
16
|
import path from "node:path";
|
|
17
|
+
import type {
|
|
18
|
+
CredentialFileId,
|
|
19
|
+
CredentialLockReason,
|
|
20
|
+
} from "@blackbelt-technology/pi-dashboard-shared/credential-encryption.js";
|
|
17
21
|
|
|
18
22
|
const _require = createRequire(import.meta.url);
|
|
19
23
|
const _lockfile = _require("proper-lockfile") as typeof import("proper-lockfile");
|
|
@@ -63,7 +67,7 @@ const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve,
|
|
|
63
67
|
* would stall every HTTP request and WebSocket frame for the whole wait.
|
|
64
68
|
* See change: fix-provider-auth-lock-contention.
|
|
65
69
|
*/
|
|
66
|
-
async function acquireLock(
|
|
70
|
+
export async function acquireLock(
|
|
67
71
|
filePath: string,
|
|
68
72
|
budgetMs: number,
|
|
69
73
|
onCompromised: (err: Error) => void,
|
|
@@ -86,6 +90,34 @@ async function acquireLock(
|
|
|
86
90
|
}
|
|
87
91
|
}
|
|
88
92
|
|
|
93
|
+
// ── Opt-in codec seam ─────────────────────────────────────────────────
|
|
94
|
+
//
|
|
95
|
+
// Only the two credential stores pass a codec (design D1); every other caller
|
|
96
|
+
// keeps byte-identical plain-JSON behaviour. See change: encrypt-credentials-at-rest.
|
|
97
|
+
|
|
98
|
+
/** What a codec makes of the bytes on disk. */
|
|
99
|
+
type CodecReadResult =
|
|
100
|
+
| { kind: "absent" }
|
|
101
|
+
/** `encrypted:false` = a valid plaintext JSON object (readable; encrypted by the next write). */
|
|
102
|
+
| { kind: "document"; data: Record<string, unknown>; encrypted: boolean }
|
|
103
|
+
/** An envelope this process cannot read. NEVER quarantined, NEVER overwritten. */
|
|
104
|
+
| { kind: "locked"; reason: CredentialLockReason }
|
|
105
|
+
| { kind: "corrupt" };
|
|
106
|
+
|
|
107
|
+
/** Encode/decode seam for `readJsonChecked` / `writeJsonAtomic` / `withLockedJsonFile`. */
|
|
108
|
+
export interface JsonFileCodec {
|
|
109
|
+
readonly fileId: CredentialFileId;
|
|
110
|
+
decode(bytes: Buffer): CodecReadResult;
|
|
111
|
+
/**
|
|
112
|
+
* Bytes to write for `data`. `existing` = the bytes currently on disk (if
|
|
113
|
+
* any). Throws (`code: "credential_locked"`) when no key is available or the
|
|
114
|
+
* existing bytes are a locked envelope: a locked file is never overwritten.
|
|
115
|
+
*/
|
|
116
|
+
encode(data: unknown, existing?: Buffer): Buffer;
|
|
117
|
+
/** The key-failure reason while no key is available (writes are refused), else `undefined`. */
|
|
118
|
+
unavailableReason(): CredentialLockReason | undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
89
121
|
/** Rejects promise-like results at the type level (see `withLockedJsonFile`). */
|
|
90
122
|
export type NotPromise<T> = T extends PromiseLike<unknown> ? never : unknown;
|
|
91
123
|
|
|
@@ -98,6 +130,11 @@ export interface LockedJsonFileOptions {
|
|
|
98
130
|
logTag?: string;
|
|
99
131
|
/** Abort the lock-retry wait. Checked before every attempt; never interrupts `fn`. */
|
|
100
132
|
signal?: AbortSignal;
|
|
133
|
+
/**
|
|
134
|
+
* Credential codec. With one, no plaintext `{}` placeholder is pre-created:
|
|
135
|
+
* the file first appears already encoded, on the first successful write.
|
|
136
|
+
*/
|
|
137
|
+
codec?: JsonFileCodec;
|
|
101
138
|
}
|
|
102
139
|
|
|
103
140
|
/**
|
|
@@ -117,13 +154,13 @@ export interface LockedJsonFileOptions {
|
|
|
117
154
|
export async function withLockedJsonFile<T>(
|
|
118
155
|
filePath: string,
|
|
119
156
|
fn: () => T & NotPromise<T>,
|
|
120
|
-
{ budgetMs = LOCK_RETRY_BUDGET_MS, createIfMissing = true, logTag = "locked-json", signal }: LockedJsonFileOptions = {},
|
|
157
|
+
{ budgetMs = LOCK_RETRY_BUDGET_MS, createIfMissing = true, logTag = "locked-json", signal, codec }: LockedJsonFileOptions = {},
|
|
121
158
|
): Promise<T> {
|
|
122
159
|
signal?.throwIfAborted();
|
|
123
160
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
124
161
|
// With `realpath: false` proper-lockfile only `mkdir`s `<file>.lock`, so the
|
|
125
162
|
// target need not exist; the placeholder is for interactive writers.
|
|
126
|
-
if (createIfMissing && !fs.existsSync(filePath)) {
|
|
163
|
+
if (createIfMissing && !codec && !fs.existsSync(filePath)) {
|
|
127
164
|
// 0600 explicitly: without it the placeholder lands at 0666 & ~umask
|
|
128
165
|
// (≈0644) and writeJsonAtomic's permission preservation carries that onto
|
|
129
166
|
// every later write. See change: fix-corrupt-auth-json-500.
|
|
@@ -165,6 +202,10 @@ export interface CheckedJsonRead<T> {
|
|
|
165
202
|
corrupt: boolean;
|
|
166
203
|
/** A backup of these exact bytes exists on disk (this call, or a dedup hit). */
|
|
167
204
|
quarantined: boolean;
|
|
205
|
+
/** Codec reads only: the file is an envelope this process cannot read. `data` is `{}`; nothing was quarantined. */
|
|
206
|
+
locked?: CredentialLockReason;
|
|
207
|
+
/** Codec reads only: `true` = decoded from an envelope, `false` = valid plaintext (to be encrypted by the next write). */
|
|
208
|
+
encrypted?: boolean;
|
|
168
209
|
}
|
|
169
210
|
|
|
170
211
|
/** In-process dedup of quarantined content: path → sha256 hex set, recorded only on a successful copy. */
|
|
@@ -239,6 +280,7 @@ function parseJsonObject(raw: string, name: string): Record<string, unknown> {
|
|
|
239
280
|
export function readJsonChecked<T extends object = Record<string, unknown>>(
|
|
240
281
|
filePath: string,
|
|
241
282
|
logTag = "locked-json",
|
|
283
|
+
codec?: JsonFileCodec,
|
|
242
284
|
): CheckedJsonRead<T> {
|
|
243
285
|
let bytes: Buffer;
|
|
244
286
|
try {
|
|
@@ -247,6 +289,14 @@ export function readJsonChecked<T extends object = Record<string, unknown>>(
|
|
|
247
289
|
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { data: {} as T, corrupt: false, quarantined: false };
|
|
248
290
|
throw err;
|
|
249
291
|
}
|
|
292
|
+
if (codec) {
|
|
293
|
+
const out = codec.decode(bytes);
|
|
294
|
+
if (out.kind === "document") return { data: out.data as T, corrupt: false, quarantined: false, encrypted: out.encrypted };
|
|
295
|
+
if (out.kind === "locked") return { data: {} as T, corrupt: false, quarantined: false, locked: out.reason };
|
|
296
|
+
if (out.kind === "absent") return { data: {} as T, corrupt: false, quarantined: false };
|
|
297
|
+
// corrupt: today's byte-exact quarantine
|
|
298
|
+
return { data: {} as T, corrupt: true, quarantined: quarantineCorruptFile(filePath, bytes, logTag) };
|
|
299
|
+
}
|
|
250
300
|
try {
|
|
251
301
|
return { data: parseJsonObject(bytes.toString("utf-8"), path.basename(filePath)) as T, corrupt: false, quarantined: false };
|
|
252
302
|
} catch (err) {
|
|
@@ -294,10 +344,22 @@ export function corruptUnbackedRefusal(filePath: string): Error {
|
|
|
294
344
|
* Atomic tmp+rename write. Preserves the existing mode with group/world bits
|
|
295
345
|
* cleared, or 0600 for a new file; `forceMode` overrides (corrupt-file repair).
|
|
296
346
|
*/
|
|
297
|
-
export function writeJsonAtomic(filePath: string, data: unknown, forceMode?: number): void {
|
|
347
|
+
export function writeJsonAtomic(filePath: string, data: unknown, forceMode?: number, codec?: JsonFileCodec): void {
|
|
298
348
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
299
|
-
const tmp = filePath
|
|
300
|
-
|
|
349
|
+
const tmp = `${filePath}.tmp`;
|
|
350
|
+
let content: string | Buffer;
|
|
351
|
+
if (codec) {
|
|
352
|
+
let existing: Buffer | undefined;
|
|
353
|
+
try {
|
|
354
|
+
existing = fs.readFileSync(filePath);
|
|
355
|
+
} catch (err) {
|
|
356
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
357
|
+
}
|
|
358
|
+
// Throws before any byte is written when no key is available or the file is a locked envelope.
|
|
359
|
+
content = codec.encode(data, existing);
|
|
360
|
+
} else {
|
|
361
|
+
content = `${JSON.stringify(data, null, 2)}\n`;
|
|
362
|
+
}
|
|
301
363
|
|
|
302
364
|
let mode = 0o600;
|
|
303
365
|
if (forceMode !== undefined) {
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<agentDir>/models.json` store: read and replace ONE `providers.<id>` block.
|
|
3
|
+
*
|
|
4
|
+
* Write = lock (`acquireLock`, 2 s `ELOCKED` retry) → read → whole-file refusals
|
|
5
|
+
* (`unreadable`, `has_comments`, `legacy_shape`, `invalid_before`) → revision check →
|
|
6
|
+
* `prepareBlock` (pre-pi refusals) → tmp file next to the real path → pi's two
|
|
7
|
+
* layers on the result → revision/bytes re-check under the lock → rename (symlink and
|
|
8
|
+
* mode kept, new file 0600). A failed write leaves `models.json` byte-identical and
|
|
9
|
+
* no tmp file. Never logs values.
|
|
10
|
+
*
|
|
11
|
+
* See change: add-provider-advanced-settings (D3, tasks 2.1 / 2.3).
|
|
12
|
+
*/
|
|
13
|
+
import { createHash } from "node:crypto";
|
|
14
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { dirname, join } from "node:path";
|
|
16
|
+
import { resolvePiAgentDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
|
|
17
|
+
import { parsePiJson, stripBom } from "@blackbelt-technology/pi-dashboard-shared/models-json-reader.js";
|
|
18
|
+
import type { ProviderBlock } from "@blackbelt-technology/pi-dashboard-shared/provider-overrides.js";
|
|
19
|
+
import { checkComposerRules, ValidatorMissingError, validateModelsJsonFile } from "../model-proxy/pi-models-validator.js";
|
|
20
|
+
import { acquireLock } from "./locked-json-file.js";
|
|
21
|
+
import { type BlockRefusal, prepareBlock } from "./provider-block-checks.js";
|
|
22
|
+
|
|
23
|
+
const PREFIX = "provider_overrides";
|
|
24
|
+
const LOCK_BUDGET_MS = 2_000;
|
|
25
|
+
|
|
26
|
+
const modelsJsonPath = (): string => join(resolvePiAgentDir(), "models.json");
|
|
27
|
+
|
|
28
|
+
const isRec = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
29
|
+
|
|
30
|
+
const refusal = (status: number, code: string, error: string): BlockRefusal => ({ status, code: `${PREFIX}.${code}`, error });
|
|
31
|
+
|
|
32
|
+
/** Whole-file refusal codes (409), also the GET `reason` for the first three. */
|
|
33
|
+
type FileRefusalCode = "unreadable" | "has_comments" | "legacy_shape" | "invalid_before";
|
|
34
|
+
|
|
35
|
+
function sortKeys(v: unknown): unknown {
|
|
36
|
+
if (Array.isArray(v)) return v.map(sortKeys);
|
|
37
|
+
if (isRec(v)) return Object.fromEntries(Object.keys(v).sort().map((k) => [k, sortKeys(v[k])]));
|
|
38
|
+
return v;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Hash of a stored block (key-order independent); absent block → hash of `null`. */
|
|
42
|
+
export function blockRevision(block: ProviderBlock | undefined): string {
|
|
43
|
+
return createHash("sha256").update(JSON.stringify(sortKeys(block ?? null))).digest("hex").slice(0, 16);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** True when a `//` comment token sits outside a string (pi's own tokenisation). */
|
|
47
|
+
function hasLineComments(text: string): boolean {
|
|
48
|
+
for (const m of text.matchAll(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g)) if (m[0][0] !== '"') return true;
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface FileState {
|
|
53
|
+
/** Raw bytes read (null = file absent). */
|
|
54
|
+
text: string | null;
|
|
55
|
+
doc: Record<string, unknown>;
|
|
56
|
+
/** Refusal that applies to the file as a whole (none = writable). */
|
|
57
|
+
fileRefusal?: FileRefusalCode;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Parse the file as pi does and classify it. `{ unreadable }` when pi cannot parse it. */
|
|
61
|
+
function readState(real: string): { ok: true; state: FileState } | { ok: false; code: "unreadable" } {
|
|
62
|
+
let text: string;
|
|
63
|
+
try {
|
|
64
|
+
text = readFileSync(real, "utf-8");
|
|
65
|
+
} catch (err) {
|
|
66
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return { ok: true, state: { text: null, doc: {} } };
|
|
67
|
+
return { ok: false, code: "unreadable" };
|
|
68
|
+
}
|
|
69
|
+
let parsed: unknown;
|
|
70
|
+
try {
|
|
71
|
+
parsed = parsePiJson(text);
|
|
72
|
+
} catch {
|
|
73
|
+
return { ok: false, code: "unreadable" };
|
|
74
|
+
}
|
|
75
|
+
const state: FileState = { text, doc: {} };
|
|
76
|
+
if (!isRec(parsed)) {
|
|
77
|
+
state.fileRefusal = "legacy_shape"; // top-level array / scalar
|
|
78
|
+
return { ok: true, state };
|
|
79
|
+
}
|
|
80
|
+
state.doc = parsed;
|
|
81
|
+
if (hasLineComments(stripBom(text))) state.fileRefusal = "has_comments";
|
|
82
|
+
else if (!isRec(parsed.providers) && ("models" in parsed || "providers" in parsed)) state.fileRefusal = "legacy_shape";
|
|
83
|
+
return { ok: true, state };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const storedBlock = (doc: Record<string, unknown>, provider: string): ProviderBlock | undefined => {
|
|
87
|
+
const providers = doc.providers;
|
|
88
|
+
if (!isRec(providers) || !Object.hasOwn(providers, provider)) return undefined;
|
|
89
|
+
const b = providers[provider];
|
|
90
|
+
return isRec(b) ? (b as ProviderBlock) : undefined;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export interface StoreRead {
|
|
94
|
+
/** Stored (unmasked) block; undefined when absent. */
|
|
95
|
+
block: ProviderBlock | undefined;
|
|
96
|
+
revision: string;
|
|
97
|
+
/** Set when a write would be refused for the file as a whole. */
|
|
98
|
+
fileRefusal?: FileRefusalCode;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Read one provider's block, for GET. `invalid_before` needs pi's validator; a missing
|
|
103
|
+
* validator is not reported here (the PUT fails closed with 503). Unreadable → refusal.
|
|
104
|
+
*/
|
|
105
|
+
export async function readModelsJsonBlock(provider: string): Promise<{ ok: true; read: StoreRead } | { ok: false; refusal: BlockRefusal }> {
|
|
106
|
+
const real = resolveReal(modelsJsonPath());
|
|
107
|
+
const r = readState(real);
|
|
108
|
+
if (!r.ok) return { ok: false, refusal: refusal(409, "unreadable", "models.json cannot be parsed") };
|
|
109
|
+
const { state } = r;
|
|
110
|
+
let fileRefusal = state.fileRefusal;
|
|
111
|
+
if (!fileRefusal && state.text !== null) {
|
|
112
|
+
try {
|
|
113
|
+
const v = await validateModelsJsonFile(real);
|
|
114
|
+
if (!v.ok) fileRefusal = "invalid_before";
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (!(err instanceof ValidatorMissingError)) throw err;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const block = storedBlock(state.doc, provider);
|
|
120
|
+
return { ok: true, read: { block, revision: blockRevision(block), ...(fileRefusal ? { fileRefusal } : {}) } };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Existing models.json providers (ids), for the 404 rule; `[]` when absent/unreadable. */
|
|
124
|
+
export function listModelsJsonProviderIds(): string[] {
|
|
125
|
+
const r = readState(resolveReal(modelsJsonPath()));
|
|
126
|
+
if (!r.ok || !isRec(r.state.doc.providers)) return [];
|
|
127
|
+
return Object.keys(r.state.doc.providers);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Stored block of one provider, sync and unlocked; undefined when the file is absent, unreadable or has no block. */
|
|
131
|
+
export function readStoredBlock(provider: string): ProviderBlock | undefined {
|
|
132
|
+
const r = readState(resolveReal(modelsJsonPath()));
|
|
133
|
+
return r.ok ? storedBlock(r.state.doc, provider) : undefined;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function resolveReal(p: string): string {
|
|
137
|
+
try {
|
|
138
|
+
return realpathSync(p);
|
|
139
|
+
} catch {
|
|
140
|
+
return p;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface WriteOptions {
|
|
145
|
+
provider: string;
|
|
146
|
+
/** Block as sent (masked values allowed). */
|
|
147
|
+
block: unknown;
|
|
148
|
+
/** Revision the client read. */
|
|
149
|
+
revision: string;
|
|
150
|
+
/** True when pi itself ships the provider (its models supply a default `baseUrl`). */
|
|
151
|
+
isBuiltIn: boolean;
|
|
152
|
+
isSelfPointing: (url: string) => boolean;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export type WriteResult =
|
|
156
|
+
| { ok: true; block: ProviderBlock; revision: string }
|
|
157
|
+
| { ok: false; refusal: BlockRefusal };
|
|
158
|
+
|
|
159
|
+
/** Replace `providers.<provider>` in `models.json` under the lock. See the file header for the order of checks. */
|
|
160
|
+
export async function writeModelsJsonBlock(opts: WriteOptions): Promise<WriteResult> {
|
|
161
|
+
const { provider } = opts;
|
|
162
|
+
const target = modelsJsonPath();
|
|
163
|
+
try {
|
|
164
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
165
|
+
} catch {
|
|
166
|
+
return fail(500, "write_failed", "Could not create the agent directory");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
let compromised: Error | undefined;
|
|
170
|
+
let release: () => Promise<void>;
|
|
171
|
+
try {
|
|
172
|
+
release = await acquireLock(target, LOCK_BUDGET_MS, (err) => {
|
|
173
|
+
compromised ??= err;
|
|
174
|
+
console.warn(`[models-json] lock compromised (${(err as { code?: string }).code ?? "unknown"})`);
|
|
175
|
+
});
|
|
176
|
+
} catch (err) {
|
|
177
|
+
if ((err as { code?: string }).code === "ELOCKED") return fail(503, "locked", "models.json is locked by another writer");
|
|
178
|
+
return fail(500, "write_failed", "Could not lock models.json");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
let tmp: string | undefined;
|
|
182
|
+
try {
|
|
183
|
+
const real = resolveReal(target);
|
|
184
|
+
const r = readState(real);
|
|
185
|
+
if (!r.ok) return fail(409, "unreadable", "models.json cannot be parsed");
|
|
186
|
+
const { state } = r;
|
|
187
|
+
if (state.fileRefusal) return fail(409, state.fileRefusal, FILE_MESSAGES[state.fileRefusal]);
|
|
188
|
+
|
|
189
|
+
if (state.text !== null) {
|
|
190
|
+
const before = await validateModelsJsonFile(real);
|
|
191
|
+
if (!before.ok) return fail(409, "invalid_before", `models.json already fails pi's check: ${before.message}`);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const stored = storedBlock(state.doc, provider);
|
|
195
|
+
if (blockRevision(stored) !== opts.revision) return fail(409, "stale_revision", "The block changed since it was read");
|
|
196
|
+
|
|
197
|
+
const prepared = prepareBlock({ incoming: opts.block, stored, prefix: PREFIX, isSelfPointing: opts.isSelfPointing });
|
|
198
|
+
if (!prepared.ok) return { ok: false, refusal: prepared.refusal };
|
|
199
|
+
const next = prepared.block;
|
|
200
|
+
const removing = Object.keys(next).length === 0;
|
|
201
|
+
// Nothing stored and nothing to store: no write (never create a file for `{}`).
|
|
202
|
+
if (removing && stored === undefined) return { ok: true, block: next, revision: blockRevision(undefined) };
|
|
203
|
+
|
|
204
|
+
const doc: Record<string, unknown> = { ...state.doc };
|
|
205
|
+
const providers: Record<string, unknown> = isRec(doc.providers) ? { ...doc.providers } : {};
|
|
206
|
+
if (removing) delete providers[provider];
|
|
207
|
+
else providers[provider] = next;
|
|
208
|
+
doc.providers = providers;
|
|
209
|
+
|
|
210
|
+
// tmp beside the REAL path (a symlinked models.json is replaced at its target).
|
|
211
|
+
tmp = `${real}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
212
|
+
const mode = existsSync(real) ? statSync(real).mode & 0o777 : 0o600;
|
|
213
|
+
try {
|
|
214
|
+
writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, { mode });
|
|
215
|
+
chmodSync(tmp, mode);
|
|
216
|
+
} catch {
|
|
217
|
+
return fail(500, "write_failed", "Could not write the temporary file");
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const check = await validateModelsJsonFile(tmp);
|
|
221
|
+
if (!check.ok) return fail(400, "rejected_by_pi", check.message);
|
|
222
|
+
if (!removing) {
|
|
223
|
+
const rule = checkComposerRules(provider, next, opts.isBuiltIn);
|
|
224
|
+
if (rule) return fail(400, "rejected_by_pi", rule);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Re-check under the lock: an unlocked hand edit made while pi's validator ran must win.
|
|
228
|
+
const again = readState(real);
|
|
229
|
+
if (!again.ok || again.state.text !== state.text) {
|
|
230
|
+
return fail(409, "stale_revision", "models.json changed while the write was being checked");
|
|
231
|
+
}
|
|
232
|
+
if (compromised) return fail(500, "write_failed", "models.json lock was compromised");
|
|
233
|
+
|
|
234
|
+
try {
|
|
235
|
+
renameSync(tmp, real);
|
|
236
|
+
tmp = undefined;
|
|
237
|
+
} catch {
|
|
238
|
+
return fail(500, "write_failed", "Could not replace models.json");
|
|
239
|
+
}
|
|
240
|
+
return { ok: true, block: next, revision: blockRevision(removing ? undefined : next) };
|
|
241
|
+
} catch (err) {
|
|
242
|
+
if (err instanceof ValidatorMissingError) return fail(503, "validator_missing", "pi's validator is unavailable");
|
|
243
|
+
return fail(500, "write_failed", "Could not write models.json");
|
|
244
|
+
} finally {
|
|
245
|
+
if (tmp) {
|
|
246
|
+
try {
|
|
247
|
+
unlinkSync(tmp);
|
|
248
|
+
} catch {
|
|
249
|
+
/* already gone */
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
await release();
|
|
254
|
+
} catch {
|
|
255
|
+
/* ignore cleanup errors */
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const FILE_MESSAGES: Record<FileRefusalCode, string> = {
|
|
261
|
+
unreadable: "models.json cannot be parsed",
|
|
262
|
+
has_comments: "models.json holds // comments; a rewrite would drop them. Edit the file by hand.",
|
|
263
|
+
legacy_shape: "models.json has no providers object",
|
|
264
|
+
invalid_before: "models.json already fails pi's check",
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
function fail(status: number, code: string, error: string): { ok: false; refusal: BlockRefusal } {
|
|
268
|
+
return { ok: false, refusal: refusal(status, code, error) };
|
|
269
|
+
}
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* See change: fix-ws-origin-cswsh.
|
|
14
14
|
*/
|
|
15
15
|
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
16
|
+
import { redactCapability } from "../live-server/capability-redact.js";
|
|
16
17
|
import {
|
|
17
18
|
type CorsOriginOptions,
|
|
18
19
|
isMutationOriginTrusted,
|
|
@@ -47,8 +48,10 @@ export function createMutationOriginGate(getOpts: () => CorsOriginOptions) {
|
|
|
47
48
|
if (isMutationOriginTrusted(req.headers.origin, req.headers.host, getOpts())) return done();
|
|
48
49
|
|
|
49
50
|
console.error(
|
|
50
|
-
|
|
51
|
-
`
|
|
51
|
+
redactCapability(
|
|
52
|
+
`[csrf-gate] rejected ${sanitizeHeaderForLog(req.method)} ${sanitizeHeaderForLog(req.url)} ` +
|
|
53
|
+
`origin=${sanitizeHeaderForLog(req.headers.origin)}`,
|
|
54
|
+
),
|
|
52
55
|
);
|
|
53
56
|
reply.code(403).send({ error: "untrusted origin" });
|
|
54
57
|
};
|