@chroxy/server 0.10.0 → 0.11.10
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 +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- 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 +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- 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 +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- 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 +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- 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-stream-parser.js +109 -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 +223 -60
- 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 +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -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 +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- 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 +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- 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 +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- 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 +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- 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 +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- 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 +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -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 +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -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 +100 -10
- 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 +82 -12
- 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 +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- 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 +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- 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-title.js +168 -0
- package/src/session-token-store.js +70 -36
- 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 +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- 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/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -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 +301 -0
- package/src/utils/composite-key.js +45 -0
- 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/iso-datetime.js +51 -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/preflight.js +485 -29
- 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 +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- 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
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* claudeConfigDir: the ONE place chroxy decides where claude keeps its data
|
|
3
|
+
* (#8270): `projects/<slug>/<id>.jsonl` transcripts, `sessions/<pid>.json`,
|
|
4
|
+
* `commands/`, `agents/`, `CLAUDE.md`, per-project memory.
|
|
5
|
+
*
|
|
6
|
+
* claude honours `CLAUDE_CONFIG_DIR` from ITS environment and writes under it
|
|
7
|
+
* instead of `~/.claude`, so a chroxy that joins `homedir()` + `.claude`
|
|
8
|
+
* looks for files that were never written there.
|
|
9
|
+
*
|
|
10
|
+
* Whose env: the DAEMON's (`process.env`) by default. A caller that holds the
|
|
11
|
+
* exact env a child is spawned with passes it.
|
|
12
|
+
*
|
|
13
|
+
* One policy for readers and the claude child: the child env is passed through
|
|
14
|
+
* {@link sanitizeClaudeConfigDirEnv}, which drops a value this module would not
|
|
15
|
+
* accept. Both sides then use `~/.claude` for it, so chroxy never reads a tree
|
|
16
|
+
* claude is not writing.
|
|
17
|
+
*
|
|
18
|
+
* Accepted spelling (exactly as written, no trimming):
|
|
19
|
+
* - a string, no NUL byte, an absolute path
|
|
20
|
+
* - not the filesystem root, and not a path that RESOLVES to the filesystem
|
|
21
|
+
* root once symlinks are followed (the canonical value is what counts)
|
|
22
|
+
* Anything else (unset, empty, padded with whitespace, relative, `~/x`, root,
|
|
23
|
+
* a symlink alias of the root) falls back to `~/.claude`.
|
|
24
|
+
*
|
|
25
|
+
* The result is the CANONICAL path (symlinks resolved through the deepest
|
|
26
|
+
* existing ancestor), so it is safe to use directly as a containment root. If
|
|
27
|
+
* the path cannot be resolved it is treated as unusable and the default is used.
|
|
28
|
+
*
|
|
29
|
+
* This is claude's data dir only. chroxy's own `~/.chroxy` / `CHROXY_CONFIG_DIR`
|
|
30
|
+
* are unrelated and untouched.
|
|
31
|
+
*/
|
|
32
|
+
import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs'
|
|
33
|
+
import { homedir, userInfo } from 'node:os'
|
|
34
|
+
import { basename, dirname, isAbsolute, join, parse, resolve } from 'node:path'
|
|
35
|
+
import { createLogger } from '../logger.js'
|
|
36
|
+
|
|
37
|
+
const log = createLogger('claude-config-dir')
|
|
38
|
+
|
|
39
|
+
/** The env key `os.homedir()` reads: `USERPROFILE` on Windows, `HOME` elsewhere. */
|
|
40
|
+
function homeEnvKey(platform) {
|
|
41
|
+
return platform === 'win32' ? 'USERPROFILE' : 'HOME'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The acceptance policy for a home value taken from an env, mirroring what Node's
|
|
46
|
+
* `os.homedir()` accepts: a string that is non-empty, has no NUL and is absolute.
|
|
47
|
+
* `/` is allowed (containers and service users run with `HOME=/`, and claude
|
|
48
|
+
* itself would use it); the root/canonical checks apply only to the
|
|
49
|
+
* `CLAUDE_CONFIG_DIR` override, where containment matters. Returns the value as
|
|
50
|
+
* written, or null.
|
|
51
|
+
* @param {unknown} raw
|
|
52
|
+
* @returns {string|null}
|
|
53
|
+
*/
|
|
54
|
+
export function acceptClaudeHome(raw) {
|
|
55
|
+
return typeof raw === 'string' && raw !== '' && !raw.includes('\0') && isAbsolute(raw) ? raw : null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The home a child resolves when its env carries no accepted home value: the
|
|
59
|
+
// account's passwd entry (win32: os.homedir(), which reads the profile API).
|
|
60
|
+
function accountHomeDir(platform) {
|
|
61
|
+
if (platform !== 'win32') {
|
|
62
|
+
try {
|
|
63
|
+
const h = userInfo().homedir
|
|
64
|
+
if (acceptClaudeHome(h) !== null) return h
|
|
65
|
+
} catch {
|
|
66
|
+
// no passwd entry: os.homedir() below
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return homedir()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The home directory claude resolves for the process that runs with `env`: the
|
|
74
|
+
* env's `HOME` (`USERPROFILE` on Windows, never `HOME` there), the same value
|
|
75
|
+
* `os.homedir()` returns inside that child. When the env carries no accepted
|
|
76
|
+
* home, the account's passwd home (`os.userInfo().homedir`; on win32
|
|
77
|
+
* `os.homedir()`) is used. The child-env sanitiser removes the same unusable
|
|
78
|
+
* value, and a child with no HOME resolves that same passwd home (#8974).
|
|
79
|
+
* @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env]
|
|
80
|
+
* @param {NodeJS.Platform} [platform]
|
|
81
|
+
* @returns {string}
|
|
82
|
+
*/
|
|
83
|
+
export function claudeHomeDir(env = process.env, platform = process.platform) {
|
|
84
|
+
return acceptClaudeHome(env?.[homeEnvKey(platform)]) ?? accountHomeDir(platform)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** claude's default data dir, `<home>/.claude`. */
|
|
88
|
+
export function defaultClaudeConfigDir(env = process.env) {
|
|
89
|
+
return join(claudeHomeDir(env), '.claude')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function isSymlink(p) {
|
|
93
|
+
try {
|
|
94
|
+
return lstatSync(p).isSymbolicLink()
|
|
95
|
+
} catch {
|
|
96
|
+
return false
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a
|
|
101
|
+
// config dir claude has not created yet is still canonicalised.
|
|
102
|
+
function canonicalize(absPath) {
|
|
103
|
+
let current = absPath
|
|
104
|
+
const tail = []
|
|
105
|
+
for (;;) {
|
|
106
|
+
try {
|
|
107
|
+
const real = realpathSync.native(current)
|
|
108
|
+
return tail.length ? join(real, ...tail.reverse()) : real
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR') throw err
|
|
111
|
+
// A component that IS a symlink whose target is missing (dangling) is not
|
|
112
|
+
// "a directory that does not exist yet": following its text could land
|
|
113
|
+
// anywhere. Treat the whole value as unusable instead of walking past it.
|
|
114
|
+
if (isSymlink(current)) throw err
|
|
115
|
+
const parent = dirname(current)
|
|
116
|
+
if (parent === current) throw err
|
|
117
|
+
tail.push(basename(current))
|
|
118
|
+
current = parent
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The canonical config dir for an override spelling, or null when the spelling
|
|
125
|
+
* is not accepted (see the module comment).
|
|
126
|
+
* @param {unknown} raw
|
|
127
|
+
* @returns {string|null}
|
|
128
|
+
*/
|
|
129
|
+
export function resolveClaudeConfigDirOverride(raw) {
|
|
130
|
+
if (typeof raw !== 'string' || raw === '' || raw.includes('\0') || !isAbsolute(raw)) return null
|
|
131
|
+
const normalised = resolve(raw)
|
|
132
|
+
if (normalised === parse(normalised).root) return null
|
|
133
|
+
let canonical
|
|
134
|
+
try {
|
|
135
|
+
canonical = canonicalize(normalised)
|
|
136
|
+
} catch {
|
|
137
|
+
return null
|
|
138
|
+
}
|
|
139
|
+
if (canonical === parse(canonical).root) return null
|
|
140
|
+
return canonical
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env] - env claude runs with
|
|
145
|
+
* @returns {string} absolute, canonical path to claude's config dir
|
|
146
|
+
*/
|
|
147
|
+
export function claudeConfigDir(env = process.env) {
|
|
148
|
+
return resolveClaudeConfigDirOverride(env?.CLAUDE_CONFIG_DIR) ?? defaultClaudeConfigDir(env)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** `<claude config dir>/projects`. */
|
|
152
|
+
export function claudeProjectsDir(env = process.env) {
|
|
153
|
+
return join(claudeConfigDir(env), 'projects')
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* claude's global config file (OAuth account metadata, user and per-project MCP
|
|
158
|
+
* servers, workspace trust). claude picks ONE active file:
|
|
159
|
+
* 1. `<config dir>/.config.json` when it is a regular file that is non-empty,
|
|
160
|
+
* or empty and writable while the modern file does not exist (legacy name);
|
|
161
|
+
* 2. otherwise `join(CLAUDE_CONFIG_DIR || home, '.claude.json')` — directly in
|
|
162
|
+
* the override dir, but in the HOME directory (not `~/.claude/`) by default.
|
|
163
|
+
* This returns that same file, so a reader and a writer never use a different one
|
|
164
|
+
* than claude does (#8974). The override goes through the same acceptance policy
|
|
165
|
+
* as {@link claudeConfigDir}; home comes from the env (see {@link claudeHomeDir}).
|
|
166
|
+
* @param {Record<string, unknown> | NodeJS.ProcessEnv | null | undefined} [env] - env claude runs with
|
|
167
|
+
* @returns {string} absolute path
|
|
168
|
+
*/
|
|
169
|
+
export function claudeGlobalConfigPath(env = process.env) {
|
|
170
|
+
const override = resolveClaudeConfigDirOverride(env?.CLAUDE_CONFIG_DIR)
|
|
171
|
+
const modern = join(override ?? claudeHomeDir(env), '.claude.json')
|
|
172
|
+
const legacy = join(claudeConfigDir(env), '.config.json')
|
|
173
|
+
try {
|
|
174
|
+
// Exactly claude's rule: a regular legacy file that is non-empty, or that is
|
|
175
|
+
// empty but writable while no modern file exists. A directory never qualifies.
|
|
176
|
+
const st = statSync(legacy)
|
|
177
|
+
if (st.isFile() && (st.size > 0 || ((st.mode & 0o222) !== 0 && !existsSync(modern)))) return legacy
|
|
178
|
+
} catch {
|
|
179
|
+
// absent / unreadable: not the active file
|
|
180
|
+
}
|
|
181
|
+
return modern
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Parse the text of claude's global config. Empty or whitespace-only content
|
|
186
|
+
* (a freshly created file) is `{}`; anything else is parsed strictly and a
|
|
187
|
+
* malformed non-empty file still throws, so a corrupt file is never clobbered.
|
|
188
|
+
* @param {string} text
|
|
189
|
+
* @returns {any}
|
|
190
|
+
*/
|
|
191
|
+
export function parseClaudeConfigText(text) {
|
|
192
|
+
return text.trim() === '' ? {} : JSON.parse(text)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const warned = new Set()
|
|
196
|
+
|
|
197
|
+
/** Is `p` a filesystem root (`/`, `C:\`)? For use sites that install a resolved dir as a containment root. */
|
|
198
|
+
export function isFilesystemRoot(p) {
|
|
199
|
+
return typeof p === 'string' && p !== '' && parse(p).root === p
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Startup check: warn once (constant text, no path) when `CLAUDE_CONFIG_DIR` is
|
|
204
|
+
* set but not usable. Does not modify `env`.
|
|
205
|
+
* @param {Record<string, unknown>} [env]
|
|
206
|
+
* @returns {boolean} true when a warning was due
|
|
207
|
+
*/
|
|
208
|
+
export function warnIfClaudeConfigDirUnusable(env = process.env) {
|
|
209
|
+
if (env?.CLAUDE_CONFIG_DIR === undefined) return false
|
|
210
|
+
const before = Object.hasOwn(env, 'CLAUDE_CONFIG_DIR')
|
|
211
|
+
const copy = sanitizeClaudeConfigDirEnv({ CLAUDE_CONFIG_DIR: env.CLAUDE_CONFIG_DIR })
|
|
212
|
+
return before && !Object.hasOwn(copy, 'CLAUDE_CONFIG_DIR')
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Make a claude child env agree with {@link claudeConfigDir}: when the env
|
|
217
|
+
* carries a `CLAUDE_CONFIG_DIR` the resolver would reject, remove it (one
|
|
218
|
+
* warning per distinct value) so claude falls back to `~/.claude` as chroxy does.
|
|
219
|
+
* An unusable home value (HOME, or USERPROFILE on Windows) is removed the same way.
|
|
220
|
+
* Mutates and returns `env`.
|
|
221
|
+
* @param {Record<string, unknown>} env
|
|
222
|
+
*/
|
|
223
|
+
export function sanitizeClaudeConfigDirEnv(env, platform = process.platform) {
|
|
224
|
+
if (!env) return env
|
|
225
|
+
// The home value the child's os.homedir() reads: an unusable one is removed so
|
|
226
|
+
// the child falls back to the account's passwd home, the same account the
|
|
227
|
+
// daemon's claudeHomeDir() fallback names (#8974).
|
|
228
|
+
const homeKey = homeEnvKey(platform)
|
|
229
|
+
if (Object.hasOwn(env, homeKey) && env[homeKey] !== undefined && acceptClaudeHome(env[homeKey]) === null) {
|
|
230
|
+
if (!warned.has(`home:${String(env[homeKey])}`)) {
|
|
231
|
+
warned.add(`home:${String(env[homeKey])}`)
|
|
232
|
+
log.warn('Ignoring an unusable home directory in the claude child env; the account home is used')
|
|
233
|
+
}
|
|
234
|
+
delete env[homeKey]
|
|
235
|
+
}
|
|
236
|
+
if (!Object.hasOwn(env, 'CLAUDE_CONFIG_DIR') || env.CLAUDE_CONFIG_DIR === undefined) return env
|
|
237
|
+
if (resolveClaudeConfigDirOverride(env.CLAUDE_CONFIG_DIR) !== null) return env
|
|
238
|
+
const key = String(env.CLAUDE_CONFIG_DIR)
|
|
239
|
+
if (!warned.has(key)) {
|
|
240
|
+
warned.add(key)
|
|
241
|
+
log.warn('Ignoring CLAUDE_CONFIG_DIR: it must be an absolute path that is not the filesystem root; using ~/.claude')
|
|
242
|
+
}
|
|
243
|
+
delete env.CLAUDE_CONFIG_DIR
|
|
244
|
+
return env
|
|
245
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #8223 — the ONE spelling of the command that signs the `claude` CLI in on a
|
|
3
|
+
* host. The AUTH_REQUIRED messages (claude-tui's in claude-tui/pty-driver.js,
|
|
4
|
+
* claude-sdk's in sdk-session.js), the provider credential hints and the doctor
|
|
5
|
+
* row all tell an operator to run it, and four hand-typed copies were already one
|
|
6
|
+
* edit from disagreeing. claude 2.1.x spells it `auth login`; plain `claude login`
|
|
7
|
+
* is stale.
|
|
8
|
+
*
|
|
9
|
+
* A module of its own, not an export of pty-driver.js, because sdk-session.js needs
|
|
10
|
+
* it and pty-driver.js resolves the claude binary at import time, which the SDK
|
|
11
|
+
* provider must not do. The dashboard and the app read the same string from
|
|
12
|
+
* `@chroxy/store-core` (`CLAUDE_LOGIN_COMMAND`, next to the AUTH_REQUIRED
|
|
13
|
+
* presentation entry); the two packages cannot share a module, so each side keeps
|
|
14
|
+
* exactly one definition.
|
|
15
|
+
*/
|
|
16
|
+
export const CLAUDE_LOGIN_COMMAND = 'claude auth login'
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export const CLAUDE_NATIVE_FIRST_PARTY_BASE_URL = 'https://api.anthropic.com'
|
|
2
|
+
|
|
3
|
+
// Every non-OAuth selector that can move Claude Code away from the direct
|
|
4
|
+
// Claude.ai subscription route. CLAUDE_CODE_OAUTH_TOKEN is deliberately absent:
|
|
5
|
+
// it is a vendor-supported way to supply the same subscription credential that
|
|
6
|
+
// `claude auth status` classifies separately.
|
|
7
|
+
export const CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV = Object.freeze([
|
|
8
|
+
'ANTHROPIC_API_HOST',
|
|
9
|
+
'ANTHROPIC_API_KEY',
|
|
10
|
+
'ANTHROPIC_AUTH_TOKEN',
|
|
11
|
+
'ANTHROPIC_AWS_API_KEY',
|
|
12
|
+
'ANTHROPIC_AWS_BASE_URL',
|
|
13
|
+
'ANTHROPIC_AWS_WORKSPACE_ID',
|
|
14
|
+
'ANTHROPIC_BEDROCK_BASE_URL',
|
|
15
|
+
'ANTHROPIC_BEDROCK_MANTLE_BASE_URL',
|
|
16
|
+
'ANTHROPIC_CUSTOM_HEADERS',
|
|
17
|
+
'ANTHROPIC_FOUNDRY_API_KEY',
|
|
18
|
+
'ANTHROPIC_FOUNDRY_AUTH_TOKEN',
|
|
19
|
+
'ANTHROPIC_FOUNDRY_BASE_URL',
|
|
20
|
+
'ANTHROPIC_FOUNDRY_RESOURCE',
|
|
21
|
+
'ANTHROPIC_GOOGLE_CLOUD_BASE_URL',
|
|
22
|
+
'ANTHROPIC_GOOGLE_CLOUD_LOCATION',
|
|
23
|
+
'ANTHROPIC_GOOGLE_CLOUD_PROJECT',
|
|
24
|
+
'ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID',
|
|
25
|
+
'ANTHROPIC_PROFILE',
|
|
26
|
+
'ANTHROPIC_UNIX_SOCKET',
|
|
27
|
+
'ANTHROPIC_VERTEX_BASE_URL',
|
|
28
|
+
'ANTHROPIC_VERTEX_PROJECT_ID',
|
|
29
|
+
'CLAUDE_CODE_API_BASE_URL',
|
|
30
|
+
'CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR',
|
|
31
|
+
'CLAUDE_CODE_CUSTOM_OAUTH_URL',
|
|
32
|
+
'CLAUDE_CODE_HOST_AUTH_ENV_VAR',
|
|
33
|
+
'CLAUDE_CODE_HOST_CREDS_FILE',
|
|
34
|
+
'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',
|
|
35
|
+
'CLAUDE_CODE_SIMPLE',
|
|
36
|
+
'CLAUDE_CODE_USE_ANTHROPIC_AWS',
|
|
37
|
+
'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
|
|
38
|
+
'CLAUDE_CODE_USE_BEDROCK',
|
|
39
|
+
'CLAUDE_CODE_USE_FOUNDRY',
|
|
40
|
+
'CLAUDE_CODE_USE_GATEWAY',
|
|
41
|
+
'CLAUDE_CODE_USE_MANTLE',
|
|
42
|
+
'CLAUDE_CODE_USE_VERTEX',
|
|
43
|
+
'_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL',
|
|
44
|
+
])
|
|
45
|
+
|
|
46
|
+
function hasValue(value) {
|
|
47
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function buildClaudeNativeRouteEnv(baseEnv = {}) {
|
|
51
|
+
const env = { ...baseEnv }
|
|
52
|
+
for (const key of CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV) delete env[key]
|
|
53
|
+
env.ANTHROPIC_BASE_URL = CLAUDE_NATIVE_FIRST_PARTY_BASE_URL
|
|
54
|
+
return env
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function claudeNativeRouteSettingsEnv() {
|
|
58
|
+
return {
|
|
59
|
+
...Object.fromEntries(CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV.map((key) => [key, ''])),
|
|
60
|
+
ANTHROPIC_BASE_URL: CLAUDE_NATIVE_FIRST_PARTY_BASE_URL,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function observeClaudeNativeRoute(env = {}) {
|
|
65
|
+
let firstPartyEndpoint = false
|
|
66
|
+
try {
|
|
67
|
+
const url = new URL(env.ANTHROPIC_BASE_URL)
|
|
68
|
+
firstPartyEndpoint = url.protocol === 'https:'
|
|
69
|
+
&& url.hostname === 'api.anthropic.com'
|
|
70
|
+
&& (url.port === '' || url.port === '443')
|
|
71
|
+
&& (url.pathname === '' || url.pathname === '/')
|
|
72
|
+
&& url.search === ''
|
|
73
|
+
&& url.hash === ''
|
|
74
|
+
} catch {}
|
|
75
|
+
const blockedKeys = CLAUDE_NATIVE_ROUTE_FORBIDDEN_ENV.filter((key) => hasValue(env[key]))
|
|
76
|
+
return {
|
|
77
|
+
firstPartyEndpoint,
|
|
78
|
+
blockedKeys,
|
|
79
|
+
safe: firstPartyEndpoint && blockedKeys.length === 0,
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { lstatSync, readlinkSync } from 'node:fs'
|
|
2
|
+
import { lstat, readlink } from 'node:fs/promises'
|
|
3
|
+
import path, { dirname, join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* open(2)-faithful, component-by-component path resolver — the SINGLE SOURCE for
|
|
7
|
+
* both security floors that need it:
|
|
8
|
+
* - the SYNCHRONOUS protected-path floor (`permission-manager.js`, #6921), which
|
|
9
|
+
* runs inside the sync `handlePermission` hot-path and cannot await; and
|
|
10
|
+
* - the ASYNC BYOK file-ops confinement (`ws-file-ops/common.js`, #6923), which
|
|
11
|
+
* walks a raw tool-supplied path before a subprocess write.
|
|
12
|
+
*
|
|
13
|
+
* Both were introduced as near-identical twins (a sync copy and an async copy) and
|
|
14
|
+
* PROMPTLY DRIFTED: #6928 was a bug present in BOTH — a `target.split(path.sep)`
|
|
15
|
+
* that, on Windows, left a forward-slash path as ONE component and fell back to a
|
|
16
|
+
* lexical `join()`, reopening the exact `..`-after-symlink escape the walk exists to
|
|
17
|
+
* close. It had to be patched in two places. This module exists so the drift-prone
|
|
18
|
+
* logic — the separator-agnostic split, the per-component lexical classification,
|
|
19
|
+
* and the symlink splice — lives ONCE; the sync and async entry points are thin fs
|
|
20
|
+
* drivers over that shared core, and `componentwise-resolver.test.js` pins them to
|
|
21
|
+
* IDENTICAL results across a battery of on-disk topologies so they cannot diverge
|
|
22
|
+
* again.
|
|
23
|
+
*
|
|
24
|
+
* ---------------------------------------------------------------------------------
|
|
25
|
+
* WHY A COMPONENT WALK (and not `realpath(resolve(base, target))`):
|
|
26
|
+
*
|
|
27
|
+
* BOTH `path.resolve()` AND Node's `fs.realpath` collapse `..` LEXICALLY — textually,
|
|
28
|
+
* before/instead of following symlinks. `realpath('link/..')` yields the symlink's
|
|
29
|
+
* LEXICAL parent; `open(2)` follows `link` to its TARGET and applies `..` from THERE.
|
|
30
|
+
* So `work/agent-x/../../settings.local.json` (with `work -> .claude/worktrees`)
|
|
31
|
+
* lexically cancels to a benign in-cwd `settings.local.json`, but a raw write really
|
|
32
|
+
* lands on `.claude/settings.local.json`. Only a walk that applies `..` AFTER
|
|
33
|
+
* resolving the symlinks so far — as the kernel does — sees the true destination.
|
|
34
|
+
* ---------------------------------------------------------------------------------
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
// #6921/#6923 — symlink-expansion cap, matching the kernel's typical MAXSYMLINKS.
|
|
38
|
+
// A chain deeper than this — or a cycle — THROWS `ELOOP`, which every caller's
|
|
39
|
+
// `catch` treats as protected / rejected (fail closed).
|
|
40
|
+
export const COMPONENTWISE_MAX_SYMLINKS = 40
|
|
41
|
+
|
|
42
|
+
// The most work one walk does: COMPONENTWISE_MAX_COMPONENTS components walked,
|
|
43
|
+
// those a symlink adds included, and a resolved path no longer than
|
|
44
|
+
// COMPONENTWISE_MAX_PATH_LENGTH characters. Past either, the walk THROWS
|
|
45
|
+
// `ENAMETOOLONG`, which every caller treats as a failure (fail closed). Each step
|
|
46
|
+
// builds and stats the full path so far, so these bound the walk's total cost.
|
|
47
|
+
// A real path is far below both: Linux's PATH_MAX is 4096 bytes, and even 40
|
|
48
|
+
// symlinks of a few dozen components each stay under the component bound.
|
|
49
|
+
export const COMPONENTWISE_MAX_COMPONENTS = 1024
|
|
50
|
+
export const COMPONENTWISE_MAX_PATH_LENGTH = 16384
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* #6928 — split a raw path into the components BELOW its parsed root. The
|
|
54
|
+
* separators are the platform's own: `/` and `\` on Windows (Node accepts forward
|
|
55
|
+
* slashes there, so a `sep`-only split would leave a forward-slash path as ONE
|
|
56
|
+
* component and the walk would fall back to a lexical `join()`), but `/` ALONE on
|
|
57
|
+
* POSIX, where `\` is an ordinary filename character — splitting on it would walk
|
|
58
|
+
* a different pathname than the one a consumer opens. `root` (already parsed by the
|
|
59
|
+
* caller, which starts `resolved` there) is sliced off first so a drive/UNC/`/`
|
|
60
|
+
* root is never walked as an ordinary component (a Windows `C:\` would otherwise
|
|
61
|
+
* appear as a `C:` component and `join` straight back onto the drive root).
|
|
62
|
+
* @param {string} p
|
|
63
|
+
* @param {string} root the already-`parse`d root of `p` (`''` for a relative path)
|
|
64
|
+
* @param {typeof import('node:path')} [pathImpl] `path.win32` / `path.posix` to
|
|
65
|
+
* drive the other platform's rules (tests); defaults to the host's `path`
|
|
66
|
+
* @returns {string[]}
|
|
67
|
+
*/
|
|
68
|
+
export function splitPathBelowRoot(p, root, pathImpl = path) {
|
|
69
|
+
const separators = pathImpl.sep === '\\' ? /[/\\]+/ : /\/+/
|
|
70
|
+
return (root ? p.slice(root.length) : p).split(separators)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Where a walk over the raw path `p` starts, and the components below that start.
|
|
75
|
+
* `current` is the real path resolved so far (the session cwd for a target, the
|
|
76
|
+
* link's parent for a link target).
|
|
77
|
+
* - a relative path starts where `current` is (`start` is `''`);
|
|
78
|
+
* - an absolute path starts at its own parsed root;
|
|
79
|
+
* - on Windows, a root-relative path (`\foo` or `/foo`, no drive) starts at the
|
|
80
|
+
* root of `current`'s drive (or share), exactly as `path.win32.resolve(current, p)`
|
|
81
|
+
* places it;
|
|
82
|
+
* - on Windows, a drive-relative path (`C:foo`) depends on that drive's current
|
|
83
|
+
* directory, which cannot be known here, so it throws EINVAL (callers fail
|
|
84
|
+
* closed). So does a root-relative path when `current` has no drive.
|
|
85
|
+
* @param {string} p
|
|
86
|
+
* @param {string} current the real path resolved so far
|
|
87
|
+
* @param {typeof import('node:path')} [pathImpl] `path.win32` / `path.posix` to
|
|
88
|
+
* drive the other platform's rules (tests); defaults to the host's `path`
|
|
89
|
+
* @returns {{ start: string, below: string[] }}
|
|
90
|
+
*/
|
|
91
|
+
export function walkStart(p, current, pathImpl = path) {
|
|
92
|
+
const { root } = pathImpl.parse(p)
|
|
93
|
+
if (pathImpl.sep === '\\') {
|
|
94
|
+
if (/^[A-Za-z]:$/.test(root)) {
|
|
95
|
+
throw Object.assign(new Error('componentwise resolver: a drive-relative path depends on the drive\'s current directory'), { code: 'EINVAL' })
|
|
96
|
+
}
|
|
97
|
+
if (root === '\\' || root === '/') {
|
|
98
|
+
const driveRoot = pathImpl.parse(current).root
|
|
99
|
+
// Only a real drive or a real share (server and share, the server neither `?` nor
|
|
100
|
+
// `.`): the `\\?\` and `\\.\` device namespaces have no drive to anchor to.
|
|
101
|
+
if (!/^[A-Za-z]:[\\/]$/.test(driveRoot) && !/^[\\/]{2}[^\\/?.][^\\/]*[\\/]+[^\\/]+[\\/]?$/.test(driveRoot)) {
|
|
102
|
+
throw Object.assign(new Error('componentwise resolver: a root-relative path has no drive to anchor to'), { code: 'EINVAL' })
|
|
103
|
+
}
|
|
104
|
+
return { start: driveRoot, below: splitPathBelowRoot(p, root, pathImpl) }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const start = pathImpl.isAbsolute(p) ? root : ''
|
|
108
|
+
return { start, below: splitPathBelowRoot(p, start, pathImpl) }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Pure: initialise the walk. An absolute target ignores the base (as `open`/`resolve`
|
|
113
|
+
* do) and starts at its parsed root so its own leading components are walked (and
|
|
114
|
+
* symlink-resolved) too; a relative target (empty root) starts at `realBase`. The
|
|
115
|
+
* root is stripped BEFORE splitting so it is never re-walked as an ordinary
|
|
116
|
+
* component (#6928).
|
|
117
|
+
* @param {string} realBase the session cwd, already resolved to its real path
|
|
118
|
+
* @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
|
|
119
|
+
* @returns {{ resolved: string, pending: string[] }}
|
|
120
|
+
*/
|
|
121
|
+
export function beginWalk(realBase, target, pathImpl = path) {
|
|
122
|
+
const { start, below } = walkStart(target, realBase, pathImpl)
|
|
123
|
+
return { resolved: start || realBase, pending: below }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Pure: resolve a single component AS FAR AS POSSIBLE without touching the
|
|
128
|
+
* filesystem. This is the ordering that must never drift between the sync and async
|
|
129
|
+
* drivers, so it lives here exactly once:
|
|
130
|
+
* - `''` / `.` → skip (resolved unchanged, no stat).
|
|
131
|
+
* - `..` → pop to the PARENT of the resolved-so-far real path (`dirname`),
|
|
132
|
+
* i.e. apply `..` AFTER following symlinks so far — NOT lexically
|
|
133
|
+
* on the pre-resolution path. No stat. When it pops a to-be-created
|
|
134
|
+
* component, the tail shrinks by one; once the tail is empty the
|
|
135
|
+
* resolved path is a directory that exists, and the driver goes
|
|
136
|
+
* back to inspecting each component.
|
|
137
|
+
* - in a tail → once a component was ENOENT, the components after it are a
|
|
138
|
+
* to-be-created tail: append by `join` with no stat.
|
|
139
|
+
* - otherwise → return the `candidate` to lstat; `resolved` is left UNCHANGED
|
|
140
|
+
* (it is committed only after the driver confirms `candidate` is
|
|
141
|
+
* not a symlink).
|
|
142
|
+
* @param {string} resolved resolved-so-far real path
|
|
143
|
+
* @param {string} comp the raw component
|
|
144
|
+
* @param {number} tail how many to-be-created components follow the last
|
|
145
|
+
* existing directory (0 when every component so far was inspected)
|
|
146
|
+
* @returns {{ resolved: string, stat: string|null, tail: number }} `stat` is the
|
|
147
|
+
* path to lstat, or `null` when the component was fully consumed lexically.
|
|
148
|
+
*/
|
|
149
|
+
function resolveComponentLexically(resolved, comp, tail) {
|
|
150
|
+
if (comp === '' || comp === '.') return { resolved, stat: null, tail }
|
|
151
|
+
if (comp === '..') return { resolved: dirname(resolved), stat: null, tail: tail > 0 ? tail - 1 : 0 }
|
|
152
|
+
const candidate = join(resolved, comp)
|
|
153
|
+
if (tail > 0) return { resolved: candidate, stat: null, tail: tail + 1 }
|
|
154
|
+
return { resolved, stat: candidate, tail }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Pure: a symlink was found at the cursor. Splice the link's own components (below
|
|
159
|
+
* its root) into `pending` AT the cursor so they — and any `..` they contain — are
|
|
160
|
+
* walked next, before the tail. Returns the resolved base to continue from: an
|
|
161
|
+
* ABSOLUTE link restarts resolution from its parsed root; a RELATIVE link continues
|
|
162
|
+
* from the symlink's PARENT (`resolved`, since the symlink component itself was not
|
|
163
|
+
* appended). Mutates `pending`.
|
|
164
|
+
* @param {string[]} pending
|
|
165
|
+
* @param {number} i cursor (index of the NEXT component to walk)
|
|
166
|
+
* @param {string} resolved resolved-so-far real path (the symlink's parent)
|
|
167
|
+
* @param {string} link the raw `readlink` target
|
|
168
|
+
* @returns {string}
|
|
169
|
+
*/
|
|
170
|
+
export function spliceSymlink(pending, i, resolved, link, pathImpl = path) {
|
|
171
|
+
// On POSIX `\` is a name character, which the split below would read as a
|
|
172
|
+
// separator; a link whose target holds one is not walked (callers fail closed).
|
|
173
|
+
if (pathImpl.sep === '/' && link.includes('\\')) {
|
|
174
|
+
throw Object.assign(new Error('componentwise resolver: link target holds a backslash'), { code: 'EINVAL' })
|
|
175
|
+
}
|
|
176
|
+
const { start, below } = walkStart(link, resolved, pathImpl)
|
|
177
|
+
pending.splice(i, 0, ...below)
|
|
178
|
+
return start || resolved
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Throw ENAMETOOLONG once a walk has consumed more than
|
|
183
|
+
* COMPONENTWISE_MAX_COMPONENTS components or its resolved path is longer than
|
|
184
|
+
* COMPONENTWISE_MAX_PATH_LENGTH characters. Called before each component and
|
|
185
|
+
* after the last.
|
|
186
|
+
* @param {number} walked components consumed so far, the current one included
|
|
187
|
+
* @param {string} resolved the path resolved so far
|
|
188
|
+
* @param {string} fnName the driver, for the message
|
|
189
|
+
*/
|
|
190
|
+
function checkWalkBounds(walked, resolved, fnName) {
|
|
191
|
+
if (walked > COMPONENTWISE_MAX_COMPONENTS || resolved.length > COMPONENTWISE_MAX_PATH_LENGTH) {
|
|
192
|
+
throw Object.assign(
|
|
193
|
+
new Error(`${fnName}: walk exceeds ${COMPONENTWISE_MAX_COMPONENTS} components or ${COMPONENTWISE_MAX_PATH_LENGTH} characters`),
|
|
194
|
+
{ code: 'ENAMETOOLONG' },
|
|
195
|
+
)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// A caller may share one walk budget across several walks (`{ left: n }`); each
|
|
200
|
+
// component walked spends one, and an exhausted budget fails like a long walk.
|
|
201
|
+
function spendWalkBudget(budget, fnName) {
|
|
202
|
+
if (budget !== undefined && --budget.left < 0) {
|
|
203
|
+
throw Object.assign(new Error(`${fnName}: the shared walk budget is spent`), { code: 'ENAMETOOLONG' })
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function symlinkBudgetError(fnName) {
|
|
208
|
+
return Object.assign(
|
|
209
|
+
new Error(`${fnName}: symlink depth exceeds ${COMPONENTWISE_MAX_SYMLINKS}`),
|
|
210
|
+
{ code: 'ELOOP' },
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* #6921 — SYNC open(2)-faithful resolver (protected-path floor hot-path). A thin
|
|
216
|
+
* `lstatSync`/`readlinkSync` driver over the shared core above. A non-ENOENT
|
|
217
|
+
* `lstat`/`readlink` error (EACCES, ELOOP) PROPAGATES so the caller's `catch` fails
|
|
218
|
+
* closed; ENOENT stops filesystem resolution (nothing deeper can be a symlink) and
|
|
219
|
+
* the remaining tail — INCLUDING any `..` — is applied against the resolved-so-far
|
|
220
|
+
* REAL path by the same pop/append rules.
|
|
221
|
+
* @param {string} realBase the session cwd, already resolved to its real path
|
|
222
|
+
* @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
|
|
223
|
+
* @param {{ left: number }} [budget] a walk budget shared with other walks
|
|
224
|
+
* @returns {string} the open(2)-faithful resolved absolute real path
|
|
225
|
+
*/
|
|
226
|
+
export function resolveTargetComponentwiseSync(realBase, target, budget) {
|
|
227
|
+
const { resolved: base, pending } = beginWalk(realBase, target)
|
|
228
|
+
let resolved = base
|
|
229
|
+
let symlinks = 0
|
|
230
|
+
let tail = 0
|
|
231
|
+
let i = 0
|
|
232
|
+
while (i < pending.length) {
|
|
233
|
+
const comp = pending[i]
|
|
234
|
+
i++
|
|
235
|
+
checkWalkBounds(i, resolved, 'resolveTargetComponentwiseSync')
|
|
236
|
+
spendWalkBudget(budget, 'resolveTargetComponentwiseSync')
|
|
237
|
+
const step = resolveComponentLexically(resolved, comp, tail)
|
|
238
|
+
resolved = step.resolved
|
|
239
|
+
tail = step.tail
|
|
240
|
+
if (step.stat === null) continue
|
|
241
|
+
let st
|
|
242
|
+
try {
|
|
243
|
+
st = lstatSync(step.stat)
|
|
244
|
+
} catch (err) {
|
|
245
|
+
if (err.code === 'ENOENT') { tail = 1; resolved = step.stat; continue }
|
|
246
|
+
throw err // EACCES etc. — fail closed via the caller's catch
|
|
247
|
+
}
|
|
248
|
+
if (st.isSymbolicLink()) {
|
|
249
|
+
if (++symlinks > COMPONENTWISE_MAX_SYMLINKS) throw symlinkBudgetError('resolveTargetComponentwiseSync')
|
|
250
|
+
resolved = spliceSymlink(pending, i, resolved, readlinkSync(step.stat))
|
|
251
|
+
} else {
|
|
252
|
+
resolved = step.stat
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
checkWalkBounds(i, resolved, 'resolveTargetComponentwiseSync')
|
|
256
|
+
return resolved
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* #6923 — ASYNC open(2)-faithful resolver (BYOK file-ops confinement). The async
|
|
261
|
+
* sibling of {@link resolveTargetComponentwiseSync} over the SAME shared core, so
|
|
262
|
+
* the two cannot diverge (pinned by `componentwise-resolver.test.js`). Same
|
|
263
|
+
* fail-closed contract: EACCES/ELOOP propagate; ENOENT applies the remaining tail
|
|
264
|
+
* (including `..`) by pop/append.
|
|
265
|
+
* @param {string} realBase the session cwd, already resolved to its real path
|
|
266
|
+
* @param {string} target a raw (NOT pre-`resolve`d — its `..` must survive) path
|
|
267
|
+
* @param {{ left: number }} [budget] a walk budget shared with other walks
|
|
268
|
+
* @returns {Promise<string>} the open(2)-faithful resolved absolute real path
|
|
269
|
+
*/
|
|
270
|
+
export async function resolveTargetComponentwiseAsync(realBase, target, budget) {
|
|
271
|
+
const { resolved: base, pending } = beginWalk(realBase, target)
|
|
272
|
+
let resolved = base
|
|
273
|
+
let symlinks = 0
|
|
274
|
+
let tail = 0
|
|
275
|
+
let i = 0
|
|
276
|
+
while (i < pending.length) {
|
|
277
|
+
const comp = pending[i]
|
|
278
|
+
i++
|
|
279
|
+
checkWalkBounds(i, resolved, 'resolveTargetComponentwiseAsync')
|
|
280
|
+
spendWalkBudget(budget, 'resolveTargetComponentwiseAsync')
|
|
281
|
+
const step = resolveComponentLexically(resolved, comp, tail)
|
|
282
|
+
resolved = step.resolved
|
|
283
|
+
tail = step.tail
|
|
284
|
+
if (step.stat === null) continue
|
|
285
|
+
let st
|
|
286
|
+
try {
|
|
287
|
+
st = await lstat(step.stat)
|
|
288
|
+
} catch (err) {
|
|
289
|
+
if (err.code === 'ENOENT') { tail = 1; resolved = step.stat; continue }
|
|
290
|
+
throw err // EACCES etc. — fail closed via the caller
|
|
291
|
+
}
|
|
292
|
+
if (st.isSymbolicLink()) {
|
|
293
|
+
if (++symlinks > COMPONENTWISE_MAX_SYMLINKS) throw symlinkBudgetError('resolveTargetComponentwiseAsync')
|
|
294
|
+
resolved = spliceSymlink(pending, i, resolved, await readlink(step.stat))
|
|
295
|
+
} else {
|
|
296
|
+
resolved = step.stat
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
checkWalkBounds(i, resolved, 'resolveTargetComponentwiseAsync')
|
|
300
|
+
return resolved
|
|
301
|
+
}
|