@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,786 @@
1
+ /**
2
+ * Generalized provider-credential store (#3855).
3
+ *
4
+ * Backs the dashboard "Provider Credentials" Settings pane. Stores per-provider
5
+ * API keys and OAuth tokens in `~/.chroxy/credentials.json`, mode 0600,
6
+ * owner-only. Never stores plaintext world-readable; refuses to read a file
7
+ * whose mode is not exactly 0600 — anything else (more permissive like 0644,
8
+ * OR stricter like 0400) is rejected, matching the #4052 BYOK store this
9
+ * generalizes (see byok-credentials.js). The strict-equality check keeps the
10
+ * boundary simple and predictable; operators always set 0600.
11
+ *
12
+ * Resolution order for each known credential env var (used by spawn-env.js):
13
+ * 1. process.env.<KEY> — explicit shell export wins (power users keep control)
14
+ * 2. credential store — fills the Tauri/launchd GUI-launch gap (cwd=/, no rc)
15
+ * 3. unset — provider's existing missing-key error path fires
16
+ *
17
+ * File layout (forward-compatible with the #4052 single-key shape):
18
+ * {
19
+ * "anthropicApiKey": "sk-ant-...", // legacy #4052 alias for ANTHROPIC_API_KEY
20
+ * "ANTHROPIC_API_KEY": "sk-ant-...",
21
+ * "GEMINI_API_KEY": "...",
22
+ * "OPENAI_API_KEY": "...",
23
+ * "CLAUDE_CODE_OAUTH_TOKEN": "..."
24
+ * }
25
+ *
26
+ * The raw value NEVER leaves this module except through resolveCredential()
27
+ * (for injection into a spawned child env). Status views only ever return the
28
+ * masked form via maskApiKey().
29
+ *
30
+ * Credentials are never logged. The redactor at logger.js scrubs `sk-ant-` and
31
+ * `Bearer` patterns, and SENSITIVE_KEYS in config.js masks the file path; this
32
+ * module additionally never passes a raw value to any logger call.
33
+ *
34
+ * At-rest encryption (#5154): on hosts with an OS keychain (macOS Keychain /
35
+ * Linux libsecret), the file is encrypted with a random data key stored in the
36
+ * keychain — see credential-cipher.js. The 0600 owner-only mode is retained as
37
+ * defense-in-depth even when encrypted. Where no keychain is available
38
+ * (Windows, headless Linux without `secret-tool`) the store falls back to 0600
39
+ * plaintext, since a key stored beside the file would be obfuscation, not
40
+ * security. `maybeEncryptCredentialsAtRest()` migrates a legacy plaintext file
41
+ * in place at startup once a keychain is present. See
42
+ * docs/security/credentials-at-rest.md for the full threat model.
43
+ */
44
+ import { readFileSync, statSync, writeFileSync, chmodSync, renameSync, mkdirSync, unlinkSync, existsSync } from 'fs'
45
+ import { join, dirname } from 'path'
46
+ import { homedir } from 'os'
47
+ import { randomBytes } from 'crypto'
48
+ import { maskApiKey } from './byok-credentials.js'
49
+ import * as realKeychain from './keychain.js'
50
+ import { createLogger } from './logger.js'
51
+ import {
52
+ CRED_KEY_SERVICE,
53
+ isEncryptedEnvelope,
54
+ decryptEnvelope,
55
+ encryptJson,
56
+ getMasterKey,
57
+ getOrCreateMasterKey,
58
+ rotateMasterKey,
59
+ setMasterKey,
60
+ } from './credential-cipher.js'
61
+
62
+ // A keychain stub that reports "no keychain here" — selects the plaintext
63
+ // fallback path.
64
+ const NO_KEYCHAIN = { isKeychainAvailable: () => false }
65
+
66
+ // #5258: Windows rename-failure codes that indicate a held handle (antivirus /
67
+ // Windows Search) on the destination, not a genuine I/O error. Mirrors
68
+ // session-state-persistence.WINDOWS_LOCK_CODES — replaceFileAtomically retries
69
+ // once on these.
70
+ const CRED_WINDOWS_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
71
+
72
+ // #5242: logger for the recoverable encrypted-but-keychain-unavailable warning.
73
+ // Injectable for tests. Credentials are NEVER passed to it — only the key NAME
74
+ // and the fact of the failure (the logger.js redactor scrubs sk-ant/Bearer too).
75
+ let _log = createLogger('credentials')
76
+ export function _setCredentialLoggerForTests(logger) {
77
+ _log = logger || createLogger('credentials')
78
+ }
79
+
80
+ // #5242: keys we've already warned about, so the spawn path (which calls
81
+ // resolveCredential on every child launch) warns once per key, not per spawn.
82
+ const _keychainUnavailableWarned = new Set()
83
+ export function _resetKeychainWarningsForTests() {
84
+ _keychainUnavailableWarned.clear()
85
+ }
86
+
87
+ /**
88
+ * #5242: emit a one-time warning that an ENCRYPTED credential exists on disk but
89
+ * its keychain data key is currently unavailable (locked keychain, transient
90
+ * `security`/`secret-tool` failure, denied/timed-out unlock prompt) — a
91
+ * RECOVERABLE condition distinct from a corrupt/bad-mode file. Without this, the
92
+ * spawn path (resolveCredential → buildSpawnEnv) silently launches a subprocess
93
+ * provider unauthenticated despite a valid credential on disk. The warning makes
94
+ * that observable; the value is never logged.
95
+ *
96
+ * @param {string} key
97
+ */
98
+ function warnKeychainUnavailableOnce(key) {
99
+ if (_keychainUnavailableWarned.has(key)) return
100
+ _keychainUnavailableWarned.add(key)
101
+ _log.warn(
102
+ `${key} is stored (encrypted) but its OS keychain data key is currently unavailable — resolving as unset. ` +
103
+ `A spawned child may launch unauthenticated. Unlock the OS keychain (or re-store the credential) and retry.`,
104
+ )
105
+ }
106
+
107
+ // Explicit test injection (an in-memory keychain), or null to use the resolved
108
+ // default. Takes precedence over the env escape hatch below.
109
+ let _keychainOverride = null
110
+
111
+ /**
112
+ * Resolve the keychain to use for at-rest encryption, evaluated lazily per call
113
+ * (NOT captured at import). `keychain.js` is imported at the top of this file,
114
+ * but no OS-keychain call (or `process.env` read) happens until a store
115
+ * operation actually runs — so importing `credential-store.js` never triggers a
116
+ * `child_process` keychain probe at module-load time. (Test isolation against
117
+ * `mock.module('child_process')` is owned by `_setup.mjs`, which deliberately
118
+ * imports neither this module nor `keychain.js`.)
119
+ *
120
+ * 1. an explicit test injection wins (the encryption suite's in-memory key);
121
+ * 2. else `CHROXY_CRED_DISABLE_KEYCHAIN=1` forces the plaintext fallback —
122
+ * an operator escape hatch for hosts with an unreliable keychain, and the
123
+ * switch the test bootstrap sets so suites never touch the real keychain;
124
+ * 3. else the real OS keychain.
125
+ */
126
+ function activeKeychain() {
127
+ if (_keychainOverride) return _keychainOverride
128
+ if (process.env.CHROXY_CRED_DISABLE_KEYCHAIN === '1') return NO_KEYCHAIN
129
+ return realKeychain
130
+ }
131
+
132
+ /**
133
+ * Test seam: inject a keychain (e.g. an in-memory one to drive the encrypted
134
+ * path), or pass null to fall back to the resolved default.
135
+ */
136
+ export function _setCredentialKeychainForTests(keychain) {
137
+ _keychainOverride = keychain || null
138
+ }
139
+
140
+ /**
141
+ * The credential env vars the store manages, with display metadata. The order
142
+ * here is the order the dashboard renders rows in.
143
+ *
144
+ * `kind`:
145
+ * 'api-key' — a provider API key (validated by `validate`).
146
+ * 'oauth-token' — a long-lived OAuth token variant (CLAUDE_CODE_OAUTH_TOKEN).
147
+ *
148
+ * `validate(value)` returns null when valid, or an error string. Kept loose on
149
+ * purpose — provider key formats evolve — but catches obvious wrong-thing
150
+ * pastes (e.g. an OpenAI key dropped into the Anthropic field).
151
+ */
152
+ export const KNOWN_CREDENTIALS = Object.freeze([
153
+ Object.freeze({
154
+ key: 'ANTHROPIC_API_KEY',
155
+ provider: 'Anthropic',
156
+ label: 'Anthropic API key',
157
+ kind: 'api-key',
158
+ validate: (v) => (v.startsWith('sk-ant-') ? null : 'Anthropic API keys start with "sk-ant-".'),
159
+ }),
160
+ Object.freeze({
161
+ key: 'CLAUDE_CODE_OAUTH_TOKEN',
162
+ provider: 'Anthropic',
163
+ label: 'Claude Code OAuth token',
164
+ kind: 'oauth-token',
165
+ // OAuth token format is opaque; only require a non-empty trimmed value.
166
+ validate: () => null,
167
+ }),
168
+ Object.freeze({
169
+ key: 'GEMINI_API_KEY',
170
+ provider: 'Google Gemini',
171
+ label: 'Gemini API key',
172
+ kind: 'api-key',
173
+ validate: () => null,
174
+ }),
175
+ Object.freeze({
176
+ key: 'OPENAI_API_KEY',
177
+ provider: 'OpenAI / Codex',
178
+ label: 'OpenAI API key',
179
+ kind: 'api-key',
180
+ validate: (v) => (v.startsWith('sk-') ? null : 'OpenAI API keys start with "sk-".'),
181
+ }),
182
+ ])
183
+
184
+ const KNOWN_KEYS = new Set(KNOWN_CREDENTIALS.map((c) => c.key))
185
+
186
+ /**
187
+ * #4052 forward-compat: the original single-key store wrote `anthropicApiKey`.
188
+ * Map that legacy field onto the canonical `ANTHROPIC_API_KEY` slot when
189
+ * reading, and keep writing it alongside the canonical key so an older server
190
+ * (or the byok-session resolver) still finds it.
191
+ */
192
+ const LEGACY_FIELD_BY_KEY = Object.freeze({ ANTHROPIC_API_KEY: 'anthropicApiKey' })
193
+
194
+ /** @returns {boolean} whether `key` is a credential the store manages. */
195
+ export function isKnownCredentialKey(key) {
196
+ return KNOWN_KEYS.has(key)
197
+ }
198
+
199
+ // Lazy-resolved per call so tests that mutate process.env.HOME between cases
200
+ // pick up the new home; if captured at module load it would freeze on first import.
201
+ function credentialsFilePath() {
202
+ return join(homedir(), '.chroxy', 'credentials.json')
203
+ }
204
+
205
+ /**
206
+ * Read + parse the credentials file, enforcing the 0600 mode boundary.
207
+ *
208
+ * @returns {{ data: Record<string, string>, fileExists: boolean, error: string | null }}
209
+ * `data` is the parsed object (empty when missing/unreadable). `error` is a
210
+ * human-readable reason when the file exists but cannot be safely read
211
+ * (bad mode, bad JSON) — callers surface it without exposing any value.
212
+ */
213
+ function readStore() {
214
+ const file = credentialsFilePath()
215
+ let stat
216
+ try {
217
+ stat = statSync(file)
218
+ } catch (err) {
219
+ if (err.code === 'ENOENT') return { data: {}, fileExists: false, error: null }
220
+ return { data: {}, fileExists: false, error: `unable to stat ${file}: ${err.message}` }
221
+ }
222
+
223
+ // Refuse any mode that is not exactly 0600 (POSIX) — both more-permissive
224
+ // (e.g. 0644) and stricter (e.g. 0400) modes are rejected. On win32 the mode
225
+ // bits don't reflect NTFS ACLs, so skip the check there (matches #4144).
226
+ if (process.platform !== 'win32') {
227
+ const perms = stat.mode & 0o777
228
+ if (perms !== 0o600) {
229
+ return {
230
+ data: {},
231
+ fileExists: true,
232
+ error: `${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600 — run: chmod 600 ${file})`,
233
+ }
234
+ }
235
+ }
236
+
237
+ let parsed
238
+ try {
239
+ parsed = JSON.parse(readFileSync(file, 'utf8'))
240
+ } catch (err) {
241
+ return { data: {}, fileExists: true, error: `${file} unreadable or not valid JSON: ${err.message}` }
242
+ }
243
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
244
+ return { data: {}, fileExists: true, error: `${file} is not a JSON object` }
245
+ }
246
+
247
+ // #5154 — an encrypted envelope requires the keychain data key to decrypt.
248
+ // A plaintext object passes through unchanged (legacy / no-keychain host).
249
+ if (isEncryptedEnvelope(parsed)) {
250
+ const key = getMasterKey(activeKeychain())
251
+ if (!key) {
252
+ // #5242: the RECOVERABLE case — the envelope is intact but the keychain
253
+ // data key can't be fetched (locked keychain, transient probe failure).
254
+ // `keychainUnavailable` distinguishes it from a decrypt-throw corruption
255
+ // below so the spawn-path warning only fires for this recoverable branch.
256
+ return {
257
+ data: {},
258
+ fileExists: true,
259
+ error: `${file} is encrypted but its decryption key is unavailable (OS keychain service "${CRED_KEY_SERVICE}" missing or unreadable)`,
260
+ encrypted: true,
261
+ keychainUnavailable: true,
262
+ }
263
+ }
264
+ try {
265
+ return { data: decryptEnvelope(parsed, key), fileExists: true, error: null, encrypted: true }
266
+ } catch (err) {
267
+ // The data key was present but decryption failed — a corrupt/invalid
268
+ // envelope, NOT a keychain-availability problem. No keychainUnavailable
269
+ // flag, so this does not trigger the keychain-unavailable warning.
270
+ return { data: {}, fileExists: true, error: `${file} could not be decrypted: ${err.message}`, encrypted: true }
271
+ }
272
+ }
273
+
274
+ return { data: parsed, fileExists: true, error: null, encrypted: false }
275
+ }
276
+
277
+ /**
278
+ * Atomically move `tmp` over `target`.
279
+ *
280
+ * #5243: relies on `renameSync`'s atomic replace — on win32 Node's
281
+ * `fs.renameSync` uses `MoveFileExW` with `MOVEFILE_REPLACE_EXISTING |
282
+ * MOVEFILE_WRITE_THROUGH` since v16 (see platform.js), so it already replaces an
283
+ * existing target without a separate delete. The previous win32 path
284
+ * `unlinkSync(target)` immediately BEFORE the rename — a crash in that window
285
+ * left no `credentials.json` at all (the live file deleted, the replacement
286
+ * never moved in). We now never pre-delete the live file; this matches the
287
+ * sibling `writeFileRestricted` (platform.js), which goes straight from
288
+ * `writeFileSync(tmp)` to `renameSync`.
289
+ *
290
+ * #5258: on Windows an antivirus / Windows Search held handle on `target` can
291
+ * make the atomic replace fail with EPERM/EACCES/EBUSY/EEXIST even though
292
+ * renameSync normally replaces atomically. We mirror
293
+ * session-state-persistence._rotateToBak's one-shot retry: snapshot the live
294
+ * target, clear it, then retry the rename once. The unlink happens ONLY after
295
+ * the atomic attempt already failed (never a pre-delete — that was the #5243
296
+ * data-loss bug). The in-memory snapshot lets us restore the live credentials
297
+ * if the *retry* also fails. It does NOT make the unlink→re-rename window
298
+ * crash-safe: a hard process crash in that window leaves `target` gone with the
299
+ * new payload only on the on-disk `.tmp` (no automated reader recovers it). To
300
+ * keep that window from ever destroying the only copy, we refuse to unlink when
301
+ * the snapshot read failed but the file is still present (see below) — so the
302
+ * worst pre-crash state is "live file intact, replace not applied".
303
+ *
304
+ * #5264: the win32 retry/refuse/restore branches emit credentials-safe
305
+ * `_log.warn` breadcrumbs (error codes only — never values or snapshot bytes)
306
+ * for observability parity with `_rotateToBak`.
307
+ *
308
+ * fs ops are injectable for testing (defaults are the real fs calls).
309
+ *
310
+ * @param {string} tmp - source temp path.
311
+ * @param {string} target - destination path.
312
+ * @param {{ rename?: Function, unlink?: Function, readFile?: Function, writeFile?: Function, platform?: string }} [deps]
313
+ */
314
+ export function replaceFileAtomically(tmp, target, deps = {}) {
315
+ const {
316
+ rename = renameSync,
317
+ unlink = unlinkSync,
318
+ readFile = readFileSync,
319
+ writeFile = writeFileSync,
320
+ platform = process.platform,
321
+ } = deps
322
+ try {
323
+ rename(tmp, target)
324
+ return
325
+ } catch (err) {
326
+ // Non-Windows, or an error that isn't a Windows held-handle lock: surface
327
+ // it unchanged (no unlink — preserves the #5243 no-pre-delete guarantee).
328
+ if (platform !== 'win32' || !err || !CRED_WINDOWS_LOCK_CODES.has(err.code)) throw err
329
+ // #5264: surface the recovery attempt for observability parity with
330
+ // session-state-persistence._rotateToBak. Only the error code is logged —
331
+ // never the credential value or any snapshot bytes (module invariant).
332
+ _log.warn(`credentials atomic replace hit a Windows held-handle lock (${err.code}); attempting one-shot retry`)
333
+ // Snapshot the live target so we can restore it if the retry also fails.
334
+ let snapshot = null
335
+ let snapshotErr = null
336
+ try { snapshot = readFile(target) } catch (readErr) { snapshotErr = readErr /* target may already be gone */ }
337
+ // If the snapshot failed but the target is still on disk (e.g. readFile threw
338
+ // EACCES/EPERM because the same held handle is blocking the read), unlinking
339
+ // it here would destroy the only copy with no way to restore — re-introducing
340
+ // the #5243 data-loss path. Keep the live file intact and surface the ORIGINAL
341
+ // lock error instead; the caller is no worse off than before the retry.
342
+ if (snapshot === null && existsSync(target)) {
343
+ _log.warn(`credentials atomic replace could not snapshot the live target before retry (lock ${err.code}, read ${snapshotErr?.code || 'unknown'}); leaving it intact and surfacing the lock error`)
344
+ throw err
345
+ }
346
+ try { unlink(target) } catch { /* best-effort — target may be gone */ }
347
+ try {
348
+ rename(tmp, target)
349
+ } catch (retryErr) {
350
+ // Retry still failed — restore the live bytes (if captured) so the prior
351
+ // credentials survive, then surface the error to the caller.
352
+ if (snapshot !== null) {
353
+ try {
354
+ writeFile(target, snapshot, { mode: 0o600 })
355
+ } catch (restoreErr) {
356
+ // Worst case: target deleted, retry failed, restore failed → no
357
+ // credentials on disk. Leave a breadcrumb (codes only) so the thrown
358
+ // error isn't the sole signal that a restore was even attempted.
359
+ _log.warn(`credentials atomic replace failed to restore the prior file after a failed retry (${restoreErr?.code || 'unknown'})`)
360
+ }
361
+ }
362
+ throw retryErr
363
+ }
364
+ }
365
+ }
366
+
367
+ /**
368
+ * Serialize + atomically write the store to `target`, encrypting the blob when
369
+ * a keychain-backed data key is available (#5154) and otherwise writing 0600
370
+ * plaintext. Preserves the temp-file → chmod 0600 → rename crash-safety and the
371
+ * post-write mode re-check (POSIX). `dir` is assumed to already exist (callers
372
+ * mkdir it). Shared by the set/delete/migrate paths.
373
+ */
374
+ function writeStoreAtomically(target, nextObj) {
375
+ const key = getOrCreateMasterKey(activeKeychain())
376
+ const payload = key ? encryptJson(nextObj, key) : nextObj
377
+
378
+ // randomBytes (not Math.random) for the atomic-write temp suffix — a predictable
379
+ // temp name is a (minor) symlink/pre-creation foothold; cryptographic randomness
380
+ // costs nothing here and matches the pattern in path-hash-trust-ledger.js.
381
+ const tmp = `${target}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`
382
+ let renamed = false
383
+ try {
384
+ writeFileSync(tmp, JSON.stringify(payload, null, 2), { mode: 0o600 })
385
+ if (process.platform !== 'win32') chmodSync(tmp, 0o600)
386
+ // #5243: atomic replace — never unlink the live target first.
387
+ replaceFileAtomically(tmp, target)
388
+ renamed = true
389
+ if (process.platform !== 'win32') {
390
+ const perms = statSync(target).mode & 0o777
391
+ if (perms !== 0o600) {
392
+ try { unlinkSync(target) } catch { /* */ }
393
+ throw new Error(`credentials file ended up with mode ${perms.toString(8)} after write; refused`)
394
+ }
395
+ }
396
+ } finally {
397
+ if (!renamed && existsSync(tmp)) {
398
+ try { unlinkSync(tmp) } catch { /* */ }
399
+ }
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Resolve the stored raw value for a credential key, honoring the legacy
405
+ * `anthropicApiKey` alias. Returns null when not present (or on a read error —
406
+ * callers that need the read error use the status surface instead).
407
+ *
408
+ * @param {string} key
409
+ * @returns {string | null}
410
+ */
411
+ export function getStoredCredential(key) {
412
+ if (!isKnownCredentialKey(key)) return null
413
+ const { data, error, keychainUnavailable } = readStore()
414
+ if (error) {
415
+ // #5242: a read error with `keychainUnavailable: true` is the RECOVERABLE
416
+ // case — an intact encrypted envelope whose keychain data key can't be
417
+ // fetched right now. Emit a one-time warning so a silent unauthenticated
418
+ // spawn is observable. Other read errors (bad mode/JSON, or a corrupt
419
+ // envelope that fails to decrypt) are already surfaced via
420
+ // getCredentialsStatus.fileError and are NOT the recoverable case.
421
+ if (keychainUnavailable) warnKeychainUnavailableOnce(key)
422
+ return null
423
+ }
424
+ const canonical = data[key]
425
+ if (typeof canonical === 'string' && canonical.length > 0) return canonical
426
+ const legacyField = LEGACY_FIELD_BY_KEY[key]
427
+ if (legacyField) {
428
+ const legacy = data[legacyField]
429
+ if (typeof legacy === 'string' && legacy.length > 0) return legacy
430
+ }
431
+ return null
432
+ }
433
+
434
+ /**
435
+ * #5867 — resolve a KNOWN credential's value AND the read metadata in one
436
+ * cipher-aware, alias-aware read. Like `getStoredCredential` but also returns
437
+ * the `readStore` metadata (`fileExists`, `error`, `keychainUnavailable`) so a
438
+ * caller can build a status `reason` that preserves the bad-mode /
439
+ * keychain-locked / corrupt-envelope / file-absent distinctions WITHOUT this
440
+ * module logging or echoing the value. The raw `value` is returned only to the
441
+ * caller. Honors the legacy `anthropicApiKey` alias like `getStoredCredential`.
442
+ *
443
+ * Used by byok-credentials.resolveAnthropicApiKey so the BYOK paid-auth read
444
+ * path goes through the encryption-aware store instead of a plaintext re-read.
445
+ *
446
+ * @param {string} key
447
+ * @returns {{ value: string | null, fileExists: boolean, error: string | null, keychainUnavailable: boolean }}
448
+ */
449
+ export function resolveStoredCredentialWithMeta(key) {
450
+ if (!isKnownCredentialKey(key)) {
451
+ return { value: null, fileExists: false, error: null, keychainUnavailable: false }
452
+ }
453
+ const { data, fileExists, error, keychainUnavailable } = readStore()
454
+ if (error) {
455
+ return { value: null, fileExists, error, keychainUnavailable: Boolean(keychainUnavailable) }
456
+ }
457
+ const canonical = data[key]
458
+ if (typeof canonical === 'string' && canonical.length > 0) {
459
+ return { value: canonical, fileExists, error: null, keychainUnavailable: false }
460
+ }
461
+ const legacyField = LEGACY_FIELD_BY_KEY[key]
462
+ if (legacyField) {
463
+ const legacy = data[legacyField]
464
+ if (typeof legacy === 'string' && legacy.length > 0) {
465
+ return { value: legacy, fileExists, error: null, keychainUnavailable: false }
466
+ }
467
+ }
468
+ return { value: null, fileExists, error: null, keychainUnavailable: false }
469
+ }
470
+
471
+ /**
472
+ * #5490 — read a single string field out of the credentials store, going
473
+ * through the SAME cipher-aware reader (`readStore`) the API-key resolvers use:
474
+ * 0600 mode enforcement, encrypted-envelope decryption, and the
475
+ * keychain-unavailable / corrupt-envelope distinctions all apply identically.
476
+ *
477
+ * Exposed for credential consumers whose field is NOT a `KNOWN_CREDENTIALS`
478
+ * env-var key — e.g. the Discord webhook URL (`discordWebhookUrl`), which lives
479
+ * in the same file but routes to the notification sink rather than a spawned
480
+ * provider. Returns the read metadata verbatim so the caller can build its own
481
+ * `reason` strings WITHOUT this module ever logging or echoing the value.
482
+ *
483
+ * The raw `value` is returned ONLY to the caller (never logged here). On any
484
+ * read error `value` is null and `error` carries a value-free reason. The
485
+ * `keychainUnavailable` flag marks the RECOVERABLE encrypted-but-locked case so
486
+ * callers can phrase a distinct (still value-free) reason.
487
+ *
488
+ * @param {string} field - the JSON field name to read (e.g. 'discordWebhookUrl')
489
+ * @returns {{ value: string | null, fileExists: boolean, error: string | null, keychainUnavailable: boolean }}
490
+ */
491
+ export function readStoredField(field) {
492
+ const { data, fileExists, error, keychainUnavailable } = readStore()
493
+ if (error) {
494
+ return { value: null, fileExists, error, keychainUnavailable: Boolean(keychainUnavailable) }
495
+ }
496
+ const raw = data[field]
497
+ const value = typeof raw === 'string' && raw.length > 0 ? raw : null
498
+ return { value, fileExists, error: null, keychainUnavailable: false }
499
+ }
500
+
501
+ /**
502
+ * Resolution order: process.env > store > unset.
503
+ *
504
+ * Used by spawn-env.js to inject stored credentials into a spawned child's
505
+ * environment when the operator's shell hasn't already exported the var. This
506
+ * is what makes a Tauri/launchd GUI launch (cwd=/, minimal PATH, no rc file)
507
+ * able to authenticate from stored credentials alone.
508
+ *
509
+ * @param {string} key
510
+ * @returns {{ value: string, source: 'env' | 'store' } | { value: null, source: 'unset' }}
511
+ */
512
+ export function resolveCredential(key) {
513
+ const envVal = process.env[key]
514
+ if (typeof envVal === 'string' && envVal.length > 0) {
515
+ return { value: envVal, source: 'env' }
516
+ }
517
+ const stored = getStoredCredential(key)
518
+ if (stored) return { value: stored, source: 'store' }
519
+ return { value: null, source: 'unset' }
520
+ }
521
+
522
+ /**
523
+ * Persist a credential value atomically with mode 0600. Trims whitespace and
524
+ * validates against the key's `validate` rule. Overwrites any existing value
525
+ * (rotation = overwrite; no rotation log in v1).
526
+ *
527
+ * Atomicity: write to a temp file with mode 0600, then rename over the target.
528
+ * A crash between write and rename leaves the prior file intact. Post-write the
529
+ * mode is re-stat'd (POSIX) and we throw if it didn't take.
530
+ *
531
+ * @param {string} key
532
+ * @param {string} rawValue
533
+ * @throws {Error} on unknown key, empty value, or validation failure
534
+ */
535
+ export function setStoredCredential(key, rawValue) {
536
+ const meta = KNOWN_CREDENTIALS.find((c) => c.key === key)
537
+ if (!meta) throw new Error(`Unknown credential key: ${key}`)
538
+ const value = typeof rawValue === 'string' ? rawValue.trim() : ''
539
+ if (value.length === 0) throw new Error(`${key} is required (non-empty string)`)
540
+ const validationError = meta.validate(value)
541
+ if (validationError) throw new Error(validationError)
542
+
543
+ const target = credentialsFilePath()
544
+ const dir = dirname(target)
545
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
546
+ if (process.platform !== 'win32') {
547
+ try { chmodSync(dir, 0o700) } catch { /* best-effort */ }
548
+ }
549
+
550
+ // Merge with the existing store so we don't clobber other keys. Read
551
+ // failures (bad mode/JSON) must NOT silently drop sibling keys, so a read
552
+ // error aborts the write with a clear message instead of overwriting.
553
+ const { data, error } = readStore()
554
+ if (error) throw new Error(error)
555
+ const next = { ...data, [key]: value }
556
+ // #4052 forward-compat: keep writing the legacy alias for ANTHROPIC_API_KEY.
557
+ const legacyField = LEGACY_FIELD_BY_KEY[key]
558
+ if (legacyField) next[legacyField] = value
559
+
560
+ writeStoreAtomically(target, next)
561
+ }
562
+
563
+ /**
564
+ * Remove a single credential from the store. No-op when absent. Rewrites the
565
+ * file atomically with the remaining keys (and removes the legacy alias too).
566
+ * Deletes the file entirely when it would be left empty.
567
+ *
568
+ * @param {string} key
569
+ */
570
+ export function deleteStoredCredential(key) {
571
+ if (!isKnownCredentialKey(key)) throw new Error(`Unknown credential key: ${key}`)
572
+ const target = credentialsFilePath()
573
+ const { data, fileExists, error } = readStore()
574
+ if (!fileExists) return
575
+ // A bad-mode/JSON file can't be safely rewritten without risking clobber of
576
+ // unknown content; surface the error rather than guess.
577
+ if (error) throw new Error(error)
578
+
579
+ const legacyField = LEGACY_FIELD_BY_KEY[key]
580
+ if (!(key in data) && !(legacyField && legacyField in data)) return // nothing to remove
581
+
582
+ const next = { ...data }
583
+ delete next[key]
584
+ if (legacyField) delete next[legacyField]
585
+
586
+ // If the store is now empty, remove the file entirely.
587
+ if (Object.keys(next).length === 0) {
588
+ try { unlinkSync(target) } catch (err) { if (err.code !== 'ENOENT') throw err }
589
+ return
590
+ }
591
+
592
+ writeStoreAtomically(target, next)
593
+ }
594
+
595
+ /**
596
+ * #5154 — encrypt a legacy plaintext credentials.json in place once an OS
597
+ * keychain is available. Mirrors the primary-token keychain migration in
598
+ * server-cli.js; call once at startup. Best-effort: never throws into boot.
599
+ *
600
+ * No-op (with a reason) when: the file is missing, no keychain is available
601
+ * (logs a one-time plaintext warning), the file is already encrypted, the file
602
+ * can't be safely read (bad mode / corrupt), or the store is empty.
603
+ *
604
+ * @param {{ log?: { info: Function, warn: Function } }} [opts]
605
+ * @returns {{ migrated: boolean, reason: string }}
606
+ */
607
+ export function maybeEncryptCredentialsAtRest({ log } = {}) {
608
+ const file = credentialsFilePath()
609
+ if (!existsSync(file)) return { migrated: false, reason: 'no-file' }
610
+
611
+ if (!activeKeychain().isKeychainAvailable()) {
612
+ if (log) log.warn(`${file} is stored as plaintext — no OS keychain available to encrypt it at rest`)
613
+ return { migrated: false, reason: 'no-keychain' }
614
+ }
615
+
616
+ const { data, error, encrypted } = readStore()
617
+ if (error) {
618
+ if (log) log.warn(`Credentials at-rest encryption skipped: ${error}`)
619
+ return { migrated: false, reason: 'read-error' }
620
+ }
621
+ if (encrypted) return { migrated: false, reason: 'already-encrypted' }
622
+ if (Object.keys(data).length === 0) return { migrated: false, reason: 'empty' }
623
+
624
+ try {
625
+ writeStoreAtomically(file, data) // getOrCreateMasterKey → writes an envelope
626
+ if (log) log.info('Encrypted credentials.json at rest using an OS-keychain-backed key')
627
+ return { migrated: true, reason: 'migrated' }
628
+ } catch (err) {
629
+ if (log) log.warn(`Credentials at-rest encryption failed: ${err.message}`)
630
+ return { migrated: false, reason: 'write-error' }
631
+ }
632
+ }
633
+
634
+ /**
635
+ * #5229 — rotate the at-rest credential data key. Generates a fresh keychain
636
+ * data key, re-encrypts the existing store under it, and atomically replaces
637
+ * credentials.json (temp → chmod 0600 → rename, via writeStoreAtomically). The
638
+ * single keychain entry (service `chroxy-cred-key`) is overwritten in place, so
639
+ * no stale key is left dangling.
640
+ *
641
+ * Crash-safety: the keychain rotation and the re-encrypting atomic write share a
642
+ * single try/catch failure domain. If either throws (disk full, permission, OS
643
+ * keychain write failure, mode re-check), the keychain is rolled back to the
644
+ * prior key (or deleted, if the store had been plaintext) so the existing on-disk
645
+ * envelope stays decryptable.
646
+ *
647
+ * One narrow exception to "envelope stays decryptable": writeStoreAtomically does
648
+ * a post-rename 0600 mode re-check, and on failure it unlinks the just-renamed
649
+ * target before throwing. In that single case the rollback restores the old key
650
+ * but there is no longer a file to decrypt — the new envelope was already removed.
651
+ * This is a defensive last resort (the file landed with unexpected perms, which
652
+ * shouldn't happen given the temp file is created mode 0600); the secrets remain
653
+ * recoverable from the provider, and the operator can re-run rekey/migrate.
654
+ *
655
+ * The only other unrecoverable window is a hard process crash between the keychain
656
+ * swap and the file rename — unavoidable without a second key slot, and
657
+ * vanishingly small.
658
+ *
659
+ * No-op (with a reason) when: no keychain is available (nowhere to hold a key),
660
+ * the file is missing, the store can't be safely read (bad mode / corrupt /
661
+ * undecryptable), or the store is empty.
662
+ *
663
+ * @param {{ log?: { info: Function, warn: Function } }} [opts]
664
+ * @returns {{ rekeyed: boolean, reason: string }}
665
+ */
666
+ export function rekeyCredentialStore({ log } = {}) {
667
+ const file = credentialsFilePath()
668
+ const keychain = activeKeychain()
669
+
670
+ if (!keychain.isKeychainAvailable()) {
671
+ if (log) log.warn('Credential rekey skipped — no OS keychain available to hold a data key')
672
+ return { rekeyed: false, reason: 'no-keychain' }
673
+ }
674
+ if (!existsSync(file)) return { rekeyed: false, reason: 'no-file' }
675
+
676
+ // Decrypt the current store up front: a read error (bad mode / corrupt /
677
+ // undecryptable) must abort BEFORE we touch the keychain, so we never strand
678
+ // a readable store behind a rotated key.
679
+ const { data, error } = readStore()
680
+ if (error) {
681
+ if (log) log.warn(`Credential rekey skipped: ${error}`)
682
+ return { rekeyed: false, reason: 'read-error' }
683
+ }
684
+ if (Object.keys(data).length === 0) return { rekeyed: false, reason: 'empty' }
685
+
686
+ // Capture the prior key for rollback (null when the store was plaintext).
687
+ const previousKey = getMasterKey(keychain)
688
+ // Treat the keychain rotation AND the re-encrypting file write as one failure
689
+ // domain: if EITHER throws we roll the keychain back to previousKey so the
690
+ // still-on-disk envelope stays decryptable. rotateMasterKey lives inside the
691
+ // try because its keychain write can throw (e.g. execFileSync to the OS
692
+ // keychain fails) and a partially-applied rotation would otherwise strand the
693
+ // existing envelope behind an uncaught error.
694
+ try {
695
+ rotateMasterKey(keychain) // keychain now holds the new key
696
+ writeStoreAtomically(file, data) // getOrCreateMasterKey → encrypts under the new key
697
+ if (log) log.info('Rotated the credential data key and re-encrypted credentials.json')
698
+ return { rekeyed: true, reason: 'rekeyed' }
699
+ } catch (err) {
700
+ // Roll the keychain back so the still-on-disk envelope stays decryptable.
701
+ // Best-effort: if rollback itself throws, surface the original error reason
702
+ // rather than masking it with a secondary keychain failure.
703
+ try {
704
+ setMasterKey(previousKey, keychain)
705
+ } catch (rollbackErr) {
706
+ if (log) log.warn(`Credential rekey rollback failed: ${rollbackErr.message}`)
707
+ }
708
+ if (log) log.warn(`Credential rekey failed: ${err.message}`)
709
+ return { rekeyed: false, reason: 'write-error' }
710
+ }
711
+ }
712
+
713
+ /** @returns {boolean} whether the credentials file exists on disk. */
714
+ export function credentialsFileExists() {
715
+ try { return existsSync(credentialsFilePath()) } catch { return false }
716
+ }
717
+
718
+ /**
719
+ * Build the masked, value-free status for every known credential. This is the
720
+ * ONLY status surface the WS layer should expose — it never includes a raw
721
+ * value. Each entry:
722
+ * - key, provider, label, kind — display metadata
723
+ * - status: 'set' | 'missing'
724
+ * - source: 'env' | 'store' | 'oauth' | 'none'
725
+ * - masked: when status='set' (and source !== 'oauth'), a redacted preview
726
+ * - oauth: true when an OAuth credential is detected for the provider
727
+ *
728
+ * @param {object} [helpers] - OAuth probes (injectable for tests).
729
+ * @param {() => boolean} [helpers.hasClaudeOAuthCreds]
730
+ * @param {() => boolean} [helpers.hasGeminiOAuthCreds]
731
+ * @param {() => boolean} [helpers.hasCodexOAuthCreds]
732
+ * @returns {{ credentials: Array<object>, fileExists: boolean, fileError: string | null }}
733
+ */
734
+ export function getCredentialsStatus(helpers = {}) {
735
+ const { hasClaudeOAuthCreds, hasGeminiOAuthCreds, hasCodexOAuthCreds } = helpers
736
+ const oauthByProvider = {
737
+ Anthropic: typeof hasClaudeOAuthCreds === 'function' ? Boolean(hasClaudeOAuthCreds()) : false,
738
+ 'Google Gemini': typeof hasGeminiOAuthCreds === 'function' ? Boolean(hasGeminiOAuthCreds()) : false,
739
+ 'OpenAI / Codex': typeof hasCodexOAuthCreds === 'function' ? Boolean(hasCodexOAuthCreds()) : false,
740
+ }
741
+
742
+ const { fileExists, error } = readStore()
743
+
744
+ const credentials = KNOWN_CREDENTIALS.map((meta) => {
745
+ const resolved = resolveCredential(meta.key)
746
+ const oauth = Boolean(oauthByProvider[meta.provider])
747
+ if (resolved.value) {
748
+ return {
749
+ key: meta.key,
750
+ provider: meta.provider,
751
+ label: meta.label,
752
+ kind: meta.kind,
753
+ status: 'set',
754
+ source: resolved.source,
755
+ masked: maskApiKey(resolved.value),
756
+ oauth,
757
+ }
758
+ }
759
+ // No API key/token configured. If the provider has OAuth creds, surface
760
+ // that as the live source (read-only — we don't manage `claude login`).
761
+ if (oauth) {
762
+ return {
763
+ key: meta.key,
764
+ provider: meta.provider,
765
+ label: meta.label,
766
+ kind: meta.kind,
767
+ status: 'missing',
768
+ source: 'oauth',
769
+ oauth: true,
770
+ }
771
+ }
772
+ return {
773
+ key: meta.key,
774
+ provider: meta.provider,
775
+ label: meta.label,
776
+ kind: meta.kind,
777
+ status: 'missing',
778
+ source: 'none',
779
+ oauth: false,
780
+ }
781
+ })
782
+
783
+ return { credentials, fileExists, fileError: error }
784
+ }
785
+
786
+ export { maskApiKey }