@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,414 @@
1
+ /**
2
+ * ExpoPushSink — Expo Push API delivery channel (#5413 Phase 1).
3
+ *
4
+ * Extracted from push.js: everything Expo-specific lives here — the push
5
+ * token registry (with disk persistence and owner ref-counting), token
6
+ * format validation, the HTTPS POST to exp.host with timeout/backoff
7
+ * retry, ticket-based pruning of invalid tokens, and the iOS Live
8
+ * Activity token path.
9
+ *
10
+ * Sink-agnostic gating (category prefs, quiet hours, rate limits) stays
11
+ * upstream in PushManager; the one per-DEVICE concern — "is this category
12
+ * muted on this specific phone?" — is evaluated here per token via the
13
+ * `context` evaluators the pipeline passes to send() (see sink.js for the
14
+ * contract).
15
+ *
16
+ * No Expo account or additional infrastructure required — uses the free
17
+ * Expo Push Service (HTTPS POST to exp.host).
18
+ */
19
+
20
+ import { readFileSync, mkdirSync } from 'node:fs'
21
+ import { dirname } from 'node:path'
22
+ import { writeFileRestricted } from '../platform.js'
23
+ import { createLogger } from '../logger.js'
24
+ import { metrics } from '../metrics.js'
25
+ import { sleep, backoffDelay } from '../utils/sleep.js'
26
+ import { NotificationSink } from './sink.js'
27
+
28
+ const log = createLogger('push')
29
+
30
+ const EXPO_PUSH_URL = 'https://exp.host/--/api/v2/push/send'
31
+
32
+ // Fetch timeout and retry configuration
33
+ const FETCH_TIMEOUT_MS = 10_000
34
+ const MAX_RETRIES = 3
35
+ const BACKOFF_BASE_MS = 1_000
36
+
37
+ /**
38
+ * Fetch with timeout and exponential backoff retry.
39
+ * Retries on 5xx responses and timeout/network errors.
40
+ * Does NOT retry on 4xx client errors.
41
+ */
42
+ async function fetchWithRetry(url, options) {
43
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
44
+ const controller = new AbortController()
45
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS)
46
+
47
+ try {
48
+ const res = await fetch(url, { ...options, signal: controller.signal })
49
+ clearTimeout(timer)
50
+
51
+ if (res.ok || (res.status >= 400 && res.status < 500)) {
52
+ return res
53
+ }
54
+
55
+ // 5xx — retry if attempts remain
56
+ if (attempt < MAX_RETRIES) {
57
+ const delay = backoffDelay(attempt, BACKOFF_BASE_MS)
58
+ log.warn(`Expo API returned ${res.status}, retrying in ${delay}ms (attempt ${attempt}/${MAX_RETRIES})`)
59
+ await sleep(delay)
60
+ continue
61
+ }
62
+
63
+ return res
64
+ } catch (err) {
65
+ clearTimeout(timer)
66
+
67
+ if (attempt < MAX_RETRIES) {
68
+ const delay = backoffDelay(attempt, BACKOFF_BASE_MS)
69
+ log.warn(`Fetch failed (${err.name}: ${err.message}), retrying in ${delay}ms (attempt ${attempt}/${MAX_RETRIES})`)
70
+ await sleep(delay)
71
+ continue
72
+ }
73
+
74
+ throw err
75
+ }
76
+ }
77
+ }
78
+
79
+ // Exported for testing (re-exported from push.js for existing importers)
80
+ export { fetchWithRetry, FETCH_TIMEOUT_MS, MAX_RETRIES, BACKOFF_BASE_MS }
81
+
82
+ export class ExpoPushSink extends NotificationSink {
83
+ constructor({ storagePath } = {}) {
84
+ super({ name: 'expo-push' })
85
+ this._storagePath = storagePath || null
86
+ this.tokens = new Set()
87
+ this._liveActivityTokens = new Set()
88
+ // Owner tracking for session-binding + prune-on-disconnect (audit
89
+ // blocker 6). `_tokenOwners` maps token -> Set<ownerId> so that when
90
+ // a client disconnects we can decrement its ownership and only
91
+ // actually prune the token from `this.tokens` when the last owner
92
+ // goes away. Without ref-counting, two connections registering the
93
+ // same token would cause the first disconnect to strip the token
94
+ // even though the second connection is still active (found by Copilot
95
+ // review on PR #2806). Owner IDs are client connection IDs in
96
+ // production; tests can use any unique string.
97
+ this._tokenOwners = new Map()
98
+ this._loadFromDisk()
99
+ }
100
+
101
+ /** Load tokens from disk if storagePath is set */
102
+ _loadFromDisk() {
103
+ if (!this._storagePath) return
104
+ try {
105
+ const data = JSON.parse(readFileSync(this._storagePath, 'utf-8'))
106
+ // Support legacy format (plain array) and new format (object with keys)
107
+ const pushTokens = Array.isArray(data) ? data : (data.tokens || [])
108
+ const laTokens = Array.isArray(data) ? [] : (data.liveActivityTokens || [])
109
+ for (const token of pushTokens) {
110
+ if (typeof token === 'string' && token.length > 0) {
111
+ this.tokens.add(token)
112
+ }
113
+ }
114
+ for (const token of laTokens) {
115
+ if (typeof token === 'string' && token.length > 0) {
116
+ this._liveActivityTokens.add(token)
117
+ }
118
+ }
119
+ } catch {
120
+ // File missing or corrupt — start with empty set
121
+ }
122
+ }
123
+
124
+ /** Persist current tokens to disk if storagePath is set */
125
+ _persistToDisk() {
126
+ if (!this._storagePath) return
127
+ try {
128
+ mkdirSync(dirname(this._storagePath), { recursive: true })
129
+ writeFileRestricted(this._storagePath, JSON.stringify({
130
+ tokens: [...this.tokens],
131
+ liveActivityTokens: [...this._liveActivityTokens],
132
+ }))
133
+ } catch (err) {
134
+ log.error(`Failed to persist tokens: ${err.message}`)
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Register a push token from a client.
140
+ *
141
+ * Accepts Expo push tokens (`ExponentPushToken[...]`) and FCM tokens
142
+ * (Firebase Cloud Messaging for Android) — both work with the Expo
143
+ * Push API. Rejects obviously-malformed values.
144
+ *
145
+ * Per the 2026-04-11 production readiness audit (blocker 6), the old
146
+ * implementation accepted ANY non-empty string, which let an
147
+ * authenticated attacker register their own `ExponentPushToken[attacker]`
148
+ * and intercept every future permission-prompt push notification. This
149
+ * method now validates the format and (via the caller) binds each
150
+ * registered token to the connection that registered it, so tokens get
151
+ * pruned on client disconnect.
152
+ */
153
+ registerToken(token, ownerId = null) {
154
+ if (typeof token !== 'string' || token.length === 0) {
155
+ log.warn(`Rejected invalid push credential: ${String(token).slice(0, 40)}`)
156
+ return false
157
+ }
158
+ if (!ExpoPushSink.isValidPushTokenFormat(token)) {
159
+ log.warn(`Rejected malformed push credential (unrecognized format): ${token.slice(0, 40)}`)
160
+ return false
161
+ }
162
+ if (!this.tokens.has(token)) {
163
+ this.tokens.add(token)
164
+ this._persistToDisk()
165
+ }
166
+ // Track ownership for ref-counted prune-on-disconnect (2026-04-11
167
+ // audit blocker 6 + Copilot review on PR #2806). Multiple clients
168
+ // may register the same token (reconnect race, multi-device); the
169
+ // token is only pruned when the last owner disconnects.
170
+ if (ownerId != null) {
171
+ let owners = this._tokenOwners.get(token)
172
+ if (!owners) {
173
+ owners = new Set()
174
+ this._tokenOwners.set(token, owners)
175
+ }
176
+ owners.add(ownerId)
177
+ }
178
+ log.info(`Registered push credential ${token.slice(0, 30)}...`)
179
+ return true
180
+ }
181
+
182
+ /**
183
+ * Release one owner's claim on a token. If the last owner goes away,
184
+ * the token is removed from the registry entirely. Returns true if
185
+ * the token was actually pruned (last owner), false if it's still
186
+ * held by someone else.
187
+ *
188
+ * Used by WsServer._handleClientDeparture to prune on disconnect
189
+ * without breaking legitimate multi-connection scenarios.
190
+ */
191
+ releaseTokenOwner(token, ownerId) {
192
+ const owners = this._tokenOwners.get(token)
193
+ if (!owners) {
194
+ // No owner tracking — legacy / test path. Remove unconditionally.
195
+ return this.removeToken(token)
196
+ }
197
+ owners.delete(ownerId)
198
+ if (owners.size === 0) {
199
+ this._tokenOwners.delete(token)
200
+ return this.removeToken(token)
201
+ }
202
+ return false
203
+ }
204
+
205
+ /**
206
+ * Validate a push-token string. This is a soft defense — it rejects
207
+ * obviously-malformed input (empty strings, whitespace, JSON
208
+ * punctuation, URLs) so typos and automated fuzzers don't land in
209
+ * the token set. The REAL defense against push-token hijack is the
210
+ * session-binding + prune-on-disconnect added in the same audit fix
211
+ * (blocker 6): any token registered by a client is tracked on that
212
+ * client's _ownedPushTokens and removed on disconnect.
213
+ *
214
+ * Policy: any non-empty string that is >= 20 characters, free of
215
+ * whitespace/control characters, and free of JSON/URL punctuation
216
+ * that would never appear in a real Expo or FCM token. Real tokens:
217
+ *
218
+ * - Expo: `ExponentPushToken[...]` (50+ chars)
219
+ * - FCM: base64url-ish, ~150 chars typically but as short as 40 in
220
+ * some SDKs
221
+ * - Legacy device tokens via the Firebase-Expo passthrough: variable
222
+ */
223
+ static isValidPushTokenFormat(token) {
224
+ if (typeof token !== 'string') return false
225
+ if (token.length < 20) return false
226
+ // Reject whitespace (including tabs/newlines), quotes, braces,
227
+ // angle brackets, forward slashes, and shell metacharacters that
228
+ // signal the caller sent garbage (a URL, a JSON blob, an error
229
+ // message, a shell-injection attempt) rather than a real push
230
+ // token. Real Expo/FCM push tokens use only alphanumerics + a
231
+ // restricted set of punctuation ([_-.:~%]) — the characters in
232
+ // this reject list never appear in them.
233
+ if (/[\s"'`<>{}&|;/\\?#]/.test(token)) return false
234
+ return true
235
+ }
236
+
237
+ /**
238
+ * Remove a push token unconditionally. Most callers should use
239
+ * releaseTokenOwner() instead so multi-owner tokens aren't stripped
240
+ * when one connection drops.
241
+ */
242
+ removeToken(token) {
243
+ if (this.tokens.delete(token)) {
244
+ this._tokenOwners.delete(token)
245
+ this._persistToDisk()
246
+ return true
247
+ }
248
+ return false
249
+ }
250
+
251
+ /**
252
+ * Register a Live Activity push token (iOS).
253
+ * Stored separately from regular push tokens.
254
+ *
255
+ * Applies the same format check as registerToken so the Live Activity
256
+ * path can't be used as a bypass for the 2026-04-11 audit blocker 6
257
+ * hardening. No WS handler currently exposes this path (verified on
258
+ * PR #2806) but the check is cheap regression prevention.
259
+ */
260
+ registerLiveActivityToken(token) {
261
+ if (typeof token !== 'string' || token.length === 0) {
262
+ log.warn(`Rejected invalid Live Activity credential: ${String(token).slice(0, 40)}`)
263
+ return false
264
+ }
265
+ if (!ExpoPushSink.isValidPushTokenFormat(token)) {
266
+ log.warn(`Rejected malformed Live Activity credential (unrecognized format): ${token.slice(0, 40)}`)
267
+ return false
268
+ }
269
+ if (!this._liveActivityTokens.has(token)) {
270
+ this._liveActivityTokens.add(token)
271
+ this._persistToDisk()
272
+ }
273
+ log.info(`Registered Live Activity credential ${token.slice(0, 30)}...`)
274
+ return true
275
+ }
276
+
277
+ /** Remove a Live Activity push token */
278
+ unregisterLiveActivityToken(token) {
279
+ if (this._liveActivityTokens.delete(token)) {
280
+ this._persistToDisk()
281
+ }
282
+ }
283
+
284
+ /** Check if we have any registered tokens */
285
+ get hasTokens() {
286
+ return this.tokens.size > 0
287
+ }
288
+
289
+ /** Check if we have any registered Live Activity tokens */
290
+ get hasLiveActivityTokens() {
291
+ return this._liveActivityTokens.size > 0
292
+ }
293
+
294
+ /** Sink contract: configured iff at least one push token is registered */
295
+ isConfigured() {
296
+ return this.tokens.size > 0
297
+ }
298
+
299
+ /**
300
+ * Sink contract: deliver one approved notification to every registered
301
+ * token, applying the per-DEVICE prefs evaluators from `context` (#4542
302
+ * per-category mute + #4544 quiet-hours gate, evaluated PER TOKEN so a
303
+ * desktop and a phone with different prefs both get the right behaviour
304
+ * from a single pipeline call). The quiet-hours gate is conditional: a
305
+ * category in the device's bypass list (default permission +
306
+ * activity_error) still fires even at 3am. Missing evaluators fail open
307
+ * (see sink.js).
308
+ */
309
+ async send(notification, context = {}) {
310
+ const { category, title, body, data = {}, categoryId } = notification
311
+ const now = context.now ?? Date.now()
312
+ const isCategoryEnabled = context.isCategoryEnabled ?? (() => true)
313
+ const isInQuietHours = context.isInQuietHours ?? (() => false)
314
+ const shouldBypassQuietHours = context.shouldBypassQuietHours ?? (() => false)
315
+
316
+ const eligibleTokens = []
317
+ for (const token of this.tokens) {
318
+ if (!isCategoryEnabled(category, token)) continue
319
+ if (isInQuietHours(now, token) && !shouldBypassQuietHours(category, token)) continue
320
+ eligibleTokens.push(token)
321
+ }
322
+ if (eligibleTokens.length === 0) {
323
+ // Every token filtered — no Expo POST. Returning `true` matches the
324
+ // existing "nothing to send is not a failure" contract.
325
+ return true
326
+ }
327
+
328
+ const messages = eligibleTokens.map((token) => ({
329
+ to: token,
330
+ sound: 'default',
331
+ title,
332
+ body,
333
+ data: { ...data, category },
334
+ ...(categoryId && { categoryId }),
335
+ }))
336
+
337
+ return await this._sendToTokenSet(this.tokens, messages, category, 'notification')
338
+ }
339
+
340
+ /**
341
+ * Send a Live Activity update to all registered Live Activity tokens.
342
+ * Expo-only side channel — not part of the NotificationSink contract
343
+ * (rate limiting for it stays upstream in PushManager).
344
+ * @param {string} state - Current activity state (e.g. 'thinking', 'writing', 'idle')
345
+ * @param {string} detail - Human-readable detail text
346
+ */
347
+ async sendLiveActivityUpdate(state, detail) {
348
+ const messages = [...this._liveActivityTokens].map((token) => ({
349
+ to: token,
350
+ sound: 'default',
351
+ title: 'Live Activity',
352
+ body: detail,
353
+ data: { state, detail, category: 'live_activity' },
354
+ }))
355
+
356
+ await this._sendToTokenSet(this._liveActivityTokens, messages, 'live_activity', 'update')
357
+ }
358
+
359
+ /**
360
+ * Post messages to the Expo Push API and prune any tokens that come back
361
+ * with an error status. Shared by send() and sendLiveActivityUpdate().
362
+ *
363
+ * @param {Set<string>} tokenSet - The Set to prune invalid tokens from
364
+ * @param {object[]} messages - Pre-built Expo push message objects
365
+ * @param {string} category - Category label used in log output
366
+ * @param {string} logLabel - Human-readable label for log messages (e.g. 'notification', 'Live Activity update')
367
+ * @returns {Promise<boolean>} `true` if Expo accepted the post (even when
368
+ * individual tokens came back with per-message errors — those are
369
+ * handled by pruning, not by reporting hard failure). `false` when the
370
+ * HTTPS POST itself failed (non-2xx, network/timeout caught here).
371
+ * Surfacing this lets callers (#3870) release per-session dedupe
372
+ * latches on real delivery failure so the next idle cycle can retry.
373
+ */
374
+ async _sendToTokenSet(tokenSet, messages, category, logLabel) {
375
+ try {
376
+ const res = await fetchWithRetry(EXPO_PUSH_URL, {
377
+ method: 'POST',
378
+ headers: { 'Content-Type': 'application/json' },
379
+ body: JSON.stringify(messages),
380
+ })
381
+
382
+ if (!res.ok) {
383
+ metrics.inc('push.failures')
384
+ log.error(`Expo Push API returned ${res.status}`)
385
+ return false
386
+ }
387
+
388
+ const result = await res.json()
389
+
390
+ // Prune tokens that returned errors (invalid/expired)
391
+ let pruned = false
392
+ if (result.data) {
393
+ for (let i = 0; i < result.data.length; i++) {
394
+ const ticket = result.data[i]
395
+ if (ticket.status === 'error') {
396
+ const token = messages[i].to
397
+ log.warn(`Removing invalid push credential ${token.slice(0, 30)}... (${ticket.message})`)
398
+ tokenSet.delete(token)
399
+ pruned = true
400
+ }
401
+ }
402
+ }
403
+ if (pruned) this._persistToDisk()
404
+
405
+ metrics.inc('push.sent')
406
+ log.info(`Sent ${category} ${logLabel} to ${messages.length} device(s)`)
407
+ return true
408
+ } catch (err) {
409
+ metrics.inc('push.failures')
410
+ log.error(`Failed to send ${logLabel}: ${err.message}`)
411
+ return false
412
+ }
413
+ }
414
+ }
@@ -0,0 +1,177 @@
1
+ /**
2
+ * #5438 — ready-for-input notification body, enriched with the #5436
3
+ * background-task snapshot.
4
+ *
5
+ * The idle push ("session finished a turn, waiting on you") is composed once
6
+ * in PushNotificationHandler and fans out through PushManager to every sink:
7
+ * the Expo sink delivers `body` as the OS notification text, and the
8
+ * DiscordWebhookSink renders `notification.body` as its status embed's
9
+ * Status field. Enriching the body HERE is therefore the single point that
10
+ * covers both sinks — no per-sink special-casing.
11
+ *
12
+ * Snapshot contract (mirrors the `claude_ready` wire fields from #5436):
13
+ * - absent (null/undefined) = no information → today's plain body
14
+ * - present, even `{ backgroundTasks: [] }`, = authoritative → an empty
15
+ * snapshot also yields the plain body (nothing outstanding to surface)
16
+ *
17
+ * Wording is kept consistent with the dashboard ActivityIndicator chips
18
+ * (#5436): most-recent task by `startedAt`, `description || toolUseId`
19
+ * detail, `+N more` overflow — and the same priority order: outstanding
20
+ * tasks win over an armed wakeup, because a still-running watcher is the
21
+ * thing the user is most likely waiting on (the wakeup will re-busy the
22
+ * session on its own anyway).
23
+ *
24
+ * Wakeup time is rendered RELATIVE ("resumes in 12m"), not as a clock time
25
+ * (#5474). The push body is delivered to an OS tray / Discord embed with no
26
+ * timezone context, and chroxy may run in a different zone than the viewer
27
+ * (e.g. a UTC container vs. an AEST user) — an absolute HH:MM in the server's
28
+ * zone misleads. A relative offset is timezone- and DST-proof, and reads
29
+ * naturally in a notification tray. (The dashboard chip keeps "Resumes at
30
+ * HH:MM" — its `getHours()` runs in the *browser*, i.e. viewer-local, so it
31
+ * is correct as-is; only the push body needed fixing.)
32
+ */
33
+
34
+ /** Today's plain idle-push body — unchanged when the snapshot has nothing. */
35
+ export const DEFAULT_READY_BODY = 'Ready for next message'
36
+
37
+ // Practical ceiling for push-notification bodies: iOS/Android tray text and
38
+ // the Expo payload both render ~1-2 lines; past ~140 chars the tail is never
39
+ // visible. The Discord embed field has its own 1000-char truncate, so this
40
+ // shared clamp is the binding one.
41
+ export const READY_BODY_MAX_LENGTH = 140
42
+
43
+ // Task descriptions and wakeup reasons come from the session transcript's
44
+ // tool_use input — model-authored text, NOT raw PTY bytes. Newlines are
45
+ // routine (the scanner's Agent fallback is `prompt.slice(0, 80)`, and
46
+ // prompts are usually multi-line); embedded escape/control bytes are
47
+ // implausible but cheap to defend against. Push trays and the Discord
48
+ // Status field render the body as flowed text, so: drop ANSI CSI/ESC
49
+ // sequences outright, turn remaining C0/C1 controls into spaces, then
50
+ // collapse all whitespace to single spaces.
51
+ function sanitizeDetail(text) {
52
+ return String(text)
53
+ .replace(/\u001b\[[0-9;?]*[ -\/]*[@-~]/g, '') // ANSI CSI sequences
54
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') // remaining C0/C1 controls
55
+ .replace(/\s+/g, ' ')
56
+ .trim()
57
+ }
58
+
59
+ /**
60
+ * Clamp `detail` so `prefix + detail + suffix` fits READY_BODY_MAX_LENGTH.
61
+ * The suffix (`+N more`) always survives — it carries the "there is more
62
+ * going on than this one line" signal that a blind tail-truncate would eat.
63
+ */
64
+ function clampDetail(prefix, detail, suffix = '') {
65
+ const budget = READY_BODY_MAX_LENGTH - prefix.length - suffix.length
66
+ if (detail.length > budget) {
67
+ let cut = detail.slice(0, Math.max(0, budget - 1))
68
+ // Never cut through a surrogate pair — a half emoji is an ill-formed
69
+ // string in the push/Discord JSON payload (renders as U+FFFD at best).
70
+ if (/[\uD800-\uDBFF]$/.test(cut)) cut = cut.slice(0, -1)
71
+ detail = `${cut}…`
72
+ }
73
+ return `${prefix}${detail}${suffix}`
74
+ }
75
+
76
+ /**
77
+ * Format the gap from `now` to a future wakeup `at` (both epoch ms) as a short
78
+ * relative offset for the push body — timezone- and DST-proof (#5474).
79
+ *
80
+ * Units climb sensibly so the string stays compact under the 140-char clamp:
81
+ * - < 60s → "<1m" (sub-minute precision isn't useful in a tray)
82
+ * - 1–89 minutes → "Nm" (e.g. "12m")
83
+ * - ≥ 90 minutes → "Hh" / "HhMm" (e.g. "2h", "2h05m")
84
+ *
85
+ * Returns null when `at` is non-finite or already in the past (the caller then
86
+ * degrades to the plain body — an offset of "in 0m" / a negative value would
87
+ * be noise, and a stale wakeup carries no useful "resumes in" signal).
88
+ */
89
+ function formatRelativeWakeup(at, now) {
90
+ if (!Number.isFinite(at) || !Number.isFinite(now)) return null
91
+ const deltaMs = at - now
92
+ if (deltaMs <= 0) return null
93
+
94
+ // Compare the raw deltaMs against each boundary and FLOOR the minute
95
+ // conversion — never round. Rounding `deltaMs/1000` (or seconds/60) can push
96
+ // a value across a branch boundary it hasn't actually reached: 59.6s would
97
+ // round to 60s and render "1m" instead of the documented "<1m", and 89.5m
98
+ // would round to 90m and switch to the hours format before the real 90m
99
+ // mark. Flooring honours "<60s" and "<90m" precisely, and — because
100
+ // totalMinutes never reaches the next-hour value early — keeps the h+m branch
101
+ // self-consistent (e.g. 1h59m30s → "1h59m", never "1h60m"/"2h0m").
102
+ if (deltaMs < 60_000) return '<1m'
103
+
104
+ const totalMinutes = Math.floor(deltaMs / 60_000)
105
+ if (totalMinutes < 90) return `${totalMinutes}m`
106
+
107
+ const hours = Math.floor(totalMinutes / 60)
108
+ const minutes = totalMinutes % 60
109
+ return minutes === 0 ? `${hours}h` : `${hours}h${String(minutes).padStart(2, '0')}m`
110
+ }
111
+
112
+ /**
113
+ * Compose the idle-push body from a background-task snapshot.
114
+ *
115
+ * @param {{ backgroundTasks?: Array<{toolUseId:string, description?:string, startedAt?:number}>,
116
+ * scheduledWakeup?: { at:number, reason?:string } | null } | null | undefined} snapshot
117
+ * Output of `getBackgroundTaskSnapshot()` (#5436), or null when the session
118
+ * type doesn't expose one / the transcript scan degraded.
119
+ * @param {number} [now] Reference epoch ms for the relative wakeup offset —
120
+ * defaults to `Date.now()`. Parameterized so tests can pin the offset against
121
+ * a fixed `at` without freezing the global clock.
122
+ * @returns {string} the notification body — DEFAULT_READY_BODY when there is
123
+ * nothing outstanding, otherwise the enriched still-watching / resumes-in
124
+ * line, clamped to READY_BODY_MAX_LENGTH.
125
+ */
126
+ export function composeReadyNotificationBody(snapshot, now = Date.now()) {
127
+ if (!snapshot || typeof snapshot !== 'object') return DEFAULT_READY_BODY
128
+
129
+ const tasks = Array.isArray(snapshot.backgroundTasks) ? snapshot.backgroundTasks : []
130
+ if (tasks.length > 0) {
131
+ // Most recent task by startedAt — same pick as the dashboard chip.
132
+ let newest = tasks[0]
133
+ for (let i = 1; i < tasks.length; i++) {
134
+ if ((tasks[i]?.startedAt ?? 0) > (newest?.startedAt ?? 0)) newest = tasks[i]
135
+ }
136
+ // Sanitize each candidate BEFORE the fallback chain so a whitespace-only
137
+ // description still falls through to the toolUseId.
138
+ const detail =
139
+ sanitizeDetail(newest?.description ?? '') ||
140
+ sanitizeDetail(newest?.toolUseId ?? '') ||
141
+ 'background task'
142
+ const suffix = tasks.length > 1 ? ` +${tasks.length - 1} more` : ''
143
+ return clampDetail('Ready for input — still watching: ', detail, suffix)
144
+ }
145
+
146
+ const wakeup = snapshot.scheduledWakeup
147
+ if (wakeup && typeof wakeup === 'object') {
148
+ // Relative offset, not an absolute clock time (#5474): the body has no
149
+ // timezone context and the server may run in a different zone than the
150
+ // viewer. A past/unparsable `at` degrades to the plain body, exactly as a
151
+ // NaN time did before.
152
+ const rel = formatRelativeWakeup(Number(wakeup.at), now)
153
+ if (rel === null) return DEFAULT_READY_BODY
154
+ const reason = sanitizeDetail(typeof wakeup.reason === 'string' ? wakeup.reason : '')
155
+ if (!reason) return `Ready for input — resumes in ${rel}`
156
+ return clampDetail(`Ready for input — resumes in ${rel}: `, reason)
157
+ }
158
+
159
+ return DEFAULT_READY_BODY
160
+ }
161
+
162
+ /**
163
+ * Read a session's background-task snapshot for notification enrichment.
164
+ * Returns null (= "no information", body unchanged) when the session type
165
+ * doesn't implement `getBackgroundTaskSnapshot()` or the read throws —
166
+ * the same degrade-to-plain-ready posture as event-normalizer's
167
+ * backgroundTaskFields().
168
+ */
169
+ export function readBackgroundTaskSnapshot(session) {
170
+ try {
171
+ return typeof session?.getBackgroundTaskSnapshot === 'function'
172
+ ? session.getBackgroundTaskSnapshot()
173
+ : null
174
+ } catch {
175
+ return null
176
+ }
177
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * SinkRegistry — holds the configured NotificationSinks and fans one
3
+ * notification out to all of them (#5413 Phase 1).
4
+ *
5
+ * This is the pipeline's fan-out point: PushManager applies the shared
6
+ * gating (category prefs, quiet hours, rate limits) ONCE, then hands the
7
+ * approved notification here. Today the registry holds a single
8
+ * ExpoPushSink; DiscordWebhookSink registers alongside it in Phase 2 with
9
+ * no pipeline changes.
10
+ *
11
+ * Semantics:
12
+ * - Unconfigured sinks (isConfigured() === false) are skipped entirely —
13
+ * they are never asked to send.
14
+ * - Sinks are invoked sequentially in registration order (deterministic;
15
+ * revisit if a slow sink ever needs to stop delaying the others).
16
+ * - fanOut resolves `true` when every configured sink resolved `true`
17
+ * (including the no-configured-sinks case), `false` when ANY configured
18
+ * sink hard-failed. One failing sink does not prevent the others from
19
+ * receiving the notification.
20
+ * - A sink that throws (contract violation — sinks must catch their own
21
+ * delivery errors) is logged and treated as a hard failure, so a buggy
22
+ * sink can't take the pipeline down.
23
+ */
24
+
25
+ export class SinkRegistry {
26
+ constructor({ logger = null } = {}) {
27
+ this._sinks = []
28
+ this._log = logger
29
+ }
30
+
31
+ /**
32
+ * Register a sink. Validates the minimal contract shape up front so a
33
+ * malformed sink fails at wiring time, not on the first notification.
34
+ */
35
+ register(sink) {
36
+ if (!sink || typeof sink.send !== 'function' || typeof sink.isConfigured !== 'function') {
37
+ throw new TypeError('SinkRegistry.register: sink must implement send() and isConfigured()')
38
+ }
39
+ if (typeof sink.name !== 'string' || sink.name.length === 0) {
40
+ throw new TypeError('SinkRegistry.register: sink must have a non-empty name')
41
+ }
42
+ this._sinks.push(sink)
43
+ return sink
44
+ }
45
+
46
+ /** Snapshot of registered sinks (registration order). */
47
+ get sinks() {
48
+ return [...this._sinks]
49
+ }
50
+
51
+ /**
52
+ * True when at least one registered sink is currently configured.
53
+ * A throwing isConfigured() is the same contract-violation class fanOut
54
+ * contains for send() — treat that sink as not configured rather than
55
+ * letting the probe take the caller down.
56
+ */
57
+ hasConfigured() {
58
+ return this._sinks.some((sink) => {
59
+ try {
60
+ return sink.isConfigured()
61
+ } catch (err) {
62
+ this._log?.error?.(`Sink '${sink.name}' threw during isConfigured: ${err?.message || err}`)
63
+ return false
64
+ }
65
+ })
66
+ }
67
+
68
+ /**
69
+ * Fan one approved notification out to every configured sink.
70
+ * @param {{ category: string, title: string, body: string, data?: object, categoryId?: string }} notification
71
+ * @param {object} [context] - Pipeline-supplied evaluators (see sink.js)
72
+ * @returns {Promise<boolean>} `true` iff no configured sink hard-failed
73
+ */
74
+ async fanOut(notification, context = {}) {
75
+ let ok = true
76
+ for (const sink of this._sinks) {
77
+ try {
78
+ // isConfigured() inside the containment too: a throwing probe
79
+ // (same contract-violation class as a throwing send) must not
80
+ // reject the whole fan-out — PushManager.send() is called
81
+ // un-awaited at several sites (e.g. ws-permissions), so an
82
+ // escaped rejection becomes an unhandledRejection.
83
+ if (!sink.isConfigured()) continue
84
+ // Only an explicit `false` counts as a hard failure — `undefined`
85
+ // (a sink with a void success path) is success. This is the
86
+ // documented sink contract, not an oversight.
87
+ const result = await sink.send(notification, context)
88
+ if (result === false) ok = false
89
+ } catch (err) {
90
+ // Contract violation — sinks must resolve false on delivery
91
+ // failure, not throw. Contain it so the other sinks still deliver.
92
+ this._log?.error?.(`Sink '${sink.name}' threw during send or isConfigured: ${err?.message || err}`)
93
+ ok = false
94
+ }
95
+ }
96
+ return ok
97
+ }
98
+ }