@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,263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracked-file index behind fuzzy mention recovery (design D5 of rich-chat-links).
|
|
3
|
+
*
|
|
4
|
+
* One index per git root (`git rev-parse --show-toplevel`), built from `git ls-files -z` — TRACKED
|
|
5
|
+
* files only, so ignored / generated paths and secrets never become candidates. The build is bounded
|
|
6
|
+
* on every axis, because a batch of 200 mentions may trigger it:
|
|
7
|
+
* - `execFile` with a 3 s timeout (plus our own timer, so a stub that never answers cannot hang us)
|
|
8
|
+
* and a 64 MiB output buffer;
|
|
9
|
+
* - at most 200,000 entries (above the cap the root is skipped and logged);
|
|
10
|
+
* - single-flight per root, and a 60 s TTL. A SKIPPED root is remembered for the TTL too, so a
|
|
11
|
+
* failing repo costs one spawn per minute, not one per mention.
|
|
12
|
+
* Every failure degrades to `{ status: "skipped" }` with ONE log line and never throws: the exact
|
|
13
|
+
* resolution result is always still returned by the caller.
|
|
14
|
+
*
|
|
15
|
+
* This module only answers "which tracked paths match"; containment and the per-mention stat budget
|
|
16
|
+
* (25) are enforced by the resolver, which also decides on-disk existence.
|
|
17
|
+
*
|
|
18
|
+
* See change: rich-chat-links (D5).
|
|
19
|
+
*/
|
|
20
|
+
import fs from "node:fs/promises";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
23
|
+
|
|
24
|
+
export const MAX_ENTRIES = 200_000;
|
|
25
|
+
export const MAX_BUFFER_BYTES = 64 * 1024 * 1024;
|
|
26
|
+
export const GIT_TIMEOUT_MS = 3000;
|
|
27
|
+
export const TTL_MS = 60_000;
|
|
28
|
+
/** Roots (and root lookups) kept per cache; least recently used is evicted beyond this. */
|
|
29
|
+
export const MAX_CACHED_ROOTS = 16;
|
|
30
|
+
/**
|
|
31
|
+
* `git` runs inside a repo we do not trust, and a repo's own config can name a program to run
|
|
32
|
+
* (`core.fsmonitor`). Command-line `-c` outranks every config file, so these always win; the
|
|
33
|
+
* untracked cache is off because it is only used by status-style scans we never need.
|
|
34
|
+
*/
|
|
35
|
+
const GIT_HARDENING_ARGS = ["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false"] as const;
|
|
36
|
+
/** Matches handed to the resolver per lookup (its per-mention stat budget). */
|
|
37
|
+
export const MAX_MATCHES = 25;
|
|
38
|
+
|
|
39
|
+
export type ExecFileLike = (
|
|
40
|
+
file: string,
|
|
41
|
+
args: readonly string[],
|
|
42
|
+
opts: { cwd: string; timeout: number; maxBuffer: number; env?: NodeJS.ProcessEnv },
|
|
43
|
+
) => Promise<{ stdout: string }>;
|
|
44
|
+
|
|
45
|
+
type SkipReason =
|
|
46
|
+
| "not-eligible"
|
|
47
|
+
| "not-a-repo"
|
|
48
|
+
| "rev-parse-failed"
|
|
49
|
+
| "ls-files-failed"
|
|
50
|
+
| "too-large"
|
|
51
|
+
| "buffer"
|
|
52
|
+
| "timeout";
|
|
53
|
+
|
|
54
|
+
type FuzzyLookup =
|
|
55
|
+
| { status: "skipped"; reason: SkipReason }
|
|
56
|
+
| {
|
|
57
|
+
status: "ok";
|
|
58
|
+
root: string;
|
|
59
|
+
/** Number of tracked files matching the mention (may exceed `matches.length`). */
|
|
60
|
+
total: number;
|
|
61
|
+
/** Absolute paths of the first {@link MAX_MATCHES} matches, in `git ls-files` order. */
|
|
62
|
+
matches: string[];
|
|
63
|
+
/** True when the root index was served from cache rather than built for this call. */
|
|
64
|
+
cached: boolean;
|
|
65
|
+
/** Build time of the root index in ms (only when built by/for this call). */
|
|
66
|
+
buildMs?: number;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export interface MentionFuzzyIndex {
|
|
70
|
+
lookup(cwd: string, mention: string): Promise<FuzzyLookup>;
|
|
71
|
+
/** Drop every cached index and root lookup (tests, cold-path measurement). */
|
|
72
|
+
clear(): void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface MentionFuzzyIndexDeps {
|
|
76
|
+
execFile?: ExecFileLike;
|
|
77
|
+
now?: () => number;
|
|
78
|
+
log?: (line: string) => void;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const defaultExecFile: ExecFileLike = async (file, args, opts) => {
|
|
82
|
+
const { stdout } = await execFileAsync(file, args, { ...opts, encoding: "utf8" });
|
|
83
|
+
return { stdout: String(stdout) };
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
type Timed<T> = { at: number; value: T };
|
|
87
|
+
type RootResult = { root: string } | { skip: SkipReason };
|
|
88
|
+
type BuildResult = { skip: SkipReason } | { byBase: Map<string, string[]>; buildMs: number };
|
|
89
|
+
|
|
90
|
+
function reasonOf(err: unknown, otherwise: SkipReason): SkipReason {
|
|
91
|
+
const e = err as { code?: unknown; killed?: unknown; message?: unknown } | null;
|
|
92
|
+
if (e?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" || /maxBuffer/i.test(String(e?.message ?? ""))) return "buffer";
|
|
93
|
+
if (e?.killed === true) return "timeout";
|
|
94
|
+
return otherwise;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Normalise a mention to a root-relative suffix, or `undefined` when fuzzy must not run for it. */
|
|
98
|
+
function eligibleSuffix(mention: string): string | undefined {
|
|
99
|
+
if (mention.startsWith("/") || mention.startsWith("~") || mention.includes("\\") || mention.includes("\0")) {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
const trimmed = mention.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "");
|
|
103
|
+
if (trimmed === "" || trimmed.split("/").some((seg) => seg === ".." || seg === "" || seg === ".")) return undefined;
|
|
104
|
+
return trimmed;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function createMentionFuzzyIndex(deps: MentionFuzzyIndexDeps = {}): MentionFuzzyIndex {
|
|
108
|
+
const exec = deps.execFile ?? defaultExecFile;
|
|
109
|
+
const now = deps.now ?? Date.now;
|
|
110
|
+
const log = deps.log ?? ((line: string) => console.warn(line));
|
|
111
|
+
|
|
112
|
+
const roots = new Map<string, Timed<RootResult>>();
|
|
113
|
+
const rootsInflight = new Map<string, Promise<RootResult>>();
|
|
114
|
+
const indexes = new Map<string, Timed<BuildResult>>();
|
|
115
|
+
const indexesInflight = new Map<string, Promise<BuildResult>>();
|
|
116
|
+
|
|
117
|
+
const fresh = <T>(entry: Timed<T> | undefined): entry is Timed<T> => entry !== undefined && now() - entry.at < TTL_MS;
|
|
118
|
+
|
|
119
|
+
/** `git` with our own deadline on top of execFile's, so an unresponsive stub or process cannot hang a request. */
|
|
120
|
+
async function git(args: readonly string[], cwd: string): Promise<string> {
|
|
121
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
122
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
123
|
+
timer = setTimeout(() => reject(Object.assign(new Error("git timed out"), { killed: true })), GIT_TIMEOUT_MS);
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
const { stdout } = await Promise.race([exec("git", [...GIT_HARDENING_ARGS, ...args], {
|
|
127
|
+
cwd,
|
|
128
|
+
timeout: GIT_TIMEOUT_MS,
|
|
129
|
+
maxBuffer: MAX_BUFFER_BYTES,
|
|
130
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
|
|
131
|
+
}), deadline]);
|
|
132
|
+
return stdout;
|
|
133
|
+
} finally {
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Is there a `.git` entry (dir or worktree/submodule file) on the way up? `lstat`, so no stat budget is spent. */
|
|
139
|
+
async function looksLikeRepo(cwd: string): Promise<boolean> {
|
|
140
|
+
for (let dir = path.resolve(cwd); ; ) {
|
|
141
|
+
try {
|
|
142
|
+
await fs.lstat(path.join(dir, ".git"));
|
|
143
|
+
return true;
|
|
144
|
+
} catch {
|
|
145
|
+
// keep walking
|
|
146
|
+
}
|
|
147
|
+
const parent = path.dirname(dir);
|
|
148
|
+
if (parent === dir) return false;
|
|
149
|
+
dir = parent;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function findRoot(cwd: string): Promise<RootResult> {
|
|
154
|
+
if (!(await looksLikeRepo(cwd))) return { skip: "not-a-repo" };
|
|
155
|
+
try {
|
|
156
|
+
const top = (await git(["rev-parse", "--show-toplevel"], cwd)).trim();
|
|
157
|
+
if (!top) throw new Error("empty toplevel");
|
|
158
|
+
return { root: top };
|
|
159
|
+
} catch (err) {
|
|
160
|
+
const skip = reasonOf(err, "rev-parse-failed");
|
|
161
|
+
log(`[mention-fuzzy-index] skipped: git rev-parse failed (${skip})`);
|
|
162
|
+
return { skip };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function build(root: string): Promise<BuildResult> {
|
|
167
|
+
const t0 = now();
|
|
168
|
+
let out: string;
|
|
169
|
+
try {
|
|
170
|
+
out = await git(["ls-files", "-z"], root);
|
|
171
|
+
} catch (err) {
|
|
172
|
+
const skip = reasonOf(err, "ls-files-failed");
|
|
173
|
+
log(`[mention-fuzzy-index] skipped: git ls-files failed (${skip})`);
|
|
174
|
+
return { skip };
|
|
175
|
+
}
|
|
176
|
+
if (out.length > MAX_BUFFER_BYTES) {
|
|
177
|
+
log(`[mention-fuzzy-index] skipped: git ls-files output exceeds ${MAX_BUFFER_BYTES} bytes`);
|
|
178
|
+
return { skip: "buffer" };
|
|
179
|
+
}
|
|
180
|
+
const files = out.split("\0");
|
|
181
|
+
if (files[files.length - 1] === "") files.pop();
|
|
182
|
+
if (files.length > MAX_ENTRIES) {
|
|
183
|
+
log(`[mention-fuzzy-index] skipped: ${files.length} tracked files exceed the ${MAX_ENTRIES} entry cap`);
|
|
184
|
+
return { skip: "too-large" };
|
|
185
|
+
}
|
|
186
|
+
const byBase = new Map<string, string[]>();
|
|
187
|
+
for (const rel of files) {
|
|
188
|
+
const base = rel.slice(rel.lastIndexOf("/") + 1);
|
|
189
|
+
const list = byBase.get(base);
|
|
190
|
+
if (list) list.push(rel);
|
|
191
|
+
else byBase.set(base, [rel]);
|
|
192
|
+
}
|
|
193
|
+
return { byBase, buildMs: now() - t0 };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Cache + single-flight around a keyed async producer. */
|
|
197
|
+
function singleFlight<T>(
|
|
198
|
+
key: string,
|
|
199
|
+
cache: Map<string, Timed<T>>,
|
|
200
|
+
inflight: Map<string, Promise<T>>,
|
|
201
|
+
produce: () => Promise<T>,
|
|
202
|
+
): { cached: T } | { pending: Promise<T> } {
|
|
203
|
+
const hit = cache.get(key);
|
|
204
|
+
if (fresh(hit)) {
|
|
205
|
+
cache.delete(key); // most recently used goes last
|
|
206
|
+
cache.set(key, hit);
|
|
207
|
+
return { cached: hit.value };
|
|
208
|
+
}
|
|
209
|
+
if (hit) cache.delete(key); // expired
|
|
210
|
+
let pending = inflight.get(key);
|
|
211
|
+
if (!pending) {
|
|
212
|
+
pending = produce()
|
|
213
|
+
.then((value) => {
|
|
214
|
+
cache.delete(key);
|
|
215
|
+
cache.set(key, { at: now(), value });
|
|
216
|
+
if (cache.size > MAX_CACHED_ROOTS) cache.delete(cache.keys().next().value as string);
|
|
217
|
+
return value;
|
|
218
|
+
})
|
|
219
|
+
.finally(() => inflight.delete(key));
|
|
220
|
+
inflight.set(key, pending);
|
|
221
|
+
}
|
|
222
|
+
return { pending };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return {
|
|
226
|
+
async lookup(cwd, mention) {
|
|
227
|
+
const suffix = eligibleSuffix(mention);
|
|
228
|
+
if (suffix === undefined) return { status: "skipped", reason: "not-eligible" };
|
|
229
|
+
|
|
230
|
+
const rootHit = singleFlight(cwd, roots, rootsInflight, () => findRoot(cwd));
|
|
231
|
+
const rootRes = "cached" in rootHit ? rootHit.cached : await rootHit.pending;
|
|
232
|
+
if ("skip" in rootRes) return { status: "skipped", reason: rootRes.skip };
|
|
233
|
+
|
|
234
|
+
const idxHit = singleFlight(rootRes.root, indexes, indexesInflight, () => build(rootRes.root));
|
|
235
|
+
const cached = "cached" in idxHit;
|
|
236
|
+
const idx = cached ? idxHit.cached : await idxHit.pending;
|
|
237
|
+
if ("skip" in idx) return { status: "skipped", reason: idx.skip };
|
|
238
|
+
|
|
239
|
+
const base = suffix.slice(suffix.lastIndexOf("/") + 1);
|
|
240
|
+
let candidates = idx.byBase.get(base) ?? [];
|
|
241
|
+
if (suffix.includes("/")) candidates = candidates.filter((rel) => rel === suffix || rel.endsWith(`/${suffix}`));
|
|
242
|
+
return {
|
|
243
|
+
status: "ok",
|
|
244
|
+
root: rootRes.root,
|
|
245
|
+
total: candidates.length,
|
|
246
|
+
matches: candidates.slice(0, MAX_MATCHES).map((rel) => path.join(rootRes.root, rel)),
|
|
247
|
+
cached,
|
|
248
|
+
...(cached ? {} : { buildMs: idx.buildMs }),
|
|
249
|
+
};
|
|
250
|
+
},
|
|
251
|
+
clear() {
|
|
252
|
+
roots.clear();
|
|
253
|
+
indexes.clear();
|
|
254
|
+
},
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
let shared: MentionFuzzyIndex | undefined;
|
|
259
|
+
/** Process-wide index used by the routes unless a test injects its own. */
|
|
260
|
+
export function getMentionFuzzyIndex(): MentionFuzzyIndex {
|
|
261
|
+
shared ??= createMentionFuzzyIndex();
|
|
262
|
+
return shared;
|
|
263
|
+
}
|
|
@@ -10,13 +10,14 @@
|
|
|
10
10
|
* `{ success:false, error }` (design D5). See change: render-office-previews.
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
-
import { createHash } from "node:crypto";
|
|
13
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
14
14
|
import fs from "node:fs/promises";
|
|
15
15
|
import os from "node:os";
|
|
16
16
|
import path from "node:path";
|
|
17
17
|
import { OFFICE_SIZE_CAPS } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
|
|
18
18
|
import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
19
19
|
import { DOCX_PROFILE } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
|
|
20
|
+
import { ContainmentBindingRefused, readFileStateChecked } from "./dashboard-state-guard.js";
|
|
20
21
|
import { loadPurify } from "./purify.js";
|
|
21
22
|
|
|
22
23
|
/** Bounded-preview + size caps (design D3). Overridable per-call for tests. */
|
|
@@ -156,6 +157,38 @@ export function createDefaultDocxPdfEngine(opts?: {
|
|
|
156
157
|
};
|
|
157
158
|
}
|
|
158
159
|
|
|
160
|
+
/**
|
|
161
|
+
* `engine.toPdf(real, out)` bound to the decided real path: identity before, identity after. If the
|
|
162
|
+
* path was swapped during conversion the output is deleted (no poisoned cache entry) and the caller
|
|
163
|
+
* is refused with {@link ContainmentBindingRefused}. See change: close-local-listener-and-egress-gaps (D2).
|
|
164
|
+
*/
|
|
165
|
+
export async function convertBound(engine: DocxPdfEngine, real: string, out: string): Promise<void> {
|
|
166
|
+
const before = await fs.lstat(real);
|
|
167
|
+
// Convert to a private temp name and publish to `out` only after the binding check passes, so a
|
|
168
|
+
// discard that fails (e.g. EPERM) can never leave a poisoned file at the cache path.
|
|
169
|
+
const tmp = `${out.replace(/\.pdf$/, "")}.${randomUUID()}.tmp.pdf`;
|
|
170
|
+
const discard = () => fs.rm(tmp, { force: true }).catch(() => undefined);
|
|
171
|
+
try {
|
|
172
|
+
await engine.toPdf(real, tmp);
|
|
173
|
+
} catch (err) {
|
|
174
|
+
await discard();
|
|
175
|
+
throw err;
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
const [afterReal, after] = await Promise.all([fs.realpath(real), fs.lstat(real)]);
|
|
179
|
+
if (afterReal !== real || after.dev !== before.dev || after.ino !== before.ino) throw new ContainmentBindingRefused();
|
|
180
|
+
} catch (err) {
|
|
181
|
+
await discard();
|
|
182
|
+
throw err instanceof ContainmentBindingRefused ? err : new ContainmentBindingRefused();
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
await fs.rename(tmp, out);
|
|
186
|
+
} catch (err) {
|
|
187
|
+
await discard();
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
159
192
|
// ── docx: render (design D8) ─────────────────────────────────────────────────
|
|
160
193
|
|
|
161
194
|
export type DocxRenderResult =
|
|
@@ -181,7 +214,7 @@ export type DocxRenderMode = "pdf" | "html" | "auto";
|
|
|
181
214
|
* DOMPurify, and applies the image cap.
|
|
182
215
|
*/
|
|
183
216
|
export async function renderDocx(
|
|
184
|
-
|
|
217
|
+
real: string,
|
|
185
218
|
stat: { mtimeMs: number; size: number },
|
|
186
219
|
opts: { mode: DocxRenderMode; engine: DocxPdfEngine; caps: OfficeCaps },
|
|
187
220
|
): Promise<DocxRenderResult> {
|
|
@@ -190,22 +223,23 @@ export async function renderDocx(
|
|
|
190
223
|
if (mode !== "html") {
|
|
191
224
|
try {
|
|
192
225
|
if (await engine.available()) {
|
|
193
|
-
const out = pdfCachePath(
|
|
226
|
+
const out = pdfCachePath(real, stat.mtimeMs, stat.size);
|
|
194
227
|
await fs.mkdir(pdfCacheDir(), { recursive: true });
|
|
195
228
|
try {
|
|
196
229
|
await fs.access(out);
|
|
197
230
|
} catch {
|
|
198
|
-
await engine
|
|
231
|
+
await convertBound(engine, real, out);
|
|
199
232
|
}
|
|
200
233
|
return { success: true, mode: "pdf" };
|
|
201
234
|
}
|
|
202
|
-
} catch {
|
|
235
|
+
} catch (err) {
|
|
236
|
+
if (err instanceof ContainmentBindingRefused) throw err;
|
|
203
237
|
// fall through to html
|
|
204
238
|
}
|
|
205
239
|
}
|
|
206
240
|
|
|
207
241
|
try {
|
|
208
|
-
const buffer = await
|
|
242
|
+
const buffer = await readFileStateChecked(real, undefined, { decidedReal: real });
|
|
209
243
|
const mammoth = (await import("mammoth")).default ?? (await import("mammoth"));
|
|
210
244
|
let imageCount = 0;
|
|
211
245
|
const convertImage = mammoth.images.imgElement((img: any) =>
|
|
@@ -230,6 +264,7 @@ export async function renderDocx(
|
|
|
230
264
|
...(truncated ? { note: "Images trimmed — download for the full document." } : {}),
|
|
231
265
|
};
|
|
232
266
|
} catch (err) {
|
|
267
|
+
if (err instanceof ContainmentBindingRefused) throw err;
|
|
233
268
|
return { success: false, error: err instanceof Error ? err.message : "failed to render docx" };
|
|
234
269
|
}
|
|
235
270
|
}
|
|
@@ -247,22 +282,23 @@ export type PptxRenderResult =
|
|
|
247
282
|
* `DOCKER_UNAVAILABLE` / convert failure → `{ success:false }`. Never throws.
|
|
248
283
|
*/
|
|
249
284
|
export async function renderPptx(
|
|
250
|
-
|
|
285
|
+
real: string,
|
|
251
286
|
stat: { mtimeMs: number; size: number },
|
|
252
287
|
opts: { engine: DocxPdfEngine },
|
|
253
288
|
): Promise<PptxRenderResult> {
|
|
254
289
|
try {
|
|
255
290
|
if (await opts.engine.available()) {
|
|
256
|
-
const out = pdfCachePath(
|
|
291
|
+
const out = pdfCachePath(real, stat.mtimeMs, stat.size);
|
|
257
292
|
await fs.mkdir(pdfCacheDir(), { recursive: true });
|
|
258
293
|
try {
|
|
259
294
|
await fs.access(out);
|
|
260
295
|
} catch {
|
|
261
|
-
await opts.engine
|
|
296
|
+
await convertBound(opts.engine, real, out);
|
|
262
297
|
}
|
|
263
298
|
return { success: true, mode: "pdf" };
|
|
264
299
|
}
|
|
265
300
|
} catch (err) {
|
|
301
|
+
if (err instanceof ContainmentBindingRefused) throw err;
|
|
266
302
|
return { success: false, error: err instanceof Error ? err.message : "failed to render pptx" };
|
|
267
303
|
}
|
|
268
304
|
return { success: false, error: "presentation rendering requires the document engine" };
|
|
@@ -352,7 +388,8 @@ export async function parseSheet(
|
|
|
352
388
|
opts: { rowLimit: number; colCap: number },
|
|
353
389
|
): Promise<SheetParseResult> {
|
|
354
390
|
try {
|
|
355
|
-
|
|
391
|
+
// Vendored SheetJS 0.20.3 (patched; the registry copy is not) — see vendor/xlsx/PROVENANCE.json.
|
|
392
|
+
const XLSX = await import("../../vendor/xlsx/xlsx.mjs");
|
|
356
393
|
let encoding: string | undefined;
|
|
357
394
|
let wb: any;
|
|
358
395
|
if (ext === ".csv") {
|
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
* worktree-of-bare session can read its OWN checkout. Evaluated in two layers
|
|
9
9
|
* per anchor:
|
|
10
10
|
*
|
|
11
|
-
* ①
|
|
11
|
+
* ① anchor: resolved under `anchor` lexically AND its real path under the anchor's real
|
|
12
|
+
* path (one `realpath`, no git spawn — the hot path). A link inside the anchor that
|
|
13
|
+
* escapes it misses here and falls to ②/grants. See change: close-local-listener-and-egress-gaps.
|
|
12
14
|
* ② checkout roots: the anchor's `thisCheckout` / `mainCheckout` from the
|
|
13
15
|
* shared resolver, each kept only when BOUND to the anchor's repository,
|
|
14
16
|
* deduplicated, and compared on real paths (`fs.realpath`). git is spawned
|
|
@@ -132,16 +134,30 @@ export async function isGrantAdmitted(
|
|
|
132
134
|
resolved: string,
|
|
133
135
|
subjects: readonly string[],
|
|
134
136
|
): Promise<boolean> {
|
|
135
|
-
|
|
137
|
+
return (await isGrantAdmittedReal(resolved, subjects)) !== null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** As {@link isGrantAdmitted} but returns the decided real path (or `null`), so the caller can bind the open to it. */
|
|
141
|
+
export async function isGrantAdmittedReal(
|
|
142
|
+
resolved: string,
|
|
143
|
+
subjects: readonly string[],
|
|
144
|
+
opts: { allowMissing?: boolean } = {},
|
|
145
|
+
): Promise<string | null> {
|
|
146
|
+
if (subjects.length === 0) return null;
|
|
136
147
|
// Dashboard secrets are never granted away. See change: close-container-loopback-impersonation (D8).
|
|
137
|
-
if (await dashboardStateRefuses(resolved)) return
|
|
148
|
+
if (await dashboardStateRefuses(resolved)) return null;
|
|
138
149
|
let real: string;
|
|
139
150
|
try {
|
|
140
151
|
real = await fs.realpath(resolved);
|
|
141
152
|
} catch {
|
|
142
|
-
|
|
153
|
+
// Reads refuse a path that does not resolve. A WRITE gate (`allowMissing`) resolves the nearest
|
|
154
|
+
// existing ancestor instead, so the gate answers before any stat and the route's own 404 follows:
|
|
155
|
+
// a write never creates a file, and a symlinked ancestor still collapses to its real prefix.
|
|
156
|
+
// See change: fix-file-link-editor-routing (D2).
|
|
157
|
+
if (!opts.allowMissing) return null;
|
|
158
|
+
real = await safeRealpath(resolved);
|
|
143
159
|
}
|
|
144
|
-
return subjects.some((subject) => within(real, subject));
|
|
160
|
+
return subjects.some((subject) => within(real, subject)) ? real : null;
|
|
145
161
|
}
|
|
146
162
|
|
|
147
163
|
/**
|
|
@@ -151,23 +167,40 @@ export async function isGrantAdmitted(
|
|
|
151
167
|
*/
|
|
152
168
|
export async function isAllowed(
|
|
153
169
|
resolved: string,
|
|
154
|
-
|
|
170
|
+
opts: { anchors: string[] },
|
|
155
171
|
): Promise<boolean> {
|
|
172
|
+
return (await isAllowedReal(resolved, opts)).allowed;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* {@link isAllowed} plus the decided real path (`safeRealpath(resolved)`, computed once). Layer ①
|
|
177
|
+
* requires the REAL path to sit under the anchor's real path as well, so an in-cwd symlink to an
|
|
178
|
+
* outside file is no longer admitted lexically. See change: close-local-listener-and-egress-gaps (D1).
|
|
179
|
+
*
|
|
180
|
+
* `skipCheckoutRoots` disables layer ② (the bound-checkout widening). A WRITE gate passes it: being in a
|
|
181
|
+
* worktree or a repo subdirectory must never authorise a write outside the cwd. Default keeps today's
|
|
182
|
+
* widening. See change: fix-file-link-editor-routing (D2).
|
|
183
|
+
*/
|
|
184
|
+
export async function isAllowedReal(
|
|
185
|
+
resolved: string,
|
|
186
|
+
{ anchors, skipCheckoutRoots }: { anchors: string[]; skipCheckoutRoots?: boolean },
|
|
187
|
+
): Promise<{ allowed: boolean; real: string }> {
|
|
156
188
|
// The dashboard state dir (token, identity key, config) is outside every anchor, whatever the
|
|
157
189
|
// anchor: a `$HOME` cwd or the `~/.pi` anchor would otherwise contain it. Decided on REAL paths.
|
|
158
190
|
// See change: close-container-loopback-impersonation (D8).
|
|
159
|
-
if (await dashboardStateRefuses(resolved)) return false;
|
|
160
|
-
|
|
191
|
+
if (await dashboardStateRefuses(resolved)) return { allowed: false, real: resolved };
|
|
192
|
+
const real = await safeRealpath(resolved);
|
|
193
|
+
// Layer ① — anchor, lexical AND real. One realpath per anchor, no spawn.
|
|
161
194
|
for (const anchor of anchors) {
|
|
162
|
-
if (within(resolved, anchor)) return true;
|
|
195
|
+
if (within(resolved, anchor) && within(real, await safeRealpath(anchor))) return { allowed: true, real };
|
|
163
196
|
}
|
|
164
197
|
// Layer ② — bound checkout roots, real-path'd (symlink-safe). Cold path.
|
|
165
|
-
|
|
198
|
+
if (skipCheckoutRoots) return { allowed: false, real };
|
|
166
199
|
for (const anchor of anchors) {
|
|
167
200
|
for (const root of await checkoutAnchors(anchor)) {
|
|
168
201
|
if (samePath(root, anchor)) continue; // no widening: that subtree is layer ①
|
|
169
|
-
if (within(
|
|
202
|
+
if (within(real, await safeRealpath(root))) return { allowed: true, real };
|
|
170
203
|
}
|
|
171
204
|
}
|
|
172
|
-
return false;
|
|
205
|
+
return { allowed: false, real };
|
|
173
206
|
}
|