@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,546 @@
1
+ /**
2
+ * POST /api/events — authenticated local event ingest (#5413 Phase 3).
3
+ *
4
+ * Lets chroxy become aware of Claude Code sessions it did NOT launch:
5
+ * external hook emitters (Phase 4's packages/claude-hooks) POST normalized
6
+ * events here, and they flow through the EXISTING notification pipeline
7
+ * (PushManager.send → per-category rate limit → prefs → sink fan-out), so
8
+ * the Discord status embed and Expo push both light up with zero new
9
+ * delivery machinery.
10
+ *
11
+ * Auth — the "ingest secret", a fourth daemon-level token class (see
12
+ * docs/security/bearer-token-authority.md §6):
13
+ * - External sessions have no per-session hook secret (chroxy never
14
+ * spawned them), and putting the PRIMARY token in every hook process's
15
+ * environment would grant full session authority to anything that can
16
+ * read a hook's env. So the endpoint accepts exactly one credential: a
17
+ * dedicated secret generated once and stored 0600 at
18
+ * `~/.chroxy/ingest-secret` (CHROXY_CONFIG_DIR honored), where the
19
+ * same-user hook emitters can read it.
20
+ * - Constant-time compared (safeTokenCompare), never logged, scoped to
21
+ * this single endpoint. The daemon may be tunnel-exposed, so this is
22
+ * bearer-gated exactly like POST /permission — possession of the
23
+ * secret is the boundary, not network position.
24
+ * - Fail closed: missing/invalid auth → 401 with no body detail; if the
25
+ * secret cannot be loaded or created, every request is rejected.
26
+ */
27
+
28
+ import { randomBytes } from 'node:crypto'
29
+ import { existsSync, mkdirSync, readFileSync, openSync, writeSync, closeSync } from 'node:fs'
30
+ import { dirname, join } from 'node:path'
31
+ import { homedir } from 'node:os'
32
+ import { safeTokenCompare } from './token-compare.js'
33
+ import { sendOversizeResponse } from './http-oversize.js'
34
+ import { writeFileRestricted } from './platform.js'
35
+ import { createLogger } from './logger.js'
36
+ import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
37
+ import { SubagentCounter } from './subagent-counter.js'
38
+ import { TurnTracker } from './turn-tracker.js'
39
+ import { IngestEventSchema } from '@chroxy/protocol'
40
+ // deriveProjectFromCwd + the chroxy-worktree helpers moved to the shared,
41
+ // Zod-free @chroxy/protocol/project subpath (audit P2-2, #5850) so the hook
42
+ // (packages/claude-hooks/src/project.js) and this server fallback can't drift.
43
+ import { deriveProjectFromCwd } from '@chroxy/protocol/project'
44
+
45
+ const log = createLogger('ingest')
46
+
47
+ /** Body cap — matches POST /permission's MAX_BODY (ws-permissions.js). */
48
+ export const MAX_INGEST_BODY_BYTES = 65536
49
+
50
+ /**
51
+ * Per-source rate limit, split into two independent class buckets (#5675).
52
+ *
53
+ * The original single per-source bucket (keyed `source:${source}`) caused a
54
+ * priority inversion under parallel-subagent load: `post_tool_use` fires on
55
+ * EVERY tool call with no client throttle (5-20/sec under heavy parallelism),
56
+ * so it drained the shared 60/min bucket in seconds — and for the rest of the
57
+ * minute the transition events that actually matter (`stop`, `subagent_stop`,
58
+ * `notification`) got 429'd and dropped, leaving the Discord embed stale.
59
+ *
60
+ * The fix keys each bucket by `source:${source}:${class}` so a flood of
61
+ * keepalives can no longer starve the must-deliver tokens:
62
+ * - KEEPALIVE (post_tool_use): small bucket, 60/min + 10 burst. Dropping
63
+ * under load is harmless — with the #5541 turn edges, user_prompt_submit
64
+ * already holds the embed in "working", so post_tool_use only freshens
65
+ * the detail line.
66
+ * - LIFECYCLE / must-deliver (session/subagent/notification/turn edges):
67
+ * generous bucket, 300/min + 60 burst. Naturally bounded by real
68
+ * transition rates even under heavy parallelism, so it never drops.
69
+ *
70
+ * PushManager's per-category limits are the second layer; Discord's own 429
71
+ * handling is the third; the pre-auth per-IP ceiling below is the outer guard.
72
+ */
73
+ const INGEST_WINDOW_MS = 60_000
74
+ const INGEST_MAX_EVENTS = 60
75
+ const INGEST_BURST = 10
76
+ const INGEST_LIFECYCLE_MAX_EVENTS = 300
77
+ const INGEST_LIFECYCLE_BURST = 60
78
+
79
+ /**
80
+ * Event classes for the split per-source rate limit (#5675). KEEPALIVE is the
81
+ * single droppable type; everything else is a meaningful transition. Unknown
82
+ * types default to 'lifecycle' (fail safe — a new/unrecognized type must never
83
+ * be silently dropped into the small keepalive bucket).
84
+ */
85
+ const KEEPALIVE_EVENT_TYPES = new Set(['post_tool_use'])
86
+
87
+ /**
88
+ * Classify an ingest event type for rate limiting. Exported for unit testing.
89
+ * Anything not in the keepalive set — including unknown, new, or
90
+ * undefined/empty types — classifies as 'lifecycle' (fail-safe: never
91
+ * silently route a meaningful event into the droppable keepalive bucket).
92
+ * @param {string | undefined} type
93
+ * @returns {'keepalive' | 'lifecycle'}
94
+ */
95
+ export function ingestEventClass(type) {
96
+ return KEEPALIVE_EVENT_TYPES.has(type) ? 'keepalive' : 'lifecycle'
97
+ }
98
+
99
+ /**
100
+ * Pre-auth per-IP ceiling (#5432 review S1/S2): the per-source buckets
101
+ * above are keyed on a caller-chosen string, so a secret-holder rotating
102
+ * `source` per request would otherwise mint a fresh bucket every time.
103
+ * The per-IP limit is the hard total — sized above the per-source limit
104
+ * because one machine legitimately runs several emitting sessions.
105
+ */
106
+ const INGEST_IP_MAX_EVENTS = 240
107
+ const INGEST_IP_BURST = 30
108
+
109
+ /**
110
+ * Event type → notification category + default title/body. Categories ride
111
+ * the existing PushManager machinery (RATE_LIMITS in push.js) and map onto
112
+ * Discord embed states via STATE_FOR_CATEGORY in discord-webhook-sink.js:
113
+ *
114
+ * session_start → session_online (embed: online — DELETE old + fresh POST,
115
+ * the bash original's SessionStart)
116
+ * session_end → session_offline (embed: offline — routine PATCH)
117
+ * subagent_* → session_activity (embed: online — routine PATCH, throttled;
118
+ * counting moves server-side in Phase 4)
119
+ * post_tool_use → session_activity
120
+ * notification → activity_waiting (existing category: input/approval needed —
121
+ * ping-worthy, like the bash Notification arm)
122
+ * EXCEPT data.notificationType === 'idle_prompt' (#5439
123
+ * GAP A) → activity_update (embed: idle — 🦀 ready ping
124
+ * with idle→idle dedup, the bash idle_prompt arm)
125
+ */
126
+ export const INGEST_CATEGORY_FOR_TYPE = {
127
+ session_start: { category: 'session_online', title: 'Session online', body: 'External session started' },
128
+ session_end: { category: 'session_offline', title: 'Session offline', body: 'External session ended' },
129
+ subagent_start: { category: 'session_activity', title: 'Subagent started', body: 'A subagent is running' },
130
+ subagent_stop: { category: 'session_activity', title: 'Subagent finished', body: 'A subagent completed' },
131
+ notification: { category: 'activity_waiting', title: 'Input needed', body: 'Claude is waiting' },
132
+ post_tool_use: { category: 'session_activity', title: 'Tool activity', body: 'Tool use completed' },
133
+ // #5541 turn edges. user_prompt_submit is the authoritative turn START:
134
+ // session_activity (online embed) so the embed flips off "Ready for input"
135
+ // immediately, and it sets turn-in-flight for the (source, sessionId) so
136
+ // the sink's GAP C idle-hold no longer applies. stop is the authoritative
137
+ // turn END: activity_update (idle embed, 🦀 "Ready for input") — Stop fires
138
+ // immediately, where Claude Code's idle Notification only fires after ~60s,
139
+ // and it clears turn-in-flight. The existing idle→idle dedup in the sink
140
+ // absorbs the later idle Notification.
141
+ user_prompt_submit: { category: 'session_activity', title: 'Turn started', body: 'User submitted a prompt' },
142
+ stop: { category: 'activity_update', title: 'Ready for input', body: 'Claude is waiting for input' },
143
+ }
144
+
145
+ /**
146
+ * #5439 GAP A: the hooks' Notification emitter forwards the matcher
147
+ * discriminator as data.notificationType. `idle_prompt` is the bash
148
+ * original's highest-volume ping ("ready for input") and must ride the
149
+ * activity_update category — the Discord sink maps it to the `idle` embed
150
+ * state (project color, idle→idle dedup). `permission_prompt` (and any
151
+ * payload without the discriminator) keeps the activity_waiting default
152
+ * above (permission embed, always re-pings).
153
+ */
154
+ export const INGEST_IDLE_PROMPT_MAPPING = {
155
+ category: 'activity_update',
156
+ title: 'Ready for input',
157
+ body: 'Claude is waiting for input',
158
+ }
159
+
160
+ /** Default on-disk location for the ingest secret (0600, same-user reads). */
161
+ export function defaultIngestSecretPath() {
162
+ const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
163
+ return join(configDir, 'ingest-secret')
164
+ }
165
+
166
+ // Synchronous millisecond sleep (Atomics.wait on a throwaway SharedArrayBuffer) —
167
+ // used only in the rare ingest-secret create race, to yield the CPU so a concurrent
168
+ // winner's writeSync can land before we re-read its (briefly 0-byte) file.
169
+ function sleepSync(ms) {
170
+ try {
171
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
172
+ } catch {
173
+ // SharedArrayBuffer/Atomics unavailable — skip the backoff; the retry loop's
174
+ // own syscall overhead still spaces the reads.
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Read the ingest secret from disk, generating + persisting it (0600,
180
+ * temp+rename via writeFileRestricted) when missing. Throws on I/O failure
181
+ * — callers decide whether that's fatal (the route fails closed; startup
182
+ * logs and carries on).
183
+ */
184
+ export function loadOrCreateIngestSecret(secretPath = defaultIngestSecretPath()) {
185
+ if (existsSync(secretPath)) {
186
+ const existing = readFileSync(secretPath, 'utf-8').trim()
187
+ if (existing.length > 0) return existing
188
+ }
189
+ const secret = randomBytes(32).toString('base64url')
190
+ mkdirSync(dirname(secretPath), { recursive: true })
191
+ // Atomic exclusive-create ('ax' fails with EEXIST if the file already exists) so
192
+ // two concurrent first-starts can't each write a DIFFERENT secret: the old
193
+ // existsSync+write check-then-act let the LAST writer win, silently invalidating
194
+ // the first process's secret (and the emitters that already authenticated with
195
+ // it). With 'ax' the FIRST writer wins; a loser re-reads the winner's secret.
196
+ let fd
197
+ try {
198
+ fd = openSync(secretPath, 'ax', 0o600)
199
+ } catch (err) {
200
+ if (err && err.code === 'EEXIST') {
201
+ // The file already exists — re-read the winner's secret. An EMPTY read means
202
+ // EITHER a corrupt / crashed-mid-write file OR a concurrent winner that just
203
+ // created the 0-byte file via its own 'ax' but hasn't flushed its writeSync
204
+ // yet. Retry briefly (yielding the CPU so the winner can be scheduled) so its
205
+ // write lands and BOTH processes converge on the winner's secret — overwriting
206
+ // here would clobber the winner's inode and re-open the very split-secret race.
207
+ for (let attempt = 0; attempt < 10; attempt++) {
208
+ const existing = readFileSync(secretPath, 'utf-8').trim()
209
+ if (existing.length > 0) return existing
210
+ if (attempt < 9) sleepSync(5)
211
+ }
212
+ // Still empty after the retry window — genuinely corrupt (not a live winner);
213
+ // recover via the legacy temp+rename overwrite.
214
+ writeFileRestricted(secretPath, secret + '\n')
215
+ return secret
216
+ }
217
+ throw err
218
+ }
219
+ try {
220
+ writeSync(fd, secret + '\n')
221
+ } finally {
222
+ closeSync(fd)
223
+ }
224
+ return secret
225
+ }
226
+
227
+ /**
228
+ * Startup helper: make sure the secret file exists BEFORE any hook tries to
229
+ * read it (chicken-and-egg: emitters authenticate with the file's content).
230
+ * Never throws — ingest is an optional surface; a failure here just means
231
+ * the route rejects everything (fail closed) until the operator fixes the
232
+ * config dir. Never logs the secret itself.
233
+ */
234
+ export function ensureIngestSecret(secretPath = defaultIngestSecretPath()) {
235
+ try {
236
+ loadOrCreateIngestSecret(secretPath)
237
+ return true
238
+ } catch (err) {
239
+ log.warn(`Could not provision ingest secret at ${secretPath}: ${err.message}`)
240
+ return false
241
+ }
242
+ }
243
+
244
+ function sendJson(res, status, body, extraHeaders = {}) {
245
+ res.writeHead(status, { 'Content-Type': 'application/json', ...extraHeaders })
246
+ res.end(JSON.stringify(body))
247
+ }
248
+
249
+ /** 401, fail closed: no body detail, nothing about WHY auth failed. */
250
+ function sendUnauthorized(res) {
251
+ res.writeHead(401)
252
+ res.end()
253
+ }
254
+
255
+ /**
256
+ * Resolve the secret the route compares against. `server._ingestSecret` is
257
+ * the test seam; otherwise load (and lazily create) from
258
+ * `server._ingestSecretPath` / the default path, cached on the server
259
+ * object so the fs probe doesn't run per event. Returns null on failure —
260
+ * the caller MUST reject (fail closed).
261
+ */
262
+ export function resolveIngestSecret(server) {
263
+ if (typeof server._ingestSecret === 'string' && server._ingestSecret.length > 0) {
264
+ return server._ingestSecret
265
+ }
266
+ if (typeof server._ingestSecretCached === 'string') return server._ingestSecretCached
267
+ try {
268
+ const secret = loadOrCreateIngestSecret(server._ingestSecretPath || defaultIngestSecretPath())
269
+ server._ingestSecretCached = secret
270
+ return secret
271
+ } catch (err) {
272
+ log.warn(`Ingest secret unavailable: ${err.message}`)
273
+ return null
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Handle POST /api/events. Order of gates:
279
+ * 1. bearer auth against the ingest secret (constant-time; 401, no detail)
280
+ * 2. body size cap (413) + defensive JSON parse (400)
281
+ * 3. IngestEventSchema validation (400 with field-level messages)
282
+ * 4. per-source rate limit (429 + Retry-After)
283
+ * 5. map type → category, derive project, dispatch into PushManager
284
+ *
285
+ * Responds 200 as soon as the event is dispatched — delivery (Discord
286
+ * retries etc.) is the pipeline's business; hook emitters must stay fast
287
+ * and fail-silent (<100ms budget in Phase 4).
288
+ */
289
+ export function handleEventIngest(server, req, res) {
290
+ // Pre-auth per-IP limit (#5432 review S1/S2), mirroring POST /permission's
291
+ // #3980 limiter: caps total throughput per client BEFORE auth (cheap 429s
292
+ // for brute-force probing) and — crucially — bounds the post-auth abuse
293
+ // where a secret-holder rotates `source` per request to mint a fresh
294
+ // per-source bucket each time. Wider window than per-source (several
295
+ // concurrent sessions emit through one IP) but a hard ceiling all the same.
296
+ // getRateLimitKey prefers the forwarded client IP for loopback/tunneled
297
+ // peers so one noisy client can't exhaust everyone's bucket, and falls
298
+ // back to the kernel socket address for direct peers (unspoofable).
299
+ if (!server._ingestIpRateLimiter) {
300
+ server._ingestIpRateLimiter = new RateLimiter({
301
+ windowMs: INGEST_WINDOW_MS,
302
+ maxMessages: INGEST_IP_MAX_EVENTS,
303
+ burst: INGEST_IP_BURST,
304
+ name: 'ingest-ip',
305
+ })
306
+ }
307
+ const clientIp = getRateLimitKey(req.socket?.remoteAddress || '', req)
308
+ {
309
+ const { allowed, retryAfterMs } = server._ingestIpRateLimiter.check(clientIp)
310
+ if (!allowed) {
311
+ log.warn(`Rate limited POST /api/events from ${clientIp}`)
312
+ sendJson(res, 429, { error: 'rate limited', retryAfterMs }, {
313
+ 'Retry-After': Math.ceil(retryAfterMs / 1000),
314
+ })
315
+ return
316
+ }
317
+ }
318
+
319
+ const secret = resolveIngestSecret(server)
320
+ const authHeader = req.headers['authorization'] || ''
321
+ const token = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : ''
322
+ // safeTokenCompare on every request (even when the secret failed to load,
323
+ // via the null → '' coercion rejecting) — no early-exit timing oracle and
324
+ // no raw token ever logged.
325
+ if (!secret || !safeTokenCompare(token, secret)) {
326
+ log.warn('Rejected POST /api/events: invalid or missing ingest auth')
327
+ sendUnauthorized(res)
328
+ return
329
+ }
330
+
331
+ // utf8 decoding so multi-byte chars split across TCP chunks reassemble
332
+ // correctly, and the cap below counts BYTES (Buffer.byteLength), not
333
+ // UTF-16 code units — body.length undercounts non-ASCII ~3x.
334
+ req.setEncoding('utf8')
335
+ let body = ''
336
+ let bodyBytes = 0
337
+ let oversized = false
338
+ req.on('data', (chunk) => {
339
+ if (oversized) return
340
+ bodyBytes += Buffer.byteLength(chunk, 'utf8')
341
+ if (bodyBytes > MAX_INGEST_BODY_BYTES) {
342
+ oversized = true
343
+ // #5433: respond BEFORE teardown — destroying the socket here would
344
+ // suppress 'end' and the client would see a reset instead of the 413.
345
+ // The helper stops consumption and closes the connection after the
346
+ // response flushes. Cap checked BEFORE append: the violating chunk is
347
+ // never buffered, so `body` never exceeds the cap in memory.
348
+ sendOversizeResponse(req, res, { error: 'body too large' })
349
+ return
350
+ }
351
+ body += chunk
352
+ })
353
+ req.on('end', () => {
354
+ // #5313 pattern: this callback runs on a later tick, OUTSIDE the HTTP
355
+ // dispatch try/catch (#5312) — wrap everything so a throw here can't
356
+ // escape to uncaughtException and take the daemon down.
357
+ try {
358
+ // #5433: the 413 was already sent from the 'data' handler.
359
+ if (oversized) return
360
+
361
+ let parsed
362
+ try {
363
+ parsed = JSON.parse(body)
364
+ } catch {
365
+ sendJson(res, 400, { error: 'invalid JSON' })
366
+ return
367
+ }
368
+
369
+ const result = IngestEventSchema.safeParse(parsed)
370
+ if (!result.success) {
371
+ const details = result.error.issues
372
+ .slice(0, 10)
373
+ .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
374
+ sendJson(res, 400, { error: 'invalid event', details })
375
+ return
376
+ }
377
+ const event = result.data
378
+
379
+ // Per-source rate limit, split into two class buckets (#5675) so a
380
+ // flood of `post_tool_use` keepalives can't starve the must-deliver
381
+ // transition events. Both lazily constructed so http-routes' mock
382
+ // servers get them for free.
383
+ //
384
+ // `_ingestRateLimiter` is the KEEPALIVE bucket — this preserves the
385
+ // documented pre-seed knob: ws-server (and existing tests) pre-seed
386
+ // `_ingestRateLimiter` for tighter keepalive knobs, and that path keeps
387
+ // working. The generous lifecycle bucket is the second limiter alongside.
388
+ const eventClass = ingestEventClass(event.type)
389
+ let limiter
390
+ if (eventClass === 'keepalive') {
391
+ if (!server._ingestRateLimiter) {
392
+ server._ingestRateLimiter = new RateLimiter({
393
+ windowMs: INGEST_WINDOW_MS,
394
+ maxMessages: INGEST_MAX_EVENTS,
395
+ burst: INGEST_BURST,
396
+ name: 'ingest-keepalive',
397
+ })
398
+ }
399
+ limiter = server._ingestRateLimiter
400
+ } else {
401
+ if (!server._ingestLifecycleRateLimiter) {
402
+ server._ingestLifecycleRateLimiter = new RateLimiter({
403
+ windowMs: INGEST_WINDOW_MS,
404
+ maxMessages: INGEST_LIFECYCLE_MAX_EVENTS,
405
+ burst: INGEST_LIFECYCLE_BURST,
406
+ name: 'ingest-lifecycle',
407
+ })
408
+ }
409
+ limiter = server._ingestLifecycleRateLimiter
410
+ }
411
+ // Independent token pools per class — keyed by class so neither can
412
+ // starve the other.
413
+ const { allowed, retryAfterMs } = limiter.check(`source:${event.source}:${eventClass}`)
414
+ if (!allowed) {
415
+ log.warn(`Rate limited POST /api/events from source "${event.source}" (${eventClass})`)
416
+ sendJson(res, 429, { error: 'rate limited', retryAfterMs }, {
417
+ 'Retry-After': Math.ceil(retryAfterMs / 1000),
418
+ })
419
+ return
420
+ }
421
+
422
+ const pushManager = server.pushManager
423
+ if (!pushManager || typeof pushManager.send !== 'function') {
424
+ sendJson(res, 503, { error: 'notification pipeline unavailable' })
425
+ return
426
+ }
427
+
428
+ let mapping = INGEST_CATEGORY_FOR_TYPE[event.type]
429
+ // Schema enum and this map are kept in lockstep; belt-and-braces only.
430
+ if (!mapping) {
431
+ sendJson(res, 400, { error: 'invalid event', details: [`type: unsupported type ${event.type}`] })
432
+ return
433
+ }
434
+
435
+ // Explicit `project` wins; otherwise derive from data.cwd (git-root
436
+ // walk). The Discord sink's _projectKey prefers data.project, so this
437
+ // is what keys the per-project status embed.
438
+ const data = event.data || {}
439
+
440
+ // #5439 GAP A: split the Notification hook by its discriminator —
441
+ // idle prompts are "ready for input" (idle embed), not approvals.
442
+ if (event.type === 'notification' && data.notificationType === 'idle_prompt') {
443
+ mapping = INGEST_IDLE_PROMPT_MAPPING
444
+ }
445
+ const project = event.project
446
+ || (typeof data.cwd === 'string' ? deriveProjectFromCwd(data.cwd) : null)
447
+
448
+ // Server-side subagent counting (#5413 Phase 4): fold subagent_start/
449
+ // subagent_stop into the per-(source, sessionId) aggregate (session_end
450
+ // clears it), and surface the active count on every event so the
451
+ // Discord embed's `data.subagents` field and the notification text can
452
+ // use it. Lazily constructed like the rate limiters; tests can pre-seed
453
+ // `_subagentCounter` for clock injection.
454
+ //
455
+ // #5463: the surfaced count is the PER-PROJECT total, not the event's
456
+ // own session count. The embed is keyed per project, and several
457
+ // sessions emit into one project (main session + worktree agents
458
+ // remapped to the parent by the hooks' GAP B filter) — stamping each
459
+ // event with its own session's count made the embed flip between
460
+ // unrelated numbers, and a zero from session B falsely fired session
461
+ // A's armed count→0 ready re-ping. `project` here is the post-remap
462
+ // name (explicit envelope project wins over cwd derivation), i.e. the
463
+ // same key _projectKey uses for the embed. Events without a project
464
+ // fall back to the per-session count — the embed key falls back to
465
+ // the sessionId in that case too, so the scopes still match.
466
+ if (!server._subagentCounter) {
467
+ server._subagentCounter = new SubagentCounter()
468
+ }
469
+ const counted = server._subagentCounter.record(event.type, event.source, event.sessionId, project)
470
+ const activeSubagents = project
471
+ ? server._subagentCounter.getProjectTotal(project)
472
+ : (counted !== null
473
+ ? counted
474
+ : server._subagentCounter.getCount(event.source, event.sessionId))
475
+
476
+ // #5541: turn-in-flight tracking, wired exactly like the subagent
477
+ // counter above. user_prompt_submit sets it, stop/session_end clear it;
478
+ // the per-project aggregate (anyTurnInFlight) rides every event as
479
+ // `data.turnInFlight` so the Discord sink can rescope its GAP C
480
+ // idle-hold (the embed must stay online while the main agent is busy,
481
+ // even when its subagents are still running). A daemon restart empties
482
+ // this in-memory map, so the flag defaults to false — today's behavior.
483
+ if (!server._turnTracker) {
484
+ server._turnTracker = new TurnTracker()
485
+ }
486
+ server._turnTracker.record(event.type, event.source, event.sessionId, project)
487
+ const turnInFlight = project
488
+ ? server._turnTracker.anyTurnInFlight(project)
489
+ : (event.sessionId ? server._turnTracker.isInFlight(event.source, event.sessionId) : false)
490
+
491
+ // #5969 (epic #5422 phase 4): keep a point-in-time view of LIVE external
492
+ // sessions so the Control Room mission-control view can render them as
493
+ // read-only entries. Per-(source, sessionId), unlike the per-project
494
+ // counters above — mission control lists individual sessions. Pure
495
+ // observability; the SessionManager helper swallows its own errors.
496
+ server.sessionManager?.recordExternalSessionEvent?.(event.type, event.source, event.sessionId, {
497
+ project,
498
+ cwd: typeof data.cwd === 'string' ? data.cwd : null,
499
+ ts: typeof event.ts === 'number' ? event.ts : undefined,
500
+ })
501
+
502
+ const title = typeof data.title === 'string' && data.title.length > 0 ? data.title : mapping.title
503
+ let notifyBody = typeof data.message === 'string' && data.message.length > 0 ? data.message : mapping.body
504
+ if (event.sessionId) {
505
+ if (event.type === 'subagent_start' || event.type === 'subagent_stop') {
506
+ notifyBody = `${notifyBody} (${activeSubagents} active)`
507
+ } else if (activeSubagents > 0) {
508
+ notifyBody = `${notifyBody} — ${activeSubagents} subagent${activeSubagents === 1 ? '' : 's'} active`
509
+ }
510
+ }
511
+
512
+ // Fire-and-forget: the pipeline owns delivery (category rate limits,
513
+ // prefs, sink retries). A hard sink failure is logged, not surfaced —
514
+ // emitters can't act on it anyway.
515
+ Promise.resolve(
516
+ pushManager.send(mapping.category, title, notifyBody, {
517
+ ...data,
518
+ source: event.source,
519
+ external: true,
520
+ ...(event.sessionId ? { sessionId: event.sessionId } : {}),
521
+ ...(project ? { project } : {}),
522
+ // `subagents` is the key the Discord sink already renders
523
+ // (discord-webhook-sink.js `data.subagents` → embed field).
524
+ ...(event.sessionId ? { subagents: activeSubagents } : {}),
525
+ // #5541: per-project turn-in-flight flag — the Discord sink reads
526
+ // `data.turnInFlight` to decide whether GAP C's idle-hold applies.
527
+ turnInFlight,
528
+ ts: event.ts,
529
+ })
530
+ ).then((ok) => {
531
+ if (ok === false) log.warn(`Ingest event ${event.type} from "${event.source}" failed sink delivery`)
532
+ }).catch((err) => {
533
+ log.warn(`Ingest event ${event.type} dispatch error: ${err?.message || err}`)
534
+ })
535
+
536
+ sendJson(res, 200, { ok: true, category: mapping.category, ...(project ? { project } : {}) })
537
+ } catch (err) {
538
+ log.error(`POST /api/events handler error: ${err?.stack || err}`)
539
+ if (!res.headersSent) {
540
+ try { sendJson(res, 500, { error: 'Internal server error' }) } catch { /* torn down */ }
541
+ } else {
542
+ try { res.end() } catch { /* already ended */ }
543
+ }
544
+ }
545
+ })
546
+ }