@chroxy/server 0.11.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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  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 +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  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 +69 -5
  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 +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -0,0 +1,113 @@
1
+ /**
2
+ * A cheap pre-filter for regular expressions that come from outside, applied
3
+ * BEFORE a pattern is accepted. It is NOT the safety mechanism.
4
+ *
5
+ * No static screen can prove that a backtracking pattern is fast (overlapping
6
+ * repeats separated by a literal, adjacent bounded repeats, repeats hidden in
7
+ * non-capturing groups all defeat one). What keeps the daemon responsive is that
8
+ * the pattern is never run on the event loop: `utils/bounded-regex.js` runs it in
9
+ * a worker with a per-match deadline and a cap on the tested text, and a match
10
+ * that runs out its deadline counts as no match.
11
+ *
12
+ * What this screen still refuses, because it is cheap and almost never wanted:
13
+ * - a pattern over `MAX_PATTERN_LENGTH` characters;
14
+ * - a backreference (`\1`..`\9`, `\k<name>`), read from the parse so that an
15
+ * escaped backslash followed by a digit (`\\1`) is not mistaken for one;
16
+ * - the classic nested shape: a group repeated without a bound (`*`, `+`,
17
+ * `{n,}`) whose body BEGINS with an unbounded repeat, such as `(a+)+`,
18
+ * `(.*a)*` or `(\s*x)+`.
19
+ * Everything else, including other patterns that can backtrack badly, is accepted
20
+ * and left to the time bound.
21
+ */
22
+ export const MAX_PATTERN_LENGTH = 200
23
+
24
+ class Refused extends Error {}
25
+
26
+ /**
27
+ * @param {unknown} source
28
+ * @returns {boolean} true when the pattern passes the pre-filter
29
+ */
30
+ export function isSafeRegexSource(source) {
31
+ if (typeof source !== 'string') return false
32
+ if (source.length > MAX_PATTERN_LENGTH) return false
33
+ try {
34
+ const end = parseAlternation(source, 0, 0)
35
+ return end.i === source.length
36
+ } catch {
37
+ return false
38
+ }
39
+ }
40
+
41
+ function parseQuantifier(src, i) {
42
+ const c = src[i]
43
+ let unbounded = false
44
+ let any = true
45
+ let j = i + 1
46
+ if (c === '*' || c === '+') {
47
+ unbounded = true
48
+ } else if (c === '?') {
49
+ // optional
50
+ } else if (c === '{') {
51
+ const m = /^\{(\d+)(,(\d*))?\}/.exec(src.slice(i))
52
+ if (!m) return { next: i, unbounded: false, any: false }
53
+ j = i + m[0].length
54
+ unbounded = m[2] !== undefined && m[3] === ''
55
+ } else {
56
+ return { next: i, unbounded: false, any: false }
57
+ }
58
+ if (src[j] === '?') j++ // lazy
59
+ return { next: j, unbounded, any }
60
+ }
61
+
62
+ /**
63
+ * Parse alternatives until the closing ')' or the end. Returns the index reached
64
+ * and whether some alternative BEGINS with an unbounded repeat.
65
+ */
66
+ function parseAlternation(src, start, depth) {
67
+ let i = start
68
+ let startsUnbounded = false
69
+ let first = true // the next atom is the first of its alternative
70
+ while (i < src.length) {
71
+ const c = src[i]
72
+ if (c === ')') {
73
+ if (depth === 0) throw new Refused()
74
+ return { i, startsUnbounded }
75
+ }
76
+ if (c === '|') { first = true; i++; continue }
77
+ let atomStartsUnbounded = false
78
+ if (c === '(') {
79
+ let j = i + 1
80
+ if (src[j] === '?') {
81
+ // (?: ... ), (?<name> ... ), or a lookaround (?= ?! ?<= ?<!): all parse as a group.
82
+ const m = /^\?(:|=|!|<=|<!|<[A-Za-z_]\w*>)/.exec(src.slice(j))
83
+ if (!m) throw new Refused()
84
+ j += m[0].length
85
+ }
86
+ const inner = parseAlternation(src, j, depth + 1)
87
+ if (src[inner.i] !== ')') throw new Refused()
88
+ atomStartsUnbounded = inner.startsUnbounded
89
+ i = inner.i + 1
90
+ } else if (c === '[') {
91
+ let j = i + 1
92
+ if (src[j] === '^') j++
93
+ for (; j < src.length && src[j] !== ']'; j++) if (src[j] === '\\') j++
94
+ if (j >= src.length) throw new Refused()
95
+ i = j + 1
96
+ } else if (c === '\\') {
97
+ const next = src[i + 1]
98
+ // A backreference is a backslash that is NOT itself escaped (this walk
99
+ // consumes `\\` as one atom) followed by 1-9, or \k<.
100
+ if ((next >= '1' && next <= '9') || (next === 'k' && src[i + 2] === '<')) throw new Refused()
101
+ i += 2
102
+ } else {
103
+ i++
104
+ }
105
+ const q = parseQuantifier(src, i)
106
+ if (q.unbounded && atomStartsUnbounded) throw new Refused()
107
+ if (first && (q.unbounded || atomStartsUnbounded)) startsUnbounded = true
108
+ first = false
109
+ i = q.next
110
+ }
111
+ if (depth !== 0) throw new Refused()
112
+ return { i, startsUnbounded }
113
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Bounded reads and atomic writes for the small JSON files the idle-only
3
+ * auto-deploy exchanges through the config directory (#8331): `pending-update.json`,
4
+ * `deploy-postpone.json`, `deploy-request.json`, `last-deploy.json` and the
5
+ * script's own state. One implementation, imported by BOTH the daemon
6
+ * (`daemon-update-status.js`) and `scripts/deploy-daemon.mjs`, so the two sides
7
+ * cannot disagree about what a hostile file looks like.
8
+ *
9
+ * The config directory is writable by other local processes, so every one of these
10
+ * files is untrusted input:
11
+ *
12
+ * - READS go through `_openTrustedFdSync` (the same open the credential reader uses):
13
+ * `O_RDONLY | O_NOFOLLOW | O_NONBLOCK` on POSIX, so a FIFO cannot block the open and
14
+ * a symlink is refused atomically; on win32 (no `O_NOFOLLOW`) a pre-open `lstat`
15
+ * plus a post-open fd/path identity check (fresh `lstat`, BigInt dev/ino), refusing
16
+ * when identity cannot be established. The descriptor is then required to be a
17
+ * REGULAR FILE, and the read ACCUMULATES from that one descriptor until EOF or
18
+ * cap + 1 bytes (a short read is legal, so one `read` is never taken for the whole
19
+ * file).
20
+ * - The result says WHY a file was not usable, because callers act differently:
21
+ * `none` no such file
22
+ * `bad` the CONTENT or kind is refused (a symlink, a FIFO, a directory, an
23
+ * oversized file, not a JSON object): reads as absent
24
+ * `error` an I/O error (EAGAIN, EIO, EACCES, …) or a read that did not complete:
25
+ * the file may be perfectly valid and MUST NOT be treated as corrupt
26
+ * - WRITES go to a RANDOM temp name opened with `O_EXCL` (so a planted file or
27
+ * symlink at that name cannot be followed or truncated), are written through
28
+ * that descriptor, and are renamed into place; the temp file is removed on
29
+ * failure.
30
+ *
31
+ * Every filesystem call goes through the injected `fs` so the deploy script's
32
+ * tests can drive it.
33
+ */
34
+
35
+ import * as realFs from 'node:fs'
36
+ import { randomBytes } from 'node:crypto'
37
+ import { _openTrustedFdSync, defaultTrustedFileReadDeps } from '../trusted-file-read.js'
38
+
39
+ /** Every file here is a few hundred bytes. A bigger one is not ours. */
40
+ export const SMALL_FILE_CAP = 4096
41
+
42
+ const C = realFs.constants
43
+ const HAS_O_NOFOLLOW = typeof C.O_NOFOLLOW === 'number' && C.O_NOFOLLOW !== 0
44
+
45
+ /**
46
+ * @param {string} file
47
+ * @param {{ fs?: object, cap?: number, platform?: string, hasONoFollow?: boolean }} [o]
48
+ * `platform` / `hasONoFollow` are test seams to drive the win32 path anywhere.
49
+ * @returns {{ state: 'none' } | { state: 'bad', reason: string } | { state: 'error', reason: string } | { state: 'ok', raw: string }}
50
+ */
51
+ export function readBoundedFile(file, { fs = realFs, cap = SMALL_FILE_CAP, platform = process.platform, hasONoFollow = HAS_O_NOFOLLOW } = {}) {
52
+ // The credential reader's own deps (its O_NOFOLLOW constant included), with only the
53
+ // filesystem calls and the platform seams swapped for ours.
54
+ const deps = {
55
+ ...defaultTrustedFileReadDeps,
56
+ hasONoFollow,
57
+ platform,
58
+ openSync: (p, flags) => fs.openSync(p, flags),
59
+ closeSync: (fd) => fs.closeSync(fd),
60
+ fstatSync: (fd) => fs.fstatSync(fd, { bigint: true }),
61
+ lstatSync: (p) => fs.lstatSync(p, { bigint: true }),
62
+ }
63
+ let opened
64
+ try {
65
+ opened = _openTrustedFdSync(file, deps)
66
+ } catch (e) {
67
+ if (e.code === 'ENOENT') return { state: 'none' }
68
+ // ELOOP is a symlink, or an identity check that could not prove the open.
69
+ if (e.code === 'ELOOP') return { state: 'bad', reason: 'is a symlink or could not be proven to be the file at its path' }
70
+ return { state: 'error', reason: e.code || String(e.message || e) }
71
+ }
72
+ const { fd, stat } = opened
73
+ try {
74
+ if (!stat.isFile()) return { state: 'bad', reason: 'is not a regular file' }
75
+ const limit = cap + 1
76
+ const buf = Buffer.alloc(limit)
77
+ let total = 0
78
+ while (total < limit) {
79
+ const n = fs.readSync(fd, buf, total, limit - total, total)
80
+ if (n === 0) break
81
+ total += n
82
+ }
83
+ if (total > cap) return { state: 'bad', reason: `is larger than ${cap} bytes` }
84
+ return { state: 'ok', raw: buf.toString('utf8', 0, total) }
85
+ } catch (e) {
86
+ return { state: 'error', reason: e.code || String(e.message || e) }
87
+ } finally {
88
+ try { fs.closeSync(fd) } catch { /* nothing to close */ }
89
+ }
90
+ }
91
+
92
+ /**
93
+ * `readBoundedFile` + parse. A value that is not a plain JSON object is `bad`; an I/O
94
+ * error stays an `error` and is never reported as unparseable content.
95
+ * @returns {{ state: 'none' } | { state: 'bad' | 'error', reason: string } | { state: 'ok', raw: string, value: object }}
96
+ */
97
+ export function readBoundedJson(file, o) {
98
+ const r = readBoundedFile(file, o)
99
+ if (r.state !== 'ok') return r
100
+ try {
101
+ const value = JSON.parse(r.raw)
102
+ if (value && typeof value === 'object' && !Array.isArray(value)) return { state: 'ok', raw: r.raw, value }
103
+ } catch { /* fall through */ }
104
+ return { state: 'bad', reason: 'is not a JSON object' }
105
+ }
106
+
107
+ /**
108
+ * Write `text` to `file` atomically: random temp name, `O_EXCL`, through the
109
+ * descriptor, rename, and the temp file removed on any failure.
110
+ * @param {string} file
111
+ * @param {string} text
112
+ * @param {{ fs?: object, mode?: number }} [o]
113
+ */
114
+ export function writeFileAtomic(file, text, { fs = realFs, mode = 0o600 } = {}) {
115
+ const tmp = `${file}.tmp-${randomBytes(8).toString('hex')}`
116
+ let fd
117
+ try {
118
+ fd = fs.openSync(tmp, C.O_WRONLY | C.O_CREAT | C.O_EXCL | (C.O_NOFOLLOW ?? 0) | (C.O_NONBLOCK ?? 0), mode)
119
+ const data = Buffer.from(text, 'utf8')
120
+ for (let off = 0; off < data.length;) off += fs.writeSync(fd, data, off, data.length - off)
121
+ fs.closeSync(fd)
122
+ fd = undefined
123
+ fs.renameSync(tmp, file)
124
+ } catch (err) {
125
+ if (fd !== undefined) { try { fs.closeSync(fd) } catch { /* already closed */ } }
126
+ try { fs.unlinkSync(tmp) } catch { /* never created, or already gone */ }
127
+ throw err
128
+ }
129
+ }
@@ -25,12 +25,37 @@
25
25
  */
26
26
  import { resolveCredential, isKnownCredentialKey } from '../credential-store.js'
27
27
  import { getChroxyHostEnv } from '../chroxy-host-metadata.js'
28
+ import { sanitizeClaudeConfigDirEnv } from './claude-config-dir.js'
28
29
 
29
30
  // Standard vars every child process needs for its runtime to function.
30
31
  // Shell PATH, locale, TERM, TMPDIR, user/home identity.
31
- const STANDARD_ALLOWLIST = [
32
+ // Exported (#7319 review) so an allowlist-mode provider that isn't wired
33
+ // through the `PROVIDERS`/`buildSpawnEnv` table below (a config-driven,
34
+ // per-entry provider like AcpSession, which has no fixed provider-specific
35
+ // allowlist to add — the operator's own `env` config IS that allowlist) can
36
+ // still start from the same baseline instead of hand-duplicating a
37
+ // security-relevant list that would then drift from this one.
38
+ export const STANDARD_ALLOWLIST = [
32
39
  'PATH',
33
40
  'HOME',
41
+ // Windows home/profile identity (#7948). Node's os.homedir() checks
42
+ // USERPROFILE first and only falls back to the Win32
43
+ // GetUserProfileDirectoryW API when it's unset — but allowlist-mode
44
+ // providers are third-party binaries, not guaranteed to go through
45
+ // os.homedir()'s fallback at all: codex (a Rust binary) documents its own
46
+ // home as %USERPROFILE%\.codex (a direct env read), and gemini's Node
47
+ // dependency google-auth-library-nodejs resolves its ADC well-known file at
48
+ // %APPDATA%\gcloud\application_default_credentials.json — unrelated to
49
+ // home-dir resolution entirely. HOMEDRIVE/HOMEPATH is the classic fallback
50
+ // pair some tools use when USERPROFILE itself is absent; LOCALAPPDATA is
51
+ // APPDATA's machine-local sibling used for cache/local config by the same
52
+ // class of Windows tooling. All five are no-ops on POSIX (unset in
53
+ // process.env there), so listing them unconditionally is harmless.
54
+ 'USERPROFILE',
55
+ 'HOMEDRIVE',
56
+ 'HOMEPATH',
57
+ 'APPDATA',
58
+ 'LOCALAPPDATA',
34
59
  'USER',
35
60
  'LOGNAME',
36
61
  'SHELL',
@@ -80,13 +105,137 @@ const STANDARD_ALLOWLIST = [
80
105
  // `extras` instead; it only authorises POST /permission, so it is safe to hand
81
106
  // to the child.
82
107
  //
108
+ // CHROXY_INGEST_SECRET (#8113) joins this list for the same reason, at lower
109
+ // severity: it authorises POST /api/events and POST /api/mailbox* (bearer-
110
+ // token-authority.md §6 — notification injection + a bounded, non-attacker-
111
+ // controlled mailbox wakeup string; no reads, no arbitrary input). The daemon
112
+ // itself never assigns it into process.env (it is generated once and
113
+ // persisted to ~/.chroxy/ingest-secret, read back from disk — grepped: no
114
+ // `process.env.CHROXY_INGEST_SECRET =` assignment anywhere in src/), so any
115
+ // value present in a child's copied env can only be something the OPERATOR's
116
+ // own shell happened to export (e.g. for their own claude-hooks testing) —
117
+ // never a value this daemon minted for itself. No spawned child in this
118
+ // audit is an `@chroxy/claude-hooks` emitter (those run inside an entirely
119
+ // separate, non-chroxy Claude Code session), so none has a legitimate use for
120
+ // it either.
121
+ //
83
122
  // Allowlist-mode providers (codex, gemini) already exclude these by omission;
84
- // this set is the belt-and-braces guarantee for denylist-mode providers (claude)
85
- // and is re-used by the claude-tui PTY spawn path (claude-tui-session.js).
123
+ // this set is the belt-and-braces guarantee for denylist-mode providers (claude,
124
+ // and claude-sdk — the env SdkSession hands the Agent SDK's `query()` for the
125
+ // `claude` child it spawns) and is re-used by the claude-tui PTY spawn path
126
+ // (claude-tui-session.js), the BYOK in-process Bash/Grep tool shell
127
+ // (byok-tool-executor.js, #8113), the user-shell PTY, and the
128
+ // MCP-server/statusline child-env builders.
86
129
  export const CHROXY_SECRET_DENYLIST = [
87
130
  'API_TOKEN',
131
+ 'CHROXY_INGEST_SECRET',
132
+ ]
133
+
134
+ // Chroxy per-SESSION env that must never reach a spawned child by AMBIENT
135
+ // INHERITANCE — only when THIS session's own builder explicitly (re-)sets it
136
+ // for its own child (#7360). Distinct from CHROXY_SECRET_DENYLIST above
137
+ // (never reaches ANY child, full stop): CHROXY_HOOK_SECRET and CHROXY_PORT
138
+ // are legitimately handed to a hook-consuming child (cli-session.js's
139
+ // `extras`, claude-tui-session.js's `_buildPtyEnv` when permissions are
140
+ // enabled) — but only THIS session's own freshly-generated/assigned values.
141
+ //
142
+ // A full-parent-env copy (`{ ...process.env }`) otherwise forwards whatever
143
+ // the DAEMON PROCESS ITSELF happened to inherit — e.g. this daemon was
144
+ // launched from inside another chroxy session (nested chroxy), or a
145
+ // developer's shell still exports a prior session's values — into a child
146
+ // that has no use for a FOREIGN session's hook secret: without hooks (or
147
+ // with a different session's hooks), the child gains nothing from the key
148
+ // and the daemon gains a needless leak surface (#7360's reproduction: a test
149
+ // suite run inside a chroxy session inherited the outer session's
150
+ // CHROXY_PORT/CHROXY_HOOK_SECRET into every child env it built).
151
+ export const CHROXY_INHERITED_SESSION_ENV = [
152
+ 'CHROXY_PORT',
153
+ 'CHROXY_HOOK_SECRET',
154
+ // #8263: "this is a claude-tui child" is per-session state exactly like the
155
+ // two above. An ambient copy (a daemon launched from inside a TUI child)
156
+ // would make a claude-cli child's legitimate user-level permission hook
157
+ // inert, so every builder strips it and ClaudeTuiSession re-adds its own.
158
+ 'CHROXY_TUI_CHILD',
159
+ ]
160
+
161
+ /**
162
+ * Strip ambiently-inherited chroxy per-session env from a full parent-env
163
+ * copy, IN PLACE, before a builder re-applies its own session's explicit
164
+ * values. Callers MUST call this BEFORE assigning/merging their own
165
+ * `CHROXY_PORT`/`CHROXY_HOOK_SECRET` (never after) — otherwise the strip
166
+ * would delete the session's own just-assigned value along with any ambient
167
+ * one, which is exactly the E3 mutant `spawn-env-inherited-secrets-roster.
168
+ * test.js` and the per-builder tests pin as a regression.
169
+ *
170
+ * Every builder that copies the full parent env into a spawned child must
171
+ * route through this so a NEW one can't quietly skip it — the roster test
172
+ * enumerates every `{ ...process.env }`-shaped copier under `src/` and
173
+ * requires each to either call this helper or carry a documented exemption.
174
+ *
175
+ * @param {Record<string, string|undefined>} env - mutated in place
176
+ * @returns {Record<string, string|undefined>} the same object, for chaining
177
+ */
178
+ export function stripInheritedChroxySecrets(env) {
179
+ for (const key of CHROXY_INHERITED_SESSION_ENV) {
180
+ delete env[key]
181
+ }
182
+ return env
183
+ }
184
+
185
+ // #8262: markers a PARENT Claude Code session exports into the shell it opens.
186
+ // A daemon started from inside such a shell inherits them, and a `claude`
187
+ // child that sees them believes it is a nested session and turns transcript
188
+ // saving OFF ("inherited CLAUDE_CODE_CHILD_SESSION marker"), so `--resume`
189
+ // after a restart finds nothing and the model silently forgets earlier turns.
190
+ // These identify the PARENT session (its id, host session, attended flag and
191
+ // its messaging channel); a chroxy-spawned claude is a top-level session and
192
+ // must start with none of them. Deliberately NOT here: auth and config the
193
+ // daemon intends to hand on (CLAUDE_CODE_OAUTH_TOKEN, CLAUDE_CODE_ENTRYPOINT,
194
+ // CLAUDE_CODE_USE_* routing, CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING, ...).
195
+ export const CLAUDE_PARENT_SESSION_ENV = [
196
+ 'CLAUDECODE',
197
+ 'CLAUDE_CODE_CHILD_SESSION',
198
+ 'CLAUDE_CODE_SESSION_ID',
199
+ 'CLAUDE_CODE_HOST_SESSION_ID',
200
+ 'CLAUDE_CODE_SESSION_ATTENDED',
201
+ 'CLAUDE_CODE_MESSAGING_SOCKET',
202
+ 'CLAUDE_CODE_MESSAGING_TOKEN',
203
+ 'CLAUDE_CODE_BRIDGE_SESSION_ID',
204
+ // The parent's worktree and its write fence would otherwise confine an
205
+ // independent child's file writes to the parent's worktree.
206
+ 'CLAUDE_CODE_HOST_WORKTREE',
207
+ 'CLAUDE_CODE_HOST_WORKTREE_FENCE',
208
+ 'CLAUDE_PID',
88
209
  ]
89
210
 
211
+ /**
212
+ * Strip a parent Claude Code session's identity markers from a full
213
+ * parent-env copy, IN PLACE, before it is handed to a spawned `claude`
214
+ * (claude-cli, claude-sdk, claude-tui). See CLAUDE_PARENT_SESSION_ENV.
215
+ *
216
+ * @param {Record<string, string|undefined>} env - mutated in place
217
+ * @returns {Record<string, string|undefined>} the same object, for chaining
218
+ */
219
+ export function stripParentClaudeSessionEnv(env) {
220
+ for (const key of CLAUDE_PARENT_SESSION_ENV) {
221
+ delete env[key]
222
+ }
223
+ return env
224
+ }
225
+
226
+ /**
227
+ * A sanitized COPY of `base` for a host-side `claude` launch that has no other
228
+ * env builder (one-shot probes, `claude --remote`, `chroxy resume`, ...): the
229
+ * parent-session markers are removed so the launched claude is a top-level
230
+ * session. Same single roster as every other launch path.
231
+ *
232
+ * @param {Record<string, string|undefined>} [base=process.env]
233
+ * @returns {Record<string, string|undefined>} a new object
234
+ */
235
+ export function buildClaudeLaunchEnv(base = process.env) {
236
+ return sanitizeClaudeConfigDirEnv(stripParentClaudeSessionEnv({ ...base }))
237
+ }
238
+
90
239
  const PROVIDERS = {
91
240
  codex: {
92
241
  mode: 'allowlist',
@@ -130,6 +279,20 @@ const PROVIDERS = {
130
279
  'CLAUDE_CODE_OAUTH_TOKEN',
131
280
  ],
132
281
  },
282
+ 'claude-sdk': {
283
+ mode: 'denylist',
284
+ // The Agent SDK child: `query()` spawns `claude` itself and takes this
285
+ // object as its `env` option. The SDK's own default is the full parent
286
+ // env, and that is kept — everything the user's shell exports is
287
+ // available to Claude Code's tools — minus the chroxy-owned daemon
288
+ // secrets every denylist-mode provider strips (CHROXY_SECRET_DENYLIST,
289
+ // applied below). No ANTHROPIC_API_KEY strip: unlike the stream-json CLI
290
+ // provider, SdkSession accepts an API key as one of its auth sources
291
+ // (SdkSession.resolveAuth), and no credential-store injection either —
292
+ // the SDK child authenticates from the user's own `claude` login.
293
+ denylist: [],
294
+ storeInjectKeys: [],
295
+ },
133
296
  }
134
297
 
135
298
  /**
@@ -180,6 +343,18 @@ export function buildSpawnEnv(provider, extras = {}) {
180
343
  for (const key of effectiveDenylist) {
181
344
  delete parentEnv[key]
182
345
  }
346
+ // #7360: drop any AMBIENTLY-inherited CHROXY_PORT/CHROXY_HOOK_SECRET before
347
+ // `extras` (below) has a chance to reassert THIS session's own values —
348
+ // stripInheritedChroxySecrets must run before the `extras` merge, never
349
+ // after, or a session that DOES set its own port/secret would have them
350
+ // wiped right back out (see the helper's own doc comment).
351
+ stripInheritedChroxySecrets(parentEnv)
352
+ // #8262: denylist mode is the claude family (claude, claude-sdk); none may
353
+ // look like a nested session.
354
+ stripParentClaudeSessionEnv(parentEnv)
355
+ // #8270: claude and chroxy must use the same data dir, so a CLAUDE_CONFIG_DIR
356
+ // the shared resolver would reject is not handed to the child.
357
+ sanitizeClaudeConfigDirEnv(parentEnv)
183
358
  // #3855: inject ONLY this provider's own credential-store keys that the
184
359
  // shell did not export (e.g. CLAUDE_CODE_OAUTH_TOKEN for claude). Scoped via
185
360
  // the per-provider `storeInjectKeys` allowlist so other providers' stored
@@ -195,5 +370,15 @@ export function buildSpawnEnv(provider, extras = {}) {
195
370
  if (resolved.value) parentEnv[key] = resolved.value
196
371
  }
197
372
  // #6633: Chroxy host identity, computed and authoritative (see allowlist branch).
198
- return { ...parentEnv, ...getChroxyHostEnv(), ...extras }
373
+ // `extras` may carry its own value; the same rule applies to it. An explicit
374
+ // unusable override means "fall back", so it must not let the parent's valid
375
+ // value take its place.
376
+ const safeExtras = { ...extras }
377
+ for (const key of ['CLAUDE_CONFIG_DIR', process.platform === 'win32' ? 'USERPROFILE' : 'HOME']) {
378
+ if (Object.hasOwn(safeExtras, key) && safeExtras[key] !== undefined) {
379
+ sanitizeClaudeConfigDirEnv(safeExtras)
380
+ if (!Object.hasOwn(safeExtras, key)) delete parentEnv[key]
381
+ }
382
+ }
383
+ return { ...parentEnv, ...getChroxyHostEnv(), ...safeExtras }
199
384
  }
@@ -0,0 +1,182 @@
1
+ import { chmodSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'fs'
2
+ import { join } from 'path'
3
+
4
+ /**
5
+ * Boot-time reaper for per-session scratch dirs under the OS tmpdir.
6
+ *
7
+ * A session removes its own dir in destroy(), but a CRASH leaks it forever, so
8
+ * a long-lived host accumulates one dir per crashed session. Introduced for
9
+ * `claude-tui`'s hook-sink dirs (#5323); generalised in #7337 when `claude-cli`
10
+ * gained a per-session dir of its own for the permission-mode sidecar. It is
11
+ * ONE implementation on purpose — a second hand-written copy of a
12
+ * "delete directories under /tmp" loop is exactly the drift `docs/false-safety-guards.md`
13
+ * catalogues, and this one deletes things.
14
+ *
15
+ * The ownership rule mirrors the worktree reaper's dead-pid-lock logic: each
16
+ * dir carries an `owner.pid` written at creation, and a dir is removed only
17
+ * when its owner is DEAD. A live owner — this just-booted daemon, or another
18
+ * chroxy on the host — keeps its dirs, so the sweep is safe to run
19
+ * unconditionally at boot: our own pid is alive, so we never delete a dir we
20
+ * are about to use.
21
+ */
22
+
23
+ /** Default grace for a pidfile-less dir. See the race note in sweepStaleOwnedDirs. */
24
+ export const OWNED_DIR_SWEEP_GRACE_MS = 60_000
25
+
26
+ /** Filename each owner stamps inside its dir so the sweep can probe liveness. */
27
+ export const OWNER_PID_FILE = 'owner.pid'
28
+
29
+ /**
30
+ * Never deletes through a base it does not own: a `base` that is a symlink, is
31
+ * not a directory, or (POSIX) belongs to another uid is skipped with a warning
32
+ * and zero counts (#7872). A missing base returns zero counts silently.
33
+ *
34
+ * @param {string} base Parent dir to scan (e.g. `/tmp/chroxy-claude-tui`).
35
+ * @param {object} [opts]
36
+ * @param {string} [opts.prefix='s-'] Only entries with this prefix are considered.
37
+ * @param {number} [opts.graceMs] Grace for pidfile-less dirs.
38
+ * @param {object} [opts.logger] Logger with info/warn.
39
+ * @param {string} [opts.label] Human name for the log line.
40
+ * @returns {{swept:number, kept:number}}
41
+ */
42
+ export function sweepStaleOwnedDirs(base, { prefix = 's-', graceMs = OWNED_DIR_SWEEP_GRACE_MS, logger, label = base } = {}) {
43
+ // #7872 — refuse a base we do not own BEFORE listing it. The sweep runs at
44
+ // boot, before any session start, so before ensureOwnedBaseDir has ever
45
+ // looked at this path. On a shared /tmp another local user can pre-create
46
+ // the base as a symlink to a directory of their choosing, and an unchecked
47
+ // readdir + rmSync would then delete that directory's orphan-looking `s-*`
48
+ // children. Same refusal as ensureOwnedBaseDir (symlink, not a directory,
49
+ // foreign uid), with one deliberate difference: this SKIPS with a warning
50
+ // instead of throwing. The sweep is hygiene, not correctness, and a throwing
51
+ // refusal would let one planted symlink wedge daemon boot. Nothing here
52
+ // mutates `base` — so an owned base that is group/other-writable is swept
53
+ // as-is; chmod-ing it back to 0700 stays ensureOwnedBaseDir's job.
54
+ let st
55
+ try { st = lstatSync(base) } catch { return { swept: 0, kept: 0 } } // missing base: the common path, stay silent
56
+ const refuse = (reason) => {
57
+ logger?.warn?.(`stale-dir sweep: refusing to sweep ${base}: ${reason}`)
58
+ return { swept: 0, kept: 0 }
59
+ }
60
+ if (st.isSymbolicLink()) return refuse('it is a symlink')
61
+ if (!st.isDirectory()) return refuse('it is not a directory')
62
+ // POSIX only, as in ensureOwnedBaseDir: Windows has no uid, and its per-user
63
+ // profile tmpdir already provides the isolation this check stands in for.
64
+ // The symlink and is-a-directory checks above apply everywhere.
65
+ const uid = process.getuid?.()
66
+ if (uid !== undefined && st.uid !== uid) return refuse(`it is owned by uid ${st.uid}, not ${uid}`)
67
+
68
+ let entries
69
+ try { entries = readdirSync(base) } catch { return { swept: 0, kept: 0 } }
70
+ let swept = 0
71
+ let kept = 0
72
+ for (const name of entries) {
73
+ if (!name.startsWith(prefix)) continue
74
+ const dir = join(base, name)
75
+ let ownerPid = null
76
+ try {
77
+ // statSync + isFile() BEFORE the read: readFileSync on a FIFO blocks
78
+ // forever with no timeout, so a planted `owner.pid` fifo would hang the
79
+ // daemon's boot sweep. A non-regular pidfile is treated as garbage, which
80
+ // routes to the grace-window branch below — the safe default for an orphan.
81
+ const pidPath = join(dir, OWNER_PID_FILE)
82
+ if (statSync(pidPath).isFile()) {
83
+ const n = parseInt(readFileSync(pidPath, 'utf8').trim(), 10)
84
+ if (Number.isInteger(n) && n > 0) ownerPid = n
85
+ }
86
+ } catch { /* no/garbage pidfile → orphaned, subject to the grace below */ }
87
+ if (ownerPid !== null) {
88
+ let alive
89
+ try {
90
+ process.kill(ownerPid, 0) // signal 0 = existence probe
91
+ alive = true
92
+ } catch (err) {
93
+ // ESRCH → dead; EPERM → exists but not ours → still alive, keep it.
94
+ alive = err && err.code === 'EPERM'
95
+ }
96
+ if (alive) { kept++; continue }
97
+ } else {
98
+ // #5359 review — a pidfile-less dir might be another process's dir caught
99
+ // BETWEEN its mkdir and its owner.pid write (a cross-process race; within
100
+ // one process those are synchronous). Give brand-new pidfile-less dirs a
101
+ // grace window before reaping so we can't delete one mid-creation; a
102
+ // genuinely orphaned dir is older than the grace and still gets swept.
103
+ try {
104
+ // #5332: wall-clock deliberately — compared against the filesystem
105
+ // mtime (also wall-clock). A monotonic clock would be meaningless here.
106
+ if (Date.now() - statSync(dir).mtimeMs < graceMs) {
107
+ kept++
108
+ continue
109
+ }
110
+ } catch { /* stat failed (dir vanished) → fall through to rmSync (no-op) */ }
111
+ }
112
+ try {
113
+ rmSync(dir, { recursive: true, force: true })
114
+ swept++
115
+ } catch (err) {
116
+ logger?.warn?.(`stale-dir sweep: failed to remove ${dir}: ${err.message}`)
117
+ }
118
+ }
119
+ if (swept > 0) logger?.info?.(`Swept ${swept} stale ${label} dir(s) from ${base} (kept ${kept} live)`)
120
+ return { swept, kept }
121
+ }
122
+
123
+ /**
124
+ * Create (or adopt) the shared BASE dir that per-session dirs live under, and
125
+ * refuse to use one an attacker could have prepared.
126
+ *
127
+ * `mkdirSync(base, { recursive: true })` returns silently when `base` already
128
+ * exists — INCLUDING when it is a symlink to a directory — and then creates
129
+ * children through it. On Linux `os.tmpdir()` is the shared `/tmp`, so another
130
+ * local user can pre-create `/tmp/chroxy-claude-cli` (or point it elsewhere)
131
+ * and then substitute a session dir whose `permission-mode` reads `auto`. The
132
+ * hook re-reads that file on every tool call, so the substitution decides
133
+ * whether tool calls are prompted. macOS is unaffected — its `$TMPDIR` is a
134
+ * per-user directory at 0700 — which is exactly why this needs an explicit
135
+ * check rather than a platform assumption.
136
+ *
137
+ * Throws when the base is a symlink, is not a directory, or (POSIX) is owned by
138
+ * another uid. A base we DO own that is group/other-writable is not refused:
139
+ * it is chmod-ed back to 0700 before use. What a caller DOES with that refusal
140
+ * is the caller's call, and the four callers deliberately differ (#7372,
141
+ * #8047): `CliSession` degrades to env-var-only, because its base carries
142
+ * only the permission-mode sidecar and losing mid-session mode switching
143
+ * beats losing the session. `ClaudeTuiSession` REFUSES to start — its base
144
+ * carries the whole hook pipeline (settings.json, the hook payloads AND the
145
+ * sidecar), so running on would be a session that reports success while the
146
+ * permission floor is silently unenforced. `CodexAppServerSession` sends the
147
+ * turn as text-only (no attachments); `DockerByokSession` runs the container
148
+ * without the key forwarded via `--env-file` — both are the same "degrade
149
+ * rather than fail the session" choice `CliSession` makes, for the same
150
+ * reason: the refused artifact is not load-bearing for the rest of the
151
+ * session. Do not read any of these as the contract for a fifth caller;
152
+ * decide it from what the base holds.
153
+ *
154
+ * @param {string} base Directory to create or adopt.
155
+ * @returns {string} `base`, once it is safe to write into.
156
+ */
157
+ export function ensureOwnedBaseDir(base) {
158
+ mkdirSync(base, { recursive: true, mode: 0o700 })
159
+ const st = lstatSync(base)
160
+ if (st.isSymbolicLink()) {
161
+ throw new Error(`${base} is a symlink — refusing to write session state through it`)
162
+ }
163
+ if (!st.isDirectory()) {
164
+ throw new Error(`${base} exists and is not a directory`)
165
+ }
166
+ // Everything below is POSIX permission semantics. Windows has no uid and its
167
+ // `mode` bits are a synthetic approximation — `st.mode & 0o077` is non-zero
168
+ // for essentially every directory there, so this would chmod on every single
169
+ // start() to no effect. The isolation these checks stand in for is already
170
+ // provided on Windows by the per-user profile tmpdir that `os.tmpdir()`
171
+ // returns. The symlink and is-a-directory checks above DO apply everywhere.
172
+ const uid = process.getuid?.()
173
+ if (uid === undefined) return base
174
+
175
+ if (st.uid !== uid) {
176
+ throw new Error(`${base} is owned by uid ${st.uid}, not ${uid} — refusing to adopt it`)
177
+ }
178
+ // mkdir's mode is masked by umask, and an ADOPTED dir keeps whatever mode it
179
+ // already had — so re-assert rather than trust the create.
180
+ if (st.mode & 0o077) chmodSync(base, 0o700)
181
+ return base
182
+ }