@chroxy/server 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CONFIG.md +411 -14
  2. package/hooks/permission-hook.sh +253 -3
  3. package/package.json +8 -15
  4. package/sidecar/node_modules/.package-lock.json +29 -0
  5. package/sidecar/node_modules/ws/LICENSE +20 -0
  6. package/sidecar/node_modules/ws/README.md +548 -0
  7. package/sidecar/node_modules/ws/browser.js +8 -0
  8. package/sidecar/node_modules/ws/index.js +22 -0
  9. package/sidecar/node_modules/ws/lib/buffer-util.js +131 -0
  10. package/sidecar/node_modules/ws/lib/constants.js +19 -0
  11. package/sidecar/node_modules/ws/lib/event-target.js +292 -0
  12. package/sidecar/node_modules/ws/lib/extension.js +203 -0
  13. package/sidecar/node_modules/ws/lib/limiter.js +55 -0
  14. package/sidecar/node_modules/ws/lib/permessage-deflate.js +528 -0
  15. package/sidecar/node_modules/ws/lib/receiver.js +706 -0
  16. package/sidecar/node_modules/ws/lib/sender.js +602 -0
  17. package/sidecar/node_modules/ws/lib/stream.js +161 -0
  18. package/sidecar/node_modules/ws/lib/subprotocol.js +62 -0
  19. package/sidecar/node_modules/ws/lib/validation.js +152 -0
  20. package/sidecar/node_modules/ws/lib/websocket-server.js +554 -0
  21. package/sidecar/node_modules/ws/lib/websocket.js +1393 -0
  22. package/sidecar/node_modules/ws/package.json +70 -0
  23. package/sidecar/node_modules/ws/wrapper.mjs +21 -0
  24. package/src/base-session.js +151 -6
  25. package/src/billing-budget.js +5 -1
  26. package/src/binary-provenance-trust.js +95 -0
  27. package/src/built-in-tools/file-ops.js +5 -4
  28. package/src/byok-mcp-client.js +1061 -13
  29. package/src/byok-mcp-config.js +1201 -4
  30. package/src/byok-mcp-fleet.js +374 -29
  31. package/src/byok-mcp-oauth-store.js +327 -0
  32. package/src/byok-mcp-oauth.js +635 -0
  33. package/src/byok-mcp-trust.js +254 -37
  34. package/src/byok-session.js +789 -13
  35. package/src/byok-tool-executor.js +20 -13
  36. package/src/checkpoint-manager.js +33 -6
  37. package/src/chroxy-host-metadata.js +122 -0
  38. package/src/claude-stream-parser.js +56 -0
  39. package/src/claude-tui/pty-driver.js +54 -14
  40. package/src/claude-tui-session.js +106 -7
  41. package/src/cli/config-cmd.js +2 -2
  42. package/src/cli/deploy-cmd.js +1 -1
  43. package/src/cli/init-cmd.js +1 -1
  44. package/src/cli/providers-cmd.js +3 -3
  45. package/src/cli/schedule-cmd.js +775 -0
  46. package/src/cli/server-cmd.js +16 -1
  47. package/src/cli/service-cmd.js +39 -19
  48. package/src/cli/shared.js +7 -4
  49. package/src/cli/tokens-cmd.js +213 -0
  50. package/src/cli/tunnel-cmd.js +1 -1
  51. package/src/cli-session.js +66 -10
  52. package/src/cli.js +4 -0
  53. package/src/codex-app-server-session.js +671 -39
  54. package/src/codex-session.js +121 -18
  55. package/src/config.js +453 -27
  56. package/src/control-room/integrations.js +16 -10
  57. package/src/control-room/skills-inventory.js +6 -1
  58. package/src/control-room/survey.js +32 -0
  59. package/src/credential-store.js +256 -10
  60. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -0
  61. package/src/diagnostics.js +3 -0
  62. package/src/docker-sdk-session.js +16 -1
  63. package/src/docker-session.js +9 -0
  64. package/src/doctor.js +19 -8
  65. package/src/environments/backends/docker.js +8 -0
  66. package/src/environments/backends/k8s.js +9 -0
  67. package/src/event-ingest.js +19 -1
  68. package/src/event-normalizer.js +354 -19
  69. package/src/external-session-registry.js +0 -0
  70. package/src/gemini-session.js +19 -2
  71. package/src/github-webhook.js +188 -4
  72. package/src/handler-utils.js +42 -8
  73. package/src/handlers/checkpoint-handlers.js +126 -19
  74. package/src/handlers/control-room-handlers.js +48 -18
  75. package/src/handlers/conversation-handlers.js +127 -2
  76. package/src/handlers/credential-handlers.js +43 -2
  77. package/src/handlers/file-handlers.js +47 -3
  78. package/src/handlers/github-webhook-handlers.js +204 -0
  79. package/src/handlers/input-handlers.js +4 -0
  80. package/src/handlers/orchestration-handlers.js +238 -0
  81. package/src/handlers/scheduler-handlers.js +510 -0
  82. package/src/handlers/session-handlers.js +10 -2
  83. package/src/handlers/settings-handlers.js +510 -11
  84. package/src/handlers/token-handlers.js +11 -2
  85. package/src/http-routes.js +159 -0
  86. package/src/jsonl-reader.js +60 -6
  87. package/src/jsonl-subprocess-session.js +35 -6
  88. package/src/keychain.js +159 -12
  89. package/src/logger.js +182 -19
  90. package/src/notification-prefs.js +88 -6
  91. package/src/notifications/discord-webhook-sink.js +30 -1
  92. package/src/orchestration/build-manager.js +56 -0
  93. package/src/orchestration/decision-contract.js +245 -0
  94. package/src/orchestration/git-ops.js +347 -0
  95. package/src/orchestration/orchestration-manager.js +1295 -0
  96. package/src/orchestration/permission-gate.js +109 -0
  97. package/src/orchestration/role-prompts.js +136 -0
  98. package/src/orchestration/run-budget.js +81 -0
  99. package/src/orchestration/run-ledger.js +487 -0
  100. package/src/orchestration/run-model.js +205 -0
  101. package/src/orchestration/run-record.js +336 -0
  102. package/src/orchestration/run-report.js +194 -0
  103. package/src/orchestration/to-wire.js +201 -0
  104. package/src/orchestration/turn-driver.js +398 -0
  105. package/src/pairing.js +146 -1
  106. package/src/permission-audit.js +79 -3
  107. package/src/permission-floor.js +455 -0
  108. package/src/permission-manager.js +492 -40
  109. package/src/permission-resolver.js +55 -7
  110. package/src/permission-rule-store.js +411 -0
  111. package/src/platform.js +367 -23
  112. package/src/providers.js +21 -2
  113. package/src/schedule-parser.js +311 -0
  114. package/src/scheduled-task-store.js +653 -0
  115. package/src/scheduler.js +1029 -0
  116. package/src/sdk-session.js +338 -5
  117. package/src/server-cli/server-orchestrator.js +23 -0
  118. package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
  119. package/src/server-cli.js +238 -26
  120. package/src/server-identity.js +28 -4
  121. package/src/service.js +291 -33
  122. package/src/session-manager.js +417 -25
  123. package/src/session-message-history.js +27 -21
  124. package/src/session-title.js +168 -0
  125. package/src/session-token-store.js +60 -35
  126. package/src/skills-usage.js +20 -2
  127. package/src/statusline.js +584 -0
  128. package/src/subagent-counter.js +9 -1
  129. package/src/supervisor.js +77 -27
  130. package/src/token-manager.js +39 -9
  131. package/src/transcript-tasks.js +41 -6
  132. package/src/tunnel/cloudflare.js +115 -8
  133. package/src/tunnel/index.js +4 -1
  134. package/src/tunnel-check.js +1 -1
  135. package/src/turn-tracker.js +0 -0
  136. package/src/usage-normalize.js +118 -0
  137. package/src/user-shell-session.js +98 -32
  138. package/src/utils/componentwise-resolver.js +205 -0
  139. package/src/utils/composite-key.js +45 -0
  140. package/src/utils/iso-datetime.js +51 -0
  141. package/src/utils/preflight.js +140 -28
  142. package/src/utils/spawn-env.js +8 -2
  143. package/src/utils/verify-binary.js +276 -0
  144. package/src/utils/verify-provenance.js +241 -0
  145. package/src/utils/wire-counters.js +48 -0
  146. package/src/worktree-gc.js +4 -1
  147. package/src/ws-file-ops/browser.js +42 -11
  148. package/src/ws-file-ops/common.js +68 -1
  149. package/src/ws-file-ops/git.js +221 -3
  150. package/src/ws-file-ops/index.js +5 -0
  151. package/src/ws-file-ops/memory.js +358 -0
  152. package/src/ws-file-ops/reader.js +124 -0
  153. package/src/ws-forwarding.js +44 -16
  154. package/src/ws-handler-context.js +19 -0
  155. package/src/ws-history.js +84 -11
  156. package/src/ws-message-handlers.js +6 -0
  157. package/src/ws-outbound-schemas.js +207 -0
  158. package/src/ws-permissions.js +285 -4
  159. package/src/ws-schemas.js +1 -0
  160. package/src/ws-server.js +301 -17
@@ -15,6 +15,7 @@ import { isPoolEnabled } from './docker-byok-pool.js'
15
15
  import { getSharedPoolStats } from './docker-byok-pool-stats.js'
16
16
  import { isValidSlug, mimeForPath } from './pages-store.js'
17
17
  import { sendOversizeResponse } from './http-oversize.js'
18
+ import { resolveOAuthCallback, MCP_OAUTH_CALLBACK_PATH } from './byok-mcp-oauth.js'
18
19
 
19
20
  /**
20
21
  * #5683 — read + JSON-parse a request body with a byte cap. Resolves to the
@@ -96,6 +97,13 @@ const PAGE_SECURITY_HEADERS = {
96
97
 
97
98
  const log = createLogger('ws')
98
99
 
100
+ /** Minimal HTML-escape for interpolating an untrusted value into a page body. */
101
+ function escapeHtml(s) {
102
+ return String(s).replace(/[&<>"']/g, (c) => (
103
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]
104
+ ))
105
+ }
106
+
99
107
  const __filename = fileURLToPath(import.meta.url)
100
108
  const __dirname = dirname(__filename)
101
109
  const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
@@ -394,6 +402,73 @@ export function createHttpHandler(server) {
394
402
  return
395
403
  }
396
404
 
405
+ // #6822 — MCP OAuth redirect callback. The browser that completed consent
406
+ // (on the user's own device) is redirected here with `?code=...&state=...`.
407
+ // This route is intentionally UNAUTHENTICATED: the redirect carries no bearer
408
+ // token, and the high-entropy `state` value (bound server-side to a specific
409
+ // pending authorization) IS the capability. We hand the code to the matching
410
+ // pending client, which redeems it + persists tokens. When the daemon isn't
411
+ // reachable from the user's browser (remote/tunneled) this page never loads —
412
+ // the user copy-pastes the code back over the wire instead (the universal
413
+ // fallback). Never logs the code.
414
+ const oauthCbPath = (req.url ?? '').split('?')[0]
415
+ if (req.method === 'GET' && oauthCbPath === MCP_OAUTH_CALLBACK_PATH) {
416
+ let code = null
417
+ let state = null
418
+ let oauthError = null
419
+ try {
420
+ const parsed = new URL(req.url, 'http://localhost')
421
+ code = parsed.searchParams.get('code')
422
+ state = parsed.searchParams.get('state')
423
+ oauthError = parsed.searchParams.get('error')
424
+ } catch { /* malformed url — handled as missing params below */ }
425
+
426
+ const page = (title, body) =>
427
+ `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">` +
428
+ `<title>${title}</title><style>body{font-family:system-ui,-apple-system,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#1a2332;line-height:1.5}` +
429
+ `code{background:#eef1f6;padding:.15rem .35rem;border-radius:.25rem;word-break:break-all}h1{font-size:1.25rem}</style></head><body>${body}</body></html>`
430
+
431
+ const sendPage = (status, title, body) => {
432
+ res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', ...PAGE_SECURITY_HEADERS })
433
+ res.end(page(title, body))
434
+ }
435
+
436
+ if (oauthError) {
437
+ sendPage(400, 'Authorization failed',
438
+ `<h1>Authorization was not completed</h1><p>The authorization server reported an error. You can close this tab and try authorizing again from Chroxy.</p>`)
439
+ return
440
+ }
441
+ if (!code || !state) {
442
+ sendPage(400, 'Authorization callback',
443
+ `<h1>Missing authorization details</h1><p>This page expects a <code>code</code> and <code>state</code> from the authorization server. If you reached it manually, return to Chroxy and use the paste-code option.</p>`)
444
+ return
445
+ }
446
+
447
+ resolveOAuthCallback(state, code)
448
+ .then((outcome) => {
449
+ if (outcome.found && outcome.ok) {
450
+ sendPage(200, 'Authorized',
451
+ `<h1>MCP server authorized</h1><p>You can close this tab and return to Chroxy — the server is reconnecting now.</p>`)
452
+ } else if (outcome.found) {
453
+ // The daemon received the callback but redemption failed. Surface the
454
+ // code so the user can retry via paste (value shown only to the user
455
+ // whose browser holds the redirect; never logged server-side).
456
+ sendPage(200, 'Finish in Chroxy',
457
+ `<h1>Almost there</h1><p>Automatic completion didn't succeed. Copy this authorization code and paste it into Chroxy:</p><p><code>${escapeHtml(code)}</code></p>`)
458
+ } else {
459
+ // No pending authorization matched this state (expired, wrong daemon,
460
+ // or already completed). Offer the paste-code fallback.
461
+ sendPage(200, 'Finish in Chroxy',
462
+ `<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
463
+ }
464
+ })
465
+ .catch(() => {
466
+ sendPage(200, 'Finish in Chroxy',
467
+ `<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
468
+ })
469
+ return
470
+ }
471
+
397
472
  // Metrics endpoint — operational counters for monitoring
398
473
  if (req.method === 'GET' && req.url === '/metrics') {
399
474
  if (!server._validateBearerAuth(req, res)) return
@@ -521,6 +596,80 @@ export function createHttpHandler(server) {
521
596
  return
522
597
  }
523
598
 
599
+ // Paired-devices roster + live revoke (#6678, part of epic #6597). The
600
+ // dashboard "Paired devices" panel lists the RUNNING daemon's paired
601
+ // session tokens (wire-safe ids, bound session, age — never token material)
602
+ // and revokes them live: unlike `chroxy tokens revoke` (which edits the
603
+ // persisted store and needs a daemon restart), these hit PairingManager's
604
+ // in-memory map so the device's next auth fails immediately.
605
+ //
606
+ // PRIMARY-token only on ALL THREE. The roster is host-level pairing state —
607
+ // a scoped/paired device must neither enumerate its siblings (information
608
+ // disclosure) nor revoke them (a host-level mutation beyond one session's
609
+ // scope). Mirrors the DELETE /api/snapshots gate; see
610
+ // docs/security/bearer-token-authority.md §9.
611
+ if (req.method === 'GET' && snapPath === '/api/paired-devices') {
612
+ if (!server._validatePrimaryBearerAuth(req, res)) return
613
+ const pm = server._pairingManager
614
+ const devices = pm && typeof pm.listSessionTokens === 'function' ? pm.listSessionTokens() : []
615
+ res.writeHead(200, { 'Content-Type': 'application/json' })
616
+ res.end(JSON.stringify({ devices }))
617
+ return
618
+ }
619
+
620
+ // Revoke ALL paired devices — the panic button. Exact-path match (no id), so
621
+ // it never collides with the per-device DELETE below.
622
+ if (req.method === 'DELETE' && snapPath === '/api/paired-devices') {
623
+ if (!server._validatePrimaryBearerAuth(req, res)) return
624
+ const pm = server._pairingManager
625
+ const result = pm && typeof pm.revokeAllSessionTokens === 'function' ? pm.revokeAllSessionTokens() : { revoked: 0 }
626
+ // #6902: a failed durable write leaves every token valid on disk — report
627
+ // failure rather than a false `ok:true` so the operator re-tries instead of
628
+ // trusting a revoke a crash would undo.
629
+ if (result.persistFailed) {
630
+ res.writeHead(500, { 'Content-Type': 'application/json' })
631
+ res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
632
+ return
633
+ }
634
+ res.writeHead(200, { 'Content-Type': 'application/json' })
635
+ res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
636
+ return
637
+ }
638
+
639
+ // Revoke ONE paired device by its wire id (from GET /api/paired-devices).
640
+ if (req.method === 'DELETE' && snapPath.startsWith('/api/paired-devices/')) {
641
+ if (!server._validatePrimaryBearerAuth(req, res)) return
642
+ const rawId = snapPath.slice('/api/paired-devices/'.length)
643
+ let id
644
+ try {
645
+ id = decodeURIComponent(rawId)
646
+ } catch {
647
+ res.writeHead(400, { 'Content-Type': 'application/json' })
648
+ res.end(JSON.stringify({ error: 'invalid id encoding' }))
649
+ return
650
+ }
651
+ const pm = server._pairingManager
652
+ const result = pm && typeof pm.revokeSessionTokenById === 'function' ? pm.revokeSessionTokenById(id) : { revoked: 0 }
653
+ // #6902: the device exists but its removal could not be durably persisted —
654
+ // distinct from "no such device". Report failure (500) rather than a false
655
+ // success so the still-valid token isn't reported as revoked.
656
+ if (result.persistFailed) {
657
+ res.writeHead(500, { 'Content-Type': 'application/json' })
658
+ res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
659
+ return
660
+ }
661
+ if (result.revoked === 0) {
662
+ // The device is already gone (revoked elsewhere, expired, or a stale id
663
+ // from a device that re-paired). 404 so the UI can reconcile its list.
664
+ res.writeHead(404, { 'Content-Type': 'application/json' })
665
+ res.end(JSON.stringify({ error: 'no such paired device', revoked: 0 }))
666
+ return
667
+ }
668
+ res.writeHead(200, { 'Content-Type': 'application/json' })
669
+ res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
670
+ return
671
+ }
672
+
524
673
  // docker-byok pool stats endpoint (#5053). Returns a rolling
525
674
  // observability snapshot — hit/miss counters, hit rate,
526
675
  // eviction-by-reason, the recent-evictions tail, and the live per-key
@@ -712,6 +861,16 @@ export function createHttpHandler(server) {
712
861
  return
713
862
  }
714
863
 
864
+ // #7004 — protected-path / secret-read FLOOR probe for the permission hook.
865
+ // The hook decides auto/acceptEdits in shell, so it asks here whether the
866
+ // target is floored before short-circuiting; a floored target is routed to a
867
+ // real prompt via POST /permission. Same per-session hook-secret auth as
868
+ // /permission; read-only (no pending request, no broadcast, no push).
869
+ if (req.method === 'POST' && req.url === '/permission-floor') {
870
+ server._permissions.handlePermissionFloorCheck(req, res)
871
+ return
872
+ }
873
+
715
874
  // Permission response endpoint (HTTP fallback)
716
875
  if (req.method === 'POST' && req.url === '/permission-response') {
717
876
  server._permissions.handlePermissionResponseHttp(req, res)
@@ -1,10 +1,20 @@
1
- import { readFileSync, statSync, existsSync } from 'fs'
2
- import { readFile } from 'fs/promises'
1
+ import { readFileSync, statSync, existsSync, openSync, readSync, closeSync, fstatSync } from 'fs'
2
+ import { readFile, stat, open } from 'fs/promises'
3
3
  import { join } from 'path'
4
4
  import { homedir } from 'os'
5
5
 
6
6
  const MAX_MESSAGES = 500
7
7
 
8
+ // Byte ceiling for a single transcript read. The wire replay is capped at
9
+ // MAX_MESSAGES frames, but the file read itself was previously unbounded — a
10
+ // caller (including a bound client via the read-only transcript endpoint, #6860)
11
+ // could trigger a full-file buffer of an arbitrarily large JSONL. Files larger
12
+ // than this are read from the TAIL only (most-recent activity), so the result is
13
+ // gracefully truncated to recent history rather than crashing or buffering the
14
+ // whole file. 25MB comfortably fits even long real transcripts while bounding
15
+ // worst-case memory. Overridable per-call for tests.
16
+ export const MAX_TRANSCRIPT_BYTES = 25 * 1024 * 1024
17
+
8
18
  /**
9
19
  * Encode a filesystem path the same way Claude Code does for its project directories.
10
20
  * Replaces all `/` with `-`.
@@ -157,10 +167,13 @@ function parseJsonlContent(raw) {
157
167
  * @param {string} filePath - Absolute path to the JSONL file
158
168
  * @returns {Array<{ type: string, content: string, tool?: string, timestamp: number, messageId?: string }>}
159
169
  */
160
- export function readConversationHistory(filePath) {
170
+ export function readConversationHistory(filePath, maxBytes = MAX_TRANSCRIPT_BYTES) {
161
171
  let raw
162
172
  try {
163
- raw = readFileSync(filePath, 'utf-8')
173
+ const { size } = statSync(filePath)
174
+ raw = size > maxBytes
175
+ ? readTailBytesSync(filePath, maxBytes)
176
+ : readFileSync(filePath, 'utf-8')
164
177
  } catch {
165
178
  return []
166
179
  }
@@ -168,6 +181,26 @@ export function readConversationHistory(filePath) {
168
181
  return parseJsonlContent(raw)
169
182
  }
170
183
 
184
+ /**
185
+ * Read the last `maxBytes` of a file (sync). Used when a JSONL exceeds the
186
+ * transcript byte ceiling so the read stays bounded. The window's first line is
187
+ * usually a partial JSONL record; parseJsonlContent skips unparseable lines, so
188
+ * the truncated head is dropped automatically.
189
+ */
190
+ function readTailBytesSync(filePath, maxBytes) {
191
+ const fd = openSync(filePath, 'r')
192
+ try {
193
+ const { size } = fstatSync(fd)
194
+ const start = Math.max(0, size - maxBytes)
195
+ const length = size - start
196
+ const buf = Buffer.alloc(length)
197
+ readSync(fd, buf, 0, length, start)
198
+ return new TextDecoder('utf-8', { fatal: false }).decode(buf)
199
+ } finally {
200
+ closeSync(fd)
201
+ }
202
+ }
203
+
171
204
  /**
172
205
  * Async variant of readConversationHistory.
173
206
  * Uses fs.promises.readFile to avoid blocking the event loop for large JSONL files.
@@ -175,13 +208,34 @@ export function readConversationHistory(filePath) {
175
208
  * @param {string} filePath - Absolute path to the JSONL file
176
209
  * @returns {Promise<Array<{ type: string, content: string, tool?: string, timestamp: number, messageId?: string }>>}
177
210
  */
178
- export async function readConversationHistoryAsync(filePath) {
211
+ export async function readConversationHistoryAsync(filePath, maxBytes = MAX_TRANSCRIPT_BYTES) {
179
212
  let raw
180
213
  try {
181
- raw = await readFile(filePath, 'utf-8')
214
+ const { size } = await stat(filePath)
215
+ raw = size > maxBytes
216
+ ? await readTailBytesAsync(filePath, maxBytes)
217
+ : await readFile(filePath, 'utf-8')
182
218
  } catch {
183
219
  return []
184
220
  }
185
221
 
186
222
  return parseJsonlContent(raw)
187
223
  }
224
+
225
+ /**
226
+ * Async variant of readTailBytesSync — read the last `maxBytes` of a file so an
227
+ * oversized transcript read stays bounded (see MAX_TRANSCRIPT_BYTES).
228
+ */
229
+ async function readTailBytesAsync(filePath, maxBytes) {
230
+ const handle = await open(filePath, 'r')
231
+ try {
232
+ const { size } = await handle.stat()
233
+ const start = Math.max(0, size - maxBytes)
234
+ const length = size - start
235
+ const buf = Buffer.alloc(length)
236
+ await handle.read(buf, 0, length, start)
237
+ return new TextDecoder('utf-8', { fatal: false }).decode(buf)
238
+ } finally {
239
+ await handle.close()
240
+ }
241
+ }
@@ -5,6 +5,8 @@ import { createLogger } from './logger.js'
5
5
  import { guardChildStreams } from './child-stream-guard.js'
6
6
  import { getErrorMessage } from './utils/error-message.js'
7
7
  import { prepareSpawn } from './utils/win-spawn.js'
8
+ import { labelBinarySpawnFailure } from './utils/verify-binary.js'
9
+ import { killProcessTree } from './platform.js'
8
10
 
9
11
  const log = createLogger('jsonl-subprocess-session')
10
12
 
@@ -159,9 +161,11 @@ export class JsonlSubprocessSession extends BaseSession {
159
161
  // this session instance. Mirrors CliSession.destroy() (#4602).
160
162
  this._clearIntentionalStop()
161
163
  if (this._process) {
162
- try {
163
- this._process.kill('SIGTERM')
164
- } catch { /* already dead */ }
164
+ // #6643 — on Windows SIGTERM only TerminateProcess-es the cmd.exe shim
165
+ // wrapping a `.cmd` provider (codex/gemini/…), orphaning the real node
166
+ // grandchild (there is no forceKill escalation on this path). Reap the
167
+ // whole tree; POSIX behaviour is an identical graceful SIGTERM.
168
+ killProcessTree(this._process)
165
169
  this._process = null
166
170
  }
167
171
  this.removeAllListeners()
@@ -294,11 +298,21 @@ export class JsonlSubprocessSession extends BaseSession {
294
298
 
295
299
  const args = this._buildArgs(effectiveText)
296
300
  let proc
301
+ // Captured once here so the spawn-time backstop (#6708) verifies the EXACT
302
+ // binary this attempt used — both the sync catch below and the async
303
+ // proc.on('error') handler — rather than a fresh re-resolve that could land
304
+ // on a different path than the one that failed.
305
+ let attemptedBinary = null
297
306
  try {
298
307
  // #6484 — the resolver can hand us a `.cmd` shim on Windows (npm-only host,
299
308
  // no native `.exe`); spawning a `.cmd` via child_process throws EINVAL on
300
309
  // Node 24, so route it through cmd.exe with proper escaping — the same
301
310
  // prepareSpawn cli-session.js uses. No-op for a `.exe` and on POSIX.
311
+ // The prepareSpawn(Klass.resolvedBinary, args) call is kept verbatim (the
312
+ // #6484 source guard scans for it); attemptedBinary captures the same
313
+ // binary for the #6708 spawn-time backstop (err.path is preferred at the
314
+ // catch sites, this is only the fallback).
315
+ attemptedBinary = Klass.resolvedBinary
302
316
  const spawnSpec = prepareSpawn(Klass.resolvedBinary, args)
303
317
  proc = spawn(spawnSpec.command, spawnSpec.args, {
304
318
  cwd: this.cwd,
@@ -310,12 +324,20 @@ export class JsonlSubprocessSession extends BaseSession {
310
324
  ...spawnSpec.options,
311
325
  })
312
326
  } catch (err) {
313
- // spawn() can throw synchronously (ENOENT for missing binary, EACCES,
327
+ // spawn() can throw synchronously (EINVAL for a bad `.cmd` on Node 24,
314
328
  // etc.) — leave _skillsPrepended false so a retry still injects the
315
329
  // skills text. Reset busy state and surface the error to the caller.
316
330
  this._isBusy = false
331
+ // #6708 — a spawn failure AFTER preflight passed means the binary changed
332
+ // out from under us (quarantined / moved / removed by XProtect between
333
+ // session-create and this turn). Re-verify the ATTEMPTED path so the error
334
+ // names the real cause + fix instead of an opaque failure.
335
+ const labeled = labelBinarySpawnFailure({
336
+ attemptedPath: err?.path || attemptedBinary,
337
+ binary: Klass.providerName,
338
+ })
317
339
  this.emit('error', {
318
- message: getErrorMessage(err, `Failed to spawn ${Klass.providerName}`),
340
+ message: labeled || getErrorMessage(err, `Failed to spawn ${Klass.providerName}`),
319
341
  })
320
342
  return
321
343
  }
@@ -433,8 +455,15 @@ export class JsonlSubprocessSession extends BaseSession {
433
455
  this._skillsPrepended = false
434
456
  }
435
457
  if (this._destroying) return
458
+ // #6708 — a launch failure here (async ENOENT/EACCES is the REAL missing-
459
+ // /quarantined-binary path; the sync catch above only sees Node-24 `.cmd`
460
+ // EINVAL) → label the ATTEMPTED path's cause + fix instead of a bare ENOENT.
461
+ const labeled = labelBinarySpawnFailure({
462
+ attemptedPath: err?.path || attemptedBinary,
463
+ binary: Klass.providerName,
464
+ })
436
465
  this.emit('error', {
437
- message: err.message || `Failed to spawn ${Klass.providerName}`,
466
+ message: labeled || err.message || `Failed to spawn ${Klass.providerName}`,
438
467
  })
439
468
  })
440
469
  }
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
 
@@ -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
+ }