@chroxy/server 0.11.0 → 0.11.11

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 (386) hide show
  1. package/CONFIG.md +206 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +958 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +304 -0
  14. package/src/agent-control/client.js +1645 -0
  15. package/src/agent-control/events.js +551 -0
  16. package/src/agent-control/local-connection.js +293 -0
  17. package/src/agent-control/mcp-server.js +547 -0
  18. package/src/anthropic-compatible-config.js +30 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-gemini-shim.js +444 -0
  21. package/src/anthropic-gemini-translate.js +1030 -0
  22. package/src/anthropic-openai-shim.js +0 -1
  23. package/src/archive-continuation.js +164 -0
  24. package/src/assistant-response.js +24 -0
  25. package/src/auth-probes.js +120 -13
  26. package/src/background-shell-tracker.js +27 -0
  27. package/src/base-session.js +1520 -36
  28. package/src/bearer-recheck.js +49 -0
  29. package/src/billing-budget.js +19 -0
  30. package/src/billing-class.js +40 -7
  31. package/src/binary-provenance-trust.js +11 -5
  32. package/src/bound-client-policy.js +291 -0
  33. package/src/built-in-tools/bash-exec.js +46 -7
  34. package/src/built-in-tools/file-ops.js +69 -5
  35. package/src/built-in-tools/tool-transforms.js +1113 -13
  36. package/src/byok-compose-state.js +6 -9
  37. package/src/byok-credentials.js +2 -3
  38. package/src/byok-mcp-client.js +92 -7
  39. package/src/byok-mcp-config.js +633 -122
  40. package/src/byok-mcp-fleet.js +49 -7
  41. package/src/byok-mcp-oauth-store.js +18 -16
  42. package/src/byok-mcp-trust.js +37 -23
  43. package/src/byok-session.js +707 -179
  44. package/src/byok-tool-executor.js +2742 -26
  45. package/src/byok-tools.js +9 -2
  46. package/src/channels/chroxy-channel-server.js +2 -3
  47. package/src/checkpoint-manager.js +64 -46
  48. package/src/claude-channel-session.js +16 -10
  49. package/src/claude-model-catalog.js +131 -16
  50. package/src/claude-model-refresh.js +385 -0
  51. package/src/claude-model-request.js +103 -0
  52. package/src/claude-setting-sources.js +74 -0
  53. package/src/claude-stream-parser.js +53 -3
  54. package/src/claude-tui/diagnostic-tail.js +83 -0
  55. package/src/claude-tui/form-driver.js +44 -7
  56. package/src/claude-tui/model-error.js +41 -0
  57. package/src/claude-tui/pty-driver.js +215 -88
  58. package/src/claude-tui/sanitize-question-payload.js +109 -0
  59. package/src/claude-tui/usage-limit.js +239 -0
  60. package/src/claude-tui-session.js +3563 -284
  61. package/src/claude-tui-tool-response.js +300 -0
  62. package/src/cli/agent-cmd.js +236 -0
  63. package/src/cli/agent-control-cmd.js +65 -0
  64. package/src/cli/config-cmd.js +4 -4
  65. package/src/cli/config-dir-cmd.js +234 -0
  66. package/src/cli/connection-state.js +54 -0
  67. package/src/cli/deploy-cmd.js +45 -10
  68. package/src/cli/doctor-cmd.js +7 -3
  69. package/src/cli/freshness-cmd.js +53 -0
  70. package/src/cli/init-cmd.js +15 -16
  71. package/src/cli/pages-cmd.js +6 -4
  72. package/src/cli/pair-code-cmd.js +7 -6
  73. package/src/cli/pair-discord-cmd.js +7 -6
  74. package/src/cli/providers-cmd.js +3 -3
  75. package/src/cli/schedule-cmd.js +91 -40
  76. package/src/cli/server-cmd.js +54 -1
  77. package/src/cli/service-cmd.js +33 -10
  78. package/src/cli/session-cmd.js +227 -74
  79. package/src/cli/shared.js +162 -11
  80. package/src/cli/shell-cmd.js +7 -4
  81. package/src/cli/status-cmd.js +19 -5
  82. package/src/cli/tokens-cmd.js +4 -5
  83. package/src/cli/tunnel-cmd.js +255 -24
  84. package/src/cli/worktree-gc-cmd.js +2 -2
  85. package/src/cli-session.js +1250 -126
  86. package/src/cli.js +8 -0
  87. package/src/codex-app-server-client.js +36 -3
  88. package/src/codex-app-server-session.js +1517 -81
  89. package/src/codex-bundled-client.js +66 -0
  90. package/src/codex-error-text.js +114 -0
  91. package/src/codex-model-catalog.js +548 -0
  92. package/src/codex-model-rejections.js +87 -0
  93. package/src/codex-native-resume.js +104 -0
  94. package/src/codex-protocol-capabilities.js +188 -0
  95. package/src/codex-session.js +450 -27
  96. package/src/config-dir-migration.js +449 -0
  97. package/src/config-dir.js +108 -0
  98. package/src/config.js +306 -26
  99. package/src/connection-authority.js +48 -0
  100. package/src/connection-info.js +78 -23
  101. package/src/connection-locality.js +60 -0
  102. package/src/container-liveness-monitor.js +189 -0
  103. package/src/continuation-metadata-worker.js +17 -0
  104. package/src/continuations.js +227 -0
  105. package/src/control-room/host-prune.js +5 -0
  106. package/src/control-room/integrations.js +7 -20
  107. package/src/control-room/skills-inventory.js +2 -2
  108. package/src/conversation-scanner.js +42 -39
  109. package/src/conversation-scope.js +59 -39
  110. package/src/conversation-search.js +28 -39
  111. package/src/credential-store.js +23 -19
  112. package/src/daemon-commit.js +92 -0
  113. package/src/daemon-idle-state.js +171 -0
  114. package/src/daemon-update-status.js +314 -0
  115. package/src/dashboard-build.js +70 -0
  116. package/src/declared-status.js +90 -0
  117. package/src/deepseek-credentials.js +2 -3
  118. package/src/dev-preview.js +170 -182
  119. package/src/device-preferences.js +2 -2
  120. package/src/diff-parser.js +87 -0
  121. package/src/discord-credentials.js +2 -3
  122. package/src/docker-byok-pool.js +3 -1
  123. package/src/docker-byok-session.js +678 -78
  124. package/src/docker-image-allowlist.js +23 -1
  125. package/src/docker-sdk-session.js +172 -3
  126. package/src/docker-session.js +294 -11
  127. package/src/doctor.js +781 -64
  128. package/src/durable-write.js +35 -0
  129. package/src/edited-input.js +264 -0
  130. package/src/environment-manager.js +175 -36
  131. package/src/environments/authority.js +101 -0
  132. package/src/environments/backends/container-claude-spawn.js +94 -0
  133. package/src/environments/backends/docker.js +31 -10
  134. package/src/environments/backends/k8s.js +49 -24
  135. package/src/environments/destroy-with-sessions.js +142 -0
  136. package/src/event-ingest.js +118 -13
  137. package/src/event-normalizer.js +186 -235
  138. package/src/folder-trust-wire.js +137 -0
  139. package/src/folder-trust-worker.js +17 -0
  140. package/src/folder-trust.js +1572 -0
  141. package/src/freshness/activity-meter.js +101 -0
  142. package/src/freshness/adapter.js +199 -0
  143. package/src/freshness/checks.js +239 -0
  144. package/src/freshness/config.js +98 -0
  145. package/src/freshness/core.js +185 -0
  146. package/src/freshness/derive.js +680 -0
  147. package/src/freshness/exchange.js +305 -0
  148. package/src/freshness/file-ledger.js +400 -0
  149. package/src/freshness/grade.js +81 -0
  150. package/src/freshness/hash.js +45 -0
  151. package/src/freshness/inbox.js +163 -0
  152. package/src/freshness/index.js +20 -0
  153. package/src/freshness/investigation.js +474 -0
  154. package/src/freshness/keys.js +177 -0
  155. package/src/freshness/ledger.js +122 -0
  156. package/src/freshness/outbox.js +131 -0
  157. package/src/freshness/policy.js +599 -0
  158. package/src/freshness/queue.js +843 -0
  159. package/src/freshness/read-errors.js +23 -0
  160. package/src/freshness/render.js +153 -0
  161. package/src/freshness/runtime.js +113 -0
  162. package/src/freshness/session-registry-adapter.js +161 -0
  163. package/src/freshness/state-file-adapter.js +167 -0
  164. package/src/freshness-runner/build-info.js +139 -0
  165. package/src/freshness-runner/cli.js +105 -0
  166. package/src/freshness-runner/run-tick.js +109 -0
  167. package/src/freshness-runner/stamp.js +57 -0
  168. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  169. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  170. package/src/freshness-sources/index.js +8 -0
  171. package/src/gemini-byok-session.js +292 -0
  172. package/src/gemini-credentials.js +67 -0
  173. package/src/gemini-key-safety.js +246 -0
  174. package/src/gemini-models.js +386 -0
  175. package/src/gemini-session.js +81 -5
  176. package/src/handler-utils.js +540 -80
  177. package/src/handlers/checkpoint-handlers.js +47 -4
  178. package/src/handlers/control-room-handlers.js +51 -11
  179. package/src/handlers/conversation-handlers.js +469 -56
  180. package/src/handlers/daemon-update-handlers.js +81 -0
  181. package/src/handlers/evaluator-handlers.js +14 -1
  182. package/src/handlers/feature-handlers.js +186 -69
  183. package/src/handlers/file-handlers.js +57 -13
  184. package/src/handlers/folder-trust-handlers.js +90 -0
  185. package/src/handlers/input-handlers.js +714 -48
  186. package/src/handlers/orchestration-handlers.js +3 -3
  187. package/src/handlers/principal-admin-handlers.js +229 -0
  188. package/src/handlers/principal-handlers.js +262 -0
  189. package/src/handlers/scheduler-handlers.js +92 -18
  190. package/src/handlers/session-handlers.js +551 -20
  191. package/src/handlers/session-pr-status-handlers.js +283 -0
  192. package/src/handlers/session-pr-threads-handlers.js +247 -0
  193. package/src/handlers/settings-handlers.js +372 -50
  194. package/src/handlers/skills-handlers.js +20 -4
  195. package/src/handlers/summarize-handlers.js +32 -1
  196. package/src/handlers/survey-throttle.js +380 -0
  197. package/src/health-proof.js +40 -0
  198. package/src/history-page.js +112 -0
  199. package/src/http-routes.js +127 -8
  200. package/src/ide/search.js +24 -6
  201. package/src/ide/symbols.js +20 -6
  202. package/src/input-context.js +117 -0
  203. package/src/instruction-policy-compiler.js +229 -0
  204. package/src/instruction-policy.js +250 -0
  205. package/src/jsonl-reader.js +378 -91
  206. package/src/jsonl-subprocess-session.js +96 -9
  207. package/src/keychain.js +1 -1
  208. package/src/logger.js +166 -30
  209. package/src/mailbox-route.js +113 -22
  210. package/src/message-wire.js +386 -0
  211. package/src/model-discovery.js +43 -3
  212. package/src/models.js +1276 -174
  213. package/src/notification-prefs.js +27 -4
  214. package/src/notifications/discord-billing-sink.js +22 -5
  215. package/src/notifications/discord-ci-sink.js +243 -0
  216. package/src/notifications/discord-webhook-client.js +71 -0
  217. package/src/notifications/discord-webhook-sink.js +64 -23
  218. package/src/notifications/expo-push-sink.js +85 -6
  219. package/src/notifications/ready-body.js +16 -5
  220. package/src/ollama-session.js +34 -2
  221. package/src/orchestration/build-manager.js +9 -2
  222. package/src/orchestration/git-ops.js +41 -7
  223. package/src/orchestration/orchestration-manager.js +112 -36
  224. package/src/orchestration/permission-gate.js +17 -2
  225. package/src/orchestration/run-model.js +2 -1
  226. package/src/orchestration/run-record.js +11 -0
  227. package/src/orchestration/turn-driver.js +185 -43
  228. package/src/orphan-reaper.js +470 -0
  229. package/src/outgoing-policy.js +189 -0
  230. package/src/pairing.js +92 -13
  231. package/src/path-hash-trust-ledger.js +642 -25
  232. package/src/permission-deadlines.js +82 -0
  233. package/src/permission-floor.js +1410 -43
  234. package/src/permission-hook.js +180 -69
  235. package/src/permission-manager.js +737 -89
  236. package/src/permission-mode-support.js +35 -0
  237. package/src/permission-resolved-by.js +89 -0
  238. package/src/permission-resolver.js +126 -8
  239. package/src/permission-scope.js +43 -0
  240. package/src/platform.js +315 -47
  241. package/src/preview-ingress.js +54 -0
  242. package/src/preview-target.js +213 -0
  243. package/src/principal-audit.js +189 -0
  244. package/src/principal-binding.js +25 -0
  245. package/src/principal-brakes.js +21 -0
  246. package/src/principal-effect.js +101 -0
  247. package/src/principal-journal.js +905 -0
  248. package/src/principal-kill-switch.js +183 -0
  249. package/src/principal-label.js +5 -0
  250. package/src/principal-pending-permissions.js +177 -0
  251. package/src/principal-policy.js +1094 -0
  252. package/src/principal-sessions-snapshot.js +208 -0
  253. package/src/principal-store.js +488 -0
  254. package/src/principal-subscriptions.js +283 -0
  255. package/src/prompt-evaluator.js +34 -4
  256. package/src/provider-customization.js +180 -0
  257. package/src/providers.js +209 -4
  258. package/src/push.js +30 -4
  259. package/src/question-route-map.js +130 -0
  260. package/src/redaction.js +531 -20
  261. package/src/roster-broadcast.js +186 -0
  262. package/src/scheduled-task-store.js +330 -26
  263. package/src/scheduler.js +368 -11
  264. package/src/sdk-session.js +2114 -188
  265. package/src/server-cli/preview-shutdown.js +22 -0
  266. package/src/server-cli/push-notification-handler.js +17 -3
  267. package/src/server-cli/server-orchestrator.js +28 -5
  268. package/src/server-cli-child.js +33 -18
  269. package/src/server-cli.js +553 -38
  270. package/src/server-identity.js +15 -11
  271. package/src/service.js +396 -25
  272. package/src/session-archive-limits.js +15 -0
  273. package/src/session-archive.js +1029 -0
  274. package/src/session-busy-state.js +72 -0
  275. package/src/session-ci-watcher.js +1099 -0
  276. package/src/session-context.js +7 -2
  277. package/src/session-manager.js +4062 -312
  278. package/src/session-message-history.js +841 -16
  279. package/src/session-name-allocator.js +685 -0
  280. package/src/session-pr-status.js +654 -0
  281. package/src/session-pr-threads.js +271 -0
  282. package/src/session-preset-trust.js +3 -3
  283. package/src/session-preset.js +10 -5
  284. package/src/session-state-persistence.js +94 -17
  285. package/src/session-timeout-manager.js +20 -0
  286. package/src/session-token-store.js +17 -8
  287. package/src/session-wake.js +240 -0
  288. package/src/shell-approval-info.js +2 -2
  289. package/src/shell-approval-store.js +3 -1
  290. package/src/skills-loader.js +7 -4
  291. package/src/skills-manager.js +2 -2
  292. package/src/skills-trust.js +95 -13
  293. package/src/skills-usage.js +2 -3
  294. package/src/snapshots-store.js +2 -3
  295. package/src/statusline.js +100 -29
  296. package/src/summarize-session.js +53 -4
  297. package/src/supervisor.js +22 -11
  298. package/src/sweep-stale-provider-dirs.js +95 -0
  299. package/src/thinking-level-wire.js +39 -0
  300. package/src/thinking-stream.js +179 -0
  301. package/src/tool-result.js +61 -0
  302. package/src/transcript-sources.js +109 -0
  303. package/src/transcript-tasks.js +372 -25
  304. package/src/trusted-file-read.js +302 -0
  305. package/src/tunnel/base.js +0 -8
  306. package/src/tunnel/cloudflare.js +34 -31
  307. package/src/tunnel/index.js +9 -0
  308. package/src/tunnel/preview.js +64 -0
  309. package/src/turn-outcome.js +140 -0
  310. package/src/usage-normalize.js +9 -5
  311. package/src/user-shell-session.js +59 -5
  312. package/src/utils/agent-sdk-version.js +107 -0
  313. package/src/utils/argv-safety.js +770 -0
  314. package/src/utils/auth-cause.js +60 -0
  315. package/src/utils/binary-package-manifest.js +639 -0
  316. package/src/utils/binary-version.js +224 -0
  317. package/src/utils/bounded-regex-worker.js +29 -0
  318. package/src/utils/bounded-regex.js +162 -0
  319. package/src/utils/claude-binary.js +43 -0
  320. package/src/utils/claude-config-dir.js +245 -0
  321. package/src/utils/claude-login-command.js +16 -0
  322. package/src/utils/claude-native-route.js +81 -0
  323. package/src/utils/componentwise-resolver.js +133 -37
  324. package/src/utils/deploy-control-files.js +87 -0
  325. package/src/utils/exec-failure-reason.js +21 -0
  326. package/src/utils/git-repo.js +42 -0
  327. package/src/utils/is-entry-point.js +137 -0
  328. package/src/utils/node-pty-probe.js +95 -0
  329. package/src/utils/node-pty-support.js +118 -0
  330. package/src/utils/opened-file-path.js +167 -0
  331. package/src/utils/path-containment.js +165 -0
  332. package/src/utils/permission-mode-sidecar.js +51 -0
  333. package/src/utils/pid-liveness.js +47 -0
  334. package/src/utils/preflight.js +360 -16
  335. package/src/utils/read-limiter.js +217 -0
  336. package/src/utils/regular-file.js +375 -0
  337. package/src/utils/safe-regex.js +113 -0
  338. package/src/utils/small-file.js +129 -0
  339. package/src/utils/spawn-env.js +189 -4
  340. package/src/utils/stale-session-dirs.js +182 -0
  341. package/src/utils/stat-identity.js +43 -0
  342. package/src/utils/verify-provenance.js +406 -13
  343. package/src/web-task-manager.js +297 -16
  344. package/src/worktree-gc.js +202 -6
  345. package/src/ws-auth.js +163 -31
  346. package/src/ws-broadcaster.js +49 -5
  347. package/src/ws-client-manager.js +24 -1
  348. package/src/ws-client-sender.js +7 -0
  349. package/src/ws-file-ops/browser.js +363 -58
  350. package/src/ws-file-ops/common.js +320 -14
  351. package/src/ws-file-ops/git.js +395 -42
  352. package/src/ws-file-ops/index.js +2 -0
  353. package/src/ws-file-ops/memory.js +137 -35
  354. package/src/ws-file-ops/open-nofollow.js +354 -0
  355. package/src/ws-file-ops/reader.js +571 -113
  356. package/src/ws-forwarding.js +349 -39
  357. package/src/ws-handler-context.js +88 -2
  358. package/src/ws-history.js +1010 -175
  359. package/src/ws-message-handlers.js +25 -1
  360. package/src/ws-permissions.js +307 -37
  361. package/src/ws-schemas.js +5 -0
  362. package/src/ws-server.js +885 -98
  363. package/sidecar/node_modules/.package-lock.json +0 -29
  364. package/sidecar/node_modules/ws/LICENSE +0 -20
  365. package/sidecar/node_modules/ws/README.md +0 -548
  366. package/sidecar/node_modules/ws/browser.js +0 -8
  367. package/sidecar/node_modules/ws/index.js +0 -22
  368. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  369. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  370. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  371. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  372. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  373. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  374. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  375. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  376. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  377. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  378. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  379. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  380. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  381. package/sidecar/node_modules/ws/package.json +0 -70
  382. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  383. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  384. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  385. package/src/dashboard-next/dist/index.html +0 -13
  386. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
@@ -1,40 +1,95 @@
1
- import { homedir } from 'os'
2
1
  import { join } from 'path'
3
2
  import { existsSync, readFileSync, unlinkSync, mkdirSync } from 'fs'
4
3
  import { writeFileRestricted } from './platform.js'
5
-
6
- function getConfigDir() {
7
- return process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
8
- }
4
+ import { configDir, configPath } from './config-dir.js'
5
+ import { probePidLiveness, PID_ALIVE, PID_DEAD } from './utils/pid-liveness.js'
9
6
 
10
7
  export function getConnectionInfoPath() {
11
- return join(getConfigDir(), 'connection.json')
8
+ return configPath('connection.json')
12
9
  }
13
10
 
14
11
  export function writeConnectionInfo(info) {
15
- const configDir = getConfigDir()
16
- mkdirSync(configDir, { recursive: true })
17
- writeFileRestricted(join(configDir, 'connection.json'), JSON.stringify(info, null, 2))
12
+ const dir = configDir()
13
+ mkdirSync(dir, { recursive: true })
14
+ writeFileRestricted(join(dir, 'connection.json'), JSON.stringify(info, null, 2))
15
+ }
16
+
17
+ /**
18
+ * The daemon's discovery record, returned ONLY when its recorded PID is verified
19
+ * alive (#9074). Every other outcome returns null:
20
+ * - no file, or an unreadable file;
21
+ * - a record with a missing or malformed pid;
22
+ * - a dead pid (ESRCH);
23
+ * - an unverified pid (EPERM under a sandbox, or any other probe error; see
24
+ * utils/pid-liveness.js).
25
+ *
26
+ * Callers use the record to send the daemon's primary bearer to a loopback port, so
27
+ * "could not verify" fails closed exactly like "not running". "Alive" is the probe's
28
+ * claim only: some process with that PID exists. It is not proof that the process
29
+ * is the daemon, or that the daemon listens on the recorded port.
30
+ *
31
+ * Deletion: before #9074 this read deleted the record on ANY probe error. The existing
32
+ * cleanup for a pid proven dead (ESRCH) is retained. Every other failure (EPERM, any
33
+ * other probe error, a missing or malformed pid) now preserves the record: "could not
34
+ * verify" is not "dead".
35
+ *
36
+ * Known, pre-existing race (documented, not introduced here): a reader can probe the
37
+ * old record's dead PID, a restarting daemon can then write its own record, and this
38
+ * unlink removes the new one. What this call does in that case: it returns null and
39
+ * transmits no credential. No claim is made here about what callers do next. Until
40
+ * the daemon writes its record again, readers find none.
41
+ *
42
+ * This reader still collapses "unverified" and "not running" into null. A caller that
43
+ * must word them differently uses `readConnectionState()` below (#9229).
44
+ *
45
+ * @param {{ probePidLiveness?: (pid: unknown) => 'alive' | 'dead' | 'unverified' }} [deps]
46
+ * @returns {object|null}
47
+ */
48
+ export function readConnectionInfo(deps = {}) {
49
+ return readConnectionState(deps).info
18
50
  }
19
51
 
20
- export function readConnectionInfo() {
52
+ /**
53
+ * Why `readConnectionState()` returned no record (#9229). `info` is non-null only
54
+ * for `CONNECTION_ALIVE`.
55
+ */
56
+ export const CONNECTION_ALIVE = 'alive'
57
+ /** No file, an unreadable or unparseable file, or a non-object record. */
58
+ export const CONNECTION_NO_RECORD = 'no_record'
59
+ /** The recorded pid is proven gone (ESRCH); the stale record was removed. */
60
+ export const CONNECTION_DEAD = 'dead'
61
+ /** Liveness could not be established (EPERM, other probe error, missing/malformed pid). The record is kept. */
62
+ export const CONNECTION_LIVENESS_UNVERIFIED = 'liveness_unverified'
63
+
64
+ /**
65
+ * `readConnectionInfo()` plus the reason, so a CLI can word "no daemon" and "could not
66
+ * verify the daemon is running" differently. This is the ONE implementation:
67
+ * `readConnectionInfo()` returns `.info` of this, so the two cannot disagree about
68
+ * when a record (and with it the bearer token) is handed out. `info` is non-null ONLY
69
+ * when the probe says `alive`; `dead` and `unverified` both carry `info: null`.
70
+ * Deletion is unchanged: only `dead` unlinks.
71
+ *
72
+ * @param {{ probePidLiveness?: (pid: unknown) => 'alive' | 'dead' | 'unverified' }} [deps]
73
+ * @returns {{ info: object, reason: 'alive' } | { info: null, reason: 'no_record'|'dead'|'liveness_unverified' }}
74
+ */
75
+ export function readConnectionState(deps = {}) {
76
+ const probe = typeof deps.probePidLiveness === 'function' ? deps.probePidLiveness : probePidLiveness
21
77
  const connFile = getConnectionInfoPath()
22
- if (!existsSync(connFile)) return null
78
+ if (!existsSync(connFile)) return { info: null, reason: CONNECTION_NO_RECORD }
79
+ let info
23
80
  try {
24
- const info = JSON.parse(readFileSync(connFile, 'utf-8'))
25
- if (info && info.pid) {
26
- try {
27
- process.kill(info.pid, 0) // signal 0 = existence check
28
- } catch {
29
- // Process is dead — stale file
30
- removeConnectionInfo()
31
- return null
32
- }
33
- }
34
- return info
81
+ info = JSON.parse(readFileSync(connFile, 'utf-8'))
35
82
  } catch {
36
- return null
83
+ return { info: null, reason: CONNECTION_NO_RECORD }
84
+ }
85
+ if (!info || typeof info !== 'object') return { info: null, reason: CONNECTION_NO_RECORD }
86
+ const liveness = probe(info.pid)
87
+ if (liveness === PID_DEAD) {
88
+ removeConnectionInfo() // the existing ESRCH cleanup, retained (see above)
89
+ return { info: null, reason: CONNECTION_DEAD }
37
90
  }
91
+ if (liveness === PID_ALIVE) return { info, reason: CONNECTION_ALIVE }
92
+ return { info: null, reason: CONNECTION_LIVENESS_UNVERIFIED }
38
93
  }
39
94
 
40
95
  export function removeConnectionInfo() {
@@ -21,6 +21,7 @@
21
21
  * this classification — it's a pure transport-efficiency hint.
22
22
  */
23
23
 
24
+ import { isIPv4 } from 'node:net'
24
25
  import { isLoopbackHost } from './bind-host.js'
25
26
  import { isPrivateOrSpecialIp } from './ssrf-guard.js'
26
27
 
@@ -53,3 +54,62 @@ export function isLocalOrLanPeer(req) {
53
54
  if (isPrivateOrSpecialIp(socketIp)) return true
54
55
  return false
55
56
  }
57
+
58
+ /**
59
+ * Strict loopback parse for AUTHORIZATION use. Not `isLoopbackHost`, which is a
60
+ * bind-host helper that accepts anything starting `::ffff:7f` — so
61
+ * `::ffff:7f00:1:2`, which is not an address at all, would pass. Accepts exactly:
62
+ * - a dotted IPv4 literal in 127.0.0.0/8,
63
+ * - `::1`,
64
+ * - an IPv4-mapped `::ffff:a.b.c.d` whose dotted part is in 127.0.0.0/8.
65
+ */
66
+ function isStrictLoopbackAddress(ip) {
67
+ const addr = ip.toLowerCase()
68
+ if (isIPv4(addr)) return addr.split('.')[0] === '127'
69
+ if (addr === '::1') return true
70
+ const mapped = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(addr)
71
+ return !!mapped && isIPv4(mapped[1]) && mapped[1].split('.')[0] === '127'
72
+ }
73
+
74
+ /**
75
+ * Any header a tunnel, CDN or reverse proxy leaves behind. Wider than
76
+ * `hasProxyHeaders` on purpose: Cloudflare can strip the visitor-IP headers
77
+ * (a managed transform), and then `cf-connecting-ip` is absent on a request
78
+ * that very much came through the tunnel. What survives is the rest of the
79
+ * family — `cf-ray`, `cf-visitor`, `cdn-loop`, `x-forwarded-proto`. Presence of
80
+ * the NAME is the test; the value is never trusted.
81
+ */
82
+ function hasAnyProxyHint(headers) {
83
+ if (!headers) return false
84
+ for (const name of Object.keys(headers)) {
85
+ const n = name.toLowerCase()
86
+ if (n.startsWith('cf-') || n.startsWith('cdn-loop') || n.startsWith('forwarded') ||
87
+ n.startsWith('x-forwarded-') || n === 'x-real-ip') return true
88
+ }
89
+ return false
90
+ }
91
+
92
+ /**
93
+ * Is this request a loopback peer that carries no sign of a proxy? (#8324)
94
+ *
95
+ * It does NOT prove direct local origin. It rejects a request whose socket is
96
+ * not loopback, and any request carrying a proxy-family header (see
97
+ * `hasAnyProxyHint`); a proxy that strips EVERY such header, or a local process
98
+ * that forwards traffic for a remote party without adding one, passes it. So it
99
+ * is defence in depth for the local-only `/api/daemon/idle` probe, and the
100
+ * primary bearer token is the authority.
101
+ *
102
+ * Stricter than `isLocalOrLanPeer`, which is a transport-efficiency hint with
103
+ * no security property riding on it: the socket address is parsed strictly, and
104
+ * ANY proxy-family header disqualifies the request. cloudflared connects to the
105
+ * daemon from 127.0.0.1, so the socket address alone proves nothing.
106
+ *
107
+ * @param {object} req - Node IncomingMessage.
108
+ * @returns {boolean}
109
+ */
110
+ export function isLoopbackPeer(req) {
111
+ const socketIp = req?.socket?.remoteAddress
112
+ if (typeof socketIp !== 'string' || socketIp.length === 0) return false
113
+ if (hasAnyProxyHint(req.headers)) return false
114
+ return isStrictLoopbackAddress(socketIp)
115
+ }
@@ -0,0 +1,189 @@
1
+ import { createLogger } from './logger.js'
2
+
3
+ const log = createLogger('container-liveness')
4
+
5
+ /**
6
+ * #7601 — how often the proactive poll inspects each live containerized session's
7
+ * container. The reactive #7599 paths already catch a vanish that happens
8
+ * DURING a turn (SDK query reject) or that closes a live exec child (CLI); this
9
+ * poll is the ONLY thing that catches an IDLE session whose container was stopped
10
+ * EXTERNALLY (a plain `docker stop`, which emits no chroxy event), and it is what
11
+ * gives a no-long-lived-process session (docker-byok, #7600) any idle
12
+ * detection at all. 30s balances "surface before the user's
13
+ * next turn" against the cost of one `docker inspect` per distinct container.
14
+ */
15
+ export const DEFAULT_LIVENESS_INTERVAL_MS = 30_000
16
+
17
+ /**
18
+ * #7620 — describe an out-of-contract verdict for the log WITHOUT trusting it.
19
+ *
20
+ * The verdict comes from the very injection seam the guard below exists to
21
+ * distrust, so a bare `JSON.stringify` is not safe: it THROWS on a circular
22
+ * object (the raw `docker inspect` blob a mis-implemented seam is most likely to
23
+ * forward) and on a BigInt. That throw would escape the per-target try into the
24
+ * tick's outer catch — replacing the diagnostic that justifies warning at all
25
+ * with a generic line, AND releasing the `_ticking` latch while other
26
+ * containers' inspects are still in flight, so the next tick re-inspects them.
27
+ * Total by construction: every branch returns a string and none can throw.
28
+ */
29
+ function describeVerdict(verdict) {
30
+ try {
31
+ return JSON.stringify(verdict) ?? String(verdict)
32
+ } catch {
33
+ return `[unserialisable ${typeof verdict}]`
34
+ }
35
+ }
36
+
37
+ /**
38
+ * ContainerLivenessMonitor — a periodic, unref'd `docker inspect` poll over the
39
+ * live containerized sessions, surfacing CONTAINER_VANISHED (#7599) on any whose
40
+ * container has been stopped or removed underneath it.
41
+ *
42
+ * Deliberately docker-agnostic: it takes an `enumerate` fn (the live targets)
43
+ * and an `inspect` fn (containerId → 'running' | 'gone' | 'unknown'), so the
44
+ * SessionManager owns lifecycle without depending on a Docker backend, and the
45
+ * daemon-down guard lives with the injected inspect (see inspectContainerLiveness).
46
+ *
47
+ * Batching: multiple sessions in one container environment share a containerId,
48
+ * so the tick inspects each DISTINCT container once and fans the verdict to every
49
+ * session bound to it. An env with no sessions contributes no target and is never
50
+ * inspected (the #7601 negative control).
51
+ */
52
+ export class ContainerLivenessMonitor {
53
+ /**
54
+ * @param {object} opts
55
+ * @param {() => Array<{sessionId: string, containerId: string, session: object}>} opts.enumerate
56
+ * live containerized poll targets (session exposes notifyContainerVanished + holds a containerId)
57
+ * @param {(containerId: string) => Promise<'running'|'gone'|'unknown'>} opts.inspect
58
+ * @param {(target: {sessionId: string, containerId: string, session: object}) => any} [opts.onRecovered]
59
+ * #7602 — called once per RECOVERY EDGE (see _tick). Optional: without it the
60
+ * poll only clears the latch, exactly as in #7601.
61
+ * @param {number} [opts.intervalMs]
62
+ * @param {object} [opts.logger]
63
+ */
64
+ constructor({ enumerate, inspect, onRecovered = null, intervalMs = DEFAULT_LIVENESS_INTERVAL_MS, logger = log } = {}) {
65
+ this._enumerate = enumerate
66
+ this._inspect = inspect
67
+ this._onRecovered = onRecovered
68
+ this._intervalMs = intervalMs
69
+ this._log = logger
70
+ this._timer = null
71
+ // Skip a tick if the prior one is still awaiting inspects (each inspect can
72
+ // block up to the docker exec/inspect timeout), so a slow Docker daemon can't
73
+ // stack overlapping ticks.
74
+ this._ticking = false
75
+ }
76
+
77
+ /**
78
+ * Start the poll. No-op if already running or if the required fns are missing
79
+ * (so a deployment that never wired a Docker inspect simply never polls).
80
+ */
81
+ start() {
82
+ if (this._timer) return
83
+ if (typeof this._enumerate !== 'function' || typeof this._inspect !== 'function') return
84
+ this._timer = setInterval(() => { this._tick() }, this._intervalMs)
85
+ // Never keep the event loop (and thus the daemon process) alive for a poll.
86
+ if (typeof this._timer.unref === 'function') this._timer.unref()
87
+ this._log.info(`Container liveness poll enabled (every ${this._intervalMs}ms)`)
88
+ }
89
+
90
+ stop() {
91
+ if (this._timer) {
92
+ clearInterval(this._timer)
93
+ this._timer = null
94
+ }
95
+ }
96
+
97
+ destroy() {
98
+ this.stop()
99
+ }
100
+
101
+ /**
102
+ * One poll pass. Enumerate live containerized sessions, inspect each distinct
103
+ * container once, and surface CONTAINER_VANISHED on the sessions whose
104
+ * container is gone (or clear the latch on the ones whose container is running
105
+ * again). Every failure is contained: one bad inspect or one throwing session
106
+ * must not abort the whole pass or wedge the interval.
107
+ *
108
+ * #7602 — the RECOVERY EDGE. `clearContainerVanished()` returns true only when
109
+ * it actually flipped the latch, i.e. exactly on the gone→running transition of
110
+ * a session that HAD vanished. `onRecovered` is invoked on that edge and only
111
+ * there, which is what keeps the re-attach from re-running on every healthy
112
+ * tick of a session that never vanished (30s apart, that would re-resolve the
113
+ * environment binding of every idle containerized session forever). A provider
114
+ * whose `clearContainerVanished` returns nothing — an older stub, or one that
115
+ * predates the boolean — yields NO edge, so the failure direction is "no
116
+ * reconnect attempted", never "reconnect attempted spuriously". #7620 holds
117
+ * that same direction for a broken INSPECT seam: only 'running' reaches the
118
+ * clear/recovery branch, and an unrecognised verdict no-ops like 'unknown'.
119
+ */
120
+ async _tick() {
121
+ if (this._ticking) return
122
+ this._ticking = true
123
+ try {
124
+ const targets = this._enumerate() || []
125
+ if (targets.length === 0) return // negative control: nothing to poll
126
+
127
+ // Batch by containerId: one inspect per DISTINCT container, fanned to every
128
+ // session bound to it (env-backed sessions share a container).
129
+ const byContainer = new Map()
130
+ for (const t of targets) {
131
+ if (!t || !t.containerId || !t.session) continue
132
+ const list = byContainer.get(t.containerId)
133
+ // #7602: the whole TARGET is carried, not just the session — the
134
+ // recovery edge hands `sessionId` to onRecovered, which is what the
135
+ // SessionManager needs to find the entry's `environmentId`.
136
+ if (list) list.push(t)
137
+ else byContainer.set(t.containerId, [t])
138
+ }
139
+
140
+ await Promise.all([...byContainer.entries()].map(async ([containerId, targets]) => {
141
+ let status
142
+ try {
143
+ status = await this._inspect(containerId)
144
+ } catch (err) {
145
+ // The inspect fn owns the gone/unknown classification; a throw here is
146
+ // unexpected. Treat it as 'unknown' — never surface a vanish on an
147
+ // inspect that failed in a way we didn't classify.
148
+ this._log.warn(`container-liveness inspect threw for ${String(containerId).slice(0, 12)}: ${err?.message || err}`)
149
+ status = 'unknown'
150
+ }
151
+ if (status === 'unknown') return // transient (daemon down / timeout) — leave the latch as-is
152
+ // #7620 — the fan-out is CLOSED over the three-value contract. `inspect`
153
+ // is an INJECTION SEAM, so 'running' is tested explicitly here and every
154
+ // unrecognised verdict degrades to the SAME no-op as 'unknown' rather
155
+ // than falling through to the clear/recovery branch below. A broken seam
156
+ // must fail in the "no reconnect attempted" direction, exactly as a
157
+ // provider whose clearContainerVanished returns nothing does — not clear
158
+ // a vanish latch and trigger a re-attach. Warned once per CONTAINER (the
159
+ // verdict is a property of the container, not of each bound session)
160
+ // because an unrecognised verdict means the seam itself is broken.
161
+ if (status !== 'running' && status !== 'gone') {
162
+ this._log.warn(`container-liveness: unrecognised verdict ${describeVerdict(status)} for ${String(containerId).slice(0, 12)} — treating as unknown`)
163
+ return
164
+ }
165
+ for (const target of targets) {
166
+ const session = target.session
167
+ try {
168
+ if (status === 'gone') {
169
+ session.notifyContainerVanished?.()
170
+ continue
171
+ }
172
+ // #7602: only a genuine gone→running transition is a recovery edge.
173
+ // A throwing re-attach is contained by this loop's own catch below,
174
+ // like every other per-session call here — it must not abort the
175
+ // fan-out to the other sessions sharing this container.
176
+ if (session.clearContainerVanished?.() !== true) continue
177
+ if (this._onRecovered) await this._onRecovered(target)
178
+ } catch (err) {
179
+ this._log.warn(`container-liveness surface failed: ${err?.message || err}`)
180
+ }
181
+ }
182
+ }))
183
+ } catch (err) {
184
+ this._log.warn(`container-liveness tick failed: ${err?.message || err}`)
185
+ } finally {
186
+ this._ticking = false
187
+ }
188
+ }
189
+ }
@@ -0,0 +1,17 @@
1
+ // Isolated metadata only: no seed body reads. Parent owns deadline and concurrency.
2
+ import { statSync } from 'node:fs'
3
+
4
+ let input = ''
5
+ process.stdin.setEncoding('utf8')
6
+ process.stdin.on('data', (chunk) => { input += chunk })
7
+ process.stdin.on('end', () => {
8
+ const results = {}
9
+ for (const { id, seedPath, cwd } of JSON.parse(input)) {
10
+ try {
11
+ const seed = statSync(seedPath)
12
+ results[id] = seed.isFile() && statSync(cwd).isDirectory()
13
+ ? `${seed.dev}:${seed.ino}:${seed.size}:${seed.mtimeMs}:${seed.ctimeMs}` : null
14
+ } catch { results[id] = null }
15
+ }
16
+ process.stdout.write(JSON.stringify(results))
17
+ })
@@ -0,0 +1,227 @@
1
+ /** Path-only, daemon-lifetime opportunities. Filesystem probes run in a child. */
2
+ import { createHash } from 'node:crypto'
3
+ import { spawn } from 'node:child_process'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ export const CONTINUATION_TTL_MS = 30 * 60_000
7
+ const MAX_CONTINUATIONS = 50
8
+
9
+ /** Longest from an announcement to its baseline probe FINISHING. A queued entry
10
+ * whose remaining budget cannot fit the baseline deadline fails closed without a
11
+ * probe, so the window in which an unannounced replacement could be adopted is at
12
+ * most this. */
13
+ export const BASELINE_MAX_WAIT_MS = 10_000
14
+ const DEFAULT_BASELINE_DEADLINE_MS = 5000
15
+ /** Slack past a batch's budget before the loop stops waiting on a probe that
16
+ * never answers (for example a child stuck in an uninterruptible stat). */
17
+ const BATCH_CAP_GRACE_MS = 250
18
+ /** How long a list request waits for baseline work already in flight. */
19
+ export const LIST_BASELINE_WAIT_MS = 1000
20
+
21
+ /** One killable worker globally; a stuck syscall cannot fill libuv's pool or
22
+ * create an unbounded process queue. Keep the slot until child close. Refresh
23
+ * calls get `timeoutMs` and return null at once while the slot is held. Baseline
24
+ * calls (`{ baseline: true, waitMs }`) get the longer `baselineTimeoutMs` and wait
25
+ * at most `waitMs` for the slot (a killed child frees it on close); a slot that
26
+ * is not free in time yields null, so a child that cannot be killed cannot park
27
+ * the caller. The worker path seam
28
+ * is direct-test-only, never populated from HTTP input. */
29
+ export function createContinuationProbe({
30
+ workerPath = fileURLToPath(new URL('./continuation-metadata-worker.js', import.meta.url)),
31
+ timeoutMs = 1000,
32
+ baselineTimeoutMs = Math.max(timeoutMs, 5000),
33
+ } = {}) {
34
+ let active = false
35
+ let waiters = []
36
+ const release = () => {
37
+ active = false
38
+ const queued = waiters
39
+ waiters = []
40
+ for (const wake of queued) wake()
41
+ }
42
+ const waitForSlot = (ms) => new Promise((resolve) => {
43
+ const wake = () => { clearTimeout(timer); resolve(true) }
44
+ const timer = setTimeout(() => { waiters = waiters.filter((w) => w !== wake); resolve(false) }, ms)
45
+ waiters.push(wake)
46
+ })
47
+ const probe = async (entries, { baseline = false, waitMs = baselineTimeoutMs } = {}) => {
48
+ if (entries.length === 0) return null
49
+ const until = Date.now() + waitMs
50
+ while (active) {
51
+ if (!baseline) return null
52
+ const left = until - Date.now()
53
+ if (left <= 0 || !(await waitForSlot(left))) return null
54
+ }
55
+ active = true
56
+ // A slot is released at most once per spawn: a late 'close' after 'error'
57
+ // (or the reverse) must never free a slot a newer probe now holds.
58
+ let released = false
59
+ const releaseOnce = () => { if (released) return; released = true; release() }
60
+ const deadline = baseline ? baselineTimeoutMs : timeoutMs
61
+ return new Promise((resolve) => {
62
+ let child, timer, settled = false, output = ''
63
+ const finish = (result) => {
64
+ if (settled) return
65
+ settled = true
66
+ clearTimeout(timer)
67
+ resolve(result)
68
+ }
69
+ try {
70
+ child = spawn(process.execPath, ['--', workerPath], { stdio: ['pipe', 'pipe', 'ignore'] })
71
+ timer = setTimeout(() => { finish(null); child.kill('SIGKILL') }, deadline)
72
+ child.on('error', () => { releaseOnce(); finish(null) })
73
+ child.on('close', (code) => {
74
+ releaseOnce()
75
+ let result = null
76
+ if (code === 0) {
77
+ try { result = JSON.parse(output) } catch { /* unavailable */ }
78
+ }
79
+ finish(result)
80
+ })
81
+ child.stdout.on('data', (chunk) => {
82
+ output += chunk
83
+ if (output.length > 65_536) { finish(null); child.kill('SIGKILL') }
84
+ })
85
+ child.stdin.on('error', () => { finish(null); child.kill('SIGKILL') })
86
+ child.stdin.end(JSON.stringify(entries.map(({ id, seedPath, cwd }) => ({ id, seedPath, cwd }))))
87
+ } catch {
88
+ if (child) child.kill('SIGKILL')
89
+ else releaseOnce()
90
+ finish(null)
91
+ }
92
+ })
93
+ }
94
+ probe.baselineTimeoutMs = baselineTimeoutMs
95
+ return probe
96
+ }
97
+
98
+ const probeMetadata = createContinuationProbe()
99
+ function expired(entry, now) {
100
+ return now - entry.ts > CONTINUATION_TTL_MS || entry.ts > now + 60_000
101
+ }
102
+
103
+ function failBaseline(entry) {
104
+ entry.fingerprint = null
105
+ entry.baselineFailed = true
106
+ entry.unavailable = 'metadata timeout'
107
+ }
108
+
109
+ const pendingBaseline = (entry, now) => entry.fingerprint === undefined && !entry.baselineFailed && !expired(entry, now)
110
+
111
+ /** Baseline queue. A baseline is adopted ONLY from a probe batch started for the
112
+ * announcement itself, never from a list/poll refresh and never from a batch the
113
+ * announcement was not part of. One loop runs at a time; an announcement that
114
+ * arrives mid-batch is picked up by the next iteration with its own probe. */
115
+ function startBaselines(server) {
116
+ if (server._continuationRefresh) return server._continuationRefresh
117
+ const holder = {}
118
+ holder.promise = (async () => {
119
+ try {
120
+ for (;;) {
121
+ const probe = server._continuationBaselineProbe
122
+ const now = Date.now()
123
+ const batch = [...(server._continuations?.values() || [])].filter((entry) => pendingBaseline(entry, now))
124
+ if (batch.length === 0) return
125
+ const deadline = probe.baselineTimeoutMs ?? DEFAULT_BASELINE_DEADLINE_MS
126
+ // A probe that starts must also finish inside the bound.
127
+ // `_continuationBaselineMaxWaitMs` is a test injection point only (like
128
+ // `_continuationProbe`): nothing in src sets it, so production always uses
129
+ // BASELINE_MAX_WAIT_MS.
130
+ const maxWait = server._continuationBaselineMaxWaitMs ?? BASELINE_MAX_WAIT_MS
131
+ const waiting = batch.filter((entry) => now - entry.receivedAt + deadline > maxWait)
132
+ for (const entry of waiting) failBaseline(entry)
133
+ const live = batch.filter((entry) => !waiting.includes(entry))
134
+ if (live.length === 0) continue
135
+ const waitMs = Math.min(...live.map((entry) => maxWait - deadline - (now - entry.receivedAt)))
136
+ // The probe is raced against the batch budget: a child that never closes
137
+ // cannot park the loop, and a late answer is never read.
138
+ let results = null, cap
139
+ try {
140
+ results = await Promise.race([
141
+ probe(live, { baseline: true, waitMs }),
142
+ new Promise((resolve) => { cap = setTimeout(() => resolve(null), waitMs + deadline + BATCH_CAP_GRACE_MS) }),
143
+ ])
144
+ } catch { /* unavailable */ } finally { clearTimeout(cap) }
145
+ for (const entry of live) {
146
+ if (server._continuations?.get(entry.id) !== entry) continue
147
+ if (!results || !Object.hasOwn(results, entry.id)) {
148
+ // Without the announcement's own initial snapshot we cannot tell
149
+ // whether a later check sees the original file or a replacement.
150
+ failBaseline(entry)
151
+ continue
152
+ }
153
+ entry.fingerprint = results[entry.id]
154
+ entry.unavailable = entry.fingerprint ? null : 'missing'
155
+ }
156
+ }
157
+ } finally {
158
+ holder.done = true
159
+ if (server._continuationRefresh === holder.promise) server._continuationRefresh = null
160
+ }
161
+ })()
162
+ if (!holder.done) server._continuationRefresh = holder.promise
163
+ return holder.promise
164
+ }
165
+
166
+ /** Re-checks entries that already have a baseline. Never adopts one. */
167
+ async function refreshEstablished(server, now, probe) {
168
+ if (server._continuationListRefresh) return server._continuationListRefresh
169
+ const entries = [...(server._continuations?.values() || [])]
170
+ .filter((entry) => entry.fingerprint !== undefined && !entry.baselineFailed && !expired(entry, now))
171
+ if (entries.length === 0) return
172
+ const refresh = (async () => {
173
+ const results = await probe(entries)
174
+ for (const entry of entries) {
175
+ if (server._continuations?.get(entry.id) !== entry) continue
176
+ if (!results || !Object.hasOwn(results, entry.id)) { entry.unavailable = 'metadata timeout'; continue }
177
+ const current = results[entry.id]
178
+ entry.unavailable = !current || !entry.fingerprint ? 'missing' : current !== entry.fingerprint ? 'changed' : null
179
+ }
180
+ })()
181
+ server._continuationListRefresh = refresh
182
+ try { await refresh } finally { if (server._continuationListRefresh === refresh) server._continuationListRefresh = null }
183
+ }
184
+
185
+ async function waitBounded(promise, ms) {
186
+ let timer
187
+ try {
188
+ await Promise.race([promise.catch(() => {}), new Promise((resolve) => { timer = setTimeout(resolve, ms) })])
189
+ } finally { clearTimeout(timer) }
190
+ }
191
+
192
+ // `server._continuationProbe` is a test injection point only: nothing on the
193
+ // HTTP path ever sets it, so production always uses the isolated child probe.
194
+ // It serves tests/continuations.test.js, which pins both defaults below.
195
+ export function recordContinuation(server, event, now = Date.now(), probe = server._continuationProbe ?? probeMetadata) {
196
+ const { seedPath, cwd } = event.data
197
+ const id = createHash('sha256').update(JSON.stringify([cwd, seedPath])).digest('hex')
198
+ if (!server._continuations) server._continuations = new Map()
199
+ const previous = server._continuations.get(id)
200
+ if (previous && event.ts <= previous.ts) return { opportunity: previous, duplicate: true }
201
+ const opportunity = { id, seedPath, cwd, ts: event.ts, receivedAt: now, fingerprint: undefined, unavailable: 'checking metadata' }
202
+ server._continuations.delete(id)
203
+ server._continuations.set(id, opportunity)
204
+ while (server._continuations.size > MAX_CONTINUATIONS) server._continuations.delete(server._continuations.keys().next().value)
205
+ // The isolated probe never delays the ingest acknowledgement. An announcement
206
+ // that lands while a batch is running is queued behind it and gets its own.
207
+ server._continuationBaselineProbe = probe
208
+ void startBaselines(server).catch(() => {})
209
+ return { opportunity, duplicate: false }
210
+ }
211
+
212
+ export async function listContinuations(server, now = Date.now(), probe = server._continuationProbe ?? probeMetadata) {
213
+ // Bounded wait for baseline work; a still-pending entry reads 'checking metadata'.
214
+ if (server._continuationRefresh) await waitBounded(server._continuationRefresh, server._continuationListWaitMs ?? LIST_BASELINE_WAIT_MS)
215
+ // The one probe worker may still be busy with a baseline: do not probe, and do
216
+ // not turn that busy answer into a spurious 'metadata timeout'.
217
+ const busy = Boolean(server._continuationRefresh)
218
+ if (!busy) await refreshEstablished(server, now, probe)
219
+ return [...(server._continuations?.values() || [])].reverse().map((entry) => {
220
+ // An established entry that could not be re-verified (baseline work holds
221
+ // the worker) must not keep reading 'available'. Response only: state is
222
+ // untouched, so it re-verifies normally once the worker is free.
223
+ const stale = busy && entry.unavailable === null && entry.fingerprint !== undefined && !entry.baselineFailed
224
+ const unavailable = expired(entry, now) ? 'expired' : stale ? 'checking metadata' : entry.unavailable
225
+ return { id: entry.id, seedPath: entry.seedPath, cwd: entry.cwd, ts: entry.ts, available: unavailable === null, unavailable }
226
+ })
227
+ }
@@ -32,6 +32,7 @@
32
32
  */
33
33
 
34
34
  import { execFile } from 'child_process'
35
+ import { assertAuthorized } from '../connection-authority.js'
35
36
  import { promisify } from 'util'
36
37
  import { parseByteSize } from './containers.js'
37
38
  import { listSnapshots } from '../snapshots-store.js'
@@ -347,6 +348,7 @@ export async function runHostPrune(opts = {}) {
347
348
  listByokSnapshots = () => listSnapshots(),
348
349
  _execFile = execFileAsync,
349
350
  _now = () => new Date(),
351
+ isAuthorized,
350
352
  } = opts
351
353
  const selected = PRUNE_KINDS.includes(kind) ? kind : 'all'
352
354
  const survey = await surveyHostPrune({ listEnvironments, listByokSnapshots, _execFile, _now })
@@ -360,9 +362,11 @@ export async function runHostPrune(opts = {}) {
360
362
  failures: [],
361
363
  }
362
364
  if (!survey.dockerAvailable) return result
365
+ assertAuthorized(isAuthorized)
363
366
 
364
367
  if (selected === 'containers' || selected === 'all') {
365
368
  for (const c of survey.containers) {
369
+ assertAuthorized(isAuthorized)
366
370
  try {
367
371
  await _execFile('docker', ['rm', c.id], EXEC_OPTS)
368
372
  result.removedContainers += 1
@@ -374,6 +378,7 @@ export async function runHostPrune(opts = {}) {
374
378
  }
375
379
  if (selected === 'images' || selected === 'all') {
376
380
  for (const img of survey.images) {
381
+ assertAuthorized(isAuthorized)
377
382
  try {
378
383
  await _execFile('docker', ['rmi', img.id], EXEC_OPTS)
379
384
  result.removedImages += 1