@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,383 @@
1
+ /**
2
+ * Long-lived server identity keypair for E2E key pinning (#5536).
3
+ *
4
+ * The transport key exchange (ws-auth.js / ws-history.js) is per-connection and
5
+ * ephemeral — it gives forward secrecy but NO server identity, so it is pure
6
+ * TOFU: a MITM who swaps the server's ephemeral exchange public key in flight
7
+ * relays the whole session undetected. To give the daemon a stable identity we
8
+ * mint a LONG-LIVED Ed25519 signing keypair once, persist it across restarts,
9
+ * and:
10
+ *
11
+ * 1. publish its PUBLIC half out-of-band in the pairing payload (QR /
12
+ * pairing-code / chroxy:// link — already a trusted channel), where the
13
+ * client PINS it; and
14
+ * 2. SIGN every per-connection ephemeral exchange public key with the secret
15
+ * half, so the client can verify (against the pinned identity) that the
16
+ * exchange key it is about to key off really came from this daemon.
17
+ *
18
+ * A MITM cannot forge the signature without the identity secret, so swapping
19
+ * the exchange key is detected and the client refuses the connection.
20
+ *
21
+ * Persistence mirrors credential-cipher.js's honest model:
22
+ * - Preferred: the OS keychain (macOS Keychain / Linux libsecret), under a
23
+ * dedicated service so it never collides with the API token or the
24
+ * credential data key.
25
+ * - Fallback: a 0600 file in ~/.chroxy/ when no keychain is available
26
+ * (Windows / headless Linux). The secret is no more exposed there than the
27
+ * API token or session state already are on the same disk, and a stable
28
+ * identity that survives restart is the whole point — a per-restart key
29
+ * would force a re-pair on every daemon bounce.
30
+ *
31
+ * The keychain module is dependency-injected (tests pass a fake) and the file
32
+ * path is overridable so tests never touch the real ~/.chroxy/ tree.
33
+ */
34
+ import { readFileSync, mkdirSync } from 'node:fs'
35
+ import { join, dirname } from 'node:path'
36
+ import { homedir } from 'node:os'
37
+ import { createSigningKeyPair, signIdentityRotation } from '@chroxy/store-core/crypto'
38
+ import nacl from 'tweetnacl'
39
+ import * as realKeychain from './keychain.js'
40
+ import { writeFileRestricted } from './platform.js'
41
+ import { createLogger } from './logger.js'
42
+
43
+ const log = createLogger('identity')
44
+
45
+ /** Keychain service for the identity secret key. Distinct from 'chroxy' (API
46
+ * token) and 'chroxy-cred-key' (credential data key) so the three never
47
+ * collide. */
48
+ export const IDENTITY_KEY_SERVICE = 'chroxy-identity-key'
49
+
50
+ /**
51
+ * Thrown when the keychain is PRESENT but the identity read FAILED (locked /
52
+ * interaction-not-allowed / backend error) — i.e. case (b) of #5615. This is the
53
+ * one case where we must NOT mint a fresh key (silent rotation → false MITM for
54
+ * every pinned client) and must NOT silently fall back to TOFU. The caller
55
+ * (server-cli) treats this distinctly: it signs nothing this boot and surfaces
56
+ * an "identity unavailable" state rather than rotating or impersonating.
57
+ *
58
+ * Distinct from a generic error so server startup can tell "keychain hiccup, do
59
+ * not rotate" apart from "no keychain at all / first run" (mint is correct) and
60
+ * from a malformed stored key (re-mint-as-absent — case (c), kept as before).
61
+ */
62
+ export class IdentityUnavailableError extends Error {
63
+ constructor(message) {
64
+ super(message)
65
+ this.name = 'IdentityUnavailableError'
66
+ this.code = 'IDENTITY_UNAVAILABLE'
67
+ }
68
+ }
69
+
70
+ /** Default on-disk fallback location. Overridable for tests. */
71
+ export const DEFAULT_IDENTITY_FILE = join(homedir(), '.chroxy', 'server-identity.json')
72
+
73
+ /**
74
+ * #5616/#5976 — the identity-rotation continuity-cert sidecar. PUBLIC data only
75
+ * (a signature + two public keys), so it is a plaintext file regardless of where
76
+ * the SECRET key lives (keychain or fallback file) — there is nothing secret to
77
+ * protect here. Single-hop by design: each rotation OVERWRITES it, retaining
78
+ * only the most-recent `prev → current` cert. A client pinned ≥2 rotations back
79
+ * has no chain to follow and correctly falls back to manual re-pair.
80
+ */
81
+ export const DEFAULT_IDENTITY_ROTATION_FILE = join(homedir(), '.chroxy', 'server-identity-rotation.json')
82
+
83
+ const SECRET_KEY_BYTES = nacl.sign.secretKeyLength // 64
84
+
85
+ /**
86
+ * Decode a stored base64 secret key into a SigningKeyPair, or return null when
87
+ * the stored value is absent / malformed (wrong length / bad base64).
88
+ * @param {string|null} storedB64
89
+ * @returns {{ publicKey: string, secretKey: Uint8Array }|null}
90
+ */
91
+ function secretKeyFromStored(storedB64) {
92
+ if (!storedB64 || typeof storedB64 !== 'string') return null
93
+ let secretKey
94
+ try {
95
+ secretKey = new Uint8Array(Buffer.from(storedB64.trim(), 'base64'))
96
+ } catch {
97
+ return null
98
+ }
99
+ if (secretKey.length !== SECRET_KEY_BYTES) return null
100
+ // The Ed25519 public key is the trailing 32 bytes of the 64-byte secret key.
101
+ // Buffer base64 is the same standard alphabet tweetnacl-util uses, so the
102
+ // public key string here matches what createSigningKeyPair produced.
103
+ const publicKey = Buffer.from(secretKey.slice(32)).toString('base64')
104
+ return { publicKey, secretKey }
105
+ }
106
+
107
+ /**
108
+ * Load the persisted identity keypair WITHOUT creating one. Checks the keychain
109
+ * first, then the 0600 fallback file. Returns the SigningKeyPair or null when
110
+ * none is stored (or the stored value is malformed — treated as absent).
111
+ *
112
+ * @param {object} [opts]
113
+ * @param {object} [opts.keychain] - injected keychain module (defaults to real)
114
+ * @param {string} [opts.filePath] - fallback file path (defaults to ~/.chroxy/server-identity.json)
115
+ * @returns {{ publicKey: string, secretKey: Uint8Array }|null}
116
+ */
117
+ export function loadServerIdentity({ keychain = realKeychain, filePath = DEFAULT_IDENTITY_FILE } = {}) {
118
+ // Keychain first (when available). #5615: distinguish a genuine "absent" from a
119
+ // READ FAILURE (locked / interaction-not-allowed). On a read failure we MUST
120
+ // NOT fall through to the file / minting path — that would silently rotate the
121
+ // identity and brick every pinned client with a false MITM alert. Throw a
122
+ // distinct error so the caller fails safe.
123
+ if (keychain.isKeychainAvailable()) {
124
+ const { status, value, error } = readIdentityFromKeychain(keychain)
125
+ if (status === 'error') {
126
+ throw new IdentityUnavailableError(
127
+ `server identity keychain read failed (${error ?? 'unknown'}); refusing to mint a replacement`,
128
+ )
129
+ }
130
+ if (status === 'found') {
131
+ const kp = secretKeyFromStored(value)
132
+ // A malformed stored value (case (c)) is treated as absent — fall through
133
+ // to the file / mint path, re-minting as before. This is deliberately
134
+ // distinct from the read-failure case above (which throws).
135
+ if (kp) return kp
136
+ }
137
+ // status === 'absent' (or malformed found) → continue to the file fallback.
138
+ }
139
+ // Fallback file. Checked even when the keychain is unavailable (disabled OR
140
+ // broken): a valid file identity is authoritative and using it does NOT rotate.
141
+ try {
142
+ const raw = readFileSync(filePath, 'utf-8')
143
+ const parsed = JSON.parse(raw)
144
+ const kp = secretKeyFromStored(parsed?.secretKey)
145
+ if (kp) return kp
146
+ } catch {
147
+ // Missing / unreadable / malformed — treated as "no identity yet".
148
+ }
149
+ // #5615 (#6234 follow-up): no file identity, and the keychain is present but
150
+ // BROKEN/unreadable (not merely disabled). We cannot confirm there is no
151
+ // pinned identity sitting in the now-unreadable keychain, so minting a fresh
152
+ // one would false-MITM every already-pinned client. Fail safe — refuse to
153
+ // mint — exactly as the pre-#6234 keychain-read-error path did, but WITHOUT
154
+ // the macOS modal (the broken state is detected by the non-prompting probe).
155
+ // Disabled keychains (tests / CHROXY_DISABLE_KEYCHAIN) are NOT broken: they
156
+ // legitimately fall through to mint a first-run identity.
157
+ if (typeof keychain.isKeychainBroken === 'function' && keychain.isKeychainBroken()) {
158
+ throw new IdentityUnavailableError(
159
+ 'server identity keychain is unavailable (broken/missing) and no fallback identity file exists; refusing to mint a replacement that would invalidate pinned clients',
160
+ )
161
+ }
162
+ return null
163
+ }
164
+
165
+ /**
166
+ * Read the identity secret from the keychain, distinguishing absent from a read
167
+ * failure. Prefers the injected keychain's `getTokenStatus` (the real module +
168
+ * fakes that opt in); falls back to `getToken` (legacy fakes) where a null read
169
+ * is treated as `absent` — those fakes cannot model a lock, which is fine since
170
+ * they never exercise the failure path.
171
+ *
172
+ * @param {object} keychain
173
+ * @returns {{ status: 'found'|'absent'|'error', value: string|null, error: string|null }}
174
+ */
175
+ function readIdentityFromKeychain(keychain) {
176
+ if (typeof keychain.getTokenStatus === 'function') {
177
+ return keychain.getTokenStatus(IDENTITY_KEY_SERVICE)
178
+ }
179
+ const value = keychain.getToken(IDENTITY_KEY_SERVICE)
180
+ return value
181
+ ? { status: 'found', value, error: null }
182
+ : { status: 'absent', value: null, error: null }
183
+ }
184
+
185
+ /**
186
+ * Persist a SigningKeyPair's secret half. Writes to the keychain when available,
187
+ * otherwise to a 0600 fallback file (creating the directory if needed). Returns
188
+ * the storage backend used ('keychain' | 'file'), or throws if the file write
189
+ * fails with no keychain available.
190
+ *
191
+ * @param {{ secretKey: Uint8Array }} keyPair
192
+ * @param {object} [opts]
193
+ * @param {object} [opts.keychain]
194
+ * @param {string} [opts.filePath]
195
+ * @returns {'keychain'|'file'}
196
+ */
197
+ export function persistServerIdentity(keyPair, { keychain = realKeychain, filePath = DEFAULT_IDENTITY_FILE } = {}) {
198
+ const secretB64 = Buffer.from(keyPair.secretKey).toString('base64')
199
+ if (keychain.isKeychainAvailable()) {
200
+ try {
201
+ keychain.setToken(secretB64, IDENTITY_KEY_SERVICE)
202
+ return 'keychain'
203
+ } catch (err) {
204
+ log.warn(`Keychain write for server identity failed (${err.message}); falling back to 0600 file`)
205
+ }
206
+ }
207
+ // 0600 file fallback. Use the repo's atomic, perm-enforcing writer
208
+ // (temp + chmod 0600 + rename) rather than a bare writeFileSync: this file
209
+ // holds the daemon's long-lived identity SECRET, so it must not be left
210
+ // partially written on a crash, and `writeFileSync`'s `mode` is honoured only
211
+ // on CREATION — a pre-existing file at a looser mode would keep that mode.
212
+ // writeFileRestricted chmods the final file to 0600 unconditionally.
213
+ mkdirSync(dirname(filePath), { recursive: true })
214
+ writeFileRestricted(filePath, JSON.stringify({ v: 1, secretKey: secretB64 }))
215
+ return 'file'
216
+ }
217
+
218
+ /**
219
+ * Get the daemon's long-lived identity keypair, minting + persisting a fresh one
220
+ * on first run. The public half is what clients pin at pairing time; the secret
221
+ * half signs each connection's ephemeral exchange key.
222
+ *
223
+ * Stable across restarts: a returning daemon loads the SAME key, so previously
224
+ * paired clients keep verifying against the identity they pinned. Re-pairing is
225
+ * only needed if the key is deliberately rotated (deleting the keychain entry /
226
+ * fallback file) — at which point pinned clients correctly refuse until re-paired.
227
+ *
228
+ * #5615 — three distinct keychain cases:
229
+ * (a) keychain absent / no identity stored → FIRST RUN, mint (correct).
230
+ * (b) keychain present but the read FAILED (locked / interaction-not-allowed)
231
+ * → `loadServerIdentity` throws {@link IdentityUnavailableError}, which
232
+ * propagates UNCAUGHT here. We do NOT mint a replacement (silent rotation
233
+ * would brick every pinned client with a false MITM alert). The caller
234
+ * decides whether to refuse startup or run with pinning disabled THIS BOOT.
235
+ * (c) keychain present but the stored value is MALFORMED → treated as absent
236
+ * (re-mint), the long-standing behaviour, kept distinct from (b).
237
+ *
238
+ * @param {object} [opts]
239
+ * @param {object} [opts.keychain]
240
+ * @param {string} [opts.filePath]
241
+ * @returns {{ publicKey: string, secretKey: Uint8Array, created: boolean, backend: 'keychain'|'file' }}
242
+ * @throws {IdentityUnavailableError} when the keychain read failed (case b)
243
+ */
244
+ export function getOrCreateServerIdentity({ keychain = realKeychain, filePath = DEFAULT_IDENTITY_FILE } = {}) {
245
+ // NB: a keychain read failure throws IdentityUnavailableError here — let it
246
+ // propagate. Catching it would re-enable the silent-rotation bug (#5615).
247
+ const existing = loadServerIdentity({ keychain, filePath })
248
+ if (existing) {
249
+ const backend = keychain.isKeychainAvailable() && keychain.getToken(IDENTITY_KEY_SERVICE) ? 'keychain' : 'file'
250
+ return { ...existing, created: false, backend }
251
+ }
252
+ const kp = createSigningKeyPair()
253
+ const backend = persistServerIdentity(kp, { keychain, filePath })
254
+ log.info(`Minted new server identity key (backend: ${backend})`)
255
+ return { ...kp, created: true, backend }
256
+ }
257
+
258
+ /**
259
+ * Load the single-hop rotation continuity cert sidecar, or null when absent /
260
+ * malformed. Returns the public triple a rotated daemon presents at handshake:
261
+ * `{ newIdentityKey, rotationCert, previousPublicKey }`.
262
+ *
263
+ * The caller MUST guard against a STALE sidecar: after a clean reinstall the
264
+ * identity is re-minted but an old sidecar may linger, so only present the cert
265
+ * when `newIdentityKey` equals the daemon's CURRENT identity public key (a stale
266
+ * sidecar names a `newIdentityKey` the daemon no longer holds). {@link
267
+ * resolveServerRotationCert} does that check.
268
+ *
269
+ * @param {object} [opts]
270
+ * @param {string} [opts.rotationFilePath]
271
+ * @returns {{ newIdentityKey: string, rotationCert: string, previousPublicKey: string }|null}
272
+ */
273
+ export function loadServerRotationCert({ rotationFilePath = DEFAULT_IDENTITY_ROTATION_FILE } = {}) {
274
+ try {
275
+ const parsed = JSON.parse(readFileSync(rotationFilePath, 'utf-8'))
276
+ const { newIdentityKey, rotationCert, previousPublicKey } = parsed ?? {}
277
+ if (
278
+ typeof newIdentityKey === 'string' && newIdentityKey &&
279
+ typeof rotationCert === 'string' && rotationCert &&
280
+ typeof previousPublicKey === 'string' && previousPublicKey
281
+ ) {
282
+ return { newIdentityKey, rotationCert, previousPublicKey }
283
+ }
284
+ } catch {
285
+ // Missing / unreadable / malformed → no cert to present.
286
+ }
287
+ return null
288
+ }
289
+
290
+ /**
291
+ * Resolve the rotation cert to present for a given CURRENT identity public key,
292
+ * applying the staleness guard: a sidecar whose `newIdentityKey` does not match
293
+ * the live identity (e.g. left over from before a clean re-mint) is ignored.
294
+ *
295
+ * @param {string} currentIdentityPublicKey - the daemon's live identity pubkey
296
+ * @param {object} [opts]
297
+ * @param {string} [opts.rotationFilePath]
298
+ * @returns {{ rotationCert: string, previousPublicKey: string }|null}
299
+ */
300
+ export function resolveServerRotationCert(currentIdentityPublicKey, { rotationFilePath = DEFAULT_IDENTITY_ROTATION_FILE } = {}) {
301
+ const sidecar = loadServerRotationCert({ rotationFilePath })
302
+ if (!sidecar) return null
303
+ if (sidecar.newIdentityKey !== currentIdentityPublicKey) {
304
+ // Stale sidecar (identity re-minted since rotation) — do NOT present it; a
305
+ // cert for an identity the daemon no longer holds would never verify and
306
+ // could only confuse a pinned client.
307
+ log.warn('Ignoring stale identity-rotation cert (newIdentityKey ≠ current identity)')
308
+ return null
309
+ }
310
+ return { rotationCert: sidecar.rotationCert, previousPublicKey: sidecar.previousPublicKey }
311
+ }
312
+
313
+ /**
314
+ * Rotate the daemon's identity (#5616/#5976, admin-initiated via
315
+ * `chroxy identity rotate`): mint a NEW identity, sign it with the OLD secret to
316
+ * mint a continuity cert ("old signs new"), persist the new secret in place of
317
+ * the old, and write the single-hop sidecar. A previously-pinned client that
318
+ * reconnects then chains its pin forward automatically (no manual re-pair) by
319
+ * verifying the cert against its pinned (old) key + the new key's live exchange
320
+ * signature.
321
+ *
322
+ * The OLD secret is read FIRST (while it still exists) — this is the only moment
323
+ * a cert can be minted. After this returns, the persisted identity is the NEW
324
+ * one; a running daemon keeps its in-memory OLD identity until restarted, so the
325
+ * caller must restart the daemon to serve the new identity.
326
+ *
327
+ * Throws when there is no current identity to rotate FROM (nothing pinned yet —
328
+ * just start the daemon, which mints a first identity), or when the keychain
329
+ * read failed ({@link IdentityUnavailableError} propagates).
330
+ *
331
+ * @param {object} [opts]
332
+ * @param {object} [opts.keychain]
333
+ * @param {string} [opts.filePath] - secret-key store path (fallback file)
334
+ * @param {string} [opts.rotationFilePath] - cert sidecar path
335
+ * @returns {{ previousPublicKey: string, newPublicKey: string, backend: 'keychain'|'file' }}
336
+ */
337
+ export function rotateServerIdentity({
338
+ keychain = realKeychain,
339
+ filePath = DEFAULT_IDENTITY_FILE,
340
+ rotationFilePath = DEFAULT_IDENTITY_ROTATION_FILE,
341
+ } = {}) {
342
+ const current = loadServerIdentity({ keychain, filePath })
343
+ if (!current) {
344
+ throw new Error(
345
+ 'No existing server identity to rotate. Start the daemon once to mint an ' +
346
+ 'identity (which clients then pair + pin) before rotating.',
347
+ )
348
+ }
349
+ const next = createSigningKeyPair()
350
+ // Mint the continuity cert WHILE the old secret is still loaded — old signs new.
351
+ const rotationCert = signIdentityRotation(next.publicKey, current.secretKey)
352
+
353
+ // ORDER MATTERS (fail-safety): write the sidecar BEFORE swapping the secret.
354
+ // - sidecar write fails → we throw here, the secret is STILL the old one →
355
+ // the identity did not rotate at all (old pins keep verifying). Safe.
356
+ // - sidecar ok but persist fails → we throw below, the secret is STILL old →
357
+ // the daemon serves the OLD identity and the just-written sidecar names a
358
+ // newIdentityKey ≠ the live identity, so resolveServerRotationCert IGNORES
359
+ // it as stale. Safe.
360
+ // The dangerous order (persist secret first) could leave a ROTATED identity
361
+ // with no cert — forcing every pinned client to manually re-pair, the exact
362
+ // failure this feature exists to prevent.
363
+ //
364
+ // Single-hop: this overwrites any prior cert — only the most recent
365
+ // prev→current hop is retained. Public data (a signature + two public keys);
366
+ // reuse writeFileRestricted for its ATOMIC temp+rename write so a crash can't
367
+ // leave a half-written cert — the 0600 mode it also sets is incidental here
368
+ // (nothing secret), not a requirement.
369
+ mkdirSync(dirname(rotationFilePath), { recursive: true })
370
+ writeFileRestricted(
371
+ rotationFilePath,
372
+ JSON.stringify({
373
+ v: 1,
374
+ newIdentityKey: next.publicKey,
375
+ rotationCert,
376
+ previousPublicKey: current.publicKey,
377
+ }),
378
+ )
379
+ // Persist the new secret in place of the old (keychain or fallback file).
380
+ const backend = persistServerIdentity(next, { keychain, filePath })
381
+ log.info(`Rotated server identity (backend: ${backend}); continuity cert written for previous pin`)
382
+ return { previousPublicKey: current.publicKey, newPublicKey: next.publicKey, backend }
383
+ }