@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
package/src/pairing.js ADDED
@@ -0,0 +1,836 @@
1
+ /**
2
+ * Ephemeral pairing manager for QR-based device pairing.
3
+ *
4
+ * Generates short-lived pairing IDs that replace permanent API tokens in QR codes.
5
+ * Flow: QR has pairing ID → app sends pair request → server validates → issues session token.
6
+ *
7
+ * Pairing IDs expire after TTL (default 60s) and are single-use.
8
+ * Recently-refreshed IDs remain valid until their TTL expires (grace period).
9
+ */
10
+ import { EventEmitter } from 'events'
11
+ import { randomBytes, timingSafeEqual } from 'crypto'
12
+ import { createLogger } from './logger.js'
13
+
14
+ const log = createLogger('pairing')
15
+
16
+ // -- Typeable short pairing code (#5512, epic #5509) --
17
+ //
18
+ // Pairing ids double as a human-typable code read off the host's own screen (the
19
+ // TV-app pattern: display-on-host = physical presence, so no extra approval — same
20
+ // trust as a scanned QR). The QR carries the SAME id, so this is one mechanism, not
21
+ // two. Codes delivered via any OTHER channel must use the #5510 approval primitive
22
+ // instead — possession of a code is only sufficient when it was read off the host.
23
+ //
24
+ // Alphabet: uppercase, ambiguity-free (no 0/O, 1/I/L). 8 chars over a 31-symbol
25
+ // alphabet ≈ 31^8 ≈ 8.5e11 combinations — paired with a 60s single-use TTL this is
26
+ // not brute-forceable. Entry is case-insensitive and tolerant of spaces/dashes;
27
+ // inputs are normalized (uppercased, separators stripped) before lookup.
28
+ export const TYPEABLE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'
29
+ const TYPEABLE_CODE_LENGTH = 8
30
+
31
+ /**
32
+ * Generate a crypto-random typeable pairing code. Rejection-samples bytes so the
33
+ * alphabet is unbiased (no modulo skew toward the first 256 % N symbols).
34
+ * @returns {string}
35
+ */
36
+ function generateTypeableCode() {
37
+ const n = TYPEABLE_ALPHABET.length
38
+ const max = Math.floor(256 / n) * n // largest multiple of n ≤ 256 (rejection bound)
39
+ let out = ''
40
+ while (out.length < TYPEABLE_CODE_LENGTH) {
41
+ const buf = randomBytes(TYPEABLE_CODE_LENGTH)
42
+ for (let i = 0; i < buf.length && out.length < TYPEABLE_CODE_LENGTH; i++) {
43
+ const b = buf[i]
44
+ if (b >= max) continue // reject to keep the distribution uniform
45
+ out += TYPEABLE_ALPHABET[b % n]
46
+ }
47
+ }
48
+ return out
49
+ }
50
+
51
+ /**
52
+ * Normalize a user-typed pairing code: uppercase, strip whitespace and dashes.
53
+ * Makes entry case-insensitive and tolerant of the spaces/dashes people add when
54
+ * reading a code aloud. Returns '' for non-string / nullish input.
55
+ * @param {string} raw
56
+ * @returns {string}
57
+ */
58
+ export function normalizePairingCode(raw) {
59
+ if (typeof raw !== 'string') return ''
60
+ return raw.replace(/[\s-]+/g, '').toUpperCase()
61
+ }
62
+
63
+ const DEFAULT_TTL_MS = 60_000
64
+ const DEFAULT_GRACE_PERIOD_MS = 3 * 60_000 // 3 minutes after first QR display
65
+ const DEFAULT_SESSION_TOKEN_TTL_MS = 24 * 60 * 60_000 // 24 hours
66
+ const SESSION_TOKEN_BYTES = 32
67
+ const MAX_SESSION_TOKENS = 100
68
+ // #5555: cadence for the background session-token TTL sweep. Mirrors the
69
+ // _pendingRequests sweep so expired tokens are reaped even when no lookup or
70
+ // new issuance touches them — without this they linger to the cap and trigger
71
+ // eviction of a still-valid (longest-paired) token, silently logging out a
72
+ // device. Hourly is ample against a multi-day TTL (default 30d, #6598); unref'd
73
+ // so it never holds the process open.
74
+ const SESSION_TOKEN_SWEEP_INTERVAL_MS = 60 * 60_000 // 1 hour
75
+ // #6598: a sliding-expiry refresh moves a token's clock on every reconnect, but
76
+ // with a multi-day TTL there's no need to hit disk each time — persist a slide at
77
+ // most this often. Structural changes (mint / sweep) persist immediately.
78
+ const SLIDE_PERSIST_THROTTLE_MS = 60 * 60_000 // 1 hour
79
+ const MAX_ACTIVE_PAIRINGS = 10
80
+
81
+ // -- Pairing-approval primitive (#5510, epic #5509) --
82
+ //
83
+ // A camera-less device requests pairing without a QR; the user approves it from
84
+ // a host-level surface. The pending queue is an UNAUTHENTICATED-fed DoS surface,
85
+ // so it is hard-bounded on three axes: a global cap, a per-request TTL, and a
86
+ // per-source rate limit. Expired entries are swept on an unref'd timer.
87
+ const DEFAULT_PENDING_TTL_MS = 120_000 // 120s — a pending request expires
88
+ const MAX_PENDING_REQUESTS = 5 // global cap on outstanding pending requests
89
+ const PENDING_SWEEP_INTERVAL_MS = 5_000 // sweep cadence for expired entries
90
+ // Per-source rate limit: at most N new requests in a rolling window.
91
+ const PENDING_RATE_MAX = 5
92
+ const PENDING_RATE_WINDOW_MS = 60_000
93
+ const MAX_RATE_SOURCES = 1_000 // cap the rate-limit map cardinality
94
+
95
+ /**
96
+ * Append the daemon's pinned E2E identity public key to a pairing URL as the
97
+ * `idk` (IDentity Key) query param (#5536). The pairing channel is the trust
98
+ * root — it already conveys the URL + pairing id out-of-band — so it is the
99
+ * sound place to convey the identity key the client pins. Old clients ignore
100
+ * the extra param. No-op when there is no identity key (encryption disabled /
101
+ * older daemon) or no base URL.
102
+ * @param {string|null} url - base chroxy:// pairing URL
103
+ * @param {string|null} identityPublicKey - base64 Ed25519 identity public key
104
+ * @returns {string|null}
105
+ */
106
+ function appendIdentityKey(url, identityPublicKey) {
107
+ if (!url || !identityPublicKey) return url
108
+ const sep = url.includes('?') ? '&' : '?'
109
+ return `${url}${sep}idk=${encodeURIComponent(identityPublicKey)}`
110
+ }
111
+
112
+ export class PairingManager extends EventEmitter {
113
+ constructor({ wsUrl = null, ttlMs = DEFAULT_TTL_MS, sessionTokenTtlMs = DEFAULT_SESSION_TOKEN_TTL_MS, autoRefresh = false, pendingTtlMs = DEFAULT_PENDING_TTL_MS, identityPublicKey = null, sessionTokenStore = null } = {}) {
114
+ super()
115
+ this._wsUrl = wsUrl
116
+ // #5536 — the daemon's long-lived E2E identity public key (base64 Ed25519),
117
+ // pinned by clients at pairing time. Rides every pairing URL as `?idk=`.
118
+ this._identityPublicKey = identityPublicKey
119
+ this._ttlMs = ttlMs
120
+ this._sessionTokenTtlMs = sessionTokenTtlMs
121
+ this._autoRefresh = autoRefresh
122
+ this._current = null
123
+ this._activePairings = new Map() // id → { expiresAt, used }
124
+ this._sessionTokens = new Map() // sessionToken → { createdAt, sessionId }
125
+ this._refreshTimer = null
126
+ // #5555: background TTL sweep for _sessionTokens (started lazily on first
127
+ // token issuance, cleared on destroy — no leaked timer).
128
+ this._sessionTokenSweepTimer = null
129
+ this._destroyed = false
130
+ // #6598: optional { load, save } adapter so paired tokens survive a daemon
131
+ // restart. When absent, behaviour is exactly as before (in-memory only).
132
+ this._sessionTokenStore = sessionTokenStore
133
+ // Throttle slide-refresh persistence: a sliding-expiry refresh moves createdAt
134
+ // on every reconnect, but with a multi-day TTL we don't need to hit disk each
135
+ // time. Structural changes (mint / sweep / revoke) always persist immediately;
136
+ // a slide persists at most once per SLIDE_PERSIST_THROTTLE_MS.
137
+ this._lastSlidePersistMs = 0
138
+ // Restore persisted tokens (expired ones are dropped lazily on first lookup,
139
+ // and by the background sweep once it's armed below).
140
+ if (this._sessionTokenStore) {
141
+ try {
142
+ for (const [token, meta] of this._sessionTokenStore.load()) {
143
+ if (typeof token === 'string' && meta && typeof meta.createdAt === 'number') {
144
+ // Coerce sessionId to string|null — a hand-edited / corrupt store must
145
+ // not inject a non-string binding that downstream handlers assume.
146
+ const sessionId = typeof meta.sessionId === 'string' ? meta.sessionId : null
147
+ this._sessionTokens.set(token, { createdAt: meta.createdAt, sessionId })
148
+ }
149
+ }
150
+ // Arm the background TTL sweep so restored-but-expired tokens are reaped
151
+ // even if nothing looks them up after a restart.
152
+ if (this._sessionTokens.size > 0) this._ensureSessionTokenSweepTimer()
153
+ } catch (err) {
154
+ // Never let a restore failure break construction — start empty so devices
155
+ // re-pair. Logged (not silent) so a genuine programming error surfaces.
156
+ log.warn(`could not restore persisted session tokens (${err.message}) — devices will re-pair`)
157
+ }
158
+ }
159
+
160
+ // -- Pairing-approval primitive (#5510) --
161
+ this._pendingTtlMs = pendingTtlMs
162
+ this._pendingRequests = new Map() // requestId → { deviceName, verifyCode, expiresAt, resolved }
163
+ this._pendingRateBuckets = new Map() // source → { count, windowStart }
164
+ this._sweepTimer = null
165
+
166
+ this._generatePairing()
167
+ if (autoRefresh) this._scheduleRefresh()
168
+ }
169
+
170
+ get currentPairingId() {
171
+ if (this._destroyed) return null
172
+ return this._current?.id || null
173
+ }
174
+
175
+ get currentPairingUrl() {
176
+ if (!this._current || !this._wsUrl) return null
177
+ const host = this._wsUrl.replace(/^wss?:\/\//, '')
178
+ return appendIdentityKey(`chroxy://${host}?pair=${this._current.id}`, this._identityPublicKey)
179
+ }
180
+
181
+ /** The daemon's pinned E2E identity public key (base64 Ed25519), or null. */
182
+ get identityPublicKey() {
183
+ return this._identityPublicKey
184
+ }
185
+
186
+ /** Update the identity public key (e.g. after the keypair is minted late). */
187
+ setIdentityPublicKey(key) {
188
+ this._identityPublicKey = key || null
189
+ }
190
+
191
+ /**
192
+ * Snapshot of the current linking-mode pairing code for host display surfaces
193
+ * (#5512): the typeable code, its chroxy:// URL (QR carries the same id), and the
194
+ * absolute expiry so a CLI/dashboard can render "expires in NNs". Null when
195
+ * destroyed or no pairing exists.
196
+ * @returns {{ code: string, url: string|null, expiresAtMs: number, ttlMs: number }|null}
197
+ */
198
+ get currentPairingCode() {
199
+ if (this._destroyed || !this._current) return null
200
+ return {
201
+ code: this._current.id,
202
+ url: this.currentPairingUrl,
203
+ identityPublicKey: this._identityPublicKey,
204
+ expiresAtMs: this._current.expiresAt,
205
+ ttlMs: this._ttlMs,
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Generate a NEW pairing ID bound at creation time to a specific session
211
+ * (#3070). Unlike `_generatePairing()`, this does NOT replace `_current`
212
+ * (the linking-mode QR keeps auto-refreshing for general device pairing);
213
+ * it adds an additional one-shot entry with `boundSessionId` stored on it.
214
+ *
215
+ * The returned URL goes into a "Share this session" QR. When the scanner
216
+ * pairs, the issued sessionToken is bound to the specified sessionId, so
217
+ * the paired client can chat into that session but cannot list/switch/
218
+ * destroy others.
219
+ *
220
+ * @param {string} sessionId - Session to bind the issued token to
221
+ * @returns {{ pairingId: string, pairingUrl: string|null }}
222
+ * @throws {Error} If sessionId is empty / non-string
223
+ */
224
+ generateBoundPairing(sessionId) {
225
+ if (typeof sessionId !== 'string' || sessionId.length === 0) {
226
+ throw new Error('generateBoundPairing requires a non-empty sessionId')
227
+ }
228
+ if (this._destroyed) {
229
+ throw new Error('PairingManager is destroyed')
230
+ }
231
+
232
+ // Cap active pairings to prevent unbounded growth. Skip _current.id
233
+ // when picking the eviction victim — the linking-mode QR's id is in
234
+ // _activePairings too, and dropping it would silently invalidate the
235
+ // main /qr (validatePairing on the linking id would return
236
+ // invalid_pairing_id even though currentPairingId still reports it).
237
+ // Falls back to evicting _current as a last resort if it's the only
238
+ // entry, which can only happen with a misconfigured cap.
239
+ if (this._activePairings.size >= MAX_ACTIVE_PAIRINGS) {
240
+ const linkingId = this._current?.id || null
241
+ let victim = null
242
+ for (const id of this._activePairings.keys()) {
243
+ if (id !== linkingId) {
244
+ victim = id
245
+ break
246
+ }
247
+ }
248
+ this._activePairings.delete(victim ?? this._activePairings.keys().next().value)
249
+ }
250
+
251
+ const id = generateTypeableCode()
252
+ const expiresAt = Date.now() + this._ttlMs
253
+ this._activePairings.set(id, { expiresAt, used: false, boundSessionId: sessionId })
254
+
255
+ const pairingUrl = this._wsUrl
256
+ ? appendIdentityKey(`chroxy://${this._wsUrl.replace(/^wss?:\/\//, '')}?pair=${id}`, this._identityPublicKey)
257
+ : null
258
+ return { pairingId: id, pairingUrl }
259
+ }
260
+
261
+ /**
262
+ * Generate a NEW pairing id flagged `requiresApproval: true` (#5513, epic
263
+ * #5509) — the Discord-delivery path. Unlike `generateBoundPairing`, a gated
264
+ * id NEVER mints a token on redemption: `validatePairing` returns
265
+ * `requires_approval` so the WsServer routes the redemption into the #5510
266
+ * pending-request approval flow (verify-code + host approve). Possession of
267
+ * the Discord channel therefore grants nothing on its own — a leaked link
268
+ * still needs an out-of-band host approval to connect.
269
+ *
270
+ * Like `generateBoundPairing`, this does NOT replace `_current` (the
271
+ * linking-mode QR keeps auto-refreshing); it adds an additional one-shot,
272
+ * single-use, TTL'd entry. Each trigger surface (CLI / dashboard button)
273
+ * calls this fresh so every Discord post carries its own ephemeral id.
274
+ *
275
+ * @returns {{ pairingId: string, pairingUrl: string|null, expiresAt: number }}
276
+ * @throws {Error} If the manager is destroyed.
277
+ */
278
+ createApprovalGatedPairingId() {
279
+ if (this._destroyed) {
280
+ throw new Error('PairingManager is destroyed')
281
+ }
282
+
283
+ // Cap active pairings to prevent unbounded growth. Skip _current.id when
284
+ // picking the eviction victim — dropping the linking-mode QR's entry would
285
+ // silently invalidate the main /qr (same rationale as generateBoundPairing).
286
+ if (this._activePairings.size >= MAX_ACTIVE_PAIRINGS) {
287
+ const linkingId = this._current?.id || null
288
+ let victim = null
289
+ for (const id of this._activePairings.keys()) {
290
+ if (id !== linkingId) {
291
+ victim = id
292
+ break
293
+ }
294
+ }
295
+ this._activePairings.delete(victim ?? this._activePairings.keys().next().value)
296
+ }
297
+
298
+ const id = generateTypeableCode()
299
+ const expiresAt = Date.now() + this._ttlMs
300
+ this._activePairings.set(id, { expiresAt, used: false, requiresApproval: true })
301
+
302
+ const pairingUrl = this._wsUrl
303
+ ? appendIdentityKey(`chroxy://${this._wsUrl.replace(/^wss?:\/\//, '')}?pair=${id}`, this._identityPublicKey)
304
+ : null
305
+ return { pairingId: id, pairingUrl, expiresAt }
306
+ }
307
+
308
+ /**
309
+ * Validate a pairing ID and issue a session token if valid.
310
+ * Accepts any active pairing ID (current or recently-refreshed within TTL).
311
+ *
312
+ * If the pairing entry was created via `generateBoundPairing(sessionId)`,
313
+ * the binding is taken from the entry — `sessionId` param is ignored.
314
+ * Otherwise (linking-mode pairings), the param controls the binding.
315
+ *
316
+ * Approval-gated entries (#5513, `createApprovalGatedPairingId`) are consumed
317
+ * (marked used) but NEVER mint a token: the call returns
318
+ * `{ valid: false, reason: 'requires_approval' }` so the caller routes the
319
+ * redemption into the host-approval flow instead.
320
+ *
321
+ * @param {string} pairingId
322
+ * @param {string|null} [sessionId] - Session ID to bind to the issued token
323
+ * (only honored when the entry has no boundSessionId of its own).
324
+ * @returns {{ valid: boolean, sessionToken?: string, reason?: string }}
325
+ */
326
+ validatePairing(pairingId, sessionId = null) {
327
+ // Normalize typed/scanned input so a code read off the host screen validates
328
+ // regardless of case or the spaces/dashes a user adds (#5512). Stored keys are
329
+ // already canonical (uppercase, separator-free) so this is a no-op for QR ids.
330
+ pairingId = normalizePairingCode(pairingId)
331
+
332
+ // Look up in active pairings (includes current + grace period entries)
333
+ const entry = this._activePairings.get(pairingId)
334
+ if (!entry) {
335
+ return { valid: false, reason: 'invalid_pairing_id' }
336
+ }
337
+
338
+ if (entry.used) {
339
+ return { valid: false, reason: 'already_used' }
340
+ }
341
+ if (Date.now() > entry.expiresAt) {
342
+ this._activePairings.delete(pairingId)
343
+ return { valid: false, reason: 'expired' }
344
+ }
345
+
346
+ // Mark as used (one-time)
347
+ entry.used = true
348
+
349
+ // Approval-gated id (#5513): consume it but mint NO token. The caller
350
+ // (WsServer / handlePairMessage) maps `requires_approval` into the #5510
351
+ // pending-request flow — host approval is still required, so possession of
352
+ // the Discord-delivered link grants nothing on its own.
353
+ if (entry.requiresApproval) {
354
+ return { valid: false, reason: 'requires_approval' }
355
+ }
356
+
357
+ // Issue a session token (with FIFO eviction at cap). Entry-bound pairings
358
+ // (#3070) take precedence — the param is only honored for linking-mode
359
+ // pairings that didn't fix a binding at creation time.
360
+ const effectiveSessionId = entry.boundSessionId || sessionId || null
361
+ const sessionToken = randomBytes(SESSION_TOKEN_BYTES).toString('base64url')
362
+ this._storeSessionToken(sessionToken, { createdAt: Date.now(), sessionId: effectiveSessionId })
363
+
364
+ // Auto-regenerate so the dashboard always shows a fresh QR (#2916), but
365
+ // only when the just-consumed ID was the linking-mode `_current`. Bound
366
+ // share-pairings shouldn't trigger a linking-mode rotation.
367
+ if (this._current && this._current.id === pairingId) {
368
+ // Emit after issuing the token so the sessionToken return value is
369
+ // ready before any pairing_refreshed listener queries currentPairingId.
370
+ this._generatePairing()
371
+ this.emit('pairing_refreshed', { pairingId: this._current.id })
372
+
373
+ // Reset the auto-refresh timer so it counts from the newly-generated ID,
374
+ // not from when the consumed ID was created. Without this, the pending
375
+ // timer fires on the old schedule and emits a spurious second
376
+ // pairing_refreshed seconds later (#3020).
377
+ if (this._autoRefresh && this._refreshTimer) {
378
+ clearTimeout(this._refreshTimer)
379
+ this._refreshTimer = null
380
+ this._scheduleRefresh()
381
+ }
382
+ }
383
+
384
+ return { valid: true, sessionToken }
385
+ }
386
+
387
+ /**
388
+ * Check if a session token (issued during pairing) is valid.
389
+ * Uses constant-time comparison to prevent timing attacks.
390
+ */
391
+ isSessionTokenValid(token) {
392
+ const meta = this._lookupToken(token)
393
+ if (meta === null) return false
394
+ // #6598 sliding expiry: a successful auth (this is called on the auth path,
395
+ // NOT on every per-message getSessionIdForToken lookup) refreshes the token's
396
+ // clock, so only a device that hasn't connected within the TTL window expires.
397
+ // `meta` is the live map value, so mutating it slides the stored entry.
398
+ meta.createdAt = Date.now()
399
+ this._maybePersistSlide()
400
+ return true
401
+ }
402
+
403
+ /**
404
+ * Return the session ID bound to a session token, or null if the token is
405
+ * invalid / expired / not bound to any session.
406
+ * Uses constant-time comparison to prevent timing attacks.
407
+ * @param {string} token
408
+ * @returns {string|null}
409
+ */
410
+ getSessionIdForToken(token) {
411
+ const meta = this._lookupToken(token)
412
+ return meta ? (meta.sessionId || null) : null
413
+ }
414
+
415
+ /**
416
+ * Look up a session token using constant-time comparison.
417
+ * Prunes expired tokens on access.
418
+ * @param {string} token
419
+ * @returns {object|null} Token metadata if found, null otherwise
420
+ */
421
+ _lookupToken(token) {
422
+ if (!token) return null
423
+ const now = Date.now()
424
+ const tokenBuf = Buffer.from(token)
425
+ for (const [stored, meta] of this._sessionTokens.entries()) {
426
+ if (now - meta.createdAt > this._sessionTokenTtlMs) {
427
+ this._sessionTokens.delete(stored)
428
+ continue
429
+ }
430
+ const storedBuf = Buffer.from(stored)
431
+ if (tokenBuf.length === storedBuf.length && timingSafeEqual(tokenBuf, storedBuf)) {
432
+ return meta
433
+ }
434
+ }
435
+ return null
436
+ }
437
+
438
+ /**
439
+ * #5555: drop every expired session token. Used both before cap-eviction
440
+ * (so we never evict a still-valid token while expired ones occupy slots)
441
+ * and by the background sweep timer. Constant-key iteration, no allocation.
442
+ * @returns {number} count of tokens removed
443
+ */
444
+ _sweepSessionTokens() {
445
+ if (this._destroyed) return 0
446
+ const now = Date.now()
447
+ let removed = 0
448
+ for (const [stored, meta] of this._sessionTokens) {
449
+ if (now - meta.createdAt > this._sessionTokenTtlMs) {
450
+ this._sessionTokens.delete(stored)
451
+ removed++
452
+ }
453
+ }
454
+ // Stop the timer once the map is empty — re-armed on the next issuance.
455
+ if (this._sessionTokens.size === 0 && this._sessionTokenSweepTimer) {
456
+ clearInterval(this._sessionTokenSweepTimer)
457
+ this._sessionTokenSweepTimer = null
458
+ }
459
+ // #6598: a sweep that dropped an expired token is a structural change —
460
+ // persist so the reaped token doesn't reappear on the next restart.
461
+ if (removed > 0) this._persistSessionTokens()
462
+ return removed
463
+ }
464
+
465
+ _ensureSessionTokenSweepTimer() {
466
+ if (this._destroyed || this._sessionTokenSweepTimer) return
467
+ this._sessionTokenSweepTimer = setInterval(() => this._sweepSessionTokens(), SESSION_TOKEN_SWEEP_INTERVAL_MS)
468
+ this._sessionTokenSweepTimer.unref?.()
469
+ }
470
+
471
+ /**
472
+ * #6598: persist the current session-token map through the injected store, if
473
+ * any. Best-effort — the store swallows + logs I/O errors, never throwing into
474
+ * token issuance or the auth path. Used for STRUCTURAL changes (mint / sweep).
475
+ */
476
+ _persistSessionTokens() {
477
+ if (!this._sessionTokenStore) return
478
+ try {
479
+ this._sessionTokenStore.save([...this._sessionTokens.entries()])
480
+ } catch { /* store logs; a failed persist just means a restart may re-pair */ }
481
+ }
482
+
483
+ /**
484
+ * #6598: persist a sliding-expiry refresh, throttled to at most once per
485
+ * SLIDE_PERSIST_THROTTLE_MS so a reconnect-happy client doesn't churn the disk.
486
+ * A slide missed by the throttle is at most SLIDE_PERSIST_THROTTLE_MS stale on
487
+ * disk, negligible against the multi-day TTL.
488
+ */
489
+ _maybePersistSlide() {
490
+ if (!this._sessionTokenStore) return
491
+ const now = Date.now()
492
+ if (now - this._lastSlidePersistMs < SLIDE_PERSIST_THROTTLE_MS) return
493
+ this._lastSlidePersistMs = now
494
+ this._persistSessionTokens()
495
+ }
496
+
497
+ /**
498
+ * #5555: issue a new session token under the cap, sweeping expired tokens
499
+ * BEFORE evicting any still-valid one. The pre-fix path evicted the oldest
500
+ * Map entry by insertion order — the longest-paired (and likely still-valid)
501
+ * device — even when expired tokens were sitting in the map ready to be
502
+ * reaped. Only after the sweep, if still at cap, do we evict the oldest
503
+ * remaining (now guaranteed all-valid) token.
504
+ * @param {string} token
505
+ * @param {object} meta - token metadata ({ createdAt, sessionId })
506
+ */
507
+ _storeSessionToken(token, meta) {
508
+ if (this._sessionTokens.size >= MAX_SESSION_TOKENS) {
509
+ this._sweepSessionTokens()
510
+ if (this._sessionTokens.size >= MAX_SESSION_TOKENS) {
511
+ const oldest = this._sessionTokens.keys().next().value
512
+ this._sessionTokens.delete(oldest)
513
+ }
514
+ }
515
+ this._sessionTokens.set(token, meta)
516
+ this._ensureSessionTokenSweepTimer()
517
+ // #6598: a freshly minted token is a structural change — persist immediately
518
+ // so a device paired right before a restart stays paired after it.
519
+ this._persistSessionTokens()
520
+ }
521
+
522
+ /**
523
+ * Extend the current pairing ID's validity and pause auto-refresh for a grace period.
524
+ * Call after displaying the QR code to give the user time to scan before rotation.
525
+ * @param {number} [durationMs] - Grace period in ms (default 3 minutes)
526
+ */
527
+ extendCurrentId(durationMs = DEFAULT_GRACE_PERIOD_MS) {
528
+ if (this._destroyed || !this._current) return
529
+
530
+ // Extend the expiry — never shorten below the existing remaining TTL
531
+ const requestedExpiry = Date.now() + durationMs
532
+ const newExpiry = Math.max(this._current.expiresAt, requestedExpiry)
533
+ this._current.expiresAt = newExpiry
534
+ const entry = this._activePairings.get(this._current.id)
535
+ if (entry) entry.expiresAt = newExpiry
536
+
537
+ // Reschedule auto-refresh to fire after the (possibly extended) grace period
538
+ if (this._autoRefresh) {
539
+ if (this._refreshTimer) clearTimeout(this._refreshTimer)
540
+ const delayMs = Math.max(0, newExpiry - Date.now())
541
+ this._refreshTimer = setTimeout(() => {
542
+ if (this._destroyed) return
543
+ this._generatePairing()
544
+ this.emit('pairing_refreshed', { pairingId: this._current.id })
545
+ this._scheduleRefresh()
546
+ }, delayMs)
547
+ this._refreshTimer.unref?.()
548
+ }
549
+ }
550
+
551
+ /**
552
+ * Manually refresh the current pairing ID.
553
+ */
554
+ refresh() {
555
+ this._generatePairing()
556
+ this.emit('pairing_refreshed', { pairingId: this._current.id })
557
+ }
558
+
559
+ /**
560
+ * Update the WebSocket URL (e.g., after tunnel reconnect).
561
+ */
562
+ setWsUrl(wsUrl) {
563
+ this._wsUrl = wsUrl
564
+ }
565
+
566
+ // ===================================================================
567
+ // Pairing-approval primitive (#5510, epic #5509)
568
+ //
569
+ // A new device sends `pair_request`; the daemon queues it with a 6-digit
570
+ // verify code and a TTL, fans the request out to host-level surfaces, and
571
+ // issues a session token only when an approver confirms it. The queue is an
572
+ // unauthenticated-fed DoS surface — bounded by cap + TTL + per-source rate.
573
+ // ===================================================================
574
+
575
+ /**
576
+ * Queue a new pending pair request.
577
+ *
578
+ * The verify code is generated SERVER-SIDE and returned to the caller only so
579
+ * the WsServer can relay it to the requester (display) and to host surfaces
580
+ * (compare). The requester never sends it back, so a mismatch is impossible by
581
+ * construction.
582
+ *
583
+ * @param {object} args
584
+ * @param {string} args.requestId - client-generated correlation id
585
+ * @param {string} [args.deviceName] - attacker-controlled label (already
586
+ * length-capped at the schema; re-clamped here defensively)
587
+ * @param {string} args.source - rate-limit key (CF-Connecting-IP / socket ip)
588
+ * @returns {{ ok: true, verifyCode: string, expiresAt: number }
589
+ * | { ok: false, reason: 'rate_limited'|'queue_full'|'duplicate_request'|'invalid' }}
590
+ */
591
+ enqueuePendingRequest({ requestId, deviceName = '', source = '' } = {}) {
592
+ if (this._destroyed) return { ok: false, reason: 'invalid' }
593
+ if (typeof requestId !== 'string' || requestId.length === 0) {
594
+ return { ok: false, reason: 'invalid' }
595
+ }
596
+
597
+ this._sweepPending()
598
+
599
+ // Per-source rate limit (rolling window). Checked BEFORE the cap so a
600
+ // single noisy source cannot starve the cap-rejection path for others.
601
+ if (this._isRateLimited(source)) {
602
+ return { ok: false, reason: 'rate_limited' }
603
+ }
604
+
605
+ // Duplicate requestId — the caller should mint a fresh id. Reject rather
606
+ // than overwrite so an in-flight approval can never be hijacked by a
607
+ // collision.
608
+ if (this._pendingRequests.has(requestId)) {
609
+ return { ok: false, reason: 'duplicate_request' }
610
+ }
611
+
612
+ // Global cap. Reject newest-on-full (fail closed) rather than evicting an
613
+ // existing entry — evicting would silently drop a request the user may be
614
+ // mid-approval on.
615
+ if (this._pendingRequests.size >= MAX_PENDING_REQUESTS) {
616
+ return { ok: false, reason: 'queue_full' }
617
+ }
618
+
619
+ // Count this request against the source's bucket only after it is accepted.
620
+ this._recordRateAttempt(source)
621
+
622
+ const verifyCode = this._generateVerifyCode()
623
+ const expiresAt = Date.now() + this._pendingTtlMs
624
+ const cleanName = typeof deviceName === 'string' ? deviceName.slice(0, 64) : ''
625
+ this._pendingRequests.set(requestId, {
626
+ deviceName: cleanName,
627
+ verifyCode,
628
+ expiresAt,
629
+ resolved: false,
630
+ })
631
+
632
+ this._ensureSweepTimer()
633
+ return { ok: true, verifyCode, expiresAt }
634
+ }
635
+
636
+ /**
637
+ * Snapshot of a pending request for fan-out to host surfaces. Never includes
638
+ * the issued token (none exists yet). Returns null if absent/expired/resolved.
639
+ */
640
+ getPendingRequest(requestId) {
641
+ const entry = this._pendingRequests.get(requestId)
642
+ if (!entry || entry.resolved) return null
643
+ if (Date.now() > entry.expiresAt) return null
644
+ return {
645
+ requestId,
646
+ deviceName: entry.deviceName,
647
+ verifyCode: entry.verifyCode,
648
+ expiresAt: entry.expiresAt,
649
+ }
650
+ }
651
+
652
+ /** All live (unresolved, unexpired) pending requests — for surface replay. */
653
+ listPendingRequests() {
654
+ this._sweepPending()
655
+ const out = []
656
+ for (const [requestId, entry] of this._pendingRequests) {
657
+ if (entry.resolved) continue
658
+ out.push({
659
+ requestId,
660
+ deviceName: entry.deviceName,
661
+ verifyCode: entry.verifyCode,
662
+ expiresAt: entry.expiresAt,
663
+ })
664
+ }
665
+ return out
666
+ }
667
+
668
+ /**
669
+ * Approve a pending request and issue a session token EXACTLY once. A second
670
+ * approve of the same requestId is a no-op error (`already_resolved`).
671
+ *
672
+ * The issued token is an unbound (host-authority) session token — same class
673
+ * and TTL as a linking-mode QR pairing. The verify code is never consulted
674
+ * here: the approver confirmed the requestId out-of-band by eyeballing the
675
+ * code on both screens.
676
+ *
677
+ * @param {string} requestId
678
+ * @returns {{ ok: true, token: string }
679
+ * | { ok: false, reason: 'not_found'|'expired'|'already_resolved' }}
680
+ */
681
+ approvePendingRequest(requestId) {
682
+ if (this._destroyed) return { ok: false, reason: 'not_found' }
683
+ const entry = this._pendingRequests.get(requestId)
684
+ if (!entry) return { ok: false, reason: 'not_found' }
685
+ if (entry.resolved) return { ok: false, reason: 'already_resolved' }
686
+ if (Date.now() > entry.expiresAt) {
687
+ entry.resolved = true
688
+ return { ok: false, reason: 'expired' }
689
+ }
690
+
691
+ // Mark resolved BEFORE issuing the token so a concurrent re-entrant approve
692
+ // (same tick) cannot mint a second token for the same request. The resolved
693
+ // entry stays in the map as a tombstone (reaped on the next sweep) so a
694
+ // second approve returns `already_resolved`, not `not_found`.
695
+ entry.resolved = true
696
+
697
+ const token = randomBytes(SESSION_TOKEN_BYTES).toString('base64url')
698
+ // Unbound (host-authority) token — sessionId: null, like linking-mode QR.
699
+ this._storeSessionToken(token, { createdAt: Date.now(), sessionId: null })
700
+ return { ok: true, token }
701
+ }
702
+
703
+ /**
704
+ * Deny / cancel a pending request. Returns true if a live entry was denied.
705
+ * Idempotent: denying an already-resolved/absent request returns false. The
706
+ * resolved tombstone is reaped on the next sweep.
707
+ */
708
+ denyPendingRequest(requestId) {
709
+ const entry = this._pendingRequests.get(requestId)
710
+ if (!entry || entry.resolved) return false
711
+ entry.resolved = true
712
+ return true
713
+ }
714
+
715
+ /** Generate a zero-padded 6-digit verification code (0-999999). */
716
+ _generateVerifyCode() {
717
+ // rejection-sampling-free: 4 bytes → uint32 → mod 1_000_000. The tiny modulo
718
+ // bias (2^32 % 1e6) is irrelevant for a 120s human-comparison code.
719
+ const n = randomBytes(4).readUInt32BE(0) % 1_000_000
720
+ return String(n).padStart(6, '0')
721
+ }
722
+
723
+ _isRateLimited(source) {
724
+ if (!source) return false
725
+ const bucket = this._pendingRateBuckets.get(source)
726
+ if (!bucket) return false
727
+ const now = Date.now()
728
+ if (now - bucket.windowStart > PENDING_RATE_WINDOW_MS) return false
729
+ return bucket.count >= PENDING_RATE_MAX
730
+ }
731
+
732
+ _recordRateAttempt(source) {
733
+ if (!source) return
734
+ const now = Date.now()
735
+ let bucket = this._pendingRateBuckets.get(source)
736
+ if (!bucket || now - bucket.windowStart > PENDING_RATE_WINDOW_MS) {
737
+ // Cap cardinality before inserting a fresh source.
738
+ if (!this._pendingRateBuckets.has(source) && this._pendingRateBuckets.size >= MAX_RATE_SOURCES) {
739
+ const oldest = this._pendingRateBuckets.keys().next().value
740
+ this._pendingRateBuckets.delete(oldest)
741
+ }
742
+ bucket = { count: 0, windowStart: now }
743
+ this._pendingRateBuckets.set(source, bucket)
744
+ }
745
+ bucket.count++
746
+ }
747
+
748
+ /**
749
+ * Remove expired pending requests, emitting `pending_request_expired` for
750
+ * each so the WsServer can notify the requester and retract host banners.
751
+ */
752
+ _sweepPending() {
753
+ if (this._destroyed) return
754
+ const now = Date.now()
755
+ for (const [requestId, entry] of this._pendingRequests) {
756
+ if (entry.resolved || now > entry.expiresAt) {
757
+ this._pendingRequests.delete(requestId)
758
+ if (!entry.resolved) {
759
+ this.emit('pending_request_expired', { requestId })
760
+ }
761
+ }
762
+ }
763
+ // Prune stale rate buckets opportunistically.
764
+ for (const [source, bucket] of this._pendingRateBuckets) {
765
+ if (now - bucket.windowStart > PENDING_RATE_WINDOW_MS) {
766
+ this._pendingRateBuckets.delete(source)
767
+ }
768
+ }
769
+ if (this._pendingRequests.size === 0 && this._sweepTimer) {
770
+ clearInterval(this._sweepTimer)
771
+ this._sweepTimer = null
772
+ }
773
+ }
774
+
775
+ _ensureSweepTimer() {
776
+ if (this._destroyed || this._sweepTimer) return
777
+ this._sweepTimer = setInterval(() => this._sweepPending(), PENDING_SWEEP_INTERVAL_MS)
778
+ this._sweepTimer.unref?.()
779
+ }
780
+
781
+ destroy() {
782
+ this._destroyed = true
783
+ this._current = null
784
+ this._activePairings.clear()
785
+ this._sessionTokens.clear()
786
+ this._pendingRequests.clear()
787
+ this._pendingRateBuckets.clear()
788
+ if (this._refreshTimer) {
789
+ clearTimeout(this._refreshTimer)
790
+ this._refreshTimer = null
791
+ }
792
+ if (this._sweepTimer) {
793
+ clearInterval(this._sweepTimer)
794
+ this._sweepTimer = null
795
+ }
796
+ if (this._sessionTokenSweepTimer) {
797
+ clearInterval(this._sessionTokenSweepTimer)
798
+ this._sessionTokenSweepTimer = null
799
+ }
800
+ this.removeAllListeners()
801
+ }
802
+
803
+ _generatePairing() {
804
+ // Prune expired entries
805
+ const now = Date.now()
806
+ for (const [id, entry] of this._activePairings) {
807
+ if (now > entry.expiresAt) {
808
+ this._activePairings.delete(id)
809
+ }
810
+ }
811
+
812
+ // Cap active pairings to prevent unbounded growth
813
+ if (this._activePairings.size >= MAX_ACTIVE_PAIRINGS) {
814
+ const oldest = this._activePairings.keys().next().value
815
+ this._activePairings.delete(oldest)
816
+ }
817
+
818
+ const id = generateTypeableCode()
819
+ const expiresAt = now + this._ttlMs
820
+ this._current = { id, createdAt: now, expiresAt }
821
+ this._activePairings.set(id, { expiresAt, used: false })
822
+ }
823
+
824
+ _scheduleRefresh() {
825
+ if (this._destroyed) return
826
+ // Refresh slightly before expiry to ensure there's always a valid ID
827
+ const refreshIn = Math.max(this._ttlMs - 5000, this._ttlMs * 0.9)
828
+ this._refreshTimer = setTimeout(() => {
829
+ if (this._destroyed) return
830
+ this._generatePairing()
831
+ this.emit('pairing_refreshed', { pairingId: this._current.id })
832
+ this._scheduleRefresh()
833
+ }, refreshIn)
834
+ this._refreshTimer.unref?.()
835
+ }
836
+ }