@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,307 @@
1
+ import fs from 'fs'
2
+ import { dirname } from 'path'
3
+ import { isWindows, writeFileRestricted } from './platform.js'
4
+ import { createLogger } from './logger.js'
5
+
6
+ const log = createLogger('session-state-persistence')
7
+
8
+ // Codes we treat as "destination is temporarily locked" on Windows.
9
+ // EPERM/EACCES: antivirus or another process holds a handle.
10
+ // EBUSY: destination is in use.
11
+ // EEXIST: destination already exists and rename won't atomically replace (NTFS).
12
+ const WINDOWS_LOCK_CODES = new Set(['EPERM', 'EACCES', 'EBUSY', 'EEXIST'])
13
+
14
+ /**
15
+ * Handles serialization/deserialization of session state to/from disk.
16
+ * Extracted from SessionManager to separate persistence concerns.
17
+ */
18
+ export class SessionStatePersistence {
19
+ /**
20
+ * @param {Object} options
21
+ * @param {string} options.stateFilePath - Path to session state JSON file
22
+ * @param {number} [options.stateTtlMs=86400000] - Max age of persisted state before discard (default: 24 hours)
23
+ * @param {number} [options.persistDebounceMs=2000] - Debounce interval for state file writes
24
+ * @param {boolean} [options.isWindowsOverride] - Test-only: force Windows-specific branches regardless of host platform
25
+ */
26
+ constructor({ stateFilePath, stateTtlMs, persistDebounceMs = 2000, isWindowsOverride } = {}) {
27
+ this._stateFilePath = stateFilePath
28
+ this._stateTtlMs = stateTtlMs ?? 24 * 60 * 60 * 1000
29
+ this._persistDebounceMs = persistDebounceMs
30
+ this._persistTimer = null
31
+ this._isWindows = isWindowsOverride ?? isWindows
32
+ }
33
+
34
+ /**
35
+ * Serialize session state to disk.
36
+ *
37
+ * Write order (audited in #4908): rotate the current file to `.bak` FIRST,
38
+ * then call `writeFileRestricted(mainPath, data)` which atomically writes
39
+ * via its own internal `.tmp` + rename on POSIX (and direct `writeFileSync`
40
+ * on Windows — see {@link writeFileRestricted}).
41
+ *
42
+ * Why rotate-then-write (not write-then-rotate)? Both orders are crash-safe,
43
+ * but rotate-first lets us reuse the shared atomic-write helper rather than
44
+ * hand-rolling a second `.tmp` + rename layer (the bespoke wrapper that
45
+ * #4874 collapsed elsewhere — this file was deferred per the #4874 issue
46
+ * body and audited separately in #4908):
47
+ * - If we crash AFTER rotate but BEFORE the write completes, `restoreState`
48
+ * falls back to `.bak` (see {@link restoreState} — when the main file is
49
+ * missing or unparseable it reads from `.bak`) which still holds the
50
+ * prior generation.
51
+ * - `writeFileRestricted` is atomic on POSIX (internal rename replaces the
52
+ * destination), so a partial write of the new generation cannot leave
53
+ * half-written bytes at `mainPath`.
54
+ * - On Windows, `writeFileRestricted` also writes to a temp file then
55
+ * `renameSync`s it into place (#4913) — the `renameSync` is the atomic
56
+ * step (it depends on the OS), and the temp write itself uses
57
+ * `writeFileSync` (no POSIX mode bits apply). Same temp+rename shape as
58
+ * POSIX since #4913; only the mode handling differs.
59
+ *
60
+ * `_rotateToBak`'s Windows retry-and-restore-`.bak` flow stays intact under
61
+ * the new order: the snapshot-and-restore happens before the main write, so
62
+ * a failed rotation leaves `.bak` holding whichever generation it held
63
+ * before serialize ran. The Windows `unlinkSync(mainPath)` step (NTFS
64
+ * EEXIST workaround) is no longer needed — after rotation, `mainPath`
65
+ * either does not exist (rotate succeeded) or holds the same bytes as
66
+ * `.bak` (rotate failed). `writeFileSync` on Windows overwrites either way.
67
+ *
68
+ * @param {object} state - The complete state object to write (version, timestamp, sessions, costs, etc.)
69
+ * @returns {object} The state that was written
70
+ */
71
+ serializeState(state) {
72
+ const dir = dirname(this._stateFilePath)
73
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
74
+ const bakPath = this._stateFilePath + '.bak'
75
+ // Rotate the current file to .bak BEFORE writing the new generation so
76
+ // one generation survives a crash mid-write. Best-effort — a missing
77
+ // source file (first write) or rename failure must not block the new write.
78
+ if (fs.existsSync(this._stateFilePath)) {
79
+ this._rotateToBak(this._stateFilePath, bakPath)
80
+ }
81
+ // writeFileRestricted does an atomic temp+rename on both POSIX and Windows
82
+ // (#4913); cleanup of the orphan temp on rename failure is handled inside.
83
+ // #5309 (WP-0.3) — pass a per-pid tmpSuffix so two processes writing the
84
+ // SAME state file (e.g. an accidental second `chroxy start` against
85
+ // ~/.chroxy/session-state.json, or a test runner + the daemon) don't race
86
+ // on a shared intermediate `.tmp` and clobber each other mid-write,
87
+ // corrupting the file. PIDs are unique among live processes, so the temp
88
+ // paths can't collide. Mirrors the models-cache precedent (models.js:488).
89
+ // Trade-off vs. the bare `.tmp`: the shared `.tmp` was self-healing (the
90
+ // next write O_TRUNC-reused it), whereas a per-pid temp orphaned by a
91
+ // hard-kill mid-write (between writeFileSync and renameSync) is never
92
+ // reused by a later process and no sweeper reclaims it. Accepted: such
93
+ // mid-write hard-kills are rare and the sidecar is tiny (matches models.js).
94
+ writeFileRestricted(this._stateFilePath, JSON.stringify(state, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
95
+ log.info(`Serialized ${state.sessions?.length ?? 0} session(s) to ${this._stateFilePath}`)
96
+ return state
97
+ }
98
+
99
+ /**
100
+ * Rotate the current state file to `.bak`. On POSIX `rename` atomically
101
+ * replaces the destination, but on Windows a pre-existing or locked `.bak`
102
+ * (antivirus / open handle) causes EPERM/EACCES/EBUSY/EEXIST. When that
103
+ * happens, remove the stale `.bak` and retry once before giving up — a
104
+ * missing rotation is acceptable (the write still proceeds) but silently
105
+ * skipping it leaves no prior-generation file to recover from.
106
+ *
107
+ * Subtlety: EPERM/EACCES/EBUSY are ambiguous — they can indicate either a
108
+ * locked *destination* (which our unlink+retry fixes) or a locked *source*
109
+ * (which our retry cannot fix). If we unlinked `.bak` on a source-locked
110
+ * error and the retry then failed, we would have silently deleted the prior
111
+ * generation for nothing. To stay crash-safe we snapshot the `.bak` bytes
112
+ * before unlinking and restore them if the retry fails, so the caller is
113
+ * never worse off than if rotation had simply been skipped.
114
+ * @private
115
+ */
116
+ _rotateToBak(mainPath, bakPath) {
117
+ try {
118
+ fs.renameSync(mainPath, bakPath)
119
+ return
120
+ } catch (err) {
121
+ if (!this._isWindows || !err || !WINDOWS_LOCK_CODES.has(err.code)) {
122
+ log.warn(`Failed to rotate state file to .bak: ${err?.message || err}`)
123
+ return
124
+ }
125
+ log.warn(`Rotation to .bak failed with ${err.code}; clearing stale .bak and retrying`)
126
+ }
127
+ // Snapshot the prior-generation .bak so we can restore it if the retry
128
+ // still fails (e.g. when the source file was actually the locked one).
129
+ let priorBak = null
130
+ try {
131
+ priorBak = fs.readFileSync(bakPath)
132
+ } catch (readErr) {
133
+ if (readErr && readErr.code !== 'ENOENT') {
134
+ log.warn(`Failed to snapshot existing .bak before retry: ${readErr.message}`)
135
+ }
136
+ }
137
+ try { fs.unlinkSync(bakPath) } catch (unlinkErr) {
138
+ if (unlinkErr && unlinkErr.code !== 'ENOENT') {
139
+ log.warn(`Failed to clear stale .bak: ${unlinkErr.message}`)
140
+ }
141
+ }
142
+ try {
143
+ fs.renameSync(mainPath, bakPath)
144
+ } catch (retryErr) {
145
+ // Still locked — give up on rotation; the primary write below will
146
+ // still proceed so the user's state is not lost. Restore the prior
147
+ // generation bytes (if any) so a recovery path remains available.
148
+ log.warn(`Retry of .bak rotation failed: ${retryErr?.message || retryErr}`)
149
+ if (priorBak !== null) {
150
+ try {
151
+ writeFileRestricted(bakPath, priorBak)
152
+ } catch (restoreErr) {
153
+ log.warn(`Failed to restore prior .bak after retry failure: ${restoreErr?.message || restoreErr}`)
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Restore session state from disk.
161
+ * @returns {object|null} The parsed state object, or null if unavailable/stale/invalid
162
+ */
163
+ restoreState() {
164
+ const mainPath = this._stateFilePath
165
+ const bakPath = this._stateFilePath + '.bak'
166
+ // If the main file is missing or unreadable, fall back to the rotated
167
+ // .bak copy (written by serializeState before every successful write).
168
+ const sourcePath = fs.existsSync(mainPath) ? mainPath : (fs.existsSync(bakPath) ? bakPath : null)
169
+ if (!sourcePath) return null
170
+
171
+ let state
172
+ try {
173
+ state = JSON.parse(fs.readFileSync(sourcePath, 'utf-8'))
174
+ } catch (err) {
175
+ log.error(`Failed to parse session state at ${sourcePath}: ${err.message}`)
176
+ // Only unlink the main file; preserve .bak as last-resort recovery
177
+ if (sourcePath === mainPath) {
178
+ try { fs.unlinkSync(mainPath) } catch {}
179
+ // Try the backup before giving up
180
+ if (fs.existsSync(bakPath)) {
181
+ try {
182
+ state = JSON.parse(fs.readFileSync(bakPath, 'utf-8'))
183
+ log.info(`Recovered session state from ${bakPath}`)
184
+ } catch (bakErr) {
185
+ log.error(`Failed to parse backup state: ${bakErr.message}`)
186
+ return null
187
+ }
188
+ } else {
189
+ return null
190
+ }
191
+ } else {
192
+ return null
193
+ }
194
+ }
195
+
196
+ if (!Array.isArray(state.sessions) || state.sessions.length === 0) {
197
+ log.info('No sessions to restore')
198
+ return null
199
+ }
200
+
201
+ // Reject stale sessions PER ENTRY (older than TTL, default 24h). A single
202
+ // whole-file `state.timestamp` check used to discard EVERY session + its
203
+ // history the moment the file aged past the TTL — a user returning after a
204
+ // weekend lost the entire list. Each entry already persists its own
205
+ // `lastActivityAt` (#5309), so filter individually and fall back to the
206
+ // file timestamp only for an entry that predates that field. (audit P2-12)
207
+ const now = Date.now()
208
+ const fresh = []
209
+ const dropped = []
210
+ for (const saved of state.sessions) {
211
+ const activityAt = (typeof saved.lastActivityAt === 'number' && saved.lastActivityAt > 0)
212
+ ? saved.lastActivityAt
213
+ : state.timestamp
214
+ if (activityAt && now - activityAt > this._stateTtlMs) {
215
+ dropped.push(saved.name || saved.id || '<unknown>')
216
+ } else {
217
+ fresh.push(saved)
218
+ }
219
+ }
220
+ if (dropped.length > 0) {
221
+ // Bound + escape the name list: session names are user-controlled
222
+ // (renameSession), so a newline-bearing name could inject log lines and
223
+ // a large drop could blow the line length. Cap to a small sample and
224
+ // JSON-stringify each so control chars are escaped. (Copilot review)
225
+ const MAX_NAMES = 10
226
+ const sample = dropped.slice(0, MAX_NAMES).map((n) => JSON.stringify(String(n)))
227
+ const more = dropped.length > MAX_NAMES ? `, …+${dropped.length - MAX_NAMES} more` : ''
228
+ log.warn(`Dropped ${dropped.length} stale session(s) (>${Math.round(this._stateTtlMs / 60000)}min since last activity): ${sample.join(', ')}${more}`)
229
+ }
230
+ if (fresh.length === 0) {
231
+ log.info('All restored sessions are stale, starting fresh')
232
+ return null
233
+ }
234
+ state.sessions = fresh
235
+ return state
236
+ }
237
+
238
+ /**
239
+ * Schedule a debounced persist. Multiple rapid calls reset the timer.
240
+ *
241
+ * #5309 (WP-0.3) — durability boundary, by design: this debounce backs
242
+ * high-frequency message-history appends only. Session-LIST mutations
243
+ * (create/destroy/rename) use flushPersist() and are never debounced, and
244
+ * every CLEAN exit path serializes immediately — SIGINT/SIGTERM (server-cli.js)
245
+ * and the supervised IPC shutdown + crash handlers (server-cli-child.js, #5308)
246
+ * all call serializeState() directly (followed by destroyAll(), which cancels
247
+ * this timer and no-ops any stray fire). So the only way to lose up to
248
+ * persistDebounceMs (2s) of
249
+ * message history is an abrupt kill that runs NO handler at all — SIGKILL,
250
+ * OOM-kill, or power loss. That window is accepted as best-effort: shrinking
251
+ * it trades constant write amplification on every token for protection against
252
+ * an unrecoverable kill we can't flush before anyway.
253
+ *
254
+ * @param {() => void} serializeFn - Function to call when the debounce fires
255
+ */
256
+ schedulePersist(serializeFn) {
257
+ clearTimeout(this._persistTimer)
258
+ this._persistTimer = setTimeout(() => {
259
+ this._persistTimer = null
260
+ try {
261
+ serializeFn()
262
+ } catch (err) {
263
+ log.error(`Failed to persist session state: ${err?.stack || err}`)
264
+ }
265
+ }, this._persistDebounceMs)
266
+ }
267
+
268
+ /**
269
+ * Cancel any pending debounced persist.
270
+ */
271
+ cancelPersist() {
272
+ clearTimeout(this._persistTimer)
273
+ this._persistTimer = null
274
+ }
275
+
276
+ /**
277
+ * Persist immediately, bypassing (and cancelling) any pending debounce.
278
+ * Used for session-list mutations that must survive an abrupt shutdown —
279
+ * callers include createSession / destroySession / renameSession, where
280
+ * losing the write would erase a user's session from the sidebar.
281
+ *
282
+ * #5701: returns whether the write succeeded so callers can surface the
283
+ * failure instead of silently losing the mutation on disk-full / locked-file
284
+ * / read-only-home conditions. (The write itself is still atomic — see
285
+ * serializeState — so a failure leaves the prior good file intact; the risk
286
+ * being signalled is the lost mutation, not corruption.)
287
+ * @param {() => void} serializeFn
288
+ * @returns {boolean} true if the write succeeded, false if it threw.
289
+ */
290
+ flushPersist(serializeFn) {
291
+ this.cancelPersist()
292
+ try {
293
+ serializeFn()
294
+ return true
295
+ } catch (err) {
296
+ log.error(`Failed to flush session state: ${err?.stack || err}`)
297
+ return false
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Clean up resources (cancel pending timer).
303
+ */
304
+ destroy() {
305
+ this.cancelPersist()
306
+ }
307
+ }
@@ -0,0 +1,166 @@
1
+ import { EventEmitter } from 'events'
2
+ import { createLogger } from './logger.js'
3
+
4
+ const log = createLogger('session-timeout')
5
+
6
+ /**
7
+ * Format milliseconds into a human-friendly duration string.
8
+ * Examples: "2 minutes", "1 hour 30 minutes", "45 seconds"
9
+ */
10
+ export function formatIdleDuration(ms) {
11
+ const totalSeconds = Math.round(ms / 1000)
12
+ if (totalSeconds < 60) return `${totalSeconds} second${totalSeconds !== 1 ? 's' : ''}`
13
+ const totalMinutes = Math.round(totalSeconds / 60)
14
+ if (totalMinutes < 60) return `${totalMinutes} minute${totalMinutes !== 1 ? 's' : ''}`
15
+ const hours = Math.floor(totalMinutes / 60)
16
+ const minutes = totalMinutes % 60
17
+ const hPart = `${hours} hour${hours !== 1 ? 's' : ''}`
18
+ return minutes > 0 ? `${hPart} ${minutes} minute${minutes !== 1 ? 's' : ''}` : hPart
19
+ }
20
+
21
+ /**
22
+ * Manages session idle timeouts independently of session lifecycle.
23
+ *
24
+ * Events emitted:
25
+ * warning { sessionId, remainingMs } — session nearing idle timeout
26
+ * timeout { sessionId, idleMs } — session has exceeded idle timeout
27
+ *
28
+ * @param {Object} options
29
+ * @param {number} options.sessionTimeoutMs — idle timeout in milliseconds
30
+ * @param {number} [options.checkIntervalMs] — how often to check (default: min(60s, timeout/4))
31
+ */
32
+ export class SessionTimeoutManager extends EventEmitter {
33
+ constructor({ sessionTimeoutMs, checkIntervalMs } = {}) {
34
+ super()
35
+ this._sessionTimeoutMs = sessionTimeoutMs || null
36
+ this._checkIntervalMs = checkIntervalMs ?? (
37
+ sessionTimeoutMs ? Math.min(60_000, Math.floor(sessionTimeoutMs / 4)) : 60_000
38
+ )
39
+ this._lastActivity = new Map() // sessionId -> timestamp
40
+ this._sessionWarned = new Set() // sessionIds that received a warning
41
+ this._timeoutCheckTimer = null
42
+ this._hasActiveViewersFn = null // (sessionId) => boolean
43
+ this._isRunningFn = null // (sessionId) => boolean
44
+ }
45
+
46
+ /**
47
+ * Set the function used to check if a session has active WebSocket viewers.
48
+ * @param {(sessionId: string) => boolean} fn
49
+ */
50
+ setActiveViewersFn(fn) {
51
+ this._hasActiveViewersFn = fn
52
+ }
53
+
54
+ /**
55
+ * Set the function used to check if a session is busy (query in progress).
56
+ * @param {(sessionId: string) => boolean} fn
57
+ */
58
+ setIsRunningFn(fn) {
59
+ this._isRunningFn = fn
60
+ }
61
+
62
+ /**
63
+ * Record activity for a session (resets idle timer).
64
+ * @param {string} sessionId
65
+ */
66
+ touchActivity(sessionId) {
67
+ this._lastActivity.set(sessionId, Date.now())
68
+ // Clear warning flag if session becomes active again
69
+ if (this._sessionWarned.has(sessionId)) {
70
+ this._sessionWarned.delete(sessionId)
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Remove a session from timeout tracking.
76
+ * @param {string} sessionId
77
+ */
78
+ removeSession(sessionId) {
79
+ this._lastActivity.delete(sessionId)
80
+ this._sessionWarned.delete(sessionId)
81
+ }
82
+
83
+ /**
84
+ * Start periodic timeout checks.
85
+ * No-op if no timeout is configured or already started.
86
+ */
87
+ start() {
88
+ if (!this._sessionTimeoutMs) return
89
+ if (this._timeoutCheckTimer) return
90
+
91
+ log.info(`Session timeout enabled: ${this._sessionTimeoutMs}ms (check every ${this._checkIntervalMs}ms)`)
92
+ this._timeoutCheckTimer = setInterval(() => {
93
+ this._checkTimeouts()
94
+ }, this._checkIntervalMs)
95
+ }
96
+
97
+ /**
98
+ * Stop periodic timeout checks.
99
+ */
100
+ stop() {
101
+ if (this._timeoutCheckTimer) {
102
+ clearInterval(this._timeoutCheckTimer)
103
+ this._timeoutCheckTimer = null
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Stop and clear all state.
109
+ */
110
+ destroy() {
111
+ this.stop()
112
+ this._lastActivity.clear()
113
+ this._sessionWarned.clear()
114
+ this._hasActiveViewersFn = null
115
+ this._isRunningFn = null
116
+ }
117
+
118
+ /**
119
+ * Check all tracked sessions for idle timeout.
120
+ * Emits 'warning' then 'timeout' events.
121
+ */
122
+ _checkTimeouts() {
123
+ if (!this._sessionTimeoutMs) return
124
+
125
+ const now = Date.now()
126
+ // Warning threshold: 2 minutes before timeout (or half the timeout, whichever is smaller)
127
+ const warningMs = Math.min(2 * 60_000, Math.floor(this._sessionTimeoutMs / 2))
128
+
129
+ const toTimeout = []
130
+
131
+ for (const [sessionId, lastActive] of this._lastActivity) {
132
+ const idleMs = now - lastActive
133
+
134
+ // Skip sessions with active viewers
135
+ if (this._hasActiveViewersFn && this._hasActiveViewersFn(sessionId)) {
136
+ this.touchActivity(sessionId) // Viewing counts as activity
137
+ continue
138
+ }
139
+
140
+ // Skip busy sessions (query in progress)
141
+ if (this._isRunningFn && this._isRunningFn(sessionId)) {
142
+ this.touchActivity(sessionId)
143
+ continue
144
+ }
145
+
146
+ // Timeout fully elapsed — destroy
147
+ if (idleMs >= this._sessionTimeoutMs) {
148
+ toTimeout.push({ sessionId, idleMs })
149
+ continue
150
+ }
151
+
152
+ // Warning threshold reached
153
+ if (!this._sessionWarned.has(sessionId) && idleMs >= this._sessionTimeoutMs - warningMs) {
154
+ const remainingMs = Math.max(0, this._sessionTimeoutMs - idleMs)
155
+ this._sessionWarned.add(sessionId)
156
+ this.emit('warning', { sessionId, remainingMs })
157
+ }
158
+ }
159
+
160
+ // Emit timeouts outside iteration loop to avoid Map mutation issues
161
+ for (const { sessionId, idleMs } of toTimeout) {
162
+ this.emit('timeout', { sessionId, idleMs })
163
+ // Don't remove here — let the caller (SessionManager) handle cleanup
164
+ }
165
+ }
166
+ }
@@ -0,0 +1,83 @@
1
+ // session-token-store.js — persist paired session tokens across daemon restarts
2
+ // (#6598). Without this, PairingManager._sessionTokens is in-memory only, so any
3
+ // restart (supervisor auto-restart, update, crash, reboot) wipes every paired
4
+ // device's token and forces a re-pair.
5
+ //
6
+ // The store is encrypted at rest with the shared credential cipher (a random data
7
+ // key in the OS keychain) — see credential-cipher.js — and written 0600 owner-only.
8
+ // Where no keychain is available (Windows, headless Linux without secret-tool) it
9
+ // falls back to 0600 plaintext, matching the credential store's posture.
10
+ //
11
+ // PairingManager stays filesystem-agnostic: it takes this as an injected
12
+ // { load, save } adapter, so tests can drive it with an in-memory fake.
13
+ import { readFileSync, statSync, existsSync, mkdirSync } from 'fs'
14
+ import { join } from 'path'
15
+ import { writeFileRestricted } from './platform.js'
16
+ import { getOrCreateMasterKey, encryptJson, decryptEnvelope, isEncryptedEnvelope } from './credential-cipher.js'
17
+ import * as realKeychain from './keychain.js'
18
+ import { createLogger } from './logger.js'
19
+
20
+ const log = createLogger('session-token-store')
21
+ const STORE_FILE = 'session-tokens.json'
22
+
23
+ /**
24
+ * Build a persistence adapter for the session-token map.
25
+ *
26
+ * @param {object} opts
27
+ * @param {string} opts.dir - directory to hold the store (e.g. `~/.chroxy`).
28
+ * @param {object} [opts.keychain] - keychain module (injectable for tests).
29
+ * @returns {{ load: () => Array<[string, object]>, save: (entries: Array<[string, object]>) => void }}
30
+ * `entries` is the `[token, meta]` pair list from the PairingManager map.
31
+ */
32
+ export function createSessionTokenStore({ dir, keychain = realKeychain } = {}) {
33
+ const file = join(dir, STORE_FILE)
34
+
35
+ return {
36
+ load() {
37
+ try {
38
+ if (!existsSync(file)) return []
39
+ // Enforce owner-only 0600 (POSIX) — same boundary as the credential store.
40
+ // A world/group-readable token file is refused rather than trusted.
41
+ if (process.platform !== 'win32') {
42
+ const perms = statSync(file).mode & 0o777
43
+ if (perms !== 0o600) {
44
+ log.warn(`${file} has mode ${perms.toString(8).padStart(3, '0')}; refusing to read (must be 0600) — devices will re-pair`)
45
+ return []
46
+ }
47
+ }
48
+ const parsed = JSON.parse(readFileSync(file, 'utf8'))
49
+ if (isEncryptedEnvelope(parsed)) {
50
+ const key = getOrCreateMasterKey(keychain)
51
+ if (!key) {
52
+ log.warn('session-token store is encrypted but no keychain key is available — devices will re-pair')
53
+ return []
54
+ }
55
+ const data = decryptEnvelope(parsed, key)
56
+ return Array.isArray(data?.entries) ? data.entries : []
57
+ }
58
+ // Plaintext fallback (no-keychain host).
59
+ return Array.isArray(parsed?.entries) ? parsed.entries : []
60
+ } catch (err) {
61
+ // A missing / corrupt / undecryptable store is not fatal: the worst case
62
+ // is that devices re-pair (the pre-#6598 behaviour). Never throw into the
63
+ // auth path.
64
+ log.warn(`could not load persisted session tokens (${err.message}) — devices will re-pair`)
65
+ return []
66
+ }
67
+ },
68
+
69
+ save(entries) {
70
+ try {
71
+ mkdirSync(dir, { recursive: true })
72
+ const payload = { v: 1, entries }
73
+ const key = getOrCreateMasterKey(keychain)
74
+ const body = key ? JSON.stringify(encryptJson(payload, key)) : JSON.stringify(payload)
75
+ writeFileRestricted(file, body)
76
+ } catch (err) {
77
+ // Persistence is best-effort: a failed write just means a restart may
78
+ // require re-pairing. Don't let it break token issuance.
79
+ log.warn(`could not persist session tokens (${err.message})`)
80
+ }
81
+ },
82
+ }
83
+ }
@@ -0,0 +1,45 @@
1
+ import { homedir } from 'os'
2
+ import { join } from 'path'
3
+ import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs'
4
+ import { writeFileRestricted } from './platform.js'
5
+
6
+ // #6277 — discovery for the host-local user-shell approval listener.
7
+ //
8
+ // The approval API runs on a SEPARATE HTTP server bound to 127.0.0.1 on an
9
+ // ephemeral port that the Cloudflare tunnel never forwards (cloudflared only
10
+ // proxies the main port). That separate, never-tunnelled listener is what makes
11
+ // the approval channel genuinely host-local — a main-port loopback check is
12
+ // defeated because tunnel traffic arrives as 127.0.0.1 via cloudflared.
13
+ //
14
+ // The port is only known once the listener binds (after the supervisor already
15
+ // wrote connection.json), so it lives in its OWN 0600 file here rather than in
16
+ // connection.json. The `chroxy shell approve` CLI reads this for the port and
17
+ // connection.json for the primary token.
18
+
19
+ function getConfigDir() {
20
+ return process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
21
+ }
22
+
23
+ export function getShellApprovalInfoPath() {
24
+ return join(getConfigDir(), 'shell-approval.json')
25
+ }
26
+
27
+ export function writeShellApprovalInfo(info) {
28
+ const dir = getConfigDir()
29
+ mkdirSync(dir, { recursive: true })
30
+ writeFileRestricted(getShellApprovalInfoPath(), JSON.stringify(info, null, 2))
31
+ }
32
+
33
+ export function readShellApprovalInfo() {
34
+ const p = getShellApprovalInfoPath()
35
+ if (!existsSync(p)) return null
36
+ try {
37
+ return JSON.parse(readFileSync(p, 'utf-8'))
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ export function removeShellApprovalInfo() {
44
+ try { unlinkSync(getShellApprovalInfoPath()) } catch { /* already gone */ }
45
+ }