@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.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
@@ -0,0 +1,741 @@
1
+ /**
2
+ * Argv option-injection guards (#7290, #7291).
3
+ *
4
+ * `execFile`/`spawn` with an array argv already stops SHELL injection — no
5
+ * shell ever sees the string. It does NOT stop ARGUMENT injection: the spawned
6
+ * program still runs its own option parser over that array, so a value that
7
+ * begins with `-` is read as an OPTION rather than as the datum it was meant
8
+ * to be. That is a distinct class, and it needs a distinct guard.
9
+ *
10
+ * There are three correct fixes. Which one applies is decided by whether a
11
+ * leading `-` is LEGITIMATE for that datum, and by how the target CLI parses
12
+ * the slot — so it is a per-CLI question, answered by MEASURING, not assumed:
13
+ *
14
+ * 1. The value can never legitimately start with `-` (a git ref, a branch,
15
+ * a container name) → REJECT it. `isSafeArgvValue` / `assertSafeArgvValue`.
16
+ *
17
+ * 2. The value legitimately can (a user's chat message — "- first point"),
18
+ * and it sits in a POSITIONAL slot → do not reject; terminate option
19
+ * parsing with a `--` separator placed BEFORE the value, and put every
20
+ * flag the command needs BEFORE the `--`. This is what the `claude`
21
+ * web-task argv does, and (since #7342) what `buildCodexArgs` does on
22
+ * both the first-turn and `resume` forms of `codex exec` — including the
23
+ * resume SESSION_ID, which is itself a positional and so must also
24
+ * precede the separator.
25
+ *
26
+ * 3. The value legitimately can, and it is the ARGUMENT TO A NAMED FLAG that
27
+ * the CLI declares as requiring one → `=`-join the long form,
28
+ * `--flag=<value>`, binding the value to the flag in a single token.
29
+ * Neither (1) nor (2) works here. This is what `GeminiSession._buildArgs`
30
+ * does for BOTH its prompt and its model id (since #7342). Measured
31
+ * against gemini-cli 0.45.2 and re-measured on 0.46.0, whose `-p/--prompt`
32
+ * and `-m/--model` use yargs `requiresArg`:
33
+ *
34
+ * gemini -p "- first bullet" usage error, exit 1
35
+ * gemini -p -- --list-extensions usage error, exit 1 (`--` BREAKS it)
36
+ * gemini --prompt="- first bullet" parses, value taken literally
37
+ *
38
+ * So a blanket "add `--` everywhere" sweep would be a REGRESSION on such
39
+ * a CLI. Beware short-circuiting flags when probing: `gemini -p --version`
40
+ * prints a version because yargs handles `--version` before it validates
41
+ * `requiresArg`, which makes it look like injection when it is not. Probe
42
+ * with a flag that does not short-circuit.
43
+ *
44
+ * `--` is NOT interchangeable with (1). It ends option parsing at ITS OWN
45
+ * position, so it cannot retroactively protect a value that precedes it.
46
+ * Measured against git 2.54.0 while fixing #7290:
47
+ *
48
+ * git diff --stat -- still applies --stat
49
+ * git diff --exit-code -- still exits 1
50
+ * git diff -O/etc/nope -- still reads the orderfile
51
+ *
52
+ * so `['diff', base, '--']` is not a fix for a dash-leading `base`, and
53
+ * `--literal-pathspecs` (#7281/#7289) does not help either — that constrains
54
+ * the PATHSPEC language, and a revision is not a pathspec.
55
+ */
56
+
57
+ /**
58
+ * True when `value` is safe to place in an argv slot whose contents would
59
+ * otherwise be option-parsed.
60
+ *
61
+ * Rejects, in order: a non-string, the empty string, a leading `-`, and any
62
+ * NUL / CR / LF. The control characters matter because several CLIs (and git's
63
+ * own `--stdin` modes) treat a newline as a record separator, so an embedded
64
+ * one can smuggle a second argument into a single slot.
65
+ *
66
+ * @param {unknown} value
67
+ * @returns {boolean}
68
+ */
69
+ export function isSafeArgvValue(value) {
70
+ return typeof value === 'string' &&
71
+ value.length > 0 &&
72
+ !value.startsWith('-') &&
73
+ !/[\0\n\r]/.test(value)
74
+ }
75
+
76
+ /**
77
+ * Throwing form of {@link isSafeArgvValue}, for call sites that must refuse
78
+ * rather than fall back.
79
+ *
80
+ * @param {unknown} value
81
+ * @param {string} [kind] - noun for the error message, e.g. 'branch', 'ref'.
82
+ * @throws {Error} when `value` would be option-parsed.
83
+ */
84
+ export function assertSafeArgvValue(value, kind = 'value') {
85
+ if (typeof value !== 'string' || value.length === 0) {
86
+ throw new Error(`empty ${kind}`)
87
+ }
88
+ if (!isSafeArgvValue(value)) {
89
+ throw new Error(`unsafe ${kind}: ${JSON.stringify(value)}`)
90
+ }
91
+ }
92
+
93
+ /**
94
+ * A git commit SHA, full or abbreviated — the shape of fix (1) for the one
95
+ * datum this repo persists as a ref: `<config dir>/known-good-ref`, written by
96
+ * `chroxy deploy` and read back by both `chroxy deploy` and the supervisor's
97
+ * rollback path.
98
+ *
99
+ * Deliberately stricter than {@link isSafeArgvValue}: the datum is always a
100
+ * SHA that chroxy wrote itself, so hex-only rejects not just `--exit-code` and
101
+ * `-O/etc/passwd` but every branch name, refspec and revision expression a
102
+ * corrupted file could otherwise smuggle into a `git` argv. Short SHAs of ≥ 7
103
+ * chars are accepted to match the supervisor's historical behaviour.
104
+ *
105
+ * Lives here, and NOT copied to a second call site: this predicate had one
106
+ * implementation inline in supervisor.js, and #7296 added the second consumer.
107
+ *
108
+ * @param {unknown} ref
109
+ * @returns {boolean}
110
+ */
111
+ export function isGitShaRef(ref) {
112
+ return typeof ref === 'string' && /^[0-9a-f]{7,40}$/i.test(ref)
113
+ }
114
+
115
+ /**
116
+ * Does a CLI's `--help` output advertise `flag` as a flag in its OWN right?
117
+ *
118
+ * A bare `help.includes('--remote')` is a false-safety guard: it reports
119
+ * success without checking, because it also matches `--remote-control`. That
120
+ * is not hypothetical — measured against the installed Claude Code CLI while
121
+ * fixing #7291, whose help text carries `--remote-control` and
122
+ * `--remote-control-session-name-prefix` and NO `--remote`:
123
+ *
124
+ * help.includes('--remote') -> true (wrong: opens the gate)
125
+ * cliHelpAdvertisesFlag(...) -> false (right)
126
+ *
127
+ * The boundaries are the whole point — the flag must be delimited on BOTH
128
+ * sides by something that is not a word character or a hyphen, which is what
129
+ * distinguishes a flag from a longer flag sharing its prefix or its suffix.
130
+ * A trailing-only test still returns true for `x--remote`, for `---remote`,
131
+ * and — the exact mirror of the defect this function exists to prevent — for
132
+ * a `-O` probe against a help line advertising `--O <file>`.
133
+ *
134
+ * @param {unknown} helpText - captured stdout of `<cli> --help`.
135
+ * @param {string} flag - the exact flag, including leading dashes, e.g. '--remote'.
136
+ * @returns {boolean}
137
+ */
138
+ export function cliHelpAdvertisesFlag(helpText, flag) {
139
+ if (typeof helpText !== 'string' || typeof flag !== 'string' || !flag) return false
140
+ return new RegExp(`(?<![\\w-])${escapeForRegExp(flag)}(?![\\w-])`).test(helpText)
141
+ }
142
+
143
+ /** Escape a flag so it can be interpolated into a RegExp body. */
144
+ function escapeForRegExp(flag) {
145
+ return flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
146
+ }
147
+
148
+ /**
149
+ * Audited-sink catalogue for `scripts/lint-argv-sinks.mjs` (#7868).
150
+ *
151
+ * The lint enumerates every `spawn`/`execFile`/`execFileSync`/`spawnSync`
152
+ * call site (and every `_buildArgs`/`build*Args`-shaped function) in
153
+ * `packages/server/src` and requires each argv element that is not provably
154
+ * a compile-time constant to be either provably safe — `assertSafeArgvValue`
155
+ * / `isSafeArgvValue` applied to it, a `--` terminator placed before it, or
156
+ * fused into one token behind a fixed non-dash prefix — or listed here.
157
+ *
158
+ * Each entry is `{ file, match, reason }`:
159
+ * - `file` — the sink's path, relative to `packages/server/src`.
160
+ * - `match` — the flagged expression's own text, matched by EXACT equality
161
+ * (modulo whitespace — #8112), never by substring. For an unresolvable
162
+ * argv, that is the whole call's normalised source text. For a single
163
+ * flagged ELEMENT (#7936), it is that element's own normalised text —
164
+ * UNCHANGED and always first — optionally followed by a site suffix:
165
+ * ` [[` + the enclosing function (or `<module>`) + the sink's callee + a
166
+ * per-(function, callee) call-site ORDINAL (review follow-through: two
167
+ * separate calls to the same callee within the same function still
168
+ * shared a key without this — see the `elementSite` doc comment in
169
+ * `lint-argv-sinks.mjs`) + the element's position within its resolved
170
+ * argv array, e.g. `` `value [[runA#execFile#0#1]]` `` (closed with `]]`)
171
+ * or the shorter `` `value [[runA#execFile` `` (an unterminated prefix of
172
+ * the site — narrows without needing the ordinal/index). An unterminated
173
+ * prefix must still end at a FIELD BOUNDARY of the site (the next
174
+ * character in the real site must be the fields' own `#` delimiter, or
175
+ * the prefix must be the whole site) — `#8126`: a bare string-prefix
176
+ * check let `runA#execFile` also match `runA#execFileSync#0#1`, since
177
+ * `SPAWN_APIS` contains callee names that are themselves string prefixes
178
+ * of each other (`execFile`/`execFileSync`, `spawn`/`spawnSync`). See
179
+ * `catalogueEntryMatchesFinding` in `lint-argv-sinks.mjs` for the exact
180
+ * boundary rule.
181
+ *
182
+ * A match written as just the bare element text (no ` [[` suffix — most
183
+ * of the entries below) matches at ANY call site in the file whose
184
+ * flagged expression is that EXACT text — never merely a site whose
185
+ * expression contains it (`docs/false-safety-guards.md`'s "substring
186
+ * match standing in for a token match", `#7290`/`#7291`: before #8112 an
187
+ * entry for the bare identifier `this._image` also matched
188
+ * `this._image || this._userSuppliedImageOverride` at the same site,
189
+ * since the old check was `.includes()`). A bare match legitimately
190
+ * spanning several call sites is still supported and still safe under
191
+ * exact matching, because every site it covers must carry that identical
192
+ * literal expression, verbatim — `docker-sdk-session.js`'s `this
193
+ * ._containerId` entry covers 5 call sites this way, and keychain.js's
194
+ * `service` entry covers 6, all bare references to the same-named,
195
+ * independently-safe value. Adding the ` [[` suffix pins a match to
196
+ * exactly the one call site it was written against — use that shape when
197
+ * two sinks in this file could otherwise share an identically-named
198
+ * flagged element (`lint-argv-sinks.mjs`'s `elementSite`, and
199
+ * `catalogueEntryMatchesFinding` for the full matching contract). Not a
200
+ * line number on purpose: a line number drifts on every unrelated edit
201
+ * above it, which would force a churn-only update on every such edit. A
202
+ * source-text match only goes stale when the FLAGGED CODE ITSELF
203
+ * changes — which is exactly when re-auditing is wanted.
204
+ *
205
+ * A template literal or `+`-concatenation is matched as its OWN whole
206
+ * text, backticks/quotes included (e.g. `` `${domain}/${SERVICE_LABEL}` ``,
207
+ * not `domain`) — it is a different expression from the bare identifier
208
+ * it embeds, even when the identifier alone is independently safe, and
209
+ * #8112 is precisely about not treating "contains a safe identifier" as
210
+ * "is safe". Where the same underlying value legitimately appears both
211
+ * bare and wrapped in a fixed-literal template at different call sites
212
+ * (`service.js`'s `domain`/`` `${domain}/${SERVICE_LABEL}` `` pair), each
213
+ * shape gets its own entry.
214
+ * - `reason` — one line: why this value cannot be attacker-controlled, or
215
+ * why the CLI it reaches cannot option-parse it.
216
+ *
217
+ * Checked in BOTH directions by the lint (#7199, #7216, #7544, #7639): an
218
+ * entry that no longer matches any real, still-unguarded finding is STALE
219
+ * and fails the build (the code moved on — remove the entry), and a real
220
+ * finding that matches no entry and no structural guard also fails. A list
221
+ * that only ever grows, or that nothing re-derives against the code, is the
222
+ * "roster checked in only one direction" shape docs/false-safety-guards.md
223
+ * catalogues.
224
+ */
225
+ export const AUDITED_SINKS = [
226
+ // ── acp-session.js ──
227
+ {
228
+ file: 'acp-session.js',
229
+ match: "spawn(spawnSpec.command, spawnSpec.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: this._buildChildEnv(), ...spawnSpec.options, })",
230
+ reason: 'entryRef.args is providers.acp[].args from the operator config.json, loaded once at boot by registerAcpProviders(); no WS/client message reaches it.',
231
+ },
232
+
233
+ // ── auth-probes.js ──
234
+ {
235
+ file: 'auth-probes.js',
236
+ match: 'service',
237
+ reason: 'keychainItemExists(service) has exactly one production caller, passing the module constant CLAUDE_KEYCHAIN_SERVICE; also sits immediately after the required-arg flag -s, consumed unconditionally regardless of content.',
238
+ },
239
+
240
+ // ── built-in-tools/bash-exec.js ──
241
+ {
242
+ file: 'built-in-tools/bash-exec.js',
243
+ match: 'command',
244
+ reason: 'this is the Bash tool: command is intentionally run as a full shell string via bash -c, which is the documented feature (pipes/redirection/heredocs), governed by the permission system rather than argv-shape — a different, already-accepted risk class from accidental option injection into an unrelated program.',
245
+ },
246
+
247
+ // ── built-in-tools/tool-transforms.js ──
248
+ {
249
+ file: 'built-in-tools/tool-transforms.js',
250
+ match: 'return { ci, ln, globArg, grepGlob }',
251
+ reason: 'not actually an argv-returning function despite the *Args name match — it returns { ci, ln, globArg, grepGlob } string fragments consumed by a shell-command-string builder (buildGrepCommand), out of this lint scope by design (see the exec()/execSync() scope note above). pattern/root are already hardened behind -e / a -- terminator (#7295); the --glob fragment is shell-quoted via shellQuote() and fused into one --glob=<value> token, so a value beginning with - is never a separate argv element; the grep-fallback glob (#7961/#7981) is no longer a grep flag at all but shell-quoted DATA used as a bash case pattern over the file list the fallback builds.',
252
+ },
253
+
254
+ // ── byok-mcp-client.js ──
255
+ {
256
+ file: 'byok-mcp-client.js',
257
+ match: "spawn(spawnSpec.command, spawnSpec.args, { env: this._buildChildEnv(), stdio: ['pipe', 'pipe', 'pipe'], ...spawnSpec.options, })",
258
+ reason: 'this._config.{command,args} is an MCP server entry the primary/owner user names to run an arbitrary local program — that is the feature (STRICT-PRIMARY gate + a requestMcpTrust approval prompt before spawn), not option-flag injection into an unrelated binary; not reachable by a non-primary client.',
259
+ },
260
+
261
+ // ── claude-tui-session.js ──
262
+ {
263
+ file: 'claude-tui-session.js',
264
+ // The full call text is 200+ chars, so this is the exact 200-char PREFIX
265
+ // the lint's own truncation (`.slice(0, 200)`, lint-argv-sinks.mjs) would
266
+ // produce for this call site — not a hand-picked shorter distinguishing
267
+ // substring (#8112: those are no longer honoured). If this call site's
268
+ // source text changes upstream of this cut point, this entry goes stale
269
+ // and must be re-derived against the new truncation.
270
+ match: "execFile(binary, args, { cwd, env, encoding: 'utf8', timeout: 5_000, maxBuffer: 64 * 1024, windowsHide: true, }, (err, stdout, stderr) => { if (err && typeof err.code !== 'number') { reject(err) retur",
271
+ reason: "runClaudeAuthStatus's two call sites (_verifyNativeConnectionRoute, _probeLoginBeforeFirstSpawn) pass claudeAuthStatusArgs(), a copy of the frozen static argv ['auth','status','--json'] — no interpolated value, never client text.",
272
+ },
273
+ // #7935 — `_spawnPty`'s node-pty `ptyMod.spawn(attemptedBinary, args, {...})`
274
+ // became a scanned sink once the lint learned to recognise node-pty
275
+ // bindings; `this._sessionId` needs no entry (recognised structurally —
276
+ // guarded by the `assertSafeArgvValue(this._sessionId, 'sessionId')` call
277
+ // right above, now that `pathKeyOf` resolves a `this.` base). The three
278
+ // entries below use the new call-site-scoped catalogueKey shape (#7936:
279
+ // element text + enclosing function + sink callee) so a future SECOND
280
+ // sink in this file reusing one of these identifiers cannot silently
281
+ // alias onto these — see elementCatalogueKey in lint-argv-sinks.mjs.
282
+ {
283
+ file: 'claude-tui-session.js',
284
+ match: 'this._settingsPath [[_spawnPty#spawn',
285
+ reason: "this._settingsPath is set by writeHookSettings(this._sinkDir, ...) to join(this._sinkDir, 'settings.json'); this._sinkDir is always join(<server-config base>, `s-${randomUUID()}`) — a daemon-generated absolute path, same reasoning as this file's execFile(binary, args) entry above (the `--settings` argument of the spawn itself).",
286
+ },
287
+ {
288
+ file: 'claude-tui-session.js',
289
+ match: 'skillsPrefix [[_spawnPty#spawn',
290
+ reason: 'bound via args.push("--append-system-prompt", skillsPrefix) — the same required-arg two-token flag on the same claude CLI that cli-session.js\'s "skillsText" entry already measured (2.1.282: a bogus flag-shaped value here starts the process normally, swallowed as the flag\'s own value); skillsPrefix carries client-settable skills/preamble text (_buildCombinedSkillsPrefix), but the argv SHAPE cannot be reinterpreted regardless of its content — same reasoning as skillsText.',
291
+ },
292
+
293
+ // ── cli-session.js ──
294
+ {
295
+ file: 'cli-session.js',
296
+ match: "spawn(spawnSpec.command, spawnSpec.args, { cwd: this.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: this._buildChildEnv(), ...spawnSpec.options, })",
297
+ reason: '_spawnPersistentProcess(args) has one caller (start()), which passes args = buildClaudeCliArgs({...}) — audited below, at buildClaudeCliArgs itself.',
298
+ },
299
+ {
300
+ file: 'cli-session.js',
301
+ match: 'model',
302
+ reason: 'this.model traces to the create_session WS model field, but is gated BEFORE CliSession is constructed by SessionManager against CliSession.getAllowedModels() (a known id allowlist, none starting with "-"), unless an operator opted the provider into config.providers.allowAnyModel (not client-reachable).',
303
+ },
304
+ {
305
+ file: 'cli-session.js',
306
+ match: "allowedTools.join(',')",
307
+ reason: 'this.allowedTools is populated only from server config (config.js allowedTools / CHROXY_ALLOWED_TOOLS env) — no WS/client code path sets it.',
308
+ },
309
+ {
310
+ file: 'cli-session.js',
311
+ match: 'skillsText',
312
+ reason: 'bound via args.push("--append-system-prompt", skillsText) — a required-arg (<prompt>) two-token flag, measured directly against the installed claude CLI (2.1.282): a bogus flag-shaped value passed this way starts the process normally (swallowed as the flag value), while the identical text as a bare option immediately errors "unknown option" — confirming the required-arg two-token form is safe regardless of skillsText content (argv-safety.js’s own documented case-3 table). skillsText itself does carry client-settable text (sessionPreamble, via set_session_preamble), but that is irrelevant here since the argv SHAPE cannot be reinterpreted.',
313
+ },
314
+ // resumeSessionId needs no catalogue entry: `-r, --resume` is declared with
315
+ // an OPTIONAL argument on the claude CLI (measured — the two-token form
316
+ // INJECTS, unlike --model/--append-system-prompt above), so buildClaudeCliArgs
317
+ // asserts it safe directly (case 1) rather than relying on it structurally.
318
+
319
+ // ── cli/deploy-cmd.js ──
320
+ {
321
+ file: 'cli/deploy-cmd.js',
322
+ match: 'fullPath',
323
+ reason: 'join(process.cwd(), file) is always an absolute path (starts with "/"), so it can never be read as a flag regardless of the tracked filename it is built from; CLI-only (chroxy deploy), no WS path.',
324
+ },
325
+ {
326
+ file: 'cli/deploy-cmd.js',
327
+ match: 'testDir',
328
+ reason: "join(process.cwd(),'packages','server','tests') is a fully literal path with no variable component; CLI-only.",
329
+ },
330
+ {
331
+ file: 'cli/deploy-cmd.js',
332
+ match: 'tagName',
333
+ reason: "`known-good-${Date.now()}` — fixed literal prefix plus a numeric timestamp; can never start with '-'. CLI-only.",
334
+ },
335
+ {
336
+ file: 'cli/deploy-cmd.js',
337
+ match: 'old',
338
+ reason: "old comes from `git tag --list 'known-good-*'` output, glob-filtered by git itself to always start with the literal 'known-good-'; never attacker text. CLI-only.",
339
+ },
340
+
341
+ // ── cli/session-cmd.js ──
342
+ {
343
+ file: 'cli/session-cmd.js',
344
+ match: 'target.convId',
345
+ reason: 'read from the local session-state.json (conversationId set either by a provider CLI itself, or accepted from a remote resume_conversation WS message only after CONVERSATION_ID_RE, a fully anchored canonical-UUID regex); the execFileSync call itself is CLI-only (chroxy resume).',
346
+ },
347
+
348
+ // ── cli/worktree-gc-cmd.js ──
349
+ {
350
+ file: 'cli/worktree-gc-cmd.js',
351
+ match: "execFileSync(cmd, args, { encoding: 'utf8' })",
352
+ reason: "dirSizeKib's one caller passes exec('du', ['-sk', path]) where path is an absolute filesystem path reported by git's own worktree-list output; CLI-only report path (chroxy worktree gc), not the daemon auto-reaper.",
353
+ },
354
+
355
+ // ── codex-session.js ──
356
+ {
357
+ file: 'codex-session.js',
358
+ match: 'return buildCodexArgs(text, this.model, this.resumeSessionId, this._resolvedCodexSandbox)',
359
+ reason: 'delegates to buildCodexArgs, a separate exported function audited at its own definition (text terminated behind --, model TOML-serialized via -c, sandbox enum-checked, threadId asserted safe — #7868).',
360
+ },
361
+ {
362
+ file: 'codex-session.js',
363
+ match: 'sandbox',
364
+ reason: 'resolveCodexSandbox(sandboxOverride) is constrained to the frozen enum CODEX_SANDBOX_MODES (read-only/workspace-write/danger-full-access); any other value is discarded and replaced by the default, and is re-gated at the WS ingress schema.',
365
+ },
366
+
367
+ // ── docker-sdk-session.js / docker-session.js ──
368
+ // Neither file's create_session wiring (session-manager.js) ever forwards a
369
+ // client image/memoryLimit/cpuLimit — providerOpts only ever carries
370
+ // containerId/containerUser/containerCliPath, so _image/_memoryLimit/
371
+ // _cpuLimit always resolve to their hardcoded literal defaults today.
372
+ {
373
+ file: 'docker-sdk-session.js',
374
+ match: 'this._containerId',
375
+ reason: 'always Docker-daemon-generated (captured from this own docker run/create stdout) or resolved server-side via environmentManager.getContainerInfo(); restore is cross-validated against the live environment record. Never accepted as raw client text.',
376
+ },
377
+ {
378
+ file: 'docker-sdk-session.js',
379
+ match: 'this._memoryLimit',
380
+ reason: "opts.memoryLimit || '2g' — never populated by the live create_session wiring, always the hardcoded literal default.",
381
+ },
382
+ {
383
+ file: 'docker-sdk-session.js',
384
+ match: 'this._cpuLimit',
385
+ reason: "opts.cpuLimit || '2' — never populated by the live create_session wiring, always the hardcoded literal default.",
386
+ },
387
+ {
388
+ file: 'docker-sdk-session.js',
389
+ // #8112: matched by whole-expression equality now, so the template's
390
+ // OWN delimiting backticks are part of the text — a bare `${...}`
391
+ // string (no backticks) no longer matches, since that is not what the
392
+ // flagged element's normalised source text actually is.
393
+ match: '`${this.cwd || process.cwd()}:/workspace`',
394
+ reason: 'this.cwd is gated by validateCwdAllowed(), which must statSync+realpathSync it to an existing real directory before this is ever reached; fixed value-slot after -v, not free text.',
395
+ },
396
+ {
397
+ file: 'docker-sdk-session.js',
398
+ match: 'this._image',
399
+ reason: "opts.image || 'node:22-slim' — never populated by the live create_session wiring, always the hardcoded literal default.",
400
+ },
401
+ {
402
+ file: 'docker-sdk-session.js',
403
+ match: 'setupCmd',
404
+ reason: 'interpolates only this._containerUser, regex-gated at construction by VALID_USERNAME_RE (^[a-z_][a-z0-9_-]{0,31}$) — cannot start with "-" or carry shell metacharacters.',
405
+ },
406
+ {
407
+ file: 'docker-sdk-session.js',
408
+ match: 'containerId',
409
+ reason: 'local var captured from this._containerId before nulling in destroy(); same chroxy/docker-generated origin as above.',
410
+ },
411
+ {
412
+ file: 'docker-session.js',
413
+ match: 'this._memoryLimit',
414
+ reason: "opts.memoryLimit || '2g' — never populated by the live create_session wiring, always the hardcoded literal default.",
415
+ },
416
+ {
417
+ file: 'docker-session.js',
418
+ match: 'this._cpuLimit',
419
+ reason: "opts.cpuLimit || '2' — never populated by the live create_session wiring, always the hardcoded literal default.",
420
+ },
421
+ {
422
+ file: 'docker-session.js',
423
+ // #8112: see the same-text entry in docker-sdk-session.js above — the
424
+ // template's own backticks are part of the matched text.
425
+ match: '`${this.cwd || process.cwd()}:/workspace`',
426
+ reason: 'same reasoning as docker-sdk-session.js: this.cwd is gated by validateCwdAllowed() to an existing real directory before reaching here.',
427
+ },
428
+ {
429
+ file: 'docker-session.js',
430
+ match: 'this._image',
431
+ reason: "opts.image || 'node:22-slim' — never populated by the live create_session wiring, always the hardcoded literal default.",
432
+ },
433
+ {
434
+ file: 'docker-session.js',
435
+ match: "spawn('docker', dockerArgs, { stdio: ['pipe', 'pipe', 'pipe'] })",
436
+ // Review (#8125): this reason previously described only the LAST three
437
+ // elements pushed onto dockerArgs before this opaque call — this.
438
+ // _containerId, the literal 'claude', and ...claudeArgs — and said
439
+ // nothing about the `--env <key>=<val>` pairs pushed earlier in
440
+ // _spawnPersistentProcess (one per FORWARDED_ENV_KEYS hit, plus
441
+ // CHROXY_HOST and getChroxyHostEnv()'s keys). This IS the opaque-wrapper
442
+ // coverage gap this PR's own docs section describes: the array's
443
+ // construction site is a DIFFERENT function from this spawn call, so the
444
+ // lint cannot see inside it and the whole array is one opaque
445
+ // attestation. Each `key` is drawn from the fixed FORWARDED_ENV_KEYS
446
+ // allowlist (or is the literal 'CHROXY_HOST' / a getChroxyHostEnv() key),
447
+ // so the pushed token's own leading text can never start with '-'
448
+ // regardless of `val` — safe, but worth stating explicitly rather than
449
+ // leaving the reason silent about most of the array's real content.
450
+ reason: "dockerArgs is: a fixed ['exec','-i','--workdir','/workspace'] prefix; zero or more '--env', `${key}=${val}` pairs where key is drawn only from the fixed FORWARDED_ENV_KEYS allowlist (plus the literal 'CHROXY_HOST' and getChroxyHostEnv()'s own keys), never client text, so the token can't start with '-' regardless of val; then this._containerId (see above, safe), the literal 'claude', and ...claudeArgs — the same delegated, separately-audited buildClaudeCliArgs() output cli-session.js uses.",
451
+ },
452
+ {
453
+ file: 'docker-session.js',
454
+ match: 'containerId',
455
+ reason: "local var in destroy(); this file's own constructor never accepts an external containerId at all (self-owned --rm container, per its own docstring).",
456
+ },
457
+
458
+ // ── doctor.js ──
459
+ {
460
+ file: 'doctor.js',
461
+ match: "execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...s.options })",
462
+ reason: "checkClaudeTuiCliVersion's default exec seam always receives the literal ['--version'] from its one call site; prepareSpawn only rewraps for a Windows .cmd shim. CLI-only (chroxy doctor).",
463
+ },
464
+ {
465
+ file: 'doctor.js',
466
+ match: "execFileSync(s.command, s.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env, ...s.options })",
467
+ reason: "checkClaudeLogin's default exec seam always receives the literal ['auth', 'status', '--json'] from its one call site; prepareSpawn only rewraps for a Windows .cmd shim. CLI-only (chroxy doctor / start preflight).",
468
+ },
469
+ {
470
+ file: 'doctor.js',
471
+ match: "execFileSync(spawnSpec.command, spawnSpec.args, { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'], env: buildClaudeLaunchEnv(), ...spawnSpec.options, })",
472
+ reason: "checkBinary's args are either the literal ['--version'] or a provider's static preflight.args declared in source (providers/*.js), never runtime/client data. CLI-only (chroxy doctor).",
473
+ },
474
+
475
+ // ── keychain.js ──
476
+ // service/account/script are always fixed internal constants across every
477
+ // real caller in this repo (DEFAULT_SERVICE='chroxy', ACCOUNT='api-token',
478
+ // IDENTITY_KEY_SERVICE, CRED_KEY_SERVICE, DISCORD_WEBHOOK_KEYCHAIN_SERVICE,
479
+ // PS_PROTECT/PS_UNPROTECT) — never client-set text. This is a whole-program
480
+ // fact this per-file lint cannot see (keychain.js only sees its own
481
+ // parameters), hence the catalogue rather than a structural guard.
482
+ {
483
+ file: 'keychain.js',
484
+ match: 'service',
485
+ reason: 'every real caller across the repo passes a fixed internal string constant (default "chroxy", or IDENTITY_KEY_SERVICE / CRED_KEY_SERVICE / DISCORD_WEBHOOK_KEYCHAIN_SERVICE) — never client-supplied text.',
486
+ },
487
+ {
488
+ file: 'keychain.js',
489
+ match: 'account',
490
+ reason: 'every real caller passes a fixed internal string constant (default ACCOUNT="api-token", or DISCORD_WEBHOOK_KEYCHAIN_ACCOUNT) — never client-supplied text.',
491
+ },
492
+ {
493
+ file: 'keychain.js',
494
+ match: 'token',
495
+ reason: "the secret value being stored, always generated server-side or set via local CLI init; also sits as -w's required argument (macOS security add-generic-password), consumed unconditionally regardless of content.",
496
+ },
497
+ // #8112: previously silenced only by ACCIDENT, as a substring of the
498
+ // 'service' entry above — service is independently safe (see that entry's
499
+ // reason), and this template wraps it in a fixed literal prefix/suffix, but
500
+ // it is a DIFFERENT expression from the bare identifier and needs its own
501
+ // exact-text entry now that matching is whole-expression equality.
502
+ {
503
+ file: 'keychain.js',
504
+ match: '`Chroxy API Token (${service})`',
505
+ reason: '_linuxSetToken\'s --label value; service is the same value the "service" entry above already establishes is never client-supplied text, wrapped in a fixed "Chroxy API Token (...)" literal.',
506
+ },
507
+ {
508
+ file: 'keychain.js',
509
+ match: 'script',
510
+ reason: '_dpapi(script, input) is only ever called with PS_PROTECT / PS_UNPROTECT, two hardcoded module-level PowerShell source constants; the actual secret goes over stdin, never argv.',
511
+ },
512
+
513
+ // ── platform.js ──
514
+ {
515
+ file: 'platform.js',
516
+ match: 'filePath',
517
+ reason: 'every caller builds filePath via configPath()/homedir()-rooted absolute paths, so it always starts with "/" (or a drive letter on Windows) and can never be read as a flag.',
518
+ },
519
+ {
520
+ file: 'platform.js',
521
+ // #8112: matched by whole-expression equality — the template's own
522
+ // backticks are part of the matched text now.
523
+ match: '`*${sid}:F`',
524
+ reason: "sid is the Windows account SID from currentUserSid(), regex-matched to /S-1-[0-9-]+/ against `whoami /user` output; the argv element also carries a literal '*' prefix.",
525
+ },
526
+ {
527
+ file: 'platform.js',
528
+ match: 'String(pid)',
529
+ reason: 'pid is always a real OS process id (child.pid from Node child_process/pty), never client-supplied text; a Node pid is always a positive integer.',
530
+ },
531
+
532
+ // ── service.js ──
533
+ {
534
+ file: 'service.js',
535
+ // #8112: whole-expression equality now, so the template's own backticks
536
+ // are part of the match — this covers ONLY installService's own
537
+ // `` `gui/${process.getuid()}` `` (no `/${SERVICE_LABEL}` suffix); the
538
+ // longer template below is a different expression with its own entry.
539
+ match: '`gui/${process.getuid()}`',
540
+ reason: 'process.getuid() is the Node builtin returning the current OS user numeric uid — always a non-negative integer; the template also carries a fixed literal "gui/" prefix.',
541
+ },
542
+ {
543
+ file: 'service.js',
544
+ match: 'servicePath',
545
+ reason: "join(homedir(), 'Library', 'LaunchAgents', `${SERVICE_LABEL}.plist`) with SERVICE_LABEL a hardcoded constant — always an internally-computed absolute path, never client input.",
546
+ },
547
+ // Review #7929 — the entries below cover `installWindowsService`,
548
+ // `getWindowsTaskStatus`, `uninstallService`, `startService`,
549
+ // `bootstrapLaunchd` and `stopService`, all of which build their `exec`
550
+ // call through `const exec = options._exec || execFileSync` (a
551
+ // test-injection seam whose fallback default was invisible to the lint
552
+ // before #7929's local-alias tracking fix — see collectImports in
553
+ // lint-argv-sinks.mjs). Every one of these functions is reachable ONLY from
554
+ // `chroxy service install/uninstall/start/stop/status` (cli/service-cmd.js)
555
+ // — no WS/client handler calls into service.js at all (grepped at audit
556
+ // time) — and every real call site there invokes them with NO options
557
+ // object, so `options._exec`/`options._taskName`/`options._wrapperPath`
558
+ // are always undefined in production.
559
+ {
560
+ file: 'service.js',
561
+ match: 'taskName',
562
+ reason: "taskName = options._taskName || WINDOWS_TASK_NAME ('Chroxy', a hardcoded module constant); options._taskName is a test-only seam never set by the one real caller (cli/service-cmd.js, always called with zero args). CLI-only, no WS path.",
563
+ },
564
+ // #8112: `state.taskName || WINDOWS_TASK_NAME` (uninstallService's win32
565
+ // branch) is a DIFFERENT expression from the bare `taskName` above — it
566
+ // used to be silenced only because `taskName` is a substring of it. Kept
567
+ // as its own entry, not folded into a widened `taskName` match, precisely
568
+ // because the reasoning is different: this is `docs/false-safety-guards.md`'s
569
+ // "the same literal expression, verbatim" family rule applied correctly —
570
+ // one entry per distinct expression, not one entry stretched to cover both.
571
+ {
572
+ file: 'service.js',
573
+ match: 'state.taskName || WINDOWS_TASK_NAME',
574
+ reason: 'state.taskName (the uninstallService win32 branch) is read back from service.json, which is written only by installWindowsService using this same taskName constant — so it round-trips a value chroxy itself wrote, never client text; the fallback to the hardcoded WINDOWS_TASK_NAME constant is dead only when service.json is missing/corrupt.',
575
+ },
576
+ {
577
+ file: 'service.js',
578
+ // #8112: was a bare 'wrapperPath', silenced only by substring accident —
579
+ // the real flagged element is this whole template (quotes included).
580
+ match: '`"${wrapperPath}"`',
581
+ reason: "wrapperPath = config._wrapperPath || join(stateDir, WINDOWS_WRAPPER_NAME) — an internally-computed absolute path (join() always returns one) or a test-only override; used as schtasks' /TR value, quoted. CLI-only (chroxy service install).",
582
+ },
583
+ {
584
+ file: 'service.js',
585
+ match: 'domain',
586
+ reason: "domain = `gui/${process.getuid()}` — process.getuid() is the Node builtin returning the current OS user's numeric uid (always a non-negative integer), with a fixed literal 'gui/' prefix; can never start with '-'. Passed bare as a positional to `launchctl bootstrap`. CLI-only (chroxy service start/stop).",
587
+ },
588
+ // #8112: `` `${domain}/${SERVICE_LABEL}` `` (bootstrapLaunchd's `launchctl
589
+ // bootout` argument) is a different expression from the bare `domain`
590
+ // above — same underlying value (see that entry), wrapped in a fixed
591
+ // `/${SERVICE_LABEL}` literal suffix; was silenced only by substring
592
+ // accident before #8112.
593
+ {
594
+ file: 'service.js',
595
+ match: '`${domain}/${SERVICE_LABEL}`',
596
+ reason: 'domain is the same `gui/${process.getuid()}` value the "domain" entry above establishes is never client-supplied text; SERVICE_LABEL is a hardcoded module constant.',
597
+ },
598
+ // #8112: `` `gui/${process.getuid()}/${SERVICE_LABEL}` `` — a THIRD,
599
+ // longer template built from the same process.getuid()/SERVICE_LABEL
600
+ // pieces as the two entries above, appearing verbatim at two call sites
601
+ // (uninstallService's darwin branch, stopService) that share one entry
602
+ // under the catalogue's ordinary bare-text "family" convention (identical
603
+ // text at both sites, not merely overlapping substrings).
604
+ {
605
+ file: 'service.js',
606
+ match: '`gui/${process.getuid()}/${SERVICE_LABEL}`',
607
+ reason: 'process.getuid() is the Node builtin returning the current OS user numeric uid (always non-negative); SERVICE_LABEL is a hardcoded module constant; the template also carries a fixed literal "gui/"..."/ " structure. Same reasoning as the shorter "gui/${process.getuid()}" entry above, one literal segment longer.',
608
+ },
609
+ {
610
+ file: 'service.js',
611
+ match: 'plistPath',
612
+ reason: 'plistPath is either state.servicePath (written by installWindowsService/installService as an internally-computed absolute path, never client text) or paths.plistPath (a server-computed default from getServicePaths()) — both existsSync-checked absolute paths before this point. CLI-only (chroxy service start).',
613
+ },
614
+
615
+ // ── session-context.js ──
616
+ {
617
+ file: 'session-context.js',
618
+ match: "execFile(GIT, args, { cwd, timeout: TIMEOUT_MS }, (err, stdout) => { if (err) return reject(err) resolve(stdout.trim()) })",
619
+ reason: "gitCommand(cwd, args)'s only 3 call sites in this file pass fully literal arrays (['rev-parse','--abbrev-ref','HEAD'], ['status','--porcelain'], ['rev-list','--count','@{upstream}..HEAD']) — args is unresolved only at this local helper's own scope.",
620
+ },
621
+
622
+ // ── session-manager.js ──
623
+ {
624
+ file: 'session-manager.js',
625
+ match: 'worktreeDir',
626
+ reason: 'join(this._worktreeBase || defaultWorktreeBase(), sessionId) — a server-config-rooted absolute path with a hex sessionId (randomBytes or restore-validated /^[a-f0-9]{32}$/), or on a #8856 restore-time recreation the same deterministic path exact-matched before use; no WS field controls it directly.',
627
+ },
628
+ {
629
+ file: 'session-manager.js',
630
+ match: 'repoDir',
631
+ reason: "repoDir is always the required argument to git's -C flag, consumed unconditionally regardless of content (argv-safety.js case 3's two-token form), so it cannot be read as an option whatever it holds. It is the create-time cwd (gated by validateCwdAllowed() at create), or on a #8856 restore the persisted worktreeRepoDir, which is restore-time input not re-validated against the cwd allowlist; _recreateMissingWorktree holds it to a non-empty absolute path and disables its hooks (config-defined commands such as checkout filters still run, as for any git call in that repository).",
632
+ },
633
+ {
634
+ file: 'utils/git-repo.js',
635
+ match: 'dir',
636
+ reason: "dir is always the required argument to git's -C flag, consumed unconditionally regardless of content (argv-safety.js case 3's two-token form), so it cannot be read as an option whatever it holds. Callers: _addDetachedWorktree's repoDir (see the session-manager.js entry above) and the check_git_repo query, which passes a home-contained, realpath-resolved existing directory (#8972).",
637
+ },
638
+ {
639
+ file: 'session-manager.js',
640
+ match: 'worktreePath',
641
+ reason: 'set at creation to the server-computed worktreeDir (see above) or, on restore, to a saved path that is exact-matched against the deterministic expected worktreeBase/sessionId path before being accepted — never wired to a live WS field.',
642
+ },
643
+
644
+ // ── supervisor.js ──
645
+ {
646
+ file: 'supervisor.js',
647
+ // #8112: whole-expression equality — the template's own backticks are
648
+ // part of the matched text now.
649
+ match: '`${tag}^{commit}`',
650
+ reason: "tag is drawn from `git tag --list 'known-good-*'` output, glob-filtered by git itself to always start with the literal 'known-good-' — not attacker text, and structurally cannot start with '-'.",
651
+ },
652
+ {
653
+ file: 'supervisor.js',
654
+ match: 'fork(script, args, opts)',
655
+ reason: "_fork(script, args, opts) is a documented override point ('Override point: fork a child process') for test injection — script/args are opaque PARAMETERS forwarded straight through, which per-file static analysis cannot resolve to the one real caller. That caller (_startChild) always passes childScript (a fixed internal path built from import.meta.url, never variable) and a literal [] for args — never attacker content. #7929 added `fork` to the lint's SPAWN_APIS roster; this entry is new because of that, not because the code changed.",
656
+ },
657
+
658
+ // ── tunnel/cloudflare.js ──
659
+ {
660
+ file: 'tunnel/cloudflare.js',
661
+ match: 'spawn(bin, argv, spawnOpts)',
662
+ reason: "the two real callers build argv from operator config only: this.tunnelName (config.tunnelName, set via `chroxy tunnel setup`, --terminated) and this.port (a server-config number embedded in a fixed 'http://localhost:' prefix); no WS handler touches either.",
663
+ },
664
+
665
+ // ── user-shell-registry.js ──
666
+ {
667
+ file: 'user-shell-registry.js',
668
+ match: 'String(pid)',
669
+ reason: 'pid originates from node-pty’s real OS pid (this._term.pid) and is additionally gated by Number.isInteger(pid) && pid > 0 on both the write and read paths before reaching here.',
670
+ },
671
+
672
+ // ── utils/resolve-binary.js ──
673
+ {
674
+ file: 'utils/resolve-binary.js',
675
+ match: 'name',
676
+ reason: "every caller passes one of a small fixed set of internal binary names baked into source ('git','claude','gemini','codex','cloudflared', or a provider's static preflight.binary.name) — never external/client input.",
677
+ },
678
+
679
+ // ── web-task-manager.js ──
680
+ {
681
+ file: 'web-task-manager.js',
682
+ match: "execFile(cmd, args, { timeout: 15_000, ...opts }, (err, stdout) => { if (err) return reject(err) resolve(stdout) })",
683
+ reason: "this generic exec wrapper's one caller passes ['--teleport', task.taskId], where task.taskId is a server-generated randomUUID() looked up from the task map — the client's raw taskId is used only as a Map key, never as the argv value itself. A separate, already-hardened call site handles the client prompt text via buildRemoteTaskArgs()'s -- terminator (#7291).",
684
+ },
685
+
686
+ // ── worktree-gc.js ──
687
+ // planRepoGc/sweepOrphanChroxyWorktrees/applyPlan run automatically at
688
+ // daemon boot and (opt-in) on a timer, not only from a human CLI
689
+ // invocation — but every argv element traces to local git-reported paths,
690
+ // server config, or a strictly hex-regex-constrained session id, never
691
+ // WS-client-supplied text.
692
+ {
693
+ file: 'worktree-gc.js',
694
+ // #8112: full call text (was a prefix) — one entry legitimately covers
695
+ // all 3 call sites (planRepoGc, sweepOrphanChroxyWorktrees, applyPlan)
696
+ // because each builds the IDENTICAL default-injection expression,
697
+ // verbatim, not merely an overlapping one.
698
+ match: "execFileSync(GIT, ['-C', cwd, ...args], { encoding: 'utf8' })",
699
+ reason: 'cwd is always an absolute repo/worktree path from server config or resolveRepoSet discovery; the only variable positionals pushed through args are absolute paths reported by `git worktree list --porcelain` itself, or a --reason-bound lockReason value — never remote/WS-supplied text.',
700
+ },
701
+ ]
702
+
703
+ /**
704
+ * How does a CLI's `--help` say `flag` is called — specifically, does it take
705
+ * a REQUIRED argument?
706
+ *
707
+ * This decides whether fix shape (2), the `--` separator, is safe, and the
708
+ * distinction is not cosmetic. Measured against the repo's commander 12.1.0
709
+ * with a client prompt of `--dangerously-skip-permissions`:
710
+ *
711
+ * declared as ['--remote', prompt] ['--remote', '--', prompt]
712
+ * --remote INJECTS safe
713
+ * --remote [name] INJECTS safe
714
+ * --remote <name> safe — swallowed as INJECTS — the `--` becomes the
715
+ * the flag's own value flag's value, freeing the
716
+ * prompt to be option-parsed
717
+ *
718
+ * So against a required-argument flag the separator is not merely useless, it
719
+ * is strictly WORSE than omitting it. No single argv shape is correct under
720
+ * both arities, so a caller must know which it faces and fail closed when it
721
+ * cannot tell.
722
+ *
723
+ * @param {unknown} helpText - captured stdout of `<cli> --help`.
724
+ * @param {string} flag - the exact flag, e.g. '--remote'.
725
+ * @returns {'absent'|'boolean'|'optional'|'required'}
726
+ */
727
+ export function cliHelpFlagArity(helpText, flag) {
728
+ if (!cliHelpAdvertisesFlag(helpText, flag)) return 'absent'
729
+ // Inspect what follows the flag on its own help line, skipping any alias
730
+ // list (`--remote, -r <name>`).
731
+ const re = new RegExp(`(?<![\\w-])${escapeForRegExp(flag)}(?![\\w-])((?:,\\s*-[\\w-]+)*)([^\\n]*)`)
732
+ const m = re.exec(helpText)
733
+ if (!m) return 'boolean'
734
+ // Only a metavar BEFORE the description column counts. Two spaces or a tab
735
+ // start the description in every help format we target, so a `<file>` in
736
+ // prose ("same as --output <file>") is not mistaken for this flag's own.
737
+ const head = m[2].split(/ {2,}|\t/)[0]
738
+ if (/^[ =]*<[^>]+>/.test(head)) return 'required'
739
+ if (/^[ =]*\[[^\]]+\]/.test(head)) return 'optional'
740
+ return 'boolean'
741
+ }