@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,544 @@
1
+ /**
2
+ * Notification preferences store (#4541, extended in #4544).
3
+ *
4
+ * Foundation for user-controllable notification settings (parent #4349).
5
+ * Persists per-category and per-device toggles, plus a quiet-hours window
6
+ * with timezone enforcement and a bypass-category list (#4544 — the actual
7
+ * time-of-day check; #4541 only persisted the window).
8
+ *
9
+ * On-disk shape (~/.chroxy/notification-prefs.json, mode 0600):
10
+ *
11
+ * {
12
+ * "categories": { // global defaults — apply to every device
13
+ * "permission": true,
14
+ * "result": true,
15
+ * "activity_update": true,
16
+ * "activity_waiting": true,
17
+ * "activity_error": true,
18
+ * "inactivity_warning": true,
19
+ * "live_activity": true
20
+ * },
21
+ * "devices": { // per-device overrides keyed by push token
22
+ * "ExponentPushToken[abc]": {
23
+ * "categories": { "result": false },
24
+ * "quietHours": { "start": "23:00", "end": "06:00", "timezone": "America/Los_Angeles" },
25
+ * "bypassCategories": ["permission"]
26
+ * }
27
+ * },
28
+ * "quietHours": { "start": "22:00", "end": "07:00", "timezone": "America/Los_Angeles" } | null,
29
+ * "bypassCategories": ["permission", "activity_error"] // categories that fire even during quiet hours
30
+ * }
31
+ *
32
+ * Decision precedence (resolveCategoryDecision):
33
+ * 1. per-device override (if pushToken is known and has an entry)
34
+ * 2. global default (categories.<name>)
35
+ * 3. fail-open `true` (unknown category — defensive lower-bound rate limits
36
+ * in push.js still apply)
37
+ *
38
+ * Quiet-hours precedence (resolveQuietHoursWindow / resolveBypassCategories):
39
+ * - Per-device REPLACES the global value entirely. A device with
40
+ * `quietHours: null` opts out of muting even if the global window is set;
41
+ * a device with `bypassCategories: []` opts out of every bypass even if
42
+ * the global list includes them.
43
+ * - Rationale (per #4544 design notes): replace is simpler than shadow
44
+ * because the user can express "this phone is special — here is its
45
+ * entire policy" without having to mentally diff against the global
46
+ * window.
47
+ *
48
+ * The defensive RATE_LIMITS gate in push.js stays in place — user prefs can
49
+ * only further mute notifications, never override the spam ceiling.
50
+ *
51
+ * Atomic writes: temp + rename + cleanup-on-failure, mirroring
52
+ * `byok-mcp-trust.js`. No mutex is needed (a single PushManager owns the
53
+ * file per process), but rename failures still clean up the .tmp file
54
+ * (#4463 pattern).
55
+ */
56
+
57
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, chmodSync, unlinkSync } from 'node:fs'
58
+ import { homedir } from 'node:os'
59
+ import { join, dirname } from 'node:path'
60
+
61
+ /**
62
+ * Authoritative category list. MUST stay in sync with the keys of
63
+ * `RATE_LIMITS` in `push.js` — these are the categories the server can
64
+ * fire today. The schema-coverage test asserts every category has a
65
+ * default.
66
+ *
67
+ * History: the issue text (#4541) sketches `permission / question / error /
68
+ * result / inactivity` as user-facing labels; the wire-level set below is
69
+ * the actual server-emitted categories (the UI in sub-issues #4542/#4543
70
+ * can map these to friendlier labels without changing the protocol).
71
+ */
72
+ export const ALL_CATEGORIES = Object.freeze([
73
+ 'permission',
74
+ 'result',
75
+ 'activity_update',
76
+ 'activity_waiting',
77
+ 'activity_error',
78
+ 'inactivity_warning',
79
+ 'live_activity',
80
+ // #5413 Phase 3: external-session categories fed by POST /api/events.
81
+ // Listed here so they are mutable in prefs and visible in snapshots —
82
+ // sanitizeCategoryMap strips unknown keys, so omitting them would make
83
+ // external-session pushes permanently un-mutable (#5432 review C1).
84
+ 'session_online',
85
+ 'session_offline',
86
+ 'session_activity',
87
+ // #5828: billing-canary warnings (silent metered default; reclassification
88
+ // trip; opt-in datacenter egress). Listed so they are mutable in prefs and
89
+ // visible in snapshots; sanitizeCategoryMap would otherwise strip them as unknown.
90
+ 'billing_warning',
91
+ // Mailbox live-interrupt: "new mail" pings fed by POST /api/mailbox
92
+ // (mailbox-route.js). Listed so the category is mutable in prefs and visible
93
+ // in snapshots (sanitizeCategoryMap strips unknown keys otherwise).
94
+ 'mailbox',
95
+ ])
96
+
97
+ /**
98
+ * Default category state for a fresh install: every category enabled.
99
+ * Pre-#4541 behaviour was "always fire (modulo RATE_LIMITS)", so defaulting
100
+ * everything to `true` preserves that contract for users who never touch
101
+ * Settings.
102
+ */
103
+ export const CATEGORY_DEFAULTS = Object.freeze(
104
+ Object.fromEntries(ALL_CATEGORIES.map((c) => [c, true]))
105
+ )
106
+
107
+ /**
108
+ * Categories that bypass quiet hours when no explicit override is set (#4544).
109
+ *
110
+ * Rationale: `permission` blocks the agent until the operator decides — if it
111
+ * gets muted by quiet hours the agent stalls indefinitely. `activity_error`
112
+ * surfaces crashes/tunnel drops/fatal session failures and demands operator
113
+ * attention in the same way. Anything else (completion pings, activity
114
+ * updates, inactivity warnings) is exactly what quiet hours is for, so it
115
+ * stays muted by default.
116
+ *
117
+ * Users can opt out per-device (`bypassCategories: []`) or extend the
118
+ * global list to silence even errors if they want.
119
+ */
120
+ export const DEFAULT_BYPASS_CATEGORIES = Object.freeze(['permission', 'activity_error'])
121
+
122
+ const _ALL_CATEGORIES_SET = new Set(ALL_CATEGORIES)
123
+ // Two-digit zero-padded HH:MM with HH in 00-23 and MM in 00-59 (#4566).
124
+ // The narrower regex replaces the older `/^\d{2}:\d{2}$/`, which accepted
125
+ // out-of-range values like `25:99` and let a hand-edited typo land in the
126
+ // in-memory prefs before fail-opening at gate-eval time.
127
+ const _HHMM_RE = /^(?:[01]\d|2[0-3]):[0-5]\d$/
128
+
129
+ export function defaultNotificationPrefsPath() {
130
+ return process.env.CHROXY_NOTIFICATION_PREFS_PATH || join(homedir(), '.chroxy', 'notification-prefs.json')
131
+ }
132
+
133
+ /**
134
+ * Build a fresh prefs object using the documented defaults. Pure — never
135
+ * touches disk. Used by loadPrefs (when no file) and as the seed for
136
+ * shallow-merge during setPrefs patches.
137
+ */
138
+ export function defaultPrefs() {
139
+ return {
140
+ categories: { ...CATEGORY_DEFAULTS },
141
+ devices: {},
142
+ quietHours: null,
143
+ // Default to the documented bypass list. `setPrefs` accepts an empty
144
+ // array to override (user explicitly says "nothing bypasses, even
145
+ // errors"), and a missing key keeps the default.
146
+ bypassCategories: [...DEFAULT_BYPASS_CATEGORIES],
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Strip any keys outside ALL_CATEGORIES and coerce non-boolean values to
152
+ * the default. A hand-edited prefs file with a typo (`resut: false`)
153
+ * should not silently break — drop the unknown key and warn at the
154
+ * read site.
155
+ */
156
+ function sanitizeCategoryMap(raw) {
157
+ if (!raw || typeof raw !== 'object') return {}
158
+ const out = {}
159
+ for (const [key, value] of Object.entries(raw)) {
160
+ if (!_ALL_CATEGORIES_SET.has(key)) continue
161
+ if (typeof value === 'boolean') out[key] = value
162
+ }
163
+ return out
164
+ }
165
+
166
+ /**
167
+ * Sanitize the on-disk `devices` map. Drops malformed entries silently —
168
+ * a corrupt per-device override should not break notifications for every
169
+ * other device.
170
+ *
171
+ * #4544: per-device entries may now carry `quietHours` and
172
+ * `bypassCategories` in addition to `categories`. `quietHours` retains
173
+ * its tri-state semantics: `undefined` = inherit global, `null` = opt out
174
+ * of muting on this device, `{ start, end, timezone }` = device-specific
175
+ * window.
176
+ */
177
+ function sanitizeDevices(raw, { log } = {}) {
178
+ if (!raw || typeof raw !== 'object') return {}
179
+ const out = {}
180
+ for (const [token, entry] of Object.entries(raw)) {
181
+ if (typeof token !== 'string' || token.length === 0) continue
182
+ if (!entry || typeof entry !== 'object') continue
183
+ const cleaned = { categories: sanitizeCategoryMap(entry.categories) }
184
+ // Tri-state: present-as-null means "explicitly disable muting on this
185
+ // device"; present-as-window means "use this window"; absent means
186
+ // "fall back to global". hasOwnProperty distinguishes absent from null.
187
+ if (Object.prototype.hasOwnProperty.call(entry, 'quietHours')) {
188
+ cleaned.quietHours = sanitizeQuietHours(entry.quietHours)
189
+ // #4566: surface a typo on a per-device window — the original block
190
+ // existed on disk but failed range/shape validation, so the device
191
+ // silently inherits "no muting" (null). Warn so the operator notices
192
+ // rather than discovering it the next time a notification fires
193
+ // outside their expected window.
194
+ if (cleaned.quietHours === null && entry.quietHours !== null) {
195
+ log?.warn?.(`notification-prefs: device ${token} quietHours rejected (invalid shape or out-of-range HH:MM)`)
196
+ }
197
+ }
198
+ if (Object.prototype.hasOwnProperty.call(entry, 'bypassCategories')) {
199
+ const bypass = sanitizeBypassList(entry.bypassCategories)
200
+ if (bypass !== null) cleaned.bypassCategories = bypass
201
+ }
202
+ // #4587: non-critical metadata for the per-device list UI. Operators
203
+ // need to tell orphan entries apart before clicking Clear — the truncated
204
+ // token alone is opaque. Strict type/range guards; no log warns
205
+ // because a malformed metadata field should never affect notification
206
+ // delivery (it just degrades the UI hint).
207
+ if (typeof entry.lastSeenAt === 'number' && Number.isFinite(entry.lastSeenAt) && entry.lastSeenAt > 0) {
208
+ cleaned.lastSeenAt = entry.lastSeenAt
209
+ }
210
+ if (typeof entry.platform === 'string' && entry.platform.length > 0 && entry.platform.length <= 32) {
211
+ cleaned.platform = entry.platform
212
+ }
213
+ out[token] = cleaned
214
+ }
215
+ return out
216
+ }
217
+
218
+ /**
219
+ * Sanitize the quiet-hours window (#4544, tightened #4566).
220
+ *
221
+ * Requires `start`, `end`, AND `timezone` to all be present and well-formed
222
+ * — a window without a timezone cannot be evaluated at the gate (see
223
+ * `isInQuietHoursIn`'s fail-open behaviour), so we refuse to load a
224
+ * half-shape that would silently mis-mute later.
225
+ *
226
+ * `start`/`end` must match the two-digit zero-padded `HH:MM` form with
227
+ * `HH` in 00-23 and `MM` in 00-59 (#4566). The previous regex
228
+ * (`/^\d{2}:\d{2}$/`) accepted out-of-range values like `25:99`, which
229
+ * survived the loader and silently fail-opened at gate-eval time; the
230
+ * stricter pattern in `_HHMM_RE` rejects those at load. Returning `null`
231
+ * here triggers a `log.warn` in `loadPrefs` so the typo surfaces.
232
+ *
233
+ * The IANA timezone is validated by constructing a `DateTimeFormat` with
234
+ * the requested zone — Node throws `RangeError` for unknown zones, which
235
+ * we catch and treat as a malformed window.
236
+ */
237
+ function sanitizeQuietHours(raw) {
238
+ if (raw === null) return null
239
+ if (!raw || typeof raw !== 'object') return null
240
+ if (typeof raw.start !== 'string' || typeof raw.end !== 'string') return null
241
+ if (!_HHMM_RE.test(raw.start) || !_HHMM_RE.test(raw.end)) return null
242
+ if (typeof raw.timezone !== 'string' || raw.timezone.length === 0) return null
243
+ try {
244
+ // Throws if the timezone is unrecognised.
245
+ new Intl.DateTimeFormat('en-US', { timeZone: raw.timezone })
246
+ } catch {
247
+ return null
248
+ }
249
+ return { start: raw.start, end: raw.end, timezone: raw.timezone }
250
+ }
251
+
252
+ /**
253
+ * Sanitize the bypass-categories list (#4544).
254
+ *
255
+ * Returns `null` when the input is missing entirely (caller distinguishes
256
+ * absent from empty-array via `null`). Returns an array of unique
257
+ * non-empty strings otherwise — non-string entries are dropped silently
258
+ * so a corrupted file doesn't break the gate. We intentionally do NOT
259
+ * whitelist against `ALL_CATEGORIES` here so a forward-compatible install
260
+ * (older binary, newer prefs file mentioning a category the binary hasn't
261
+ * shipped yet) preserves the stored value.
262
+ */
263
+ function sanitizeBypassList(raw) {
264
+ if (raw == null) return null
265
+ if (!Array.isArray(raw)) return []
266
+ const seen = new Set()
267
+ for (const item of raw) {
268
+ if (typeof item !== 'string') continue
269
+ const trimmed = item.trim()
270
+ if (trimmed.length === 0) continue
271
+ seen.add(trimmed)
272
+ }
273
+ return [...seen]
274
+ }
275
+
276
+ /**
277
+ * Load and merge prefs from disk over the documented defaults. A missing
278
+ * file is normal (first run) — returns defaults. A malformed file falls
279
+ * back to defaults with a warn log so the user notices but pushes keep
280
+ * working.
281
+ */
282
+ export function loadPrefs(filePath = defaultNotificationPrefsPath(), { log } = {}) {
283
+ const base = defaultPrefs()
284
+ if (!existsSync(filePath)) return base
285
+ try {
286
+ const raw = JSON.parse(readFileSync(filePath, 'utf8'))
287
+ // bypassCategories: explicit on-disk array overrides defaults; absent
288
+ // key keeps defaults. A read-side `null` (corruption / hand-edit) is
289
+ // coerced to defaults so the gate never misbehaves.
290
+ let bypass = base.bypassCategories
291
+ if (Object.prototype.hasOwnProperty.call(raw ?? {}, 'bypassCategories')) {
292
+ const cleaned = sanitizeBypassList(raw.bypassCategories)
293
+ bypass = cleaned ?? [...DEFAULT_BYPASS_CATEGORIES]
294
+ }
295
+ const cleanedQuietHours = sanitizeQuietHours(raw?.quietHours)
296
+ // #4566: warn when the on-disk file carried a quietHours block but it
297
+ // failed validation. The pre-#4566 behaviour silently dropped the bad
298
+ // window and the operator believed quiet-hours were active. We skip
299
+ // the warn for `null` (explicit "no quiet hours") and for "key absent"
300
+ // — only a present, non-null, rejected block deserves the signal.
301
+ const rawQuietHours = raw?.quietHours
302
+ if (
303
+ cleanedQuietHours === null &&
304
+ rawQuietHours !== null &&
305
+ rawQuietHours !== undefined
306
+ ) {
307
+ log?.warn?.(`notification-prefs ${filePath} quietHours rejected (invalid shape or out-of-range HH:MM)`)
308
+ }
309
+ return {
310
+ categories: { ...base.categories, ...sanitizeCategoryMap(raw?.categories) },
311
+ devices: sanitizeDevices(raw?.devices, { log }),
312
+ quietHours: cleanedQuietHours,
313
+ bypassCategories: bypass,
314
+ }
315
+ } catch (err) {
316
+ log?.warn?.(`notification-prefs ${filePath} unreadable: ${err?.message || err}`)
317
+ return base
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Persist a prefs object to disk. Atomic temp+rename so a crashed write
323
+ * cannot corrupt the file. On POSIX the file ends up at mode 0600.
324
+ *
325
+ * #4463 pattern: if renameSync throws (cross-device link, FS quota, ACL),
326
+ * unlink the .tmp file on the failure path and re-throw the ORIGINAL
327
+ * rename error so the caller sees the real failure rather than a
328
+ * cleanup-side ENOENT. The cleanup unlink swallows its own errors so a
329
+ * race that already cleaned the temp doesn't mask the original failure.
330
+ */
331
+ export function savePrefs(prefs, filePath = defaultNotificationPrefsPath()) {
332
+ const dir = dirname(filePath)
333
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 })
334
+ const tmp = `${filePath}.tmp`
335
+ writeFileSync(tmp, JSON.stringify(prefs, null, 2), { mode: 0o600 })
336
+ try { chmodSync(tmp, 0o600) } catch {}
337
+ try {
338
+ renameSync(tmp, filePath)
339
+ } catch (err) {
340
+ try { unlinkSync(tmp) } catch {}
341
+ throw err
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Resolve "should category X fire for device Y given prefs Z?".
347
+ *
348
+ * 1. per-device override wins when present (the user explicitly toggled
349
+ * this device).
350
+ * 2. otherwise the global default applies.
351
+ * 3. unknown categories fall through to `true` (fail-open). The defensive
352
+ * RATE_LIMITS gate in push.js still throttles unknowns at the
353
+ * documented `?? 30_000` default, so a fail-open here doesn't enable
354
+ * spam.
355
+ */
356
+ export function resolveCategoryDecision(prefs, category, pushToken) {
357
+ if (!prefs || typeof prefs !== 'object') return true
358
+ const deviceEntry = pushToken && prefs.devices ? prefs.devices[pushToken] : null
359
+ if (deviceEntry?.categories && typeof deviceEntry.categories[category] === 'boolean') {
360
+ return deviceEntry.categories[category]
361
+ }
362
+ if (prefs.categories && typeof prefs.categories[category] === 'boolean') {
363
+ return prefs.categories[category]
364
+ }
365
+ return true
366
+ }
367
+
368
+ /** Alias surface for PushManager.isCategoryEnabled. */
369
+ export function isCategoryEnabledIn(prefs, category, pushToken) {
370
+ return resolveCategoryDecision(prefs, category, pushToken)
371
+ }
372
+
373
+ /**
374
+ * Resolve the effective quiet-hours window for a device (#4544).
375
+ *
376
+ * Per-device entry REPLACES the global window when the device entry
377
+ * carries the `quietHours` key — including the `null` case (which means
378
+ * "this device is never muted by quiet hours"). When the device entry
379
+ * does NOT carry the key, the global window applies.
380
+ */
381
+ export function resolveQuietHoursWindow(prefs, pushToken) {
382
+ if (!prefs || typeof prefs !== 'object') return null
383
+ if (pushToken && prefs.devices) {
384
+ const entry = prefs.devices[pushToken]
385
+ if (entry && Object.prototype.hasOwnProperty.call(entry, 'quietHours')) {
386
+ return entry.quietHours
387
+ }
388
+ }
389
+ return prefs.quietHours || null
390
+ }
391
+
392
+ /**
393
+ * Resolve the effective bypass-category list for a device (#4544).
394
+ *
395
+ * Same REPLACE semantics as quiet-hours: per-device list (when present,
396
+ * including empty array) wins entirely. When absent, the global list
397
+ * (or `DEFAULT_BYPASS_CATEGORIES` when the global is also absent)
398
+ * applies.
399
+ */
400
+ export function resolveBypassCategories(prefs, pushToken) {
401
+ if (!prefs || typeof prefs !== 'object') return [...DEFAULT_BYPASS_CATEGORIES]
402
+ if (pushToken && prefs.devices) {
403
+ const entry = prefs.devices[pushToken]
404
+ if (entry && Array.isArray(entry.bypassCategories)) {
405
+ return [...entry.bypassCategories]
406
+ }
407
+ }
408
+ if (Array.isArray(prefs.bypassCategories)) return [...prefs.bypassCategories]
409
+ return [...DEFAULT_BYPASS_CATEGORIES]
410
+ }
411
+
412
+ /**
413
+ * Quick predicate: does this category bypass quiet hours for this device?
414
+ * Pure composition over `resolveBypassCategories`.
415
+ */
416
+ export function shouldBypassQuietHours(prefs, category, pushToken) {
417
+ const list = resolveBypassCategories(prefs, pushToken)
418
+ return list.includes(category)
419
+ }
420
+
421
+ /**
422
+ * Memoized `Intl.DateTimeFormat` instances keyed by IANA timezone (#4568).
423
+ *
424
+ * The quiet-hours gate runs once per registered push token per
425
+ * `PushManager.send()` call. Each `Intl.DateTimeFormat` instance carries a
426
+ * few KB of locale data, so re-allocating on every call wastes work in a hot
427
+ * path that scales with token count.
428
+ *
429
+ * Bounded memory: the set of timezones in real prefs is tiny (one global
430
+ * window plus at most one per device) and stable for the process lifetime,
431
+ * so a plain `Map` with no eviction is safe — no LRU bookkeeping needed.
432
+ * If a future feature lets users construct ad-hoc timezone strings (e.g.
433
+ * from untrusted input), revisit this; today every timezone arrives via
434
+ * `sanitizeQuietHours`, which only persists strings the constructor accepts.
435
+ *
436
+ * Failure-cache policy: we only cache SUCCESSFUL constructions. A
437
+ * `RangeError` from an unrecognised IANA zone returns `null` upstream so
438
+ * the gate fail-opens; never caching the failure means a later prefs reload
439
+ * that fixes the typo will reconstruct cleanly with the same key.
440
+ */
441
+ const _dtfCache = new Map()
442
+
443
+ /**
444
+ * Test-only escape hatch: clear the cached formatters so a test can
445
+ * deterministically count constructor invocations (e.g. by spying on
446
+ * `Intl.DateTimeFormat`). Production code never needs this — the cache is
447
+ * correct for the process lifetime.
448
+ */
449
+ export function _resetDateTimeFormatCacheForTests() {
450
+ _dtfCache.clear()
451
+ }
452
+
453
+ function _getDateTimeFormat(timezone) {
454
+ let dtf = _dtfCache.get(timezone)
455
+ if (dtf) return dtf
456
+ try {
457
+ dtf = new Intl.DateTimeFormat('en-US', {
458
+ timeZone: timezone,
459
+ hour: '2-digit',
460
+ minute: '2-digit',
461
+ hourCycle: 'h23',
462
+ })
463
+ } catch {
464
+ return null
465
+ }
466
+ _dtfCache.set(timezone, dtf)
467
+ return dtf
468
+ }
469
+
470
+ /**
471
+ * Format `now` (epoch ms) in the given IANA timezone and return its
472
+ * minute-of-day (0..1439). Uses `Intl.DateTimeFormat` with a 24-hour
473
+ * `h23` cycle so DST transitions and non-Pacific zones are handled
474
+ * correctly without re-implementing zone math.
475
+ *
476
+ * Returns `null` when the timezone is unrecognised (Node throws
477
+ * `RangeError` from the constructor; we treat that as a malformed window
478
+ * and let the caller fail open). Formatter instances are memoized in
479
+ * `_dtfCache` to avoid re-allocating locale data on every call (#4568).
480
+ */
481
+ function _wallClockMinutes(now, timezone) {
482
+ const dtf = _getDateTimeFormat(timezone)
483
+ if (!dtf) return null
484
+ const parts = dtf.formatToParts(new Date(now))
485
+ const hour = Number(parts.find((p) => p.type === 'hour')?.value)
486
+ const minute = Number(parts.find((p) => p.type === 'minute')?.value)
487
+ if (!Number.isFinite(hour) || !Number.isFinite(minute)) return null
488
+ return hour * 60 + minute
489
+ }
490
+
491
+ /** Parse "HH:MM" → minutes since midnight, or null on malformed input. */
492
+ function _parseHHMM(s) {
493
+ if (typeof s !== 'string' || !_HHMM_RE.test(s)) return null
494
+ const [h, m] = s.split(':').map(Number)
495
+ if (h > 23 || m > 59) return null
496
+ return h * 60 + m
497
+ }
498
+
499
+ /**
500
+ * Real quiet-hours enforcement (#4544).
501
+ *
502
+ * Returns true when `now` falls inside the device's effective quiet-hours
503
+ * window (per-device override beats global). The window is interpreted
504
+ * with start INCLUSIVE and end EXCLUSIVE — i.e. [start, end) — so a
505
+ * window of 22:00-07:00 includes 22:00:00.000 but excludes 07:00:00.000.
506
+ *
507
+ * Midnight wrap: when start > end the window spans midnight, so it
508
+ * matches `minutes >= start OR minutes < end`. When start === end the
509
+ * window has zero duration and never matches (defensive — a UI that
510
+ * accidentally writes start=end shouldn't lock out all notifications).
511
+ *
512
+ * Defensive fail-open: any structural error (no window, no timezone,
513
+ * unparseable times, unrecognised IANA zone) returns false. The
514
+ * alternative — fail-CLOSED — would silently swallow every push for a
515
+ * misconfigured user, which is the worst possible outcome for a
516
+ * notification system. The companion checkers (`isCategoryEnabledIn`,
517
+ * `RATE_LIMITS`) provide layered protection regardless.
518
+ */
519
+ export function isInQuietHoursIn(prefs, now, pushToken) {
520
+ // Defensive: `now` must be a finite epoch-ms. Without this guard a caller
521
+ // passing `null`/`undefined`/`NaN` would coerce through `new Date(now)`
522
+ // (e.g. `new Date(null)` → 1970-01-01T00:00:00Z) and silently activate
523
+ // quiet hours for every push that happens to fall inside a window
524
+ // overlapping 00:00 UTC. Fail-open (return false) matches the rest of
525
+ // the function's posture — better to deliver a push than to silently
526
+ // suppress all of them on a caller bug. (#4567)
527
+ if (!Number.isFinite(now)) return false
528
+ const window = resolveQuietHoursWindow(prefs, pushToken)
529
+ if (!window) return false
530
+ if (typeof window.timezone !== 'string' || window.timezone.length === 0) return false
531
+ const startMin = _parseHHMM(window.start)
532
+ const endMin = _parseHHMM(window.end)
533
+ if (startMin == null || endMin == null) return false
534
+ // Zero-duration window: never matches (defensive).
535
+ if (startMin === endMin) return false
536
+ const nowMin = _wallClockMinutes(now, window.timezone)
537
+ if (nowMin == null) return false
538
+ if (startMin < endMin) {
539
+ // Same-day window.
540
+ return nowMin >= startMin && nowMin < endMin
541
+ }
542
+ // Midnight-wrap window: [start, 24:00) ∪ [00:00, end).
543
+ return nowMin >= startMin || nowMin < endMin
544
+ }