@mycadet/gateway 0.13.0 → 0.14.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 (410) hide show
  1. package/Dockerfile +1 -0
  2. package/README.md +10 -10
  3. package/eslint.config.mjs +7 -8
  4. package/knip.json +2 -8
  5. package/node_modules/@mycadet/assistant-client/src/__tests__/assistant-client.test.ts +40 -34
  6. package/node_modules/@mycadet/assistant-client/src/http-client.ts +59 -8
  7. package/node_modules/@mycadet/assistant-client/src/index.ts +4 -0
  8. package/node_modules/@mycadet/assistant-client/src/proxy-forward.ts +5 -4
  9. package/node_modules/@mycadet/assistant-client/src/websocket-upstream.ts +21 -31
  10. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/package.json +18 -0
  11. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/endpoint.test.ts +36 -0
  12. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/endpoint.ts +142 -0
  13. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/index.ts +18 -0
  14. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/ipc-framing.ts +295 -0
  15. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/listen-options.ts +3 -0
  16. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.test.ts +444 -0
  17. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.ts +236 -0
  18. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/tsconfig.json +20 -0
  19. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
  20. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
  21. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
  22. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
  23. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
  24. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
  25. package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
  26. package/node_modules/@mycadet/ces-client/package.json +7 -2
  27. package/node_modules/@mycadet/ces-client/src/index.ts +6 -0
  28. package/node_modules/@mycadet/ces-client/src/ipc-credentials.ts +363 -0
  29. package/node_modules/@mycadet/ces-client/src/log-export.ts +187 -0
  30. package/node_modules/@mycadet/ces-client/src/socket-path.ts +34 -0
  31. package/node_modules/@mycadet/ces-client/src/test-support.ts +280 -0
  32. package/node_modules/@mycadet/environments/package.json +0 -1
  33. package/node_modules/@mycadet/environments/src/index.ts +7 -19
  34. package/node_modules/@mycadet/environments/src/shell.test.ts +0 -45
  35. package/node_modules/@mycadet/environments/src/shell.ts +0 -50
  36. package/node_modules/@mycadet/environments/src/test-path-guard.ts +1 -1
  37. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
  38. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
  39. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
  40. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
  41. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
  42. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
  43. package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
  44. package/node_modules/@mycadet/gateway-client/src/__tests__/gateway-client.test.ts +5 -5
  45. package/node_modules/@mycadet/gateway-client/src/__tests__/package-boundary.test.ts +1 -1
  46. package/node_modules/@mycadet/gateway-client/src/__tests__/status-contracts.test.ts +1 -20
  47. package/node_modules/@mycadet/gateway-client/src/admission-policy-contract.ts +1 -2
  48. package/node_modules/@mycadet/gateway-client/src/gateway-ipc-contracts.ts +0 -16
  49. package/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.test.ts +1 -1
  50. package/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
  51. package/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
  52. package/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
  53. package/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
  54. package/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
  55. package/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
  56. package/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
  57. package/package.json +15 -13
  58. package/scripts/generate-openapi.ts +24 -32
  59. package/src/__tests__/actor-token-revocation.test.ts +14 -7
  60. package/src/__tests__/auto-approve-conversation-thresholds.test.ts +16 -16
  61. package/src/__tests__/auto-approve-thresholds.test.ts +22 -20
  62. package/src/__tests__/binding-helpers.test.ts +9 -12
  63. package/src/__tests__/channel-admission-policy-routes.test.ts +20 -34
  64. package/src/__tests__/channel-permission-overrides-routes.test.ts +20 -26
  65. package/src/__tests__/channel-verification-session-proxy.test.ts +36 -22
  66. package/src/__tests__/cli-entry-init.test.ts +103 -0
  67. package/src/__tests__/config.test.ts +4 -5
  68. package/src/__tests__/contact-handlers.test.ts +8 -10
  69. package/src/__tests__/contact-prompt-submit.test.ts +3 -1
  70. package/src/__tests__/contact-record-submit.test.ts +3 -1
  71. package/src/__tests__/contact-rich-read.test.ts +11 -20
  72. package/src/__tests__/contact-store-bind-principal.test.ts +12 -15
  73. package/src/__tests__/contact-store-invites.test.ts +6 -6
  74. package/src/__tests__/contact-store-mark-channel-verified.test.ts +8 -10
  75. package/src/__tests__/contact-store-merge-contacts.test.ts +7 -10
  76. package/src/__tests__/contact-store-mirror-op-missing.test.ts +7 -11
  77. package/src/__tests__/contacts-control-plane-proxy.test.ts +3 -21
  78. package/src/__tests__/contacts-info-client.test.ts +6 -5
  79. package/src/__tests__/contacts-info-joiner.test.ts +8 -13
  80. package/src/__tests__/contacts-scoped-route-fallthrough.test.ts +14 -12
  81. package/src/__tests__/credential-cache.test.ts +1 -6
  82. package/src/__tests__/credential-reader.test.ts +146 -157
  83. package/src/__tests__/credential-requests.test.ts +1 -3
  84. package/src/__tests__/credential-watcher-cloud-bootstrap.test.ts +57 -104
  85. package/src/__tests__/data-migration-m0007-backfill-ingress-invites.test.ts +14 -17
  86. package/src/__tests__/data-migration-m0008-upsert-acl-columns-from-assistant.test.ts +10 -13
  87. package/src/__tests__/data-migration-m0009-invite-fields-backfill.test.ts +20 -19
  88. package/src/__tests__/data-migration-m0010-drop-assistant-ingress-invites.test.ts +12 -15
  89. package/src/__tests__/data-migration-m0013-verification-sessions-backfill.test.ts +20 -23
  90. package/src/__tests__/data-migration-m0014-drop-assistant-verification-tables.test.ts +12 -15
  91. package/src/__tests__/data-migration-m0015-guardian-requests-backfill.test.ts +6 -9
  92. package/src/__tests__/data-migration-m0016-drop-assistant-guardian-tables.test.ts +16 -19
  93. package/src/__tests__/data-migration-m0017-coerce-escalate-policy.test.ts +6 -10
  94. package/src/__tests__/db-connection-isolation.test.ts +1 -2
  95. package/src/__tests__/db-proxy-allowlist.test.ts +25 -16
  96. package/src/__tests__/desktop-stream-websocket.test.ts +34 -28
  97. package/src/__tests__/device-identity-text.test.ts +4 -6
  98. package/src/__tests__/devices-mine.test.ts +12 -11
  99. package/src/__tests__/devices.test.ts +60 -260
  100. package/src/__tests__/discord-verification-contact-upgrade.test.ts +10 -13
  101. package/src/__tests__/edge-auth.test.ts +10 -148
  102. package/src/__tests__/edge-guardian-auth.test.ts +60 -44
  103. package/src/__tests__/guardian-binding-channel-reuse.test.ts +16 -18
  104. package/src/__tests__/guardian-bootstrap-binding.test.ts +7 -8
  105. package/src/__tests__/guardian-bootstrap-lookups.test.ts +25 -27
  106. package/src/__tests__/guardian-delivery-resolver.test.ts +8 -12
  107. package/src/__tests__/guardian-pin.test.ts +3 -1
  108. package/src/__tests__/handle-inbound-admission.test.ts +3 -12
  109. package/src/__tests__/handle-inbound-app-context.test.ts +3 -6
  110. package/src/__tests__/handle-inbound-invite-intercept.test.ts +3 -6
  111. package/src/__tests__/handle-inbound-trust-verdict.test.ts +3 -12
  112. package/src/__tests__/helpers/contact-route-table.ts +53 -32
  113. package/src/__tests__/helpers/env.ts +19 -0
  114. package/src/__tests__/helpers/gateway-config.ts +32 -0
  115. package/src/__tests__/helpers/remote-web-pairing-fixtures.ts +1 -7
  116. package/src/__tests__/helpers/signing-key.ts +27 -0
  117. package/src/__tests__/inbound-contact-seed.test.ts +7 -8
  118. package/src/__tests__/invite-redemption-engine-voice.test.ts +2 -3
  119. package/src/__tests__/invite-route-auth.test.ts +17 -15
  120. package/src/__tests__/ipc-contact-routes.test.ts +11 -19
  121. package/src/__tests__/ipc-contact-threshold.test.ts +16 -9
  122. package/src/__tests__/ipc-invite-routes.test.ts +6 -5
  123. package/src/__tests__/ipc-server-multi-client.test.ts +8 -1
  124. package/src/__tests__/ipc-server-watchdog.test.ts +16 -6
  125. package/src/__tests__/ipc-slack-thread-routes.test.ts +1 -2
  126. package/src/__tests__/ipc-voice-invite-routes.test.ts +3 -5
  127. package/src/__tests__/live-voice-websocket.test.ts +103 -95
  128. package/src/__tests__/load-guards.test.ts +0 -1
  129. package/src/__tests__/logger-retention.test.ts +11 -9
  130. package/src/__tests__/lum-2783-recovery-e2e.test.ts +3 -1
  131. package/src/__tests__/m0006-reconcile-contacts.test.ts +10 -13
  132. package/src/__tests__/oauth-callback.test.ts +13 -5
  133. package/src/__tests__/pair-origin-allowlist.test.ts +4 -118
  134. package/src/__tests__/rate-limit-loopback.test.ts +1 -5
  135. package/src/__tests__/refresh-device-binding.test.ts +3 -1
  136. package/src/__tests__/remote-web-pairing-challenge.test.ts +71 -132
  137. package/src/__tests__/remote-web-pairing-token.test.ts +16 -140
  138. package/src/__tests__/remote-web-pairing-verification.test.ts +17 -1
  139. package/src/__tests__/remote-web-public-base-url.test.ts +79 -0
  140. package/src/__tests__/resolve-assistant.test.ts +0 -1
  141. package/src/__tests__/runtime-client.test.ts +9 -9
  142. package/src/__tests__/runtime-health-proxy.test.ts +19 -14
  143. package/src/__tests__/runtime-proxy-auth.test.ts +129 -63
  144. package/src/__tests__/runtime-proxy-catchall-methods.test.ts +152 -0
  145. package/src/__tests__/runtime-proxy-device-stamp.test.ts +31 -24
  146. package/src/__tests__/runtime-proxy-error-body.test.ts +28 -30
  147. package/src/__tests__/runtime-proxy.test.ts +66 -59
  148. package/src/__tests__/runtime-stream-test-utils.ts +14 -3
  149. package/src/__tests__/seed-admission-policy.test.ts +1 -10
  150. package/src/__tests__/shared-invite-redeem.test.ts +7 -20
  151. package/src/__tests__/shared-invite-registration.test.ts +0 -34
  152. package/src/__tests__/slack-control-plane-proxy.test.ts +29 -17
  153. package/src/__tests__/slack-display-name.test.ts +3 -6
  154. package/src/__tests__/slack-normalize.test.ts +0 -1
  155. package/src/__tests__/slack-reaction-normalize.test.ts +0 -1
  156. package/src/__tests__/slack-socket-mode-catchup.test.ts +1 -2
  157. package/src/__tests__/slack-socket-mode-group-dm.test.ts +2 -3
  158. package/src/__tests__/slack-socket-mode-liveness.test.ts +6 -29
  159. package/src/__tests__/slack-socket-mode-outbound-root.test.ts +2 -3
  160. package/src/__tests__/slack-socket-mode-thread-tracking.test.ts +2 -3
  161. package/src/__tests__/sleep-wake-detector.test.ts +52 -25
  162. package/src/__tests__/speech-relay-websocket.test.ts +108 -100
  163. package/src/__tests__/stt-stream-websocket.test.ts +62 -69
  164. package/src/__tests__/telegram-control-plane-proxy.test.ts +36 -19
  165. package/src/__tests__/telegram-normalize.test.ts +1 -1
  166. package/src/__tests__/telegram-webhook-drop-visibility.test.ts +2 -3
  167. package/src/__tests__/telegram-webhook-handler.test.ts +121 -68
  168. package/src/__tests__/telegram-webhook-manager.test.ts +70 -90
  169. package/src/__tests__/test-preload.ts +21 -3
  170. package/src/__tests__/text-verification-helpers.test.ts +1 -1
  171. package/src/__tests__/trust-rules-route-auth.test.ts +16 -26
  172. package/src/__tests__/trust-rules-routes.test.ts +22 -25
  173. package/src/__tests__/twilio-media-websocket.test.ts +61 -59
  174. package/src/__tests__/twilio-webhooks.test.ts +5 -6
  175. package/src/__tests__/unversioned-api-fallthrough.test.ts +86 -0
  176. package/src/__tests__/upgrade-policy.test.ts +161 -0
  177. package/src/__tests__/upstream-transport.test.ts +20 -15
  178. package/src/__tests__/vercel-route-auth.test.ts +22 -36
  179. package/src/__tests__/watch-stream-websocket.test.ts +84 -91
  180. package/src/__tests__/whatsapp-download.test.ts +0 -1
  181. package/src/__tests__/whatsapp-webhook.test.ts +3 -3
  182. package/src/attachments/ingest.test.ts +0 -1
  183. package/src/auth/guardian-bootstrap.ts +5 -12
  184. package/src/auth/guardian-refresh.ts +0 -2
  185. package/src/auth/token-exchange.ts +23 -57
  186. package/src/auth/token-service.ts +69 -22
  187. package/src/auth-rate-limiter.ts +6 -0
  188. package/src/channels/inbound-event.test.ts +54 -0
  189. package/src/channels/inbound-event.ts +29 -3
  190. package/src/channels/ingress-verification.ts +10 -3
  191. package/src/channels/plugin-inbound.test.ts +4 -3
  192. package/src/channels/types.ts +0 -2
  193. package/src/cli/__tests__/contacts.test.ts +83 -60
  194. package/src/cli/__tests__/pairing.test.ts +230 -48
  195. package/src/cli/contacts.ts +0 -130
  196. package/src/cli/index.ts +20 -34
  197. package/src/cli/pairing.ts +118 -59
  198. package/src/cli/program.ts +227 -0
  199. package/src/cloud-features.ts +13 -0
  200. package/src/cloud-identity.ts +1 -1
  201. package/src/config-file-cache.ts +6 -0
  202. package/src/config-file-utils.ts +1 -1
  203. package/src/config-file-watcher.ts +104 -0
  204. package/src/config.ts +25 -23
  205. package/src/credential-cache.ts +6 -0
  206. package/src/credential-reader.ts +53 -35
  207. package/src/credential-watcher.ts +219 -22
  208. package/src/db/__tests__/session-store.test.ts +2 -1
  209. package/src/db/admission-policy-store.ts +1 -2
  210. package/src/db/connection.ts +12 -4
  211. package/src/db/contact-store.ts +82 -0
  212. package/src/db/data-migrations/m0002-actor-token-tables-to-gateway.ts +2 -7
  213. package/src/db/schema.ts +15 -0
  214. package/src/db/seed-admission-policy.ts +1 -1
  215. package/src/db/seed-trust-rules.ts +1 -4
  216. package/src/db/session-store.ts +0 -6
  217. package/src/discord/admission-log-visibility.test.ts +2 -2
  218. package/src/discord/forward.test.ts +3 -6
  219. package/src/discord/forward.ts +4 -8
  220. package/src/discord/lifecycle.ts +104 -0
  221. package/src/email/normalize.ts +1 -1
  222. package/src/email/register-callback.test.ts +1 -2
  223. package/src/email/register-callback.ts +4 -11
  224. package/src/guardian-contract.ts +30 -0
  225. package/src/handlers/handle-inbound.ts +2 -2
  226. package/src/http/browser-auth-cookies.ts +27 -22
  227. package/src/http/edge-forwarded-header.ts +0 -39
  228. package/src/http/loopback-guard.ts +0 -47
  229. package/src/http/middleware/auth.ts +35 -188
  230. package/src/http/middleware/cors.test.ts +66 -0
  231. package/src/http/middleware/cors.ts +23 -2
  232. package/src/http/router.ts +188 -151
  233. package/src/http/routes/assistant-handle.test.ts +133 -0
  234. package/src/http/routes/assistant-handle.ts +94 -0
  235. package/src/http/routes/audio-proxy.ts +49 -39
  236. package/src/http/routes/auto-approve-thresholds.ts +308 -230
  237. package/src/http/routes/brain-graph-proxy.ts +61 -52
  238. package/src/http/routes/channel-admission-policy.ts +219 -154
  239. package/src/http/routes/channel-ingress.test.ts +24 -19
  240. package/src/http/routes/channel-ingress.ts +255 -137
  241. package/src/http/routes/channel-permission-overrides.ts +189 -112
  242. package/src/http/routes/channel-readiness-proxy.ts +66 -45
  243. package/src/http/routes/channel-verification-session-proxy.test.ts +33 -82
  244. package/src/http/routes/channel-verification-session-proxy.ts +100 -455
  245. package/src/http/routes/cloud-hop.ts +138 -0
  246. package/src/http/routes/cloud-push-proxy.test.ts +34 -33
  247. package/src/http/routes/cloud-push-proxy.ts +56 -127
  248. package/src/http/routes/contacts-control-plane-proxy.ts +0 -12
  249. package/src/http/routes/contacts-control-plane-route-table.ts +372 -119
  250. package/src/http/routes/credential-entry-page.ts +12 -0
  251. package/src/http/routes/credential-requests.ts +10 -4
  252. package/src/http/routes/desktop-setup-proxy.ts +21 -11
  253. package/src/http/routes/desktop-stream-websocket.ts +67 -41
  254. package/src/http/routes/devices-mine.ts +11 -0
  255. package/src/http/routes/devices.ts +7 -63
  256. package/src/http/routes/email-webhook.test.ts +4 -20
  257. package/src/http/routes/guardian-channel-create.test.ts +6 -9
  258. package/src/http/routes/guardian-pin.ts +1 -1
  259. package/src/http/routes/guardian-refresh.ts +65 -2
  260. package/src/http/routes/index.ts +88 -0
  261. package/src/http/routes/ingress-domains.test.ts +57 -2
  262. package/src/http/routes/ingress-domains.ts +46 -14
  263. package/src/http/routes/integrations-status.ts +18 -0
  264. package/src/http/routes/ipc-runtime-proxy.test.ts +31 -6
  265. package/src/http/routes/ipc-runtime-proxy.ts +6 -3
  266. package/src/http/routes/live-voice-websocket.ts +159 -148
  267. package/src/http/routes/log-export.test.ts +61 -87
  268. package/src/http/routes/log-export.ts +143 -150
  269. package/src/http/routes/log-tail.test.ts +49 -32
  270. package/src/http/routes/log-tail.ts +31 -21
  271. package/src/http/routes/migration-rollback-proxy.ts +38 -32
  272. package/src/http/routes/oauth-apps-proxy.ts +109 -62
  273. package/src/http/routes/oauth-providers-proxy.ts +60 -51
  274. package/src/http/routes/pair.ts +23 -346
  275. package/src/http/routes/plugin-webhook-websocket.test.ts +73 -77
  276. package/src/http/routes/plugin-webhook-websocket.ts +210 -215
  277. package/src/http/routes/plugin-webhook.test.ts +3 -1
  278. package/src/http/routes/plugin-webhook.ts +0 -3
  279. package/src/http/routes/ps.ts +25 -20
  280. package/src/http/routes/regex-to-openapi-path.ts +39 -0
  281. package/src/http/routes/remote-web-pairing-challenge.ts +35 -81
  282. package/src/http/routes/remote-web-pairing-routes.ts +39 -0
  283. package/src/http/routes/remote-web-pairing-token.ts +6 -11
  284. package/src/http/routes/remote-web-pairing-verification.ts +7 -7
  285. package/src/http/routes/runtime-audio-stream.ts +147 -147
  286. package/src/http/routes/runtime-health-proxy.ts +43 -32
  287. package/src/http/routes/runtime-proxy.ts +54 -20
  288. package/src/http/routes/shared-invite-redeem.ts +1 -7
  289. package/src/http/routes/slack-control-plane-proxy.ts +57 -46
  290. package/src/http/routes/speech-relay-websocket.ts +310 -270
  291. package/src/http/routes/stt-stream-websocket.ts +102 -107
  292. package/src/http/routes/telegram-control-plane-proxy.ts +87 -58
  293. package/src/http/routes/telegram-webhook.test.ts +3 -19
  294. package/src/http/routes/telegram-webhook.ts +3 -2
  295. package/src/http/routes/terminal.test.ts +165 -0
  296. package/src/http/routes/terminal.ts +123 -0
  297. package/src/http/routes/trust-rules.suggest.test.ts +14 -22
  298. package/src/http/routes/trust-rules.ts +432 -246
  299. package/src/http/routes/tunnel-status.ts +26 -13
  300. package/src/http/routes/twilio-control-plane-proxy.ts +105 -64
  301. package/src/http/routes/twilio-media-websocket.ts +157 -147
  302. package/src/http/routes/twilio-voice-webhook.test.ts +14 -43
  303. package/src/http/routes/types.ts +92 -10
  304. package/src/http/routes/upgrade-broadcast-proxy.ts +38 -32
  305. package/src/http/routes/upgrade-policy.ts +186 -0
  306. package/src/http/routes/user-profile.test.ts +129 -0
  307. package/src/http/routes/user-profile.ts +204 -0
  308. package/src/http/routes/vercel-control-plane-proxy.ts +74 -52
  309. package/src/http/routes/watch-stream-websocket.ts +99 -138
  310. package/src/http/routes/webhook-routes.ts +214 -0
  311. package/src/http/routes/whatsapp-webhook.test.ts +3 -19
  312. package/src/http/routes/whatsapp-webhook.ts +2 -1
  313. package/src/http/routes/workspace-commit-proxy.ts +38 -30
  314. package/src/index.ts +298 -2481
  315. package/src/ipc/__tests__/admission-policy-handlers.test.ts +4 -18
  316. package/src/ipc/__tests__/guardian-request-routes.test.ts +7 -3
  317. package/src/ipc/__tests__/invite-ipc-routes.test.ts +13 -5
  318. package/src/ipc/__tests__/verification-session-routes.test.ts +5 -3
  319. package/src/ipc/admission-policy-handlers.ts +2 -2
  320. package/src/ipc/channel-socket-health-handlers.test.ts +56 -41
  321. package/src/ipc/channel-socket-health-handlers.ts +41 -31
  322. package/src/ipc/credential-request-handlers.ts +43 -19
  323. package/src/ipc/log-tail-handlers.test.ts +8 -35
  324. package/src/ipc/log-tail-handlers.ts +8 -11
  325. package/src/ipc/risk-classification-handlers.test.ts +0 -3
  326. package/src/ipc/risk-classification-handlers.ts +4 -4
  327. package/src/ipc/routes.ts +37 -0
  328. package/src/ipc/server.ts +13 -43
  329. package/src/ipc/trust-rules-handlers.test.ts +1 -2
  330. package/src/ipc/tunnel-handlers.ts +18 -18
  331. package/src/ipc/webhook-route-handlers.test.ts +5 -27
  332. package/src/ipc/webhook-route-handlers.ts +35 -39
  333. package/src/logger.ts +6 -26
  334. package/src/paths.ts +4 -4
  335. package/src/remote-web/pairing-challenge-store.ts +6 -35
  336. package/src/remote-web/pairing-mint.ts +2 -6
  337. package/src/remote-web/public-base-url.ts +65 -0
  338. package/src/risk/admission-policy-cache.ts +5 -12
  339. package/src/risk/bash-risk-classifier.test.ts +5 -6
  340. package/src/risk/bash-risk-classifier.ts +0 -3
  341. package/src/risk/command-registry/commands/gateway.ts +2 -1
  342. package/src/risk/file-risk-classifier.test.ts +1 -8
  343. package/src/risk/project-boundary.test.ts +3 -1
  344. package/src/risk/shell-identity.ts +1 -4
  345. package/src/risk/shell-parser.ts +1 -5
  346. package/src/risk/skill-risk-classifier.ts +1 -2
  347. package/src/runtime/client.ts +33 -27
  348. package/src/schema.ts +725 -163
  349. package/src/slack/errors.ts +1 -2
  350. package/src/slack/lifecycle.ts +327 -0
  351. package/src/slack/message-schemas.ts +1 -1
  352. package/src/slack/slack-web.ts +0 -1
  353. package/src/slack/socket-mode.ts +1 -1
  354. package/src/sleep-wake-detector.ts +62 -33
  355. package/src/telegram/normalize.test.ts +1 -1
  356. package/src/telegram/normalize.ts +1 -1
  357. package/src/telegram/send.test.ts +3 -19
  358. package/src/telegram/webhook-manager.ts +16 -31
  359. package/src/tunnel/allowed-paths.test.ts +27 -65
  360. package/src/tunnel/allowed-paths.ts +2 -27
  361. package/src/tunnel/binary-websocket.ts +1 -2
  362. package/src/tunnel/bridge-utils.ts +3 -8
  363. package/src/tunnel/client.test.ts +80 -67
  364. package/src/tunnel/client.ts +36 -28
  365. package/src/tunnel/http-bridge.test.ts +13 -40
  366. package/src/tunnel/websocket-bridge.test.ts +11 -2
  367. package/src/tunnel/websocket-bridge.ts +3 -1
  368. package/src/twilio/webhook-sync-trigger.ts +4 -4
  369. package/src/twilio/webhook-sync.test.ts +1 -33
  370. package/src/twilio/webhook-sync.ts +0 -4
  371. package/src/verification/code-parsing.ts +0 -3
  372. package/src/verification/rate-limit-helpers.ts +6 -2
  373. package/src/verification/session-service.ts +1 -1
  374. package/src/verification/shared-invite-registration.ts +3 -13
  375. package/src/verification/text-verification.ts +1 -1
  376. package/src/whatsapp/normalize.ts +1 -1
  377. package/node_modules/@mycadet/environments/src/__tests__/cloud-assistant-hub-url.test.ts +0 -38
  378. package/node_modules/@mycadet/environments/src/seeds.ts +0 -99
  379. package/node_modules/@mycadet/environments/src/types.ts +0 -70
  380. package/openapi.json +0 -2325
  381. package/src/__tests__/feature-flag-defaults-sync.test.ts +0 -44
  382. package/src/__tests__/feature-flag-resolver.test.ts +0 -151
  383. package/src/__tests__/feature-flag-watcher-callback.test.ts +0 -63
  384. package/src/__tests__/feature-flags-route.test.ts +0 -764
  385. package/src/__tests__/guardian-init-lockfile.test.ts +0 -883
  386. package/src/__tests__/ipc-feature-flag-routes.test.ts +0 -240
  387. package/src/__tests__/pair-device-bound.test.ts +0 -296
  388. package/src/__tests__/remote-web-ingress-denylist.test.ts +0 -113
  389. package/src/__tests__/remote-web-pairing-requests.test.ts +0 -277
  390. package/src/__tests__/route-schema-guard.test.ts +0 -489
  391. package/src/cloud-user-id.ts +0 -12
  392. package/src/feature-flag-defaults.ts +0 -197
  393. package/src/feature-flag-env-overrides.test.ts +0 -166
  394. package/src/feature-flag-env-overrides.ts +0 -58
  395. package/src/feature-flag-registry.json +0 -506
  396. package/src/feature-flag-resolver.ts +0 -47
  397. package/src/feature-flag-store.ts +0 -115
  398. package/src/feature-flag-watcher.ts +0 -105
  399. package/src/http/routes/a2a-routes.test.ts +0 -146
  400. package/src/http/routes/a2a-routes.ts +0 -126
  401. package/src/http/routes/auto-approve-thresholds-routes.ts +0 -92
  402. package/src/http/routes/channel-admission-policy-routes.ts +0 -67
  403. package/src/http/routes/channel-ingress-routes.ts +0 -135
  404. package/src/http/routes/channel-permission-overrides-routes.ts +0 -92
  405. package/src/http/routes/contacts-control-plane-routes.ts +0 -278
  406. package/src/http/routes/feature-flags.ts +0 -185
  407. package/src/http/routes/remote-web-pairing-requests.ts +0 -123
  408. package/src/http/routes/trust-rules-routes.ts +0 -188
  409. package/src/ipc/feature-flag-handlers.ts +0 -63
  410. package/src/types.ts +0 -11
@@ -20,14 +20,20 @@
20
20
  * HTTP rejection, so the daemon's dial-failure probe works end-to-end
21
21
  */
22
22
 
23
+ import { Server, ServerWebSocket } from "bun";
24
+ import { z } from "zod";
25
+
23
26
  import type { OutgoingHttpHeaders } from "node:http";
24
27
 
25
28
  import { tunnelHostForCloudHost } from "@mycadet/service-contracts/ingress";
26
29
 
27
30
  import { resolveScopeProfile } from "../../auth/scopes.js";
28
31
  import { validateEdgeToken } from "../../auth/token-exchange.js";
29
- import type { GatewayConfig } from "../../config.js";
30
- import type { CredentialCache } from "../../credential-cache.js";
32
+ import { getConfig, type GatewayConfig } from "../../config.js";
33
+ import {
34
+ getCredentials,
35
+ type CredentialCache,
36
+ } from "../../credential-cache.js";
31
37
  import { credentialKey } from "../../credential-key.js";
32
38
  import { getLogger } from "../../logger.js";
33
39
  import { getCloudBaseUrl } from "../../cloud-url.js";
@@ -84,7 +90,7 @@ const ALLOWED_PARAMS: Record<SpeechRelayOperation, ReadonlySet<string>> = {
84
90
  "punctuate",
85
91
  ]),
86
92
  // `model` is the client-selected TTS voice; tunnel only dials it after
87
- // Django's rate-card guard prices and echoes that exact model, so
93
+ // The cloud's rate-card guard prices and echoes that exact model, so
88
94
  // forwarding it does not widen what the assistant API key can spend on.
89
95
  tts: new Set(["encoding", "sample_rate", "container", "model"]),
90
96
  };
@@ -129,26 +135,35 @@ export interface SpeechRelayDeps {
129
135
  fetchImpl?: typeof fetch;
130
136
  }
131
137
 
132
- export type SpeechRelaySocketData = {
133
- wsType: "speech-relay";
134
- operation: SpeechRelayOperation;
135
- /** wss URL of the tunnel speech endpoint, params already attached. */
136
- upstreamWsUrl: string;
137
- /** https twin of upstreamWsUrl, for failure probes. */
138
- upstreamHttpUrl: string;
139
- deps: SpeechRelayDeps;
140
- upstream?: WebSocket;
141
- upstreamOpened?: boolean;
142
- /**
143
- * Set by the close handler; open() re-checks it after its async
144
- * credential read so a daemon that hung up mid-read doesn't leave a
145
- * dialed tunnel session with no close left to forward.
146
- */
147
- downstreamClosed?: boolean;
148
- pendingMessages?: (string | ArrayBuffer | Uint8Array)[];
149
- /** Total bytes held in pendingMessages, checked against MAX_PENDING_BYTES. */
150
- pendingBytes?: number;
151
- };
138
+ export const speechRelaySocketDataSchema = z.object({
139
+ wsType: z.literal("speech-relay"),
140
+ operation: z.enum(["stt", "tts"]),
141
+ upstreamWsUrl: z.string(),
142
+ upstreamHttpUrl: z.string(),
143
+ deps: z.custom<SpeechRelayDeps>(() => true),
144
+ upstream: z.custom<WebSocket>(() => true).optional(),
145
+ upstreamOpened: z.boolean().optional(),
146
+ downstreamClosed: z.boolean().optional(),
147
+ pendingMessages: z
148
+ .array(
149
+ z.union([
150
+ z.string(),
151
+ z.instanceof(ArrayBuffer),
152
+ z.custom<Uint8Array>((v) => v instanceof Uint8Array),
153
+ ]),
154
+ )
155
+ .optional(),
156
+ pendingBytes: z.number().optional(),
157
+ });
158
+
159
+ export type SpeechRelaySocketData = z.infer<typeof speechRelaySocketDataSchema>;
160
+
161
+ /** Discriminate an untyped socket as a speech relay socket. */
162
+ export function isSpeechRelaySocketData(
163
+ ws: ServerWebSocket<unknown>,
164
+ ): ws is ServerWebSocket<SpeechRelaySocketData> {
165
+ return speechRelaySocketDataSchema.safeParse(ws.data).success;
166
+ }
152
167
 
153
168
  function jsonError(status: number, code: string, detail: string): Response {
154
169
  return new Response(JSON.stringify({ code, detail }), {
@@ -252,123 +267,145 @@ async function probeTunnel(
252
267
  }
253
268
 
254
269
  /**
255
- * Create the upgrade handler for one speech-relay path. Async: the
270
+ * The upgrade handler shared by the three speech-relay paths. Async: the
256
271
  * non-upgrade probe branch awaits tunnel.
257
272
  */
258
- export function createSpeechRelayUpgradeHandler(
259
- config: GatewayConfig,
273
+ async function handleSpeechRelayUpgrade(
274
+ req: Request,
275
+ server: Server<unknown>,
260
276
  operation: SpeechRelayOperation,
261
- deps: SpeechRelayDeps,
262
277
  version: SpeechRelayVersion = "v1",
263
- ) {
264
- return async function handleUpgrade(
265
- req: Request,
266
- server: import("bun").Server<unknown>,
267
- ): Promise<Response | undefined> {
268
- if (req.method !== "GET") {
269
- return jsonError(405, "method_not_allowed", "GET only");
270
- }
278
+ ): Promise<Response | undefined> {
279
+ const config = getConfig();
280
+ const deps: SpeechRelayDeps = { credentials: getCredentials() };
271
281
 
272
- // This is a daemon-loopback service path. Anything that arrived
273
- // through tunnel's inbound tunnel (or the edge proxy) is categorically
274
- // rejected — the relay must never be reachable from outside.
275
- if (
276
- req.headers.get(TUNNEL_FORWARDED_HEADER) !== null ||
277
- requestHasTunnelBridgeAuth(req)
278
- ) {
279
- log.warn("Speech relay: rejected tunnel-forwarded request");
280
- return jsonError(403, "forbidden", "not reachable via ingress");
281
- }
282
+ if (req.method !== "GET") {
283
+ return jsonError(405, "method_not_allowed", "GET only");
284
+ }
282
285
 
283
- const url = new URL(req.url);
284
- const params = url.searchParams;
285
- const rawToken = params.get("key");
286
- if (!rawToken) {
287
- return jsonError(401, "invalid_token", "missing service token");
288
- }
289
- const result = validateEdgeToken(rawToken);
290
- if (
291
- !result.ok ||
292
- result.claims.sub !== DAEMON_SERVICE_SUB ||
293
- !resolveScopeProfile(result.claims.scope_profile).has("speech.relay")
294
- ) {
295
- log.warn(
296
- {
297
- reason: !result.ok
298
- ? result.reason
299
- : result.claims.sub !== DAEMON_SERVICE_SUB
300
- ? "wrong_sub"
301
- : "missing_speech_scope",
302
- },
303
- "Speech relay: authentication failed",
304
- );
305
- return jsonError(401, "invalid_token", "service token rejected");
306
- }
286
+ // This is a daemon-loopback service path. Anything that arrived
287
+ // through tunnel's inbound tunnel (or the edge proxy) is categorically
288
+ // rejected — the relay must never be reachable from outside.
289
+ if (
290
+ req.headers.get(TUNNEL_FORWARDED_HEADER) !== null ||
291
+ requestHasTunnelBridgeAuth(req)
292
+ ) {
293
+ log.warn("Speech relay: rejected tunnel-forwarded request");
294
+ return jsonError(403, "forbidden", "not reachable via ingress");
295
+ }
307
296
 
308
- // ?key= is the daemon→gateway auth carrier, not a tunnel param.
309
- params.delete("key");
310
- const allowed = allowedParams(operation, version);
311
- for (const param of params.keys()) {
312
- if (!allowed.has(param)) {
313
- return jsonError(
314
- 400,
315
- "invalid_request",
316
- `unsupported query parameter: ${param}`,
317
- );
318
- }
319
- }
320
- const { wsUrl, httpUrl } = tunnelSpeechUrls(
321
- await resolveTunnelBaseUrl(config),
322
- operation,
323
- params,
324
- version,
297
+ const url = new URL(req.url);
298
+ const params = url.searchParams;
299
+ const rawToken = params.get("key");
300
+ if (!rawToken) {
301
+ return jsonError(401, "invalid_token", "missing service token");
302
+ }
303
+ const result = validateEdgeToken(rawToken);
304
+ if (
305
+ !result.ok ||
306
+ result.claims.sub !== DAEMON_SERVICE_SUB ||
307
+ !resolveScopeProfile(result.claims.scope_profile).has("speech.relay")
308
+ ) {
309
+ log.warn(
310
+ {
311
+ reason: !result.ok
312
+ ? result.reason
313
+ : result.claims.sub !== DAEMON_SERVICE_SUB
314
+ ? "wrong_sub"
315
+ : "missing_speech_scope",
316
+ },
317
+ "Speech relay: authentication failed",
325
318
  );
319
+ return jsonError(401, "invalid_token", "service token rejected");
320
+ }
326
321
 
327
- // Non-upgrade request: this is the daemon's dial-failure probe.
328
- // Replay the gate and hand back tunnel's own rejection.
329
- if (!isWebsocketUpgradeRequest(req)) {
330
- const apiKey = await readAssistantApiKey(deps);
331
- if (!apiKey) {
332
- return jsonError(
333
- 401,
334
- "missing_platform_connection",
335
- "no Cadet assistant API key is stored — connect the cloud account",
336
- );
337
- }
338
- const rejection = await probeTunnel(
339
- httpUrl,
340
- apiKey,
341
- deps.fetchImpl ?? fetch,
322
+ // ?key= is the daemon→gateway auth carrier, not a tunnel param.
323
+ params.delete("key");
324
+ const allowed = allowedParams(operation, version);
325
+ for (const param of params.keys()) {
326
+ if (!allowed.has(param)) {
327
+ return jsonError(
328
+ 400,
329
+ "invalid_request",
330
+ `unsupported query parameter: ${param}`,
342
331
  );
343
- if (rejection) {
344
- return jsonError(rejection.status, rejection.code, rejection.detail);
345
- }
332
+ }
333
+ }
334
+ const { wsUrl, httpUrl } = tunnelSpeechUrls(
335
+ await resolveTunnelBaseUrl(config),
336
+ operation,
337
+ params,
338
+ version,
339
+ );
340
+
341
+ // Non-upgrade request: this is the daemon's dial-failure probe.
342
+ // Replay the gate and hand back tunnel's own rejection.
343
+ if (!isWebsocketUpgradeRequest(req)) {
344
+ const apiKey = await readAssistantApiKey(deps);
345
+ if (!apiKey) {
346
346
  return jsonError(
347
- 426,
348
- "upgrade_required",
349
- "the gate passed; connect with a WebSocket upgrade",
347
+ 401,
348
+ "missing_platform_connection",
349
+ "no Cadet assistant API key is stored — connect the cloud account",
350
350
  );
351
351
  }
352
-
353
- const upgraded = server.upgrade(req, {
354
- data: {
355
- wsType: "speech-relay",
356
- operation,
357
- upstreamWsUrl: wsUrl,
358
- upstreamHttpUrl: httpUrl,
359
- deps,
360
- } satisfies SpeechRelaySocketData,
361
- });
362
- if (!upgraded) {
363
- return jsonError(500, "upgrade_failed", "WebSocket upgrade failed");
352
+ const rejection = await probeTunnel(
353
+ httpUrl,
354
+ apiKey,
355
+ deps.fetchImpl ?? fetch,
356
+ );
357
+ if (rejection) {
358
+ return jsonError(rejection.status, rejection.code, rejection.detail);
364
359
  }
365
- return undefined;
366
- };
360
+ return jsonError(
361
+ 426,
362
+ "upgrade_required",
363
+ "the gate passed; connect with a WebSocket upgrade",
364
+ );
365
+ }
366
+
367
+ const upgraded = server.upgrade(req, {
368
+ data: {
369
+ wsType: "speech-relay",
370
+ operation,
371
+ upstreamWsUrl: wsUrl,
372
+ upstreamHttpUrl: httpUrl,
373
+ deps,
374
+ } satisfies SpeechRelaySocketData,
375
+ });
376
+ if (!upgraded) {
377
+ return jsonError(500, "upgrade_failed", "WebSocket upgrade failed");
378
+ }
379
+ return undefined;
380
+ }
381
+
382
+ export function handleSpeechRelaySttWs(
383
+ req: Request,
384
+ server: Server<unknown>,
385
+ ): Promise<Response | undefined> {
386
+ return handleSpeechRelayUpgrade(req, server, "stt");
387
+ }
388
+
389
+ // Managed STT v2 (Flux). Separate handler rather than a param on v1: the
390
+ // contract version is the endpoint, and v2 accepts query params v1 must
391
+ // keep rejecting.
392
+ export function handleSpeechRelaySttV2Ws(
393
+ req: Request,
394
+ server: Server<unknown>,
395
+ ): Promise<Response | undefined> {
396
+ return handleSpeechRelayUpgrade(req, server, "stt", "v2");
397
+ }
398
+
399
+ export function handleSpeechRelayTtsWs(
400
+ req: Request,
401
+ server: Server<unknown>,
402
+ ): Promise<Response | undefined> {
403
+ return handleSpeechRelayUpgrade(req, server, "tts");
367
404
  }
368
405
 
369
406
  /** Send a tunnel_error control frame downstream (best-effort). */
370
407
  function sendRelayError(
371
- ws: import("bun").ServerWebSocket<SpeechRelaySocketData>,
408
+ ws: ServerWebSocket<SpeechRelaySocketData>,
372
409
  code: string,
373
410
  detail: string,
374
411
  ): void {
@@ -385,158 +422,161 @@ function sendRelayError(
385
422
  * `tunnel_error` frame (probing tunnel for the real rejection) so the daemon
386
423
  * adapter's existing error mapping applies unchanged.
387
424
  */
388
- export function getSpeechRelayWebsocketHandlers() {
389
- return {
390
- async open(ws: import("bun").ServerWebSocket<SpeechRelaySocketData>) {
391
- const { deps, upstreamWsUrl, upstreamHttpUrl, operation } = ws.data;
392
- ws.data.pendingMessages = [];
393
- ws.data.pendingBytes = 0;
394
- ws.data.upstreamOpened = false;
395
-
396
- const apiKey = await readAssistantApiKey(deps);
397
- if (ws.data.downstreamClosed) {
398
- // The daemon hung up while the credential read was pending; there
399
- // is no close left to forward, so dialing now would leak a tunnel
400
- // session until its timeout.
401
- log.info({ operation }, "Speech relay: daemon closed before dial");
402
- return;
403
- }
404
- if (!apiKey) {
405
- log.warn({ operation }, "Speech relay: no assistant API key stored");
425
+ export async function openSpeechRelayWebsocket(
426
+ ws: ServerWebSocket<SpeechRelaySocketData>,
427
+ ) {
428
+ const { deps, upstreamWsUrl, upstreamHttpUrl, operation } = ws.data;
429
+ ws.data.pendingMessages = [];
430
+ ws.data.pendingBytes = 0;
431
+ ws.data.upstreamOpened = false;
432
+
433
+ const apiKey = await readAssistantApiKey(deps);
434
+ if (ws.data.downstreamClosed) {
435
+ // The daemon hung up while the credential read was pending; there
436
+ // is no close left to forward, so dialing now would leak a tunnel
437
+ // session until its timeout.
438
+ log.info({ operation }, "Speech relay: daemon closed before dial");
439
+ return;
440
+ }
441
+ if (!apiKey) {
442
+ log.warn({ operation }, "Speech relay: no assistant API key stored");
443
+ sendRelayError(
444
+ ws,
445
+ "missing_platform_connection",
446
+ "no Cadet assistant API key is stored — connect the cloud account",
447
+ );
448
+ ws.close(1011, "missing_platform_connection");
449
+ return;
450
+ }
451
+
452
+ const WsCtor = (deps.webSocketConstructor ??
453
+ WebSocket) as WebSocketConstructorWithHeaders;
454
+ const upstream = new WsCtor(upstreamWsUrl, {
455
+ headers: { Authorization: `Api-Key ${apiKey}` },
456
+ });
457
+ // TTS audio arrives as binary frames; without this they surface as
458
+ // Blobs and the downstream forward would crash.
459
+ try {
460
+ upstream.binaryType = "arraybuffer";
461
+ } catch {
462
+ // Test fakes may not implement the setter.
463
+ }
464
+ ws.data.upstream = upstream;
465
+
466
+ // A rejected handshake can emit error and close (in either order,
467
+ // sometimes both) before the async rejection probe resolves —
468
+ // forwarding that raw close would beat the synthesized tunnel_error
469
+ // frame to the daemon. Route every pre-open failure through one
470
+ // guarded path instead.
471
+ let dialFailureHandled = false;
472
+ const handleDialFailure = () => {
473
+ if (dialFailureHandled) {
474
+ return;
475
+ }
476
+ dialFailureHandled = true;
477
+ void probeTunnel(upstreamHttpUrl, apiKey, deps.fetchImpl ?? fetch).then(
478
+ (rejection) => {
479
+ log.error(
480
+ { operation, code: rejection?.code },
481
+ "Speech relay upstream dial failed",
482
+ );
406
483
  sendRelayError(
407
484
  ws,
408
- "missing_platform_connection",
409
- "no Cadet assistant API key is stored — connect the cloud account",
485
+ rejection?.code ?? "provider_unreachable",
486
+ rejection?.detail ?? "could not reach the speech relay",
410
487
  );
411
- ws.close(1011, "missing_platform_connection");
412
- return;
413
- }
488
+ ws.close(1011, rejection?.code ?? "upstream_error");
489
+ },
490
+ );
491
+ };
414
492
 
415
- const WsCtor = (deps.webSocketConstructor ??
416
- WebSocket) as WebSocketConstructorWithHeaders;
417
- const upstream = new WsCtor(upstreamWsUrl, {
418
- headers: { Authorization: `Api-Key ${apiKey}` },
419
- });
420
- // TTS audio arrives as binary frames; without this they surface as
421
- // Blobs and the downstream forward would crash.
422
- try {
423
- upstream.binaryType = "arraybuffer";
424
- } catch {
425
- // Test fakes may not implement the setter.
426
- }
427
- ws.data.upstream = upstream;
428
-
429
- // A rejected handshake can emit error and close (in either order,
430
- // sometimes both) before the async rejection probe resolves —
431
- // forwarding that raw close would beat the synthesized tunnel_error
432
- // frame to the daemon. Route every pre-open failure through one
433
- // guarded path instead.
434
- let dialFailureHandled = false;
435
- const handleDialFailure = () => {
436
- if (dialFailureHandled) {
437
- return;
438
- }
439
- dialFailureHandled = true;
440
- void probeTunnel(upstreamHttpUrl, apiKey, deps.fetchImpl ?? fetch).then(
441
- (rejection) => {
442
- log.error(
443
- { operation, code: rejection?.code },
444
- "Speech relay upstream dial failed",
445
- );
446
- sendRelayError(
447
- ws,
448
- rejection?.code ?? "provider_unreachable",
449
- rejection?.detail ?? "could not reach the speech relay",
450
- );
451
- ws.close(1011, rejection?.code ?? "upstream_error");
452
- },
453
- );
454
- };
455
-
456
- upstream.addEventListener("open", () => {
457
- log.info({ operation }, "Speech relay upstream connected to tunnel");
458
- ws.data.upstreamOpened = true;
459
- const pending = ws.data.pendingMessages;
460
- if (pending) {
461
- for (const msg of pending) {
462
- upstream.send(msg);
463
- }
464
- ws.data.pendingMessages = undefined;
465
- }
466
- });
467
-
468
- upstream.addEventListener("message", (event) => {
469
- const data =
470
- typeof event.data === "string"
471
- ? event.data
472
- : new Uint8Array(event.data as ArrayBuffer);
473
- ws.send(data);
474
- });
475
-
476
- upstream.addEventListener("close", (event) => {
477
- if (!ws.data.upstreamOpened) {
478
- handleDialFailure();
479
- return;
480
- }
481
- log.info(
482
- { code: event.code, operation },
483
- "Speech relay upstream closed",
484
- );
485
- ws.close(event.code, event.reason);
486
- });
487
-
488
- upstream.addEventListener("error", () => {
489
- if (!ws.data.upstreamOpened) {
490
- handleDialFailure();
491
- return;
492
- }
493
- // Mid-session transport failure; tunnel already sent its own
494
- // tunnel_error frame if it had one.
495
- log.error({ operation }, "Speech relay upstream error");
496
- ws.close(1011, "upstream_error");
497
- });
498
- },
499
-
500
- message(
501
- ws: import("bun").ServerWebSocket<SpeechRelaySocketData>,
502
- message: string | ArrayBuffer | Uint8Array,
503
- ) {
504
- const upstream = ws.data.upstream;
505
- if (upstream && upstream.readyState === WebSocket.OPEN) {
506
- upstream.send(message);
507
- } else if (ws.data.pendingMessages) {
508
- const size =
509
- typeof message === "string"
510
- ? Buffer.byteLength(message)
511
- : message.byteLength;
512
- if ((ws.data.pendingBytes ?? 0) + size > MAX_PENDING_BYTES) {
513
- log.warn(
514
- "Speech relay pending message buffer overflow — closing connection",
515
- );
516
- ws.close(1008, "Buffer overflow");
517
- return;
518
- }
519
- ws.data.pendingBytes = (ws.data.pendingBytes ?? 0) + size;
520
- ws.data.pendingMessages.push(message);
493
+ upstream.addEventListener("open", () => {
494
+ log.info({ operation }, "Speech relay upstream connected to tunnel");
495
+ ws.data.upstreamOpened = true;
496
+ const pending = ws.data.pendingMessages;
497
+ if (pending) {
498
+ for (const msg of pending) {
499
+ upstream.send(msg);
521
500
  }
522
- },
523
-
524
- close(
525
- ws: import("bun").ServerWebSocket<SpeechRelaySocketData>,
526
- code: number,
527
- reason: string,
528
- ) {
529
- ws.data.downstreamClosed = true;
530
- const { upstream, operation } = ws.data;
531
- log.info({ code, reason, operation }, "Speech relay downstream closed");
532
501
  ws.data.pendingMessages = undefined;
533
- if (
534
- upstream &&
535
- (upstream.readyState === WebSocket.OPEN ||
536
- upstream.readyState === WebSocket.CONNECTING)
537
- ) {
538
- upstream.close(code, reason);
539
- }
540
- },
541
- };
502
+ }
503
+ });
504
+
505
+ upstream.addEventListener("message", (event) => {
506
+ const data =
507
+ typeof event.data === "string"
508
+ ? event.data
509
+ : new Uint8Array(event.data as ArrayBuffer);
510
+ ws.send(data);
511
+ });
512
+
513
+ upstream.addEventListener("close", (event) => {
514
+ if (!ws.data.upstreamOpened) {
515
+ handleDialFailure();
516
+ return;
517
+ }
518
+ log.info({ code: event.code, operation }, "Speech relay upstream closed");
519
+ ws.close(event.code, event.reason);
520
+ });
521
+
522
+ upstream.addEventListener("error", () => {
523
+ if (!ws.data.upstreamOpened) {
524
+ handleDialFailure();
525
+ return;
526
+ }
527
+ // Mid-session transport failure; tunnel already sent its own
528
+ // tunnel_error frame if it had one.
529
+ log.error({ operation }, "Speech relay upstream error");
530
+ ws.close(1011, "upstream_error");
531
+ });
532
+ }
533
+
534
+ /**
535
+ * The speech relay message arm: forward downstream frames upstream,
536
+ * byte-capped buffering while the tunnel dial connects.
537
+ */
538
+ export function messageSpeechRelayWebsocket(
539
+ ws: ServerWebSocket<SpeechRelaySocketData>,
540
+ message: string | ArrayBuffer | Uint8Array,
541
+ ) {
542
+ const upstream = ws.data.upstream;
543
+ if (upstream && upstream.readyState === WebSocket.OPEN) {
544
+ upstream.send(message);
545
+ } else if (ws.data.pendingMessages) {
546
+ const size =
547
+ typeof message === "string"
548
+ ? Buffer.byteLength(message)
549
+ : message.byteLength;
550
+ if ((ws.data.pendingBytes ?? 0) + size > MAX_PENDING_BYTES) {
551
+ log.warn(
552
+ "Speech relay pending message buffer overflow — closing connection",
553
+ );
554
+ ws.close(1008, "Buffer overflow");
555
+ return;
556
+ }
557
+ ws.data.pendingBytes = (ws.data.pendingBytes ?? 0) + size;
558
+ ws.data.pendingMessages.push(message);
559
+ }
560
+ }
561
+
562
+ /**
563
+ * The speech relay close arm: mark the downstream closed, drop the pending
564
+ * buffer, and close the upstream dial unless it already finished.
565
+ */
566
+ export function closeSpeechRelayWebsocket(
567
+ ws: ServerWebSocket<SpeechRelaySocketData>,
568
+ code: number,
569
+ reason: string,
570
+ ) {
571
+ ws.data.downstreamClosed = true;
572
+ const { upstream, operation } = ws.data;
573
+ log.info({ code, reason, operation }, "Speech relay downstream closed");
574
+ ws.data.pendingMessages = undefined;
575
+ if (
576
+ upstream &&
577
+ (upstream.readyState === WebSocket.OPEN ||
578
+ upstream.readyState === WebSocket.CONNECTING)
579
+ ) {
580
+ upstream.close(code, reason);
581
+ }
542
582
  }