@chroxy/server 0.11.0 → 0.11.11
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/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,1572 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-folder trust for project settings.
|
|
3
|
+
*
|
|
4
|
+
* Project settings (`.mcp.json`, `.claude/settings.json`, project `CLAUDE.md`,
|
|
5
|
+
* skills, agents, commands) load ONLY after an explicit owner trust decision for
|
|
6
|
+
* the folder. Every folder starts untrusted, including one with no command-bearing
|
|
7
|
+
* files (trusting it loads its CLAUDE.md and other project settings).
|
|
8
|
+
*
|
|
9
|
+
* Trusting a folder trusts that repository: while trusted, Claude Code loads the
|
|
10
|
+
* folder's project settings and picks up changes made to them during the session.
|
|
11
|
+
* chroxy re-checks the files listed below at each launch and when the status line
|
|
12
|
+
* runs, and asks again when they change. The digest is a change detector, not a
|
|
13
|
+
* containment boundary.
|
|
14
|
+
*
|
|
15
|
+
* Files considered (absolute paths, hashed by full content):
|
|
16
|
+
* - `.mcp.json` and `.claude/settings.json` in the folder's real path and in every
|
|
17
|
+
* ancestor directory up to the filesystem root.
|
|
18
|
+
* - `.claude/skills`, `.claude/agents` and `.claude/commands` in the folder and in
|
|
19
|
+
* every ancestor (recursively, following symlinks with cycle detection).
|
|
20
|
+
* - the same three directories in every nested `.claude` below the folder, found
|
|
21
|
+
* by a bounded walk (symlinked directories followed, cycles refused) that skips
|
|
22
|
+
* `.git` and `node_modules`.
|
|
23
|
+
* - in a linked git worktree, the main checkout's `.claude/skills`.
|
|
24
|
+
* - the user's own Claude config directory is skipped wherever it appears, and
|
|
25
|
+
* `.claude/settings.local.json` is never considered.
|
|
26
|
+
*
|
|
27
|
+
* Incompleteness is always HARD and fails closed: any error other than "absent",
|
|
28
|
+
* a non-regular file, a dangling or circular link, a file over the per-file limit,
|
|
29
|
+
* or any budget exceeded (bytes, files, directories, entries, depth; a display scan
|
|
30
|
+
* has a wall-clock budget for the nested search, and so does every scan run in this
|
|
31
|
+
* thread (the status line's, trust and untrust's), which an over-budget walk leaves
|
|
32
|
+
* incomplete. Only a launch scan in the worker has none: its walk is bounded by entries
|
|
33
|
+
* and depth, and the worker's overall timeout can still end it, which fails closed). The folder is untrusted and cannot be
|
|
34
|
+
* trusted. What is NOT covered by the digest: files that settings merely refer to
|
|
35
|
+
* (hook scripts, for example), `CLAUDE.md` and rules. Trusting a folder trusts its code.
|
|
36
|
+
*
|
|
37
|
+
* Each file is read ONCE, with `O_NONBLOCK` and an `fstat` that rejects anything
|
|
38
|
+
* that is not a regular file; the digest and the summary come from the same bytes.
|
|
39
|
+
* Nothing here throws.
|
|
40
|
+
*
|
|
41
|
+
* The store lock's guarantees and their limit are described above `LOCK_LEASE_MS`.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
import {
|
|
45
|
+
closeSync, constants as fsConstants, existsSync, fstatSync, futimesSync, linkSync, lstatSync, mkdirSync, openSync, opendirSync,
|
|
46
|
+
readdirSync, readFileSync, readlinkSync, readSync, realpathSync, statSync, unlinkSync, writeFileSync, writeSync,
|
|
47
|
+
} from 'node:fs'
|
|
48
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
49
|
+
import { hostname } from 'node:os'
|
|
50
|
+
import { basename, dirname, join, resolve, sep } from 'node:path'
|
|
51
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
52
|
+
import { Worker, SHARE_ENV } from 'node:worker_threads'
|
|
53
|
+
import { configPath } from './config-dir.js'
|
|
54
|
+
import { claudeConfigDir } from './utils/claude-config-dir.js'
|
|
55
|
+
import { canonicalJson, sha256Hex, withTrustStoreLock, writeFileAtomic0600 } from './byok-mcp-trust.js'
|
|
56
|
+
import { redactMcpUrl } from './byok-mcp-config.js'
|
|
57
|
+
import { createLogger } from './logger.js'
|
|
58
|
+
|
|
59
|
+
const log = createLogger('folder-trust')
|
|
60
|
+
/** On-disk record version. Other versions are dropped at load. */
|
|
61
|
+
export const FOLDER_TRUST_RECORD_VERSION = 2
|
|
62
|
+
|
|
63
|
+
/** Most files hashed in content directories before the scan is HARD-incomplete. */
|
|
64
|
+
export const MAX_SCANNED_FILES = 2000
|
|
65
|
+
/** Largest single file; a larger one is HARD. */
|
|
66
|
+
export const MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
67
|
+
/** Total bytes read across one scan; more is HARD. */
|
|
68
|
+
export const MAX_TOTAL_BYTES = 32 * 1024 * 1024
|
|
69
|
+
/** Deepest directory level inside a content directory (HARD beyond). */
|
|
70
|
+
export const MAX_DEPTH = 16
|
|
71
|
+
/** Directories and entries read by all content traversals of one scan (HARD beyond). */
|
|
72
|
+
export const MAX_CONTENT_DIRS = 2000
|
|
73
|
+
export const MAX_CONTENT_ENTRIES = 20_000
|
|
74
|
+
/** Directories visited by the nested `.claude` search (HARD beyond). */
|
|
75
|
+
export const MAX_NESTED_DIRS = 20_000
|
|
76
|
+
/** Directory entries read by the nested search (HARD beyond). */
|
|
77
|
+
export const MAX_NESTED_ENTRIES = 200_000
|
|
78
|
+
/** Deepest level of the nested search (HARD beyond). */
|
|
79
|
+
export const MAX_NESTED_DEPTH = 32
|
|
80
|
+
/** Wall-clock budget of the nested search in every scan run in the daemon's own thread, and in display scans (HARD beyond). Worker launch scans have none. */
|
|
81
|
+
export const NESTED_BUDGET_MS = 1500
|
|
82
|
+
/** Limits of a display scan or an in-thread scan: the entry and depth bounds plus the wall-clock budget. */
|
|
83
|
+
const DISPLAY_LIMITS = Object.freeze({ nestedBudgetMs: NESTED_BUDGET_MS })
|
|
84
|
+
/** Largest config file parsed for the summary; a larger one is still hashed. */
|
|
85
|
+
export const MAX_PARSE_BYTES = 256 * 1024
|
|
86
|
+
/** Cache lifetime of a scan, for display and for the status line's folder-level check. */
|
|
87
|
+
export const SCAN_CACHE_TTL_MS = 2000
|
|
88
|
+
|
|
89
|
+
const CONTENT_DIRS = ['agents', 'skills', 'commands']
|
|
90
|
+
const MAX_SUMMARY_ITEMS = 50
|
|
91
|
+
const MAX_SUMMARY_STRING = 500
|
|
92
|
+
const SKIP_NESTED = new Set(['.git', 'node_modules'])
|
|
93
|
+
const O_READ = fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0)
|
|
94
|
+
|
|
95
|
+
export function folderTrustStorePath() {
|
|
96
|
+
return configPath('folder-trust.json')
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const isAbsentCode = (err) => err?.code === 'ENOENT' || err?.code === 'ENOTDIR'
|
|
100
|
+
const byPath = (a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Real path of `p`. Only ENOENT falls back to the raw (resolved) path; any other
|
|
104
|
+
* error is reported as `error` so the caller can refuse instead of guessing.
|
|
105
|
+
* @returns {{ path: string, error?: string }}
|
|
106
|
+
*/
|
|
107
|
+
export function resolveRealPath(p) {
|
|
108
|
+
try {
|
|
109
|
+
return { path: realpathSync.native(p) }
|
|
110
|
+
} catch (err) {
|
|
111
|
+
if (err?.code === 'ENOENT') return { path: resolve(p) }
|
|
112
|
+
return { path: resolve(p), error: err?.code || 'error' }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Mutable state of one scan. */
|
|
117
|
+
function newScan(limits = {}) {
|
|
118
|
+
return {
|
|
119
|
+
limits: {
|
|
120
|
+
maxFileBytes: limits.maxFileBytes ?? MAX_FILE_BYTES,
|
|
121
|
+
maxTotalBytes: limits.maxTotalBytes ?? MAX_TOTAL_BYTES,
|
|
122
|
+
maxFiles: limits.maxFiles ?? MAX_SCANNED_FILES,
|
|
123
|
+
nestedBudgetMs: limits.nestedBudgetMs ?? Infinity,
|
|
124
|
+
},
|
|
125
|
+
// Directory-enumeration budgets: every directory and entry is counted as it is read.
|
|
126
|
+
content: { dirs: 0, entries: 0, maxDirs: limits.maxContentDirs ?? MAX_CONTENT_DIRS, maxEntries: limits.maxContentEntries ?? MAX_CONTENT_ENTRIES },
|
|
127
|
+
nested: { dirs: 0, entries: 0, maxDirs: limits.maxNestedDirs ?? MAX_NESTED_DIRS, maxEntries: limits.maxNestedEntries ?? MAX_NESTED_ENTRIES },
|
|
128
|
+
bytes: 0,
|
|
129
|
+
files: 0,
|
|
130
|
+
hard: [],
|
|
131
|
+
entries: [],
|
|
132
|
+
config: [],
|
|
133
|
+
counts: { agents: 0, skills: 0, commands: 0 },
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const hard = (scan, path, why) => { scan.hard.push(`${path}: ${why}`) }
|
|
138
|
+
/** A whole-scan refusal whose text stands alone. */
|
|
139
|
+
const hardNote = (scan, text) => { scan.hard.push(text) }
|
|
140
|
+
|
|
141
|
+
/** Real path inside a scan: any error but ENOENT is HARD. */
|
|
142
|
+
function realOf(p, scan) {
|
|
143
|
+
const r = resolveRealPath(p)
|
|
144
|
+
if (r.error) hard(scan, p, r.error)
|
|
145
|
+
return r.path
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* List one directory incrementally (`opendir`), counting each entry as it is read
|
|
150
|
+
* and stopping at the budget BEFORE anything more is allocated.
|
|
151
|
+
* @returns {{ absent: true } | { hard: string } | { entries: import('node:fs').Dirent[] }}
|
|
152
|
+
*/
|
|
153
|
+
function listDir(path, counter, deadline) {
|
|
154
|
+
let dir
|
|
155
|
+
try {
|
|
156
|
+
dir = opendirSync(path)
|
|
157
|
+
} catch (err) {
|
|
158
|
+
return isAbsentCode(err) ? { absent: true } : { hard: err?.code || 'unreadable' }
|
|
159
|
+
}
|
|
160
|
+
const out = []
|
|
161
|
+
try {
|
|
162
|
+
counter.dirs += 1
|
|
163
|
+
if (counter.dirs > counter.maxDirs) return { hard: `This folder is too large to review (more than ${counter.maxDirs} directories)` }
|
|
164
|
+
for (;;) {
|
|
165
|
+
const d = dir.readSync()
|
|
166
|
+
if (!d) break
|
|
167
|
+
counter.entries += 1
|
|
168
|
+
if (counter.entries > counter.maxEntries) return { hard: `This folder is too large to review (more than ${counter.maxEntries} entries)` }
|
|
169
|
+
if (deadline !== undefined && (counter.entries & 255) === 0 && Date.now() > deadline) {
|
|
170
|
+
return { hard: 'This folder is too large to review (the search took too long)' }
|
|
171
|
+
}
|
|
172
|
+
out.push(d)
|
|
173
|
+
}
|
|
174
|
+
} catch (err) {
|
|
175
|
+
return { hard: err?.code || 'unreadable' }
|
|
176
|
+
} finally {
|
|
177
|
+
try { dir.closeSync() } catch { /* nothing to do */ }
|
|
178
|
+
}
|
|
179
|
+
out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
|
|
180
|
+
return { entries: out }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Record a listDir refusal: budget notes stand alone, errors carry the path. */
|
|
184
|
+
function listingHard(scan, path, listing) {
|
|
185
|
+
if (listing.hard.startsWith('This folder is too large')) hardNote(scan, listing.hard)
|
|
186
|
+
else hard(scan, path, listing.hard)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Read one file, once. Returns null when absent, `{ hard: true }` when it could not
|
|
191
|
+
* be read faithfully (already recorded), else `{ buf, linkTarget }`. A symlink is
|
|
192
|
+
* followed: the bytes are the target's.
|
|
193
|
+
*/
|
|
194
|
+
function readRegular(path, scan) {
|
|
195
|
+
let lst
|
|
196
|
+
try {
|
|
197
|
+
lst = lstatSync(path)
|
|
198
|
+
} catch (err) {
|
|
199
|
+
if (isAbsentCode(err)) return null
|
|
200
|
+
hard(scan, path, err?.code || 'unreadable')
|
|
201
|
+
return { hard: true }
|
|
202
|
+
}
|
|
203
|
+
let linkTarget
|
|
204
|
+
if (lst.isSymbolicLink()) {
|
|
205
|
+
try { linkTarget = realpathSync.native(path) } catch { linkTarget = undefined }
|
|
206
|
+
}
|
|
207
|
+
let fd
|
|
208
|
+
try {
|
|
209
|
+
fd = openSync(path, O_READ)
|
|
210
|
+
} catch (err) {
|
|
211
|
+
// The path exists (lstat saw it), so ENOENT here is a dangling link.
|
|
212
|
+
hard(scan, path, err?.code === 'ENOENT' ? 'dangling symlink' : (err?.code || 'unreadable'))
|
|
213
|
+
return { hard: true }
|
|
214
|
+
}
|
|
215
|
+
try {
|
|
216
|
+
const st = fstatSync(fd)
|
|
217
|
+
if (!st.isFile()) {
|
|
218
|
+
hard(scan, path, 'not a regular file')
|
|
219
|
+
return { hard: true }
|
|
220
|
+
}
|
|
221
|
+
if (st.size > scan.limits.maxFileBytes) {
|
|
222
|
+
hard(scan, path, 'file too large to review')
|
|
223
|
+
return { hard: true }
|
|
224
|
+
}
|
|
225
|
+
if (scan.bytes + st.size > scan.limits.maxTotalBytes) {
|
|
226
|
+
hard(scan, path, 'too many bytes to review')
|
|
227
|
+
return { hard: true }
|
|
228
|
+
}
|
|
229
|
+
const buf = Buffer.allocUnsafe(Math.min(st.size, scan.limits.maxFileBytes) + 1)
|
|
230
|
+
let n = 0
|
|
231
|
+
for (;;) {
|
|
232
|
+
const got = readSync(fd, buf, n, buf.length - n, null)
|
|
233
|
+
if (got === 0) break
|
|
234
|
+
n += got
|
|
235
|
+
if (n >= buf.length) break
|
|
236
|
+
}
|
|
237
|
+
if (n > scan.limits.maxFileBytes || n > st.size) {
|
|
238
|
+
hard(scan, path, 'file changed while it was read')
|
|
239
|
+
return { hard: true }
|
|
240
|
+
}
|
|
241
|
+
scan.bytes += n
|
|
242
|
+
return { buf: buf.subarray(0, n), linkTarget }
|
|
243
|
+
} catch (err) {
|
|
244
|
+
hard(scan, path, err?.code || 'unreadable')
|
|
245
|
+
return { hard: true }
|
|
246
|
+
} finally {
|
|
247
|
+
try { closeSync(fd) } catch { /* nothing to do */ }
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const sha256Buf = (buf) => createHash('sha256').update(buf).digest('hex')
|
|
252
|
+
|
|
253
|
+
/** A settings-style file (`.mcp.json`, `settings.json`). */
|
|
254
|
+
function addConfigFile(path, kind, scan) {
|
|
255
|
+
const r = readRegular(path, scan)
|
|
256
|
+
if (!r || r.hard) return
|
|
257
|
+
scan.entries.push({ path, sha256: sha256Buf(r.buf), ...(r.linkTarget ? { linkTarget: r.linkTarget } : {}) })
|
|
258
|
+
scan.config.push({ path, kind, buf: r.buf })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Every file under one content directory. */
|
|
262
|
+
function walkContent(dir, sub, scan, stack, visited, depth) {
|
|
263
|
+
const listing = listDir(dir, scan.content)
|
|
264
|
+
if (listing.absent) return
|
|
265
|
+
if (listing.hard) {
|
|
266
|
+
listingHard(scan, dir, listing)
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
for (const dirent of listing.entries) {
|
|
270
|
+
const full = join(dir, dirent.name)
|
|
271
|
+
let lst
|
|
272
|
+
try {
|
|
273
|
+
lst = lstatSync(full)
|
|
274
|
+
} catch (err) {
|
|
275
|
+
if (!isAbsentCode(err)) hard(scan, full, err?.code || 'unreadable')
|
|
276
|
+
continue
|
|
277
|
+
}
|
|
278
|
+
let isDir = lst.isDirectory()
|
|
279
|
+
let linkTarget
|
|
280
|
+
if (lst.isSymbolicLink()) {
|
|
281
|
+
let st
|
|
282
|
+
try {
|
|
283
|
+
st = statSync(full)
|
|
284
|
+
} catch (err) {
|
|
285
|
+
hard(scan, full, err?.code === 'ENOENT' ? 'dangling symlink' : (err?.code || 'unreadable'))
|
|
286
|
+
continue
|
|
287
|
+
}
|
|
288
|
+
isDir = st.isDirectory()
|
|
289
|
+
if (isDir) {
|
|
290
|
+
const real = realOf(full, scan)
|
|
291
|
+
if (stack.has(real)) {
|
|
292
|
+
hard(scan, full, 'symlink cycle')
|
|
293
|
+
continue
|
|
294
|
+
}
|
|
295
|
+
if (visited.has(real)) continue
|
|
296
|
+
linkTarget = real
|
|
297
|
+
scan.entries.push({ path: full, sha256: sha256Hex(`dirlink:${real}`), linkTarget })
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (isDir) {
|
|
301
|
+
if (depth >= MAX_DEPTH) {
|
|
302
|
+
hard(scan, full, 'directory nesting too deep')
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
const real = realOf(full, scan)
|
|
306
|
+
visited.add(real)
|
|
307
|
+
stack.add(real)
|
|
308
|
+
walkContent(full, sub, scan, stack, visited, depth + 1)
|
|
309
|
+
stack.delete(real)
|
|
310
|
+
continue
|
|
311
|
+
}
|
|
312
|
+
if (scan.files >= scan.limits.maxFiles) {
|
|
313
|
+
hard(scan, dir, 'too many files to review')
|
|
314
|
+
return
|
|
315
|
+
}
|
|
316
|
+
scan.files += 1
|
|
317
|
+
const r = readRegular(full, scan)
|
|
318
|
+
if (!r || r.hard) continue
|
|
319
|
+
scan.counts[sub] += 1
|
|
320
|
+
scan.entries.push({ path: full, sha256: sha256Buf(r.buf), ...(r.linkTarget ? { linkTarget: r.linkTarget } : {}) })
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** One content root (`.claude/skills|agents|commands`): lstat it first, so a link to nowhere is HARD, not "absent". */
|
|
325
|
+
function scanContentRoot(dir, sub, scan) {
|
|
326
|
+
let lst
|
|
327
|
+
try {
|
|
328
|
+
lst = lstatSync(dir)
|
|
329
|
+
} catch (err) {
|
|
330
|
+
if (!isAbsentCode(err)) hard(scan, dir, err?.code || 'unreadable')
|
|
331
|
+
return
|
|
332
|
+
}
|
|
333
|
+
if (lst.isSymbolicLink()) {
|
|
334
|
+
let st
|
|
335
|
+
try {
|
|
336
|
+
st = statSync(dir)
|
|
337
|
+
} catch (err) {
|
|
338
|
+
hard(scan, dir, err?.code === 'ENOENT' ? 'dangling symlink' : (err?.code || 'unreadable'))
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
if (!st.isDirectory()) return
|
|
342
|
+
} else if (!lst.isDirectory()) {
|
|
343
|
+
return
|
|
344
|
+
}
|
|
345
|
+
const real = realOf(dir, scan)
|
|
346
|
+
walkContent(dir, sub, scan, new Set([real]), new Set([real]), 0)
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function scanContentLocation(dotClaude, scan) {
|
|
350
|
+
for (const sub of CONTENT_DIRS) scanContentRoot(join(dotClaude, sub), sub, scan)
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function ancestorsOf(realPath) {
|
|
354
|
+
const dirs = []
|
|
355
|
+
let current = realPath
|
|
356
|
+
for (;;) {
|
|
357
|
+
dirs.push(current)
|
|
358
|
+
const parent = dirname(current)
|
|
359
|
+
if (parent === current) break
|
|
360
|
+
current = parent
|
|
361
|
+
}
|
|
362
|
+
return dirs
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** `<main>/.claude` when `realPath` sits in a linked git worktree, else null. */
|
|
366
|
+
function mainCheckoutDotClaude(realPath, scan) {
|
|
367
|
+
for (const dir of ancestorsOf(realPath)) {
|
|
368
|
+
const git = join(dir, '.git')
|
|
369
|
+
let lst
|
|
370
|
+
try {
|
|
371
|
+
lst = lstatSync(git)
|
|
372
|
+
} catch (err) {
|
|
373
|
+
if (!isAbsentCode(err)) hard(scan, git, err?.code || 'unreadable')
|
|
374
|
+
continue
|
|
375
|
+
}
|
|
376
|
+
if (lst.isDirectory()) return null // the folder's own repository, not a linked worktree
|
|
377
|
+
const r = readRegular(git, scan)
|
|
378
|
+
if (!r || r.hard) return null
|
|
379
|
+
const m = /^gitdir:\s*(.+?)\s*$/m.exec(r.buf.toString('utf8'))
|
|
380
|
+
if (!m) {
|
|
381
|
+
hard(scan, git, 'unparsable .git file')
|
|
382
|
+
return null
|
|
383
|
+
}
|
|
384
|
+
const gitdir = resolve(dir, m[1])
|
|
385
|
+
// <main>/.git/worktrees/<name>
|
|
386
|
+
const worktrees = dirname(gitdir)
|
|
387
|
+
const mainGit = dirname(worktrees)
|
|
388
|
+
if (worktrees.endsWith('worktrees') && mainGit.endsWith('.git')) return join(dirname(mainGit), '.claude')
|
|
389
|
+
return null
|
|
390
|
+
}
|
|
391
|
+
return null
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Nested `.claude` directories below `root`, by a bounded breadth-first walk.
|
|
396
|
+
* Symlinked directories are followed, with realpath cycle detection. Any budget
|
|
397
|
+
* (directories, entries, depth, wall clock) running out is HARD.
|
|
398
|
+
*/
|
|
399
|
+
function findNestedDotClaude(root, rootReal, scan) {
|
|
400
|
+
const found = []
|
|
401
|
+
const queue = [[root, rootReal, 0]]
|
|
402
|
+
const visited = new Set([rootReal])
|
|
403
|
+
const deadline = Date.now() + scan.limits.nestedBudgetMs
|
|
404
|
+
for (let head = 0; head < queue.length; head += 1) {
|
|
405
|
+
const [dir, real, depth] = queue[head]
|
|
406
|
+
if (Date.now() > deadline) {
|
|
407
|
+
hardNote(scan, 'This folder is too large to review (the search took too long)')
|
|
408
|
+
return found
|
|
409
|
+
}
|
|
410
|
+
const listing = listDir(dir, scan.nested, deadline)
|
|
411
|
+
if (listing.absent) continue
|
|
412
|
+
if (listing.hard) {
|
|
413
|
+
listingHard(scan, dir, listing)
|
|
414
|
+
if (listing.hard.startsWith('This folder is too large')) return found
|
|
415
|
+
continue
|
|
416
|
+
}
|
|
417
|
+
for (const d of listing.entries) {
|
|
418
|
+
const child = join(dir, d.name)
|
|
419
|
+
let isDir = d.isDirectory()
|
|
420
|
+
let childReal = join(real, d.name)
|
|
421
|
+
if (d.isSymbolicLink()) {
|
|
422
|
+
let st
|
|
423
|
+
try {
|
|
424
|
+
st = statSync(child)
|
|
425
|
+
} catch (err) {
|
|
426
|
+
hard(scan, child, err?.code === 'ENOENT' ? 'dangling symlink' : (err?.code || 'unreadable'))
|
|
427
|
+
continue
|
|
428
|
+
}
|
|
429
|
+
isDir = st.isDirectory()
|
|
430
|
+
if (!isDir) continue
|
|
431
|
+
childReal = realOf(child, scan)
|
|
432
|
+
if (real === childReal || real.startsWith(childReal.endsWith(sep) ? childReal : childReal + sep)) {
|
|
433
|
+
hard(scan, child, 'symlink cycle')
|
|
434
|
+
continue
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (!isDir) continue
|
|
438
|
+
if (d.name === '.claude') {
|
|
439
|
+
if (dir !== root) found.push(child)
|
|
440
|
+
continue
|
|
441
|
+
}
|
|
442
|
+
if (SKIP_NESTED.has(d.name)) continue
|
|
443
|
+
if (visited.has(childReal)) continue
|
|
444
|
+
visited.add(childReal)
|
|
445
|
+
if (depth + 1 > MAX_NESTED_DEPTH) {
|
|
446
|
+
hardNote(scan, `This folder is too large to review (more than ${MAX_NESTED_DEPTH} levels deep)`)
|
|
447
|
+
return found
|
|
448
|
+
}
|
|
449
|
+
queue.push([child, childReal, depth + 1])
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return found
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const clip = (value) => {
|
|
456
|
+
const s = typeof value === 'string' ? value : String(value ?? '')
|
|
457
|
+
return s.length > MAX_SUMMARY_STRING ? `${s.slice(0, MAX_SUMMARY_STRING)}…` : s
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Take at most MAX_SUMMARY_ITEMS of `items`, noting what was left out. */
|
|
461
|
+
function capped(items, what, warnings) {
|
|
462
|
+
if (items.length > MAX_SUMMARY_ITEMS) {
|
|
463
|
+
warnings.push(`${items.length - MAX_SUMMARY_ITEMS} more ${what} not shown`)
|
|
464
|
+
return items.slice(0, MAX_SUMMARY_ITEMS)
|
|
465
|
+
}
|
|
466
|
+
return items
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
function summarizeConfig(config, summary) {
|
|
470
|
+
const { warnings } = summary
|
|
471
|
+
let clipped = false
|
|
472
|
+
const c = (v) => {
|
|
473
|
+
const s = clip(v)
|
|
474
|
+
if (s.length < String(v).length) clipped = true
|
|
475
|
+
return s
|
|
476
|
+
}
|
|
477
|
+
for (const { path, kind, buf } of config) {
|
|
478
|
+
if (buf.length > MAX_PARSE_BYTES) {
|
|
479
|
+
warnings.push(`${path}: too large to summarize; it is still covered by the trust check`)
|
|
480
|
+
continue
|
|
481
|
+
}
|
|
482
|
+
let doc
|
|
483
|
+
try {
|
|
484
|
+
doc = JSON.parse(buf.toString('utf8'))
|
|
485
|
+
} catch {
|
|
486
|
+
warnings.push(`${path}: not valid JSON`)
|
|
487
|
+
continue
|
|
488
|
+
}
|
|
489
|
+
if (!doc || typeof doc !== 'object') continue
|
|
490
|
+
if (kind === 'mcp') {
|
|
491
|
+
const servers = doc.mcpServers
|
|
492
|
+
if (!servers || typeof servers !== 'object' || Array.isArray(servers)) continue
|
|
493
|
+
for (const name of capped(Object.keys(servers), 'MCP servers', warnings)) {
|
|
494
|
+
const s = servers[name]
|
|
495
|
+
if (!s || typeof s !== 'object') continue
|
|
496
|
+
const item = { file: path, name: c(name) }
|
|
497
|
+
if (typeof s.command === 'string') item.command = c(s.command)
|
|
498
|
+
if (Array.isArray(s.args)) item.args = capped(s.args, 'arguments', warnings).map(c)
|
|
499
|
+
if (typeof s.url === 'string') item.url = redactMcpUrl(s.url)
|
|
500
|
+
if (typeof s.type === 'string') item.type = c(s.type)
|
|
501
|
+
// Environment VALUES routinely hold credentials: only the keys are listed.
|
|
502
|
+
if (s.env && typeof s.env === 'object' && !Array.isArray(s.env)) item.envKeys = capped(Object.keys(s.env), 'environment keys', warnings).map(c)
|
|
503
|
+
summary.mcpServers.push(item)
|
|
504
|
+
}
|
|
505
|
+
continue
|
|
506
|
+
}
|
|
507
|
+
if (doc.hooks && typeof doc.hooks === 'object' && !Array.isArray(doc.hooks)) {
|
|
508
|
+
for (const event of capped(Object.keys(doc.hooks), 'hook events', warnings)) {
|
|
509
|
+
const commands = []
|
|
510
|
+
for (const group of Array.isArray(doc.hooks[event]) ? doc.hooks[event] : []) {
|
|
511
|
+
for (const hook of Array.isArray(group?.hooks) ? group.hooks : []) {
|
|
512
|
+
if (typeof hook?.command === 'string') commands.push(hook.command)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
summary.hooks.push({ file: path, event: c(event), commands: capped(commands, 'hook commands', warnings).map(c) })
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const sl = doc.statusLine
|
|
519
|
+
if (sl && typeof sl === 'object' && typeof sl.command === 'string') summary.statusLine.push({ file: path, command: c(sl.command) })
|
|
520
|
+
if (doc.enabledPlugins && typeof doc.enabledPlugins === 'object' && !Array.isArray(doc.enabledPlugins)) {
|
|
521
|
+
for (const key of capped(Object.keys(doc.enabledPlugins), 'plugins', warnings)) summary.enabledPlugins.push({ file: path, plugin: c(key) })
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
if (clipped) warnings.push(`Some values longer than ${MAX_SUMMARY_STRING} characters were shortened`)
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Scan the command-bearing settings files that apply to `cwd`.
|
|
529
|
+
*
|
|
530
|
+
* @param {string} cwd
|
|
531
|
+
* @param {object} [limits] - maxFileBytes, maxTotalBytes, maxFiles, maxNestedDirs, ...; `nestedBudgetMs`
|
|
532
|
+
* (wall clock of the nested search) is unset by default, so the walk is bounded by entries and depth only
|
|
533
|
+
* @returns {{
|
|
534
|
+
* realPath: string,
|
|
535
|
+
* files: { path: string, sha256: string }[],
|
|
536
|
+
* digest: string,
|
|
537
|
+
* summary: object,
|
|
538
|
+
* hasCommandBearingFiles: boolean,
|
|
539
|
+
* hardIncomplete: boolean,
|
|
540
|
+
* }}
|
|
541
|
+
*/
|
|
542
|
+
let scanCount = 0
|
|
543
|
+
/** Test seam: how many scans have run in this process. */
|
|
544
|
+
export function scanCountForTest() {
|
|
545
|
+
return scanCount
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function scanFolderSettings(cwd, limits) {
|
|
549
|
+
scanCount += 1
|
|
550
|
+
const scan = newScan(limits)
|
|
551
|
+
const summary = {
|
|
552
|
+
files: [],
|
|
553
|
+
mcpServers: [],
|
|
554
|
+
hooks: [],
|
|
555
|
+
statusLine: [],
|
|
556
|
+
enabledPlugins: [],
|
|
557
|
+
counts: scan.counts,
|
|
558
|
+
warnings: [],
|
|
559
|
+
hasCommandBearingFiles: false,
|
|
560
|
+
untrustable: false,
|
|
561
|
+
}
|
|
562
|
+
let realPath = ''
|
|
563
|
+
if (typeof cwd === 'string' && cwd !== '') {
|
|
564
|
+
try {
|
|
565
|
+
const root = resolveRealPath(cwd)
|
|
566
|
+
realPath = root.path
|
|
567
|
+
if (root.error) hard(scan, realPath, root.error)
|
|
568
|
+
// The user's own Claude dir, resolved once through any dotfile symlinks, so it
|
|
569
|
+
// compares equal to the real path of a `.claude` found anywhere below.
|
|
570
|
+
let userDir = null
|
|
571
|
+
try {
|
|
572
|
+
const u = resolveRealPath(claudeConfigDir())
|
|
573
|
+
userDir = u.error ? null : u.path
|
|
574
|
+
if (u.error) hard(scan, claudeConfigDir(), u.error)
|
|
575
|
+
} catch { userDir = null }
|
|
576
|
+
const isUserDir = (dotClaude) => {
|
|
577
|
+
if (userDir === null) return false
|
|
578
|
+
const r = resolveRealPath(dotClaude)
|
|
579
|
+
if (r.error) {
|
|
580
|
+
hard(scan, dotClaude, r.error)
|
|
581
|
+
return false
|
|
582
|
+
}
|
|
583
|
+
return r.path === userDir
|
|
584
|
+
}
|
|
585
|
+
const seen = new Set()
|
|
586
|
+
const location = (dotClaude) => {
|
|
587
|
+
if (seen.has(dotClaude) || isUserDir(dotClaude)) return
|
|
588
|
+
seen.add(dotClaude)
|
|
589
|
+
scanContentLocation(dotClaude, scan)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
for (const dir of ancestorsOf(realPath)) {
|
|
593
|
+
addConfigFile(join(dir, '.mcp.json'), 'mcp', scan)
|
|
594
|
+
const dotClaude = join(dir, '.claude')
|
|
595
|
+
if (!isUserDir(dotClaude)) addConfigFile(join(dotClaude, 'settings.json'), 'settings', scan)
|
|
596
|
+
location(dotClaude)
|
|
597
|
+
}
|
|
598
|
+
for (const nested of findNestedDotClaude(realPath, realPath, scan)) location(nested)
|
|
599
|
+
const main = mainCheckoutDotClaude(realPath, scan)
|
|
600
|
+
if (main && !seen.has(main) && !isUserDir(main)) {
|
|
601
|
+
seen.add(main)
|
|
602
|
+
scanContentRoot(join(main, 'skills'), 'skills', scan)
|
|
603
|
+
}
|
|
604
|
+
} catch (err) {
|
|
605
|
+
// The scan must never throw into a launch path; an unfinished scan cannot be approved.
|
|
606
|
+
hard(scan, realPath || String(cwd), err?.code || err?.message || 'scan failed')
|
|
607
|
+
}
|
|
608
|
+
} else {
|
|
609
|
+
hard(scan, String(cwd), 'no folder')
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const files = scan.entries.map(({ path, sha256 }) => ({ path, sha256 })).sort(byPath)
|
|
613
|
+
summary.files = scan.entries.map(({ path, linkTarget }) => ({ path, ...(linkTarget ? { linkTarget } : {}) })).sort(byPath)
|
|
614
|
+
summary.hasCommandBearingFiles = files.length > 0
|
|
615
|
+
try {
|
|
616
|
+
summarizeConfig(scan.config.sort(byPath), summary)
|
|
617
|
+
} catch (err) {
|
|
618
|
+
summary.warnings.push(`summary incomplete: ${err?.message || 'error'}`)
|
|
619
|
+
}
|
|
620
|
+
const hardIncomplete = scan.hard.length > 0
|
|
621
|
+
if (hardIncomplete) {
|
|
622
|
+
summary.untrustable = true
|
|
623
|
+
for (const h of scan.hard.slice(0, 10)) summary.warnings.push(h.startsWith('This folder is too large') ? h : `Cannot review this folder: ${h}`)
|
|
624
|
+
if (scan.hard.length > 10) summary.warnings.push(`${scan.hard.length - 10} more problems not shown`)
|
|
625
|
+
}
|
|
626
|
+
return {
|
|
627
|
+
realPath: realPath || resolve(String(cwd ?? '')),
|
|
628
|
+
files,
|
|
629
|
+
digest: sha256Hex(canonicalJson(files)),
|
|
630
|
+
summary,
|
|
631
|
+
hasCommandBearingFiles: files.length > 0,
|
|
632
|
+
hardIncomplete,
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ── Store ────────────────────────────────────────────────────────────────
|
|
637
|
+
|
|
638
|
+
const HEX64 = /^[0-9a-f]{64}$/
|
|
639
|
+
|
|
640
|
+
function isRecord(r) {
|
|
641
|
+
if (!r || typeof r !== 'object' || r.v !== FOLDER_TRUST_RECORD_VERSION) return false
|
|
642
|
+
if (typeof r.path !== 'string' || r.path === '' || typeof r.trustedAt !== 'string') return false
|
|
643
|
+
if (typeof r.digest !== 'string' || !HEX64.test(r.digest) || !Array.isArray(r.files)) return false
|
|
644
|
+
if (!r.files.every((f) => f && typeof f.path === 'string' && typeof f.sha256 === 'string' && HEX64.test(f.sha256))) return false
|
|
645
|
+
// The digest is a function of the file list; a record that disagrees was edited.
|
|
646
|
+
const files = r.files.map(({ path, sha256 }) => ({ path, sha256 })).sort(byPath)
|
|
647
|
+
return sha256Hex(canonicalJson(files)) === r.digest
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Read the store; a missing, corrupt or other-version file yields no records. */
|
|
651
|
+
export function loadFolderTrustRecords(filePath = folderTrustStorePath()) {
|
|
652
|
+
if (!existsSync(filePath)) return []
|
|
653
|
+
try {
|
|
654
|
+
const raw = JSON.parse(readFileSync(filePath, 'utf8'))
|
|
655
|
+
const list = Array.isArray(raw?.records) ? raw.records : []
|
|
656
|
+
const seen = new Set()
|
|
657
|
+
const records = []
|
|
658
|
+
for (const r of list) {
|
|
659
|
+
if (!isRecord(r) || seen.has(r.path)) continue
|
|
660
|
+
seen.add(r.path)
|
|
661
|
+
records.push({
|
|
662
|
+
v: r.v,
|
|
663
|
+
path: r.path,
|
|
664
|
+
digest: r.digest,
|
|
665
|
+
files: r.files.map(({ path, sha256 }) => ({ path, sha256 })),
|
|
666
|
+
trustedAt: r.trustedAt,
|
|
667
|
+
})
|
|
668
|
+
}
|
|
669
|
+
return records
|
|
670
|
+
} catch (err) {
|
|
671
|
+
log.warn(`folder trust store unreadable: ${err?.message || err}`)
|
|
672
|
+
return []
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
function saveFolderTrustRecords(records, filePath = folderTrustStorePath()) {
|
|
677
|
+
// Fenced: the lock must still be ours at the last moment before the rename.
|
|
678
|
+
writeFileAtomic0600(filePath, JSON.stringify({ records }, null, 2), () => assertStoreLockHeld(filePath))
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// ── Cross-process lock ───────────────────────────────────────────────────
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* The store lock is a file created whole and atomically (the full body is written to a unique
|
|
685
|
+
* temp file, then hard-linked to the lock path; where linking is unsupported, `O_EXCL` create
|
|
686
|
+
* plus write). Its holder refreshes the file's mtime while it works (a lease). A lock is stale
|
|
687
|
+
* when its lease has expired, whatever its pid says, or, when it was written under the same
|
|
688
|
+
* hostname (and, on Linux, PID namespace) as this process, as soon as its holder is known to be
|
|
689
|
+
* gone. A lock that is neither is live and is never reclaimed.
|
|
690
|
+
*
|
|
691
|
+
* Accepted limit: a process suspended for longer than the lease while holding, reclaiming or
|
|
692
|
+
* creating the lock can overlap with another holder. Writes re-check ownership before the rename
|
|
693
|
+
* (`assertStoreLockHeld`), which narrows but does not remove this. Specifically: a holder suspended
|
|
694
|
+
* between that check and the rename; a reclaimer suspended between its guarded checks and the
|
|
695
|
+
* unlink after its guard's lease expired; a creator suspended between creating and writing the lock
|
|
696
|
+
* on the `O_EXCL` fallback path. A file lock without operating-system primitives cannot close them.
|
|
697
|
+
*/
|
|
698
|
+
const LOCK_LEASE_MS = 15_000
|
|
699
|
+
const LOCK_HEARTBEAT_MS = LOCK_LEASE_MS / 4
|
|
700
|
+
/** A guard is held for the length of one synchronous reclaim; this long without a refresh and it is abandoned. */
|
|
701
|
+
const GUARD_LEASE_MS = 15_000
|
|
702
|
+
/** Long enough to outlast one lease after a holder crashes. */
|
|
703
|
+
const LOCK_WAIT_MS = LOCK_LEASE_MS + 5_000
|
|
704
|
+
let lockWaitMs = LOCK_WAIT_MS
|
|
705
|
+
/** Test seam: how long a caller waits for the store lock. Call with no argument to restore. */
|
|
706
|
+
export function setLockWaitForTest(ms) {
|
|
707
|
+
lockWaitMs = ms ?? LOCK_WAIT_MS
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
|
|
711
|
+
|
|
712
|
+
/** `readLock` that tells an unreadable file (undefined) from an absent one (null). */
|
|
713
|
+
const readLockForOwnership = (lockPath) => {
|
|
714
|
+
try {
|
|
715
|
+
return readFileSync(lockPath, 'utf8')
|
|
716
|
+
} catch (err) {
|
|
717
|
+
return err?.code === 'ENOENT' ? null : undefined
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/** Test seam: replaces the read-back of a just-written lock, to make it fail. */
|
|
722
|
+
let lockReadBackHook = null
|
|
723
|
+
export function setLockReadBackHookForTest(fn) {
|
|
724
|
+
lockReadBackHook = fn ?? null
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
/** The read seam covers every ownership read of the protocol, so a test can make each of them fail. */
|
|
728
|
+
const ownershipRead = (path) => (lockReadBackHook ? lockReadBackHook(path, readLockForOwnership) : readLockForOwnership(path))
|
|
729
|
+
|
|
730
|
+
/** Random per process: a pid alone does not tell this process from an earlier one that had the same pid. */
|
|
731
|
+
const PROCESS_NONCE = randomBytes(8).toString('hex')
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* Where a pid is meaningful: the hostname plus, on Linux, the PID namespace. Null (unknown) when it
|
|
735
|
+
* cannot be determined, which disables the fast path below.
|
|
736
|
+
*/
|
|
737
|
+
function computeDiscriminator() {
|
|
738
|
+
try {
|
|
739
|
+
let d = hostname()
|
|
740
|
+
if (process.platform === 'linux') d += `|${readlinkSync('/proc/self/ns/pid')}`
|
|
741
|
+
d = d.replace(/[\r\n]/g, '')
|
|
742
|
+
return d || null
|
|
743
|
+
} catch {
|
|
744
|
+
return null
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
let localDiscriminator = computeDiscriminator()
|
|
748
|
+
/** Test seam: replaces this process's discriminator (null for unknown). No argument restores. */
|
|
749
|
+
export function setLockDiscriminatorForTest(d) {
|
|
750
|
+
localDiscriminator = d === undefined ? computeDiscriminator() : d
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** The mtime (ns) and size of a lock-protocol file, taken when it is judged and compared again before it is removed. */
|
|
754
|
+
export function statLockIdentity(path) {
|
|
755
|
+
try {
|
|
756
|
+
const st = statSync(path, { bigint: true })
|
|
757
|
+
return { mtimeNs: st.mtimeNs, size: st.size }
|
|
758
|
+
} catch {
|
|
759
|
+
return null
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
const sameIdentity = (a, b) => a !== null && b !== null && a !== undefined && b !== undefined && a.mtimeNs === b.mtimeNs && a.size === b.size
|
|
763
|
+
|
|
764
|
+
const pidAlive = (pid) => {
|
|
765
|
+
try {
|
|
766
|
+
process.kill(pid, 0)
|
|
767
|
+
return true
|
|
768
|
+
} catch (err) {
|
|
769
|
+
return err?.code !== 'ESRCH'
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
/**
|
|
774
|
+
* Expired: older than the lease, or dated in the future by more than one lease. The second case
|
|
775
|
+
* tolerates clock steps and skewed network file systems: such a lock is treated as expired. A live
|
|
776
|
+
* holder recovers its lease at its next beat (the heartbeat sets the mtime to its own clock) only if
|
|
777
|
+
* no reclaimer removed the lock first: a beat never recreates a lock file.
|
|
778
|
+
*/
|
|
779
|
+
function leaseExpired(path, leaseMs) {
|
|
780
|
+
try {
|
|
781
|
+
const age = Date.now() - statSync(path).mtimeMs
|
|
782
|
+
return age > leaseMs || age < -leaseMs
|
|
783
|
+
} catch {
|
|
784
|
+
return false
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* The fast path: the holder named in a lock or guard body is known to be gone. Only for a body
|
|
790
|
+
* written under this process's discriminator; any other (or none: the previous format) is left to the lease.
|
|
791
|
+
* Lock bodies are `pid, token, time, nonce, discriminator`; guard bodies `pid, token, nonce, discriminator`.
|
|
792
|
+
*/
|
|
793
|
+
function holderGone(content, nonceLine, discLine, inFlight) {
|
|
794
|
+
const lines = content.split('\n')
|
|
795
|
+
const pid = Number.parseInt(lines[0], 10)
|
|
796
|
+
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
797
|
+
const disc = lines[discLine]
|
|
798
|
+
if (!disc || !localDiscriminator || disc !== localDiscriminator) return false
|
|
799
|
+
if (pid === process.pid) {
|
|
800
|
+
const nonce = lines[nonceLine]
|
|
801
|
+
if (!nonce) return false
|
|
802
|
+
if (nonce !== PROCESS_NONCE) return true // an earlier process that had our pid
|
|
803
|
+
return !inFlight(lines[1]) // ours, and no call of ours owns it: a release that failed
|
|
804
|
+
}
|
|
805
|
+
return !pidAlive(pid)
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** Tokens of the lock calls in flight in this process (waiting or holding). */
|
|
809
|
+
const liveTokens = new Set()
|
|
810
|
+
/** Tokens of the guards this process's reclaims hold right now. */
|
|
811
|
+
const heldGuardTokens = new Set()
|
|
812
|
+
|
|
813
|
+
/** Stale: the lease expired, or the holder is known to be gone. Anything else is live. */
|
|
814
|
+
export function lockIsStale(lockPath, content) {
|
|
815
|
+
if (content === null || content === undefined) return false
|
|
816
|
+
return leaseExpired(lockPath, LOCK_LEASE_MS) || holderGone(content, 3, 4, (t) => liveTokens.has(t))
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
let unlinkImpl = unlinkSync
|
|
820
|
+
/** Test seam: replaces the unlink used to release lock-protocol files. No argument restores. */
|
|
821
|
+
export function setLockUnlinkForTest(fn) {
|
|
822
|
+
unlinkImpl = fn ?? unlinkSync
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
let linkImpl = linkSync
|
|
826
|
+
/** Test seam: replaces the hard link that creates the lock. No argument restores. */
|
|
827
|
+
export function setLockLinkForTest(fn) {
|
|
828
|
+
linkImpl = fn ?? linkSync
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
let openImpl = openSync
|
|
832
|
+
/** Test seam: replaces the open of the lock for the heartbeat's descriptor. No argument restores. */
|
|
833
|
+
export function setLockOpenForTest(fn) {
|
|
834
|
+
openImpl = fn ?? openSync
|
|
835
|
+
}
|
|
836
|
+
let futimesImpl = futimesSync
|
|
837
|
+
/** Test seam: replaces the descriptor-based mtime refresh of the heartbeat. No argument restores. */
|
|
838
|
+
export function setLockFutimesForTest(fn) {
|
|
839
|
+
futimesImpl = fn ?? futimesSync
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
let createHook = null
|
|
843
|
+
/** Test seam: called after the lock's temp file is written and before it is linked into place. */
|
|
844
|
+
export function setLockCreateHookForTest(fn) {
|
|
845
|
+
createHook = fn ?? null
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/**
|
|
849
|
+
* Remove a lock-protocol file we own. On Windows a reader that has it open makes the
|
|
850
|
+
* unlink fail transiently, and leaving our own file behind would hold everyone else off
|
|
851
|
+
* for as long as this process lives, so retry briefly. Gone already is success.
|
|
852
|
+
*/
|
|
853
|
+
function unlinkOwned(path, platform = process.platform) {
|
|
854
|
+
for (let attempt = 0; attempt < 20; attempt += 1) {
|
|
855
|
+
try {
|
|
856
|
+
unlinkImpl(path)
|
|
857
|
+
return true
|
|
858
|
+
} catch (err) {
|
|
859
|
+
if (err?.code === 'ENOENT') return true
|
|
860
|
+
if (!isTransientLockError(err, platform) || err?.code === 'EEXIST') return false
|
|
861
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
return false
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const RELEASE_RETRY_MAX_DELAY_MS = 5_000
|
|
868
|
+
|
|
869
|
+
/**
|
|
870
|
+
* The release could not be done (the unlink kept failing, or the file could not be read to
|
|
871
|
+
* check it): keep trying in the background, with capped backoff, without blocking the caller.
|
|
872
|
+
* Stops when the file is gone or no longer matches `owned`; an unreadable file is retried.
|
|
873
|
+
*/
|
|
874
|
+
function releaseInBackground(path, owned, delayMs = 50) {
|
|
875
|
+
const timer = setTimeout(() => {
|
|
876
|
+
const held = readLockForOwnership(path)
|
|
877
|
+
if (held === null) return
|
|
878
|
+
let removed = false
|
|
879
|
+
if (typeof held === 'string') {
|
|
880
|
+
if (!owned(held)) return
|
|
881
|
+
try { unlinkImpl(path); removed = true } catch (err) { removed = err?.code === 'ENOENT' }
|
|
882
|
+
}
|
|
883
|
+
if (!removed) releaseInBackground(path, owned, Math.min(delayMs * 2, RELEASE_RETRY_MAX_DELAY_MS))
|
|
884
|
+
}, delayMs)
|
|
885
|
+
timer.unref?.()
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/** A guard is abandoned when its lease expired, or its holder is known to be gone. */
|
|
889
|
+
function guardIsAbandoned(guard, content) {
|
|
890
|
+
return leaseExpired(guard, GUARD_LEASE_MS) || holderGone(content, 2, 3, (t) => heldGuardTokens.has(t))
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
const hasToken = (content) => {
|
|
894
|
+
const t = content.split('\n')[1]
|
|
895
|
+
return Boolean(t) && /^[\w.-]+$/.test(t) && !t.includes('-')
|
|
896
|
+
}
|
|
897
|
+
const tokenOf = (content) => (hasToken(content) ? content.split('\n')[1] : `u${sha256Hex(content).slice(0, 16)}`)
|
|
898
|
+
/**
|
|
899
|
+
* What a guard is named for: the token of a lock that has one. A lock without a token
|
|
900
|
+
* (the previous format's residue) is named by its content hash, mtime and size.
|
|
901
|
+
*/
|
|
902
|
+
const lockKey = (content, identity) => {
|
|
903
|
+
if (typeof content !== 'string') return identity ? `unreadablem${identity.mtimeNs}s${identity.size}` : 'unreadable'
|
|
904
|
+
return hasToken(content) || !identity ? tokenOf(content) : `${tokenOf(content)}m${identity.mtimeNs}s${identity.size}`
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/** Test seam: called while a reclaim holds its guard, before it re-reads the lock. */
|
|
908
|
+
let reclaimHook = null
|
|
909
|
+
export function setReclaimHookForTest(fn) {
|
|
910
|
+
reclaimHook = fn ?? null
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Remove guards left for a lock other than the current one, once their lease has expired. Only
|
|
915
|
+
* called with a lock that was read successfully; their holders, if any are still alive, re-read
|
|
916
|
+
* the lock and find it changed.
|
|
917
|
+
*/
|
|
918
|
+
function collectGuards(lockPath, currentKey) {
|
|
919
|
+
const dir = dirname(lockPath)
|
|
920
|
+
const prefix = `${basename(lockPath)}.reclaim-`
|
|
921
|
+
let names
|
|
922
|
+
try { names = readdirSync(dir) } catch { return }
|
|
923
|
+
for (const name of names) {
|
|
924
|
+
if (!name.startsWith(prefix) || name.slice(prefix.length).split('-')[0] === currentKey) continue
|
|
925
|
+
try {
|
|
926
|
+
if (leaseExpired(join(dir, name), GUARD_LEASE_MS)) unlinkSync(join(dir, name))
|
|
927
|
+
} catch { /* gone, or not ours to judge */ }
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/** Remove lock temp files left by a creator that died between writing and linking. */
|
|
932
|
+
function collectTempFiles(lockPath) {
|
|
933
|
+
const dir = dirname(lockPath)
|
|
934
|
+
const prefix = `${basename(lockPath)}.tmp-`
|
|
935
|
+
let names
|
|
936
|
+
try { names = readdirSync(dir) } catch { return }
|
|
937
|
+
for (const name of names) {
|
|
938
|
+
if (!name.startsWith(prefix)) continue
|
|
939
|
+
try {
|
|
940
|
+
if (leaseExpired(join(dir, name), LOCK_LEASE_MS)) unlinkSync(join(dir, name))
|
|
941
|
+
} catch { /* gone */ }
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
/**
|
|
946
|
+
* Remove a lock that was judged stale, without ever vacating a live one. Reclaiming is guarded
|
|
947
|
+
* by a file named for the lock it is about (`<lock>.reclaim-<token of the judged lock>`), created
|
|
948
|
+
* `O_EXCL` and holding its holder's pid, a token, a nonce and a discriminator. Under it the lock
|
|
949
|
+
* is re-read and removed only if it is still the judged file: the same content, mtime and size
|
|
950
|
+
* (a live holder refreshes the mtime). The guard is then released only if it still holds this
|
|
951
|
+
* reclaim's token.
|
|
952
|
+
*
|
|
953
|
+
* No process deletes a guard another may hold. If a guard exists and is abandoned (its lease
|
|
954
|
+
* expired, or its holder is known to be gone) it is left where it is and this reclaim escalates
|
|
955
|
+
* to a guard named after that guard's token, to the same rule, to a bounded depth. Tokens are
|
|
956
|
+
* random and never reused, so a name is only ever created once and removed by its own holder.
|
|
957
|
+
* Leftover guards for a lock that is no longer current are collected once their lease has expired,
|
|
958
|
+
* and only after a successful read of the current lock.
|
|
959
|
+
* @param {string} lockPath
|
|
960
|
+
* @param {string|undefined} judged the content that was judged stale; undefined when the file could not
|
|
961
|
+
* be read but its lease had expired (it is then removed only if it still cannot be read, and is still the judged file)
|
|
962
|
+
* @param {{ mtimeNs: bigint, size: bigint }} identity the file's `statLockIdentity` when it was judged
|
|
963
|
+
* @returns {boolean} true when this call removed the lock
|
|
964
|
+
*/
|
|
965
|
+
export function reclaimStale(lockPath, judged, identity) {
|
|
966
|
+
if (!identity) return false
|
|
967
|
+
const current = ownershipRead(lockPath)
|
|
968
|
+
if (current === null) collectGuards(lockPath, '')
|
|
969
|
+
else if (typeof current === 'string' && hasToken(current)) collectGuards(lockPath, tokenOf(current))
|
|
970
|
+
let guard = `${lockPath}.reclaim-${lockKey(judged, identity)}`
|
|
971
|
+
const guardToken = `${process.pid}.${randomBytes(8).toString('hex')}`
|
|
972
|
+
const guardBody = `${process.pid}\n${guardToken}\n${PROCESS_NONCE}\n${localDiscriminator ?? ''}\n`
|
|
973
|
+
for (let depth = 0; ; depth += 1) {
|
|
974
|
+
try {
|
|
975
|
+
writeFileSync(guard, guardBody, { mode: 0o600, flag: 'wx' })
|
|
976
|
+
heldGuardTokens.add(guardToken)
|
|
977
|
+
break
|
|
978
|
+
} catch (err) {
|
|
979
|
+
if (err?.code !== 'EEXIST' || depth >= RECLAIM_MAX_DEPTH) return false
|
|
980
|
+
const held = ownershipRead(guard)
|
|
981
|
+
if (typeof held !== 'string' || !guardIsAbandoned(guard, held)) return false
|
|
982
|
+
guard = `${guard}-${tokenOf(held)}`
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
let removed = false
|
|
986
|
+
try {
|
|
987
|
+
if (reclaimHook) reclaimHook()
|
|
988
|
+
if (ownershipRead(lockPath) === judged && sameIdentity(statLockIdentity(lockPath), identity)) {
|
|
989
|
+
try {
|
|
990
|
+
unlinkSync(lockPath)
|
|
991
|
+
removed = true
|
|
992
|
+
} catch { /* already gone */ }
|
|
993
|
+
}
|
|
994
|
+
} finally {
|
|
995
|
+
const back = ownershipRead(guard)
|
|
996
|
+
const ours = (c) => c === guardBody
|
|
997
|
+
if (back === undefined) releaseInBackground(guard, ours)
|
|
998
|
+
else if (ours(back) && !unlinkOwned(guard)) releaseInBackground(guard, ours)
|
|
999
|
+
heldGuardTokens.delete(guardToken)
|
|
1000
|
+
}
|
|
1001
|
+
return removed
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* How many abandoned guards one reclaim will step over before giving up and waiting. It bounds the
|
|
1006
|
+
* walk down an escalation chain (one file operation per step), so a reclaim always ends; past it the
|
|
1007
|
+
* caller waits and retries within its own deadline, and each guard in the chain is only ever passed
|
|
1008
|
+
* over once its lease expired or its holder is known to be gone.
|
|
1009
|
+
*/
|
|
1010
|
+
const RECLAIM_MAX_DEPTH = 4
|
|
1011
|
+
|
|
1012
|
+
/**
|
|
1013
|
+
* On Windows, creating a file that another process is deleting, or has open, fails with
|
|
1014
|
+
* EPERM / EACCES / EBUSY instead of EEXIST. That is contention, not a fault: the caller
|
|
1015
|
+
* waits and retries within its deadline. Elsewhere those codes are real errors.
|
|
1016
|
+
*/
|
|
1017
|
+
export function isTransientLockError(err, platform = process.platform) {
|
|
1018
|
+
if (err?.code === 'EEXIST') return true
|
|
1019
|
+
return platform === 'win32' && (err?.code === 'EPERM' || err?.code === 'EACCES' || err?.code === 'EBUSY')
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
/** The lock call whose critical section is running, for `assertStoreLockHeld`. */
|
|
1023
|
+
const lockContext = new AsyncLocalStorage()
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* Throws unless the store lock the running call took is still ours. The writes the lock protects
|
|
1027
|
+
* call it immediately before their final rename (see the note above `LOCK_LEASE_MS`).
|
|
1028
|
+
*/
|
|
1029
|
+
export function assertStoreLockHeld(storePath) {
|
|
1030
|
+
const ctx = lockContext.getStore()
|
|
1031
|
+
if (!ctx) throw new Error('folder trust store lock is not held')
|
|
1032
|
+
if (resolve(storePath) !== resolve(ctx.storePath)) throw new Error('folder trust store lock does not protect this file')
|
|
1033
|
+
if (fenceHook) fenceHook(ctx.lockPath)
|
|
1034
|
+
const back = readLockForOwnership(ctx.lockPath)
|
|
1035
|
+
if (typeof back !== 'string' || !back.includes(`\n${ctx.token}\n`)) throw new Error('folder trust store lock was lost')
|
|
1036
|
+
}
|
|
1037
|
+
let fenceHook = null
|
|
1038
|
+
/** Test seam: called at the start of the fence check, with the lock path. */
|
|
1039
|
+
export function setLockFenceHookForTest(fn) {
|
|
1040
|
+
fenceHook = fn ?? null
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
/**
|
|
1044
|
+
* Create the lock whole: a full body in a temp file, linked into place. EEXIST is contention
|
|
1045
|
+
* (thrown). Where the link is unsupported (or fails for any other reason) the lock is created
|
|
1046
|
+
* with `O_EXCL` and written, and the caller must confirm it.
|
|
1047
|
+
* @returns {'linked'|'written'}
|
|
1048
|
+
*/
|
|
1049
|
+
function createLock(lockPath, body, token) {
|
|
1050
|
+
const tmp = `${lockPath}.tmp-${token}`
|
|
1051
|
+
let linked = false
|
|
1052
|
+
try {
|
|
1053
|
+
writeFileSync(tmp, body, { mode: 0o600, flag: 'wx' })
|
|
1054
|
+
if (createHook) createHook(lockPath, tmp)
|
|
1055
|
+
linkImpl(tmp, lockPath)
|
|
1056
|
+
linked = true
|
|
1057
|
+
} catch (err) {
|
|
1058
|
+
if (err?.code === 'EEXIST') throw err
|
|
1059
|
+
} finally {
|
|
1060
|
+
try { unlinkSync(tmp) } catch { /* never created, or collected by age */ }
|
|
1061
|
+
}
|
|
1062
|
+
if (linked) return 'linked'
|
|
1063
|
+
const fd = openSync(lockPath, 'wx', 0o600)
|
|
1064
|
+
try {
|
|
1065
|
+
fallbackWriteImpl(fd, body)
|
|
1066
|
+
} catch (err) {
|
|
1067
|
+
// The file is ours (we just created it) and is empty or partial: take it away before failing.
|
|
1068
|
+
try { closeSync(fd) } catch { /* closed below if not */ }
|
|
1069
|
+
try { unlinkSync(lockPath) } catch { /* gone */ }
|
|
1070
|
+
throw err
|
|
1071
|
+
}
|
|
1072
|
+
closeSync(fd)
|
|
1073
|
+
return 'written'
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
let fallbackWriteImpl = (fd, body) => { writeSync(fd, body) }
|
|
1077
|
+
/** Test seam: replaces the write of the lock body on the `O_EXCL` fallback. No argument restores. */
|
|
1078
|
+
export function setLockFallbackWriteForTest(fn) {
|
|
1079
|
+
fallbackWriteImpl = fn ?? ((fd, body) => { writeSync(fd, body) })
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
export async function withInterprocessLock(storePath, fn) {
|
|
1083
|
+
const lockPath = `${storePath}.lock`
|
|
1084
|
+
const dir = dirname(lockPath)
|
|
1085
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
1086
|
+
const deadline = Date.now() + lockWaitMs
|
|
1087
|
+
const token = `${process.pid}.${randomBytes(8).toString('hex')}`
|
|
1088
|
+
liveTokens.add(token)
|
|
1089
|
+
try {
|
|
1090
|
+
return await acquireAndRun(lockPath, token, deadline, fn, storePath)
|
|
1091
|
+
} finally {
|
|
1092
|
+
liveTokens.delete(token)
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
async function acquireAndRun(lockPath, token, deadline, fn, storePath) {
|
|
1097
|
+
const body = `${process.pid}\n${token}\n${Date.now()}\n${PROCESS_NONCE}\n${localDiscriminator ?? ''}\n`
|
|
1098
|
+
const isOurs = (content) => typeof content === 'string' && content.includes(`\n${token}\n`)
|
|
1099
|
+
let wrote = false
|
|
1100
|
+
// Giving up: our file may still be on disk (a failed release, reads that kept failing), so keep
|
|
1101
|
+
// trying to remove it in the background rather than leave it to block everyone else.
|
|
1102
|
+
const timedOut = () => {
|
|
1103
|
+
if (wrote) releaseInBackground(lockPath, isOurs)
|
|
1104
|
+
return new Error('folder trust store is locked by another process')
|
|
1105
|
+
}
|
|
1106
|
+
collectTempFiles(lockPath)
|
|
1107
|
+
for (;;) {
|
|
1108
|
+
try {
|
|
1109
|
+
const how = createLock(lockPath, body, token)
|
|
1110
|
+
wrote = true
|
|
1111
|
+
if (how === 'linked') break
|
|
1112
|
+
// Written in place (the fallback): read it back. A read that fails (a transient Windows
|
|
1113
|
+
// error, a scanner holding the file) is retried; if ownership still cannot be confirmed,
|
|
1114
|
+
// our own just-written file is removed (its token is known) rather than left to block us.
|
|
1115
|
+
let confirmed = false
|
|
1116
|
+
for (let attempt = 0; attempt < 5 && !confirmed; attempt += 1) {
|
|
1117
|
+
const back = ownershipRead(lockPath)
|
|
1118
|
+
// A bounded (10 ms, at most 5 times) synchronous pause: this retry sits between two
|
|
1119
|
+
// synchronous steps of the protocol and must not yield, and the bound keeps the event loop
|
|
1120
|
+
// from being held for more than about 50 ms.
|
|
1121
|
+
if (back === undefined) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10); continue }
|
|
1122
|
+
if (isOurs(back)) confirmed = true
|
|
1123
|
+
break
|
|
1124
|
+
}
|
|
1125
|
+
if (confirmed) break
|
|
1126
|
+
// Only an absent or our own file is removed; an unreadable one is not known to be ours.
|
|
1127
|
+
const now = ownershipRead(lockPath)
|
|
1128
|
+
if (now === null || isOurs(now)) unlinkOwned(lockPath)
|
|
1129
|
+
} catch (err) {
|
|
1130
|
+
if (!isTransientLockError(err)) throw err
|
|
1131
|
+
// Stat before reading: a file replaced in between then fails the identity comparison under the guard.
|
|
1132
|
+
const identity = statLockIdentity(lockPath)
|
|
1133
|
+
const content = ownershipRead(lockPath)
|
|
1134
|
+
if (isOurs(content)) {
|
|
1135
|
+
// Our own file from an earlier pass whose read-back failed: ours to run under.
|
|
1136
|
+
break
|
|
1137
|
+
}
|
|
1138
|
+
// An unreadable lock is judged by its lease alone.
|
|
1139
|
+
const stale = content === undefined ? leaseExpired(lockPath, LOCK_LEASE_MS) : lockIsStale(lockPath, content)
|
|
1140
|
+
if (identity && stale && reclaimStale(lockPath, content, identity)) {
|
|
1141
|
+
// Progress was made; go round again, but never past the deadline.
|
|
1142
|
+
if (Date.now() > deadline) throw timedOut()
|
|
1143
|
+
continue
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (Date.now() > deadline) throw timedOut()
|
|
1147
|
+
await sleep(20)
|
|
1148
|
+
}
|
|
1149
|
+
// The lease: refresh the lock's mtime while we hold it, so a live holder is never judged stale.
|
|
1150
|
+
// Through a descriptor opened on our own file, so a replacement at the path is never refreshed.
|
|
1151
|
+
let fd = null
|
|
1152
|
+
let notOurs = false
|
|
1153
|
+
// Keep a descriptor only for a file that is ours. A failed open or read (a scanner holding the
|
|
1154
|
+
// file, say) is retried on the next beat; a file that is not ours is never refreshed or retried.
|
|
1155
|
+
const openOwn = () => {
|
|
1156
|
+
let opened = null
|
|
1157
|
+
try {
|
|
1158
|
+
opened = openImpl(lockPath, 'r+')
|
|
1159
|
+
if (isOurs(readFileSync(opened, 'utf8'))) { fd = opened; return }
|
|
1160
|
+
notOurs = true
|
|
1161
|
+
} catch { /* retried at the next beat */ }
|
|
1162
|
+
if (opened !== null) { try { closeSync(opened) } catch { /* already closed */ } }
|
|
1163
|
+
}
|
|
1164
|
+
openOwn()
|
|
1165
|
+
const heartbeat = setInterval(() => {
|
|
1166
|
+
try {
|
|
1167
|
+
if (fd === null && !notOurs) openOwn()
|
|
1168
|
+
if (fd !== null) {
|
|
1169
|
+
const t = new Date()
|
|
1170
|
+
futimesImpl(fd, t, t)
|
|
1171
|
+
}
|
|
1172
|
+
} catch { /* the next beat tries again */ }
|
|
1173
|
+
}, LOCK_HEARTBEAT_MS)
|
|
1174
|
+
heartbeat.unref?.()
|
|
1175
|
+
try {
|
|
1176
|
+
return await lockContext.run({ lockPath, token, storePath }, fn)
|
|
1177
|
+
} finally {
|
|
1178
|
+
clearInterval(heartbeat)
|
|
1179
|
+
// Closed before the unlink: an open descriptor can make the unlink fail on Windows.
|
|
1180
|
+
if (fd !== null) { try { closeSync(fd) } catch { /* nothing to release */ } }
|
|
1181
|
+
const back = ownershipRead(lockPath)
|
|
1182
|
+
if (back === undefined) releaseInBackground(lockPath, isOurs)
|
|
1183
|
+
else if (isOurs(back) && !unlinkOwned(lockPath)) releaseInBackground(lockPath, isOurs)
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
function withStoreLock(storePath, fn) {
|
|
1188
|
+
return withTrustStoreLock(storePath, () => withInterprocessLock(storePath, fn))
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
// ── Cache (display only) ─────────────────────────────────────────────────
|
|
1192
|
+
|
|
1193
|
+
const scanCache = new Map()
|
|
1194
|
+
let cacheGeneration = 0
|
|
1195
|
+
|
|
1196
|
+
/** Drop every cached scan. Called on any trust change so it takes effect at once. */
|
|
1197
|
+
export function invalidateFolderTrustCache() {
|
|
1198
|
+
cacheGeneration += 1
|
|
1199
|
+
inflight.clear()
|
|
1200
|
+
scanCache.clear()
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
const freshHit = (realPath) => {
|
|
1204
|
+
const hit = scanCache.get(realPath)
|
|
1205
|
+
return hit && Date.now() - hit.at <= SCAN_CACHE_TTL_MS ? hit.scan : null
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
function scanCached(cwd, useCache) {
|
|
1209
|
+
if (useCache) {
|
|
1210
|
+
const r = resolveRealPath(cwd)
|
|
1211
|
+
const hit = r.error ? null : freshHit(r.path)
|
|
1212
|
+
if (hit) return hit
|
|
1213
|
+
}
|
|
1214
|
+
// A launch decision never reads the cache; its scan does feed it for display callers.
|
|
1215
|
+
const scan = scanFolderSettings(cwd, DISPLAY_LIMITS)
|
|
1216
|
+
scanCache.set(scan.realPath, { at: Date.now(), scan })
|
|
1217
|
+
return scan
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1220
|
+
// ── Off-thread scans ─────────────────────────────────────────────────────
|
|
1221
|
+
//
|
|
1222
|
+
// Two lanes, each with its own worker thread and one scan at a time: `display`
|
|
1223
|
+
// (cacheable, shared per folder) and `launch` (a fresh scan per decision, never
|
|
1224
|
+
// cached or shared). A scan that does not answer within WORKER_SCAN_TIMEOUT_MS has
|
|
1225
|
+
// its worker terminated; the next request gets a fresh worker.
|
|
1226
|
+
|
|
1227
|
+
/** Longest one off-thread scan may run before its worker is terminated. */
|
|
1228
|
+
export const WORKER_SCAN_TIMEOUT_MS = 5000
|
|
1229
|
+
|
|
1230
|
+
let workerUrl = new URL('./folder-trust-worker.js', import.meta.url)
|
|
1231
|
+
let workerTimeoutMs = WORKER_SCAN_TIMEOUT_MS
|
|
1232
|
+
let workerFactory = null
|
|
1233
|
+
/** Test seam: the worker script, the per-scan timeout (a number, or a function of the folder), and a factory standing in for `new Worker`. No argument restores. */
|
|
1234
|
+
export function setWorkerForTest({ url, timeoutMs, factory } = {}) {
|
|
1235
|
+
workerUrl = url ?? new URL('./folder-trust-worker.js', import.meta.url)
|
|
1236
|
+
workerTimeoutMs = timeoutMs ?? WORKER_SCAN_TIMEOUT_MS
|
|
1237
|
+
workerFactory = factory ?? null
|
|
1238
|
+
for (const lane of [displayLane, launchLane]) {
|
|
1239
|
+
const rec = lane.rec
|
|
1240
|
+
lane.rec = null
|
|
1241
|
+
if (rec) {
|
|
1242
|
+
rec.w.terminate().catch(() => {})
|
|
1243
|
+
settleActive(rec, new Error('scan worker replaced'))
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
const START_FAILURES = new Set(['ERR_MODULE_NOT_FOUND', 'ERR_WORKER_PATH', 'ERR_WORKER_INIT_FAILED', 'ERR_WORKER_UNSUPPORTED_OPERATION'])
|
|
1249
|
+
const workerError = (code, message) => Object.assign(new Error(message), { code })
|
|
1250
|
+
|
|
1251
|
+
const newLane = () => ({ rec: null, queue: [] })
|
|
1252
|
+
const displayLane = newLane()
|
|
1253
|
+
const launchLane = newLane()
|
|
1254
|
+
|
|
1255
|
+
let workerScans = 0
|
|
1256
|
+
/** Test seam: how many scans have been handed to a worker. */
|
|
1257
|
+
export function workerScanCountForTest() {
|
|
1258
|
+
return workerScans
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/** Settle the request a worker record is running, once. */
|
|
1262
|
+
function settleActive(rec, err, scan) {
|
|
1263
|
+
const req = rec.active
|
|
1264
|
+
if (!req) return
|
|
1265
|
+
rec.active = null
|
|
1266
|
+
clearTimeout(req.timer)
|
|
1267
|
+
if (err) req.reject(err)
|
|
1268
|
+
else req.resolve(scan)
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/**
|
|
1272
|
+
* A worker record has stopped (error, exit, timeout). It rejects ITS OWN request
|
|
1273
|
+
* only, and replaces the lane's worker only if it is still the lane's current one:
|
|
1274
|
+
* a late event from an older worker cannot touch its replacement.
|
|
1275
|
+
*/
|
|
1276
|
+
function retire(lane, rec, err) {
|
|
1277
|
+
if (lane.rec === rec) lane.rec = null
|
|
1278
|
+
settleActive(rec, err)
|
|
1279
|
+
pump(lane)
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
function startWorker(lane) {
|
|
1283
|
+
const w = workerFactory ? workerFactory() : new Worker(workerUrl, { env: SHARE_ENV })
|
|
1284
|
+
const rec = { w, active: null }
|
|
1285
|
+
w.on('message', ({ id, scan }) => {
|
|
1286
|
+
if (!rec.active || rec.active.id !== id) return
|
|
1287
|
+
if (lane.rec === rec) w.unref() // idle: never keeps the process alive
|
|
1288
|
+
settleActive(rec, scan ? null : workerError('WORKER_SCAN_FAILED', 'scan failed'), scan)
|
|
1289
|
+
pump(lane)
|
|
1290
|
+
})
|
|
1291
|
+
// A worker that could not even start (its script cannot be loaded) is "unavailable"; any other
|
|
1292
|
+
// error or exit, after it started, is a crash.
|
|
1293
|
+
w.on('error', (err) => retire(lane, rec, START_FAILURES.has(err?.code) ? workerError('WORKER_UNAVAILABLE', err.message) : err))
|
|
1294
|
+
w.on('exit', () => retire(lane, rec, new Error('scan worker exited')))
|
|
1295
|
+
// After the listeners: adding a 'message' listener would otherwise re-ref the worker's port.
|
|
1296
|
+
w.unref()
|
|
1297
|
+
lane.rec = rec
|
|
1298
|
+
return rec
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
let nextId = 1
|
|
1302
|
+
/** Hand the next queued request to the lane's worker when it is idle. */
|
|
1303
|
+
function pump(lane) {
|
|
1304
|
+
if (lane.queue.length === 0) return
|
|
1305
|
+
if (lane.rec?.active) return
|
|
1306
|
+
let rec = lane.rec
|
|
1307
|
+
const req = lane.queue.shift()
|
|
1308
|
+
try {
|
|
1309
|
+
rec ??= startWorker(lane)
|
|
1310
|
+
} catch (err) {
|
|
1311
|
+
req.reject(workerError('WORKER_UNAVAILABLE', err?.message || 'scan worker could not be created'))
|
|
1312
|
+
pump(lane)
|
|
1313
|
+
return
|
|
1314
|
+
}
|
|
1315
|
+
workerScans += 1
|
|
1316
|
+
rec.active = req
|
|
1317
|
+
req.id = nextId++
|
|
1318
|
+
const timeoutMs = typeof workerTimeoutMs === 'function' ? workerTimeoutMs(req.cwd) : workerTimeoutMs
|
|
1319
|
+
req.timer = setTimeout(() => {
|
|
1320
|
+
// Only this worker is stopped; whatever is queued behind runs on a fresh one.
|
|
1321
|
+
rec.w.terminate().catch(() => {})
|
|
1322
|
+
retire(lane, rec, workerError('WORKER_TIMEOUT', 'scan timed out'))
|
|
1323
|
+
}, timeoutMs)
|
|
1324
|
+
rec.w.ref() // a scan in flight keeps the process alive until it answers
|
|
1325
|
+
rec.w.postMessage({ id: req.id, cwd: req.cwd, limits: req.limits })
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Run one scan in the lane's worker. Rejects with `code` WORKER_TIMEOUT when it does
|
|
1330
|
+
* not answer in time, WORKER_SCAN_FAILED when the scan itself failed, otherwise (the
|
|
1331
|
+
* worker could not be created, or died) with a plain error.
|
|
1332
|
+
*/
|
|
1333
|
+
function scanInWorker(lane, cwd, limits) {
|
|
1334
|
+
return new Promise((resolve, reject) => {
|
|
1335
|
+
lane.queue.push({ cwd, limits, resolve, reject, id: 0, timer: null })
|
|
1336
|
+
pump(lane)
|
|
1337
|
+
})
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
/** What a display caller sees for a scan that timed out: not reviewable, never trusted. */
|
|
1341
|
+
function incompleteScan(cwd, why, timedOut = true) {
|
|
1342
|
+
const files = []
|
|
1343
|
+
return {
|
|
1344
|
+
realPath: resolveRealPath(cwd).path,
|
|
1345
|
+
files,
|
|
1346
|
+
digest: sha256Hex(canonicalJson(files)),
|
|
1347
|
+
summary: {
|
|
1348
|
+
files: [], mcpServers: [], hooks: [], statusLine: [], enabledPlugins: [],
|
|
1349
|
+
counts: { agents: 0, skills: 0, commands: 0 },
|
|
1350
|
+
warnings: [why], hasCommandBearingFiles: false, untrustable: true,
|
|
1351
|
+
},
|
|
1352
|
+
hasCommandBearingFiles: false,
|
|
1353
|
+
hardIncomplete: true,
|
|
1354
|
+
// The scan did not answer in time: the folder was not reviewed, which says nothing
|
|
1355
|
+
// about whether it changed. Display only.
|
|
1356
|
+
timedOut,
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
const inflight = new Map()
|
|
1361
|
+
|
|
1362
|
+
/**
|
|
1363
|
+
* Scan for DISPLAY without blocking the main thread: a fresh cached scan, else one
|
|
1364
|
+
* run in a worker thread (the in-thread scan only if the worker is unavailable or
|
|
1365
|
+
* died; a scan that TIMED OUT is shown as not reviewable, never re-run here).
|
|
1366
|
+
* Concurrent requests for one folder share one scan. Any result, an incomplete one
|
|
1367
|
+
* included, is cached for SCAN_CACHE_TTL_MS. Never used for a launch decision.
|
|
1368
|
+
*/
|
|
1369
|
+
async function scanForDisplay(cwd) {
|
|
1370
|
+
const r = resolveRealPath(cwd)
|
|
1371
|
+
const hit = r.error ? null : freshHit(r.path)
|
|
1372
|
+
if (hit) return hit
|
|
1373
|
+
let pendingScan = inflight.get(r.path)
|
|
1374
|
+
if (!pendingScan) {
|
|
1375
|
+
const generation = cacheGeneration
|
|
1376
|
+
const promise = scanInWorker(displayLane, cwd, DISPLAY_LIMITS)
|
|
1377
|
+
.catch((err) => (err?.code === 'WORKER_TIMEOUT'
|
|
1378
|
+
? incompleteScan(cwd, 'This folder is too large to review (the search took too long)')
|
|
1379
|
+
: scanFolderSettings(cwd, DISPLAY_LIMITS)))
|
|
1380
|
+
.then((scan) => {
|
|
1381
|
+
// A trust change while this ran invalidated the cache: do not store a stale scan.
|
|
1382
|
+
if (generation === cacheGeneration) scanCache.set(scan.realPath, { at: Date.now(), scan })
|
|
1383
|
+
return scan
|
|
1384
|
+
})
|
|
1385
|
+
.finally(() => { if (inflight.get(r.path) === promise) inflight.delete(r.path) })
|
|
1386
|
+
pendingScan = promise
|
|
1387
|
+
inflight.set(r.path, promise)
|
|
1388
|
+
}
|
|
1389
|
+
return pendingScan
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* The trust state of `cwd` for a LAUNCH decision, computed off the main thread: a
|
|
1394
|
+
* fresh scan started now, in the launch lane. It never reads or writes the display
|
|
1395
|
+
* cache and is never shared with another request. A timeout, a failed scan, or a worker
|
|
1396
|
+
* that errored or exited is reported as `untrusted` (fail closed); the in-thread scan
|
|
1397
|
+
* runs only when the worker cannot be created at all, and then with the display budget.
|
|
1398
|
+
* That budget bounds the nested walk, not every synchronous filesystem call: a limit we accept.
|
|
1399
|
+
* @returns {Promise<{ status: 'trusted'|'untrusted', realPath: string, digest: string, summary: object }>}
|
|
1400
|
+
*/
|
|
1401
|
+
export async function getFolderTrustStateForLaunch(cwd) {
|
|
1402
|
+
// A folder with no trust record is untrusted whatever a scan would find: no scan.
|
|
1403
|
+
const real = resolveRealPath(cwd)
|
|
1404
|
+
if (real.error || !loadFolderTrustRecords().some((r) => r.path === real.path)) {
|
|
1405
|
+
const none = incompleteScan(cwd, 'This folder is not trusted', false)
|
|
1406
|
+
return { status: 'untrusted', realPath: none.realPath, digest: none.digest, summary: none.summary }
|
|
1407
|
+
}
|
|
1408
|
+
let scan
|
|
1409
|
+
try {
|
|
1410
|
+
scan = await scanInWorker(launchLane, cwd, {})
|
|
1411
|
+
} catch (err) {
|
|
1412
|
+
if (err?.code === 'WORKER_UNAVAILABLE') {
|
|
1413
|
+
// The worker could not be created at all: scan here, with the display wall-clock
|
|
1414
|
+
// budget so a slow folder is incomplete (untrusted) rather than a stalled daemon.
|
|
1415
|
+
scan = scanFolderSettings(cwd, DISPLAY_LIMITS)
|
|
1416
|
+
} else {
|
|
1417
|
+
// A timeout, a failed scan, or a worker that errored or exited mid-scan: not allowed.
|
|
1418
|
+
scan = incompleteScan(cwd, 'This folder could not be reviewed')
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return { status: statusOf(scan), realPath: scan.realPath, digest: scan.digest, summary: scan.summary }
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/** The trust state of `cwd` for display, computed off-thread. Same shape as getFolderTrustState. */
|
|
1425
|
+
export async function getFolderTrustStateForDisplay(cwd) {
|
|
1426
|
+
const scan = await scanForDisplay(cwd)
|
|
1427
|
+
return {
|
|
1428
|
+
status: statusOf(scan), realPath: scan.realPath, digest: scan.digest, summary: scan.summary,
|
|
1429
|
+
...(scan.timedOut ? { timedOut: true } : {}),
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
/**
|
|
1434
|
+
* The state if a fresh scan is cached, else null (and a worker scan is started to
|
|
1435
|
+
* warm the cache). For emitters that must answer synchronously.
|
|
1436
|
+
*/
|
|
1437
|
+
export function getFolderTrustStateIfCached(cwd) {
|
|
1438
|
+
const r = resolveRealPath(cwd)
|
|
1439
|
+
const hit = r.error ? null : freshHit(r.path)
|
|
1440
|
+
if (hit) {
|
|
1441
|
+
return {
|
|
1442
|
+
status: statusOf(hit), realPath: hit.realPath, digest: hit.digest, summary: hit.summary,
|
|
1443
|
+
...(hit.timedOut ? { timedOut: true } : {}),
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
scanForDisplay(cwd).catch(() => {})
|
|
1447
|
+
return null
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function statusOf(scan) {
|
|
1451
|
+
// An incomplete scan never reads as trusted.
|
|
1452
|
+
if (scan.hardIncomplete) return 'untrusted'
|
|
1453
|
+
const record = loadFolderTrustRecords().find((r) => r.path === scan.realPath)
|
|
1454
|
+
return record && record.digest === scan.digest ? 'trusted' : 'untrusted'
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
/**
|
|
1458
|
+
* The trust state of `cwd`: `trusted` (a record matches the real path AND the
|
|
1459
|
+
* current digest) or `untrusted`. Nothing loads without `trusted`.
|
|
1460
|
+
*
|
|
1461
|
+
* @param {string} cwd
|
|
1462
|
+
* @param {{ cached?: boolean }} [opts] - `cached` reuses a scan up to 2 s old (display only)
|
|
1463
|
+
* @returns {{ status: 'trusted'|'untrusted', realPath: string, digest: string, summary: object }}
|
|
1464
|
+
*/
|
|
1465
|
+
export function getFolderTrustState(cwd, { cached = false } = {}) {
|
|
1466
|
+
const scan = scanCached(cwd, cached)
|
|
1467
|
+
return { status: statusOf(scan), realPath: scan.realPath, digest: scan.digest, summary: scan.summary }
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
/** True only when a record matches the current real path and digest. */
|
|
1471
|
+
export function isFolderTrusted(cwd, opts) {
|
|
1472
|
+
if (typeof cwd !== 'string' || cwd === '') return false
|
|
1473
|
+
return getFolderTrustState(cwd, opts).status === 'trusted'
|
|
1474
|
+
}
|
|
1475
|
+
|
|
1476
|
+
/**
|
|
1477
|
+
* Record trust for the folder's CURRENT settings, but only if they are still the
|
|
1478
|
+
* ones the owner reviewed (`expectedDigest`). Returns the new state, or
|
|
1479
|
+
* `{ ok: false, code, error }`.
|
|
1480
|
+
*
|
|
1481
|
+
* @param {string} cwd
|
|
1482
|
+
* @param {string} expectedDigest - the digest of the summary the owner saw
|
|
1483
|
+
*/
|
|
1484
|
+
export async function trustFolder(cwd, expectedDigest) {
|
|
1485
|
+
if (typeof cwd !== 'string' || cwd === '') return { ok: false, status: 'untrusted', code: 'FOLDER_TRUST_NOT_APPLIED', error: 'no folder' }
|
|
1486
|
+
return withStoreLock(folderTrustStorePath(), async () => {
|
|
1487
|
+
const scan = scanFolderSettings(cwd, DISPLAY_LIMITS)
|
|
1488
|
+
const base = { realPath: scan.realPath, digest: scan.digest, summary: scan.summary }
|
|
1489
|
+
if (scan.hardIncomplete) {
|
|
1490
|
+
return { ok: false, status: 'untrusted', ...base, code: 'FOLDER_TRUST_UNTRUSTABLE', error: 'This folder could not be fully reviewed' }
|
|
1491
|
+
}
|
|
1492
|
+
if (typeof expectedDigest !== 'string' || expectedDigest !== scan.digest) {
|
|
1493
|
+
return { ok: false, status: statusOf(scan), ...base, code: 'FOLDER_TRUST_CHANGED', error: 'The folder changed since it was reviewed' }
|
|
1494
|
+
}
|
|
1495
|
+
const records = loadFolderTrustRecords().filter((r) => r.path !== scan.realPath)
|
|
1496
|
+
records.push({
|
|
1497
|
+
v: FOLDER_TRUST_RECORD_VERSION,
|
|
1498
|
+
path: scan.realPath,
|
|
1499
|
+
digest: scan.digest,
|
|
1500
|
+
files: scan.files,
|
|
1501
|
+
trustedAt: new Date().toISOString(),
|
|
1502
|
+
})
|
|
1503
|
+
try {
|
|
1504
|
+
saveFolderTrustRecords(records)
|
|
1505
|
+
} finally {
|
|
1506
|
+
invalidateFolderTrustCache()
|
|
1507
|
+
}
|
|
1508
|
+
return { ok: true, status: 'trusted', ...base }
|
|
1509
|
+
})
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/** Remove any trust record for the folder. */
|
|
1513
|
+
export async function untrustFolder(cwd) {
|
|
1514
|
+
if (typeof cwd !== 'string' || cwd === '') return { ok: false, status: 'untrusted', code: 'FOLDER_TRUST_NOT_APPLIED', error: 'no folder' }
|
|
1515
|
+
return withStoreLock(folderTrustStorePath(), async () => {
|
|
1516
|
+
const rp = resolveRealPath(cwd)
|
|
1517
|
+
if (rp.error) return { ok: false, status: 'untrusted', code: 'FOLDER_TRUST_NOT_APPLIED', error: 'The folder could not be resolved' }
|
|
1518
|
+
const realPath = rp.path
|
|
1519
|
+
const before = loadFolderTrustRecords()
|
|
1520
|
+
const after = before.filter((r) => r.path !== realPath)
|
|
1521
|
+
try {
|
|
1522
|
+
if (after.length !== before.length) saveFolderTrustRecords(after)
|
|
1523
|
+
} finally {
|
|
1524
|
+
invalidateFolderTrustCache()
|
|
1525
|
+
}
|
|
1526
|
+
// No record remains for this path, so it is untrusted without a scan; whoever needs the
|
|
1527
|
+
// folder's summary gets it from a display (worker) scan.
|
|
1528
|
+
return { ok: true, status: 'untrusted', realPath }
|
|
1529
|
+
})
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/**
|
|
1533
|
+
* The text of `<folder>/.claude/settings.json` if, and only if, (1) the folder is
|
|
1534
|
+
* currently trusted (a record matches its real path and its CURRENT full digest, and
|
|
1535
|
+
* the scan is complete) and (2) this file's bytes hash to exactly what the record
|
|
1536
|
+
* holds. Read once; the caller parses and acts on these same bytes.
|
|
1537
|
+
*
|
|
1538
|
+
* The folder-level part (1) uses the scan cache, so after the owner stops trusting
|
|
1539
|
+
* a folder, or a file elsewhere in it changes, the status line can keep running a
|
|
1540
|
+
* file that still matches its record for up to SCAN_CACHE_TTL_MS (2 s). Trust and
|
|
1541
|
+
* untrust invalidate the cache at once. The file hash (2) is never cached.
|
|
1542
|
+
*
|
|
1543
|
+
* @param {string} cwd
|
|
1544
|
+
* @returns {string|null}
|
|
1545
|
+
*/
|
|
1546
|
+
export function readTrustedProjectSettings(cwd) {
|
|
1547
|
+
if (typeof cwd !== 'string' || cwd === '') return null
|
|
1548
|
+
const rp = resolveRealPath(cwd)
|
|
1549
|
+
if (rp.error) return null
|
|
1550
|
+
const state = getFolderTrustState(cwd, { cached: true })
|
|
1551
|
+
if (state.status !== 'trusted') return null
|
|
1552
|
+
const record = loadFolderTrustRecords().find((r) => r.path === rp.path)
|
|
1553
|
+
if (!record) return null
|
|
1554
|
+
const target = join(rp.path, '.claude', 'settings.json')
|
|
1555
|
+
const want = record.files.find((f) => f.path === target)?.sha256
|
|
1556
|
+
if (!want) return null
|
|
1557
|
+
const r = readRegular(target, newScan())
|
|
1558
|
+
if (!r || r.hard) return null
|
|
1559
|
+
return sha256Buf(r.buf) === want ? r.buf.toString('utf8') : null
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
/**
|
|
1563
|
+
* The trust status and real path to report after a change failed. A folder with no
|
|
1564
|
+
* record is untrusted without a scan; a recorded one is read from a display (worker) scan.
|
|
1565
|
+
* @returns {Promise<{ status: 'trusted'|'untrusted', realPath: string }>}
|
|
1566
|
+
*/
|
|
1567
|
+
export async function getFolderTrustStatusForReply(cwd) {
|
|
1568
|
+
const r = resolveRealPath(cwd)
|
|
1569
|
+
if (r.error || !loadFolderTrustRecords().some((rec) => rec.path === r.path)) return { status: 'untrusted', realPath: r.path }
|
|
1570
|
+
const state = await getFolderTrustStateForDisplay(cwd)
|
|
1571
|
+
return { status: state.status, realPath: state.realPath }
|
|
1572
|
+
}
|