@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
@@ -1,52 +1,72 @@
1
1
  /**
2
- * Conversation listing / search scope enforcement.
2
+ * Conversation listing / search / transcript scope.
3
3
  *
4
- * Closes Adversary A8 (2026-04-11 audit). Previously,
5
- * `list_conversations` and `search_conversations` scanned every JSONL
6
- * under `~/.claude/projects/**` and returned the full set to any
7
- * authenticated client — including bound pairing-issued mobile clients
8
- * that should only see the session they were paired for. A mobile user
9
- * could enumerate every Claude Code conversation across every project
10
- * on the operator's machine, grep for secrets-in-transcripts, and
11
- * identify high-value targets for follow-up attacks.
4
+ * - **Unbound client** (main API token, desktop dashboard, test client):
5
+ * everything, unchanged. Unbound clients already have full-token access, so
6
+ * filtering would only hide conversations behind a cosmetic scope.
12
7
  *
13
- * Defense: scope the result set to what the client is allowed to see.
14
- *
15
- * - **Bound client** (has `client.boundSessionId`): only conversations
16
- * whose recorded `cwd` is the bound session's cwd, or a subdirectory
17
- * of it. If the bound session has no cwd (shouldn't happen, but
18
- * defensive), return the empty set.
19
- *
20
- * - **Unbound client** (main API token, desktop dashboard, test
21
- * client): return the full set unchanged. Unbound clients already
22
- * have full-token access and can create any session they want;
23
- * filtering here would just hide conversations behind a cosmetic
24
- * scope.
25
- *
26
- * This is a soft defense — an attacker who holds the main API token
27
- * can already read the files directly. The check exists specifically
28
- * to shrink the blast radius of a compromised pairing token.
8
+ * - **Bound client** (`client.boundSessionId` is set, including an empty or
9
+ * non-string value — those are bindings that name no session, and they match
10
+ * nothing): only the conversation the bound session is itself running.
11
+ * Directory containment is NOT ownership. Two sessions can share a project
12
+ * directory, and a project can sit beneath another session's directory, so a
13
+ * conversation recorded under the bound session's cwd may belong to a
14
+ * different session. A conversation is visible to a bound client only when:
15
+ * 1. its id equals the conversation the daemon associates with the bound
16
+ * session (`sessionManager.getConversationId`), AND
17
+ * 2. its recorded cwd is the bound session's cwd or beneath it.
18
+ * When the daemon does not know the association (a session that has not
19
+ * started a conversation yet, or a manager that cannot report one) the answer
20
+ * is "none": the scope fails closed rather than falling back to the directory.
29
21
  */
22
+ import { isAbsolute } from 'path'
30
23
  import { isPathWithin } from './handler-utils.js'
24
+ import { isBoundClient } from './environments/authority.js'
25
+
26
+ /**
27
+ * The conversation id the daemon associates with the client's bound session, or
28
+ * null when it is unknown or the client is not usable as a bound client.
29
+ * @param {object} client
30
+ * @param {object} ctx
31
+ * @returns {string|null}
32
+ */
33
+ export function boundConversationId(client, ctx) {
34
+ const sid = client?.boundSessionId
35
+ if (typeof sid !== 'string' || sid.length === 0) return null
36
+ const id = ctx?.sessions?.sessionManager?.getConversationId?.(sid)
37
+ return typeof id === 'string' && id.length > 0 ? id : null
38
+ }
39
+
40
+ /**
41
+ * May this client read the conversation `conversationId` recorded under `cwd`?
42
+ * Unbound clients always may. A bound client may only when it is the bound
43
+ * session's own conversation and `cwd` is inside the session's directory.
44
+ * @param {{ conversationId: string, cwd: string|null }} conv
45
+ * @param {object} client
46
+ * @param {object} ctx
47
+ * @returns {boolean}
48
+ */
49
+ export function clientOwnsConversation(conv, client, ctx) {
50
+ if (!isBoundClient(client)) return true
51
+ const ownId = boundConversationId(client, ctx)
52
+ if (!ownId || conv?.conversationId !== ownId) return false
53
+ const allowedCwd = ctx?.sessions?.sessionManager?.getSession?.(client.boundSessionId)?.cwd
54
+ if (!allowedCwd || typeof allowedCwd !== 'string' || !isAbsolute(allowedCwd)) return false
55
+ // `isPathWithin` refuses a non-absolute argument (#7273), and `cwd` is read
56
+ // out of a record on disk: anything unusable fails closed.
57
+ const cwd = conv?.cwd
58
+ if (!cwd || typeof cwd !== 'string' || !isAbsolute(cwd)) return false
59
+ return isPathWithin(cwd, allowedCwd)
60
+ }
31
61
 
32
62
  /**
33
- * @param {Array<{ cwd: string|null }>} conversations
63
+ * @param {Array<{ conversationId: string, cwd: string|null }>} conversations
34
64
  * @param {object} client - Connected client state
35
- * @param {object} ctx - Handler context (needs `sessionManager.getSession`)
65
+ * @param {object} ctx - Handler context (needs `sessions.sessionManager`)
36
66
  * @returns {Array} Filtered conversation list
37
67
  */
38
68
  export function scopeConversationsToClient(conversations, client, ctx) {
39
69
  if (!Array.isArray(conversations)) return []
40
- // Unbound clients: full token, full visibility.
41
- if (!client?.boundSessionId) return conversations
42
- const entry = ctx?.sessions?.sessionManager?.getSession?.(client.boundSessionId)
43
- const allowedCwd = entry?.cwd
44
- // Bound-but-cwd-missing: fail closed. A bound client should not see
45
- // *any* conversation if we can't confidently scope the result.
46
- if (!allowedCwd || typeof allowedCwd !== 'string') return []
47
- return conversations.filter((conv) => {
48
- const cwd = conv?.cwd
49
- if (!cwd || typeof cwd !== 'string') return false
50
- return cwd === allowedCwd || isPathWithin(cwd, allowedCwd)
51
- })
70
+ if (!isBoundClient(client)) return conversations
71
+ return conversations.filter((conv) => clientOwnsConversation(conv, client, ctx))
52
72
  }
@@ -1,10 +1,10 @@
1
- import { readdir, stat, readFile, open } from 'fs/promises'
1
+ import { readdir, stat, realpath } from 'fs/promises'
2
+ import { readContainedBytes } from './utils/regular-file.js'
2
3
  import { join, basename } from 'path'
3
- import { homedir } from 'os'
4
+ import { claudeProjectsDir } from './utils/claude-config-dir.js'
4
5
  import { decodeProjectPath } from './jsonl-reader.js'
5
6
  import { runWithConcurrency } from './utils/concurrency.js'
6
7
 
7
- const PROJECTS_DIR = join(homedir(), '.claude', 'projects')
8
8
  const MIN_FILE_SIZE = 100
9
9
  const CONCURRENCY = 10
10
10
  const MAX_FILE_READ = 512 * 1024 // read up to 512KB per file for search
@@ -43,26 +43,17 @@ export function extractSearchableText(entry) {
43
43
  * Search a single JSONL conversation file for a query string.
44
44
  * Returns null if no match, or a result object if found.
45
45
  */
46
- async function searchFile(filePath, queryLower, conversationId, projectName, decodedPath) {
46
+ async function searchFile(filePath, queryLower, conversationId, projectName, decodedPath, root) {
47
47
  let text
48
48
  try {
49
49
  const fileStat = await stat(filePath)
50
50
  if (fileStat.size < MIN_FILE_SIZE) return null
51
51
 
52
- // Read file content (capped at MAX_FILE_READ)
53
- if (fileStat.size <= MAX_FILE_READ) {
54
- text = await readFile(filePath, 'utf-8')
55
- } else {
56
- const buf = Buffer.alloc(MAX_FILE_READ)
57
- const handle = await open(filePath, 'r')
58
- try {
59
- const { bytesRead } = await handle.read(buf, 0, MAX_FILE_READ, 0)
60
- const decoder = new TextDecoder('utf-8', { fatal: false })
61
- text = decoder.decode(buf.subarray(0, bytesRead))
62
- } finally {
63
- await handle.close()
64
- }
65
- }
52
+ // Read file content (capped at MAX_FILE_READ). The open never blocks and
53
+ // refuses anything that is not a regular file (utils/regular-file.js).
54
+ const bytes = await readContainedBytes(filePath, root, MAX_FILE_READ, { head: true })
55
+ if (bytes === null) return null
56
+ text = new TextDecoder('utf-8', { fatal: false }).decode(bytes)
66
57
  } catch {
67
58
  return null
68
59
  }
@@ -143,6 +134,8 @@ async function searchFile(filePath, queryLower, conversationId, projectName, dec
143
134
  * @param {Object} [opts] - Options
144
135
  * @param {string} [opts.projectsDir] - Root directory to scan
145
136
  * @param {number} [opts.maxResults] - Maximum results to return (default 50)
137
+ * @param {string} [opts.conversationId] - Search only this conversation's file
138
+ * @param {string} [opts.projectDirName] - Search only this project directory
146
139
  * @returns {Promise<Array<{
147
140
  * conversationId: string,
148
141
  * projectName: string,
@@ -160,13 +153,15 @@ export async function searchConversations(query, opts = {}) {
160
153
  if (trimmed.length > MAX_QUERY_LENGTH) return []
161
154
 
162
155
  const queryLower = trimmed.toLowerCase()
163
- const projectsDir = opts.projectsDir || PROJECTS_DIR
156
+ const projectsDir = opts.projectsDir || claudeProjectsDir()
164
157
  const maxResults = opts.maxResults || DEFAULT_MAX_RESULTS
165
158
 
166
159
  // Collect all JSONL files across projects
167
160
  let projectDirs
161
+ let rootReal
168
162
  try {
169
- projectDirs = await readdir(projectsDir, { withFileTypes: true })
163
+ rootReal = await realpath(projectsDir)
164
+ projectDirs = await readdir(rootReal, { withFileTypes: true })
170
165
  } catch {
171
166
  return []
172
167
  }
@@ -175,9 +170,13 @@ export async function searchConversations(query, opts = {}) {
175
170
  for (const dir of projectDirs) {
176
171
  if (!dir.isDirectory()) continue
177
172
  const encodedName = dir.name
173
+ // Restricted to one project directory: every other project is skipped before
174
+ // any of its files is listed or read, so the same conversation id in a
175
+ // different project cannot take part in the ranking.
176
+ if (opts.projectDirName && encodedName !== opts.projectDirName) continue
178
177
  const decodedPath = decodeProjectPath(encodedName)
179
178
  const projectName = decodedPath ? basename(decodedPath) : encodedName
180
- const dirPath = join(projectsDir, encodedName)
179
+ const dirPath = join(rootReal, encodedName)
181
180
 
182
181
  let files
183
182
  try {
@@ -187,6 +186,9 @@ export async function searchConversations(query, opts = {}) {
187
186
  }
188
187
 
189
188
  for (const file of files.filter((f) => f.endsWith('.jsonl'))) {
189
+ // Restricted to one conversation: every other file is skipped BEFORE it is
190
+ // read, so what is ranked and truncated below is only what the caller may see.
191
+ if (opts.conversationId && file !== `${opts.conversationId}.jsonl`) continue
190
192
  candidates.push({
191
193
  filePath: join(dirPath, file),
192
194
  conversationId: file.replace('.jsonl', ''),
@@ -198,7 +200,7 @@ export async function searchConversations(query, opts = {}) {
198
200
 
199
201
  // Search files in parallel
200
202
  const tasks = candidates.map((c) => () =>
201
- searchFile(c.filePath, queryLower, c.conversationId, c.projectName, c.decodedPath)
203
+ searchFile(c.filePath, queryLower, c.conversationId, c.projectName, c.decodedPath, rootReal)
202
204
  )
203
205
 
204
206
  const results = await runWithConcurrency(tasks, CONCURRENCY)
@@ -42,13 +42,14 @@
42
42
  * docs/security/credentials-at-rest.md for the full threat model.
43
43
  */
44
44
  import { readFileSync, statSync, writeFileSync, chmodSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'fs'
45
- import { join, dirname } from 'path'
46
- import { homedir } from 'os'
45
+ import { dirname } from 'path'
47
46
  import { randomBytes } from 'crypto'
48
47
  import { maskApiKey } from './byok-credentials.js'
49
48
  import * as realKeychain from './keychain.js'
50
49
  import { createLogger } from './logger.js'
51
50
  import { fsyncForDurability, confirmRenameDurable } from './platform.js'
51
+ import { configPath } from './config-dir.js'
52
+ import { readTrustedSecretFile } from './trusted-file-read.js'
52
53
  import {
53
54
  CRED_KEY_SERVICE,
54
55
  isEncryptedEnvelope,
@@ -215,12 +216,19 @@ export function isKnownCredentialKey(key) {
215
216
  // Lazy-resolved per call so tests that mutate process.env.HOME between cases
216
217
  // pick up the new home; if captured at module load it would freeze on first import.
217
218
  function credentialsFilePath() {
218
- return join(homedir(), '.chroxy', 'credentials.json')
219
+ return configPath('credentials.json')
219
220
  }
220
221
 
221
222
  /**
222
223
  * Read + parse the credentials file, enforcing the 0600 mode boundary.
223
224
  *
225
+ * #7893: the mode check and the read go through `readTrustedSecretFile` —
226
+ * ONE `open(O_NOFOLLOW)` + `fstat(fd)` + read from that same fd, so a
227
+ * rename or symlink-swap of `credentials.json` between the mode check and
228
+ * the read (the old `statSync(path)` then `readFileSync(path)` shape) is
229
+ * refused outright — a symlink is never followed, regardless of what its
230
+ * target's own mode is.
231
+ *
224
232
  * @returns {{ data: Record<string, string>, fileExists: boolean, error: string | null }}
225
233
  * `data` is the parsed object (empty when missing/unreadable). `error` is a
226
234
  * human-readable reason when the file exists but cannot be safely read
@@ -228,31 +236,27 @@ function credentialsFilePath() {
228
236
  */
229
237
  function readStore() {
230
238
  const file = credentialsFilePath()
231
- let stat
232
- try {
233
- stat = statSync(file)
234
- } catch (err) {
235
- if (err.code === 'ENOENT') return { data: {}, fileExists: false, error: null }
236
- return { data: {}, fileExists: false, error: `unable to stat ${file}: ${err.message}` }
237
- }
238
-
239
- // Refuse any mode that is not exactly 0600 (POSIX) — both more-permissive
240
- // (e.g. 0644) and stricter (e.g. 0400) modes are rejected. On win32 the mode
241
- // bits don't reflect NTFS ACLs, so skip the check there (matches #4144).
242
- if (process.platform !== 'win32') {
243
- const perms = stat.mode & 0o777
244
- if (perms !== 0o600) {
239
+ const result = readTrustedSecretFile(file, { mode: 0o600 })
240
+ if (result.status === 'absent') return { data: {}, fileExists: false, error: null }
241
+ if (result.status === 'refused') {
242
+ // Refuse any mode that is not exactly 0600 (POSIX) — both more-permissive
243
+ // (e.g. 0644) and stricter (e.g. 0400) modes are rejected. On win32 the mode
244
+ // bits don't reflect NTFS ACLs, so skip the check there (matches #4144).
245
+ if (result.code === 'EMODE') {
245
246
  return {
246
247
  data: {},
247
248
  fileExists: true,
248
- error: `${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600 — run: chmod 600 ${file})`,
249
+ error: `${file} has mode ${result.mode.toString(8).padStart(3, '0')}; refusing to read (must be 0600 — run: chmod 600 ${file})`,
249
250
  }
250
251
  }
252
+ // Any other refusal (open/fstat failure, symlink refused, not a regular
253
+ // file, …) — never assumed absent; surfaced as a read failure.
254
+ return { data: {}, fileExists: false, error: `unable to stat ${file}: ${result.cause ? result.cause.message : result.code}` }
251
255
  }
252
256
 
253
257
  let parsed
254
258
  try {
255
- parsed = JSON.parse(readFileSync(file, 'utf8'))
259
+ parsed = JSON.parse(result.content)
256
260
  } catch (err) {
257
261
  return { data: {}, fileExists: true, error: `${file} unreadable or not valid JSON: ${err.message}` }
258
262
  }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The commit this daemon was started from (#8324).
3
+ *
4
+ * The idle-only auto-deploy (`scripts/deploy-daemon.mjs`) must know what the
5
+ * RUNNING process is, not infer it from pids and journals: after a restart it
6
+ * counts only if the daemon itself reports the desired commit. So the daemon
7
+ * resolves it once, at startup, from its own checkout.
8
+ *
9
+ * `git rev-parse HEAD` is run at the repo root derived from this file's
10
+ * location, and the answer is accepted only if git says that directory IS the
11
+ * top level of a checkout: a server installed under `node_modules` inside some
12
+ * other project would otherwise report THAT project's HEAD. Any failure
13
+ * (git missing, not a checkout, timeout, odd output) is `null`; this never throws.
14
+ */
15
+ import { spawnSync } from 'node:child_process'
16
+ import { realpathSync } from 'node:fs'
17
+ import path, { dirname, resolve } from 'node:path'
18
+ import { fileURLToPath } from 'node:url'
19
+ import { CHROXY_INHERITED_SESSION_ENV, CHROXY_SECRET_DENYLIST, stripInheritedChroxySecrets } from './utils/spawn-env.js'
20
+
21
+ const FULL_SHA = /^[0-9a-f]{40}$/
22
+
23
+ /**
24
+ * @param {string} dir - the directory that must be the root of a git checkout
25
+ * @param {{ spawn?: Function }} [deps]
26
+ * @returns {string|null} 40-hex HEAD, or null
27
+ */
28
+ export function resolveRepoCommit(dir, { spawn = spawnSync } = {}) {
29
+ // One retry: a CPU spike at restart can time a single attempt out, and a good
30
+ // build that reports `commit: null` is judged unverified and rolled back.
31
+ return attempt(dir, spawn) ?? attempt(dir, spawn)
32
+ }
33
+
34
+ /**
35
+ * Are these two paths the same directory? `git rev-parse --show-toplevel` prints
36
+ * forward slashes even on Windows (`A:/runners/x`), and a CI runner's temp path
37
+ * can be an 8.3 short name, so a string compare of the two is wrong there.
38
+ * Both sides go through `realpath.native` (which expands short names) and the
39
+ * platform's own `resolve` (which normalises the separators), then compare
40
+ * case-insensitively on Windows only. Pure: the platform, `path` module and
41
+ * realpath are parameters so Windows-shaped inputs are testable anywhere.
42
+ *
43
+ * @param {string} a
44
+ * @param {string} b
45
+ * @param {{ path?: typeof path, realpath?: (p: string) => string, windows?: boolean }} [deps]
46
+ */
47
+ export function isSameDirectory(a, b, { path: p = path, realpath = realpathSync.native, windows = process.platform === 'win32' } = {}) {
48
+ try {
49
+ const norm = (x) => {
50
+ const r = p.resolve(realpath(p.resolve(x)))
51
+ return windows ? r.toLowerCase() : r
52
+ }
53
+ return norm(a) === norm(b)
54
+ } catch {
55
+ return false
56
+ }
57
+ }
58
+
59
+ // The environment git is spawned with. EVERY GIT_* variable goes, not a
60
+ // hand-picked few: GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR, GIT_CEILING_DIRECTORIES,
61
+ // GIT_CONFIG_* ... each can point git at some other repository or change what it
62
+ // prints. And git has no use for the daemon's own secrets (API_TOKEN, the hook
63
+ // and ingest secrets), so those are stripped too.
64
+ function buildGitEnv() {
65
+ // Keys are compared case-INSENSITIVELY: Windows treats `Git_Dir` as `GIT_DIR`.
66
+ const env = {}
67
+ for (const [k, v] of Object.entries(process.env)) if (!k.toUpperCase().startsWith('GIT_')) env[k] = v
68
+ stripInheritedChroxySecrets(env)
69
+ const secret = new Set([...CHROXY_SECRET_DENYLIST, ...CHROXY_INHERITED_SESSION_ENV].map((k) => k.toUpperCase()))
70
+ for (const k of Object.keys(env)) if (secret.has(k.toUpperCase())) delete env[k]
71
+ return env
72
+ }
73
+
74
+ function attempt(dir, spawn) {
75
+ try {
76
+ const r = spawn('git', ['rev-parse', '--show-toplevel', 'HEAD'], {
77
+ cwd: dir, encoding: 'utf8', timeout: 5000, env: buildGitEnv(), stdio: ['ignore', 'pipe', 'ignore'],
78
+ })
79
+ if (!r || r.error || r.status !== 0 || typeof r.stdout !== 'string') return null
80
+ const [top, sha, ...extra] = r.stdout.trim().split('\n')
81
+ if (extra.length > 0 || !FULL_SHA.test(sha ?? '')) return null
82
+ if (!isSameDirectory(top, dir)) return null
83
+ return sha
84
+ } catch {
85
+ return null
86
+ }
87
+ }
88
+
89
+ const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', '..')
90
+
91
+ /** Resolved once, when the daemon loads this module. */
92
+ export const DAEMON_COMMIT = resolveRepoCommit(REPO_ROOT)
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Is the daemon safe to restart right now? (#8324)
3
+ *
4
+ * The idle-only auto-deploy (`scripts/deploy-daemon.mjs`) restarts the owner's
5
+ * daily daemon, which kills every live session. It may only do that when
6
+ * nothing would be lost. "Idle" here is deliberately strict and means ALL of:
7
+ *
8
+ * - no session is busy (a turn is running, OR a tracked background shell
9
+ * still holds the session busy — `isBusy` merges both, #8302)
10
+ * - no session has a permission request waiting on a human
11
+ * - no session has an AskUserQuestion waiting on a human
12
+ * - no hook-routed permission request is parked on the daemon
13
+ * - nothing `getRestartBlockers()` names: work `isBusy` does not report, such
14
+ * as a background agent that outlived its turn, input accepted but not yet
15
+ * dispatched, or a TUI whose terminal is still producing output
16
+ * - no session's provider has produced output in the last
17
+ * PROVIDER_QUIET_WINDOW_MS (#8743). `isBusy` is the daemon's own turn
18
+ * bookkeeping, and when that is wrong the provider is still working while
19
+ * the session reads idle: trial run B2-cy-codex lost a 17-minute Codex run to
20
+ * a restart while codex emitted every few seconds. The window is read from
21
+ * what the provider SAID (`providerActivityAgeMs`), not from the turn state.
22
+ *
23
+ * FAIL SAFE. Every uncertainty reads as NOT idle. "Could not check" must never
24
+ * be the same observable outcome as "nothing to check" (docs/false-safety-guards.md):
25
+ * a missing session manager, a throwing accessor and a malformed row each add a
26
+ * reason and force `idle: false`. A deploy that is wrongly deferred costs a
27
+ * ten-minute wait; a deploy that is wrongly allowed kills a running turn.
28
+ */
29
+
30
+ /**
31
+ * How long every session's provider must have been silent before the daemon
32
+ * may be restarted (#8743). A working provider emits every few seconds, so the
33
+ * window holds a restart off across ordinary pauses; only a single silent
34
+ * stretch longer than the window (one long command that reports nothing) gets
35
+ * through, and then only when `isBusy` is wrong too. Shorter than the deploy
36
+ * tick, so a quiet daemon still deploys on the next tick or the one after.
37
+ */
38
+ export const PROVIDER_QUIET_WINDOW_MS = 5 * 60 * 1000
39
+
40
+ /**
41
+ * @param {object} input
42
+ * @param {object|null|undefined} input.sessionManager - exposes listSessions()
43
+ * and getSession(id).
44
+ * @param {() => number} [input.getHookPendingPermissionCount] - hook-routed
45
+ * requests parked on the daemon.
46
+ * @returns {{ idle: boolean, reasons: string[], sessions: object[], hookPendingPermissions: number }}
47
+ */
48
+ export function computeDaemonIdleState({ sessionManager, getHookPendingPermissionCount } = {}) {
49
+ const reasons = []
50
+ const sessions = []
51
+ let hookPendingPermissions = 0
52
+
53
+ if (!sessionManager || typeof sessionManager.listSessions !== 'function') {
54
+ reasons.push('idle state unavailable: no session manager')
55
+ return { idle: false, reasons, sessions, hookPendingPermissions }
56
+ }
57
+
58
+ let rows
59
+ try {
60
+ rows = sessionManager.listSessions()
61
+ if (!Array.isArray(rows)) throw new Error('listSessions() did not return an array')
62
+ } catch (err) {
63
+ reasons.push(`idle state unavailable: ${err?.message || String(err)}`)
64
+ return { idle: false, reasons, sessions, hookPendingPermissions }
65
+ }
66
+
67
+ for (const row of rows) {
68
+ const sessionId = row?.sessionId
69
+ const label = row?.name ? `"${row.name}"` : String(sessionId)
70
+ let pendingPermissions = 0
71
+ let pendingQuestions = 0
72
+ let restartBlockers = []
73
+ let providerActivityAgeMs = null
74
+ try {
75
+ const entrySession = sessionManager.getSession?.(sessionId)?.session
76
+ if (!entrySession) {
77
+ // A row with no live session behind it cannot be inspected.
78
+ throw new Error(`session ${label} not inspectable`)
79
+ }
80
+ pendingPermissions = countPending(entrySession, 'pending permission count', () => entrySession.getPendingPermissionCount())
81
+ pendingQuestions = countPending(entrySession, 'pending question count', () => entrySession.getPendingQuestions().length)
82
+ restartBlockers = readBlockers(entrySession)
83
+ providerActivityAgeMs = readActivityAge(entrySession)
84
+ } catch (err) {
85
+ reasons.push(`idle state unavailable for session ${label}: ${err?.message || String(err)}`)
86
+ pendingPermissions = 0
87
+ pendingQuestions = 0
88
+ restartBlockers = []
89
+ providerActivityAgeMs = null
90
+ }
91
+ const isBusy = row?.isBusy === true
92
+ sessions.push({
93
+ sessionId,
94
+ name: row?.name ?? null,
95
+ isBusy,
96
+ busyReason: row?.busyReason ?? null,
97
+ backgroundShellCount: Number.isSafeInteger(row?.backgroundShellCount) ? row.backgroundShellCount : 0,
98
+ pendingPermissions,
99
+ pendingQuestions,
100
+ restartBlockers,
101
+ providerActivityAgeMs,
102
+ })
103
+ if (isBusy) reasons.push(`session ${label} busy: ${row?.busyReason || 'turn'}`)
104
+ if (pendingPermissions > 0) reasons.push(`session ${label} has ${pendingPermissions} pending permission(s)`)
105
+ if (pendingQuestions > 0) reasons.push(`session ${label} has ${pendingQuestions} pending question(s)`)
106
+ for (const b of restartBlockers) reasons.push(`session ${label} restart blocked: ${b}`)
107
+ if (providerActivityAgeMs !== null && providerActivityAgeMs < PROVIDER_QUIET_WINDOW_MS) {
108
+ reasons.push(`session ${label} provider active ${Math.round(providerActivityAgeMs / 1000)}s ago (quiet window ${PROVIDER_QUIET_WINDOW_MS / 60000}m)`)
109
+ }
110
+ }
111
+
112
+ try {
113
+ const n = typeof getHookPendingPermissionCount === 'function' ? getHookPendingPermissionCount() : 0
114
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error('hook permission count is not a count')
115
+ hookPendingPermissions = n
116
+ if (n > 0) reasons.push(`${n} hook-routed permission request(s) pending`)
117
+ } catch (err) {
118
+ reasons.push(`idle state unavailable: ${err?.message || String(err)}`)
119
+ }
120
+
121
+ return { idle: reasons.length === 0, reasons, sessions, hookPendingPermissions }
122
+ }
123
+
124
+ // A provider that lacks the accessor is not "has none": it is "cannot say", and
125
+ // that reads as not idle. BaseSession carries both accessors, so a missing one
126
+ // means a stub or custom provider we cannot vouch for.
127
+ function countPending(session, what, read) {
128
+ let n
129
+ try {
130
+ n = read()
131
+ } catch (err) {
132
+ throw new Error(`${what} unavailable (${err?.message || String(err)})`)
133
+ }
134
+ if (!Number.isSafeInteger(n) || n < 0) throw new Error(`${what} is not a count`)
135
+ return n
136
+ }
137
+
138
+ // `getRestartBlockers()` is the one accessor whose EMPTY result means "safe", so
139
+ // every shape that is not a clean array of strings is "cannot say" (fail
140
+ // closed), exactly like the counts above: a missing method, a throw, or a
141
+ // non-array. Entries are not shape-checked: any entry at all becomes a pushed
142
+ // reason string, which already forces `idle: false`, so such a check could not
143
+ // change a verdict.
144
+ function readBlockers(session) {
145
+ if (typeof session.getRestartBlockers !== 'function') {
146
+ throw new Error('restart blockers unavailable (no getRestartBlockers)')
147
+ }
148
+ let out
149
+ try {
150
+ out = session.getRestartBlockers()
151
+ } catch (err) {
152
+ throw new Error(`restart blockers unavailable (${err?.message || String(err)})`)
153
+ }
154
+ if (!Array.isArray(out)) throw new Error('restart blockers is not an array')
155
+ return out.map(String)
156
+ }
157
+
158
+ // `providerActivityAgeMs` is null for "never active", which is safe, so like the
159
+ // blockers every other shape is "cannot say": a missing getter (undefined), a
160
+ // throw, NaN, a negative or fractional number.
161
+ function readActivityAge(session) {
162
+ let age
163
+ try {
164
+ age = session.providerActivityAgeMs
165
+ } catch (err) {
166
+ throw new Error(`provider activity unavailable (${err?.message || String(err)})`)
167
+ }
168
+ if (age === null) return null
169
+ if (!Number.isSafeInteger(age) || age < 0) throw new Error('provider activity age is not a duration')
170
+ return age
171
+ }