@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,883 +0,0 @@
1
- import { describe, test, expect, mock, afterEach, beforeEach } from "bun:test";
2
- import {
3
- existsSync,
4
- mkdirSync,
5
- mkdtempSync,
6
- readFileSync,
7
- rmSync,
8
- writeFileSync,
9
- } from "node:fs";
10
- import { tmpdir } from "node:os";
11
- import { join } from "node:path";
12
- import { Database } from "bun:sqlite";
13
- import type { GatewayConfig } from "../config.js";
14
- import { initSigningKey } from "../auth/token-service.js";
15
- import { initGatewayDb, resetGatewayDb } from "../db/connection.js";
16
-
17
- const TEST_SIGNING_KEY = Buffer.from("test-signing-key-at-least-32-bytes-long");
18
- initSigningKey(TEST_SIGNING_KEY);
19
-
20
- // fetchMock retained for proxyToRuntime calls (verification, etc.)
21
- type FetchFn = (
22
- input: string | URL | Request,
23
- init?: RequestInit,
24
- ) => Promise<Response>;
25
- let fetchMock: ReturnType<typeof mock<FetchFn>> = mock(
26
- async () => new Response(),
27
- );
28
-
29
- mock.module("../fetch.js", () => ({
30
- fetchImpl: (...args: Parameters<FetchFn>) => fetchMock(...args),
31
- }));
32
-
33
- // Mock the IPC proxy so guardian-bootstrap reads/writes the local test DB
34
- let testAssistantDb: Database | null = null;
35
-
36
- mock.module("../db/assistant-db-proxy.js", () => ({
37
- async assistantDbQuery(sql: string, bind?: any[]) {
38
- if (!testAssistantDb) throw new Error("test assistant DB not initialized");
39
- const stmt = testAssistantDb.prepare(sql);
40
- return bind ? stmt.all(...bind) : stmt.all();
41
- },
42
-
43
- async assistantDbRun(sql: string, bind?: any[]) {
44
- if (!testAssistantDb) throw new Error("test assistant DB not initialized");
45
- const stmt = testAssistantDb.prepare(sql);
46
- const result = bind ? stmt.run(...bind) : stmt.run();
47
- return {
48
- changes: result.changes,
49
- lastInsertRowid: Number(result.lastInsertRowid),
50
- };
51
- },
52
- async assistantDbExec(sql: string) {
53
- if (!testAssistantDb) throw new Error("test assistant DB not initialized");
54
- testAssistantDb.exec(sql);
55
- },
56
- }));
57
-
58
- // The guardian identity mirror goes through the typed transactional IPC
59
- // (`contacts_mirror_apply`); record the emitted ops so the bootstrap test can
60
- // assert the mirror fired with the gateway-minted ids. The op's DB effect is
61
- // covered assistant-side in contacts-mirror-apply.test.ts.
62
- const mirrorApplyOps: unknown[][] = [];
63
- const realAssistantClient = await import("../ipc/assistant-client.js");
64
- mock.module("../ipc/assistant-client.js", () => ({
65
- ...realAssistantClient,
66
- async ipcCallAssistant(
67
- method: string,
68
- params?: { body?: { ops?: unknown[] } },
69
- ) {
70
- if (method === "contacts_mirror_apply") {
71
- mirrorApplyOps.push(params?.body?.ops ?? []);
72
- }
73
- return { ok: true };
74
- },
75
- }));
76
-
77
- const { createChannelVerificationSessionProxyHandler } =
78
- await import("../http/routes/channel-verification-session-proxy.js");
79
-
80
- // ---------------------------------------------------------------------------
81
- // Test directory setup
82
- // ---------------------------------------------------------------------------
83
-
84
- let testRoot: string;
85
- let securityDir: string;
86
-
87
- /** Lock-file and consumed-file paths under the test security dir. */
88
- function lockPath(): string {
89
- return join(securityDir, "guardian-init.lock");
90
- }
91
- function consumedPath(): string {
92
- return join(securityDir, "guardian-init-consumed.json");
93
- }
94
-
95
- async function setupTestDirs(): Promise<void> {
96
- testRoot = mkdtempSync(join(tmpdir(), "guardian-bootstrap-test-"));
97
- securityDir = join(testRoot, "protected");
98
- mkdirSync(securityDir, { recursive: true });
99
-
100
- const dbDir = join(testRoot, "data", "db");
101
- mkdirSync(dbDir, { recursive: true });
102
-
103
- const db = new Database(join(dbDir, "assistant.db"));
104
- db.exec("PRAGMA journal_mode=WAL");
105
- db.exec("PRAGMA foreign_keys=ON");
106
-
107
- db.exec(`
108
- CREATE TABLE IF NOT EXISTS contacts (
109
- id TEXT PRIMARY KEY,
110
- display_name TEXT NOT NULL,
111
- notes TEXT,
112
- created_at INTEGER NOT NULL,
113
- updated_at INTEGER NOT NULL,
114
- role TEXT NOT NULL DEFAULT 'contact',
115
- principal_id TEXT,
116
- user_file TEXT,
117
- contact_type TEXT NOT NULL DEFAULT 'human'
118
- )
119
- `);
120
- db.exec(`
121
- CREATE TABLE IF NOT EXISTS contact_channels (
122
- id TEXT PRIMARY KEY,
123
- contact_id TEXT NOT NULL REFERENCES contacts(id) ON DELETE CASCADE,
124
- type TEXT NOT NULL,
125
- address TEXT NOT NULL,
126
- is_primary INTEGER NOT NULL DEFAULT 0,
127
- external_user_id TEXT,
128
- external_chat_id TEXT,
129
- status TEXT NOT NULL DEFAULT 'unverified',
130
- policy TEXT NOT NULL DEFAULT 'allow',
131
- verified_at INTEGER,
132
- verified_via TEXT,
133
- invite_id TEXT,
134
- revoked_reason TEXT,
135
- blocked_reason TEXT,
136
- last_seen_at INTEGER,
137
- interaction_count INTEGER NOT NULL DEFAULT 0,
138
- last_interaction INTEGER,
139
- updated_at INTEGER,
140
- created_at INTEGER NOT NULL
141
- )
142
- `);
143
-
144
- // Keep the DB open for the IPC proxy mock
145
- testAssistantDb = db;
146
-
147
- // Point gateway at temp dirs
148
- process.env.CADET_WORKSPACE_DIR = testRoot;
149
- process.env.GATEWAY_SECURITY_DIR = securityDir;
150
-
151
- // Initialize gateway DB so token operations can write to it
152
- await initGatewayDb();
153
- }
154
-
155
- function makeConfig(overrides: Partial<GatewayConfig> = {}): GatewayConfig {
156
- return {
157
- assistantRuntimeBaseUrl: "http://localhost:7821",
158
- routingEntries: [],
159
- port: 7830,
160
- runtimeProxyRequireAuth: true,
161
- runtimeTimeoutMs: 30000,
162
- runtimeMaxRetries: 2,
163
- runtimeInitialBackoffMs: 500,
164
- maxWebhookPayloadBytes: 1048576,
165
- logFile: { dir: undefined, retentionDays: 30 },
166
- maxAttachmentBytes: {
167
- telegram: 50 * 1024 * 1024,
168
- slack: 100 * 1024 * 1024,
169
- whatsapp: 16 * 1024 * 1024,
170
- default: 50 * 1024 * 1024,
171
- },
172
- maxAttachmentConcurrency: 3,
173
- gatewayInternalBaseUrl: "http://127.0.0.1:7830",
174
- trustProxy: false,
175
- ...overrides,
176
- };
177
- }
178
-
179
- beforeEach(async () => {
180
- await setupTestDirs();
181
- });
182
-
183
- afterEach(() => {
184
- resetGatewayDb();
185
- fetchMock = mock(async () => new Response());
186
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
187
- if (testAssistantDb) {
188
- try {
189
- testAssistantDb.close();
190
- } catch {
191
- /* best effort */
192
- }
193
- testAssistantDb = null;
194
- }
195
- try {
196
- rmSync(testRoot, { recursive: true, force: true });
197
- } catch {
198
- /* best effort */
199
- }
200
- });
201
-
202
- // ---------------------------------------------------------------------------
203
- // Helpers
204
- // ---------------------------------------------------------------------------
205
-
206
- function lockFileExists(): boolean {
207
- return existsSync(lockPath());
208
- }
209
-
210
- function consumedSecrets(): number[] {
211
- try {
212
- return JSON.parse(readFileSync(consumedPath(), "utf-8")) as number[];
213
- } catch {
214
- return [];
215
- }
216
- }
217
-
218
- // ---------------------------------------------------------------------------
219
- // Tests
220
- // ---------------------------------------------------------------------------
221
-
222
- describe("guardian/init bootstrap secret", () => {
223
- test("rejects requests without secret when GUARDIAN_BOOTSTRAP_SECRET is set", async () => {
224
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "test-secret-abc123";
225
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
226
- const res = await handler.handleGuardianInit(
227
- new Request("http://localhost:7830/v1/guardian/init", {
228
- method: "POST",
229
- headers: { "Content-Type": "application/json" },
230
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
231
- }),
232
- );
233
-
234
- expect(res.status).toBe(403);
235
- const body = await res.json();
236
- expect(body.error).toBe("Invalid bootstrap secret");
237
- });
238
-
239
- test("rejects requests with wrong secret", async () => {
240
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "test-secret-abc123";
241
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
242
- const res = await handler.handleGuardianInit(
243
- new Request("http://localhost:7830/v1/guardian/init", {
244
- method: "POST",
245
- headers: {
246
- "Content-Type": "application/json",
247
- "x-bootstrap-secret": "wrong-secret",
248
- },
249
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
250
- }),
251
- );
252
-
253
- expect(res.status).toBe(403);
254
- const body = await res.json();
255
- expect(body.error).toBe("Invalid bootstrap secret");
256
- });
257
-
258
- test("accepts requests with correct secret and writes lock for single secret", async () => {
259
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "test-secret-abc123";
260
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
261
- const res = await handler.handleGuardianInit(
262
- new Request("http://localhost:7830/v1/guardian/init", {
263
- method: "POST",
264
- headers: {
265
- "Content-Type": "application/json",
266
- "x-bootstrap-secret": "test-secret-abc123",
267
- },
268
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
269
- }),
270
- );
271
-
272
- expect(res.status).toBe(200);
273
- const body = await res.json();
274
- expect(body.guardianPrincipalId).toMatch(/^principal-/);
275
- expect(body.accessToken).toBeTruthy();
276
- expect(body.refreshToken).toBeTruthy();
277
- expect(body.isNew).toBe(true);
278
- // Single secret: consumed file written and lock file created immediately
279
- expect(consumedSecrets()).toContain(0);
280
- expect(lockFileExists()).toBe(true);
281
- });
282
-
283
- test("skips secret check when GUARDIAN_BOOTSTRAP_SECRET is not set", async () => {
284
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
285
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
286
- const res = await handler.handleGuardianInit(
287
- new Request("http://localhost:7830/v1/guardian/init", {
288
- method: "POST",
289
- headers: { "Content-Type": "application/json" },
290
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
291
- }),
292
- );
293
-
294
- expect(res.status).toBe(200);
295
- const body = await res.json();
296
- expect(body.accessToken).toBeTruthy();
297
- });
298
- });
299
-
300
- describe("guardian/init edge-proxy guard", () => {
301
- // The self-hosted nginx edge (SPA over an ngrok tunnel) sets this marker.
302
- // Every hop in that chain is loopback, so clientIp is the legitimate-looking
303
- // 127.0.0.1 — the marker is the unspoofable proof the request was forwarded
304
- // by the edge and must be rejected, regardless of deploy mode.
305
- const EDGE_HEADER = "x-cadet-edge-forwarded";
306
-
307
- function makeEdgeForwardedRequest(secret?: string): Request {
308
- const headers: Record<string, string> = {
309
- "Content-Type": "application/json",
310
- [EDGE_HEADER]: "1",
311
- };
312
- if (secret) headers["x-bootstrap-secret"] = secret;
313
- return new Request("http://localhost:7830/v1/guardian/init", {
314
- method: "POST",
315
- headers,
316
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
317
- });
318
- }
319
-
320
- test("rejects an edge-forwarded request from a loopback peer in bare-metal mode", async () => {
321
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
322
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
323
- // clientIp is loopback (as it always is behind the edge) — without the
324
- // marker this would mint a token (see "skips secret check" above).
325
- const res = await handler.handleGuardianInit(
326
- makeEdgeForwardedRequest(),
327
- "127.0.0.1",
328
- );
329
-
330
- expect(res.status).toBe(403);
331
- const body = await res.json();
332
- expect(body.error).toBe(
333
- "Bootstrap endpoint is not accessible via the web edge",
334
- );
335
- });
336
-
337
- test("rejects an edge-forwarded request even with a valid bootstrap secret", async () => {
338
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "test-secret-abc123";
339
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
340
- const res = await handler.handleGuardianInit(
341
- makeEdgeForwardedRequest("test-secret-abc123"),
342
- "127.0.0.1",
343
- );
344
-
345
- // Rejected before the secret is ever considered.
346
- expect(res.status).toBe(403);
347
- const body = await res.json();
348
- expect(body.error).toBe(
349
- "Bootstrap endpoint is not accessible via the web edge",
350
- );
351
- });
352
-
353
- // Regression: with GATEWAY_TRUST_PROXY enabled, the gateway resolves clientIp
354
- // from the leftmost (client-spoofable) X-Forwarded-For entry. A remote caller
355
- // forging `X-Forwarded-For: 127.0.0.1` would otherwise pass the bare-metal
356
- // loopback check and reach the token-minting bootstrap path. The header's
357
- // presence alone must be rejected in bare-metal mode.
358
- test("rejects a spoofed X-Forwarded-For loopback in bare-metal mode", async () => {
359
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
360
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
361
- const res = await handler.handleGuardianInit(
362
- new Request("http://localhost:7830/v1/guardian/init", {
363
- method: "POST",
364
- headers: {
365
- "Content-Type": "application/json",
366
- "x-forwarded-for": "127.0.0.1",
367
- },
368
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
369
- }),
370
- // clientIp as it would be resolved from the spoofed header when
371
- // GATEWAY_TRUST_PROXY is on.
372
- "127.0.0.1",
373
- );
374
-
375
- expect(res.status).toBe(403);
376
- const body = await res.json();
377
- expect(body.error).toBe("Bootstrap endpoint is local-only");
378
- });
379
- });
380
-
381
- describe("guardian/init one-time-use lockfile", () => {
382
- test("first call succeeds and creates lock file", async () => {
383
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
384
- const res = await handler.handleGuardianInit(
385
- new Request("http://localhost:7830/v1/guardian/init", {
386
- method: "POST",
387
- headers: { "Content-Type": "application/json" },
388
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
389
- }),
390
- );
391
-
392
- expect(res.status).toBe(200);
393
- const body = await res.json();
394
- expect(body.guardianPrincipalId).toMatch(/^principal-/);
395
- expect(body.accessToken).toBeTruthy();
396
- expect(body.refreshToken).toBeTruthy();
397
- expect(lockFileExists()).toBe(true);
398
- });
399
-
400
- test("second call is rejected by lockfile", async () => {
401
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
402
-
403
- // First call succeeds
404
- const res1 = await handler.handleGuardianInit(
405
- new Request("http://localhost:7830/v1/guardian/init", {
406
- method: "POST",
407
- headers: { "Content-Type": "application/json" },
408
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
409
- }),
410
- );
411
- expect(res1.status).toBe(200);
412
-
413
- // Second call rejected by lockfile
414
- const res2 = await handler.handleGuardianInit(
415
- new Request("http://localhost:7830/v1/guardian/init", {
416
- method: "POST",
417
- headers: { "Content-Type": "application/json" },
418
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
419
- }),
420
- );
421
- expect(res2.status).toBe(403);
422
- const body = await res2.json();
423
- expect(body.error).toBe("Bootstrap already completed");
424
- });
425
-
426
- test("concurrent requests are rejected by in-memory guard", async () => {
427
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
428
-
429
- const makeReq = () =>
430
- new Request("http://localhost:7830/v1/guardian/init", {
431
- method: "POST",
432
- headers: { "Content-Type": "application/json" },
433
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
434
- });
435
-
436
- // Fire two requests concurrently
437
- const p1 = handler.handleGuardianInit(makeReq());
438
- const p2 = handler.handleGuardianInit(makeReq());
439
-
440
- // Second request should be rejected immediately by in-memory guard
441
- const res2 = await p2;
442
- expect(res2.status).toBe(403);
443
-
444
- const res1 = await p1;
445
- expect(res1.status).toBe(200);
446
-
447
- // Lock file should be written exactly once
448
- expect(lockFileExists()).toBe(true);
449
- });
450
-
451
- test("bootstrap creates contact and token records in the DB", async () => {
452
- mirrorApplyOps.length = 0;
453
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
454
- const res = await handler.handleGuardianInit(
455
- new Request("http://localhost:7830/v1/guardian/init", {
456
- method: "POST",
457
- headers: { "Content-Type": "application/json" },
458
- body: JSON.stringify({ platform: "cli", deviceId: "my-device" }),
459
- }),
460
- );
461
- expect(res.status).toBe(200);
462
- const body = await res.json();
463
-
464
- // Assistant DB mirrors identity only (no ACL columns — gateway-owned) via a
465
- // single atomic upsert_channel op keyed on the gateway-minted ids.
466
- expect(mirrorApplyOps).toHaveLength(1);
467
- const op = mirrorApplyOps[0][0] as Record<string, unknown>;
468
- expect(op.op).toBe("upsert_channel");
469
- expect(op.type).toBe("cadet");
470
- expect(op.isPrimary).toBe(true);
471
- expect(op.contactId).toBeTruthy();
472
- expect(op.channelId).toBeTruthy();
473
-
474
- // Verify token records were written to the gateway DB
475
- const gwDb = new Database(join(securityDir, "gateway.sqlite"), {
476
- readonly: true,
477
- });
478
-
479
- // Gateway DB owns the ACL state for the guardian binding.
480
- const gwContact = gwDb
481
- .query<
482
- { role: string; principal_id: string },
483
- []
484
- >("SELECT role, principal_id FROM contacts WHERE role = 'guardian'")
485
- .get();
486
- expect(gwContact).toBeTruthy();
487
- expect(gwContact!.principal_id).toBe(body.guardianPrincipalId);
488
-
489
- const gwChannel = gwDb
490
- .query<
491
- { status: string; policy: string },
492
- []
493
- >("SELECT status, policy FROM contact_channels WHERE type = 'cadet'")
494
- .get();
495
- expect(gwChannel).toBeTruthy();
496
- expect(gwChannel!.status).toBe("active");
497
- expect(gwChannel!.policy).toBe("allow");
498
-
499
- const tokenCount = gwDb
500
- .query<
501
- { cnt: number },
502
- []
503
- >("SELECT COUNT(*) as cnt FROM actor_token_records WHERE status = 'active'")
504
- .get();
505
- expect(tokenCount!.cnt).toBe(1);
506
-
507
- const refreshCount = gwDb
508
- .query<
509
- { cnt: number },
510
- []
511
- >("SELECT COUNT(*) as cnt FROM actor_refresh_token_records WHERE status = 'active'")
512
- .get();
513
- expect(refreshCount!.cnt).toBe(1);
514
-
515
- gwDb.close();
516
- });
517
-
518
- test("a client-reported hostname in the init request is persisted on the token record", async () => {
519
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
520
- const res = await handler.handleGuardianInit(
521
- new Request("http://localhost:7830/v1/guardian/init", {
522
- method: "POST",
523
- headers: { "Content-Type": "application/json" },
524
- body: JSON.stringify({
525
- platform: "cli",
526
- deviceId: "my-remote-device",
527
- clientReportedName: "Alices-MacBook-Pro.local",
528
- }),
529
- }),
530
- );
531
- expect(res.status).toBe(200);
532
-
533
- const gwDb = new Database(join(securityDir, "gateway.sqlite"), {
534
- readonly: true,
535
- });
536
- const tokenRow = gwDb
537
- .query<
538
- { client_reported_name: string | null },
539
- []
540
- >("SELECT client_reported_name FROM actor_token_records WHERE status = 'active'")
541
- .get();
542
- expect(tokenRow?.client_reported_name).toBe("Alices-MacBook-Pro.local");
543
- gwDb.close();
544
- });
545
- });
546
-
547
- describe("guardian/init multi-secret consumption tracking", () => {
548
- const SECRET_A = "secret-laptop-aaa";
549
- const SECRET_B = "secret-remote-bbb";
550
-
551
- function makeInitRequest(secret?: string): Request {
552
- const headers: Record<string, string> = {
553
- "Content-Type": "application/json",
554
- };
555
- if (secret) {
556
- headers["x-bootstrap-secret"] = secret;
557
- }
558
- return new Request("http://localhost:7830/v1/guardian/init", {
559
- method: "POST",
560
- headers,
561
- body: JSON.stringify({
562
- platform: "cli",
563
- deviceId: `device-${secret ?? "none"}`,
564
- }),
565
- });
566
- }
567
-
568
- test("first secret is consumed but lock is deferred until all secrets used", async () => {
569
- process.env.GUARDIAN_BOOTSTRAP_SECRET = `${SECRET_A},${SECRET_B}`;
570
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
571
- const res = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
572
-
573
- expect(res.status).toBe(200);
574
- expect(consumedSecrets()).toEqual([0]);
575
- expect(lockFileExists()).toBe(false);
576
- });
577
-
578
- test("lock file written after all secrets consumed", async () => {
579
- process.env.GUARDIAN_BOOTSTRAP_SECRET = `${SECRET_A},${SECRET_B}`;
580
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
581
-
582
- const res1 = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
583
- expect(res1.status).toBe(200);
584
- expect(lockFileExists()).toBe(false);
585
-
586
- const res2 = await handler.handleGuardianInit(makeInitRequest(SECRET_B));
587
- expect(res2.status).toBe(200);
588
- expect(lockFileExists()).toBe(true);
589
- });
590
-
591
- test("reusing a consumed secret is rejected", async () => {
592
- process.env.GUARDIAN_BOOTSTRAP_SECRET = `${SECRET_A},${SECRET_B}`;
593
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
594
-
595
- const res1 = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
596
- expect(res1.status).toBe(200);
597
-
598
- const res2 = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
599
- expect(res2.status).toBe(403);
600
- const body = await res2.json();
601
- expect(body.error).toBe("Bootstrap secret already used");
602
- });
603
-
604
- test("all secrets rejected after full consumption and lock", async () => {
605
- process.env.GUARDIAN_BOOTSTRAP_SECRET = `${SECRET_A},${SECRET_B}`;
606
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
607
-
608
- await handler.handleGuardianInit(makeInitRequest(SECRET_A));
609
- await handler.handleGuardianInit(makeInitRequest(SECRET_B));
610
- expect(lockFileExists()).toBe(true);
611
-
612
- const res = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
613
- expect(res.status).toBe(403);
614
- const body = await res.json();
615
- expect(body.error).toContain("already");
616
- });
617
-
618
- test("concurrent requests with same secret rejected by in-flight guard", async () => {
619
- process.env.GUARDIAN_BOOTSTRAP_SECRET = `${SECRET_A},${SECRET_B}`;
620
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
621
-
622
- const p1 = handler.handleGuardianInit(makeInitRequest(SECRET_A));
623
- const res2 = await handler.handleGuardianInit(makeInitRequest(SECRET_A));
624
-
625
- expect(res2.status).toBe(403);
626
- const body = await res2.json();
627
- expect(body.error).toBe("Bootstrap secret already used");
628
-
629
- const res1 = await p1;
630
- expect(res1.status).toBe(200);
631
- });
632
- });
633
-
634
- describe("guardian/reset-bootstrap", () => {
635
- test("removes lock file and allows re-init on bare-metal", async () => {
636
- // Pre-create a lock file
637
- writeFileSync(lockPath(), new Date().toISOString(), { mode: 0o600 });
638
- expect(lockFileExists()).toBe(true);
639
-
640
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
641
- const res = await handler.handleResetBootstrap("127.0.0.1");
642
- expect(res.status).toBe(200);
643
- expect(lockFileExists()).toBe(false);
644
- });
645
-
646
- test("succeeds idempotently when lock file does not exist", async () => {
647
- expect(lockFileExists()).toBe(false);
648
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
649
-
650
- const res = await handler.handleResetBootstrap("127.0.0.1");
651
- expect(res.status).toBe(200);
652
- });
653
-
654
- test("rejects non-loopback clients", async () => {
655
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
656
-
657
- const res = await handler.handleResetBootstrap("192.168.1.100");
658
- expect(res.status).toBe(403);
659
- const body = await res.json();
660
- expect(body.error).toBe("Loopback-only endpoint");
661
- });
662
-
663
- test("rejects without valid bootstrap secret when secrets are configured", async () => {
664
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "some-secret";
665
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
666
-
667
- const res = await handler.handleResetBootstrap("127.0.0.1");
668
- expect(res.status).toBe(403);
669
- const body = await res.json();
670
- expect(body.error).toBe("Invalid bootstrap secret");
671
- });
672
-
673
- test("allows reset with valid bootstrap secret", async () => {
674
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "some-secret";
675
- writeFileSync(lockPath(), new Date().toISOString(), { mode: 0o600 });
676
- writeFileSync(consumedPath(), JSON.stringify([0]) + "\n", { mode: 0o600 });
677
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
678
-
679
- const req = new Request(
680
- "http://localhost:7830/v1/guardian/reset-bootstrap",
681
- {
682
- method: "POST",
683
- headers: { "x-bootstrap-secret": "some-secret" },
684
- },
685
- );
686
- const res = await handler.handleResetBootstrap("127.0.0.1", req);
687
- expect(res.status).toBe(200);
688
- expect(lockFileExists()).toBe(false);
689
- expect(consumedSecrets()).toEqual([]);
690
- });
691
-
692
- test("resets in-flight flag so init can proceed", async () => {
693
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
694
-
695
- // First init succeeds and writes lock
696
- const res1 = await handler.handleGuardianInit(
697
- new Request("http://localhost:7830/v1/guardian/init", {
698
- method: "POST",
699
- headers: { "Content-Type": "application/json" },
700
- body: JSON.stringify({ platform: "cli", deviceId: "d" }),
701
- }),
702
- "127.0.0.1",
703
- );
704
- expect(res1.status).toBe(200);
705
- expect(lockFileExists()).toBe(true);
706
-
707
- // Second init is rejected
708
- const blocked = await handler.handleGuardianInit(
709
- new Request("http://localhost:7830/v1/guardian/init", {
710
- method: "POST",
711
- headers: { "Content-Type": "application/json" },
712
- body: JSON.stringify({ platform: "cli", deviceId: "d2" }),
713
- }),
714
- "127.0.0.1",
715
- );
716
- expect(blocked.status).toBe(403);
717
-
718
- // Reset clears the lock
719
- const resetRes = await handler.handleResetBootstrap("127.0.0.1");
720
- expect(resetRes.status).toBe(200);
721
- expect(lockFileExists()).toBe(false);
722
-
723
- // Third init succeeds again
724
- const res3 = await handler.handleGuardianInit(
725
- new Request("http://localhost:7830/v1/guardian/init", {
726
- method: "POST",
727
- headers: { "Content-Type": "application/json" },
728
- body: JSON.stringify({ platform: "cli", deviceId: "d3" }),
729
- }),
730
- "127.0.0.1",
731
- );
732
- expect(res3.status).toBe(200);
733
- });
734
- });
735
-
736
- describe("guardian/init bare-metal loopback gating", () => {
737
- test("rejects non-loopback clients in bare-metal mode", async () => {
738
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
739
- delete process.env.IS_CLOUD;
740
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
741
- const res = await handler.handleGuardianInit(
742
- new Request("http://localhost:7830/v1/guardian/init", {
743
- method: "POST",
744
- headers: { "Content-Type": "application/json" },
745
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
746
- }),
747
- "192.168.1.100",
748
- );
749
-
750
- expect(res.status).toBe(403);
751
- const body = await res.json();
752
- expect(body.error).toBe("Bootstrap endpoint is local-only");
753
- });
754
-
755
- test("allows loopback clients in bare-metal mode", async () => {
756
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
757
- delete process.env.IS_CLOUD;
758
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
759
- const res = await handler.handleGuardianInit(
760
- new Request("http://localhost:7830/v1/guardian/init", {
761
- method: "POST",
762
- headers: { "Content-Type": "application/json" },
763
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
764
- }),
765
- "127.0.0.1",
766
- );
767
-
768
- expect(res.status).toBe(200);
769
- const body = await res.json();
770
- expect(body.accessToken).toBeTruthy();
771
- });
772
-
773
- test("skips loopback check in Docker mode (secret-based)", async () => {
774
- process.env.GUARDIAN_BOOTSTRAP_SECRET = "docker-secret-123";
775
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
776
- const res = await handler.handleGuardianInit(
777
- new Request("http://localhost:7830/v1/guardian/init", {
778
- method: "POST",
779
- headers: {
780
- "Content-Type": "application/json",
781
- "x-bootstrap-secret": "docker-secret-123",
782
- },
783
- body: JSON.stringify({ platform: "cli", deviceId: "test-device" }),
784
- }),
785
- "10.0.2.15",
786
- );
787
-
788
- expect(res.status).toBe(200);
789
- const body = await res.json();
790
- expect(body.accessToken).toBeTruthy();
791
- });
792
-
793
- test("skips loopback check in cloud-managed mode (IS_CLOUD=true)", async () => {
794
- delete process.env.GUARDIAN_BOOTSTRAP_SECRET;
795
- process.env.IS_CLOUD = "true";
796
- try {
797
- const handler =
798
- createChannelVerificationSessionProxyHandler(makeConfig());
799
- const res = await handler.handleGuardianInit(
800
- new Request("http://localhost:7830/v1/guardian/init", {
801
- method: "POST",
802
- headers: { "Content-Type": "application/json" },
803
- body: JSON.stringify({
804
- platform: "web",
805
- deviceId: "platform-abc123",
806
- }),
807
- }),
808
- "::ffff:10.112.1.68",
809
- );
810
-
811
- expect(res.status).toBe(200);
812
- const body = await res.json();
813
- expect(body.accessToken).toBeTruthy();
814
- } finally {
815
- delete process.env.IS_CLOUD;
816
- }
817
- });
818
- });
819
-
820
- describe("guardian/init request validation", () => {
821
- test("accepts Windows bootstrap requests", async () => {
822
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
823
- const res = await handler.handleGuardianInit(
824
- new Request("http://localhost:7830/v1/guardian/init", {
825
- method: "POST",
826
- headers: { "Content-Type": "application/json" },
827
- body: JSON.stringify({
828
- platform: "windows",
829
- deviceId: "windows-device",
830
- }),
831
- }),
832
- );
833
-
834
- expect(res.status).toBe(200);
835
- const body = await res.json();
836
- expect(body.accessToken).toBeTruthy();
837
- });
838
-
839
- test("rejects missing platform", async () => {
840
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
841
- const res = await handler.handleGuardianInit(
842
- new Request("http://localhost:7830/v1/guardian/init", {
843
- method: "POST",
844
- headers: { "Content-Type": "application/json" },
845
- body: JSON.stringify({ deviceId: "test-device" }),
846
- }),
847
- );
848
-
849
- expect(res.status).toBe(400);
850
- const body = await res.json();
851
- expect(body.error).toContain("Missing required fields");
852
- });
853
-
854
- test("rejects invalid platform", async () => {
855
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
856
- const res = await handler.handleGuardianInit(
857
- new Request("http://localhost:7830/v1/guardian/init", {
858
- method: "POST",
859
- headers: { "Content-Type": "application/json" },
860
- body: JSON.stringify({ platform: "ios", deviceId: "test-device" }),
861
- }),
862
- );
863
-
864
- expect(res.status).toBe(400);
865
- const body = await res.json();
866
- expect(body.error).toContain("Invalid platform");
867
- });
868
-
869
- test("rejects invalid JSON body", async () => {
870
- const handler = createChannelVerificationSessionProxyHandler(makeConfig());
871
- const res = await handler.handleGuardianInit(
872
- new Request("http://localhost:7830/v1/guardian/init", {
873
- method: "POST",
874
- headers: { "Content-Type": "application/json" },
875
- body: "not json",
876
- }),
877
- );
878
-
879
- expect(res.status).toBe(400);
880
- const body = await res.json();
881
- expect(body.error).toBe("Invalid JSON body");
882
- });
883
- });