@chroxy/server 0.10.0 → 0.11.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (326) hide show
  1. package/CONFIG.md +602 -19
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +416 -11
  5. package/package.json +20 -23
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1353 -41
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +24 -1
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +101 -0
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +74 -9
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +1153 -20
  37. package/src/byok-mcp-config.js +1712 -8
  38. package/src/byok-mcp-fleet.js +416 -29
  39. package/src/byok-mcp-oauth-store.js +329 -0
  40. package/src/byok-mcp-oauth.js +635 -0
  41. package/src/byok-mcp-trust.js +257 -40
  42. package/src/byok-session.js +1400 -149
  43. package/src/byok-tool-executor.js +2681 -38
  44. package/src/byok-tools.js +9 -2
  45. package/src/channels/chroxy-channel-server.js +2 -3
  46. package/src/checkpoint-manager.js +96 -51
  47. package/src/chroxy-host-metadata.js +122 -0
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-stream-parser.js +109 -3
  53. package/src/claude-tui/diagnostic-tail.js +83 -0
  54. package/src/claude-tui/form-driver.js +44 -7
  55. package/src/claude-tui/model-error.js +41 -0
  56. package/src/claude-tui/pty-driver.js +223 -60
  57. package/src/claude-tui/sanitize-question-payload.js +109 -0
  58. package/src/claude-tui/usage-limit.js +239 -0
  59. package/src/claude-tui-session.js +3611 -286
  60. package/src/claude-tui-tool-response.js +300 -0
  61. package/src/cli/agent-control-cmd.js +65 -0
  62. package/src/cli/config-cmd.js +6 -6
  63. package/src/cli/config-dir-cmd.js +234 -0
  64. package/src/cli/deploy-cmd.js +46 -11
  65. package/src/cli/doctor-cmd.js +7 -3
  66. package/src/cli/init-cmd.js +16 -17
  67. package/src/cli/providers-cmd.js +6 -6
  68. package/src/cli/schedule-cmd.js +804 -0
  69. package/src/cli/server-cmd.js +64 -2
  70. package/src/cli/service-cmd.js +70 -27
  71. package/src/cli/session-cmd.js +227 -74
  72. package/src/cli/shared.js +168 -14
  73. package/src/cli/tokens-cmd.js +212 -0
  74. package/src/cli/tunnel-cmd.js +256 -25
  75. package/src/cli/worktree-gc-cmd.js +2 -2
  76. package/src/cli-session.js +1117 -116
  77. package/src/cli.js +8 -0
  78. package/src/codex-app-server-client.js +36 -3
  79. package/src/codex-app-server-session.js +2108 -101
  80. package/src/codex-bundled-client.js +66 -0
  81. package/src/codex-model-catalog.js +548 -0
  82. package/src/codex-model-rejections.js +87 -0
  83. package/src/codex-native-resume.js +104 -0
  84. package/src/codex-protocol-capabilities.js +188 -0
  85. package/src/codex-session.js +571 -45
  86. package/src/config-dir-migration.js +444 -0
  87. package/src/config-dir.js +108 -0
  88. package/src/config.js +738 -52
  89. package/src/connection-authority.js +48 -0
  90. package/src/connection-info.js +5 -9
  91. package/src/connection-locality.js +60 -0
  92. package/src/container-liveness-monitor.js +189 -0
  93. package/src/continuation-metadata-worker.js +17 -0
  94. package/src/continuations.js +114 -0
  95. package/src/control-room/host-prune.js +5 -0
  96. package/src/control-room/integrations.js +23 -30
  97. package/src/control-room/skills-inventory.js +8 -3
  98. package/src/control-room/survey.js +32 -0
  99. package/src/conversation-scanner.js +40 -18
  100. package/src/conversation-scope.js +59 -39
  101. package/src/conversation-search.js +24 -22
  102. package/src/credential-store.js +279 -29
  103. package/src/daemon-commit.js +92 -0
  104. package/src/daemon-idle-state.js +171 -0
  105. package/src/daemon-update-status.js +314 -0
  106. package/src/dashboard-build.js +70 -0
  107. package/src/declared-status.js +90 -0
  108. package/src/deepseek-credentials.js +2 -3
  109. package/src/dev-preview.js +169 -182
  110. package/src/device-preferences.js +2 -2
  111. package/src/diagnostics.js +3 -0
  112. package/src/diff-parser.js +87 -0
  113. package/src/discord-credentials.js +2 -3
  114. package/src/docker-byok-pool.js +3 -1
  115. package/src/docker-byok-session.js +678 -78
  116. package/src/docker-image-allowlist.js +23 -1
  117. package/src/docker-sdk-session.js +188 -4
  118. package/src/docker-session.js +293 -10
  119. package/src/doctor.js +783 -66
  120. package/src/edited-input.js +264 -0
  121. package/src/environment-manager.js +175 -36
  122. package/src/environments/authority.js +95 -0
  123. package/src/environments/backends/container-claude-spawn.js +94 -0
  124. package/src/environments/backends/docker.js +39 -10
  125. package/src/environments/backends/k8s.js +58 -24
  126. package/src/environments/destroy-with-sessions.js +142 -0
  127. package/src/event-ingest.js +137 -14
  128. package/src/event-normalizer.js +363 -110
  129. package/src/external-session-registry.js +0 -0
  130. package/src/gemini-session.js +100 -7
  131. package/src/github-webhook.js +188 -4
  132. package/src/handler-utils.js +563 -62
  133. package/src/handlers/checkpoint-handlers.js +162 -20
  134. package/src/handlers/control-room-handlers.js +99 -29
  135. package/src/handlers/conversation-handlers.js +563 -25
  136. package/src/handlers/credential-handlers.js +43 -2
  137. package/src/handlers/daemon-update-handlers.js +81 -0
  138. package/src/handlers/evaluator-handlers.js +14 -1
  139. package/src/handlers/feature-handlers.js +186 -69
  140. package/src/handlers/file-handlers.js +101 -13
  141. package/src/handlers/github-webhook-handlers.js +204 -0
  142. package/src/handlers/input-handlers.js +689 -48
  143. package/src/handlers/orchestration-handlers.js +238 -0
  144. package/src/handlers/scheduler-handlers.js +584 -0
  145. package/src/handlers/session-handlers.js +546 -16
  146. package/src/handlers/session-pr-status-handlers.js +283 -0
  147. package/src/handlers/session-pr-threads-handlers.js +247 -0
  148. package/src/handlers/settings-handlers.js +822 -35
  149. package/src/handlers/skills-handlers.js +13 -4
  150. package/src/handlers/summarize-handlers.js +32 -1
  151. package/src/handlers/survey-throttle.js +380 -0
  152. package/src/handlers/token-handlers.js +11 -2
  153. package/src/health-proof.js +40 -0
  154. package/src/history-page.js +104 -0
  155. package/src/http-routes.js +286 -8
  156. package/src/ide/search.js +24 -6
  157. package/src/ide/symbols.js +20 -6
  158. package/src/input-context.js +117 -0
  159. package/src/instruction-policy-compiler.js +229 -0
  160. package/src/instruction-policy.js +250 -0
  161. package/src/jsonl-reader.js +309 -48
  162. package/src/jsonl-subprocess-session.js +122 -9
  163. package/src/keychain.js +160 -13
  164. package/src/logger.js +240 -31
  165. package/src/mailbox-route.js +11 -22
  166. package/src/message-wire.js +386 -0
  167. package/src/model-discovery.js +43 -3
  168. package/src/models.js +1276 -174
  169. package/src/notification-prefs.js +100 -10
  170. package/src/notifications/discord-billing-sink.js +22 -5
  171. package/src/notifications/discord-ci-sink.js +243 -0
  172. package/src/notifications/discord-webhook-client.js +71 -0
  173. package/src/notifications/discord-webhook-sink.js +82 -12
  174. package/src/notifications/expo-push-sink.js +85 -6
  175. package/src/notifications/ready-body.js +16 -5
  176. package/src/ollama-session.js +34 -2
  177. package/src/orchestration/build-manager.js +63 -0
  178. package/src/orchestration/decision-contract.js +245 -0
  179. package/src/orchestration/git-ops.js +381 -0
  180. package/src/orchestration/orchestration-manager.js +1342 -0
  181. package/src/orchestration/permission-gate.js +121 -0
  182. package/src/orchestration/role-prompts.js +136 -0
  183. package/src/orchestration/run-budget.js +81 -0
  184. package/src/orchestration/run-ledger.js +487 -0
  185. package/src/orchestration/run-model.js +206 -0
  186. package/src/orchestration/run-record.js +336 -0
  187. package/src/orchestration/run-report.js +194 -0
  188. package/src/orchestration/to-wire.js +201 -0
  189. package/src/orchestration/turn-driver.js +422 -0
  190. package/src/orphan-reaper.js +413 -0
  191. package/src/outgoing-policy.js +183 -0
  192. package/src/pairing.js +236 -12
  193. package/src/path-hash-trust-ledger.js +642 -25
  194. package/src/permission-audit.js +79 -3
  195. package/src/permission-deadlines.js +82 -0
  196. package/src/permission-floor.js +1770 -0
  197. package/src/permission-hook.js +180 -69
  198. package/src/permission-manager.js +1175 -94
  199. package/src/permission-mode-support.js +35 -0
  200. package/src/permission-resolver.js +174 -12
  201. package/src/permission-rule-store.js +411 -0
  202. package/src/permission-scope.js +43 -0
  203. package/src/platform.js +483 -23
  204. package/src/preview-ingress.js +54 -0
  205. package/src/preview-target.js +213 -0
  206. package/src/prompt-evaluator.js +34 -4
  207. package/src/provider-customization.js +180 -0
  208. package/src/providers.js +228 -6
  209. package/src/push.js +30 -4
  210. package/src/question-route-map.js +130 -0
  211. package/src/redaction.js +360 -8
  212. package/src/roster-broadcast.js +186 -0
  213. package/src/schedule-parser.js +311 -0
  214. package/src/scheduled-task-store.js +945 -0
  215. package/src/scheduler.js +1099 -0
  216. package/src/sdk-session.js +2374 -168
  217. package/src/server-cli/preview-shutdown.js +22 -0
  218. package/src/server-cli/push-notification-handler.js +11 -2
  219. package/src/server-cli/server-orchestrator.js +50 -4
  220. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  221. package/src/server-cli-child.js +33 -18
  222. package/src/server-cli.js +760 -62
  223. package/src/server-identity.js +42 -14
  224. package/src/service.js +682 -53
  225. package/src/session-archive-limits.js +15 -0
  226. package/src/session-archive.js +1029 -0
  227. package/src/session-busy-state.js +72 -0
  228. package/src/session-ci-watcher.js +926 -0
  229. package/src/session-context.js +7 -2
  230. package/src/session-manager.js +3879 -308
  231. package/src/session-message-history.js +749 -37
  232. package/src/session-pr-status.js +654 -0
  233. package/src/session-pr-threads.js +271 -0
  234. package/src/session-preset-trust.js +3 -3
  235. package/src/session-preset.js +10 -5
  236. package/src/session-state-persistence.js +94 -17
  237. package/src/session-timeout-manager.js +20 -0
  238. package/src/session-title.js +168 -0
  239. package/src/session-token-store.js +70 -36
  240. package/src/session-wake.js +240 -0
  241. package/src/shell-approval-info.js +2 -2
  242. package/src/shell-approval-store.js +3 -1
  243. package/src/skills-loader.js +7 -4
  244. package/src/skills-manager.js +2 -2
  245. package/src/skills-trust.js +95 -13
  246. package/src/skills-usage.js +22 -5
  247. package/src/snapshots-store.js +2 -3
  248. package/src/statusline.js +596 -0
  249. package/src/subagent-counter.js +9 -1
  250. package/src/summarize-session.js +51 -4
  251. package/src/supervisor.js +99 -38
  252. package/src/sweep-stale-provider-dirs.js +95 -0
  253. package/src/thinking-level-wire.js +39 -0
  254. package/src/thinking-stream.js +179 -0
  255. package/src/token-manager.js +39 -9
  256. package/src/tool-result.js +61 -0
  257. package/src/transcript-sources.js +109 -0
  258. package/src/transcript-tasks.js +413 -31
  259. package/src/trusted-file-read.js +302 -0
  260. package/src/tunnel/base.js +0 -8
  261. package/src/tunnel/cloudflare.js +145 -35
  262. package/src/tunnel/index.js +13 -1
  263. package/src/tunnel/preview.js +64 -0
  264. package/src/tunnel-check.js +1 -1
  265. package/src/turn-outcome.js +137 -0
  266. package/src/turn-tracker.js +0 -0
  267. package/src/usage-normalize.js +122 -0
  268. package/src/user-shell-session.js +157 -37
  269. package/src/utils/agent-sdk-version.js +107 -0
  270. package/src/utils/argv-safety.js +741 -0
  271. package/src/utils/auth-cause.js +60 -0
  272. package/src/utils/binary-package-manifest.js +597 -0
  273. package/src/utils/binary-version.js +224 -0
  274. package/src/utils/bounded-regex-worker.js +25 -0
  275. package/src/utils/bounded-regex.js +153 -0
  276. package/src/utils/claude-binary.js +43 -0
  277. package/src/utils/claude-config-dir.js +245 -0
  278. package/src/utils/claude-login-command.js +16 -0
  279. package/src/utils/claude-native-route.js +81 -0
  280. package/src/utils/componentwise-resolver.js +301 -0
  281. package/src/utils/composite-key.js +45 -0
  282. package/src/utils/deploy-control-files.js +87 -0
  283. package/src/utils/exec-failure-reason.js +21 -0
  284. package/src/utils/git-repo.js +42 -0
  285. package/src/utils/is-entry-point.js +137 -0
  286. package/src/utils/iso-datetime.js +51 -0
  287. package/src/utils/node-pty-probe.js +95 -0
  288. package/src/utils/node-pty-support.js +118 -0
  289. package/src/utils/opened-file-path.js +167 -0
  290. package/src/utils/path-containment.js +165 -0
  291. package/src/utils/permission-mode-sidecar.js +51 -0
  292. package/src/utils/preflight.js +485 -29
  293. package/src/utils/read-limiter.js +217 -0
  294. package/src/utils/regular-file.js +375 -0
  295. package/src/utils/safe-regex.js +113 -0
  296. package/src/utils/small-file.js +129 -0
  297. package/src/utils/spawn-env.js +196 -5
  298. package/src/utils/stale-session-dirs.js +182 -0
  299. package/src/utils/stat-identity.js +43 -0
  300. package/src/utils/verify-binary.js +276 -0
  301. package/src/utils/verify-provenance.js +634 -0
  302. package/src/utils/wire-counters.js +48 -0
  303. package/src/web-task-manager.js +256 -16
  304. package/src/worktree-gc.js +11 -3
  305. package/src/ws-auth.js +69 -21
  306. package/src/ws-broadcaster.js +14 -2
  307. package/src/ws-client-manager.js +16 -1
  308. package/src/ws-client-sender.js +7 -0
  309. package/src/ws-file-ops/browser.js +370 -66
  310. package/src/ws-file-ops/common.js +384 -11
  311. package/src/ws-file-ops/git.js +615 -44
  312. package/src/ws-file-ops/index.js +7 -0
  313. package/src/ws-file-ops/memory.js +460 -0
  314. package/src/ws-file-ops/open-nofollow.js +354 -0
  315. package/src/ws-file-ops/reader.js +676 -94
  316. package/src/ws-forwarding.js +373 -55
  317. package/src/ws-handler-context.js +89 -2
  318. package/src/ws-history.js +1018 -177
  319. package/src/ws-message-handlers.js +23 -1
  320. package/src/ws-outbound-schemas.js +207 -0
  321. package/src/ws-permissions.js +589 -38
  322. package/src/ws-schemas.js +6 -0
  323. package/src/ws-server.js +936 -105
  324. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  325. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  326. package/src/dashboard-next/dist/index.html +0 -13
package/src/keychain.js CHANGED
@@ -1,18 +1,44 @@
1
1
  /**
2
2
  * OS keychain integration for secure token storage.
3
3
  *
4
- * Uses native CLI tools (no npm dependencies):
4
+ * Uses native OS crypto (no npm dependencies):
5
5
  * - macOS: `security` command (Keychain Services)
6
6
  * - Linux: `secret-tool` (libsecret)
7
- * - Windows/fallback: returns null (caller falls back to chmod 600 file)
7
+ * - Windows: DPAPI via PowerShell, ciphertext under %LOCALAPPDATA%\Chroxy (#6644)
8
+ * - Fallback (no usable backend): returns null → caller uses the 0600 file
8
9
  */
9
10
  import { execFileSync } from 'child_process'
10
- import { existsSync } from 'node:fs'
11
- import { isMac, isLinux } from './platform.js'
11
+ import { existsSync, readFileSync, mkdirSync, unlinkSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+ import { homedir } from 'node:os'
14
+ import { isMac, isLinux, isWindows, writeFileRestricted } from './platform.js'
12
15
 
13
16
  const DEFAULT_SERVICE = 'chroxy'
14
17
  const ACCOUNT = 'api-token'
15
18
 
19
+ // -- Windows DPAPI backend (#6644) --
20
+ // Windows has no launchd/systemd-style secret CLI, so the keychain "token"
21
+ // (e.g. the credential-cipher data key, the API token) is protected with the
22
+ // per-user DPAPI master key and stored under %LOCALAPPDATA%\Chroxy\. Protect/
23
+ // Unprotect run in PowerShell with the secret passed over STDIN (never argv —
24
+ // process args are world-readable via WMI on Windows), mirroring the Linux
25
+ // secret-tool stdin pattern. The ciphertext file is written owner-only via
26
+ // writeFileRestricted (icacls DACL, #6644).
27
+ //
28
+ // Every value stored here is ASCII and newline-free (a base64 data key, an API
29
+ // token), so the stdin round-trip is encoding-agnostic and the read-side
30
+ // trailing-newline trim is a defensive no-op. If a non-ASCII / trailing-newline
31
+ // secret is ever stored, pin the console encoding (Input/OutputEncoding = UTF8)
32
+ // in the PS scripts first.
33
+ // Read LAZILY (not a module const) so tests can redirect LOCALAPPDATA to a temp
34
+ // dir and stay hermetic, mirroring the keychain off-switch's per-call read.
35
+ function winCredDir() {
36
+ return join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'Chroxy')
37
+ }
38
+ const WIN_POWERSHELL = `${process.env.SystemRoot || process.env.windir || 'C:\\Windows'}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
39
+ const PS_PROTECT = "$ErrorActionPreference='Stop';Add-Type -AssemblyName System.Security;$p=[Console]::In.ReadToEnd();$b=[Text.Encoding]::UTF8.GetBytes($p);$e=[Security.Cryptography.ProtectedData]::Protect($b,$null,'CurrentUser');[Console]::Out.Write([Convert]::ToBase64String($e))"
40
+ const PS_UNPROTECT = "$ErrorActionPreference='Stop';Add-Type -AssemblyName System.Security;$b=[Convert]::FromBase64String(([Console]::In.ReadToEnd()).Trim());$d=[Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser');[Console]::Out.Write([Text.Encoding]::UTF8.GetString($d))"
41
+
16
42
  /**
17
43
  * Global off-switch for OS keychain access.
18
44
  *
@@ -97,6 +123,10 @@ function _probeKeychainUsable() {
97
123
  return false
98
124
  }
99
125
  }
126
+ if (isWindows) {
127
+ // DPAPI is usable if a Protect→Unprotect round-trip works for this user.
128
+ return _probeDpapiUsable()
129
+ }
100
130
  return false
101
131
  }
102
132
 
@@ -148,8 +178,9 @@ export function isKeychainBroken() {
148
178
  /**
149
179
  * @typedef {object} KeychainHealth
150
180
  * @property {'usable'|'broken'|'disabled'|'unsupported'} status — keychain state.
151
- * @property {'keychain'|'file'} backend — where credentials are ACTUALLY stored
152
- * right now (the file/env fallback whenever the keychain isn't usable).
181
+ * @property {'keychain'|'dpapi'|'file'} backend — where credentials are ACTUALLY
182
+ * stored right now: the OS keychain (mac/linux), Windows DPAPI (#6644), or the
183
+ * 0600 file/env fallback whenever no secret backend is usable.
153
184
  * @property {string} detail — one-line human explanation of the status.
154
185
  * @property {string} [repairHint] — present only for `broken`: how to fix it.
155
186
  */
@@ -173,6 +204,21 @@ export function keychainHealth() {
173
204
  detail: 'OS keychain disabled via CHROXY_DISABLE_KEYCHAIN — using the 0600 file/env fallback',
174
205
  }
175
206
  }
207
+ if (isWindows) {
208
+ // Windows uses DPAPI (per-user), not a keychain CLI (#6644).
209
+ if (keychainUsable()) {
210
+ return {
211
+ status: 'usable',
212
+ backend: 'dpapi',
213
+ detail: 'credentials are protected with Windows DPAPI (per-user, CurrentUser scope)',
214
+ }
215
+ }
216
+ return {
217
+ status: 'unsupported',
218
+ backend: 'file',
219
+ detail: 'Windows DPAPI/PowerShell unavailable — using the 0600 file/env fallback',
220
+ }
221
+ }
176
222
  if (!isMac && !isLinux) {
177
223
  return {
178
224
  status: 'unsupported',
@@ -218,6 +264,9 @@ export function getToken(service = DEFAULT_SERVICE, account = ACCOUNT) {
218
264
  if (isLinux) {
219
265
  return _linuxGetToken(service, account)
220
266
  }
267
+ if (isWindows) {
268
+ return _winGetToken(service, account)
269
+ }
221
270
  return null
222
271
  }
223
272
 
@@ -257,12 +306,21 @@ export function getToken(service = DEFAULT_SERVICE, account = ACCOUNT) {
257
306
  export function getTokenStatus(service = DEFAULT_SERVICE) {
258
307
  // The explicit off-switch (tests) → 'absent': the file fallback owns identity.
259
308
  if (keychainDisabled()) return { status: 'absent', value: null, error: null }
260
- // Platforms with NO keychain backend (Windows/other) → 'absent': there is no
261
- // keychain that could hold an identity, so the file legitimately owns it (the
262
- // documented "other platforms" contract). This must come BEFORE the broken
263
- // check — `keychainUsable()` is always false on those platforms, and reporting
264
- // 'error' there would wrongly block identity loading.
265
- if (!isMac && !isLinux) return { status: 'absent', value: null, error: null }
309
+ // Platforms with NO secret backend at all → 'absent': there is nothing that
310
+ // could hold an identity, so the file legitimately owns it (the documented
311
+ // "other platforms" contract). Windows HAS a backend (DPAPI, #6644) so it is
312
+ // not lumped in here.
313
+ if (!isMac && !isLinux && !isWindows) return { status: 'absent', value: null, error: null }
314
+ // Windows with DPAPI/PowerShell unavailable: if a ciphertext file EXISTS but
315
+ // we can't decrypt it, that is stored-but-unreadable → 'error' so an identity
316
+ // caller fails safe (does not re-mint and false-MITM already-pinned clients,
317
+ // #5615). With NO stored file the file/env fallback legitimately owns identity
318
+ // → 'absent' (the documented no-backend contract).
319
+ if (isWindows && !keychainUsable()) {
320
+ return existsSync(_winCredFile(service, ACCOUNT))
321
+ ? { status: 'error', value: null, error: 'DPAPI unavailable — stored credential cannot be read' }
322
+ : { status: 'absent', value: null, error: null }
323
+ }
266
324
  // #5615 fail-safe: on mac/linux a BROKEN/missing keychain reads as 'error',
267
325
  // NOT 'absent' — an identity caller that re-mints on 'absent' would false-MITM
268
326
  // every already-pinned client. 'error' fails safe (don't rotate) AND avoids
@@ -273,6 +331,9 @@ export function getTokenStatus(service = DEFAULT_SERVICE) {
273
331
  if (isMac) {
274
332
  return _macGetTokenStatus(service)
275
333
  }
334
+ if (isWindows) {
335
+ return _winGetTokenStatus(service)
336
+ }
276
337
  return _linuxGetTokenStatus(service)
277
338
  }
278
339
 
@@ -289,6 +350,8 @@ export function setToken(token, service = DEFAULT_SERVICE) {
289
350
  _macSetToken(service, token)
290
351
  } else if (isLinux) {
291
352
  _linuxSetToken(service, token)
353
+ } else if (isWindows) {
354
+ _winSetToken(service, token)
292
355
  }
293
356
  }
294
357
 
@@ -302,6 +365,8 @@ export function deleteToken(service = DEFAULT_SERVICE) {
302
365
  _macDeleteToken(service)
303
366
  } else if (isLinux) {
304
367
  _linuxDeleteToken(service)
368
+ } else if (isWindows) {
369
+ _winDeleteToken(service)
305
370
  }
306
371
  }
307
372
 
@@ -334,7 +399,7 @@ export function migrateToken(config, service = DEFAULT_SERVICE) {
334
399
  }
335
400
 
336
401
  // Return config without apiToken
337
- const { apiToken, ...rest } = config
402
+ const { apiToken: _apiToken, ...rest } = config
338
403
  return { migrated: true, config: rest }
339
404
  }
340
405
 
@@ -456,3 +521,85 @@ function _linuxDeleteToken(service) {
456
521
  // Not found — that's fine
457
522
  }
458
523
  }
524
+
525
+ // -- Windows implementation (DPAPI via PowerShell) --
526
+
527
+ // Ciphertext file for a (service, account) pair. Non-filename characters are
528
+ // squashed so a service like `chroxy-cred-key` maps to a safe path; the pair is
529
+ // preserved so different accounts under one service never collide.
530
+ function _winCredFile(service, account) {
531
+ const safe = (s) => String(s).replace(/[^A-Za-z0-9._-]/g, '_')
532
+ return join(winCredDir(), `${safe(service)}__${safe(account)}.dpapi`)
533
+ }
534
+
535
+ // Run a DPAPI Protect/Unprotect. The secret (plaintext to protect, or base64
536
+ // ciphertext to unprotect) is passed on STDIN; the result comes back on STDOUT.
537
+ // Nothing sensitive is ever placed in argv.
538
+ function _dpapi(script, input) {
539
+ return String(execFileSync(WIN_POWERSHELL, ['-NoProfile', '-NonInteractive', '-Command', script], {
540
+ input: Buffer.from(input, 'utf-8'),
541
+ encoding: 'utf-8',
542
+ windowsHide: true,
543
+ timeout: 5000,
544
+ stdio: ['pipe', 'pipe', 'pipe'],
545
+ }))
546
+ }
547
+
548
+ function _winSetToken(service, token) {
549
+ const cipher = _dpapi(PS_PROTECT, token).trim()
550
+ if (!cipher) throw new Error('DPAPI Protect returned empty ciphertext')
551
+ const dir = winCredDir()
552
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
553
+ // Owner-only DACL is stamped by writeFileRestricted (icacls, #6644).
554
+ writeFileRestricted(_winCredFile(service, ACCOUNT), cipher)
555
+ }
556
+
557
+ function _winGetToken(service, account = ACCOUNT) {
558
+ const file = _winCredFile(service, account)
559
+ if (!existsSync(file)) return null
560
+ try {
561
+ const plain = _dpapi(PS_UNPROTECT, readFileSync(file, 'utf-8')).replace(/\r?\n$/, '')
562
+ return plain || null
563
+ } catch {
564
+ // Corrupt ciphertext, wrong user (DPAPI is per-user), or PowerShell/DPAPI
565
+ // unavailable → treat as unreadable (caller falls back / re-prompts).
566
+ return null
567
+ }
568
+ }
569
+
570
+ function _winGetTokenStatus(service) {
571
+ const file = _winCredFile(service, ACCOUNT)
572
+ if (!existsSync(file)) return { status: 'absent', value: null, error: null }
573
+ try {
574
+ const plain = _dpapi(PS_UNPROTECT, readFileSync(file, 'utf-8')).replace(/\r?\n$/, '')
575
+ return plain
576
+ ? { status: 'found', value: plain, error: null }
577
+ : { status: 'absent', value: null, error: null }
578
+ } catch (err) {
579
+ // A stored-but-unreadable entry is an ERROR (not absence): a caller that
580
+ // re-mints on 'absent' must fail safe here (mirrors the mac/linux contract).
581
+ return { status: 'error', value: null, error: (err && err.message) || 'DPAPI unprotect failed' }
582
+ }
583
+ }
584
+
585
+ function _winDeleteToken(service) {
586
+ const file = _winCredFile(service, ACCOUNT)
587
+ try {
588
+ if (existsSync(file)) unlinkSync(file)
589
+ } catch {
590
+ // Best-effort — a missing/locked file is fine.
591
+ }
592
+ }
593
+
594
+ // DPAPI availability probe: a round-trip of a marker string. Proves PowerShell +
595
+ // ProtectedData are usable for THIS user before we advertise the backend.
596
+ function _probeDpapiUsable() {
597
+ try {
598
+ const marker = 'chroxy-dpapi-probe'
599
+ const cipher = _dpapi(PS_PROTECT, marker).trim()
600
+ if (!cipher) return false
601
+ return _dpapi(PS_UNPROTECT, cipher).replace(/\r?\n$/, '') === marker
602
+ } catch {
603
+ return false
604
+ }
605
+ }
package/src/logger.js CHANGED
@@ -15,16 +15,37 @@
15
15
  * // => 2026-02-22T12:34:56.789Z [INFO] [supervisor] Server ready
16
16
  */
17
17
 
18
- import { appendFileSync, statSync, renameSync, mkdirSync, chmodSync } from 'fs'
18
+ import {
19
+ appendFileSync, statSync, renameSync, mkdirSync, chmodSync,
20
+ openSync, readSync, closeSync, writeFileSync, truncateSync,
21
+ } from 'fs'
19
22
  import { join } from 'path'
20
- import { homedir } from 'os'
21
- import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue } from './redaction.js'
23
+ import { SENSITIVE_PATTERNS, API_KEY_PATTERNS, redactValue, redactWhole, clipRedacted } from './redaction.js'
24
+ import { configPath } from './config-dir.js'
22
25
 
23
- const DEFAULT_LOG_DIR = join(homedir(), '.chroxy', 'logs')
26
+ function defaultLogDir() {
27
+ return configPath('logs')
28
+ }
24
29
  const MAX_LOG_SIZE = 5 * 1024 * 1024 // 5MB
25
30
  const MAX_LOG_FILES = 3
26
31
  const ROTATION_CHECK_INTERVAL = 100 // check every N writes
27
32
 
33
+ // #7162: audit retention floor (discord-return-path.md §9.1). [AUDIT] lines are
34
+ // dual-written to a dedicated chroxy-audit.log with its own rotation budget, so
35
+ // the audit trail's lifetime is bounded by AUDIT volume alone — a noisy debug
36
+ // period churning chroxy.log through its 5MB×3 cascade can never displace an
37
+ // audit line. Budget: 10MB live + 4 archives ≈ 50MB ceiling; §9.1's rate
38
+ // ceilings and reject-collapse bound audit volume, so this is years of trail.
39
+ const AUDIT_LOG_NAME = 'chroxy-audit.log'
40
+ const MAX_AUDIT_LOG_SIZE = 10 * 1024 * 1024 // 10MB
41
+ const MAX_AUDIT_LOG_FILES = 4
42
+
43
+ // #7162: bounds for the service-manager stdout/stderr capture files
44
+ // (launchd StandardOutPath / systemd StandardOutput=file: / cmd `>>`), which
45
+ // no service manager rotates. Capped at daemon boot by capStdioCaptureLogs().
46
+ const STDIO_CAPTURE_MAX_SIZE = 5 * 1024 * 1024 // 5MB
47
+ const STDIO_CAPTURE_TAIL_KEEP = 1 * 1024 * 1024 // preserved to *.old.log
48
+
28
49
  const LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }
29
50
 
30
51
  // #6029: the value-SHAPE patterns (SENSITIVE_PATTERNS / API_KEY_PATTERNS) and
@@ -44,10 +65,28 @@ export function redactSensitive(msg) {
44
65
  return redactValue(msg)
45
66
  }
46
67
 
68
+ // The most of one log line that is kept, in characters. The whole line is redacted
69
+ // first (up to the redactor's admission ceiling) and the redacted text is then cut
70
+ // by `clipRedacted`: a slice that also drops the end of what it kept, so a fragment of
71
+ // a pattern at the cut is not shown.
72
+ // `redactSensitive` itself keeps all of its result: its callers redact first and then
73
+ // keep a tail or a slice of their own.
74
+ const LOG_LINE_MAX = 64 * 1024
75
+ const LOG_TRUNCATION_MARKER = '... [truncated]'
76
+
77
+ function redactLogMessage(msg) {
78
+ if (typeof msg !== 'string') return redactSensitive(msg)
79
+ const { text, clipped } = redactWhole(msg)
80
+ return clipped || text.length > LOG_LINE_MAX
81
+ ? clipRedacted(text, LOG_LINE_MAX, LOG_TRUNCATION_MARKER)
82
+ : text
83
+ }
84
+
47
85
  // #5358: escape/control sequences a TUI can interleave INTO a token while
48
86
  // styling it (e.g. `sk-ant-oat01-AAAA\x1b[1mBBBB`), splitting the run so the
49
87
  // contiguous patterns above miss it. Mirrors the claude-tui ANSI_STRIP set,
50
- // kept local so logger.js stays dependency-free.
88
+ // kept local so logger.js stays dependency-free. Sticky: it is asked for a match AT
89
+ // the current offset, and a global search would scan the rest of the text each time.
51
90
  const TOKEN_SPLITTING_ESCAPE = new RegExp(
52
91
  [
53
92
  '\\x1b\\[[0-9;?]*[\\x40-\\x7E]', // CSI
@@ -56,7 +95,7 @@ const TOKEN_SPLITTING_ESCAPE = new RegExp(
56
95
  '\\x1b[=>cN]', // single-char terminal-mode codes
57
96
  '[\\x00-\\x08\\x0b-\\x1f\\x7f]', // stray C0 controls (except \t and \n)
58
97
  ].join('|'),
59
- 'g',
98
+ 'y',
60
99
  )
61
100
 
62
101
  /**
@@ -78,9 +117,12 @@ const TOKEN_SPLITTING_ESCAPE = new RegExp(
78
117
  * marker-prefixed patterns (sk-/AIza/Bearer/JWT/key=value) are the safe set.
79
118
  *
80
119
  * @param {string} s latin1/utf8 string (one char per byte for the dump path)
120
+ * @param {string} [fill] the one character each redacted character becomes
121
+ * (default 'X'). A caller that goes on to reshape the text can pass a
122
+ * character it will not otherwise meet and turn the runs into a marker.
81
123
  * @returns {string}
82
124
  */
83
- export function redactSensitivePreservingEscapes(s) {
125
+ export function redactSensitivePreservingEscapes(s, fill = 'X') {
84
126
  // Walk s, skipping escape runs, building a stripped copy + index map back to s.
85
127
  let stripped = ''
86
128
  const map = []
@@ -88,7 +130,7 @@ export function redactSensitivePreservingEscapes(s) {
88
130
  while (i < s.length) {
89
131
  TOKEN_SPLITTING_ESCAPE.lastIndex = i
90
132
  const m = TOKEN_SPLITTING_ESCAPE.exec(s)
91
- if (m && m.index === i) { i += m[0].length || 1; continue }
133
+ if (m) { i += m[0].length || 1; continue }
92
134
  stripped += s[i]
93
135
  map.push(i)
94
136
  i++
@@ -99,7 +141,7 @@ export function redactSensitivePreservingEscapes(s) {
99
141
  pattern.lastIndex = 0
100
142
  let match
101
143
  while ((match = pattern.exec(stripped)) !== null) {
102
- for (let k = match.index; k < match.index + match[0].length; k++) chars[map[k]] = 'X'
144
+ for (let k = match.index; k < match.index + match[0].length; k++) chars[map[k]] = fill
103
145
  changed = true
104
146
  if (match[0].length === 0) pattern.lastIndex++ // guard against a zero-width match
105
147
  }
@@ -110,9 +152,18 @@ export function redactSensitivePreservingEscapes(s) {
110
152
  let _logLevel = LOG_LEVELS[process.env.LOG_LEVEL] ?? LOG_LEVELS.info
111
153
  let _jsonMode = false
112
154
  let _logToFile = false
113
- let _logDir = DEFAULT_LOG_DIR
155
+ // #7052 — deliberately NOT `defaultLogDir()` here. A module-scope initializer
156
+ // runs at import, so it would freeze the log directory against whatever
157
+ // CHROXY_CONFIG_DIR happened to be when the module graph was first walked —
158
+ // the exact defect config-dir.js exists to prevent, one level of indirection
159
+ // away from where the lint could see it. Resolved lazily in initFileLogging()
160
+ // instead, so a test that relocates the config dir in a `beforeEach` is
161
+ // honored (#4633).
162
+ let _logDir = null
114
163
  let _logPath = null
164
+ let _auditLogPath = null
115
165
  let _writeCount = 0
166
+ let _quietConsole = false
116
167
 
117
168
  /** Set of callbacks for broadcasting log entries (supports multiple WsServer instances) */
118
169
  const _logListeners = new Set()
@@ -162,7 +213,9 @@ export function initFileLogging({ level = 'info', logDir } = {}) {
162
213
  _logLevel = LOG_LEVELS[level] ?? LOG_LEVELS.info
163
214
  _logToFile = true
164
215
  _writeCount = 0
165
- if (logDir) _logDir = logDir
216
+ // Resolve per call, not at import (#7052): an explicit logDir wins, otherwise
217
+ // ask config-dir.js now so CHROXY_CONFIG_DIR is read at the moment it matters.
218
+ _logDir = logDir || defaultLogDir()
166
219
  // #3734 review (Copilot): create the log directory at mode 0700, and
167
220
  // chmod existing dirs the same way. Logs may contain sensitive data
168
221
  // (tool inputs, tokens that slip past the redactor), so they must not
@@ -179,6 +232,24 @@ export function initFileLogging({ level = 'info', logDir } = {}) {
179
232
  // we keep going. The mkdir mode bit covers fresh-create.
180
233
  }
181
234
  _logPath = join(_logDir, 'chroxy.log')
235
+ _auditLogPath = join(_logDir, AUDIT_LOG_NAME)
236
+ }
237
+
238
+ /**
239
+ * #7162: quiet the console mirror in daemon mode. Under a service manager the
240
+ * console streams are captured to chroxy-stdout/stderr.log, which nothing
241
+ * rotates — mirroring every file-logged line there is how the capture reached
242
+ * 32MB in a month. When quiet, info/debug/audit lines skip the console (the
243
+ * rotated file log is authoritative); warn/error still print, so crash-adjacent
244
+ * output keeps landing in chroxy-stderr.log.
245
+ *
246
+ * Fail-safe: quieting only ever suppresses a line that was ALSO written to the
247
+ * file log — if file logging is off or the path is unset, the console mirror
248
+ * stays on regardless of this flag (see write()).
249
+ * @param {boolean} enabled
250
+ */
251
+ export function setConsoleQuiet(enabled) {
252
+ _quietConsole = !!enabled
182
253
  }
183
254
 
184
255
  /**
@@ -191,6 +262,89 @@ export function getLogPath() {
191
262
  return _logToFile ? _logPath : null
192
263
  }
193
264
 
265
+ /**
266
+ * Return the on-disk audit log path (#7162), or `null` if file logging is
267
+ * disabled. #7169's fail-closed audit writer gates on this being non-null —
268
+ * it is the "file-backed logging" precondition §9.1 requires `enable` to check.
269
+ * @returns {string|null}
270
+ */
271
+ export function getAuditLogPath() {
272
+ return _logToFile ? _auditLogPath : null
273
+ }
274
+
275
+ /**
276
+ * #7162: bound the service-manager capture files (launchd StandardOutPath /
277
+ * systemd StandardOutput=file: / the Windows wrapper's `>>`), which no service
278
+ * manager rotates. Called once at daemon boot.
279
+ *
280
+ * Mechanics are copy-tail-then-truncate, NEVER rename: the service manager
281
+ * (and this process, as fd 1/2) holds an open descriptor on the inode, so a
282
+ * rename would silently divert the live stream into the archive until the next
283
+ * restart. launchd opens the capture with O_APPEND, so writes after the
284
+ * truncate land at the new end. On systemd (`file:` — non-append fd) the
285
+ * truncate is safe ONLY while the fd offset is ~0, which is why the single
286
+ * call site is the `start` command (server-cmd.js), in the process the
287
+ * service manager spawned, BEFORE any supervisor fork — a supervised child
288
+ * restart re-entering this would truncate under the supervisor's live
289
+ * offset. Windows is excluded outright: the Task Scheduler wrapper redirects
290
+ * with cmd `>>`, whose handle does not have POSIX append semantics, and the
291
+ * next write would re-extend the file with a NUL-padded gap — the generated
292
+ * .cmd wrapper rotates the captures itself before the redirect handle exists
293
+ * (see generateWindowsServiceWrapper).
294
+ *
295
+ * @param {object} [options]
296
+ * @param {string} [options.logDir] - defaults to defaultLogDir(), i.e.
297
+ * `<config dir>/logs`, which follows CHROXY_CONFIG_DIR since #7052. The
298
+ * capture location is baked into the plist/unit by `service install`, which
299
+ * now propagates CHROXY_CONFIG_DIR so both halves agree. Still deliberately
300
+ * does NOT follow a custom CHROXY_LOG_DIR, which only moves the logger's own
301
+ * files
302
+ * @param {number} [options.maxSize] - cap before truncation kicks in
303
+ * @param {number} [options.tailKeep] - bytes preserved to `<name>.old.log`
304
+ * @returns {Array<{file: string, archive: string, preservedBytes: number}>}
305
+ * one entry per file that was capped (empty when nothing exceeded the cap)
306
+ */
307
+ export function capStdioCaptureLogs({
308
+ logDir,
309
+ maxSize = STDIO_CAPTURE_MAX_SIZE,
310
+ tailKeep = STDIO_CAPTURE_TAIL_KEEP,
311
+ } = {}) {
312
+ if (process.platform === 'win32') return []
313
+ const dir = logDir || defaultLogDir()
314
+ const capped = []
315
+ for (const name of ['chroxy-stdout.log', 'chroxy-stderr.log']) {
316
+ const filePath = join(dir, name)
317
+ try {
318
+ const stats = statSync(filePath)
319
+ if (stats.size <= maxSize) continue
320
+ const archive = filePath.replace(/\.log$/, '.old.log')
321
+ const keep = Math.min(tailKeep, stats.size)
322
+ const fd = openSync(filePath, 'r')
323
+ let tail
324
+ try {
325
+ const buf = Buffer.alloc(keep)
326
+ const read = readSync(fd, buf, 0, keep, stats.size - keep)
327
+ tail = buf.subarray(0, read)
328
+ } finally {
329
+ closeSync(fd)
330
+ }
331
+ // Start the archive on a whole line when the tail begins mid-line
332
+ // (when keep < size, byte 0 is almost certainly a truncated line).
333
+ if (keep < stats.size) {
334
+ const nl = tail.indexOf(0x0a)
335
+ if (nl !== -1 && nl < tail.length - 1) tail = tail.subarray(nl + 1)
336
+ }
337
+ writeFileSync(archive, tail)
338
+ truncateSync(filePath, 0)
339
+ capped.push({ file: filePath, archive, preservedBytes: tail.length })
340
+ } catch {
341
+ // Capture file absent, or unreadable — nothing to bound. Never let a
342
+ // capping failure interfere with boot (#746 spirit).
343
+ }
344
+ }
345
+ return capped
346
+ }
347
+
194
348
  /**
195
349
  * Close file logging. Used in tests for cleanup.
196
350
  */
@@ -198,26 +352,35 @@ export function closeFileLogging() {
198
352
  _logToFile = false
199
353
  _jsonMode = false
200
354
  _logLevel = LOG_LEVELS.info
201
- _logDir = DEFAULT_LOG_DIR
355
+ _logDir = defaultLogDir()
202
356
  _logPath = null
357
+ _auditLogPath = null
203
358
  _writeCount = 0
359
+ _quietConsole = false
204
360
  _logListeners.clear()
205
361
  }
206
362
 
207
- function _maybeRotate() {
208
- if (!_logPath) return
363
+ /**
364
+ * Size-gated rename-cascade rotation, shared by the main log and the audit log.
365
+ * Rotate: base.N.log (overwritten) <- ... <- base.1.log <- base.log
366
+ */
367
+ function _maybeRotateAt(logPath, maxSize, maxFiles) {
368
+ if (!logPath) return
209
369
  try {
210
- const stats = statSync(_logPath)
211
- if (stats.size < MAX_LOG_SIZE) return
370
+ const stats = statSync(logPath)
371
+ if (stats.size < maxSize) return
212
372
  } catch (err) {
213
373
  if (err?.code !== 'ENOENT') console.error('[logger] stat failed:', err?.message)
214
374
  return
215
375
  }
216
376
 
217
- // Rotate: chroxy.3.log (overwritten) <- chroxy.2.log <- chroxy.1.log <- chroxy.log
218
- for (let i = MAX_LOG_FILES; i >= 1; i--) {
219
- const from = i === 1 ? _logPath : _logPath.replace('.log', `.${i - 1}.log`)
220
- const to = _logPath.replace('.log', `.${i}.log`)
377
+ // #7162: anchored to the FINAL '.log' — a first-occurrence string replace
378
+ // would rewrite a '.log' embedded in the directory path (e.g. a log dir
379
+ // named 'my.logs'), aiming every rename at a nonexistent sibling dir and
380
+ // silently disabling rotation (the ENOENT is swallowed below by design).
381
+ for (let i = maxFiles; i >= 1; i--) {
382
+ const from = i === 1 ? logPath : logPath.replace(/\.log$/, `.${i - 1}.log`)
383
+ const to = logPath.replace(/\.log$/, `.${i}.log`)
221
384
  try {
222
385
  renameSync(from, to)
223
386
  } catch (err) {
@@ -226,6 +389,10 @@ function _maybeRotate() {
226
389
  }
227
390
  }
228
391
 
392
+ function _maybeRotate() {
393
+ _maybeRotateAt(_logPath, MAX_LOG_SIZE, MAX_LOG_FILES)
394
+ }
395
+
229
396
  /**
230
397
  * Change the minimum log level at runtime.
231
398
  * Useful for --verbose CLI flags to enable debug output. (#747)
@@ -264,17 +431,42 @@ export function createLogger(component, context = {}) {
264
431
  // listener broadcast, file write) is identical to a normal line.
265
432
  if (!always && LOG_LEVELS[level] < _logLevel) return
266
433
 
267
- const safeMsg = redactSensitive(msg)
434
+ const safeMsg = redactLogMessage(msg)
268
435
  const timestamp = new Date().toISOString()
269
436
  const line = _jsonMode
270
437
  ? JSON.stringify({ ts: timestamp, level, component, msg: safeMsg })
271
438
  : `${timestamp} [${level.toUpperCase()}] [${component}] ${safeMsg}`
272
439
 
440
+ // #7162: the file write happens FIRST so console quieting can key on this
441
+ // line's ACTUAL fate rather than on configuration: a quieted line whose
442
+ // file append fails (disk full, permissions) falls back to the console
443
+ // mirror, so no line — audit lines above all — is ever lost to both
444
+ // sinks at once.
445
+ let fileWriteOk = false
446
+ if (_logToFile && _logPath) {
447
+ try {
448
+ appendFileSync(_logPath, line + '\n')
449
+ fileWriteOk = true
450
+ _writeCount++
451
+ if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
452
+ _maybeRotate()
453
+ }
454
+ } catch {
455
+ // Silently ignore write failures (disk full, permission denied, etc.)
456
+ // to prevent logging errors from crashing the server (#746).
457
+ // fileWriteOk stays false, which re-enables the console mirror below.
458
+ }
459
+ }
460
+
273
461
  // Write to console (for foreground mode). #6566: `toConsole:false` suppresses
274
462
  // the console write while keeping the file + listener paths — used by the
275
463
  // supervisor to log a REDACTED connect-block line to disk while printing the
276
464
  // un-redacted line to the operator's terminal separately under --show-token.
277
- if (toConsole) {
465
+ // #7162: daemon-mode quieting drops info/debug/audit console mirrors, but
466
+ // only for a line the file log verifiably recorded (fileWriteOk).
467
+ const quieted = _quietConsole && fileWriteOk
468
+ && level !== 'warn' && level !== 'error'
469
+ if (toConsole && !quieted) {
278
470
  if (level === 'error') console.error(line)
279
471
  else if (level === 'warn') console.warn(line)
280
472
  else console.log(line)
@@ -293,17 +485,22 @@ export function createLogger(component, context = {}) {
293
485
  }
294
486
  }
295
487
 
296
- // Write to file in daemon mode
297
- if (_logToFile && _logPath) {
488
+ // #7162: audit lines additionally land in the dedicated audit log — the
489
+ // §9.1 retention floor. Gated on the level itself (only audit() produces
490
+ // it), NOT on `always`, so a future caller passing {always:true} to
491
+ // info()/warn() cannot write non-audit content into the forensic file.
492
+ // Rotation is size-checked on every audit write (audit volume is
493
+ // rate-ceiling-bounded, so the per-write stat is cheap). The line stays
494
+ // in chroxy.log above ("in the daemon log", §9.1); this copy is the one
495
+ // whose retention noise can't touch. Kept fire-and-forget here — #7169's
496
+ // fail-closed audit writer layers its success-reporting on top of this
497
+ // sink rather than replacing the level-independent path.
498
+ if (level === 'audit' && _logToFile && _auditLogPath) {
298
499
  try {
299
- appendFileSync(_logPath, line + '\n')
300
- _writeCount++
301
- if (_writeCount % ROTATION_CHECK_INTERVAL === 0) {
302
- _maybeRotate()
303
- }
500
+ appendFileSync(_auditLogPath, line + '\n')
501
+ _maybeRotateAt(_auditLogPath, MAX_AUDIT_LOG_SIZE, MAX_AUDIT_LOG_FILES)
304
502
  } catch {
305
- // Silently ignore write failures (disk full, permission denied, etc.)
306
- // to prevent logging errors from crashing the server (#746)
503
+ // Same #746 rationale as above.
307
504
  }
308
505
  }
309
506
  }
@@ -386,3 +583,15 @@ export function loggerForSession(component, sessionId) {
386
583
  export function sessionLogger(sessionId, component = 'ws') {
387
584
  return sessionId ? loggerForSession(component, sessionId) : createLogger(component)
388
585
  }
586
+
587
+ /**
588
+ * A client-supplied value, safe to put in a log line: a JSON-quoted string
589
+ * capped at 128 characters, so a newline or control character in it cannot
590
+ * start a second log line. A non-string is named by its type.
591
+ * @param {unknown} value
592
+ * @returns {string}
593
+ */
594
+ export function loggableValue(value) {
595
+ if (typeof value !== 'string') return typeof value
596
+ return JSON.stringify(value.slice(0, 128))
597
+ }