@chroxy/server 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -0,0 +1,455 @@
1
+ /**
2
+ * The protected-path / secret-read PERMISSION FLOOR — the SINGLE source of truth,
3
+ * shared by BOTH permission pipelines. #7004.
4
+ *
5
+ * Chroxy has two permission paths, and the floor must be identical on both:
6
+ * - IN-PROCESS (SDK / BYOK / codex app-server): `permission-manager.js`
7
+ * `handlePermission` calls {@link isFlooredTarget} before every lenient-mode
8
+ * short-circuit (auto / an `allow` rule / acceptEdits).
9
+ * - HOOK-ROUTED (claude-tui — the DEFAULT provider — and cli-session):
10
+ * `hooks/permission-hook.sh` decides auto / acceptEdits in SHELL, so it
11
+ * cannot import this module. It instead consults `POST /permission-floor`
12
+ * (`ws-permissions.js` `handlePermissionFloorCheck`), which calls the SAME
13
+ * {@link isFlooredTarget}, and routes a floored target to a real prompt.
14
+ *
15
+ * #7004 was exactly the drift this module exists to prevent: the floor lived
16
+ * only in `permission-manager.js`, which hook-routed providers never traverse,
17
+ * so `auto`/`acceptEdits` on claude-tui read `.env` / `id_rsa` ungated. Keep the
18
+ * floor HERE — never reimplement it in the shell hook or a second JS call site
19
+ * (the #6986/#7001 lesson: divergent copies of a security check are how these
20
+ * bugs happen). A leaf module by design (no logger, no EventEmitter, no rule
21
+ * store) so an HTTP handler can import it without pulling in PermissionManager
22
+ * or joining its permission-rule-store import cycle — the same shape as
23
+ * `redaction.js`, the sanitizer both paths already share.
24
+ *
25
+ * Everything here is PURE except the deliberate symlink resolution (realpath /
26
+ * lstat), which FAILS CLOSED — see {@link isProtectedPathValue}.
27
+ */
28
+ import { realpathSync } from 'node:fs'
29
+ import { resolve, relative, sep, isAbsolute, dirname, basename, join } from 'node:path'
30
+ import { resolveTargetComponentwiseSync } from './utils/componentwise-resolver.js'
31
+
32
+ // #6794 — hardcoded protected-path floor. Even under lenient settings (auto /
33
+ // acceptEdits / a broad `allow` rule) Chroxy must not SILENTLY auto-approve a
34
+ // path-carrying tool aimed at a repo-control / agent-config directory or a
35
+ // secret file. This mirrors Claude Code's own "always ask" floor (desktop
36
+ // parity): the target simply falls through to the interactive prompt instead
37
+ // of short-circuiting — a floor, never a hard deny.
38
+ //
39
+ // Protected DIRECTORY segment names, matched at any depth of the path the write
40
+ // RESOLVES into (see isProtectedPathValue for the relative-vs-absolute framing
41
+ // that keeps a session's own cwd from false-matching). `.config/git` (the XDG
42
+ // git-config dir) is a two-segment sequence handled separately, not a bare segment.
43
+ const PROTECTED_DIR_SEGMENTS = new Set(['.git', '.claude', '.vscode'])
44
+
45
+ // #6803 — SECRET FILE names. Distinct from the protected DIRECTORY segments
46
+ // above: these carry credentials / private keys, so their floor applies to
47
+ // READS as well as writes (mirrors Claude Code's "don't auto-read known
48
+ // secrets" floor). The write floor (isProtectedPathTarget) matches the config
49
+ // DIRS *and* these secret files; the read floor (isSecretReadTarget) matches
50
+ // ONLY these secret files — reading `.git/config` or `.claude/settings.json`
51
+ // is a common benign operation and must not prompt, but auto-reading a private
52
+ // key or an env file under a broad `allow Read` must not silently succeed.
53
+ //
54
+ // Matched (case-insensitively, see isProtectedPathValue) at ANY path segment:
55
+ // - `.env` or `.env.*` → env files (.env / .env.local / …)
56
+ // - one of SECRET_FILE_EXACT → SSH keys, credential dotfiles
57
+ // - a segment ending in an extension in SECRET_FILE_EXTENSIONS → PEM / keys /
58
+ // PKCS#12 keystores
59
+ // A floor only ever forces a PROMPT (never a deny), so a rare false positive on
60
+ // an unrelated `.key`/`.pem` file is acceptable and conservative.
61
+ const SECRET_FILE_EXACT = new Set([
62
+ 'id_rsa', 'id_dsa', 'id_ecdsa', 'id_ed25519', // SSH private keys
63
+ '.npmrc', '.pgpass', '.netrc', // credential dotfiles
64
+ ])
65
+ const SECRET_FILE_EXTENSIONS = ['.pem', '.key', '.p12', '.pfx']
66
+
67
+ // Tool-input fields that name a filesystem target. Presence of one is what
68
+ // makes a tool "path-carrying" for the floor (Write/Edit → file_path,
69
+ // NotebookEdit → notebook_path, Read/Glob/Grep → file_path/path). A tool with
70
+ // none of these (Bash, Task, WebFetch, WebSearch) cannot be floored here —
71
+ // command-shaped access is out of scope for a path floor. Exported (#6773) so
72
+ // the editedInput whitelist guard test can assert no editable field is ever a
73
+ // path field (a path-redirect would let an edit slip past the protected floor).
74
+ export const PROTECTED_PATH_INPUT_FIELDS = ['file_path', 'path', 'notebook_path']
75
+
76
+ // #6803 — tools whose floor is SECRETS-ONLY (non-mutating reads). handlePermission
77
+ // routes these through isSecretReadTarget (env files + key material) instead of
78
+ // the full config-dir floor. EVERY OTHER path-carrying tool — the mutating ones
79
+ // (Write / Edit / NotebookEdit / apply_patch) and any future tool — gets the full
80
+ // isProtectedPathTarget floor. Defaulting the unknown/mutating case to the FULL
81
+ // floor is fail-safe: a new write-shaped tool inherits the stronger floor.
82
+ export const SECRET_READ_FLOOR_TOOLS = new Set(['Read', 'Glob', 'Grep'])
83
+
84
+ /**
85
+ * #6803 — is a single (already-lowercased) path segment a known secret FILE?
86
+ * Env files, SSH/credential dotfiles, and PEM/key/keystore extensions. Pure
87
+ * string ops (no regex) so it can't be mangled by a later edit.
88
+ * @param {string} seg a lowercased path segment
89
+ * @returns {boolean}
90
+ */
91
+ function isSecretFileSegment(seg) {
92
+ if (seg === '.env' || seg.startsWith('.env.')) return true
93
+ if (SECRET_FILE_EXACT.has(seg)) return true
94
+ for (const ext of SECRET_FILE_EXTENSIONS) {
95
+ if (seg.length > ext.length && seg.endsWith(ext)) return true
96
+ }
97
+ return false
98
+ }
99
+
100
+ /**
101
+ * #6803 (PR #6873 security review) — credential-DENSE config FILES that must be
102
+ * floored for READS too (not just writes). These live INSIDE a config dir, so
103
+ * the secret-file matcher above misses them, but they routinely carry secrets:
104
+ * - `.git/config` — a remote URL can embed a PAT (`https://TOKEN@…`)
105
+ * - `.git/credentials` — git's plaintext credential store
106
+ * - `.config/git/config` + `.config/git/credentials` — the XDG equivalents
107
+ * - `.claude/settings*.json` — may hold ANTHROPIC_API_KEY / env secrets
108
+ * A broad `allow Read` / auto / bypass must not silently read these (Chroxy
109
+ * streams tool-results to phone/Discord, amplifying any leak). OTHER files in
110
+ * the config dirs (`.claude/skills/*.md`, a secret-free `.vscode/settings.json`)
111
+ * stay un-floored for reads per #6803's intent.
112
+ *
113
+ * Matched as a 2-/3-segment sequence anchored at index `i` of the (lowercased,
114
+ * `..`-stripped) segment array, so any depth prefix (`sub/.git/config`) matches.
115
+ * Pure string ops (no regex) — consistent with the rest of the floor.
116
+ * @param {string[]} segments lowercased path segments
117
+ * @param {number} i the current segment index
118
+ * @returns {boolean}
119
+ */
120
+ function isCredentialConfigSegment(segments, i) {
121
+ const seg = segments[i]
122
+ // .git/config (PAT-embedded remote URLs) and .git/credentials (git store).
123
+ if (seg === '.git' && (segments[i + 1] === 'config' || segments[i + 1] === 'credentials')) return true
124
+ // XDG git: .config/git/config and .config/git/credentials.
125
+ if (seg === '.config' && segments[i + 1] === 'git' &&
126
+ (segments[i + 2] === 'config' || segments[i + 2] === 'credentials')) return true
127
+ // .claude/settings*.json (settings.json / settings.local.json — may hold keys).
128
+ const child = segments[i + 1]
129
+ if (seg === '.claude' && typeof child === 'string' && child.startsWith('settings') && child.endsWith('.json')) return true
130
+ return false
131
+ }
132
+
133
+ // #6851 — depth ceiling for the sync deepest-ancestor realpath walk. Absolute
134
+ // paths never legitimately nest this deep; the cap only guards a pathological /
135
+ // malicious tail (a to-be-created path with hundreds of nonexistent components
136
+ // under a symlinked parent), which FAILS CLOSED rather than trust a lexical guess.
137
+ const _FLOOR_REALPATH_MAX_DEPTH = 256
138
+
139
+ /**
140
+ * #6851 — SYNC deepest-existing-ancestor realpath: the symlink-resolving core of
141
+ * the floor's #6851 hardening, and the synchronous sibling of
142
+ * {@link realpathOfDeepestAncestor} in `ws-file-ops/common.js` (BYOK's
143
+ * post-approval confinement). The floor runs inside the SYNCHRONOUS
144
+ * `handlePermission` hot-path, so it cannot await that async twin — it uses
145
+ * `realpathSync` instead.
146
+ *
147
+ * Resolves every symlink in the EXISTING ancestor chain of a (possibly not-yet-
148
+ * created) ABSOLUTE path, then re-appends the non-existent tail components. The
149
+ * naive "realpath the whole target, fall back to the lexical path on ENOENT"
150
+ * pattern has a symlink-escape hole on to-be-created files: a symlinked PARENT
151
+ * plus a non-existent leaf makes the lexical fallback hide the parent symlink.
152
+ * Walking up to the deepest EXISTING ancestor and realpath-ing THAT closes it.
153
+ *
154
+ * FAIL-CLOSED at every ambiguous edge — it THROWS (never returns a lexical
155
+ * guess) when no ancestor resolves or the depth is pathological, and lets a
156
+ * non-ENOENT error (EACCES on a directory, ELOOP on a symlink cycle) propagate,
157
+ * so the floor's `catch` treats the target as protected.
158
+ * @param {string} absPath an absolute path (may not exist yet)
159
+ * @returns {string} the real path with all symlink ancestors resolved
160
+ */
161
+ function realpathDeepestAncestorSync(absPath) {
162
+ if (!isAbsolute(absPath)) {
163
+ // A relative path would resolve against the SERVER process cwd, not the
164
+ // session cwd — fail loudly (and, via the caller's catch, closed).
165
+ throw Object.assign(new Error(`realpathDeepestAncestorSync requires an absolute path, got: ${absPath}`), { code: 'EINVAL' })
166
+ }
167
+ const segments = []
168
+ let cursor = absPath
169
+ for (let i = 0; i < _FLOOR_REALPATH_MAX_DEPTH; i++) {
170
+ try {
171
+ const realAncestor = realpathSync(cursor)
172
+ if (segments.length === 0) return realAncestor
173
+ // `segments` was pushed leaf-first while cursor climbed, so reverse to
174
+ // rebuild ancestor→leaf order for join().
175
+ return join(realAncestor, ...segments.slice().reverse())
176
+ } catch (err) {
177
+ if (err.code !== 'ENOENT') throw err
178
+ const parent = dirname(cursor)
179
+ if (parent === cursor) {
180
+ // Reached the fs root without resolving any ancestor — unreachable on a
181
+ // real OS (`/` always realpaths). FAIL CLOSED: a lexical fallback here
182
+ // would reopen the exact bypass this helper closes.
183
+ throw Object.assign(new Error(`realpathDeepestAncestorSync: no existing ancestor for ${absPath}`), { code: 'ENOENT' })
184
+ }
185
+ segments.push(basename(cursor))
186
+ cursor = parent
187
+ }
188
+ }
189
+ // Depth ceiling hit — FAIL CLOSED rather than trust a pathological tail.
190
+ throw Object.assign(new Error(`realpathDeepestAncestorSync: path depth exceeds ${_FLOOR_REALPATH_MAX_DEPTH}`), { code: 'ENAMETOOLONG' })
191
+ }
192
+
193
+ // #6921/#6928 — the SYNC open(2)-faithful component-wise resolver (the crux of the
194
+ // #6921 floor hardening: it applies `..` AFTER following each symlink, unlike the
195
+ // lexical `realpath(resolve(base, target))` shape it replaced) now lives in
196
+ // `utils/componentwise-resolver.js`, the SINGLE SOURCE shared with the async BYOK
197
+ // confinement path (`ws-file-ops/common.js`). Co-locating the two open(2)-faithful
198
+ // walks is what keeps them from drifting again — #6928 was a bug present in BOTH
199
+ // copies. Imported as `resolveTargetComponentwiseSync` at the top of this file.
200
+
201
+ /**
202
+ * #6851 — the pure segment scan, factored out of {@link isProtectedPathValue} so
203
+ * the lexical pass and the symlink-resolved pass share ONE matcher. Given a
204
+ * resolution `base` and an already-resolved absolute `resolved` target, applies
205
+ * the #6806 relative-vs-absolute framing (below) and tests each segment. No fs
206
+ * access — string ops only.
207
+ *
208
+ * #6806 — the discriminator is whether the resolved target stays INSIDE base's
209
+ * own subtree:
210
+ * - UNDER base → scan the path RELATIVE to base, so base's own prefix segments
211
+ * (its `.claude`) are excluded and a benign in-workspace write is never
212
+ * floored. Under-base relatives never contain `..`.
213
+ * - ESCAPES base (a `..`-traversal ABOVE it — itself suspicious) → scan the
214
+ * RESOLVED ABSOLUTE path, so a protected segment sitting in base's PREFIX
215
+ * (the very `.claude/` a worktree lives under, reached by `../../x`) is
216
+ * caught. The floor only ever forces a PROMPT, so over-flooring a sibling
217
+ * traversal (already escaping the workspace) is safe and conservative.
218
+ * @param {string} base
219
+ * @param {string} resolved an absolute path already resolved against base
220
+ * @param {boolean} secretsOnly
221
+ * @returns {boolean}
222
+ */
223
+ function _scanResolvedTarget(base, resolved, secretsOnly) {
224
+ const rel = relative(base, resolved)
225
+ // Target is inside base's own subtree when the relative path neither is nor
226
+ // begins with `..` (and isn't a foreign absolute — a Windows cross-drive
227
+ // `relative()` can return one). Empty rel = the target IS base (still "inside").
228
+ const underCwd = rel === '' ||
229
+ (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..' + sep))
230
+ const scanned = underCwd ? rel : resolved
231
+ // Split on BOTH separators (#6928): `scanned` is a native-sep resolved path
232
+ // here, but a separator-agnostic split keeps the segment scan robust to any
233
+ // foreign `\`/`/` that survives (and can never wrongly merge two segments — a
234
+ // filename cannot contain a separator on the platform that produced it).
235
+ const segments = scanned.split(/[/\\]+/)
236
+ .filter((s) => s.length > 0 && s !== '..')
237
+ .map((s) => s.toLowerCase())
238
+ for (let i = 0; i < segments.length; i++) {
239
+ const seg = segments[i]
240
+ // Secret files, and credential-dense config files, are floored under BOTH
241
+ // the read and the write floor (PR #6873 review — the read floor must not
242
+ // silently auto-read .git/config, git credentials, or .claude/settings*.json).
243
+ if (isSecretFileSegment(seg)) return true
244
+ if (isCredentialConfigSegment(segments, i)) return true
245
+ if (secretsOnly) continue
246
+ // Config DIRS (any file within them) are floored only under the full (write)
247
+ // floor; a read of a NON-credential config file stays un-prompted.
248
+ if (PROTECTED_DIR_SEGMENTS.has(seg)) return true
249
+ if (seg === '.config' && segments[i + 1] === 'git') return true
250
+ }
251
+ return false
252
+ }
253
+
254
+ /**
255
+ * #6794 / #6806 / #6851 — is a single path value protected, resolved against
256
+ * `base` (the session cwd)?
257
+ *
258
+ * TWO passes, ORed — a hit on EITHER floors the target:
259
+ * (1) LEXICAL (the pre-#6851 floor, unchanged). `resolve()` absorbs absolute
260
+ * paths, a leading `./`, and `..` traversal; the resolved path is scanned
261
+ * segment-by-segment ({@link _scanResolvedTarget}). Pure string ops, no fs
262
+ * access — fast, and every input the old floor flagged still flags.
263
+ * (2) #6851/#6921 SYMLINK. The lexical pass is symlink-BLIND: because
264
+ * `resolve()` collapses `..` textually, a symlink in cwd's PREFIX (the
265
+ * chroxy agent worktree can live under a *symlink* to a real `.claude/`),
266
+ * a symlinked COMPONENT of the target, OR a `..` that FOLLOWS a symlinked
267
+ * component can make a path that lexically looks OUTSIDE a protected dir
268
+ * RESOLVE INTO `.git`/`.claude`/`.vscode`/`.config/git` or a secret file
269
+ * (and vice-versa). Pass (2) resolves the base to its real path, then walks
270
+ * the target COMPONENT BY COMPONENT via
271
+ * {@link resolveTargetComponentwiseSync} — following each symlink and
272
+ * applying each `..` against the resolved-so-far REAL path, exactly as
273
+ * `open(2)` does — and re-runs the SAME segment scan. It only ADDS matches
274
+ * on top of (1); it never un-floors a lexical hit (pass (1) already
275
+ * returned). The raw (NOT pre-`resolve`d) target is handed to the walker so
276
+ * its `..` survives to be applied post-symlink — the #6921 fix. The earlier
277
+ * #6851 shape (`realpathDeepestAncestorSync(resolve(realBase, target))`)
278
+ * could not close this: both `resolve()` and Node's `realpathSync` collapse
279
+ * `..` LEXICALLY, so a `..` after a symlinked component was cancelled before
280
+ * any symlink was followed.
281
+ *
282
+ * FAIL-CLOSED: any error resolving the real paths (EACCES on a directory, ELOOP
283
+ * on a symlink cycle/depth bomb, an unresolvable base) is treated as PROTECTED —
284
+ * the floor forces the interactive prompt, never assumes the target is safe. The
285
+ * floor only ever forces a PROMPT (never a hard deny), so over-flooring an
286
+ * ambiguous resolution is conservative and correct.
287
+ *
288
+ * #6922 — TOCTOU: this resolution happens at permission-CHECK time and is NOT
289
+ * atomic with the downstream read/write. A symlink anywhere in the path can be
290
+ * swapped between this check and the executor's `open` (e.g. via an un-floored
291
+ * `Bash` step interleaved with the write), so a benign realpath here does not
292
+ * GUARANTEE a benign open later. This floor is defense-in-depth / prompt-only,
293
+ * and chroxy does not own the downstream `open` for SDK/TUI/codex providers, so a
294
+ * fully atomic guard (`openat2(RESOLVE_NO_SYMLINKS)` held across the write) is not
295
+ * achievable at this layer. Do not over-trust the resolved path as an atomic
296
+ * guarantee — see #6922.
297
+ *
298
+ * #6806 — WHICH segments each pass scans, and the #6794 worktree false-positive
299
+ * guard it preserves, live in {@link _scanResolvedTarget}. #6803 —
300
+ * `secretsOnly` narrows the match to SECRET / credential files (the read floor);
301
+ * the full (write) floor passes `secretsOnly = false`.
302
+ * @param {string} target a path value from a tool input
303
+ * @param {string} base the resolution base (session cwd)
304
+ * @param {boolean} [secretsOnly] match only secret / credential files
305
+ * @returns {boolean}
306
+ */
307
+ function isProtectedPathValue(target, base, secretsOnly = false) {
308
+ // (1) LEXICAL floor — pre-#6851 behavior, authoritative on a hit (no fs cost).
309
+ const resolvedLexical = resolve(base, target)
310
+ if (_scanResolvedTarget(base, resolvedLexical, secretsOnly)) return true
311
+ // (2) #6851/#6921 SYMLINK floor — resolve the real base, then walk the RAW
312
+ // target component-by-component (open(2) semantics) and re-scan. A resolution
313
+ // error FAILS CLOSED (return true → force the prompt). Runs only on a
314
+ // lexically-clean target (the common benign case), so the fs cost is a couple
315
+ // of realpath/lstat walks per otherwise-auto-approved permission check.
316
+ try {
317
+ // Pass `base` DIRECTLY — never `resolve(base)`. `realpathDeepestAncestorSync`
318
+ // REQUIRES an absolute path and THROWS on a relative one; that guard exists
319
+ // precisely so a relative base can't be silently reframed against the SERVER
320
+ // process cwd (`process.cwd()`) — the WRONG root (the floor must be anchored
321
+ // on the SESSION's cwd). In normal operation `base` IS absolute (the session
322
+ // cwd from the WS client / a worktree dir / the process.cwd() fallback), so
323
+ // this is a no-op; a relative/malformed base hits the throw and FAILS CLOSED
324
+ // (caught below → return true → force the prompt) instead of resolving
325
+ // against process.cwd(). Wrapping in resolve() would defeat BOTH the guard
326
+ // and the wrong-root framing it protects against.
327
+ const realBase = realpathDeepestAncestorSync(base)
328
+ // Pass the RAW `target` (its `..` intact) to the component walker, so a `..`
329
+ // after a symlinked component climbs from the symlink's TARGET, not its
330
+ // lexical parent. Do NOT pre-resolve() it — that would collapse the `..`.
331
+ const realTarget = resolveTargetComponentwiseSync(realBase, target)
332
+ return _scanResolvedTarget(realBase, realTarget, secretsOnly)
333
+ } catch {
334
+ return true
335
+ }
336
+ }
337
+
338
+ /**
339
+ * #6794 — does this tool input target a protected path? Inspects EVERY present
340
+ * {@link PROTECTED_PATH_INPUT_FIELDS} value (a benign `file_path` must not
341
+ * shadow a protected `path`), resolves each against the session cwd (so
342
+ * absolute paths, a leading `./`, and `..` traversal all normalize), then
343
+ * tests the resolved path segment-by-segment. ANY protected field floors the
344
+ * input. See {@link isProtectedPathValue} for the #6806 relative-vs-absolute
345
+ * framing that decides which segments are scanned.
346
+ *
347
+ * #6805/#6828 — codex `apply_patch` carries its per-file targets in an ARRAY:
348
+ * `input.changes` is `FileUpdateChange[] = { path, kind, diff }` (see
349
+ * codex-app-server-session.js `_describeApproval`), with the top-level
350
+ * `file_path` set to the approval's `grantRoot` — typically the benign repo
351
+ * root. Scanning only the flat fields therefore let a member edit under
352
+ * `.git/`/`.env*` escape the floor (and, with a persisted `{apply_patch,
353
+ * allow}` rule from #6771, be durably auto-approved). Every array entry's
354
+ * `path` is now checked with the same matcher — ANY protected member floors
355
+ * the WHOLE request. A string-shaped `changes` (codex's legacy unified-diff
356
+ * `item.patch` passthrough) carries no parseable paths and is skipped, same
357
+ * as any other non-array field.
358
+ *
359
+ * A benign in-workspace write is never floored — a git worktree that itself
360
+ * lives under a real `.claude/` dir writing to `packages/…` stays UNfloored
361
+ * because a target under cwd is scanned relative to cwd (its own `.claude`
362
+ * prefix excluded). But a `..`-traversal back UP into that same `.claude`
363
+ * (`../../settings.local.json` → the real agent config) IS floored, because an
364
+ * above-cwd target is scanned as its resolved ABSOLUTE path (#6806). See
365
+ * {@link isProtectedPathValue} for the full reconciliation.
366
+ *
367
+ * Segment rules (a match on ANY segment floors the write; see
368
+ * {@link isProtectedPathValue} for the lowercase rationale):
369
+ * - a segment in {@link PROTECTED_DIR_SEGMENTS} (`.git` / `.claude` / `.vscode`)
370
+ * - a `.config` segment immediately followed by `git` (the XDG git-config dir)
371
+ * - a segment that is `.env` or starts with `.env.` (`.env` / `.env.local` / …)
372
+ *
373
+ * Returns false for any missing / non-string path field, so a command-shaped
374
+ * tool (Bash, WebFetch) is never floored. Pure + side-effect-free (string ops
375
+ * only — no regex, so the `.env.*` match can't be mangled by later edits).
376
+ *
377
+ * @param {object} input the tool input
378
+ * @param {string} [cwd] the session cwd (falls back to process.cwd())
379
+ * @returns {boolean}
380
+ */
381
+ export function isProtectedPathTarget(input, cwd) {
382
+ return _matchesFloor(input, cwd, false)
383
+ }
384
+
385
+ /**
386
+ * #6803 — the READ floor: does this tool input target a known SECRET FILE
387
+ * (env file or key material)? Same field-scanning as {@link isProtectedPathTarget}
388
+ * (every present path field + `changes[]`, resolved against cwd) but matches
389
+ * ONLY secret files — the config DIRS (.git/.claude/.vscode/.config/git) are a
390
+ * WRITE concern and are deliberately NOT floored for reads, so a Read/Glob/Grep
391
+ * of a config dir stays a normal, un-prompted operation. handlePermission uses
392
+ * this for {@link SECRET_READ_FLOOR_TOOLS}; every other tool uses the full floor.
393
+ * @param {object} input the tool input
394
+ * @param {string} [cwd] the session cwd (falls back to process.cwd())
395
+ * @returns {boolean}
396
+ */
397
+ export function isSecretReadTarget(input, cwd) {
398
+ return _matchesFloor(input, cwd, true)
399
+ }
400
+
401
+ /**
402
+ * Shared floor matcher — inspects every present {@link PROTECTED_PATH_INPUT_FIELDS}
403
+ * value AND every `changes[]` member path (codex apply_patch, #6805/#6828),
404
+ * resolving each against the session cwd, and tests it with {@link isProtectedPathValue}.
405
+ * `secretsOnly` selects the read floor (secret files) vs the full write floor
406
+ * (config dirs + secret files). ANY protected field/member floors the input.
407
+ * @param {object} input
408
+ * @param {string} [cwd]
409
+ * @param {boolean} secretsOnly
410
+ * @returns {boolean}
411
+ */
412
+ function _matchesFloor(input, cwd, secretsOnly) {
413
+ if (!input || typeof input !== 'object') return false
414
+ const base = (typeof cwd === 'string' && cwd.length > 0) ? cwd : process.cwd()
415
+ for (const field of PROTECTED_PATH_INPUT_FIELDS) {
416
+ if (typeof input[field] !== 'string' || input[field].length === 0) continue
417
+ if (isProtectedPathValue(input[field], base, secretsOnly)) return true
418
+ }
419
+ // #6805/#6828 — walk the array-shaped per-file targets (codex apply_patch).
420
+ if (Array.isArray(input.changes)) {
421
+ for (const change of input.changes) {
422
+ if (!change || typeof change.path !== 'string' || change.path.length === 0) continue
423
+ if (isProtectedPathValue(change.path, base, secretsOnly)) return true
424
+ }
425
+ }
426
+ return false
427
+ }
428
+
429
+ /**
430
+ * #7004 — the floor decision for ONE (tool, input) pair: the tool-aware choice
431
+ * between the read floor and the full write floor, plus the predicate itself.
432
+ * This is the WHOLE floor semantic in one call, so both pipelines can share it
433
+ * verbatim instead of re-deriving "which floor applies to which tool":
434
+ *
435
+ * - {@link SECRET_READ_FLOOR_TOOLS} (Read / Glob / Grep — non-mutating) are
436
+ * floored ONLY on secret + credential files ({@link isSecretReadTarget});
437
+ * reading a config dir stays benign and un-prompted.
438
+ * - EVERY other tool (the mutating ones, and any future/unknown tool) gets the
439
+ * full config-dir + secret floor ({@link isProtectedPathTarget}) — defaulting
440
+ * the unknown case to the STRONGER floor is fail-safe.
441
+ *
442
+ * A `true` return means "must not be silently auto-approved" — it forces the
443
+ * interactive PROMPT. It is never a deny: the floor only ever removes a
444
+ * short-circuit, so a false positive costs one prompt, never access.
445
+ *
446
+ * @param {string} toolName the tool requesting permission
447
+ * @param {object} input the tool input
448
+ * @param {string} [cwd] the session cwd (the floor's resolution base)
449
+ * @returns {boolean} true when the target is floored (prompt required)
450
+ */
451
+ export function isFlooredTarget(toolName, input, cwd) {
452
+ return SECRET_READ_FLOOR_TOOLS.has(toolName)
453
+ ? isSecretReadTarget(input, cwd)
454
+ : isProtectedPathTarget(input, cwd)
455
+ }