@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
@@ -1,13 +1,11 @@
1
1
  /**
2
2
  * Token exchange module for the gateway's auth system.
3
3
  *
4
- * The gateway receives edge tokens (aud=cadet-gateway) from external clients
5
- * and mints short-lived exchange tokens (aud=cadet-daemon) for forwarding
6
- * to the runtime. This exchange proves gateway origin — only the gateway
7
- * holds the signing key needed to mint daemon-audience tokens.
8
- *
9
- * Exchange tokens have a 60-second TTL and rewrite the sub claim's assistant
10
- * segment to 'self' (the daemon's internal scope constant).
4
+ * The gateway receives edge tokens (aud=cadet-gateway) from external
5
+ * clients and forwards the verified identity to the runtime in
6
+ * `x-cadet-*` headers — the daemon verifies no tokens. The gateway is
7
+ * the only signer: it holds the signing key for the edge tokens it
8
+ * mints (relay dials, browser page tokens) and for nothing else.
11
9
  */
12
10
 
13
11
  import { getLogger } from "../logger.js";
@@ -15,13 +13,11 @@ import { getLogger } from "../logger.js";
15
13
  import { CURRENT_POLICY_EPOCH } from "./policy.js";
16
14
  import { parseSub } from "./subject.js";
17
15
  import { mintToken, verifyToken, type VerifyResult } from "./token-service.js";
16
+ import type { ForwardedIdentity } from "@mycadet/assistant-client";
18
17
  import type { ScopeProfile, TokenClaims } from "./types.js";
19
18
 
20
19
  const log = getLogger("token-exchange");
21
20
 
22
- /** TTL for exchange tokens — short-lived, minted per-request. */
23
- const EXCHANGE_TOKEN_TTL_SECONDS = 60;
24
-
25
21
  // ---------------------------------------------------------------------------
26
22
  // Edge token validation
27
23
  // ---------------------------------------------------------------------------
@@ -43,7 +39,7 @@ export function validateEdgeToken(
43
39
  }
44
40
 
45
41
  // ---------------------------------------------------------------------------
46
- // Exchange token minting
42
+ // Forwarded identity
47
43
  // ---------------------------------------------------------------------------
48
44
 
49
45
  /**
@@ -72,60 +68,30 @@ export function toDaemonSubject(edgeSub: string): string {
72
68
  }
73
69
 
74
70
  /**
75
- * Mint a short-lived exchange token (aud=cadet-daemon) from validated
76
- * edge claims. The sub claim's assistant segment is rewritten to 'self'
77
- * so the daemon always uses its internal scope constant.
71
+ * The identity the runtime should see for a verified edge caller: the
72
+ * sub rewritten to the daemon's internal scope, carrying the profile the
73
+ * edge token was minted with (the daemon resolves the same profile's
74
+ * scopes, so its route policies see exactly what the edge admitted).
78
75
  */
79
- export function mintExchangeToken(
76
+ export function forwardedIdentityFromClaims(
80
77
  edgeClaims: TokenClaims,
81
78
  targetScopeProfile: ScopeProfile,
82
- ): string {
83
- return mintToken({
84
- aud: "cadet-daemon",
85
- sub: toDaemonSubject(edgeClaims.sub),
86
- scope_profile: targetScopeProfile,
87
- policy_epoch: CURRENT_POLICY_EPOCH,
88
- ttlSeconds: EXCHANGE_TOKEN_TTL_SECONDS,
89
- });
79
+ ): ForwardedIdentity {
80
+ const subject = toDaemonSubject(edgeClaims.sub);
81
+ const parsed = parseSub(subject);
82
+ return {
83
+ subject,
84
+ principalType: parsed.ok ? parsed.principalType : "svc_gateway",
85
+ scopeProfile: targetScopeProfile,
86
+ };
90
87
  }
91
88
 
92
89
  // ---------------------------------------------------------------------------
93
- // Gateway-minted service tokens
90
+ // Gateway-minted edge tokens
94
91
  // ---------------------------------------------------------------------------
95
92
 
96
- /**
97
- * Mint an ingress exchange token for webhook handlers.
98
- * Used after platform signature validation (Telegram, Twilio, WhatsApp, Slack)
99
- * to forward authenticated inbound events to the runtime.
100
- *
101
- * sub=svc:gateway:self, scope_profile=gateway_ingress_v1
102
- */
103
- export function mintIngressToken(): string {
104
- return mintToken({
105
- aud: "cadet-daemon",
106
- sub: "svc:gateway:self",
107
- scope_profile: "gateway_ingress_v1",
108
- policy_epoch: CURRENT_POLICY_EPOCH,
109
- ttlSeconds: EXCHANGE_TOKEN_TTL_SECONDS,
110
- });
111
- }
112
-
113
- /**
114
- * Mint a service token for gateway-to-runtime service calls.
115
- * Used for delivery endpoints, control-plane proxies, and other
116
- * gateway-originated requests to the daemon.
117
- *
118
- * sub=svc:gateway:self, scope_profile=gateway_service_v1
119
- */
120
- export function mintServiceToken(): string {
121
- return mintToken({
122
- aud: "cadet-daemon",
123
- sub: "svc:gateway:self",
124
- scope_profile: "gateway_service_v1",
125
- policy_epoch: CURRENT_POLICY_EPOCH,
126
- ttlSeconds: EXCHANGE_TOKEN_TTL_SECONDS,
127
- });
128
- }
93
+ /** TTL for the gateway's own short-lived edge tokens. */
94
+ const EXCHANGE_TOKEN_TTL_SECONDS = 60;
129
95
 
130
96
  /**
131
97
  * Mint a relay token for Twilio WebSocket connections.
@@ -13,12 +13,13 @@ import {
13
13
  mkdirSync,
14
14
  readFileSync,
15
15
  renameSync,
16
+ rmSync,
16
17
  writeFileSync,
17
18
  } from "node:fs";
18
19
  import { dirname, join } from "node:path";
19
20
 
20
21
  import { getLogger } from "../logger.js";
21
- import { getGatewaySecurityDir } from "../paths.js";
22
+ import { getGatewaySecurityDir, getWorkspaceDir } from "../paths.js";
22
23
 
23
24
  import { isStaleEpoch } from "./policy.js";
24
25
  import type { ScopeProfile, TokenAudience, TokenClaims } from "./types.js";
@@ -39,29 +40,22 @@ export function getSigningKeyPath(): string {
39
40
  * Resolve the signing key for the gateway.
40
41
  *
41
42
  * Resolution order:
42
- * 1. ACTOR_TOKEN_SIGNING_KEY env var (hex-encoded, set by CLI for Docker)
43
- * 2. Load from disk (GATEWAY_SECURITY_DIR/actor-token-signing-key)
43
+ * 1. Load from disk (GATEWAY_SECURITY_DIR/actor-token-signing-key)
44
+ * 2. Adopt the key the assistant's daemon era persisted under the
45
+ * workspace's transitional directory — the one-time migration for
46
+ * instances hatched before the gateway owned key custody. Consumed
47
+ * on read: the adopted key is persisted gateway-side and the old
48
+ * file removed.
44
49
  * 3. Generate a new key and persist to disk (local mode)
45
50
  */
46
51
  export function loadOrCreateSigningKey(): Buffer {
47
- const envKey = process.env.ACTOR_TOKEN_SIGNING_KEY;
48
- if (envKey) {
49
- if (!/^[0-9a-f]{64}$/i.test(envKey)) {
50
- throw new Error(
51
- `Invalid ACTOR_TOKEN_SIGNING_KEY: expected 64 hex characters, got ${envKey.length} chars`,
52
- );
53
- }
54
- log.info("Signing key loaded from ACTOR_TOKEN_SIGNING_KEY env var");
55
- return Buffer.from(envKey, "hex");
56
- }
57
-
58
52
  const keyPath = getSigningKeyPath();
59
53
 
60
54
  if (existsSync(keyPath)) {
61
55
  try {
62
56
  const raw = readFileSync(keyPath);
63
57
  if (raw.length === 32) {
64
- log.info("Auth signing key loaded from disk");
58
+ log.debug("Auth signing key loaded from disk");
65
59
  return raw;
66
60
  }
67
61
  log.warn("Signing key file has unexpected length, regenerating");
@@ -70,25 +64,78 @@ export function loadOrCreateSigningKey(): Buffer {
70
64
  }
71
65
  }
72
66
 
67
+ const adopted = adoptLegacySigningKey(keyPath);
68
+ if (adopted) {
69
+ return adopted;
70
+ }
71
+
73
72
  const newKey = randomBytes(32);
73
+ persistSigningKey(keyPath, newKey);
74
+
75
+ log.info("Auth signing key generated and persisted");
76
+ return newKey;
77
+ }
78
+
79
+ /** The assistant daemon era's transitional key path (under its workspace). */
80
+ function legacySigningKeyPath(): string {
81
+ return join(getWorkspaceDir(), "deprecated", "actor-token-signing-key");
82
+ }
83
+
84
+ /**
85
+ * One-time adoption of the daemon-era key: a pre-custody instance holds
86
+ * its identity only in the workspace's transitional file. Copy it into
87
+ * gateway-security and consume the original, so the assistant container
88
+ * stops having the signing key — this process is the sole holder now.
89
+ * Returns undefined when there is nothing (or nothing valid) to adopt.
90
+ */
91
+ function adoptLegacySigningKey(keyPath: string): Buffer | undefined {
92
+ const legacyPath = legacySigningKeyPath();
93
+ if (!existsSync(legacyPath)) {
94
+ return undefined;
95
+ }
96
+ try {
97
+ const raw = readFileSync(legacyPath);
98
+ if (raw.length !== 32) {
99
+ log.warn(
100
+ { legacyPath },
101
+ "Legacy signing key file has unexpected length, ignoring",
102
+ );
103
+ return undefined;
104
+ }
105
+ persistSigningKey(keyPath, raw);
106
+ rmSync(legacyPath, { force: true });
107
+ log.info(
108
+ { legacyPath },
109
+ "Adopted the daemon-era signing key into gateway security",
110
+ );
111
+ return raw;
112
+ } catch (err) {
113
+ log.warn({ err, legacyPath }, "Failed to adopt legacy signing key");
114
+ return undefined;
115
+ }
116
+ }
117
+
118
+ /** Atomic-write + chmod 0600 persistence into the gateway security dir. */
119
+ function persistSigningKey(keyPath: string, key: Buffer): void {
74
120
  const dir = dirname(keyPath);
75
121
  if (!existsSync(dir)) {
76
122
  mkdirSync(dir, { recursive: true });
77
123
  }
78
124
  const tmpPath = keyPath + ".tmp." + process.pid;
79
- writeFileSync(tmpPath, newKey, { mode: 0o600 });
125
+ writeFileSync(tmpPath, key, { mode: 0o600 });
80
126
  renameSync(tmpPath, keyPath);
81
127
  chmodSync(keyPath, 0o600);
82
-
83
- log.info("Auth signing key generated and persisted");
84
- return newKey;
85
128
  }
86
129
 
87
130
  /**
88
- * Initialize (or reinitialize) the signing key. Called at gateway startup.
131
+ * Initialize (or reinitialize) the signing key. Called at gateway startup —
132
+ * loads or creates the on-disk key via `loadOrCreateSigningKey()`, the one
133
+ * path every real entrypoint shares. Tests that need a deterministic key
134
+ * write one to the security dir first (see
135
+ * `src/__tests__/helpers/signing-key.ts`).
89
136
  */
90
- export function initSigningKey(key: Buffer): void {
91
- signingKey = key;
137
+ export function initSigningKey(): void {
138
+ signingKey = loadOrCreateSigningKey();
92
139
  }
93
140
 
94
141
  function getSigningKey(): Buffer {
@@ -78,3 +78,9 @@ export class AuthRateLimiter {
78
78
  }
79
79
  }
80
80
  }
81
+
82
+ let cachedLimiter: AuthRateLimiter | undefined;
83
+ /** The process-wide auth rate limiter — the router and guarded routes share it. */
84
+ export function getAuthRateLimiter(): AuthRateLimiter {
85
+ return (cachedLimiter ??= new AuthRateLimiter());
86
+ }
@@ -0,0 +1,54 @@
1
+ import { describe, expect, mock, test } from "bun:test";
2
+
3
+ let cleanupCalls = 0;
4
+ let failEveryNth = 0;
5
+
6
+ // The scheduler's only dependency is the store's sweep; mocking it keeps the
7
+ // test about the wiring — tick, report, survive a failed sweep, stop.
8
+ mock.module("../db/inbound-dedup-store.js", () => ({
9
+ cleanupExpiredInboundEvents: () => {
10
+ cleanupCalls += 1;
11
+ if (failEveryNth > 0 && cleanupCalls % failEveryNth === 0) {
12
+ throw new Error("simulated sweep failure");
13
+ }
14
+ return 2;
15
+ },
16
+ }));
17
+
18
+ const { startInboundEventExpirationCleanup } =
19
+ await import("./inbound-event.js");
20
+
21
+ describe("startInboundEventExpirationCleanup", () => {
22
+ test("sweeps on the interval and stops when told", async () => {
23
+ cleanupCalls = 0;
24
+ failEveryNth = 0;
25
+
26
+ const stop = startInboundEventExpirationCleanup(20);
27
+ try {
28
+ await Bun.sleep(70);
29
+ const swept = cleanupCalls;
30
+ expect(swept).toBeGreaterThanOrEqual(2);
31
+
32
+ stop();
33
+ const afterStop = cleanupCalls;
34
+ await Bun.sleep(60);
35
+ expect(cleanupCalls).toBe(afterStop);
36
+ } finally {
37
+ stop();
38
+ }
39
+ });
40
+
41
+ test("a failed sweep does not stop the scheduler", async () => {
42
+ cleanupCalls = 0;
43
+ failEveryNth = 2;
44
+
45
+ const stop = startInboundEventExpirationCleanup(20);
46
+ try {
47
+ await Bun.sleep(90);
48
+ // Half the sweeps threw; the interval kept ticking anyway.
49
+ expect(cleanupCalls).toBeGreaterThanOrEqual(3);
50
+ } finally {
51
+ stop();
52
+ }
53
+ });
54
+ });
@@ -6,6 +6,10 @@ import {
6
6
  } from "@mycadet/gateway-client";
7
7
  import type { ChannelConversationType } from "@mycadet/gateway-client";
8
8
  import type { ChannelId } from "./types.js";
9
+ import { cleanupExpiredInboundEvents } from "../db/inbound-dedup-store.js";
10
+ import { getLogger } from "../logger.js";
11
+
12
+ const log = getLogger("inbound-event");
9
13
 
10
14
  /**
11
15
  * Channel-discriminated inbound event model.
@@ -17,7 +21,7 @@ import type { ChannelId } from "./types.js";
17
21
 
18
22
  export type InboundChannelId = Extract<
19
23
  ChannelId,
20
- "telegram" | "whatsapp" | "slack" | "email" | "a2a" | "discord" | "plugin"
24
+ "telegram" | "whatsapp" | "slack" | "email" | "discord" | "plugin"
21
25
  >;
22
26
 
23
27
  export type GatewayInboundAttachment = {
@@ -161,7 +165,6 @@ export type TelegramInboundEvent = InboundEventBase<"telegram">;
161
165
  export type WhatsAppInboundEvent = InboundEventBase<"whatsapp">;
162
166
  export type SlackInboundEvent = InboundEventBase<"slack">;
163
167
  export type EmailInboundEvent = InboundEventBase<"email">;
164
- export type A2aInboundEvent = InboundEventBase<"a2a">;
165
168
  /**
166
169
  * Constructed by `discord/normalize.ts`. `conversationExternalId` is the
167
170
  * channel snowflake (the parent channel when the message is in a thread, the
@@ -185,7 +188,6 @@ export type GatewayInboundEvent =
185
188
  | WhatsAppInboundEvent
186
189
  | SlackInboundEvent
187
190
  | EmailInboundEvent
188
- | A2aInboundEvent
189
191
  | DiscordInboundEvent
190
192
  | PluginInboundEvent;
191
193
 
@@ -202,3 +204,27 @@ export function eventRefersToAnotherMessage(
202
204
  ): boolean {
203
205
  return inboundEventRefersToAnotherMessage(resolveInboundEventKind(message));
204
206
  }
207
+
208
+ const INBOUND_DEDUP_CLEANUP_INTERVAL_MS = 60 * 60 * 1_000;
209
+
210
+ /**
211
+ * Sweeps expired inbound dedup claims on an interval. Hourly by default,
212
+ * because nothing depends on the sweep being timely: an expired claim is
213
+ * already reclaimed in place by the next delivery on the same key, so this
214
+ * is a size bound, not a correctness one. Returns the stop thunk.
215
+ */
216
+ export function startInboundEventExpirationCleanup(
217
+ intervalMs = INBOUND_DEDUP_CLEANUP_INTERVAL_MS,
218
+ ) {
219
+ const inboundDedupCleanup = setInterval(() => {
220
+ try {
221
+ const evicted = cleanupExpiredInboundEvents();
222
+ if (evicted > 0) {
223
+ log.debug({ evicted }, "Evicted expired inbound dedup claims");
224
+ }
225
+ } catch (err) {
226
+ log.warn({ err }, "Inbound dedup cleanup failed");
227
+ }
228
+ }, intervalMs);
229
+ return () => clearInterval(inboundDedupCleanup);
230
+ }
@@ -227,7 +227,8 @@ function requestUrlCandidates(opts: {
227
227
  }
228
228
 
229
229
  const proto =
230
- opts.headers.get("x-forwarded-proto") ?? opts.headers.get("x-original-proto");
230
+ opts.headers.get("x-forwarded-proto") ??
231
+ opts.headers.get("x-original-proto");
231
232
  const host =
232
233
  opts.headers.get("x-forwarded-host") ?? opts.headers.get("x-original-host");
233
234
  if (raw && proto && host) {
@@ -382,7 +383,10 @@ function verifyStandardWebhooks(opts: {
382
383
  if (!Number.isSafeInteger(Number(timestamp))) {
383
384
  return { ok: false, reason: "missing_timestamp" };
384
385
  }
385
- if (Math.abs(nowMs - stampedMs) > STANDARD_WEBHOOKS_TOLERANCE_SECONDS * 1000) {
386
+ if (
387
+ Math.abs(nowMs - stampedMs) >
388
+ STANDARD_WEBHOOKS_TOLERANCE_SECONDS * 1000
389
+ ) {
386
390
  return { ok: false, reason: "stale_timestamp" };
387
391
  }
388
392
 
@@ -536,7 +540,10 @@ export function verifyDeclaredSignature(opts: {
536
540
 
537
541
  // Length is compared first because timingSafeEqual throws on a mismatch,
538
542
  // and digest length is a function of the declared algorithm.
539
- if (digest.length === expected.length && timingSafeEqual(digest, expected)) {
543
+ if (
544
+ digest.length === expected.length &&
545
+ timingSafeEqual(digest, expected)
546
+ ) {
540
547
  return { ok: true };
541
548
  }
542
549
  }
@@ -75,9 +75,10 @@ describe("readPluginInbound", () => {
75
75
  });
76
76
 
77
77
  it("maps a scoped plugin actor onto the plugin's own contact channel", () => {
78
- expect(
79
- pluginMemberIdentity("plugin", "imessage:+12025550142"),
80
- ).toEqual({ type: "imessage", address: "+12025550142" });
78
+ expect(pluginMemberIdentity("plugin", "imessage:+12025550142")).toEqual({
79
+ type: "imessage",
80
+ address: "+12025550142",
81
+ });
81
82
  expect(pluginMemberIdentity("plugin", "meeting-bot:room-42")).toEqual({
82
83
  type: "meeting-bot",
83
84
  address: "room-42",
@@ -15,7 +15,6 @@ export const CHANNEL_IDS = [
15
15
  "whatsapp",
16
16
  "slack",
17
17
  "email",
18
- "a2a",
19
18
  "discord",
20
19
  "plugin",
21
20
  "cadet-shared",
@@ -40,7 +39,6 @@ export const INTERFACE_IDS = [
40
39
  "whatsapp",
41
40
  "slack",
42
41
  "email",
43
- "a2a",
44
42
  "plugin",
45
43
  ] as const;
46
44
 
@@ -1,18 +1,16 @@
1
1
  /**
2
- * Tests for `gateway contacts`. Parse and execute against a stub IPC
3
- * caller so the suite does not need a live gateway socket.
2
+ * Tests for `gateway contacts`. Run through the commander program with a
3
+ * stub IPC caller injected, so the suite covers the flag-to-command
4
+ * adaptation and the execute layer without a live gateway socket.
4
5
  */
5
6
 
6
- import { beforeEach, describe, expect, test } from "bun:test";
7
+ import { beforeEach, describe, expect, spyOn, test } from "bun:test";
7
8
 
8
- import {
9
- executeContactsCommand,
10
- parseContactsArgs,
11
- type GatewayIpcCall,
12
- } from "../contacts.js";
9
+ import { buildGatewayCliProgram } from "../program.js";
13
10
 
14
- let lastIpc: { method: string; params?: Record<string, unknown> } | null =
15
- null;
11
+ import type { GatewayIpcCall } from "../contacts.js";
12
+
13
+ let lastIpc: { method: string; params?: Record<string, unknown> } | null = null;
16
14
  let ipcResult: unknown = { ok: true, contacts: [] };
17
15
 
18
16
  const ipc: GatewayIpcCall = async (method, params) => {
@@ -20,26 +18,58 @@ const ipc: GatewayIpcCall = async (method, params) => {
20
18
  return ipcResult;
21
19
  };
22
20
 
21
+ let stdout: string[];
22
+ let stderr: string[];
23
+
23
24
  async function run(
24
25
  args: string[],
25
26
  ): Promise<{ code: number; stdout: string; stderr: string }> {
26
- const stdout: string[] = [];
27
- const stderr: string[] = [];
28
- const log = console.log;
29
- const error = console.error;
30
- console.log = (...parts: unknown[]) => {
31
- stdout.push(parts.map(String).join(" "));
32
- };
33
- console.error = (...parts: unknown[]) => {
34
- stderr.push(parts.map(String).join(" "));
35
- };
27
+ stdout = [];
28
+ stderr = [];
29
+ const logSpy = spyOn(console, "log").mockImplementation(
30
+ (...parts: unknown[]) => {
31
+ stdout.push(parts.map(String).join(" "));
32
+ },
33
+ );
34
+ const errorSpy = spyOn(console, "error").mockImplementation(
35
+ (...parts: unknown[]) => {
36
+ stderr.push(parts.map(String).join(" "));
37
+ },
38
+ );
39
+ // Commander writes help and parse-error text straight to the streams —
40
+ // capture those too, or help/error assertions read empty.
41
+ const outSpy = spyOn(process.stdout, "write").mockImplementation((chunk) => {
42
+ stdout.push(String(chunk));
43
+ return true;
44
+ });
45
+ const errSpy = spyOn(process.stderr, "write").mockImplementation((chunk) => {
46
+ stderr.push(String(chunk));
47
+ return true;
48
+ });
49
+ const exitSpy = spyOn(process, "exit").mockImplementation(
50
+ (code?: number): never => {
51
+ throw new Error(`exit:${code}`);
52
+ },
53
+ );
36
54
  try {
37
- const parsed = parseContactsArgs(args);
38
- const code = await executeContactsCommand(parsed, ipc);
39
- return { code, stdout: stdout.join("\n"), stderr: stderr.join("\n") };
55
+ await buildGatewayCliProgram(ipc).parseAsync(args, { from: "user" });
56
+ return { code: 0, stdout: stdout.join("\n"), stderr: stderr.join("\n") };
57
+ } catch (e) {
58
+ const match = /^exit:(-?\d+)$/.exec(e instanceof Error ? e.message : "");
59
+ if (match) {
60
+ return {
61
+ code: Number(match[1]),
62
+ stdout: stdout.join("\n"),
63
+ stderr: stderr.join("\n"),
64
+ };
65
+ }
66
+ throw e;
40
67
  } finally {
41
- console.log = log;
42
- console.error = error;
68
+ logSpy.mockRestore();
69
+ errorSpy.mockRestore();
70
+ outSpy.mockRestore();
71
+ errSpy.mockRestore();
72
+ exitSpy.mockRestore();
43
73
  }
44
74
  }
45
75
 
@@ -48,43 +78,11 @@ beforeEach(() => {
48
78
  ipcResult = { ok: true, contacts: [] };
49
79
  });
50
80
 
51
- describe("parseContactsArgs", () => {
52
- test("maps inherit to a null ceiling", () => {
53
- expect(
54
- parseContactsArgs([
55
- "set-risk-threshold",
56
- "contact-1",
57
- "--threshold",
58
- "inherit",
59
- ]),
60
- ).toEqual({
61
- kind: "set-risk-threshold",
62
- contactId: "contact-1",
63
- threshold: null,
64
- json: false,
65
- });
66
- });
67
-
68
- test("rejects an unknown threshold without calling IPC", () => {
69
- expect(
70
- parseContactsArgs([
71
- "set-risk-threshold",
72
- "contact-1",
73
- "--threshold",
74
- "full",
75
- ]),
76
- ).toEqual({
77
- kind: "error",
78
- message:
79
- 'Invalid --threshold "full". Must be one of: none, low, medium, high, inherit.',
80
- });
81
- });
82
- });
83
-
84
81
  describe("gateway contacts set-risk-threshold", () => {
85
82
  test("writes a ceiling over IPC", async () => {
86
83
  ipcResult = { ok: true, contactId: "contact-1", threshold: "high" };
87
84
  const { code, stdout } = await run([
85
+ "contacts",
88
86
  "set-risk-threshold",
89
87
  "contact-1",
90
88
  "--threshold",
@@ -101,6 +99,7 @@ describe("gateway contacts set-risk-threshold", () => {
101
99
  test("maps inherit to a null ceiling", async () => {
102
100
  ipcResult = { ok: true, contactId: "contact-1", threshold: null };
103
101
  const { code, stdout } = await run([
102
+ "contacts",
104
103
  "set-risk-threshold",
105
104
  "contact-1",
106
105
  "--threshold",
@@ -114,9 +113,23 @@ describe("gateway contacts set-risk-threshold", () => {
114
113
  expect(stdout).toContain("Set assistant access for contact-1 to inherit");
115
114
  });
116
115
 
116
+ test("rejects an unknown threshold without calling IPC", async () => {
117
+ const { code, stderr } = await run([
118
+ "contacts",
119
+ "set-risk-threshold",
120
+ "contact-1",
121
+ "--threshold",
122
+ "full",
123
+ ]);
124
+ expect(code).toBe(1);
125
+ expect(stderr).toContain("full");
126
+ expect(lastIpc).toBeNull();
127
+ });
128
+
117
129
  test("maps a missing contact to exit 1", async () => {
118
130
  ipcResult = { ok: false, error: "not_found" };
119
131
  const { code, stderr } = await run([
132
+ "contacts",
120
133
  "set-risk-threshold",
121
134
  "contact-missing",
122
135
  "--threshold",
@@ -129,6 +142,7 @@ describe("gateway contacts set-risk-threshold", () => {
129
142
  test("exits 1 when the gateway is unreachable", async () => {
130
143
  ipcResult = undefined;
131
144
  const { code, stderr } = await run([
145
+ "contacts",
132
146
  "set-risk-threshold",
133
147
  "contact-1",
134
148
  "--threshold",
@@ -152,7 +166,7 @@ describe("gateway contacts list and get", () => {
152
166
  },
153
167
  ],
154
168
  };
155
- const { code, stdout } = await run(["list"]);
169
+ const { code, stdout } = await run(["contacts", "list"]);
156
170
  expect(code).toBe(0);
157
171
  expect(lastIpc).toEqual({
158
172
  method: "contacts_list_rich",
@@ -163,6 +177,15 @@ describe("gateway contacts list and get", () => {
163
177
  expect(stdout).toContain("access:high");
164
178
  });
165
179
 
180
+ test("filters the list by role", async () => {
181
+ const { code } = await run(["contacts", "list", "--role", "guardian"]);
182
+ expect(code).toBe(0);
183
+ expect(lastIpc).toEqual({
184
+ method: "contacts_list_rich",
185
+ params: { role: "guardian" },
186
+ });
187
+ });
188
+
166
189
  test("gets one contact over IPC", async () => {
167
190
  ipcResult = {
168
191
  ok: true,
@@ -173,7 +196,7 @@ describe("gateway contacts list and get", () => {
173
196
  autoApproveThreshold: null,
174
197
  },
175
198
  };
176
- const { code, stdout } = await run(["get", "contact-1"]);
199
+ const { code, stdout } = await run(["contacts", "get", "contact-1"]);
177
200
  expect(code).toBe(0);
178
201
  expect(lastIpc).toEqual({
179
202
  method: "contacts_get_rich",