@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,676 @@
1
+ import { randomUUID } from 'crypto'
2
+ import { createLogger } from './logger.js'
3
+ import { RateLimiter, getRateLimitKey } from './rate-limiter.js'
4
+ import { buildSessionTokenMismatchPayload } from './handler-utils.js'
5
+ import { settlePush } from './push.js'
6
+ import { createPermissionResolver } from './permission-resolver.js'
7
+ import { sendOversizeResponse } from './http-oversize.js'
8
+ import { redactValue, sanitizeToolInput } from './redaction.js'
9
+ import { buildPermissionRequestMessage } from '@chroxy/protocol'
10
+
11
+ const log = createLogger('ws')
12
+
13
+ // -- Permission TTL --
14
+ const PERMISSION_TTL_MS = 300_000 // 5 minutes
15
+
16
+ // -- Broadcast safety --
17
+ // `sanitizeToolInput` (key-name + recursive value-shape redaction) lives in
18
+ // redaction.js (#6038) so the SDK/TUI provider path (permission-manager.js)
19
+ // shares the exact same sanitizer as this hook path. Imported above and
20
+ // re-exported below for back-compat with existing importers/tests.
21
+
22
+ /**
23
+ * Build the human-readable `description` broadcast alongside a permission
24
+ * request. #6029: the description is derived from RAW toolInput and broadcast
25
+ * next to the sanitized `input`, so a secret in command/url/etc. would leak here
26
+ * even though `input` is clean. The final string is run through `redactValue` so
27
+ * the broadcast description can never carry a secret-shaped value.
28
+ *
29
+ * @param {object} toolInput
30
+ * @returns {string}
31
+ */
32
+ function buildPermissionDescription(toolInput) {
33
+ const raw = toolInput.description
34
+ || toolInput.command
35
+ || toolInput.file_path
36
+ || toolInput.pattern
37
+ || toolInput.query
38
+ || JSON.stringify(toolInput).slice(0, 200)
39
+ return redactValue(raw)
40
+ }
41
+
42
+ /**
43
+ * #5372 — single JSON response helper for the permission HTTP handlers. The
44
+ * `writeHead(status, {'Content-Type':'application/json'})` + `end(JSON.stringify(...))`
45
+ * pattern was hand-written 12+ times across the two handlers, which let the
46
+ * content-type and error-body shape drift between sites. Centralizing it gives
47
+ * one place to set the header; `extraHeaders` covers the one site (rate-limit)
48
+ * that also emits `Retry-After`. The `Content-Type` is merged AFTER
49
+ * `extraHeaders` so a caller can never accidentally override it (#5389 review).
50
+ *
51
+ * @param {import('http').ServerResponse} res
52
+ * @param {number} status - HTTP status code.
53
+ * @param {object} body - JSON-serializable response body.
54
+ * @param {object} [extraHeaders] - additional response headers to merge.
55
+ */
56
+ function sendJson(res, status, body, extraHeaders) {
57
+ res.writeHead(status, { ...extraHeaders, 'Content-Type': 'application/json' })
58
+ res.end(JSON.stringify(body))
59
+ }
60
+
61
+ /**
62
+ * Create a permission handler for the WsServer.
63
+ * Manages HTTP permission lifecycle (hook requests, responses, resend, resolve).
64
+ *
65
+ * @param {Object} opts
66
+ * @param {Function} opts.sendFn - (ws, message) => void
67
+ * @param {Function} opts.broadcastFn - (message) => void
68
+ * @param {Function} opts.validateBearerAuth - (req, res) => boolean — validates main API token (used by /permission-response)
69
+ * @param {Function} opts.validateHookAuth - (req, res) => boolean — validates per-session hook secret (used by /permission)
70
+ * @param {Object|null} opts.pushManager - PushManager instance (nullable)
71
+ * @param {Map} opts.pendingPermissions - requestId -> { resolve, timer } (owned by WsServer)
72
+ * @param {Map} opts.permissionSessionMap - requestId -> sessionId (owned by WsServer)
73
+ * @param {Function} [opts.registerPermissionRoute] - (requestId, sessionId) => void. Optional WsServer-provided helper that records the permissionSessionMap entry AND auto-subscribes every currently-eligible authenticated client to sessionId, keeping the settings-handler's unbound-client subscription guard (#4798) symmetric with the _broadcastToSession recipient filter. When omitted (unit-test fixtures constructing the handler directly), all three dispatch paths (HTTP request, HTTP resend on reconnect, and any future direct map writes) fall back to a bare permissionSessionMap.set() — security-equivalent for tests because there are no real WS clients to auto-subscribe.
74
+ * @param {Function} [opts.unregisterPermissionRoute] - (requestId) => void. Optional WsServer-provided teardown counterpart to registerPermissionRoute (#5704): on resolve/expire it deletes the permissionSessionMap entry AND decrements the permission-induced subscription refcount, removing the auto-subscription once no permission still holds it (and the client is neither active on nor explicitly subscribed to the session). Omitted in unit-test fixtures (which use bare permissionSessionMap semantics).
75
+ * @param {Function} opts.getSessionManager - () => sessionManager (late-bound for test compat)
76
+ * @param {Object|null} opts.pairingManager - PairingManager instance used to look up token→sessionId bindings for the HTTP permission-response fallback. Optional — when null, HTTP responses skip the binding check (single-token mode).
77
+ * @param {Function} [opts.findSessionByHookSecret] - (hookSecret) => session|null. Optional session lookup used during /permission handling to resolve the session associated with a per-session hook secret (#2831 — pause that session's inactivity timer while a hook permission is outstanding).
78
+ * @param {Function} [opts.getPermissionAudit] - () => PermissionAuditLog or null (late-bound). When present, HTTP user-initiated permission responses are audited with `clientId: 'http'` and `reason: 'user'` (#3059). Optional for backwards compat with existing test fixtures.
79
+ * @param {Object} [opts.rateLimit] - Override RateLimiter config for POST /permission. Mainly for tests; production uses the 30+10 default below.
80
+ * @returns {Object} Permission handler methods
81
+ */
82
+ export function createPermissionHandler({ sendFn, broadcastFn, validateBearerAuth, validateHookAuth, pushManager, pendingPermissions, permissionSessionMap, registerPermissionRoute, unregisterPermissionRoute, getSessionManager, pairingManager, findSessionByHookSecret, getPermissionAudit, rateLimit }) {
83
+ let _permissionCounter = 0
84
+
85
+ // Rate limiter for HTTP permission requests (per source IP)
86
+ // #3996: name='http-permission' so eviction logs and /diagnostics can
87
+ // identify this limiter distinctly from the WS-side _permissionRateLimiter.
88
+ // name comes AFTER the spread so a stray `name` in the override (e.g.
89
+ // from a test fixture) can't displace the canonical 'http-permission'
90
+ // tag that operators rely on in eviction logs and /diagnostics.
91
+ const _httpPermissionLimiter = new RateLimiter({ ...(rateLimit || { windowMs: 60_000, maxMessages: 30, burst: 10 }), name: 'http-permission' })
92
+
93
+ // Fall back to validateBearerAuth if validateHookAuth is not provided (backwards compat for tests)
94
+ const _validateHookAuth = validateHookAuth || validateBearerAuth
95
+
96
+ // #5704: tear down a permission route's map entry AND its permission-induced
97
+ // subscription refcount together. Prefer the WsServer-provided hook (which
98
+ // drops the refcount and unsubscribes idle clients); fall back to a bare
99
+ // delete for unit-test fixtures that construct the handler without it (no real
100
+ // WS clients to unsubscribe — behaviour-equivalent).
101
+ function tearDownRoute(requestId) {
102
+ if (typeof unregisterPermissionRoute === 'function') unregisterPermissionRoute(requestId)
103
+ else permissionSessionMap.delete(requestId)
104
+ }
105
+
106
+ // #5373: the session-binding check + SDK-vs-legacy dispatch + audit live in
107
+ // the shared permission-resolver (also used by the WS handler in
108
+ // settings-handlers.js), so the binding rule lives in ONE place. The HTTP
109
+ // handler below maps the resolver's transport-agnostic ResolveResult to HTTP
110
+ // status codes; the body buffering / oversize / crash-guard stay here.
111
+ // `resolvePermission` is a hoisted function declaration below.
112
+ const permissionResolver = createPermissionResolver({
113
+ permissionSessionMap,
114
+ pendingPermissions,
115
+ getSessionManager,
116
+ resolveLegacyPermission: resolvePermission,
117
+ getPermissionAudit,
118
+ onRouteTeardown: tearDownRoute,
119
+ })
120
+
121
+ /** Handle POST /permission from the hook script */
122
+ function handlePermissionRequest(req, res) {
123
+ // Rate limit by source IP. Use getRateLimitKey so that when the request
124
+ // arrived via the local cloudflared process (TCP peer = 127.0.0.1) we key
125
+ // off the forwarded CF-Connecting-IP / X-Forwarded-For header instead of
126
+ // the loopback address. Without this every tunneled client collapses into
127
+ // one bucket and a single noisy mobile can rate-limit everyone (#3980).
128
+ // For direct (non-loopback) peers the helper falls back to the kernel-
129
+ // supplied socket address so the header cannot be spoofed to share or
130
+ // exhaust another IP's bucket — same approach #3978 took for /diagnostics.
131
+ const socketIp = req.socket?.remoteAddress || ''
132
+ const clientIp = getRateLimitKey(socketIp, req)
133
+ const { allowed, retryAfterMs } = _httpPermissionLimiter.check(clientIp)
134
+ if (!allowed) {
135
+ log.warn(`Rate limited POST /permission from ${clientIp}`)
136
+ sendJson(res, 429, { error: 'rate limited', retryAfterMs }, { 'Retry-After': Math.ceil(retryAfterMs / 1000) })
137
+ return
138
+ }
139
+
140
+ if (!_validateHookAuth(req, res)) {
141
+ log.warn('Rejected unauthenticated POST /permission')
142
+ return
143
+ }
144
+
145
+ const MAX_BODY = 65536
146
+ // utf8 decoding + byte-accurate cap (Buffer.byteLength, not UTF-16 code
147
+ // units), checked BEFORE append so the violating chunk is never buffered.
148
+ req.setEncoding('utf8')
149
+ let body = ''
150
+ let bodyBytes = 0
151
+ let oversized = false
152
+ req.on('data', (chunk) => {
153
+ if (oversized) return
154
+ bodyBytes += Buffer.byteLength(chunk, 'utf8')
155
+ if (bodyBytes > MAX_BODY) {
156
+ oversized = true
157
+ // #5433: respond BEFORE teardown — req.destroy() here suppressed
158
+ // 'end' (the 413 branch below was dead code) and the hook saw a
159
+ // socket reset instead of the documented 413 deny. The helper stops
160
+ // consumption without buffering past the cap and closes the
161
+ // connection after the response flushes.
162
+ sendOversizeResponse(req, res, { decision: 'deny' })
163
+ return
164
+ }
165
+ body += chunk
166
+ })
167
+ req.on('end', () => {
168
+ // #5313 (WP-1.3): this callback fires on a later tick, after the HTTP
169
+ // dispatch that registered it has already returned — so a throw here is
170
+ // NOT caught by the route handler's wrapper and escapes to
171
+ // uncaughtException → process.exit(1), crashing the daemon. The inner
172
+ // JSON.parse is already guarded; this wraps the WHOLE body (res.writeHead
173
+ // on a torn-down socket, downstream session/broadcast calls) so any other
174
+ // throw is contained and returns a 500 to the client when possible.
175
+ try {
176
+ // #5433: the 413 deny was already sent from the 'data' handler.
177
+ if (oversized) return
178
+
179
+ let hookData
180
+ try {
181
+ hookData = JSON.parse(body)
182
+ } catch {
183
+ sendJson(res, 400, { decision: 'deny' })
184
+ return
185
+ }
186
+
187
+ const requestId = `perm-${randomUUID()}`
188
+
189
+ log.info(`Permission request ${requestId}: ${hookData.tool_name || 'unknown tool'}`)
190
+
191
+ const tool = hookData.tool_name || 'Unknown tool'
192
+ const toolInput = hookData.tool_input || {}
193
+ const sanitizedInput = sanitizeToolInput(toolInput)
194
+ const description = buildPermissionDescription(toolInput)
195
+
196
+ // #2831: find the CliSession this hook permission belongs to (via
197
+ // the per-session hook secret from the Authorization header) so we
198
+ // can pause its inactivity timer while the user decides.
199
+ // #2832: also use the chroxy-managed sessionId to populate
200
+ // permissionSessionMap so paired clients (boundSessionId set) can
201
+ // approve hook-originated permissions for their bound session.
202
+ // Without this entry, the binding check in permission_response
203
+ // rejects every approval with SESSION_TOKEN_MISMATCH.
204
+ const authHeader = (req.headers && req.headers['authorization']) || ''
205
+ const hookToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
206
+ const ownerLookup = (hookToken && typeof findSessionByHookSecret === 'function')
207
+ ? findSessionByHookSecret(hookToken)
208
+ : null
209
+ const ownerSession = ownerLookup?.session ?? null
210
+ const ownerSessionId = ownerLookup?.sessionId ?? null
211
+ if (ownerSession && typeof ownerSession.notifyPermissionPending === 'function') {
212
+ ownerSession.notifyPermissionPending(requestId)
213
+ }
214
+ if (ownerSessionId) {
215
+ // #4798: prefer the WsServer-provided helper so dispatch also auto-
216
+ // subscribes eligible clients to the permission's session — keeps the
217
+ // settings-handler subscription guard symmetric with the broadcast
218
+ // filter. Fall back to a bare Map.set when the helper isn't wired
219
+ // (unit-test fixtures construct the handler directly).
220
+ if (typeof registerPermissionRoute === 'function') {
221
+ registerPermissionRoute(requestId, ownerSessionId)
222
+ } else {
223
+ permissionSessionMap.set(requestId, ownerSessionId)
224
+ }
225
+ }
226
+ // Diagnostic correlation log for #2832 — paired with
227
+ // [session-binding-resend] and [session-binding-reject]. The
228
+ // requestId is the stable correlation key across the permission
229
+ // lifecycle; sessionId reflects the chroxy session that owns the
230
+ // hook secret (or `none` when the hook secret is unattributable).
231
+ // Gated at debug level (#2854) to avoid spamming prod logs — enable
232
+ // with `LOG_LEVEL=debug` when triangulating SESSION_TOKEN_MISMATCH.
233
+ log.debug(`[session-binding-create] permission ${requestId} created via HTTP (sessionId=${ownerSessionId ?? 'none'}, sourceIp=${clientIp})`)
234
+
235
+ broadcastFn(buildPermissionRequestMessage({
236
+ requestId,
237
+ tool,
238
+ description,
239
+ input: sanitizedInput,
240
+ remainingMs: 300_000,
241
+ // #5667: carry the owning session so clients route the prompt to the
242
+ // session that actually asked, instead of falling back to whatever tab
243
+ // is focused. Matches the resend-on-reconnect (line ~485) and SDK
244
+ // (line ~406) paths, which already include sessionId. The builder omits
245
+ // `sessionId` entirely (absent, not null) when undefined — the request
246
+ // maps to no chroxy session and clients fall back to the active one.
247
+ sessionId: ownerSessionId || undefined,
248
+ }))
249
+
250
+ if (pushManager) {
251
+ // #5702 (8d): settle the fire-and-forget send so a failed phone
252
+ // notification is logged (named), not silently dropped while the
253
+ // dashboard card still appears.
254
+ settlePush(
255
+ pushManager.send('permission', 'Permission needed', `Claude wants to use: ${tool}`, { requestId, tool }, 'permission'),
256
+ `permission requested: ${tool}`,
257
+ log,
258
+ )
259
+ }
260
+
261
+ let closed = false
262
+
263
+ const cleanup = () => {
264
+ if (timer) clearTimeout(timer)
265
+ pendingPermissions.delete(requestId)
266
+ // #5704: tear down the map entry + permission-induced subscription
267
+ // refcount together (resolve / timeout-auto-deny / connection-close all
268
+ // land here). Was a bare permissionSessionMap.delete that left the
269
+ // auto-subscription dangling for the permission's lifetime + forever.
270
+ tearDownRoute(requestId)
271
+ // #2831: release the inactivity-timer pause, regardless of
272
+ // whether we're cleaning up from a resolve, timeout, or abort.
273
+ if (ownerSession && typeof ownerSession.notifyPermissionResolved === 'function') {
274
+ ownerSession.notifyPermissionResolved(requestId)
275
+ }
276
+ }
277
+
278
+ const onClose = () => {
279
+ if (closed) return
280
+ closed = true
281
+ log.info(`Permission ${requestId} connection closed by client`)
282
+ cleanup()
283
+ }
284
+
285
+ req.on('aborted', onClose)
286
+ res.on('close', onClose)
287
+
288
+ const timer = setTimeout(() => {
289
+ if (closed) return
290
+ closed = true
291
+ log.info(`Permission ${requestId} timed out, auto-denying`)
292
+ cleanup()
293
+ sendJson(res, 200, { decision: 'deny' })
294
+ }, 300_000)
295
+
296
+ pendingPermissions.set(requestId, {
297
+ resolve: (decision) => {
298
+ if (closed) return
299
+ closed = true
300
+ cleanup()
301
+ log.info(`Permission ${requestId} resolved: ${decision}`)
302
+ sendJson(res, 200, { decision })
303
+ },
304
+ timer,
305
+ data: { requestId, tool, description, input: sanitizedInput, remainingMs: 300_000, createdAt: Date.now() },
306
+ })
307
+ } catch (err) {
308
+ // #5313 (WP-1.3): see the try at the top of this end callback.
309
+ const message = err?.message || String(err)
310
+ log.error(`POST /permission end handler threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
311
+ // #5313 review — the recovery response can ITSELF throw if the original
312
+ // failure was a torn-down socket (res.writeHead/res.end raising). Guard
313
+ // it so the catch can't re-crash the daemon; nothing more we can do.
314
+ try {
315
+ if (!res.headersSent) {
316
+ sendJson(res, 500, { error: 'Internal server error' })
317
+ } else {
318
+ res.end()
319
+ }
320
+ } catch { /* socket already torn down */ }
321
+ }
322
+ })
323
+ }
324
+
325
+ /** Handle POST /permission-response from iOS notification actions (HTTP fallback) */
326
+ function handlePermissionResponseHttp(req, res) {
327
+ if (!validateBearerAuth(req, res)) {
328
+ log.warn('Rejected unauthenticated POST /permission-response')
329
+ return
330
+ }
331
+
332
+ // Look up whether the presented Bearer token is bound to a specific
333
+ // session via pairing. If it is, the caller may ONLY respond to
334
+ // permission requests belonging to that bound session. Without this,
335
+ // a session-bound pairing token could approve/deny permission
336
+ // requests from other sessions via the HTTP fallback — discovered
337
+ // in the 2026-04-11 production readiness audit (blocker 5). The
338
+ // 616aeaf62 / 2c0ac7d2d session-binding sweep missed the HTTP path.
339
+ const authHeader = (req.headers && req.headers['authorization']) || ''
340
+ const presentedToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : null
341
+ const callerBoundSessionId = (pairingManager && presentedToken)
342
+ ? pairingManager.getSessionIdForToken(presentedToken)
343
+ : null
344
+
345
+ // SECURITY (swarm-audit): reject an UNBOUND PAIRING token — a pairing-ISSUED
346
+ // token with no bound session, e.g. one a device obtained from the auto-
347
+ // refreshing linking-mode QR, which is handed out PRE host-approval. Such a
348
+ // token resolves to callerBoundSessionId=null, which the resolver treats as
349
+ // unrestricted, so without this guard it could answer ANY session's permission
350
+ // over this HTTP fallback. This PRESERVES the #5373 "invariant G": the PRIMARY
351
+ // API token is NOT a pairing token (isSessionTokenValid=false) so it keeps full
352
+ // HTTP authority, and bound pairing tokens are binding-checked by the resolver
353
+ // below — only unbound *pairing* tokens are rejected. The typeof guard keeps
354
+ // single-token / partial-pairingManager modes working (no isSessionTokenValid →
355
+ // treated as the primary token, i.e. not rejected).
356
+ const tokenIsPairingToken = !!(
357
+ pairingManager &&
358
+ typeof pairingManager.isSessionTokenValid === 'function' &&
359
+ presentedToken &&
360
+ pairingManager.isSessionTokenValid(presentedToken)
361
+ )
362
+ if (tokenIsPairingToken && callerBoundSessionId === null) {
363
+ log.warn('Rejected HTTP /permission-response: an unbound pairing token cannot answer permission requests')
364
+ sendJson(res, 403, { error: 'unbound token cannot answer cross-session permissions' })
365
+ return
366
+ }
367
+
368
+ const MAX_BODY = 4096
369
+ // utf8 decoding + byte-accurate cap, checked BEFORE append — see
370
+ // handlePermissionRequest above; the three capped readers stay in lockstep.
371
+ req.setEncoding('utf8')
372
+ let body = ''
373
+ let bodyBytes = 0
374
+ let oversized = false
375
+ req.on('data', (chunk) => {
376
+ if (oversized) return
377
+ bodyBytes += Buffer.byteLength(chunk, 'utf8')
378
+ if (bodyBytes > MAX_BODY) {
379
+ oversized = true
380
+ // #5433: same shared rejection as handlePermissionRequest /
381
+ // /api/events — this site already responded before teardown, but the
382
+ // helper also stops consumption (pause + listener removal, so an
383
+ // attacker can't keep streaming into a live connection) and closes
384
+ // the socket after the 413 flushes (Connection: close). It contains
385
+ // torn-down-socket throws internally (#5389 guard preserved).
386
+ sendOversizeResponse(req, res, { error: 'body too large' })
387
+ return
388
+ }
389
+ body += chunk
390
+ })
391
+ req.on('end', () => {
392
+ // #5313 (WP-1.3): same crash shape as handlePermissionRequest's end
393
+ // callback — fires on a later tick, escapes the route wrapper, and an
394
+ // uncaught throw (res.writeHead on a torn-down socket, getSessionManager
395
+ // / respondToPermission / broadcast downstream) crashes the daemon.
396
+ // Wrap the whole body; the inner JSON.parse guard is preserved.
397
+ try {
398
+ if (oversized) return
399
+
400
+ let parsed
401
+ try {
402
+ parsed = JSON.parse(body)
403
+ } catch {
404
+ sendJson(res, 400, { error: 'invalid JSON' })
405
+ return
406
+ }
407
+
408
+ const { requestId, decision } = parsed
409
+ if (!requestId || typeof requestId !== 'string') {
410
+ sendJson(res, 400, { error: 'missing requestId' })
411
+ return
412
+ }
413
+
414
+ const validDecisions = ['allow', 'deny', 'allowAlways']
415
+ if (!validDecisions.includes(decision)) {
416
+ sendJson(res, 400, { error: `invalid decision, must be one of: ${validDecisions.join(', ')}` })
417
+ return
418
+ }
419
+
420
+ // #5373: delegate the binding check + SDK-vs-legacy dispatch + audit to
421
+ // the shared resolver. clientId 'http' distinguishes these from auto-deny
422
+ // entries (clientId=null) in forensic queries. HTTP passes NO dispatch
423
+ // fallback — it has no per-connection activeSessionId, so the dispatch
424
+ // session is the raw mapping only (unchanged from the prior inline code).
425
+ const result = permissionResolver.resolve(requestId, decision, callerBoundSessionId, { clientId: 'http' })
426
+ switch (result.kind) {
427
+ case 'binding_mismatch': {
428
+ // For a bound caller the requestId MUST be explicitly mapped to that
429
+ // session (no fallback bypass — the #2806 residual, enforced in the
430
+ // resolver). Reject cross-session responses with the unified payload.
431
+ log.warn(`HTTP /permission-response rejected: token bound to ${result.boundSessionId} tried to respond to ${requestId}`)
432
+ // Issue #2912: enrich the HTTP body with the same fields as the WS
433
+ // SESSION_TOKEN_MISMATCH payload so clients handle both surfaces
434
+ // identically (legacy `error` key preserved for old clients).
435
+ const unified = buildSessionTokenMismatchPayload({
436
+ sessionManager: getSessionManager(),
437
+ boundSessionId: result.boundSessionId,
438
+ message: 'not authorized for this permission request',
439
+ })
440
+ sendJson(res, 403, { error: unified.message, ...unified })
441
+ return
442
+ }
443
+ case 'resolved': {
444
+ // #3048: the SDK branch's broadcast is handled by the unified pipeline
445
+ // (PermissionManager → SdkSession → SessionManager → broadcast). The
446
+ // legacy branch has no PermissionManager, so it keeps the inline
447
+ // broadcast (#2905) — sessionId included only when the request was mapped.
448
+ if (result.via === 'legacy') {
449
+ broadcastFn({
450
+ type: 'permission_resolved',
451
+ requestId,
452
+ decision,
453
+ ...(result.sessionId ? { sessionId: result.sessionId } : {}),
454
+ })
455
+ }
456
+ log.info(`Permission ${requestId} resolved via HTTP: ${decision} (${result.via})`)
457
+ sendJson(res, 200, { ok: true })
458
+ return
459
+ }
460
+ case 'expired':
461
+ // UX landmine #5: auto-denied (timed out) before the user tapped the
462
+ // notification — tell the app so it shows "expired", not "approved".
463
+ log.info(`Permission ${requestId} already expired when HTTP response arrived (SDK)`)
464
+ sendJson(res, 410, { error: 'expired', message: 'This permission request has already expired or been resolved' })
465
+ return
466
+ case 'not_found':
467
+ default:
468
+ sendJson(res, 404, { error: 'unknown or expired requestId' })
469
+ return
470
+ }
471
+ } catch (err) {
472
+ // #5313 (WP-1.3): see the try at the top of this end callback.
473
+ const message = err?.message || String(err)
474
+ log.error(`POST /permission-response end handler threw: ${message}${err?.stack ? '\n' + err.stack : ''}`)
475
+ // #5313 review — guard the recovery response so a torn-down-socket
476
+ // throw in writeHead/end can't re-crash the daemon from the catch.
477
+ try {
478
+ if (!res.headersSent) {
479
+ sendJson(res, 500, { error: 'Internal server error' })
480
+ } else {
481
+ res.end()
482
+ }
483
+ } catch { /* socket already torn down */ }
484
+ }
485
+ })
486
+ }
487
+
488
+ /**
489
+ * Re-send any pending permission requests to a newly connected/reconnected client.
490
+ * @param {WebSocket} ws
491
+ * @param {Object} [client] - Optional client descriptor for diagnostic logging (#2832)
492
+ */
493
+ function resendPendingPermissions(ws, client) {
494
+ // SDK-mode: check all sessions for pending permissions
495
+ const sm = getSessionManager()
496
+ if (sm?._sessions instanceof Map) {
497
+ for (const [sessionId, entry] of sm._sessions) {
498
+ if (entry.session?._pendingPermissions instanceof Map) {
499
+ for (const [requestId] of entry.session._pendingPermissions) {
500
+ const permData = entry.session._lastPermissionData?.get(requestId)
501
+ if (permData) {
502
+ const elapsed = Math.max(0, Date.now() - (permData.createdAt ?? Date.now()))
503
+ const ttl = permData.remainingMs ?? PERMISSION_TTL_MS
504
+ const remainingMs = Math.min(ttl, Math.max(0, ttl - elapsed))
505
+ if (remainingMs <= 0) {
506
+ log.debug(`Skipping expired permission ${requestId}`)
507
+ continue
508
+ }
509
+ log.info(`Re-sending pending permission ${requestId} to reconnected client (${Math.round(remainingMs / 1000)}s remaining)`)
510
+ // Diagnostic correlation log for #2832 — grep by requestId
511
+ // to see whether the recipient's boundSessionId matches the
512
+ // origin session recorded at [session-binding-create]. Gated
513
+ // at debug level (#2854) to avoid spamming prod logs on every
514
+ // post-auth reconnection — enable with `LOG_LEVEL=debug`.
515
+ if (client) {
516
+ log.debug(`[session-binding-resend] permission ${requestId} resent to client ${client.id} (sessionId=${sessionId}, activeSession=${client.activeSessionId ?? 'none'}, boundSession=${client.boundSessionId ?? 'none'})`)
517
+ } else {
518
+ log.debug(`[session-binding-resend] permission ${requestId} resent (sessionId=${sessionId}, client=unknown)`)
519
+ }
520
+ // #4798: prefer the auto-subscribing helper so re-sending a
521
+ // pending permission also seeds subscribedSessionIds on
522
+ // eligible clients — matches the dispatch-time behaviour and
523
+ // keeps the settings-handler subscription guard symmetric
524
+ // across the reconnect path. The bare Map.set fallback covers
525
+ // unit-test fixtures that construct the handler directly.
526
+ if (typeof registerPermissionRoute === 'function') {
527
+ registerPermissionRoute(requestId, sessionId)
528
+ } else {
529
+ permissionSessionMap.set(requestId, sessionId)
530
+ }
531
+ // #6054: buildPermissionRequestMessage throws on field drift (the
532
+ // intended #6031 fail-loud guard). Isolate it per-permission so one
533
+ // malformed pending entry can't abort the loop and strand the
534
+ // remaining valid prompts for this reconnecting client.
535
+ try {
536
+ sendFn(ws, buildPermissionRequestMessage({
537
+ requestId: permData.requestId ?? requestId,
538
+ tool: permData.tool,
539
+ description: permData.description,
540
+ input: permData.input,
541
+ remainingMs,
542
+ sessionId,
543
+ }))
544
+ } catch (err) {
545
+ log.warn(`Skipping malformed pending permission ${requestId} on resend: ${err?.message ?? err}`)
546
+ continue
547
+ }
548
+ }
549
+ }
550
+ }
551
+ }
552
+ }
553
+
554
+ // Legacy HTTP-held permissions
555
+ for (const [requestId, pending] of pendingPermissions) {
556
+ if (pending.data) {
557
+ const elapsed = Math.max(0, Date.now() - (pending.data.createdAt ?? Date.now()))
558
+ const ttl = pending.data.remainingMs ?? PERMISSION_TTL_MS
559
+ const remainingMs = Math.min(ttl, Math.max(0, ttl - elapsed))
560
+ if (remainingMs <= 0) {
561
+ log.debug(`Skipping expired legacy permission ${requestId}`)
562
+ continue
563
+ }
564
+ log.info(`Re-sending pending legacy permission ${requestId} to reconnected client (${Math.round(remainingMs / 1000)}s remaining)`)
565
+ // Gated at debug level (#2854) — see comment above.
566
+ if (client) {
567
+ log.debug(`[session-binding-resend] legacy permission ${requestId} resent to client ${client.id} (activeSession=${client.activeSessionId ?? 'none'}, boundSession=${client.boundSessionId ?? 'none'})`)
568
+ } else {
569
+ log.debug(`[session-binding-resend] legacy permission ${requestId} resent (client=unknown)`)
570
+ }
571
+ // #6054: isolate the per-permission build+send so a single drifted
572
+ // legacy entry can't abort the loop (see SDK path above).
573
+ try {
574
+ sendFn(ws, buildPermissionRequestMessage({
575
+ requestId: pending.data.requestId ?? requestId,
576
+ tool: pending.data.tool,
577
+ description: pending.data.description,
578
+ input: pending.data.input,
579
+ remainingMs,
580
+ }))
581
+ } catch (err) {
582
+ log.warn(`Skipping malformed pending legacy permission ${requestId} on resend: ${err?.message ?? err}`)
583
+ continue
584
+ }
585
+ }
586
+ }
587
+ }
588
+
589
+ /** Resolve a pending permission request */
590
+ function resolvePermission(requestId, decision) {
591
+ const pending = pendingPermissions.get(requestId)
592
+ if (pending) {
593
+ pending.resolve(decision)
594
+ } else {
595
+ log.warn(`No pending permission for ${requestId}`)
596
+ }
597
+ }
598
+
599
+ /**
600
+ * #5731 T7: auto-deny + clear any pending HTTP-hook permissions belonging to
601
+ * a single session. Called when that session is destroyed. Without it, the
602
+ * hook's POST /permission stays parked on a held response with a 5-min
603
+ * auto-deny timer: the tool call blocks for the full timeout, then the timer
604
+ * fires against a session that no longer exists, and the held `res` +
605
+ * resolve closure leak until then. `resolve('deny')` runs the shared
606
+ * cleanup() (clears the timer, deletes both maps, sends the deny response,
607
+ * releases the #2831 inactivity-pause). Collect the ids first so the
608
+ * resolve→cleanup→delete doesn't mutate permissionSessionMap mid-iteration.
609
+ * @param {string} sessionId
610
+ * @returns {number} how many pending permissions were drained
611
+ */
612
+ function drainSessionPermissions(sessionId) {
613
+ if (!sessionId) return 0
614
+ const toDeny = []
615
+ for (const [requestId, sid] of permissionSessionMap) {
616
+ if (sid === sessionId) toDeny.push(requestId)
617
+ }
618
+ let drained = 0
619
+ for (const requestId of toDeny) {
620
+ const pending = pendingPermissions.get(requestId)
621
+ if (!pending) continue
622
+ // Count before resolving: resolve() runs cleanup() (clears the timer +
623
+ // deletes both maps + releases the inactivity pause) FIRST and only then
624
+ // writes the HTTP deny response. So even if that response write throws on
625
+ // an already torn-down socket, the entry IS drained — the leak is gone.
626
+ // Treat such a throw as a debug-level note (the drain succeeded; only the
627
+ // best-effort response write failed) rather than a misleading warning on
628
+ // a mass session-destroy. A pending entry is never already-closed here:
629
+ // cleanup() deletes it from pendingPermissions, so a closed one wouldn't
630
+ // be in the map for us to fetch.
631
+ drained++
632
+ try {
633
+ pending.resolve('deny')
634
+ } catch (err) {
635
+ log.debug(`Pending permission ${requestId} drained for destroyed session ${sessionId}, but the deny response write failed (socket likely gone): ${err?.message || err}`)
636
+ }
637
+ }
638
+ if (drained > 0) {
639
+ log.info(`Drained ${drained} pending HTTP permission(s) for destroyed session ${sessionId}`)
640
+ }
641
+ return drained
642
+ }
643
+
644
+ /** Clean up: auto-deny all pending permissions */
645
+ function destroy() {
646
+ for (const [, pending] of pendingPermissions) {
647
+ clearTimeout(pending.timer)
648
+ try { pending.resolve('deny') } catch {}
649
+ }
650
+ pendingPermissions.clear()
651
+ // #5704: each resolve('deny') above ran cleanup()→tearDownRoute(), so most
652
+ // entries are already gone. Tear down any remainder (e.g. SDK-routed entries
653
+ // with no HTTP pending) through the same hook so the subscription refcount
654
+ // is released, not just the map — then clear to drop any helper-less leftovers.
655
+ for (const requestId of [...permissionSessionMap.keys()]) {
656
+ tearDownRoute(requestId)
657
+ }
658
+ permissionSessionMap.clear()
659
+ }
660
+
661
+ return {
662
+ handlePermissionRequest,
663
+ handlePermissionResponseHttp,
664
+ resendPendingPermissions,
665
+ resolvePermission,
666
+ drainSessionPermissions,
667
+ destroy,
668
+ // #3996: expose the HTTP-permission limiter so /diagnostics can include
669
+ // its eviction stats alongside the three WsServer-owned limiters.
670
+ // Read-only handle — callers must only invoke getEvictionStats() on it.
671
+ _httpPermissionLimiter,
672
+ }
673
+ }
674
+
675
+ // Exported for testing
676
+ export { sanitizeToolInput, buildPermissionDescription }