@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.
- package/Dockerfile +1 -0
- package/README.md +10 -10
- package/eslint.config.mjs +7 -8
- package/knip.json +2 -8
- package/node_modules/@mycadet/assistant-client/src/__tests__/assistant-client.test.ts +40 -34
- package/node_modules/@mycadet/assistant-client/src/http-client.ts +59 -8
- package/node_modules/@mycadet/assistant-client/src/index.ts +4 -0
- package/node_modules/@mycadet/assistant-client/src/proxy-forward.ts +5 -4
- package/node_modules/@mycadet/assistant-client/src/websocket-upstream.ts +21 -31
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/package.json +18 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/endpoint.test.ts +36 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/endpoint.ts +142 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/index.ts +18 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/ipc-framing.ts +295 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/listen-options.ts +3 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.test.ts +444 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.ts +236 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/ipc-server-utils/tsconfig.json +20 -0
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
- package/node_modules/@mycadet/ces-client/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
- package/node_modules/@mycadet/ces-client/package.json +7 -2
- package/node_modules/@mycadet/ces-client/src/index.ts +6 -0
- package/node_modules/@mycadet/ces-client/src/ipc-credentials.ts +363 -0
- package/node_modules/@mycadet/ces-client/src/log-export.ts +187 -0
- package/node_modules/@mycadet/ces-client/src/socket-path.ts +34 -0
- package/node_modules/@mycadet/ces-client/src/test-support.ts +280 -0
- package/node_modules/@mycadet/environments/package.json +0 -1
- package/node_modules/@mycadet/environments/src/index.ts +7 -19
- package/node_modules/@mycadet/environments/src/shell.test.ts +0 -45
- package/node_modules/@mycadet/environments/src/shell.ts +0 -50
- package/node_modules/@mycadet/environments/src/test-path-guard.ts +1 -1
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
- package/node_modules/@mycadet/gateway-client/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
- package/node_modules/@mycadet/gateway-client/src/__tests__/gateway-client.test.ts +5 -5
- package/node_modules/@mycadet/gateway-client/src/__tests__/package-boundary.test.ts +1 -1
- package/node_modules/@mycadet/gateway-client/src/__tests__/status-contracts.test.ts +1 -20
- package/node_modules/@mycadet/gateway-client/src/admission-policy-contract.ts +1 -2
- package/node_modules/@mycadet/gateway-client/src/gateway-ipc-contracts.ts +0 -16
- package/node_modules/@mycadet/ipc-server-utils/src/socket-watchdog.test.ts +1 -1
- package/node_modules/@mycadet/service-contracts/src/__tests__/contracts.test.ts +5 -2
- package/node_modules/@mycadet/service-contracts/src/__tests__/remote-web-pairing.test.ts +17 -14
- package/node_modules/@mycadet/service-contracts/src/channels.ts +0 -1
- package/node_modules/@mycadet/service-contracts/src/cloud-credential.ts +5 -5
- package/node_modules/@mycadet/service-contracts/src/ingress.ts +7 -3
- package/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +32 -70
- package/node_modules/@mycadet/service-contracts/src/rpc.ts +33 -3
- package/package.json +15 -13
- package/scripts/generate-openapi.ts +24 -32
- package/src/__tests__/actor-token-revocation.test.ts +14 -7
- package/src/__tests__/auto-approve-conversation-thresholds.test.ts +16 -16
- package/src/__tests__/auto-approve-thresholds.test.ts +22 -20
- package/src/__tests__/binding-helpers.test.ts +9 -12
- package/src/__tests__/channel-admission-policy-routes.test.ts +20 -34
- package/src/__tests__/channel-permission-overrides-routes.test.ts +20 -26
- package/src/__tests__/channel-verification-session-proxy.test.ts +36 -22
- package/src/__tests__/cli-entry-init.test.ts +103 -0
- package/src/__tests__/config.test.ts +4 -5
- package/src/__tests__/contact-handlers.test.ts +8 -10
- package/src/__tests__/contact-prompt-submit.test.ts +3 -1
- package/src/__tests__/contact-record-submit.test.ts +3 -1
- package/src/__tests__/contact-rich-read.test.ts +11 -20
- package/src/__tests__/contact-store-bind-principal.test.ts +12 -15
- package/src/__tests__/contact-store-invites.test.ts +6 -6
- package/src/__tests__/contact-store-mark-channel-verified.test.ts +8 -10
- package/src/__tests__/contact-store-merge-contacts.test.ts +7 -10
- package/src/__tests__/contact-store-mirror-op-missing.test.ts +7 -11
- package/src/__tests__/contacts-control-plane-proxy.test.ts +3 -21
- package/src/__tests__/contacts-info-client.test.ts +6 -5
- package/src/__tests__/contacts-info-joiner.test.ts +8 -13
- package/src/__tests__/contacts-scoped-route-fallthrough.test.ts +14 -12
- package/src/__tests__/credential-cache.test.ts +1 -6
- package/src/__tests__/credential-reader.test.ts +146 -157
- package/src/__tests__/credential-requests.test.ts +1 -3
- package/src/__tests__/credential-watcher-cloud-bootstrap.test.ts +57 -104
- package/src/__tests__/data-migration-m0007-backfill-ingress-invites.test.ts +14 -17
- package/src/__tests__/data-migration-m0008-upsert-acl-columns-from-assistant.test.ts +10 -13
- package/src/__tests__/data-migration-m0009-invite-fields-backfill.test.ts +20 -19
- package/src/__tests__/data-migration-m0010-drop-assistant-ingress-invites.test.ts +12 -15
- package/src/__tests__/data-migration-m0013-verification-sessions-backfill.test.ts +20 -23
- package/src/__tests__/data-migration-m0014-drop-assistant-verification-tables.test.ts +12 -15
- package/src/__tests__/data-migration-m0015-guardian-requests-backfill.test.ts +6 -9
- package/src/__tests__/data-migration-m0016-drop-assistant-guardian-tables.test.ts +16 -19
- package/src/__tests__/data-migration-m0017-coerce-escalate-policy.test.ts +6 -10
- package/src/__tests__/db-connection-isolation.test.ts +1 -2
- package/src/__tests__/db-proxy-allowlist.test.ts +25 -16
- package/src/__tests__/desktop-stream-websocket.test.ts +34 -28
- package/src/__tests__/device-identity-text.test.ts +4 -6
- package/src/__tests__/devices-mine.test.ts +12 -11
- package/src/__tests__/devices.test.ts +60 -260
- package/src/__tests__/discord-verification-contact-upgrade.test.ts +10 -13
- package/src/__tests__/edge-auth.test.ts +10 -148
- package/src/__tests__/edge-guardian-auth.test.ts +60 -44
- package/src/__tests__/guardian-binding-channel-reuse.test.ts +16 -18
- package/src/__tests__/guardian-bootstrap-binding.test.ts +7 -8
- package/src/__tests__/guardian-bootstrap-lookups.test.ts +25 -27
- package/src/__tests__/guardian-delivery-resolver.test.ts +8 -12
- package/src/__tests__/guardian-pin.test.ts +3 -1
- package/src/__tests__/handle-inbound-admission.test.ts +3 -12
- package/src/__tests__/handle-inbound-app-context.test.ts +3 -6
- package/src/__tests__/handle-inbound-invite-intercept.test.ts +3 -6
- package/src/__tests__/handle-inbound-trust-verdict.test.ts +3 -12
- package/src/__tests__/helpers/contact-route-table.ts +53 -32
- package/src/__tests__/helpers/env.ts +19 -0
- package/src/__tests__/helpers/gateway-config.ts +32 -0
- package/src/__tests__/helpers/remote-web-pairing-fixtures.ts +1 -7
- package/src/__tests__/helpers/signing-key.ts +27 -0
- package/src/__tests__/inbound-contact-seed.test.ts +7 -8
- package/src/__tests__/invite-redemption-engine-voice.test.ts +2 -3
- package/src/__tests__/invite-route-auth.test.ts +17 -15
- package/src/__tests__/ipc-contact-routes.test.ts +11 -19
- package/src/__tests__/ipc-contact-threshold.test.ts +16 -9
- package/src/__tests__/ipc-invite-routes.test.ts +6 -5
- package/src/__tests__/ipc-server-multi-client.test.ts +8 -1
- package/src/__tests__/ipc-server-watchdog.test.ts +16 -6
- package/src/__tests__/ipc-slack-thread-routes.test.ts +1 -2
- package/src/__tests__/ipc-voice-invite-routes.test.ts +3 -5
- package/src/__tests__/live-voice-websocket.test.ts +103 -95
- package/src/__tests__/load-guards.test.ts +0 -1
- package/src/__tests__/logger-retention.test.ts +11 -9
- package/src/__tests__/lum-2783-recovery-e2e.test.ts +3 -1
- package/src/__tests__/m0006-reconcile-contacts.test.ts +10 -13
- package/src/__tests__/oauth-callback.test.ts +13 -5
- package/src/__tests__/pair-origin-allowlist.test.ts +4 -118
- package/src/__tests__/rate-limit-loopback.test.ts +1 -5
- package/src/__tests__/refresh-device-binding.test.ts +3 -1
- package/src/__tests__/remote-web-pairing-challenge.test.ts +71 -132
- package/src/__tests__/remote-web-pairing-token.test.ts +16 -140
- package/src/__tests__/remote-web-pairing-verification.test.ts +17 -1
- package/src/__tests__/remote-web-public-base-url.test.ts +79 -0
- package/src/__tests__/resolve-assistant.test.ts +0 -1
- package/src/__tests__/runtime-client.test.ts +9 -9
- package/src/__tests__/runtime-health-proxy.test.ts +19 -14
- package/src/__tests__/runtime-proxy-auth.test.ts +129 -63
- package/src/__tests__/runtime-proxy-catchall-methods.test.ts +152 -0
- package/src/__tests__/runtime-proxy-device-stamp.test.ts +31 -24
- package/src/__tests__/runtime-proxy-error-body.test.ts +28 -30
- package/src/__tests__/runtime-proxy.test.ts +66 -59
- package/src/__tests__/runtime-stream-test-utils.ts +14 -3
- package/src/__tests__/seed-admission-policy.test.ts +1 -10
- package/src/__tests__/shared-invite-redeem.test.ts +7 -20
- package/src/__tests__/shared-invite-registration.test.ts +0 -34
- package/src/__tests__/slack-control-plane-proxy.test.ts +29 -17
- package/src/__tests__/slack-display-name.test.ts +3 -6
- package/src/__tests__/slack-normalize.test.ts +0 -1
- package/src/__tests__/slack-reaction-normalize.test.ts +0 -1
- package/src/__tests__/slack-socket-mode-catchup.test.ts +1 -2
- package/src/__tests__/slack-socket-mode-group-dm.test.ts +2 -3
- package/src/__tests__/slack-socket-mode-liveness.test.ts +6 -29
- package/src/__tests__/slack-socket-mode-outbound-root.test.ts +2 -3
- package/src/__tests__/slack-socket-mode-thread-tracking.test.ts +2 -3
- package/src/__tests__/sleep-wake-detector.test.ts +52 -25
- package/src/__tests__/speech-relay-websocket.test.ts +108 -100
- package/src/__tests__/stt-stream-websocket.test.ts +62 -69
- package/src/__tests__/telegram-control-plane-proxy.test.ts +36 -19
- package/src/__tests__/telegram-normalize.test.ts +1 -1
- package/src/__tests__/telegram-webhook-drop-visibility.test.ts +2 -3
- package/src/__tests__/telegram-webhook-handler.test.ts +121 -68
- package/src/__tests__/telegram-webhook-manager.test.ts +70 -90
- package/src/__tests__/test-preload.ts +21 -3
- package/src/__tests__/text-verification-helpers.test.ts +1 -1
- package/src/__tests__/trust-rules-route-auth.test.ts +16 -26
- package/src/__tests__/trust-rules-routes.test.ts +22 -25
- package/src/__tests__/twilio-media-websocket.test.ts +61 -59
- package/src/__tests__/twilio-webhooks.test.ts +5 -6
- package/src/__tests__/unversioned-api-fallthrough.test.ts +86 -0
- package/src/__tests__/upgrade-policy.test.ts +161 -0
- package/src/__tests__/upstream-transport.test.ts +20 -15
- package/src/__tests__/vercel-route-auth.test.ts +22 -36
- package/src/__tests__/watch-stream-websocket.test.ts +84 -91
- package/src/__tests__/whatsapp-download.test.ts +0 -1
- package/src/__tests__/whatsapp-webhook.test.ts +3 -3
- package/src/attachments/ingest.test.ts +0 -1
- package/src/auth/guardian-bootstrap.ts +5 -12
- package/src/auth/guardian-refresh.ts +0 -2
- package/src/auth/token-exchange.ts +23 -57
- package/src/auth/token-service.ts +69 -22
- package/src/auth-rate-limiter.ts +6 -0
- package/src/channels/inbound-event.test.ts +54 -0
- package/src/channels/inbound-event.ts +29 -3
- package/src/channels/ingress-verification.ts +10 -3
- package/src/channels/plugin-inbound.test.ts +4 -3
- package/src/channels/types.ts +0 -2
- package/src/cli/__tests__/contacts.test.ts +83 -60
- package/src/cli/__tests__/pairing.test.ts +230 -48
- package/src/cli/contacts.ts +0 -130
- package/src/cli/index.ts +20 -34
- package/src/cli/pairing.ts +118 -59
- package/src/cli/program.ts +227 -0
- package/src/cloud-features.ts +13 -0
- package/src/cloud-identity.ts +1 -1
- package/src/config-file-cache.ts +6 -0
- package/src/config-file-utils.ts +1 -1
- package/src/config-file-watcher.ts +104 -0
- package/src/config.ts +25 -23
- package/src/credential-cache.ts +6 -0
- package/src/credential-reader.ts +53 -35
- package/src/credential-watcher.ts +219 -22
- package/src/db/__tests__/session-store.test.ts +2 -1
- package/src/db/admission-policy-store.ts +1 -2
- package/src/db/connection.ts +12 -4
- package/src/db/contact-store.ts +82 -0
- package/src/db/data-migrations/m0002-actor-token-tables-to-gateway.ts +2 -7
- package/src/db/schema.ts +15 -0
- package/src/db/seed-admission-policy.ts +1 -1
- package/src/db/seed-trust-rules.ts +1 -4
- package/src/db/session-store.ts +0 -6
- package/src/discord/admission-log-visibility.test.ts +2 -2
- package/src/discord/forward.test.ts +3 -6
- package/src/discord/forward.ts +4 -8
- package/src/discord/lifecycle.ts +104 -0
- package/src/email/normalize.ts +1 -1
- package/src/email/register-callback.test.ts +1 -2
- package/src/email/register-callback.ts +4 -11
- package/src/guardian-contract.ts +30 -0
- package/src/handlers/handle-inbound.ts +2 -2
- package/src/http/browser-auth-cookies.ts +27 -22
- package/src/http/edge-forwarded-header.ts +0 -39
- package/src/http/loopback-guard.ts +0 -47
- package/src/http/middleware/auth.ts +35 -188
- package/src/http/middleware/cors.test.ts +66 -0
- package/src/http/middleware/cors.ts +23 -2
- package/src/http/router.ts +188 -151
- package/src/http/routes/assistant-handle.test.ts +133 -0
- package/src/http/routes/assistant-handle.ts +94 -0
- package/src/http/routes/audio-proxy.ts +49 -39
- package/src/http/routes/auto-approve-thresholds.ts +308 -230
- package/src/http/routes/brain-graph-proxy.ts +61 -52
- package/src/http/routes/channel-admission-policy.ts +219 -154
- package/src/http/routes/channel-ingress.test.ts +24 -19
- package/src/http/routes/channel-ingress.ts +255 -137
- package/src/http/routes/channel-permission-overrides.ts +189 -112
- package/src/http/routes/channel-readiness-proxy.ts +66 -45
- package/src/http/routes/channel-verification-session-proxy.test.ts +33 -82
- package/src/http/routes/channel-verification-session-proxy.ts +100 -455
- package/src/http/routes/cloud-hop.ts +138 -0
- package/src/http/routes/cloud-push-proxy.test.ts +34 -33
- package/src/http/routes/cloud-push-proxy.ts +56 -127
- package/src/http/routes/contacts-control-plane-proxy.ts +0 -12
- package/src/http/routes/contacts-control-plane-route-table.ts +372 -119
- package/src/http/routes/credential-entry-page.ts +12 -0
- package/src/http/routes/credential-requests.ts +10 -4
- package/src/http/routes/desktop-setup-proxy.ts +21 -11
- package/src/http/routes/desktop-stream-websocket.ts +67 -41
- package/src/http/routes/devices-mine.ts +11 -0
- package/src/http/routes/devices.ts +7 -63
- package/src/http/routes/email-webhook.test.ts +4 -20
- package/src/http/routes/guardian-channel-create.test.ts +6 -9
- package/src/http/routes/guardian-pin.ts +1 -1
- package/src/http/routes/guardian-refresh.ts +65 -2
- package/src/http/routes/index.ts +88 -0
- package/src/http/routes/ingress-domains.test.ts +57 -2
- package/src/http/routes/ingress-domains.ts +46 -14
- package/src/http/routes/integrations-status.ts +18 -0
- package/src/http/routes/ipc-runtime-proxy.test.ts +31 -6
- package/src/http/routes/ipc-runtime-proxy.ts +6 -3
- package/src/http/routes/live-voice-websocket.ts +159 -148
- package/src/http/routes/log-export.test.ts +61 -87
- package/src/http/routes/log-export.ts +143 -150
- package/src/http/routes/log-tail.test.ts +49 -32
- package/src/http/routes/log-tail.ts +31 -21
- package/src/http/routes/migration-rollback-proxy.ts +38 -32
- package/src/http/routes/oauth-apps-proxy.ts +109 -62
- package/src/http/routes/oauth-providers-proxy.ts +60 -51
- package/src/http/routes/pair.ts +23 -346
- package/src/http/routes/plugin-webhook-websocket.test.ts +73 -77
- package/src/http/routes/plugin-webhook-websocket.ts +210 -215
- package/src/http/routes/plugin-webhook.test.ts +3 -1
- package/src/http/routes/plugin-webhook.ts +0 -3
- package/src/http/routes/ps.ts +25 -20
- package/src/http/routes/regex-to-openapi-path.ts +39 -0
- package/src/http/routes/remote-web-pairing-challenge.ts +35 -81
- package/src/http/routes/remote-web-pairing-routes.ts +39 -0
- package/src/http/routes/remote-web-pairing-token.ts +6 -11
- package/src/http/routes/remote-web-pairing-verification.ts +7 -7
- package/src/http/routes/runtime-audio-stream.ts +147 -147
- package/src/http/routes/runtime-health-proxy.ts +43 -32
- package/src/http/routes/runtime-proxy.ts +54 -20
- package/src/http/routes/shared-invite-redeem.ts +1 -7
- package/src/http/routes/slack-control-plane-proxy.ts +57 -46
- package/src/http/routes/speech-relay-websocket.ts +310 -270
- package/src/http/routes/stt-stream-websocket.ts +102 -107
- package/src/http/routes/telegram-control-plane-proxy.ts +87 -58
- package/src/http/routes/telegram-webhook.test.ts +3 -19
- package/src/http/routes/telegram-webhook.ts +3 -2
- package/src/http/routes/terminal.test.ts +165 -0
- package/src/http/routes/terminal.ts +123 -0
- package/src/http/routes/trust-rules.suggest.test.ts +14 -22
- package/src/http/routes/trust-rules.ts +432 -246
- package/src/http/routes/tunnel-status.ts +26 -13
- package/src/http/routes/twilio-control-plane-proxy.ts +105 -64
- package/src/http/routes/twilio-media-websocket.ts +157 -147
- package/src/http/routes/twilio-voice-webhook.test.ts +14 -43
- package/src/http/routes/types.ts +92 -10
- package/src/http/routes/upgrade-broadcast-proxy.ts +38 -32
- package/src/http/routes/upgrade-policy.ts +186 -0
- package/src/http/routes/user-profile.test.ts +129 -0
- package/src/http/routes/user-profile.ts +204 -0
- package/src/http/routes/vercel-control-plane-proxy.ts +74 -52
- package/src/http/routes/watch-stream-websocket.ts +99 -138
- package/src/http/routes/webhook-routes.ts +214 -0
- package/src/http/routes/whatsapp-webhook.test.ts +3 -19
- package/src/http/routes/whatsapp-webhook.ts +2 -1
- package/src/http/routes/workspace-commit-proxy.ts +38 -30
- package/src/index.ts +298 -2481
- package/src/ipc/__tests__/admission-policy-handlers.test.ts +4 -18
- package/src/ipc/__tests__/guardian-request-routes.test.ts +7 -3
- package/src/ipc/__tests__/invite-ipc-routes.test.ts +13 -5
- package/src/ipc/__tests__/verification-session-routes.test.ts +5 -3
- package/src/ipc/admission-policy-handlers.ts +2 -2
- package/src/ipc/channel-socket-health-handlers.test.ts +56 -41
- package/src/ipc/channel-socket-health-handlers.ts +41 -31
- package/src/ipc/credential-request-handlers.ts +43 -19
- package/src/ipc/log-tail-handlers.test.ts +8 -35
- package/src/ipc/log-tail-handlers.ts +8 -11
- package/src/ipc/risk-classification-handlers.test.ts +0 -3
- package/src/ipc/risk-classification-handlers.ts +4 -4
- package/src/ipc/routes.ts +37 -0
- package/src/ipc/server.ts +13 -43
- package/src/ipc/trust-rules-handlers.test.ts +1 -2
- package/src/ipc/tunnel-handlers.ts +18 -18
- package/src/ipc/webhook-route-handlers.test.ts +5 -27
- package/src/ipc/webhook-route-handlers.ts +35 -39
- package/src/logger.ts +6 -26
- package/src/paths.ts +4 -4
- package/src/remote-web/pairing-challenge-store.ts +6 -35
- package/src/remote-web/pairing-mint.ts +2 -6
- package/src/remote-web/public-base-url.ts +65 -0
- package/src/risk/admission-policy-cache.ts +5 -12
- package/src/risk/bash-risk-classifier.test.ts +5 -6
- package/src/risk/bash-risk-classifier.ts +0 -3
- package/src/risk/command-registry/commands/gateway.ts +2 -1
- package/src/risk/file-risk-classifier.test.ts +1 -8
- package/src/risk/project-boundary.test.ts +3 -1
- package/src/risk/shell-identity.ts +1 -4
- package/src/risk/shell-parser.ts +1 -5
- package/src/risk/skill-risk-classifier.ts +1 -2
- package/src/runtime/client.ts +33 -27
- package/src/schema.ts +725 -163
- package/src/slack/errors.ts +1 -2
- package/src/slack/lifecycle.ts +327 -0
- package/src/slack/message-schemas.ts +1 -1
- package/src/slack/slack-web.ts +0 -1
- package/src/slack/socket-mode.ts +1 -1
- package/src/sleep-wake-detector.ts +62 -33
- package/src/telegram/normalize.test.ts +1 -1
- package/src/telegram/normalize.ts +1 -1
- package/src/telegram/send.test.ts +3 -19
- package/src/telegram/webhook-manager.ts +16 -31
- package/src/tunnel/allowed-paths.test.ts +27 -65
- package/src/tunnel/allowed-paths.ts +2 -27
- package/src/tunnel/binary-websocket.ts +1 -2
- package/src/tunnel/bridge-utils.ts +3 -8
- package/src/tunnel/client.test.ts +80 -67
- package/src/tunnel/client.ts +36 -28
- package/src/tunnel/http-bridge.test.ts +13 -40
- package/src/tunnel/websocket-bridge.test.ts +11 -2
- package/src/tunnel/websocket-bridge.ts +3 -1
- package/src/twilio/webhook-sync-trigger.ts +4 -4
- package/src/twilio/webhook-sync.test.ts +1 -33
- package/src/twilio/webhook-sync.ts +0 -4
- package/src/verification/code-parsing.ts +0 -3
- package/src/verification/rate-limit-helpers.ts +6 -2
- package/src/verification/session-service.ts +1 -1
- package/src/verification/shared-invite-registration.ts +3 -13
- package/src/verification/text-verification.ts +1 -1
- package/src/whatsapp/normalize.ts +1 -1
- package/node_modules/@mycadet/environments/src/__tests__/cloud-assistant-hub-url.test.ts +0 -38
- package/node_modules/@mycadet/environments/src/seeds.ts +0 -99
- package/node_modules/@mycadet/environments/src/types.ts +0 -70
- package/openapi.json +0 -2325
- package/src/__tests__/feature-flag-defaults-sync.test.ts +0 -44
- package/src/__tests__/feature-flag-resolver.test.ts +0 -151
- package/src/__tests__/feature-flag-watcher-callback.test.ts +0 -63
- package/src/__tests__/feature-flags-route.test.ts +0 -764
- package/src/__tests__/guardian-init-lockfile.test.ts +0 -883
- package/src/__tests__/ipc-feature-flag-routes.test.ts +0 -240
- package/src/__tests__/pair-device-bound.test.ts +0 -296
- package/src/__tests__/remote-web-ingress-denylist.test.ts +0 -113
- package/src/__tests__/remote-web-pairing-requests.test.ts +0 -277
- package/src/__tests__/route-schema-guard.test.ts +0 -489
- package/src/cloud-user-id.ts +0 -12
- package/src/feature-flag-defaults.ts +0 -197
- package/src/feature-flag-env-overrides.test.ts +0 -166
- package/src/feature-flag-env-overrides.ts +0 -58
- package/src/feature-flag-registry.json +0 -506
- package/src/feature-flag-resolver.ts +0 -47
- package/src/feature-flag-store.ts +0 -115
- package/src/feature-flag-watcher.ts +0 -105
- package/src/http/routes/a2a-routes.test.ts +0 -146
- package/src/http/routes/a2a-routes.ts +0 -126
- package/src/http/routes/auto-approve-thresholds-routes.ts +0 -92
- package/src/http/routes/channel-admission-policy-routes.ts +0 -67
- package/src/http/routes/channel-ingress-routes.ts +0 -135
- package/src/http/routes/channel-permission-overrides-routes.ts +0 -92
- package/src/http/routes/contacts-control-plane-routes.ts +0 -278
- package/src/http/routes/feature-flags.ts +0 -185
- package/src/http/routes/remote-web-pairing-requests.ts +0 -123
- package/src/http/routes/trust-rules-routes.ts +0 -188
- package/src/ipc/feature-flag-handlers.ts +0 -63
- package/src/types.ts +0 -11
package/src/index.ts
CHANGED
|
@@ -1,207 +1,93 @@
|
|
|
1
|
-
process.title = "cadet-gateway";
|
|
2
|
-
|
|
3
|
-
import { eventRefersToAnotherMessage } from "./channels/inbound-event.js";
|
|
4
|
-
import { buildSlackSourceMetadata } from "./slack/source-metadata.js";
|
|
5
1
|
import { randomBytes } from "node:crypto";
|
|
6
|
-
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
} from "
|
|
12
|
-
|
|
13
|
-
import { AuthRateLimiter } from "./auth-rate-limiter.js";
|
|
14
|
-
import {
|
|
15
|
-
loadOrCreateSigningKey,
|
|
16
|
-
initSigningKey,
|
|
17
|
-
} from "./auth/token-service.js";
|
|
18
|
-
import { validateEdgeToken, mintServiceToken } from "./auth/token-exchange.js";
|
|
19
|
-
import { findGuardianForChannelActor } from "./auth/guardian-bootstrap.js";
|
|
20
|
-
import { ConfigFileCache } from "./config-file-cache.js";
|
|
21
|
-
import { ConfigFileWatcher } from "./config-file-watcher.js";
|
|
22
|
-
import { FeatureFlagWatcher } from "./feature-flag-watcher.js";
|
|
23
|
-
|
|
2
|
+
import { TWILIO_MEDIA_STREAM_WEBHOOK_PATH } from "@mycadet/service-contracts/twilio-ingress";
|
|
3
|
+
import { getAuthRateLimiter } from "./auth-rate-limiter.js";
|
|
4
|
+
import { initSigningKey } from "./auth/token-service.js";
|
|
5
|
+
import { forwardedIdentityHeaders } from "@mycadet/assistant-client";
|
|
6
|
+
import { getConfigFileCache } from "./config-file-cache.js";
|
|
7
|
+
import { startConfigFileWatcher } from "./config-file-watcher.js";
|
|
24
8
|
import { loadConfig } from "./config.js";
|
|
25
|
-
import {
|
|
9
|
+
import { CircuitBreakerOpenError } from "./runtime/client.js";
|
|
10
|
+
import { getCredentials } from "./credential-cache.js";
|
|
26
11
|
import { credentialKey } from "./credential-key.js";
|
|
12
|
+
import { startCredentialWatcher } from "./credential-watcher.js";
|
|
27
13
|
import {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
import { handleGuardianRefresh } from "./http/routes/guardian-refresh.js";
|
|
34
|
-
|
|
35
|
-
import { createTelegramWebhookHandler } from "./http/routes/telegram-webhook.js";
|
|
36
|
-
import { createAudioProxyHandler } from "./http/routes/audio-proxy.js";
|
|
37
|
-
import { createTwilioVoiceWebhookHandler } from "./http/routes/twilio-voice-webhook.js";
|
|
38
|
-
import { createTwilioStatusWebhookHandler } from "./http/routes/twilio-status-webhook.js";
|
|
39
|
-
import { createTwilioVoiceVerifyCallbackHandler } from "./http/routes/twilio-voice-verify-callback.js";
|
|
40
|
-
import {
|
|
41
|
-
createTwilioMediaWebsocketHandler,
|
|
42
|
-
getMediaStreamWebsocketHandlers,
|
|
43
|
-
type MediaStreamSocketData,
|
|
14
|
+
closeTwilioMediaStream,
|
|
15
|
+
handleTwilioMediaWs,
|
|
16
|
+
isMediaStreamSocketData,
|
|
17
|
+
messageTwilioMediaStream,
|
|
18
|
+
openTwilioMediaWebsocket,
|
|
44
19
|
} from "./http/routes/twilio-media-websocket.js";
|
|
45
20
|
import {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
21
|
+
closeSttStreamWebsocket,
|
|
22
|
+
handleSttStreamWs,
|
|
23
|
+
isSttStreamSocketData,
|
|
24
|
+
messageSttStreamWebsocket,
|
|
25
|
+
openSttStreamWebsocket,
|
|
49
26
|
} from "./http/routes/stt-stream-websocket.js";
|
|
50
27
|
import {
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
28
|
+
closeWatchStreamWebsocket,
|
|
29
|
+
handleWatchStreamWs,
|
|
30
|
+
isWatchStreamSocketData,
|
|
31
|
+
messageWatchStreamWebsocket,
|
|
32
|
+
openWatchStreamWebsocket,
|
|
54
33
|
} from "./http/routes/watch-stream-websocket.js";
|
|
55
34
|
import {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
35
|
+
closeDesktopStreamWebsocket,
|
|
36
|
+
handleDesktopStreamWs,
|
|
37
|
+
isDesktopStreamSocketData,
|
|
38
|
+
messageDesktopStreamWebsocket,
|
|
39
|
+
openDesktopStreamWebsocket,
|
|
59
40
|
} from "./http/routes/desktop-stream-websocket.js";
|
|
60
41
|
import {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
42
|
+
closeSpeechRelayWebsocket,
|
|
43
|
+
handleSpeechRelaySttWs,
|
|
44
|
+
handleSpeechRelaySttV2Ws,
|
|
45
|
+
handleSpeechRelayTtsWs,
|
|
46
|
+
isSpeechRelaySocketData,
|
|
47
|
+
messageSpeechRelayWebsocket,
|
|
48
|
+
openSpeechRelayWebsocket,
|
|
64
49
|
} from "./http/routes/speech-relay-websocket.js";
|
|
65
50
|
import {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
51
|
+
closeLiveVoiceWebsocket,
|
|
52
|
+
handleLiveVoiceWs,
|
|
53
|
+
isLiveVoiceSocketData,
|
|
54
|
+
messageLiveVoiceWebsocket,
|
|
55
|
+
openLiveVoiceWebsocket,
|
|
69
56
|
} from "./http/routes/live-voice-websocket.js";
|
|
70
|
-
import { createWhatsAppWebhookHandler } from "./http/routes/whatsapp-webhook.js";
|
|
71
|
-
|
|
72
|
-
import { createEmailWebhookHandler } from "./http/routes/email-webhook.js";
|
|
73
|
-
import { createGuardianChannelHandler } from "./http/routes/guardian-channel-create.js";
|
|
74
|
-
import { createInboundRegisterHandler } from "./http/routes/inbound-register.js";
|
|
75
|
-
import { createMailgunWebhookHandler } from "./http/routes/mailgun-webhook.js";
|
|
76
|
-
import { createResendWebhookHandler } from "./http/routes/resend-webhook.js";
|
|
77
|
-
|
|
78
|
-
import { createOAuthCallbackHandler } from "./http/routes/oauth-callback.js";
|
|
79
|
-
import { createMcpOAuthClientMetadataHandler } from "./http/routes/mcp-oauth-client-metadata.js";
|
|
80
|
-
import {
|
|
81
|
-
createFeatureFlagsGetHandler,
|
|
82
|
-
createFeatureFlagsPatchHandler,
|
|
83
|
-
} from "./http/routes/feature-flags.js";
|
|
84
|
-
import {
|
|
85
|
-
createGlobalThresholdGetHandler,
|
|
86
|
-
createGlobalThresholdPutHandler,
|
|
87
|
-
createConversationThresholdGetHandler,
|
|
88
|
-
createConversationThresholdPutHandler,
|
|
89
|
-
createConversationThresholdDeleteHandler,
|
|
90
|
-
} from "./http/routes/auto-approve-thresholds.js";
|
|
91
|
-
import { createChannelVerificationSessionProxyHandler } from "./http/routes/channel-verification-session-proxy.js";
|
|
92
|
-
import { createTelegramControlPlaneProxyHandler } from "./http/routes/telegram-control-plane-proxy.js";
|
|
93
|
-
import { createTwilioControlPlaneProxyHandler } from "./http/routes/twilio-control-plane-proxy.js";
|
|
94
|
-
import { createVercelControlPlaneProxyHandler } from "./http/routes/vercel-control-plane-proxy.js";
|
|
95
|
-
import { createContactsControlPlaneProxyHandler } from "./http/routes/contacts-control-plane-proxy.js";
|
|
96
|
-
import { buildContactsControlPlaneRoutes } from "./http/routes/contacts-control-plane-route-table.js";
|
|
97
|
-
import {
|
|
98
|
-
handleContactPromptSubmit,
|
|
99
|
-
handleContactRecordSubmit,
|
|
100
|
-
} from "./http/routes/contact-prompt.js";
|
|
101
|
-
import {
|
|
102
|
-
handleListDevices,
|
|
103
|
-
handleRevokeDevice,
|
|
104
|
-
} from "./http/routes/devices.js";
|
|
105
|
-
import { handleGetMyDevice } from "./http/routes/devices-mine.js";
|
|
106
|
-
import { handleSaveIngressDomain } from "./http/routes/ingress-domains.js";
|
|
107
|
-
import { handlePair } from "./http/routes/pair.js";
|
|
108
|
-
import { handleCredentialEntryPage } from "./http/routes/credential-entry-page.js";
|
|
109
|
-
import {
|
|
110
|
-
handleCredentialRequestPeek,
|
|
111
|
-
handleCredentialRequestSubmit,
|
|
112
|
-
} from "./http/routes/credential-requests.js";
|
|
113
|
-
import { handleCreateRemoteWebPairingChallenge } from "./http/routes/remote-web-pairing-challenge.js";
|
|
114
|
-
import {
|
|
115
|
-
handleApproveRemoteWebPairingRequest,
|
|
116
|
-
handleDenyRemoteWebPairingRequest,
|
|
117
|
-
handleListRemoteWebPairingRequests,
|
|
118
|
-
} from "./http/routes/remote-web-pairing-requests.js";
|
|
119
|
-
import { handleRemoteWebPairingToken } from "./http/routes/remote-web-pairing-token.js";
|
|
120
|
-
import { handleVerifyRemoteWebPairingChallenge } from "./http/routes/remote-web-pairing-verification.js";
|
|
121
|
-
import { handleSharedInviteRedeem } from "./http/routes/shared-invite-redeem.js";
|
|
122
|
-
import { createSlackControlPlaneProxyHandler } from "./http/routes/slack-control-plane-proxy.js";
|
|
123
|
-
import { createOAuthAppsProxyHandler } from "./http/routes/oauth-apps-proxy.js";
|
|
124
|
-
import { createOAuthProvidersProxyHandler } from "./http/routes/oauth-providers-proxy.js";
|
|
125
|
-
import { createChannelReadinessProxyHandler } from "./http/routes/channel-readiness-proxy.js";
|
|
126
|
-
import { createCloudPushProxyHandler } from "./http/routes/cloud-push-proxy.js";
|
|
127
|
-
import { createPsHandler } from "./http/routes/ps.js";
|
|
128
|
-
import { createTunnelStatusHandler } from "./http/routes/tunnel-status.js";
|
|
129
|
-
import { createRuntimeHealthProxyHandler } from "./http/routes/runtime-health-proxy.js";
|
|
130
|
-
import { createUpgradeBroadcastProxyHandler } from "./http/routes/upgrade-broadcast-proxy.js";
|
|
131
|
-
import { createMigrationRollbackProxyHandler } from "./http/routes/migration-rollback-proxy.js";
|
|
132
|
-
import { createWorkspaceCommitProxyHandler } from "./http/routes/workspace-commit-proxy.js";
|
|
133
|
-
import { createDesktopSetupProxyHandler } from "./http/routes/desktop-setup-proxy.js";
|
|
134
|
-
import { createBrainGraphProxyHandler } from "./http/routes/brain-graph-proxy.js";
|
|
135
|
-
import { createLogExportHandler } from "./http/routes/log-export.js";
|
|
136
|
-
import { createLogTailHandler } from "./http/routes/log-tail.js";
|
|
137
|
-
import {
|
|
138
|
-
createAgentCardHandler,
|
|
139
|
-
A2A_AGENT_CARD_PATH,
|
|
140
|
-
} from "./http/routes/a2a-routes.js";
|
|
141
|
-
import {
|
|
142
|
-
createTrustRulesListHandler,
|
|
143
|
-
createTrustRulesCreateHandler,
|
|
144
|
-
createTrustRulesUpdateHandler,
|
|
145
|
-
createTrustRulesDeleteHandler,
|
|
146
|
-
createTrustRulesResetHandler,
|
|
147
|
-
createTrustRulesSuggestHandler,
|
|
148
|
-
} from "./http/routes/trust-rules.js";
|
|
149
57
|
import { initTrustRuleCache } from "./risk/trust-rule-cache.js";
|
|
150
58
|
import { initAdmissionPolicyCache } from "./risk/admission-policy-cache.js";
|
|
151
59
|
import {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
createChannelAdmissionPolicyDeleteHandler,
|
|
155
|
-
} from "./http/routes/channel-admission-policy.js";
|
|
156
|
-
import {
|
|
157
|
-
createChannelIngressApproveHandler,
|
|
158
|
-
createChannelIngressListHandler,
|
|
159
|
-
createChannelIngressRevokeHandler,
|
|
160
|
-
} from "./http/routes/channel-ingress.js";
|
|
161
|
-
import { createPluginWebhookHandler } from "./http/routes/plugin-webhook.js";
|
|
162
|
-
import {
|
|
163
|
-
createPluginWebhookWebsocketHandler,
|
|
164
|
-
getPluginWebhookWebsocketHandlers,
|
|
60
|
+
closePluginWebhookWebsocket,
|
|
61
|
+
handlePluginWebhookWs,
|
|
165
62
|
isPluginWebhookSocketData,
|
|
63
|
+
messagePluginWebhookWebsocket,
|
|
64
|
+
openPluginWebhookWebsocket,
|
|
166
65
|
} from "./http/routes/plugin-webhook-websocket.js";
|
|
167
|
-
import { resolveCachedPluginIngress } from "./channels/plugin-ingress-approvals.js";
|
|
168
66
|
import {
|
|
169
67
|
reconcilePluginWebhookRoutes,
|
|
170
68
|
watchPluginIngressForWebhookRoutes,
|
|
171
69
|
} from "./channels/plugin-webhook-route-sync.js";
|
|
172
70
|
import { PLUGIN_WEBHOOK_PATH_PATTERN } from "./channels/plugin-ingress.js";
|
|
173
71
|
import {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
72
|
+
getLogger,
|
|
73
|
+
initLogger,
|
|
74
|
+
LOG_RETENTION_SWEEP_INTERVAL_MS,
|
|
75
|
+
pruneOldLogFiles,
|
|
76
|
+
type LogFileConfig,
|
|
77
|
+
} from "./logger.js";
|
|
180
78
|
import {
|
|
181
79
|
bindCloudIdentityCredentialCache,
|
|
182
80
|
ensureCloudIdentityIds,
|
|
183
|
-
resolveCloudAssistantIdOrUndefined,
|
|
184
81
|
} from "./cloud-identity.js";
|
|
185
|
-
import { getCloudBaseUrl } from "./cloud-url.js";
|
|
186
|
-
import { CircuitBreakerOpenError, uploadAttachment } from "./runtime/client.js";
|
|
187
|
-
import {
|
|
188
|
-
appendFailedAttachmentNotice,
|
|
189
|
-
ingestAttachments,
|
|
190
|
-
} from "./attachments/ingest.js";
|
|
191
|
-
import { createConversationTaskQueue } from "./channels/conversation-queue.js";
|
|
192
82
|
import { buildSchema } from "./schema.js";
|
|
193
|
-
import {
|
|
194
|
-
|
|
195
|
-
type SlackSocketModeClient,
|
|
196
|
-
} from "./slack/socket-mode.js";
|
|
197
|
-
import { downloadSlackFile } from "./slack/download.js";
|
|
198
|
-
import { slackBotContactNote } from "./slack/actor.js";
|
|
199
|
-
import { DiscordGatewayClient } from "./discord/gateway-socket.js";
|
|
200
|
-
import { createDiscordInboundEventHandler } from "./discord/forward.js";
|
|
201
|
-
import { handleInbound } from "./handlers/handle-inbound.js";
|
|
202
|
-
import { upsertContactChannel } from "./verification/contact-helpers.js";
|
|
83
|
+
import { startDiscordGateway } from "./discord/lifecycle.js";
|
|
84
|
+
import { startSlackGateway } from "./slack/lifecycle.js";
|
|
203
85
|
import { checkAuthRateLimit } from "./http/middleware/rate-limit.js";
|
|
204
|
-
import {
|
|
86
|
+
import {
|
|
87
|
+
extractBearerToken,
|
|
88
|
+
isHttpAuthDisabled,
|
|
89
|
+
logAuthBypassState,
|
|
90
|
+
} from "./http/middleware/auth.js";
|
|
205
91
|
import {
|
|
206
92
|
resolveExtensionOrigin,
|
|
207
93
|
handleExtensionPreflight,
|
|
@@ -210,60 +96,25 @@ import {
|
|
|
210
96
|
handlePreflight,
|
|
211
97
|
withCorsHeaders,
|
|
212
98
|
} from "./http/middleware/cors.js";
|
|
213
|
-
import {
|
|
214
|
-
import {
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
type GetClientIp,
|
|
218
|
-
} from "./http/router.js";
|
|
219
|
-
import { SleepWakeDetector } from "./sleep-wake-detector.js";
|
|
220
|
-
import { callTelegramApi } from "./telegram/api.js";
|
|
221
|
-
import { fetchImpl } from "./fetch.js";
|
|
222
|
-
import {
|
|
223
|
-
areCloudFeaturesEnabled,
|
|
224
|
-
isFeatureFlagEnabled,
|
|
225
|
-
} from "./feature-flag-resolver.js";
|
|
226
|
-
import { isNewCommand, handleNewCommand } from "./webhook-pipeline.js";
|
|
227
|
-
import { reconcileTelegramWebhook } from "./telegram/webhook-manager.js";
|
|
228
|
-
import { registerEmailCallbackRoute } from "./email/register-callback.js";
|
|
99
|
+
import { validateEdgeToken } from "./auth/token-exchange.js";
|
|
100
|
+
import { createRouter, type GetClientIp } from "./http/router.js";
|
|
101
|
+
import { ROUTES, webhookDedupCaches } from "./http/routes/index.js";
|
|
102
|
+
import { startSleepWakeDetector } from "./sleep-wake-detector.js";
|
|
229
103
|
import { hasTwilioSetupStarted } from "./twilio/setup-state.js";
|
|
230
|
-
import {
|
|
231
|
-
import {
|
|
232
|
-
isOnlyTunnelPublicBaseUrlChange,
|
|
233
|
-
shouldSyncTwilioPhoneWebhooksAfterConfigChange,
|
|
234
|
-
} from "./twilio/webhook-sync-trigger.js";
|
|
235
|
-
import { GatewayIpcServer } from "./ipc/server.js";
|
|
236
|
-
import { contactRoutes } from "./ipc/contact-handlers.js";
|
|
237
|
-
import { inviteRoutes } from "./ipc/invite-handlers.js";
|
|
238
|
-
import { verificationSessionRoutes } from "./ipc/verification-session-handlers.js";
|
|
239
|
-
import { guardianRequestRoutes } from "./ipc/guardian-request-handlers.js";
|
|
240
|
-
import { featureFlagRoutes } from "./ipc/feature-flag-handlers.js";
|
|
241
|
-
import { admissionPolicyRoutes } from "./ipc/admission-policy-handlers.js";
|
|
242
|
-
import { channelPermissionRoutes } from "./ipc/channel-permission-handlers.js";
|
|
243
|
-
import { trustVerdictRoutes } from "./ipc/trust-verdict-handlers.js";
|
|
244
|
-
import { guardianDeliveryRoutes } from "./ipc/guardian-delivery-handlers.js";
|
|
245
|
-
import { createLogTailRoutes } from "./ipc/log-tail-handlers.js";
|
|
246
|
-
import { createChannelSocketHealthRoutes } from "./ipc/channel-socket-health-handlers.js";
|
|
247
|
-
import { createCredentialRequestIpcRoutes } from "./ipc/credential-request-handlers.js";
|
|
248
|
-
import { slackThreadRoutes } from "./ipc/slack-thread-handlers.js";
|
|
249
|
-
import { thresholdRoutes } from "./ipc/threshold-handlers.js";
|
|
250
|
-
import { trustRulesRoutes } from "./ipc/trust-rules-handlers.js";
|
|
251
|
-
|
|
252
|
-
import { riskClassificationRoutes } from "./ipc/risk-classification-handlers.js";
|
|
253
|
-
import { createTunnelRoutes } from "./ipc/tunnel-handlers.js";
|
|
254
|
-
import { createWebhookRouteRoutes } from "./ipc/webhook-route-handlers.js";
|
|
104
|
+
import { startIpcServer } from "./ipc/server.js";
|
|
255
105
|
import { refreshRouteSchema } from "./ipc/route-schema-cache.js";
|
|
256
106
|
import { initGatewayDb } from "./db/connection.js";
|
|
257
|
-
import { cleanupExpiredInboundEvents } from "./db/inbound-dedup-store.js";
|
|
258
107
|
import { onWebhookIngressRoutesChanged } from "./db/webhook-ingress-route-store.js";
|
|
259
108
|
import { runPostAssistantReady } from "./post-assistant-ready.js";
|
|
109
|
+
import { getTunnelClient } from "./tunnel/client.js";
|
|
260
110
|
import {
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
} from "./
|
|
265
|
-
import { VERSION_HEADER_NAME, VERSION_HEADER_VALUE } from "./version.js";
|
|
111
|
+
APP_VERSION,
|
|
112
|
+
VERSION_HEADER_NAME,
|
|
113
|
+
VERSION_HEADER_VALUE,
|
|
114
|
+
} from "./version.js";
|
|
266
115
|
import { isWebsocketUpgradeRequest } from "./http/utils.js";
|
|
116
|
+
import { startInboundEventExpirationCleanup } from "./channels/inbound-event.js";
|
|
117
|
+
process.title = "cadet-gateway";
|
|
267
118
|
|
|
268
119
|
const log = getLogger("main");
|
|
269
120
|
|
|
@@ -280,84 +131,8 @@ let postAssistantReadyComplete = false;
|
|
|
280
131
|
* trigger side effects (e.g. Telegram webhook reconciliation,
|
|
281
132
|
* Slack socket restart).
|
|
282
133
|
*/
|
|
283
|
-
const SERVICE_DISPLAY_NAMES: Record<string, string> = {
|
|
284
|
-
telegram: "Telegram",
|
|
285
|
-
twilio: "Twilio",
|
|
286
|
-
whatsapp: "WhatsApp",
|
|
287
|
-
slack_channel: "Slack channel",
|
|
288
|
-
discord_channel: "Discord channel",
|
|
289
|
-
};
|
|
290
|
-
|
|
291
|
-
function detectCredentialChanges(
|
|
292
|
-
event: CredentialChangeEvent,
|
|
293
|
-
logTarget: { info: (msg: string) => void },
|
|
294
|
-
): Set<string> {
|
|
295
|
-
const changed = new Set<string>();
|
|
296
|
-
for (const service of event.changedServices) {
|
|
297
|
-
const displayName = SERVICE_DISPLAY_NAMES[service] ?? service;
|
|
298
|
-
const creds = event.credentials.get(service);
|
|
299
|
-
logTarget.info(
|
|
300
|
-
creds
|
|
301
|
-
? `${displayName} credentials loaded from credential vault`
|
|
302
|
-
: `${displayName} credentials cleared`,
|
|
303
|
-
);
|
|
304
|
-
changed.add(service);
|
|
305
|
-
}
|
|
306
|
-
return changed;
|
|
307
|
-
}
|
|
308
|
-
|
|
309
134
|
// Shared rate limiter for auth failures and unauthenticated endpoints
|
|
310
|
-
const authRateLimiter =
|
|
311
|
-
|
|
312
|
-
function isMediaStreamSocketData(data: unknown): data is MediaStreamSocketData {
|
|
313
|
-
return (
|
|
314
|
-
!!data &&
|
|
315
|
-
typeof data === "object" &&
|
|
316
|
-
(data as { wsType?: unknown }).wsType === "twilio-media-stream"
|
|
317
|
-
);
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
function isSttStreamSocketData(data: unknown): data is SttStreamSocketData {
|
|
321
|
-
return (
|
|
322
|
-
!!data &&
|
|
323
|
-
typeof data === "object" &&
|
|
324
|
-
(data as { wsType?: unknown }).wsType === "stt-stream"
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function isWatchStreamSocketData(data: unknown): data is WatchStreamSocketData {
|
|
329
|
-
return (
|
|
330
|
-
!!data &&
|
|
331
|
-
typeof data === "object" &&
|
|
332
|
-
(data as { wsType?: unknown }).wsType === "watch-stream"
|
|
333
|
-
);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
function isDesktopStreamSocketData(
|
|
337
|
-
data: unknown,
|
|
338
|
-
): data is DesktopStreamSocketData {
|
|
339
|
-
return (
|
|
340
|
-
!!data &&
|
|
341
|
-
typeof data === "object" &&
|
|
342
|
-
(data as { wsType?: unknown }).wsType === "desktop-stream"
|
|
343
|
-
);
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
function isLiveVoiceSocketData(data: unknown): data is LiveVoiceSocketData {
|
|
347
|
-
return (
|
|
348
|
-
!!data &&
|
|
349
|
-
typeof data === "object" &&
|
|
350
|
-
(data as { wsType?: unknown }).wsType === "live-voice"
|
|
351
|
-
);
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
function isSpeechRelaySocketData(data: unknown): data is SpeechRelaySocketData {
|
|
355
|
-
return (
|
|
356
|
-
!!data &&
|
|
357
|
-
typeof data === "object" &&
|
|
358
|
-
(data as { wsType?: unknown }).wsType === "speech-relay"
|
|
359
|
-
);
|
|
360
|
-
}
|
|
135
|
+
const authRateLimiter = getAuthRateLimiter();
|
|
361
136
|
|
|
362
137
|
/** Log-safe socket-type discriminant for unknown-socket diagnostics. */
|
|
363
138
|
function extractWsType(data: unknown): unknown {
|
|
@@ -394,24 +169,42 @@ function getClientIp(
|
|
|
394
169
|
}
|
|
395
170
|
|
|
396
171
|
/**
|
|
397
|
-
*
|
|
398
|
-
*
|
|
399
|
-
*
|
|
400
|
-
*
|
|
401
|
-
*
|
|
172
|
+
* Background log-retention sweep (field feedback item 8): the prune used to
|
|
173
|
+
* run inside initLogger — and on every UTC rollover inside getLogger() —
|
|
174
|
+
* both on hot paths. The gateway main process owns the interval now; a
|
|
175
|
+
* dedicated monitoring worker is the follow-up wiring (out of scope for
|
|
176
|
+
* now). Unref'd so it never holds the process open.
|
|
402
177
|
*/
|
|
403
|
-
|
|
178
|
+
function startLogRetentionSweep(config: LogFileConfig): void {
|
|
179
|
+
if (!config.dir) return;
|
|
180
|
+
const interval = setInterval(() => {
|
|
181
|
+
try {
|
|
182
|
+
const removed = pruneOldLogFiles(config.dir!, config.retentionDays);
|
|
183
|
+
if (removed > 0) {
|
|
184
|
+
log.info(
|
|
185
|
+
{ removed, retentionDays: config.retentionDays },
|
|
186
|
+
"Pruned old log files",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
} catch (err) {
|
|
190
|
+
log.warn({ err }, "Log retention sweep failed");
|
|
191
|
+
}
|
|
192
|
+
}, LOG_RETENTION_SWEEP_INTERVAL_MS);
|
|
193
|
+
interval.unref();
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
type StopTask = () => Promise<void> | void;
|
|
404
197
|
|
|
405
198
|
async function main() {
|
|
406
199
|
const config = loadConfig();
|
|
407
200
|
initLogger(config.logFile);
|
|
201
|
+
startLogRetentionSweep(config.logFile);
|
|
408
202
|
|
|
409
203
|
log.info("Starting Cadet Gateway...");
|
|
410
204
|
|
|
411
205
|
// Initialize the JWT signing key shared with the daemon.
|
|
412
206
|
// This must happen before any request handling.
|
|
413
|
-
|
|
414
|
-
initSigningKey(signingKey);
|
|
207
|
+
initSigningKey();
|
|
415
208
|
log.info("JWT signing key initialized");
|
|
416
209
|
|
|
417
210
|
await initGatewayDb();
|
|
@@ -430,1460 +223,126 @@ async function main() {
|
|
|
430
223
|
// Instantiate caches for credential and config file reads.
|
|
431
224
|
// Handlers read dynamic credentials and config.json values from these
|
|
432
225
|
// caches at call time, with automatic TTL refresh.
|
|
433
|
-
const credentialCache =
|
|
226
|
+
const credentialCache = getCredentials();
|
|
434
227
|
bindCloudIdentityCredentialCache(credentialCache);
|
|
435
228
|
void ensureCloudIdentityIds();
|
|
436
|
-
const configFileCache =
|
|
437
|
-
const tunnelClient =
|
|
438
|
-
credentials: credentialCache,
|
|
439
|
-
configFile: configFileCache,
|
|
440
|
-
});
|
|
229
|
+
const configFileCache = getConfigFileCache();
|
|
230
|
+
const tunnelClient = getTunnelClient();
|
|
441
231
|
// Tunnel only sees a webhook route on the next tunnel connect, so a registry
|
|
442
|
-
// write
|
|
443
|
-
//
|
|
444
|
-
// must never touch the tunnel in that state. A flag flip re-advertises via
|
|
445
|
-
// the flag-change handler, which picks up any rows written while off.
|
|
232
|
+
// write changes the advertised rules, so the tunnel re-advertises them on
|
|
233
|
+
// its next connect.
|
|
446
234
|
onWebhookIngressRoutesChanged(() => {
|
|
447
|
-
|
|
448
|
-
tunnelClient?.requestRulesRefresh("webhook-routes-changed");
|
|
449
|
-
}
|
|
235
|
+
tunnelClient.requestRulesRefresh("webhook-routes-changed");
|
|
450
236
|
});
|
|
451
237
|
|
|
452
238
|
// ── Integration readiness flags ──
|
|
453
239
|
// Track whether each integration has valid credentials so route
|
|
454
240
|
// preconditions can gate requests synchronously. Updated by the
|
|
455
241
|
// credential watcher callback whenever credentials change.
|
|
456
|
-
let telegramReady = false;
|
|
457
|
-
let whatsappReady = false;
|
|
458
|
-
let cadetReady = false;
|
|
459
|
-
let tunnelStartRequested = false;
|
|
460
|
-
|
|
461
|
-
function maybeStartTunnelForTwilio(
|
|
462
|
-
reason: string,
|
|
463
|
-
twilioCredentials?: Record<string, string> | null,
|
|
464
|
-
): boolean {
|
|
465
|
-
if (tunnelStartRequested || !tunnelClient) {
|
|
466
|
-
return tunnelStartRequested;
|
|
467
|
-
}
|
|
468
|
-
if (!hasTwilioSetupStarted(configFileCache, twilioCredentials)) {
|
|
469
|
-
return false;
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
tunnelStartRequested = true;
|
|
473
|
-
log.info({ reason }, "Starting Tunnel after Twilio setup detected");
|
|
474
|
-
tunnelClient.start();
|
|
475
|
-
return true;
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
/**
|
|
479
|
-
* Start the Tunnel for web live voice.
|
|
480
|
-
*
|
|
481
|
-
* Tunnel is the browser's ingress for the live-voice WebSocket, but the tunnel
|
|
482
|
-
* was historically only started for Twilio (see
|
|
483
|
-
* {@link maybeStartTunnelForTwilio}). Without this, an assistant with no
|
|
484
|
-
* Twilio setup never registers a Tunnel, so the browser's
|
|
485
|
-
* `/v1/live-voice` upgrade fails with "assistant tunnel is not connected".
|
|
486
|
-
* Live voice is available to every assistant, so this runs unconditionally at
|
|
487
|
-
* startup. Shares the `tunnelStartRequested` latch with the Twilio path — one
|
|
488
|
-
* tunnel serves both — and `tunnelClient.start()` is idempotent.
|
|
489
|
-
*/
|
|
490
|
-
function startTunnelForLiveVoice(reason: string): boolean {
|
|
491
|
-
if (tunnelStartRequested || !tunnelClient) {
|
|
492
|
-
return tunnelStartRequested;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
tunnelStartRequested = true;
|
|
496
|
-
log.info({ reason }, "Starting Tunnel for live voice");
|
|
497
|
-
tunnelClient.start();
|
|
498
|
-
return true;
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
/**
|
|
502
|
-
* Start the Tunnel when a credential link is minted. Unlike the Twilio
|
|
503
|
-
* and live-voice paths this has no precondition: creating a one-time
|
|
504
|
-
* credential link is itself the request to expose public ingress, and the
|
|
505
|
-
* tunnel is the browser's route to the credential-entry page. Shares the
|
|
506
|
-
* `tunnelStartRequested` latch — one tunnel serves every ingress consumer —
|
|
507
|
-
* and `tunnelClient.start()` is idempotent.
|
|
508
|
-
*/
|
|
509
|
-
function maybeStartTunnelForCredentialLink(reason: string): boolean {
|
|
510
|
-
if (tunnelStartRequested || !tunnelClient) {
|
|
511
|
-
return tunnelStartRequested;
|
|
512
|
-
}
|
|
513
|
-
tunnelStartRequested = true;
|
|
514
|
-
log.info({ reason }, "Starting Tunnel after credential link minted");
|
|
515
|
-
tunnelClient.start();
|
|
516
|
-
return true;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* Make public ingress live for a freshly minted credential link: enable it
|
|
521
|
-
* when explicitly disabled (only an explicit `false` — a default `undefined`
|
|
522
|
-
* already means enabled on platform) and start the Tunnel so the link
|
|
523
|
-
* is actually reachable.
|
|
524
|
-
*/
|
|
525
|
-
async function ensurePublicIngressLiveForCredentialLink(): Promise<void> {
|
|
526
|
-
if (
|
|
527
|
-
configFileCache.getBoolean("ingress", "enabled", { force: true }) ===
|
|
528
|
-
false
|
|
529
|
-
) {
|
|
530
|
-
await enablePublicIngress(configFileCache);
|
|
531
|
-
log.info("Auto-enabled public ingress for credential link creation");
|
|
532
|
-
}
|
|
533
|
-
maybeStartTunnelForCredentialLink("credential link minted");
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
async function readTwilioCredentialsForTunnelStartup(): Promise<Record<
|
|
537
|
-
string,
|
|
538
|
-
string
|
|
539
|
-
> | null> {
|
|
540
|
-
try {
|
|
541
|
-
const [accountSid, authToken] = await Promise.all([
|
|
542
|
-
credentialCache.get(credentialKey("twilio", "account_sid")),
|
|
543
|
-
credentialCache.get(credentialKey("twilio", "auth_token")),
|
|
544
|
-
]);
|
|
545
|
-
if (!accountSid?.trim() || !authToken?.trim()) {
|
|
546
|
-
return null;
|
|
547
|
-
}
|
|
548
|
-
return { account_sid: accountSid, auth_token: authToken };
|
|
549
|
-
} catch (err) {
|
|
550
|
-
log.warn(
|
|
551
|
-
{ err },
|
|
552
|
-
"Failed to read Twilio credentials before Tunnel startup gate",
|
|
553
|
-
);
|
|
554
|
-
return null;
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
const twilioValidationCaches = {
|
|
559
|
-
credentials: credentialCache,
|
|
560
|
-
configFile: configFileCache,
|
|
561
|
-
};
|
|
562
|
-
|
|
563
|
-
const { handler: handleTelegramWebhook, dedupCache: telegramDedupCache } =
|
|
564
|
-
createTelegramWebhookHandler(config, {
|
|
565
|
-
credentials: credentialCache,
|
|
566
|
-
configFile: configFileCache,
|
|
567
|
-
});
|
|
568
|
-
const isTelegramConfigured = () => telegramReady;
|
|
569
|
-
const isWhatsAppConfigured = () => whatsappReady;
|
|
570
|
-
|
|
571
|
-
const handleTwilioVoiceWebhook = createTwilioVoiceWebhookHandler(
|
|
572
|
-
config,
|
|
573
|
-
twilioValidationCaches,
|
|
574
|
-
);
|
|
575
|
-
const handleTwilioStatusWebhook = createTwilioStatusWebhookHandler(
|
|
576
|
-
config,
|
|
577
|
-
twilioValidationCaches,
|
|
578
|
-
);
|
|
579
|
-
const handleTwilioVoiceVerifyCallback =
|
|
580
|
-
createTwilioVoiceVerifyCallbackHandler(config, twilioValidationCaches);
|
|
581
|
-
const handleTwilioMediaWs = createTwilioMediaWebsocketHandler(config);
|
|
582
|
-
const handlePluginWebhookWs = createPluginWebhookWebsocketHandler({
|
|
583
|
-
config,
|
|
584
|
-
resolve: resolveCachedPluginIngress,
|
|
585
|
-
credentials: credentialCache,
|
|
586
|
-
});
|
|
587
|
-
const handleSttStreamWs = createSttStreamWebsocketHandler(config);
|
|
588
|
-
const handleWatchStreamWs = createWatchStreamWebsocketHandler(config);
|
|
589
|
-
const handleDesktopStreamWs = createDesktopStreamWebsocketHandler(config);
|
|
590
|
-
const handleLiveVoiceWs = createLiveVoiceWebsocketHandler(config);
|
|
591
|
-
const handleSpeechRelaySttWs = createSpeechRelayUpgradeHandler(
|
|
592
|
-
config,
|
|
593
|
-
"stt",
|
|
594
|
-
{ credentials: credentialCache },
|
|
595
|
-
);
|
|
596
|
-
// Managed STT v2 (Flux). Separate handler rather than a param on v1: the
|
|
597
|
-
// contract version is the endpoint, and v2 accepts query params v1 must
|
|
598
|
-
// keep rejecting.
|
|
599
|
-
const handleSpeechRelaySttV2Ws = createSpeechRelayUpgradeHandler(
|
|
600
|
-
config,
|
|
601
|
-
"stt",
|
|
602
|
-
{ credentials: credentialCache },
|
|
603
|
-
"v2",
|
|
604
|
-
);
|
|
605
|
-
const handleSpeechRelayTtsWs = createSpeechRelayUpgradeHandler(
|
|
606
|
-
config,
|
|
607
|
-
"tts",
|
|
608
|
-
{ credentials: credentialCache },
|
|
609
|
-
);
|
|
610
|
-
const twilioMediaStreamWebsocketHandlers = getMediaStreamWebsocketHandlers();
|
|
611
|
-
const pluginWebhookWebsocketHandlers = getPluginWebhookWebsocketHandlers();
|
|
612
|
-
const sttStreamWebsocketHandlers = getSttStreamWebsocketHandlers();
|
|
613
|
-
const watchStreamWebsocketHandlers = getWatchStreamWebsocketHandlers();
|
|
614
|
-
const desktopStreamWebsocketHandlers = getDesktopStreamWebsocketHandlers();
|
|
615
|
-
const liveVoiceWebsocketHandlers = getLiveVoiceWebsocketHandlers();
|
|
616
|
-
const speechRelayWebsocketHandlers = getSpeechRelayWebsocketHandlers();
|
|
617
|
-
const { handler: handleWhatsAppWebhook, dedupCache: whatsappDedupCache } =
|
|
618
|
-
createWhatsAppWebhookHandler(config, {
|
|
619
|
-
credentials: credentialCache,
|
|
620
|
-
configFile: configFileCache,
|
|
621
|
-
});
|
|
622
|
-
const { handler: handleEmailWebhook, dedupCache: emailDedupCache } =
|
|
623
|
-
createEmailWebhookHandler(config, {
|
|
624
|
-
credentials: credentialCache,
|
|
625
|
-
configFile: configFileCache,
|
|
626
|
-
});
|
|
627
|
-
const { handler: handleResendWebhook } = createResendWebhookHandler(config, {
|
|
628
|
-
credentials: credentialCache,
|
|
629
|
-
configFile: configFileCache,
|
|
630
|
-
});
|
|
631
|
-
const { handler: handleMailgunWebhook } = createMailgunWebhookHandler(
|
|
632
|
-
config,
|
|
633
|
-
{
|
|
634
|
-
credentials: credentialCache,
|
|
635
|
-
configFile: configFileCache,
|
|
636
|
-
},
|
|
637
|
-
);
|
|
638
|
-
const handleInboundRegister = createInboundRegisterHandler(
|
|
639
|
-
config,
|
|
640
|
-
credentialCache,
|
|
641
|
-
);
|
|
642
|
-
const handleGuardianChannelCreate = createGuardianChannelHandler();
|
|
643
|
-
const handleOAuthCallback = createOAuthCallbackHandler(config);
|
|
644
|
-
const handleMcpOAuthClientMetadata =
|
|
645
|
-
createMcpOAuthClientMetadataHandler(configFileCache);
|
|
646
|
-
const channelVerificationSessionProxy =
|
|
647
|
-
createChannelVerificationSessionProxyHandler(config);
|
|
648
|
-
const telegramControlPlaneProxy =
|
|
649
|
-
createTelegramControlPlaneProxyHandler(config);
|
|
650
|
-
const vercelControlPlaneProxy = createVercelControlPlaneProxyHandler(config);
|
|
651
|
-
const contactsControlPlaneProxy =
|
|
652
|
-
createContactsControlPlaneProxyHandler(config);
|
|
653
|
-
const twilioControlPlaneProxy = createTwilioControlPlaneProxyHandler(config);
|
|
654
|
-
const slackControlPlaneProxy = createSlackControlPlaneProxyHandler(config);
|
|
655
|
-
const oauthAppsProxy = createOAuthAppsProxyHandler(config);
|
|
656
|
-
const oauthProvidersProxy = createOAuthProvidersProxyHandler(config);
|
|
657
|
-
const channelReadinessProxy = createChannelReadinessProxyHandler(config);
|
|
658
|
-
const cloudPushProxy = createCloudPushProxyHandler(credentialCache);
|
|
659
|
-
const psHandler = createPsHandler(config);
|
|
660
|
-
const tunnelStatusHandler = createTunnelStatusHandler(tunnelClient);
|
|
661
|
-
const runtimeHealthProxy = createRuntimeHealthProxyHandler(config);
|
|
662
|
-
const upgradeBroadcastProxy = createUpgradeBroadcastProxyHandler(config);
|
|
663
|
-
const migrationRollbackProxy = createMigrationRollbackProxyHandler(config);
|
|
664
|
-
const workspaceCommitProxy = createWorkspaceCommitProxyHandler(config);
|
|
665
|
-
const desktopSetupProxy = createDesktopSetupProxyHandler(config);
|
|
666
|
-
const brainGraphProxy = createBrainGraphProxyHandler(config);
|
|
667
|
-
const handleLogExport = createLogExportHandler(config);
|
|
668
|
-
const handleLogTail = createLogTailHandler(config);
|
|
669
|
-
const handleFeatureFlagsGet = createFeatureFlagsGetHandler();
|
|
670
|
-
// Assigned once `ipcServer` exists (see `emitFlagChanged` below). Passing a
|
|
671
|
-
// thunk lets the PATCH handler push flag changes to connected clients the
|
|
672
|
-
// moment a write commits, rather than waiting on the FeatureFlagWatcher.
|
|
673
|
-
let emitFlagChanged: () => void = () => {};
|
|
674
|
-
const handleFeatureFlagsPatch = createFeatureFlagsPatchHandler(() =>
|
|
675
|
-
emitFlagChanged(),
|
|
676
|
-
);
|
|
677
|
-
const handleGlobalThresholdGet = createGlobalThresholdGetHandler();
|
|
678
|
-
const handleGlobalThresholdPut = createGlobalThresholdPutHandler();
|
|
679
|
-
const handleConversationThresholdGet =
|
|
680
|
-
createConversationThresholdGetHandler();
|
|
681
|
-
const handleConversationThresholdPut =
|
|
682
|
-
createConversationThresholdPutHandler();
|
|
683
|
-
const handleConversationThresholdDelete =
|
|
684
|
-
createConversationThresholdDeleteHandler();
|
|
685
|
-
const handleTrustRulesList = createTrustRulesListHandler();
|
|
686
|
-
const handleTrustRulesCreate = createTrustRulesCreateHandler();
|
|
687
|
-
const handleTrustRulesUpdate = createTrustRulesUpdateHandler();
|
|
688
|
-
const handleTrustRulesDelete = createTrustRulesDeleteHandler();
|
|
689
|
-
const handleTrustRulesReset = createTrustRulesResetHandler();
|
|
690
|
-
const handleTrustRulesSuggest = createTrustRulesSuggestHandler();
|
|
691
|
-
const handleChannelAdmissionPolicyList =
|
|
692
|
-
createChannelAdmissionPolicyListHandler();
|
|
693
|
-
const handleChannelAdmissionPolicySet =
|
|
694
|
-
createChannelAdmissionPolicySetHandler();
|
|
695
|
-
const handleChannelAdmissionPolicyDelete =
|
|
696
|
-
createChannelAdmissionPolicyDeleteHandler();
|
|
697
|
-
const handleChannelIngressList = createChannelIngressListHandler();
|
|
698
|
-
const handleChannelIngressApprove = createChannelIngressApproveHandler();
|
|
699
|
-
const handleChannelIngressRevoke = createChannelIngressRevokeHandler();
|
|
700
|
-
const handlePluginWebhook = createPluginWebhookHandler({
|
|
701
|
-
config,
|
|
702
|
-
resolve: resolveCachedPluginIngress,
|
|
703
|
-
credentials: credentialCache,
|
|
704
|
-
// HMAC payloads can sign the public request URL. Read through the cache
|
|
705
|
-
// so a tunnel registering a public base is picked up without a restart.
|
|
706
|
-
ingressPublicBaseUrl: () =>
|
|
707
|
-
configFileCache.getString("ingress", "publicBaseUrl"),
|
|
708
|
-
});
|
|
709
|
-
const handleChannelPermissionOverridesList =
|
|
710
|
-
createChannelPermissionOverridesListHandler();
|
|
711
|
-
const handleChannelPermissionOverrideSet =
|
|
712
|
-
createChannelPermissionOverrideSetHandler();
|
|
713
|
-
const handleChannelPermissionOverrideDelete =
|
|
714
|
-
createChannelPermissionOverrideDeleteHandler();
|
|
715
|
-
const handleChannelPermissionResolve =
|
|
716
|
-
createChannelPermissionResolveHandler();
|
|
717
|
-
|
|
718
|
-
const handleAgentCard = createAgentCardHandler(configFileCache);
|
|
719
|
-
|
|
720
|
-
const audioProxy = createAudioProxyHandler(config);
|
|
721
|
-
|
|
722
|
-
const handleRuntimeProxy = createRuntimeProxyHandler(config);
|
|
723
|
-
|
|
724
|
-
// Helper to reject when an integration isn't configured
|
|
725
|
-
const requireConfigured = (
|
|
726
|
-
check: () => boolean,
|
|
727
|
-
name: string,
|
|
728
|
-
): (() => Response | null) => {
|
|
729
|
-
return () => {
|
|
730
|
-
if (!check()) {
|
|
731
|
-
log.warn(
|
|
732
|
-
{ integration: name },
|
|
733
|
-
`${name} integration not configured — rejecting request with 503`,
|
|
734
|
-
);
|
|
735
|
-
return Response.json(
|
|
736
|
-
{ error: `${name} integration not configured` },
|
|
737
|
-
{ status: 503 },
|
|
738
|
-
);
|
|
739
|
-
}
|
|
740
|
-
return null;
|
|
741
|
-
};
|
|
742
|
-
};
|
|
743
|
-
|
|
744
|
-
const requireTelegram = requireConfigured(isTelegramConfigured, "Telegram");
|
|
745
|
-
const requireWhatsApp = requireConfigured(isWhatsAppConfigured, "WhatsApp");
|
|
746
|
-
|
|
747
|
-
// ── Route table ──
|
|
748
|
-
// Routes are matched top-to-bottom. The first match wins.
|
|
749
|
-
// Auth middleware is applied declaratively per route — no manual
|
|
750
|
-
// requireEdgeAuth/wrapWithAuthFailureTracking calls needed.
|
|
751
|
-
const routes: RouteDefinition[] = [
|
|
752
|
-
// ── A2A agent card discovery (read-only, unauthenticated per spec) ──
|
|
753
|
-
{
|
|
754
|
-
path: A2A_AGENT_CARD_PATH,
|
|
755
|
-
method: "GET",
|
|
756
|
-
handler: (req) => handleAgentCard(req),
|
|
757
|
-
},
|
|
758
|
-
|
|
759
|
-
// ── Webhooks (unauthenticated, validated by provider-specific mechanisms) ──
|
|
760
|
-
{
|
|
761
|
-
path: "/webhooks/telegram",
|
|
762
|
-
precondition: requireTelegram,
|
|
763
|
-
handler: (req) => handleTelegramWebhook(req),
|
|
764
|
-
},
|
|
765
|
-
{
|
|
766
|
-
path: TWILIO_VOICE_WEBHOOK_PATH,
|
|
767
|
-
handler: (req) => handleTwilioVoiceWebhook(req),
|
|
768
|
-
},
|
|
769
|
-
{
|
|
770
|
-
path: TWILIO_STATUS_WEBHOOK_PATH,
|
|
771
|
-
handler: (req) => handleTwilioStatusWebhook(req),
|
|
772
|
-
},
|
|
773
|
-
{
|
|
774
|
-
path: "/webhooks/twilio/voice-verify",
|
|
775
|
-
handler: (req) => handleTwilioVoiceVerifyCallback(req),
|
|
776
|
-
},
|
|
777
|
-
{
|
|
778
|
-
path: "/webhooks/whatsapp",
|
|
779
|
-
precondition: requireWhatsApp,
|
|
780
|
-
handler: (req) => handleWhatsAppWebhook(req),
|
|
781
|
-
},
|
|
782
|
-
{
|
|
783
|
-
path: "/webhooks/email",
|
|
784
|
-
handler: (req) => handleEmailWebhook(req),
|
|
785
|
-
},
|
|
786
|
-
{
|
|
787
|
-
path: "/webhooks/resend",
|
|
788
|
-
handler: (req) => handleResendWebhook(req),
|
|
789
|
-
},
|
|
790
|
-
{
|
|
791
|
-
path: "/webhooks/mailgun",
|
|
792
|
-
handler: (req) => handleMailgunWebhook(req),
|
|
793
|
-
},
|
|
794
|
-
// Plugin-declared webhooks. Public like their neighbours above; what makes
|
|
795
|
-
// them safe is that only a guardian-approved declaration creates one, every
|
|
796
|
-
// other path here 404s, and each request is signature-checked. Any method —
|
|
797
|
-
// the plugin's route module decides which verbs it answers. WebSocket-kind
|
|
798
|
-
// declarations are upgraded in the pre-router, before this entry is reached.
|
|
799
|
-
{
|
|
800
|
-
path: PLUGIN_WEBHOOK_PATH_PATTERN,
|
|
801
|
-
handler: (req, params) =>
|
|
802
|
-
handlePluginWebhook(req, params[0]!, params[1]!),
|
|
803
|
-
},
|
|
804
|
-
|
|
805
|
-
// ── BYO provider registration (auto-verify guardian email) ──
|
|
806
|
-
{
|
|
807
|
-
path: "/inbound/register",
|
|
808
|
-
method: "POST",
|
|
809
|
-
auth: "edge-scoped",
|
|
810
|
-
scope: "internal.write",
|
|
811
|
-
handler: (req) => handleInboundRegister(req),
|
|
812
|
-
},
|
|
813
|
-
|
|
814
|
-
// ── Guardian channel creation (platform auto-verify) ──
|
|
815
|
-
{
|
|
816
|
-
path: "/v1/contacts/guardian/channel",
|
|
817
|
-
method: "POST",
|
|
818
|
-
auth: "edge-guardian",
|
|
819
|
-
handler: (req) => handleGuardianChannelCreate(req),
|
|
820
|
-
},
|
|
821
|
-
|
|
822
|
-
// ── Audio serving (unauthenticated — Twilio fetches these URLs directly) ──
|
|
823
|
-
{
|
|
824
|
-
path: /^\/v1\/audio\/([^/]+)$/,
|
|
825
|
-
method: "GET",
|
|
826
|
-
handler: (_req, params) => audioProxy.handleGetAudio(_req, params[0]),
|
|
827
|
-
},
|
|
828
|
-
{
|
|
829
|
-
path: "/webhooks/oauth/callback",
|
|
830
|
-
method: "GET",
|
|
831
|
-
auth: "track-failures",
|
|
832
|
-
trackFailureStatuses: [400],
|
|
833
|
-
handler: (req) => handleOAuthCallback(req),
|
|
834
|
-
},
|
|
835
|
-
{
|
|
836
|
-
path: "/oauth/client-metadata.json",
|
|
837
|
-
method: "GET",
|
|
838
|
-
handler: () => handleMcpOAuthClientMetadata(),
|
|
839
|
-
},
|
|
840
|
-
|
|
841
|
-
// ── Runtime health ──
|
|
842
|
-
{
|
|
843
|
-
path: "/v1/health",
|
|
844
|
-
method: "GET",
|
|
845
|
-
auth: "edge",
|
|
846
|
-
handler: (req) => runtimeHealthProxy.handleRuntimeHealth(req),
|
|
847
|
-
},
|
|
848
|
-
{
|
|
849
|
-
path: "/v1/healthz",
|
|
850
|
-
method: "GET",
|
|
851
|
-
auth: "edge",
|
|
852
|
-
handler: (req) => runtimeHealthProxy.handleRuntimeHealth(req),
|
|
853
|
-
},
|
|
854
|
-
|
|
855
|
-
// ── Process status ──
|
|
856
|
-
{
|
|
857
|
-
path: "/v1/ps",
|
|
858
|
-
method: "GET",
|
|
859
|
-
auth: "edge",
|
|
860
|
-
handler: () => psHandler.handlePs(),
|
|
861
|
-
},
|
|
862
|
-
|
|
863
|
-
// ── Ingress domain recording (guardian bearer, loopback fallback) ──
|
|
864
|
-
{
|
|
865
|
-
path: "/v1/ingress/domains",
|
|
866
|
-
method: "POST",
|
|
867
|
-
auth: "edge-guardian",
|
|
868
|
-
handler: (req, _params, getClientIp) =>
|
|
869
|
-
handleSaveIngressDomain(req, getClientIp(), configFileCache),
|
|
870
|
-
},
|
|
871
|
-
|
|
872
|
-
// ── Tunnel status ──
|
|
873
|
-
{
|
|
874
|
-
path: "/v1/tunnel/status",
|
|
875
|
-
method: "GET",
|
|
876
|
-
auth: "edge",
|
|
877
|
-
handler: () => tunnelStatusHandler.handleTunnelStatus(),
|
|
878
|
-
},
|
|
879
|
-
// Assistant-scoped mirror: self-hosted clients emit /v1/assistants/<id>/tunnel/status
|
|
880
|
-
// and rewriteForSelfHostedIngress preserves that path, so a flat-only route
|
|
881
|
-
// would fall through to the runtime proxy and 404. The assistant id is discarded.
|
|
882
|
-
{
|
|
883
|
-
path: /^\/v1\/assistants\/[^/]+\/tunnel\/status\/?$/,
|
|
884
|
-
method: "GET",
|
|
885
|
-
auth: "edge-scoped",
|
|
886
|
-
handler: () => tunnelStatusHandler.handleTunnelStatus(),
|
|
887
|
-
},
|
|
888
|
-
|
|
889
|
-
// ── Brain graph ──
|
|
890
|
-
{
|
|
891
|
-
path: "/v1/brain-graph",
|
|
892
|
-
method: "GET",
|
|
893
|
-
auth: "edge",
|
|
894
|
-
handler: (req) => brainGraphProxy.handleBrainGraph(req),
|
|
895
|
-
},
|
|
896
|
-
{
|
|
897
|
-
path: "/v1/brain-graph-ui",
|
|
898
|
-
method: "GET",
|
|
899
|
-
auth: "edge",
|
|
900
|
-
handler: (req) => brainGraphProxy.handleBrainGraphUI(req),
|
|
901
|
-
},
|
|
902
|
-
// ── Telegram control plane ──
|
|
903
|
-
{
|
|
904
|
-
path: "/v1/integrations/telegram/config",
|
|
905
|
-
method: "GET",
|
|
906
|
-
auth: "edge",
|
|
907
|
-
handler: (req) => telegramControlPlaneProxy.handleGetTelegramConfig(req),
|
|
908
|
-
},
|
|
909
|
-
{
|
|
910
|
-
path: "/v1/integrations/telegram/config",
|
|
911
|
-
method: "POST",
|
|
912
|
-
auth: "edge",
|
|
913
|
-
handler: (req) => telegramControlPlaneProxy.handleSetTelegramConfig(req),
|
|
914
|
-
},
|
|
915
|
-
{
|
|
916
|
-
path: "/v1/integrations/telegram/config",
|
|
917
|
-
method: "DELETE",
|
|
918
|
-
auth: "edge",
|
|
919
|
-
handler: (req) =>
|
|
920
|
-
telegramControlPlaneProxy.handleClearTelegramConfig(req),
|
|
921
|
-
},
|
|
922
|
-
{
|
|
923
|
-
path: "/v1/integrations/telegram/commands",
|
|
924
|
-
method: "POST",
|
|
925
|
-
auth: "edge",
|
|
926
|
-
handler: (req) =>
|
|
927
|
-
telegramControlPlaneProxy.handleSetTelegramCommands(req),
|
|
928
|
-
},
|
|
929
|
-
{
|
|
930
|
-
path: "/v1/integrations/telegram/setup",
|
|
931
|
-
method: "POST",
|
|
932
|
-
auth: "edge",
|
|
933
|
-
handler: (req) => telegramControlPlaneProxy.handleSetupTelegram(req),
|
|
934
|
-
},
|
|
935
|
-
|
|
936
|
-
// ── Vercel control plane ──
|
|
937
|
-
// The dedicated proxy mints a gateway service token, so the daemon
|
|
938
|
-
// never sees the caller's scopes. Edge-scoped auth is the check.
|
|
939
|
-
{
|
|
940
|
-
path: "/v1/integrations/vercel/config",
|
|
941
|
-
method: "GET",
|
|
942
|
-
auth: "edge-scoped",
|
|
943
|
-
scope: "settings.read",
|
|
944
|
-
handler: (req) => vercelControlPlaneProxy.handleGetVercelConfig(req),
|
|
945
|
-
},
|
|
946
|
-
{
|
|
947
|
-
path: "/v1/integrations/vercel/config",
|
|
948
|
-
method: "POST",
|
|
949
|
-
auth: "edge-scoped",
|
|
950
|
-
scope: "settings.write",
|
|
951
|
-
handler: (req) => vercelControlPlaneProxy.handleSetVercelConfig(req),
|
|
952
|
-
},
|
|
953
|
-
{
|
|
954
|
-
path: "/v1/integrations/vercel/config",
|
|
955
|
-
method: "DELETE",
|
|
956
|
-
auth: "edge-scoped",
|
|
957
|
-
scope: "settings.write",
|
|
958
|
-
handler: (req) => vercelControlPlaneProxy.handleDeleteVercelConfig(req),
|
|
959
|
-
},
|
|
960
|
-
|
|
961
|
-
// ── Contacts control plane ──
|
|
962
|
-
// Route table shared with the fall-through regression test; see
|
|
963
|
-
// contacts-control-plane-route-table.ts.
|
|
964
|
-
...buildContactsControlPlaneRoutes({
|
|
965
|
-
contactsControlPlaneProxy,
|
|
966
|
-
handleContactPromptSubmit,
|
|
967
|
-
handleContactRecordSubmit,
|
|
968
|
-
}),
|
|
969
|
-
|
|
970
|
-
// ── Generic loopback pairing (localhost-only, auth: none) ──
|
|
971
|
-
{
|
|
972
|
-
path: "/v1/pair",
|
|
973
|
-
method: "POST",
|
|
974
|
-
auth: "none",
|
|
975
|
-
handler: (req, _params, getClientIp) => handlePair(req, getClientIp()),
|
|
976
|
-
},
|
|
977
|
-
{
|
|
978
|
-
path: "/v1/remote-web/pairing-challenge",
|
|
979
|
-
method: "POST",
|
|
980
|
-
auth: "none",
|
|
981
|
-
handler: (req, _params, getClientIp, getRawPeerIp) =>
|
|
982
|
-
handleCreateRemoteWebPairingChallenge(
|
|
983
|
-
req,
|
|
984
|
-
getClientIp(),
|
|
985
|
-
getRawPeerIp(),
|
|
986
|
-
),
|
|
987
|
-
},
|
|
988
|
-
{
|
|
989
|
-
path: "/v1/remote-web/pairing-verification",
|
|
990
|
-
method: "POST",
|
|
991
|
-
auth: "none",
|
|
992
|
-
handler: (req, _params, getClientIp) =>
|
|
993
|
-
handleVerifyRemoteWebPairingChallenge(req, getClientIp()),
|
|
994
|
-
},
|
|
995
|
-
{
|
|
996
|
-
path: "/v1/remote-web/pairing-token",
|
|
997
|
-
method: "POST",
|
|
998
|
-
auth: "none",
|
|
999
|
-
handler: (req) => handleRemoteWebPairingToken(req),
|
|
1000
|
-
},
|
|
1001
|
-
{
|
|
1002
|
-
path: "/v1/remote-web/pairing-requests",
|
|
1003
|
-
method: "GET",
|
|
1004
|
-
auth: "none",
|
|
1005
|
-
handler: (req, _params, getClientIp) =>
|
|
1006
|
-
handleListRemoteWebPairingRequests(req, getClientIp()),
|
|
1007
|
-
},
|
|
1008
|
-
{
|
|
1009
|
-
path: "/v1/remote-web/pairing-requests/approve",
|
|
1010
|
-
method: "POST",
|
|
1011
|
-
auth: "none",
|
|
1012
|
-
handler: (req, _params, getClientIp) =>
|
|
1013
|
-
handleApproveRemoteWebPairingRequest(req, getClientIp()),
|
|
1014
|
-
},
|
|
1015
|
-
{
|
|
1016
|
-
path: "/v1/remote-web/pairing-requests/deny",
|
|
1017
|
-
method: "POST",
|
|
1018
|
-
auth: "none",
|
|
1019
|
-
handler: (req, _params, getClientIp) =>
|
|
1020
|
-
handleDenyRemoteWebPairingRequest(req, getClientIp()),
|
|
1021
|
-
},
|
|
1022
|
-
// ── Shared-invite redemption (auth: none) ──
|
|
1023
|
-
// The invite link token in the request body is the credential.
|
|
1024
|
-
{
|
|
1025
|
-
path: "/v1/shared/invites/redeem",
|
|
1026
|
-
method: "POST",
|
|
1027
|
-
auth: "none",
|
|
1028
|
-
handler: (req, _params, getClientIp) =>
|
|
1029
|
-
handleSharedInviteRedeem(req, getClientIp()),
|
|
1030
|
-
},
|
|
1031
|
-
// ── Credential requests (one-time credential-collection links) ──
|
|
1032
|
-
// Unauthenticated by design: the single-use token in the request BODY is
|
|
1033
|
-
// the credential to act. Invalid tokens count as auth failures.
|
|
1034
|
-
// The entry page is a static self-contained HTML shell (no token
|
|
1035
|
-
// server-side — it rides the URL fragment); Tunnel-tunneled deployments
|
|
1036
|
-
// have no SPA server behind the tunnel, so the gateway serves it.
|
|
1037
|
-
{
|
|
1038
|
-
path: "/assistant/credentials/enter",
|
|
1039
|
-
method: "GET",
|
|
1040
|
-
auth: "none",
|
|
1041
|
-
handler: (req) => handleCredentialEntryPage(req),
|
|
1042
|
-
},
|
|
1043
|
-
{
|
|
1044
|
-
path: "/v1/credential-requests/peek",
|
|
1045
|
-
method: "POST",
|
|
1046
|
-
auth: "track-failures",
|
|
1047
|
-
trackFailureStatuses: [404],
|
|
1048
|
-
handler: (req) => handleCredentialRequestPeek(req),
|
|
1049
|
-
},
|
|
1050
|
-
{
|
|
1051
|
-
path: "/v1/credential-requests/submit",
|
|
1052
|
-
method: "POST",
|
|
1053
|
-
auth: "track-failures",
|
|
1054
|
-
trackFailureStatuses: [404],
|
|
1055
|
-
handler: (req) => handleCredentialRequestSubmit(req),
|
|
1056
|
-
},
|
|
1057
|
-
// ── Device management (localhost-only, auth: none; self-guards loopback) ──
|
|
1058
|
-
{
|
|
1059
|
-
path: "/v1/devices",
|
|
1060
|
-
method: "GET",
|
|
1061
|
-
auth: "none",
|
|
1062
|
-
handler: (req, _params, getClientIp) =>
|
|
1063
|
-
handleListDevices(req, getClientIp()),
|
|
1064
|
-
},
|
|
1065
|
-
{
|
|
1066
|
-
path: "/v1/devices/revoke",
|
|
1067
|
-
method: "POST",
|
|
1068
|
-
auth: "none",
|
|
1069
|
-
handler: (req, _params, getClientIp) =>
|
|
1070
|
-
handleRevokeDevice(req, getClientIp()),
|
|
1071
|
-
},
|
|
1072
|
-
|
|
1073
|
-
// ── The caller's own paired-device row (bearer-authed, browser-legit) ──
|
|
1074
|
-
{
|
|
1075
|
-
path: "/v1/devices/mine",
|
|
1076
|
-
method: "GET",
|
|
1077
|
-
auth: "edge",
|
|
1078
|
-
handler: (req) => handleGetMyDevice(req),
|
|
1079
|
-
},
|
|
1080
|
-
|
|
1081
|
-
// ── Channel verification sessions ──
|
|
1082
|
-
{
|
|
1083
|
-
// Bootstrap endpoint — may be replaced with an SSH-based exchange in the
|
|
1084
|
-
// future so that remote clients never need an exposed HTTP endpoint.
|
|
1085
|
-
path: "/v1/guardian/init",
|
|
1086
|
-
method: "POST",
|
|
1087
|
-
auth: "none",
|
|
1088
|
-
handler: (req, _params, getClientIp) =>
|
|
1089
|
-
channelVerificationSessionProxy.handleGuardianInit(req, getClientIp()),
|
|
1090
|
-
},
|
|
1091
|
-
{
|
|
1092
|
-
path: "/v1/guardian/reset-bootstrap",
|
|
1093
|
-
method: "POST",
|
|
1094
|
-
auth: "none",
|
|
1095
|
-
handler: (req, _params, getClientIp) =>
|
|
1096
|
-
channelVerificationSessionProxy.handleResetBootstrap(
|
|
1097
|
-
getClientIp(),
|
|
1098
|
-
req,
|
|
1099
|
-
),
|
|
1100
|
-
},
|
|
1101
|
-
{
|
|
1102
|
-
path: "/v1/channel-verification-sessions",
|
|
1103
|
-
method: "POST",
|
|
1104
|
-
auth: "edge",
|
|
1105
|
-
handler: (req) =>
|
|
1106
|
-
channelVerificationSessionProxy.handleCreateVerificationSession(req),
|
|
1107
|
-
},
|
|
1108
|
-
{
|
|
1109
|
-
path: "/v1/channel-verification-sessions",
|
|
1110
|
-
method: "DELETE",
|
|
1111
|
-
auth: "edge",
|
|
1112
|
-
handler: (req) =>
|
|
1113
|
-
channelVerificationSessionProxy.handleCancelVerificationSession(req),
|
|
1114
|
-
},
|
|
1115
|
-
{
|
|
1116
|
-
path: "/v1/channel-verification-sessions/resend",
|
|
1117
|
-
method: "POST",
|
|
1118
|
-
auth: "edge",
|
|
1119
|
-
handler: (req) =>
|
|
1120
|
-
channelVerificationSessionProxy.handleResendVerificationSession(req),
|
|
1121
|
-
},
|
|
1122
|
-
{
|
|
1123
|
-
path: "/v1/channel-verification-sessions/status",
|
|
1124
|
-
method: "GET",
|
|
1125
|
-
auth: "edge",
|
|
1126
|
-
handler: (req) =>
|
|
1127
|
-
channelVerificationSessionProxy.handleGetVerificationStatus(req),
|
|
1128
|
-
},
|
|
1129
|
-
{
|
|
1130
|
-
path: "/v1/channel-verification-sessions/revoke",
|
|
1131
|
-
method: "POST",
|
|
1132
|
-
auth: "edge",
|
|
1133
|
-
handler: (req) =>
|
|
1134
|
-
channelVerificationSessionProxy.handleRevokeVerificationBinding(req),
|
|
1135
|
-
},
|
|
1136
|
-
|
|
1137
|
-
// ── Guardian refresh (custom auth: accepts expired JWTs) ──
|
|
1138
|
-
// The refresh endpoint's purpose is to obtain a new access token,
|
|
1139
|
-
// so rejecting expired tokens would create a deadlock once the JWT
|
|
1140
|
-
// expires. Signature, audience, and policy epoch are still verified
|
|
1141
|
-
// — only the expiration check is relaxed.
|
|
1142
|
-
{
|
|
1143
|
-
path: "/v1/guardian/refresh",
|
|
1144
|
-
method: "POST",
|
|
1145
|
-
auth: "custom",
|
|
1146
|
-
handler: (req, _params, getClientIp) => {
|
|
1147
|
-
if (hasRemoteWebRefreshCookie(req)) {
|
|
1148
|
-
return handleGuardianRefresh(req);
|
|
1149
|
-
}
|
|
1150
|
-
|
|
1151
|
-
const authHeader = req.headers.get("authorization");
|
|
1152
|
-
if (!authHeader || !authHeader.toLowerCase().startsWith("bearer ")) {
|
|
1153
|
-
authRateLimiter.recordFailure(getClientIp());
|
|
1154
|
-
log.warn(
|
|
1155
|
-
{ path: new URL(req.url).pathname },
|
|
1156
|
-
"Guardian refresh auth rejected: missing or malformed Authorization header",
|
|
1157
|
-
);
|
|
1158
|
-
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1159
|
-
}
|
|
1160
|
-
const token = authHeader.slice(7);
|
|
1161
|
-
const result = validateEdgeToken(token, { allowExpired: true });
|
|
1162
|
-
if (!result.ok) {
|
|
1163
|
-
authRateLimiter.recordFailure(getClientIp());
|
|
1164
|
-
log.warn(
|
|
1165
|
-
{ path: new URL(req.url).pathname, reason: result.reason },
|
|
1166
|
-
"Guardian refresh auth rejected: token validation failed",
|
|
1167
|
-
);
|
|
1168
|
-
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
1169
|
-
}
|
|
1170
|
-
return handleGuardianRefresh(req);
|
|
1171
|
-
},
|
|
1172
|
-
},
|
|
1173
|
-
|
|
1174
|
-
// ── Twilio control plane ──
|
|
1175
|
-
{
|
|
1176
|
-
path: "/v1/integrations/twilio/config",
|
|
1177
|
-
method: "GET",
|
|
1178
|
-
auth: "edge",
|
|
1179
|
-
handler: (req) => twilioControlPlaneProxy.handleGetTwilioConfig(req),
|
|
1180
|
-
},
|
|
1181
|
-
{
|
|
1182
|
-
path: "/v1/integrations/twilio/credentials",
|
|
1183
|
-
method: "POST",
|
|
1184
|
-
auth: "edge",
|
|
1185
|
-
handler: (req) => twilioControlPlaneProxy.handleSetTwilioCredentials(req),
|
|
1186
|
-
},
|
|
1187
|
-
{
|
|
1188
|
-
path: "/v1/integrations/twilio/credentials",
|
|
1189
|
-
method: "DELETE",
|
|
1190
|
-
auth: "edge",
|
|
1191
|
-
handler: (req) =>
|
|
1192
|
-
twilioControlPlaneProxy.handleClearTwilioCredentials(req),
|
|
1193
|
-
},
|
|
1194
|
-
{
|
|
1195
|
-
path: "/v1/integrations/twilio/numbers",
|
|
1196
|
-
method: "GET",
|
|
1197
|
-
auth: "edge",
|
|
1198
|
-
handler: (req) => twilioControlPlaneProxy.handleListTwilioNumbers(req),
|
|
1199
|
-
},
|
|
1200
|
-
{
|
|
1201
|
-
path: "/v1/integrations/twilio/numbers/provision",
|
|
1202
|
-
method: "POST",
|
|
1203
|
-
auth: "edge",
|
|
1204
|
-
handler: (req) =>
|
|
1205
|
-
twilioControlPlaneProxy.handleProvisionTwilioNumber(req),
|
|
1206
|
-
},
|
|
1207
|
-
{
|
|
1208
|
-
path: "/v1/integrations/twilio/numbers/assign",
|
|
1209
|
-
method: "POST",
|
|
1210
|
-
auth: "edge",
|
|
1211
|
-
handler: (req) => twilioControlPlaneProxy.handleAssignTwilioNumber(req),
|
|
1212
|
-
},
|
|
1213
|
-
{
|
|
1214
|
-
path: "/v1/integrations/twilio/numbers/release",
|
|
1215
|
-
method: "POST",
|
|
1216
|
-
auth: "edge",
|
|
1217
|
-
handler: (req) => twilioControlPlaneProxy.handleReleaseTwilioNumber(req),
|
|
1218
|
-
},
|
|
1219
|
-
// ── Slack control plane ──
|
|
1220
|
-
{
|
|
1221
|
-
path: "/v1/slack/channels",
|
|
1222
|
-
method: "GET",
|
|
1223
|
-
auth: "edge",
|
|
1224
|
-
handler: (req) => slackControlPlaneProxy.handleListSlackChannels(req),
|
|
1225
|
-
},
|
|
1226
|
-
{
|
|
1227
|
-
path: "/v1/slack/share",
|
|
1228
|
-
method: "POST",
|
|
1229
|
-
auth: "edge",
|
|
1230
|
-
handler: (req) => slackControlPlaneProxy.handleShareToSlack(req),
|
|
1231
|
-
},
|
|
1232
|
-
|
|
1233
|
-
// ── OAuth providers ──
|
|
1234
|
-
{
|
|
1235
|
-
path: "/v1/oauth/providers",
|
|
1236
|
-
method: "GET",
|
|
1237
|
-
auth: "edge-scoped",
|
|
1238
|
-
scope: "settings.read",
|
|
1239
|
-
handler: (req) => oauthProvidersProxy.handleListProviders(req),
|
|
1240
|
-
},
|
|
1241
|
-
{
|
|
1242
|
-
path: /^\/v1\/oauth\/providers\/([^/]+)\/?$/,
|
|
1243
|
-
method: "GET",
|
|
1244
|
-
auth: "edge-scoped",
|
|
1245
|
-
scope: "settings.read",
|
|
1246
|
-
handler: (req, params) =>
|
|
1247
|
-
oauthProvidersProxy.handleGetProvider(req, params[0]),
|
|
1248
|
-
},
|
|
1249
|
-
|
|
1250
|
-
// ── OAuth apps ──
|
|
1251
|
-
{
|
|
1252
|
-
path: "/v1/oauth/apps",
|
|
1253
|
-
method: "GET",
|
|
1254
|
-
auth: "edge-scoped",
|
|
1255
|
-
scope: "settings.read",
|
|
1256
|
-
handler: (req) => oauthAppsProxy.handleListApps(req),
|
|
1257
|
-
},
|
|
1258
|
-
{
|
|
1259
|
-
path: "/v1/oauth/apps",
|
|
1260
|
-
method: "POST",
|
|
1261
|
-
auth: "edge-scoped",
|
|
1262
|
-
scope: "settings.write",
|
|
1263
|
-
handler: (req) => oauthAppsProxy.handleCreateApp(req),
|
|
1264
|
-
},
|
|
1265
|
-
{
|
|
1266
|
-
path: /^\/v1\/oauth\/apps\/([^/]+)\/?$/,
|
|
1267
|
-
method: "DELETE",
|
|
1268
|
-
auth: "edge-scoped",
|
|
1269
|
-
scope: "settings.write",
|
|
1270
|
-
handler: (req, params) => oauthAppsProxy.handleDeleteApp(req, params[0]),
|
|
1271
|
-
},
|
|
1272
|
-
{
|
|
1273
|
-
path: /^\/v1\/oauth\/apps\/([^/]+)\/connections\/?$/,
|
|
1274
|
-
method: "GET",
|
|
1275
|
-
auth: "edge-scoped",
|
|
1276
|
-
scope: "settings.read",
|
|
1277
|
-
handler: (req, params) =>
|
|
1278
|
-
oauthAppsProxy.handleListConnections(req, params[0]),
|
|
1279
|
-
},
|
|
1280
|
-
{
|
|
1281
|
-
path: /^\/v1\/oauth\/connections\/([^/]+)\/?$/,
|
|
1282
|
-
method: "DELETE",
|
|
1283
|
-
auth: "edge-scoped",
|
|
1284
|
-
scope: "settings.write",
|
|
1285
|
-
handler: (req, params) =>
|
|
1286
|
-
oauthAppsProxy.handleDeleteConnection(req, params[0]),
|
|
1287
|
-
},
|
|
1288
|
-
{
|
|
1289
|
-
path: /^\/v1\/oauth\/apps\/([^/]+)\/connect\/?$/,
|
|
1290
|
-
method: "POST",
|
|
1291
|
-
auth: "edge-scoped",
|
|
1292
|
-
scope: "settings.write",
|
|
1293
|
-
handler: (req, params) => oauthAppsProxy.handleConnect(req, params[0]),
|
|
1294
|
-
},
|
|
1295
|
-
|
|
1296
|
-
// ── Upgrade broadcast ──
|
|
1297
|
-
{
|
|
1298
|
-
path: "/v1/admin/upgrade-broadcast",
|
|
1299
|
-
method: "POST",
|
|
1300
|
-
auth: "edge-scoped",
|
|
1301
|
-
scope: "admin.write",
|
|
1302
|
-
handler: (req) => upgradeBroadcastProxy(req),
|
|
1303
|
-
},
|
|
1304
|
-
|
|
1305
|
-
// ── Workspace commit ──
|
|
1306
|
-
{
|
|
1307
|
-
path: "/v1/admin/workspace-commit",
|
|
1308
|
-
method: "POST",
|
|
1309
|
-
auth: "edge-scoped",
|
|
1310
|
-
scope: "admin.write",
|
|
1311
|
-
handler: (req) => workspaceCommitProxy(req),
|
|
1312
|
-
},
|
|
1313
|
-
|
|
1314
|
-
// ── Migration rollback ──
|
|
1315
|
-
{
|
|
1316
|
-
path: "/v1/admin/rollback-migrations",
|
|
1317
|
-
method: "POST",
|
|
1318
|
-
auth: "edge-scoped",
|
|
1319
|
-
scope: "admin.write",
|
|
1320
|
-
handler: (req) => migrationRollbackProxy(req),
|
|
1321
|
-
},
|
|
1322
|
-
|
|
1323
|
-
// ── Platform push / Live Activity tokens ──
|
|
1324
|
-
// Django-owned registration. Remote-gateway clients hit these
|
|
1325
|
-
// same-origin; without a dedicated route they fall through to the
|
|
1326
|
-
// runtime-proxy catch-all and 404. The handler forwards to Django
|
|
1327
|
-
// with the stored assistant API key and platform assistant UUID.
|
|
1328
|
-
{
|
|
1329
|
-
path: /^\/v1\/assistants\/[^/]+\/push-tokens\/?$/,
|
|
1330
|
-
method: "POST",
|
|
1331
|
-
auth: "edge-scoped",
|
|
1332
|
-
scope: "settings.write",
|
|
1333
|
-
handler: (req) => cloudPushProxy.handleUpsertPushToken(req),
|
|
1334
|
-
},
|
|
1335
|
-
{
|
|
1336
|
-
path: /^\/v1\/assistants\/[^/]+\/push-tokens\/([^/]+)\/?$/,
|
|
1337
|
-
method: "DELETE",
|
|
1338
|
-
auth: "edge-scoped",
|
|
1339
|
-
scope: "settings.write",
|
|
1340
|
-
handler: (req, params) =>
|
|
1341
|
-
cloudPushProxy.handleDeletePushToken(req, params[0]),
|
|
1342
|
-
},
|
|
1343
|
-
{
|
|
1344
|
-
path: /^\/v1\/assistants\/[^/]+\/live-activity\/tokens\/?$/,
|
|
1345
|
-
method: "POST",
|
|
1346
|
-
auth: "edge-scoped",
|
|
1347
|
-
scope: "settings.write",
|
|
1348
|
-
handler: (req) => cloudPushProxy.handleUpsertLiveActivityToken(req),
|
|
1349
|
-
},
|
|
1350
|
-
{
|
|
1351
|
-
path: /^\/v1\/assistants\/[^/]+\/live-activity\/tokens\/([^/]+)\/?$/,
|
|
1352
|
-
method: "DELETE",
|
|
1353
|
-
auth: "edge-scoped",
|
|
1354
|
-
scope: "settings.write",
|
|
1355
|
-
handler: (req, params) =>
|
|
1356
|
-
cloudPushProxy.handleDeleteLiveActivityToken(req, params[0]),
|
|
1357
|
-
},
|
|
1358
|
-
|
|
1359
|
-
// ── Channel readiness ──
|
|
1360
|
-
{
|
|
1361
|
-
path: "/v1/channels/readiness",
|
|
1362
|
-
method: "GET",
|
|
1363
|
-
auth: "edge",
|
|
1364
|
-
handler: (req) => channelReadinessProxy.handleGetChannelReadiness(req),
|
|
1365
|
-
},
|
|
1366
|
-
{
|
|
1367
|
-
path: "/v1/channels/readiness/refresh",
|
|
1368
|
-
method: "POST",
|
|
1369
|
-
auth: "edge",
|
|
1370
|
-
handler: (req) =>
|
|
1371
|
-
channelReadinessProxy.handleRefreshChannelReadiness(req),
|
|
1372
|
-
},
|
|
1373
|
-
|
|
1374
|
-
{
|
|
1375
|
-
path: /^\/v1\/assistants\/([^/]+)\/channels\/readiness\/$/,
|
|
1376
|
-
method: "GET",
|
|
1377
|
-
auth: "edge",
|
|
1378
|
-
handler: (req) => channelReadinessProxy.handleGetChannelReadiness(req),
|
|
1379
|
-
},
|
|
1380
|
-
|
|
1381
|
-
// ── Integration status ──
|
|
1382
|
-
{
|
|
1383
|
-
path: "/integrations/status",
|
|
1384
|
-
method: "GET",
|
|
1385
|
-
auth: "edge",
|
|
1386
|
-
handler: () =>
|
|
1387
|
-
Response.json({
|
|
1388
|
-
email: {
|
|
1389
|
-
address: configFileCache.getString("email", "address") ?? null,
|
|
1390
|
-
},
|
|
1391
|
-
}),
|
|
1392
|
-
},
|
|
1393
|
-
{
|
|
1394
|
-
path: /^\/v1\/assistants\/([^/]+)\/integrations\/status\/$/,
|
|
1395
|
-
method: "GET",
|
|
1396
|
-
auth: "edge",
|
|
1397
|
-
handler: () =>
|
|
1398
|
-
Response.json({
|
|
1399
|
-
email: {
|
|
1400
|
-
address: configFileCache.getString("email", "address") ?? null,
|
|
1401
|
-
},
|
|
1402
|
-
}),
|
|
1403
|
-
},
|
|
1404
|
-
|
|
1405
|
-
// ── Feature flags (scope-protected) ──
|
|
1406
|
-
{
|
|
1407
|
-
path: "/v1/feature-flags",
|
|
1408
|
-
method: "GET",
|
|
1409
|
-
auth: "edge-scoped",
|
|
1410
|
-
scope: "feature_flags.read",
|
|
1411
|
-
handler: (req) => handleFeatureFlagsGet(req),
|
|
1412
|
-
},
|
|
1413
|
-
{
|
|
1414
|
-
path: /^\/v1\/assistants\/([^/]+)\/feature-flags\/?$/,
|
|
1415
|
-
method: "GET",
|
|
1416
|
-
auth: "edge-scoped",
|
|
1417
|
-
scope: "feature_flags.read",
|
|
1418
|
-
handler: (req) => handleFeatureFlagsGet(req),
|
|
1419
|
-
},
|
|
1420
|
-
{
|
|
1421
|
-
path: /^\/v1\/feature-flags\/(.+)$/,
|
|
1422
|
-
method: "PATCH",
|
|
1423
|
-
auth: "edge-scoped",
|
|
1424
|
-
scope: "feature_flags.write",
|
|
1425
|
-
handler: (req, params) => {
|
|
1426
|
-
let flagKey: string;
|
|
1427
|
-
try {
|
|
1428
|
-
flagKey = decodeURIComponent(params[0]);
|
|
1429
|
-
} catch {
|
|
1430
|
-
return Response.json(
|
|
1431
|
-
{ error: "Invalid flag key encoding" },
|
|
1432
|
-
{ status: 400 },
|
|
1433
|
-
);
|
|
1434
|
-
}
|
|
1435
|
-
return handleFeatureFlagsPatch(req, flagKey);
|
|
1436
|
-
},
|
|
1437
|
-
},
|
|
1438
|
-
{
|
|
1439
|
-
path: /^\/v1\/assistants\/([^/]+)\/feature-flags\/(.+)$/,
|
|
1440
|
-
method: "PATCH",
|
|
1441
|
-
auth: "edge-scoped",
|
|
1442
|
-
scope: "feature_flags.write",
|
|
1443
|
-
handler: (req, params) => {
|
|
1444
|
-
let flagKey: string;
|
|
1445
|
-
try {
|
|
1446
|
-
flagKey = decodeURIComponent(params[1].replace(/\/$/, ""));
|
|
1447
|
-
} catch {
|
|
1448
|
-
return Response.json(
|
|
1449
|
-
{ error: "Invalid flag key encoding" },
|
|
1450
|
-
{ status: 400 },
|
|
1451
|
-
);
|
|
1452
|
-
}
|
|
1453
|
-
return handleFeatureFlagsPatch(req, flagKey);
|
|
1454
|
-
},
|
|
1455
|
-
},
|
|
1456
|
-
|
|
1457
|
-
// ── Auto-approve thresholds (scope-protected) ──
|
|
1458
|
-
{
|
|
1459
|
-
path: "/v1/permissions/thresholds",
|
|
1460
|
-
method: "GET",
|
|
1461
|
-
auth: "edge-scoped",
|
|
1462
|
-
scope: "settings.read",
|
|
1463
|
-
handler: (req) => handleGlobalThresholdGet(req),
|
|
1464
|
-
},
|
|
1465
|
-
{
|
|
1466
|
-
path: /^\/v1\/assistants\/([^/]+)\/permissions\/thresholds\/?$/,
|
|
1467
|
-
method: "GET",
|
|
1468
|
-
auth: "edge-scoped",
|
|
1469
|
-
scope: "settings.read",
|
|
1470
|
-
handler: (req) => handleGlobalThresholdGet(req),
|
|
1471
|
-
},
|
|
1472
|
-
{
|
|
1473
|
-
path: "/v1/permissions/thresholds",
|
|
1474
|
-
method: "PUT",
|
|
1475
|
-
auth: "edge-scoped",
|
|
1476
|
-
scope: "settings.write",
|
|
1477
|
-
handler: (req) => handleGlobalThresholdPut(req),
|
|
1478
|
-
},
|
|
1479
|
-
{
|
|
1480
|
-
path: /^\/v1\/assistants\/([^/]+)\/permissions\/thresholds\/?$/,
|
|
1481
|
-
method: "PUT",
|
|
1482
|
-
auth: "edge-scoped",
|
|
1483
|
-
scope: "settings.write",
|
|
1484
|
-
handler: (req) => handleGlobalThresholdPut(req),
|
|
1485
|
-
},
|
|
1486
|
-
|
|
1487
|
-
// ── Per-conversation threshold overrides (scope-protected) ──
|
|
1488
|
-
{
|
|
1489
|
-
path: /^\/v1\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1490
|
-
method: "GET",
|
|
1491
|
-
auth: "edge-scoped",
|
|
1492
|
-
scope: "settings.read",
|
|
1493
|
-
handler: (req, params) => handleConversationThresholdGet(req, params),
|
|
1494
|
-
},
|
|
1495
|
-
{
|
|
1496
|
-
path: /^\/v1\/assistants\/([^/]+)\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1497
|
-
method: "GET",
|
|
1498
|
-
auth: "edge-scoped",
|
|
1499
|
-
scope: "settings.read",
|
|
1500
|
-
handler: (req, params) =>
|
|
1501
|
-
handleConversationThresholdGet(req, params.slice(1)),
|
|
1502
|
-
},
|
|
1503
|
-
{
|
|
1504
|
-
path: /^\/v1\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1505
|
-
method: "PUT",
|
|
1506
|
-
auth: "edge-scoped",
|
|
1507
|
-
scope: "settings.write",
|
|
1508
|
-
handler: (req, params) => handleConversationThresholdPut(req, params),
|
|
1509
|
-
},
|
|
1510
|
-
{
|
|
1511
|
-
path: /^\/v1\/assistants\/([^/]+)\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1512
|
-
method: "PUT",
|
|
1513
|
-
auth: "edge-scoped",
|
|
1514
|
-
scope: "settings.write",
|
|
1515
|
-
handler: (req, params) =>
|
|
1516
|
-
handleConversationThresholdPut(req, params.slice(1)),
|
|
1517
|
-
},
|
|
1518
|
-
{
|
|
1519
|
-
path: /^\/v1\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1520
|
-
method: "DELETE",
|
|
1521
|
-
auth: "edge-scoped",
|
|
1522
|
-
scope: "settings.write",
|
|
1523
|
-
handler: (req, params) => handleConversationThresholdDelete(req, params),
|
|
1524
|
-
},
|
|
1525
|
-
{
|
|
1526
|
-
path: /^\/v1\/assistants\/([^/]+)\/permissions\/thresholds\/conversations\/([^/]+)\/?$/,
|
|
1527
|
-
method: "DELETE",
|
|
1528
|
-
auth: "edge-scoped",
|
|
1529
|
-
scope: "settings.write",
|
|
1530
|
-
handler: (req, params) =>
|
|
1531
|
-
handleConversationThresholdDelete(req, params.slice(1)),
|
|
1532
|
-
},
|
|
1533
|
-
|
|
1534
|
-
// ── Log export ──
|
|
1535
|
-
{
|
|
1536
|
-
path: "/v1/logs/export",
|
|
1537
|
-
method: "POST",
|
|
1538
|
-
auth: "edge",
|
|
1539
|
-
handler: (req, params, getClientIp) =>
|
|
1540
|
-
handleLogExport(req, params, getClientIp),
|
|
1541
|
-
},
|
|
1542
|
-
{
|
|
1543
|
-
path: "/v1/logs/tail",
|
|
1544
|
-
method: "GET",
|
|
1545
|
-
auth: "edge",
|
|
1546
|
-
handler: (req) => handleLogTail(req),
|
|
1547
|
-
},
|
|
1548
|
-
|
|
1549
|
-
// ── Trust rules v3 ──
|
|
1550
|
-
{
|
|
1551
|
-
path: "/v1/trust-rules",
|
|
1552
|
-
method: "GET",
|
|
1553
|
-
auth: "edge-scoped",
|
|
1554
|
-
scope: "settings.read",
|
|
1555
|
-
handler: (req) => handleTrustRulesList(req),
|
|
1556
|
-
},
|
|
1557
|
-
{
|
|
1558
|
-
// Must appear before the POST /v1/trust-rules create entry and before
|
|
1559
|
-
// the /:id catch-all regex so the literal path is matched first.
|
|
1560
|
-
path: "/v1/trust-rules/suggest",
|
|
1561
|
-
method: "POST",
|
|
1562
|
-
auth: "edge-scoped",
|
|
1563
|
-
scope: "settings.write",
|
|
1564
|
-
handler: (req) => handleTrustRulesSuggest(req),
|
|
1565
|
-
},
|
|
1566
|
-
{
|
|
1567
|
-
path: "/v1/trust-rules",
|
|
1568
|
-
method: "POST",
|
|
1569
|
-
auth: "edge-scoped",
|
|
1570
|
-
scope: "settings.write",
|
|
1571
|
-
handler: (req) => handleTrustRulesCreate(req),
|
|
1572
|
-
},
|
|
1573
|
-
{
|
|
1574
|
-
// Reset must be registered before the /:id catch-all regex
|
|
1575
|
-
path: /^\/v1\/trust-rules\/([^/]+)\/reset$/,
|
|
1576
|
-
method: "POST",
|
|
1577
|
-
auth: "edge-scoped",
|
|
1578
|
-
scope: "settings.write",
|
|
1579
|
-
handler: (req, params) => handleTrustRulesReset(req, params[0]),
|
|
1580
|
-
},
|
|
1581
|
-
{
|
|
1582
|
-
path: /^\/v1\/trust-rules\/([^/]+)$/,
|
|
1583
|
-
method: "PATCH",
|
|
1584
|
-
auth: "edge-scoped",
|
|
1585
|
-
scope: "settings.write",
|
|
1586
|
-
handler: (req, params) => handleTrustRulesUpdate(req, params[0]),
|
|
1587
|
-
},
|
|
1588
|
-
{
|
|
1589
|
-
path: /^\/v1\/trust-rules\/([^/]+)$/,
|
|
1590
|
-
method: "DELETE",
|
|
1591
|
-
auth: "edge-scoped",
|
|
1592
|
-
scope: "settings.write",
|
|
1593
|
-
handler: (req, params) => handleTrustRulesDelete(req, params[0]),
|
|
1594
|
-
},
|
|
1595
|
-
|
|
1596
|
-
// ── Channel admission policy — flat routes ──
|
|
1597
|
-
// Storage + CRUD for the per-channel admission floor. Gateway-owned: the
|
|
1598
|
-
// admission-policy store and cache live here, not in the daemon. The
|
|
1599
|
-
// platform's RuntimeProxyView strips the `/v1/assistants/<id>/` prefix and
|
|
1600
|
-
// forwards the flat path to the gateway via `/gateway-query`, so these flat
|
|
1601
|
-
// routes are what actually serve client traffic. The mutation regexes
|
|
1602
|
-
// tolerate a trailing slash.
|
|
1603
|
-
{
|
|
1604
|
-
path: /^\/v1\/channel-admission-policy\/?$/,
|
|
1605
|
-
method: "GET",
|
|
1606
|
-
auth: "edge-scoped",
|
|
1607
|
-
scope: "settings.read",
|
|
1608
|
-
handler: (req) => handleChannelAdmissionPolicyList(req),
|
|
1609
|
-
},
|
|
1610
|
-
{
|
|
1611
|
-
path: /^\/v1\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1612
|
-
method: "PUT",
|
|
1613
|
-
auth: "edge-scoped",
|
|
1614
|
-
scope: "settings.write",
|
|
1615
|
-
handler: (req, params) => handleChannelAdmissionPolicySet(req, params[0]),
|
|
1616
|
-
},
|
|
1617
|
-
{
|
|
1618
|
-
path: /^\/v1\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1619
|
-
method: "POST",
|
|
1620
|
-
auth: "edge-scoped",
|
|
1621
|
-
scope: "settings.write",
|
|
1622
|
-
handler: (req, params) => handleChannelAdmissionPolicySet(req, params[0]),
|
|
1623
|
-
},
|
|
1624
|
-
{
|
|
1625
|
-
path: /^\/v1\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1626
|
-
method: "DELETE",
|
|
1627
|
-
auth: "edge-scoped",
|
|
1628
|
-
scope: "settings.write",
|
|
1629
|
-
handler: (req, params) =>
|
|
1630
|
-
handleChannelAdmissionPolicyDelete(req, params[0]),
|
|
1631
|
-
},
|
|
1632
|
-
|
|
1633
|
-
// ── Channel admission policy — assistant-scoped variants ──
|
|
1634
|
-
// Mirror the flat routes for clients that use GatewayHTTPClient's
|
|
1635
|
-
// auto-prefix, which builds URLs like
|
|
1636
|
-
// /v1/assistants/<id>/channel-admission-policy/<channel>/. Without these,
|
|
1637
|
-
// the request falls through to the runtime-proxy catch-all and the daemon
|
|
1638
|
-
// serves 404 (the daemon does not implement this gateway storage API).
|
|
1639
|
-
// Admission policy is gateway-global, so the assistant id is matched and
|
|
1640
|
-
// discarded — same precedent as the assistant-scoped trust-rules routes
|
|
1641
|
-
// below.
|
|
1642
|
-
{
|
|
1643
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-admission-policy\/?$/,
|
|
1644
|
-
method: "GET",
|
|
1645
|
-
auth: "edge-scoped",
|
|
1646
|
-
scope: "settings.read",
|
|
1647
|
-
handler: (req) => handleChannelAdmissionPolicyList(req),
|
|
1648
|
-
},
|
|
1649
|
-
{
|
|
1650
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1651
|
-
method: "PUT",
|
|
1652
|
-
auth: "edge-scoped",
|
|
1653
|
-
scope: "settings.write",
|
|
1654
|
-
handler: (req, params) => handleChannelAdmissionPolicySet(req, params[0]),
|
|
1655
|
-
},
|
|
1656
|
-
{
|
|
1657
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1658
|
-
method: "POST",
|
|
1659
|
-
auth: "edge-scoped",
|
|
1660
|
-
scope: "settings.write",
|
|
1661
|
-
handler: (req, params) => handleChannelAdmissionPolicySet(req, params[0]),
|
|
1662
|
-
},
|
|
1663
|
-
{
|
|
1664
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-admission-policy\/([^/]+)\/?$/,
|
|
1665
|
-
method: "DELETE",
|
|
1666
|
-
auth: "edge-scoped",
|
|
1667
|
-
scope: "settings.write",
|
|
1668
|
-
handler: (req, params) =>
|
|
1669
|
-
handleChannelAdmissionPolicyDelete(req, params[0]),
|
|
1670
|
-
},
|
|
1671
|
-
|
|
1672
|
-
// ── Channel ingress approval ──
|
|
1673
|
-
// Same shape as channel-permission-overrides below, with two differences:
|
|
1674
|
-
// auth is edge-guardian rather than edge-scoped, because approving ingress
|
|
1675
|
-
// is the decision the assistant must not make for itself; and there are no
|
|
1676
|
-
// assistant-scoped variants, because the guardian reaches these directly
|
|
1677
|
-
// rather than through the cloud proxy. Deliberately absent from the IPC
|
|
1678
|
-
// surface for the same reason as the auth choice. Approve and revoke are
|
|
1679
|
-
// POST verb paths because a grant has no id of its own until a guardian
|
|
1680
|
-
// creates one. The listing is guardian-only for a different reason: it says
|
|
1681
|
-
// which declarations are waiting, which the public surface will not.
|
|
1682
|
-
{
|
|
1683
|
-
path: /^\/v1\/channel-ingress\/?$/,
|
|
1684
|
-
method: "GET",
|
|
1685
|
-
auth: "edge-guardian",
|
|
1686
|
-
handler: () => handleChannelIngressList(),
|
|
1687
|
-
},
|
|
1688
|
-
{
|
|
1689
|
-
path: /^\/v1\/channel-ingress\/([^/]+)\/approve\/?$/,
|
|
1690
|
-
method: "POST",
|
|
1691
|
-
auth: "edge-guardian",
|
|
1692
|
-
handler: (req, params) => handleChannelIngressApprove(req, params[0]!),
|
|
1693
|
-
},
|
|
1694
|
-
{
|
|
1695
|
-
path: /^\/v1\/channel-ingress\/([^/]+)\/revoke\/?$/,
|
|
1696
|
-
method: "POST",
|
|
1697
|
-
auth: "edge-guardian",
|
|
1698
|
-
handler: (req, params) => handleChannelIngressRevoke(req, params[0]!),
|
|
1699
|
-
},
|
|
1700
242
|
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
method: "GET",
|
|
1712
|
-
auth: "edge-guardian",
|
|
1713
|
-
handler: () => handleChannelIngressList(),
|
|
1714
|
-
},
|
|
1715
|
-
{
|
|
1716
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-ingress\/([^/]+)\/approve\/?$/,
|
|
1717
|
-
method: "POST",
|
|
1718
|
-
auth: "edge-guardian",
|
|
1719
|
-
handler: (req, params) => handleChannelIngressApprove(req, params[0]!),
|
|
1720
|
-
},
|
|
1721
|
-
{
|
|
1722
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-ingress\/([^/]+)\/revoke\/?$/,
|
|
1723
|
-
method: "POST",
|
|
1724
|
-
auth: "edge-guardian",
|
|
1725
|
-
handler: (req, params) => handleChannelIngressRevoke(req, params[0]!),
|
|
1726
|
-
},
|
|
243
|
+
function maybeStartTunnelForTwilio(
|
|
244
|
+
reason: string,
|
|
245
|
+
twilioCredentials?: Record<string, string> | null,
|
|
246
|
+
): void {
|
|
247
|
+
if (!tunnelClient || tunnelClient.isRunning()) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (!hasTwilioSetupStarted(configFileCache, twilioCredentials)) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
1727
253
|
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
// delete is a POST verb path because cells are keyed by a composite
|
|
1733
|
-
// (selector × contact-type), not a row id.
|
|
1734
|
-
{
|
|
1735
|
-
path: /^\/v1\/channel-permission-overrides\/?$/,
|
|
1736
|
-
method: "GET",
|
|
1737
|
-
auth: "edge-scoped",
|
|
1738
|
-
scope: "settings.read",
|
|
1739
|
-
handler: (req) => handleChannelPermissionOverridesList(req),
|
|
1740
|
-
},
|
|
1741
|
-
{
|
|
1742
|
-
path: /^\/v1\/channel-permission-overrides\/?$/,
|
|
1743
|
-
method: "PUT",
|
|
1744
|
-
auth: "edge-scoped",
|
|
1745
|
-
scope: "settings.write",
|
|
1746
|
-
handler: (req) => handleChannelPermissionOverrideSet(req),
|
|
1747
|
-
},
|
|
1748
|
-
{
|
|
1749
|
-
path: /^\/v1\/channel-permission-overrides\/delete\/?$/,
|
|
1750
|
-
method: "POST",
|
|
1751
|
-
auth: "edge-scoped",
|
|
1752
|
-
scope: "settings.write",
|
|
1753
|
-
handler: (req) => handleChannelPermissionOverrideDelete(req),
|
|
1754
|
-
},
|
|
1755
|
-
// Resolve is a read (settings.read) despite the POST verb — the body
|
|
1756
|
-
// carries a composite query, same rationale as /delete above.
|
|
1757
|
-
{
|
|
1758
|
-
path: /^\/v1\/channel-permission-overrides\/resolve\/?$/,
|
|
1759
|
-
method: "POST",
|
|
1760
|
-
auth: "edge-scoped",
|
|
1761
|
-
scope: "settings.read",
|
|
1762
|
-
handler: (req) => handleChannelPermissionResolve(req),
|
|
1763
|
-
},
|
|
254
|
+
log.info({ reason }, "Starting Tunnel after Twilio setup detected");
|
|
255
|
+
tunnelClient.start();
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
1764
258
|
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
},
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
method: "POST",
|
|
1785
|
-
auth: "edge-scoped",
|
|
1786
|
-
scope: "settings.write",
|
|
1787
|
-
handler: (req) => handleChannelPermissionOverrideDelete(req),
|
|
1788
|
-
},
|
|
1789
|
-
{
|
|
1790
|
-
path: /^\/v1\/assistants\/[^/]+\/channel-permission-overrides\/resolve\/?$/,
|
|
1791
|
-
method: "POST",
|
|
1792
|
-
auth: "edge-scoped",
|
|
1793
|
-
scope: "settings.read",
|
|
1794
|
-
handler: (req) => handleChannelPermissionResolve(req),
|
|
1795
|
-
},
|
|
259
|
+
/**
|
|
260
|
+
* Start the Tunnel for web live voice.
|
|
261
|
+
*
|
|
262
|
+
* Tunnel is the browser's ingress for the live-voice WebSocket, but the tunnel
|
|
263
|
+
* was historically only started for Twilio (see
|
|
264
|
+
* {@link maybeStartTunnelForTwilio}). Without this, an assistant with no
|
|
265
|
+
* Twilio setup never registers a Tunnel, so the browser's
|
|
266
|
+
* `/v1/live-voice` upgrade fails with "assistant tunnel is not connected".
|
|
267
|
+
* Live voice is available to every assistant, so this runs unconditionally at
|
|
268
|
+
* startup. Shares the `tunnelStartRequested` latch with the Twilio path — one
|
|
269
|
+
* tunnel serves both — and `tunnelClient.start()` is idempotent.
|
|
270
|
+
*/
|
|
271
|
+
function startTunnelForLiveVoice(reason: string): void {
|
|
272
|
+
if (!tunnelClient || tunnelClient.isRunning()) {
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
log.info({ reason }, "Starting Tunnel for live voice");
|
|
276
|
+
tunnelClient.start();
|
|
277
|
+
}
|
|
1796
278
|
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
279
|
+
async function readTwilioCredentialsForTunnelStartup(): Promise<Record<
|
|
280
|
+
string,
|
|
281
|
+
string
|
|
282
|
+
> | null> {
|
|
283
|
+
try {
|
|
284
|
+
const [accountSid, authToken] = await Promise.all([
|
|
285
|
+
credentialCache.get(credentialKey("twilio", "account_sid")),
|
|
286
|
+
credentialCache.get(credentialKey("twilio", "auth_token")),
|
|
287
|
+
]);
|
|
288
|
+
if (!accountSid?.trim() || !authToken?.trim()) {
|
|
289
|
+
return null;
|
|
290
|
+
}
|
|
291
|
+
return { account_sid: accountSid, auth_token: authToken };
|
|
292
|
+
} catch (err) {
|
|
293
|
+
log.warn(
|
|
294
|
+
{ err },
|
|
295
|
+
"Failed to read Twilio credentials before Tunnel startup gate",
|
|
296
|
+
);
|
|
297
|
+
return null;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Assistant-scoped mirrors of the browser stream sockets: the scoped data
|
|
302
|
+
// plane emits /v1/assistants/<id>/<route> — the same verbatim shape every
|
|
303
|
+
// scoped forwarder carries — so the upgrade pre-router admits the scoped
|
|
304
|
+
// spelling of each socket and discards the id, the same mirror the route
|
|
305
|
+
// table keeps for tunnel/status. Daemon-only sockets (speech relay) get no
|
|
306
|
+
// mirror: they are never browser-reachable.
|
|
307
|
+
const SCOPED_WS_MIRRORS: Array<{
|
|
308
|
+
pattern: RegExp;
|
|
309
|
+
upgrade: (
|
|
310
|
+
req: Request,
|
|
311
|
+
server: Parameters<typeof handleSttStreamWs>[1],
|
|
312
|
+
) => Promise<Response | undefined> | Response | undefined;
|
|
313
|
+
}> = [
|
|
1823
314
|
{
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
auth: "edge-scoped",
|
|
1827
|
-
scope: "settings.write",
|
|
1828
|
-
handler: (req) => handleTrustRulesCreate(req),
|
|
315
|
+
pattern: /^\/v1\/assistants\/[^/]+\/live-voice\/?$/,
|
|
316
|
+
upgrade: handleLiveVoiceWs,
|
|
1829
317
|
},
|
|
1830
318
|
{
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
method: "POST",
|
|
1834
|
-
auth: "edge-scoped",
|
|
1835
|
-
scope: "settings.write",
|
|
1836
|
-
handler: (req, params) => handleTrustRulesReset(req, params[0]),
|
|
319
|
+
pattern: /^\/v1\/assistants\/[^/]+\/stt\/stream\/?$/,
|
|
320
|
+
upgrade: handleSttStreamWs,
|
|
1837
321
|
},
|
|
1838
322
|
{
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
auth: "edge-scoped",
|
|
1842
|
-
scope: "settings.write",
|
|
1843
|
-
handler: (req, params) => handleTrustRulesUpdate(req, params[0]),
|
|
323
|
+
pattern: /^\/v1\/assistants\/[^/]+\/watch\/stream\/?$/,
|
|
324
|
+
upgrade: handleWatchStreamWs,
|
|
1844
325
|
},
|
|
1845
326
|
{
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
auth: "edge-scoped",
|
|
1849
|
-
scope: "settings.write",
|
|
1850
|
-
handler: (req, params) => handleTrustRulesDelete(req, params[0]),
|
|
327
|
+
pattern: /^\/v1\/assistants\/[^/]+\/desktop\/stream\/?$/,
|
|
328
|
+
upgrade: handleDesktopStreamWs,
|
|
1851
329
|
},
|
|
1852
330
|
];
|
|
1853
|
-
|
|
1854
|
-
//
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
handler: (req) => handleCreateToken(req, server, config.trustProxy),
|
|
1860
|
-
});
|
|
1861
|
-
|
|
1862
|
-
for (const method of ["GET", "POST"] as const) {
|
|
1863
|
-
const setupRoute = {
|
|
1864
|
-
method,
|
|
1865
|
-
auth: "edge-guardian" as const,
|
|
1866
|
-
handler: desktopSetupProxy,
|
|
1867
|
-
};
|
|
1868
|
-
routes.push(
|
|
1869
|
-
{ path: /^\/v1\/desktop\/setup\/?$/, ...setupRoute },
|
|
1870
|
-
{ path: /^\/v1\/assistants\/[^/]+\/desktop\/setup\/?$/, ...setupRoute },
|
|
1871
|
-
);
|
|
1872
|
-
}
|
|
1873
|
-
|
|
1874
|
-
// Runtime proxy catch-all — must be last so specific routes are checked first.
|
|
1875
|
-
routes.push({
|
|
1876
|
-
path: /^\//, // match everything
|
|
1877
|
-
auth: "track-failures",
|
|
1878
|
-
handler: (req, _params, getClientIp) =>
|
|
1879
|
-
handleRuntimeProxy(req, getClientIp()),
|
|
1880
|
-
});
|
|
1881
|
-
|
|
1882
|
-
const router = createRouter(routes, {
|
|
331
|
+
// ── Route table ──
|
|
332
|
+
// One routes array, owned by the routes barrel: every HTTP route is
|
|
333
|
+
// declared in a per-domain ROUTES array and concatenated there, in
|
|
334
|
+
// dispatch order (the runtime-proxy catch-all last). Routes are matched
|
|
335
|
+
// top-to-bottom; auth middleware is applied declaratively per route.
|
|
336
|
+
const router = createRouter(ROUTES, {
|
|
1883
337
|
authRateLimiter,
|
|
1884
338
|
trustProxy: config.trustProxy,
|
|
1885
339
|
});
|
|
1886
340
|
|
|
341
|
+
// The webhook dedup caches whose lifecycle (cleanup timers, credential
|
|
342
|
+
// resets) this process manages below.
|
|
343
|
+
const { telegramDedupCache, whatsappDedupCache, emailDedupCache } =
|
|
344
|
+
webhookDedupCaches();
|
|
345
|
+
|
|
1887
346
|
/** Stamp the assistant version header on a response. */
|
|
1888
347
|
function stampVersion<T extends Response>(res: T): T {
|
|
1889
348
|
res.headers.set(VERSION_HEADER_NAME, VERSION_HEADER_VALUE);
|
|
@@ -1897,95 +356,100 @@ async function main() {
|
|
|
1897
356
|
// to accommodate large app package uploads.
|
|
1898
357
|
maxRequestBodySize: 512 * 1024 * 1024,
|
|
1899
358
|
websocket: {
|
|
359
|
+
// Every stream's socket data carries a `wsType` discriminant, and
|
|
360
|
+
// each websocket module owns a zod-parsed `isXSocketData` predicate —
|
|
361
|
+
// the narrowest type discrimination, no casts. A WS route table like
|
|
362
|
+
// the HTTP one below falls out of this shape when a seventh stream
|
|
363
|
+
// makes the if-chain worth a table.
|
|
1900
364
|
open(ws) {
|
|
1901
|
-
if (isMediaStreamSocketData(ws
|
|
1902
|
-
|
|
365
|
+
if (isMediaStreamSocketData(ws)) {
|
|
366
|
+
openTwilioMediaWebsocket(ws);
|
|
1903
367
|
return;
|
|
1904
368
|
}
|
|
1905
|
-
if (isPluginWebhookSocketData(ws
|
|
1906
|
-
|
|
369
|
+
if (isPluginWebhookSocketData(ws)) {
|
|
370
|
+
openPluginWebhookWebsocket(ws);
|
|
1907
371
|
return;
|
|
1908
372
|
}
|
|
1909
|
-
if (isSttStreamSocketData(ws
|
|
1910
|
-
|
|
373
|
+
if (isSttStreamSocketData(ws)) {
|
|
374
|
+
openSttStreamWebsocket(ws);
|
|
1911
375
|
return;
|
|
1912
376
|
}
|
|
1913
|
-
if (isWatchStreamSocketData(ws
|
|
1914
|
-
|
|
377
|
+
if (isWatchStreamSocketData(ws)) {
|
|
378
|
+
openWatchStreamWebsocket(ws);
|
|
1915
379
|
return;
|
|
1916
380
|
}
|
|
1917
|
-
if (isDesktopStreamSocketData(ws
|
|
1918
|
-
|
|
381
|
+
if (isDesktopStreamSocketData(ws)) {
|
|
382
|
+
openDesktopStreamWebsocket(ws);
|
|
1919
383
|
return;
|
|
1920
384
|
}
|
|
1921
|
-
if (isLiveVoiceSocketData(ws
|
|
1922
|
-
|
|
385
|
+
if (isLiveVoiceSocketData(ws)) {
|
|
386
|
+
openLiveVoiceWebsocket(ws);
|
|
1923
387
|
return;
|
|
1924
388
|
}
|
|
1925
|
-
if (isSpeechRelaySocketData(ws
|
|
1926
|
-
void
|
|
389
|
+
if (isSpeechRelaySocketData(ws)) {
|
|
390
|
+
void openSpeechRelayWebsocket(ws);
|
|
1927
391
|
return;
|
|
1928
392
|
}
|
|
1929
393
|
closeUnknownSocket(ws, "open");
|
|
1930
394
|
},
|
|
1931
395
|
message(ws, message) {
|
|
1932
|
-
if (isMediaStreamSocketData(ws
|
|
1933
|
-
|
|
396
|
+
if (isMediaStreamSocketData(ws)) {
|
|
397
|
+
messageTwilioMediaStream(ws, message);
|
|
1934
398
|
return;
|
|
1935
399
|
}
|
|
1936
|
-
if (isPluginWebhookSocketData(ws
|
|
1937
|
-
|
|
400
|
+
if (isPluginWebhookSocketData(ws)) {
|
|
401
|
+
messagePluginWebhookWebsocket(ws, message);
|
|
1938
402
|
return;
|
|
1939
403
|
}
|
|
1940
|
-
if (isSttStreamSocketData(ws
|
|
1941
|
-
|
|
404
|
+
if (isSttStreamSocketData(ws)) {
|
|
405
|
+
messageSttStreamWebsocket(ws, message);
|
|
1942
406
|
return;
|
|
1943
407
|
}
|
|
1944
|
-
if (isWatchStreamSocketData(ws
|
|
1945
|
-
|
|
408
|
+
if (isWatchStreamSocketData(ws)) {
|
|
409
|
+
messageWatchStreamWebsocket(ws, message);
|
|
1946
410
|
return;
|
|
1947
411
|
}
|
|
1948
|
-
if (isDesktopStreamSocketData(ws
|
|
1949
|
-
|
|
412
|
+
if (isDesktopStreamSocketData(ws)) {
|
|
413
|
+
messageDesktopStreamWebsocket(ws, message);
|
|
1950
414
|
return;
|
|
1951
415
|
}
|
|
1952
|
-
if (isLiveVoiceSocketData(ws
|
|
1953
|
-
|
|
416
|
+
if (isLiveVoiceSocketData(ws)) {
|
|
417
|
+
messageLiveVoiceWebsocket(ws, message);
|
|
1954
418
|
return;
|
|
1955
419
|
}
|
|
1956
|
-
if (isSpeechRelaySocketData(ws
|
|
1957
|
-
|
|
420
|
+
if (isSpeechRelaySocketData(ws)) {
|
|
421
|
+
messageSpeechRelayWebsocket(ws, message);
|
|
1958
422
|
return;
|
|
1959
423
|
}
|
|
1960
424
|
closeUnknownSocket(ws, "message");
|
|
1961
425
|
},
|
|
1962
426
|
close(ws, code, reason) {
|
|
1963
|
-
if (isMediaStreamSocketData(ws
|
|
1964
|
-
|
|
427
|
+
if (isMediaStreamSocketData(ws)) {
|
|
428
|
+
closeTwilioMediaStream(ws, code, reason);
|
|
1965
429
|
return;
|
|
1966
430
|
}
|
|
1967
|
-
if (isPluginWebhookSocketData(ws
|
|
1968
|
-
|
|
431
|
+
if (isPluginWebhookSocketData(ws)) {
|
|
432
|
+
closePluginWebhookWebsocket(ws, code, reason);
|
|
1969
433
|
return;
|
|
1970
434
|
}
|
|
1971
|
-
if (isSttStreamSocketData(ws
|
|
1972
|
-
|
|
435
|
+
if (isSttStreamSocketData(ws)) {
|
|
436
|
+
closeSttStreamWebsocket(ws, code, reason);
|
|
1973
437
|
return;
|
|
1974
438
|
}
|
|
1975
|
-
if (isWatchStreamSocketData(ws
|
|
1976
|
-
|
|
439
|
+
if (isWatchStreamSocketData(ws)) {
|
|
440
|
+
closeWatchStreamWebsocket(ws, code, reason);
|
|
1977
441
|
return;
|
|
1978
442
|
}
|
|
1979
|
-
if (isDesktopStreamSocketData(ws
|
|
1980
|
-
|
|
443
|
+
if (isDesktopStreamSocketData(ws)) {
|
|
444
|
+
closeDesktopStreamWebsocket(ws, code, reason);
|
|
1981
445
|
return;
|
|
1982
446
|
}
|
|
1983
|
-
if (isLiveVoiceSocketData(ws
|
|
1984
|
-
|
|
447
|
+
if (isLiveVoiceSocketData(ws)) {
|
|
448
|
+
closeLiveVoiceWebsocket(ws, code, reason);
|
|
1985
449
|
return;
|
|
1986
450
|
}
|
|
1987
|
-
if (isSpeechRelaySocketData(ws
|
|
1988
|
-
|
|
451
|
+
if (isSpeechRelaySocketData(ws)) {
|
|
452
|
+
closeSpeechRelayWebsocket(ws, code, reason);
|
|
1989
453
|
return;
|
|
1990
454
|
}
|
|
1991
455
|
log.error(
|
|
@@ -2035,7 +499,22 @@ async function main() {
|
|
|
2035
499
|
const includeMigrations =
|
|
2036
500
|
url.searchParams.get("include") === "migrations";
|
|
2037
501
|
if (!includeMigrations) {
|
|
2038
|
-
|
|
502
|
+
// The probe doubles as the app shell's identity ping: the version it
|
|
503
|
+
// serves, and whether the CALLER's own credentials (the browser
|
|
504
|
+
// access cookie, or a bearer) authenticate. The /v1 routes can serve
|
|
505
|
+
// 200 unauthenticated over loopback trust, so this verdict is the one
|
|
506
|
+
// reliable signal a client has before it mounts an authenticated UI.
|
|
507
|
+
// Probes without credentials (k8s liveness) read authenticated:false —
|
|
508
|
+
// they only look at the status code.
|
|
509
|
+
const token = extractBearerToken(req);
|
|
510
|
+
const authenticated = isHttpAuthDisabled()
|
|
511
|
+
? true
|
|
512
|
+
: token !== null && validateEdgeToken(token).ok;
|
|
513
|
+
return Response.json({
|
|
514
|
+
status: "ok",
|
|
515
|
+
version: APP_VERSION,
|
|
516
|
+
authenticated,
|
|
517
|
+
});
|
|
2039
518
|
}
|
|
2040
519
|
// Fetch the daemon's /v1/health to surface migration state
|
|
2041
520
|
// (dbVersion, lastWorkspaceMigrationId) so the CLI can capture
|
|
@@ -2045,7 +524,7 @@ async function main() {
|
|
|
2045
524
|
`${config.assistantRuntimeBaseUrl}/v1/health`,
|
|
2046
525
|
{
|
|
2047
526
|
signal: AbortSignal.timeout(3000),
|
|
2048
|
-
headers:
|
|
527
|
+
headers: forwardedIdentityHeaders(),
|
|
2049
528
|
},
|
|
2050
529
|
);
|
|
2051
530
|
if (upstream.ok) {
|
|
@@ -2176,7 +655,7 @@ async function main() {
|
|
|
2176
655
|
) {
|
|
2177
656
|
const upgradeResult = handleTwilioMediaWs(req, server);
|
|
2178
657
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2179
|
-
return undefined
|
|
658
|
+
return undefined;
|
|
2180
659
|
}
|
|
2181
660
|
|
|
2182
661
|
// Plugin ingress declared as `websocket`. Claimed only for a genuine
|
|
@@ -2192,14 +671,23 @@ async function main() {
|
|
|
2192
671
|
match[2]!,
|
|
2193
672
|
);
|
|
2194
673
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2195
|
-
return undefined
|
|
674
|
+
return undefined;
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
if (isWebsocketUpgradeRequest(req)) {
|
|
679
|
+
for (const mirror of SCOPED_WS_MIRRORS) {
|
|
680
|
+
if (!mirror.pattern.test(url.pathname)) continue;
|
|
681
|
+
const upgradeResult = await mirror.upgrade(req, server);
|
|
682
|
+
if (upgradeResult !== undefined) return upgradeResult;
|
|
683
|
+
return undefined;
|
|
2196
684
|
}
|
|
2197
685
|
}
|
|
2198
686
|
|
|
2199
687
|
if (url.pathname === "/v1/stt/stream") {
|
|
2200
688
|
const upgradeResult = handleSttStreamWs(req, server);
|
|
2201
689
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2202
|
-
return undefined
|
|
690
|
+
return undefined;
|
|
2203
691
|
}
|
|
2204
692
|
|
|
2205
693
|
// Reachable both ways: directly on a self-hosted ingress with an actor
|
|
@@ -2212,7 +700,7 @@ async function main() {
|
|
|
2212
700
|
if (upgradeResult !== undefined) {
|
|
2213
701
|
return upgradeResult;
|
|
2214
702
|
}
|
|
2215
|
-
return undefined
|
|
703
|
+
return undefined;
|
|
2216
704
|
}
|
|
2217
705
|
|
|
2218
706
|
// Guardian-only through the same gate as the watch stream.
|
|
@@ -2221,13 +709,13 @@ async function main() {
|
|
|
2221
709
|
if (upgradeResult !== undefined) {
|
|
2222
710
|
return upgradeResult;
|
|
2223
711
|
}
|
|
2224
|
-
return undefined
|
|
712
|
+
return undefined;
|
|
2225
713
|
}
|
|
2226
714
|
|
|
2227
715
|
if (url.pathname === "/v1/live-voice") {
|
|
2228
716
|
const upgradeResult = await handleLiveVoiceWs(req, server);
|
|
2229
717
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2230
|
-
return undefined
|
|
718
|
+
return undefined;
|
|
2231
719
|
}
|
|
2232
720
|
|
|
2233
721
|
// Managed-speech relay: daemon-only egress to tunnel. NOT in
|
|
@@ -2235,19 +723,19 @@ async function main() {
|
|
|
2235
723
|
if (url.pathname === "/v1/speech/stt/stream") {
|
|
2236
724
|
const upgradeResult = await handleSpeechRelaySttWs(req, server);
|
|
2237
725
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2238
|
-
return undefined
|
|
726
|
+
return undefined;
|
|
2239
727
|
}
|
|
2240
728
|
|
|
2241
729
|
if (url.pathname === "/v2/speech/stt/stream") {
|
|
2242
730
|
const upgradeResult = await handleSpeechRelaySttV2Ws(req, server);
|
|
2243
731
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2244
|
-
return undefined
|
|
732
|
+
return undefined;
|
|
2245
733
|
}
|
|
2246
734
|
|
|
2247
735
|
if (url.pathname === "/v1/speech/tts/stream") {
|
|
2248
736
|
const upgradeResult = await handleSpeechRelayTtsWs(req, server);
|
|
2249
737
|
if (upgradeResult !== undefined) return upgradeResult;
|
|
2250
|
-
return undefined
|
|
738
|
+
return undefined;
|
|
2251
739
|
}
|
|
2252
740
|
|
|
2253
741
|
// Attach a trace ID to every non-healthcheck request for
|
|
@@ -2309,6 +797,8 @@ async function main() {
|
|
|
2309
797
|
return notFound;
|
|
2310
798
|
}
|
|
2311
799
|
|
|
800
|
+
void refreshRouteSchema();
|
|
801
|
+
|
|
2312
802
|
log.info({ port: server.port }, "Gateway HTTP server listening");
|
|
2313
803
|
|
|
2314
804
|
// Complete post-assistant-ready startup work after binding /healthz.
|
|
@@ -2332,718 +822,45 @@ async function main() {
|
|
|
2332
822
|
whatsappDedupCache.startCleanup();
|
|
2333
823
|
emailDedupCache.startCleanup();
|
|
2334
824
|
|
|
2335
|
-
|
|
2336
|
-
// already reclaimed in place by the next claim on the same key, so this only
|
|
2337
|
-
// keeps the table from growing a row per message that nothing will read
|
|
2338
|
-
// again.
|
|
2339
|
-
const inboundDedupCleanup = setInterval(() => {
|
|
2340
|
-
try {
|
|
2341
|
-
const evicted = cleanupExpiredInboundEvents();
|
|
2342
|
-
if (evicted > 0) {
|
|
2343
|
-
log.debug({ evicted }, "Evicted expired inbound dedup claims");
|
|
2344
|
-
}
|
|
2345
|
-
} catch (err) {
|
|
2346
|
-
log.warn({ err }, "Inbound dedup cleanup failed");
|
|
2347
|
-
}
|
|
2348
|
-
}, INBOUND_DEDUP_CLEANUP_INTERVAL_MS);
|
|
2349
|
-
|
|
2350
|
-
const telegramCaches = {
|
|
2351
|
-
credentials: credentialCache,
|
|
2352
|
-
configFile: configFileCache,
|
|
2353
|
-
};
|
|
2354
|
-
|
|
2355
|
-
function registerTelegramCommands(): void {
|
|
2356
|
-
callTelegramApi(
|
|
2357
|
-
"setMyCommands",
|
|
2358
|
-
{
|
|
2359
|
-
commands: [
|
|
2360
|
-
{ command: "new", description: "Start a new conversation" },
|
|
2361
|
-
{ command: "help", description: "Show available commands" },
|
|
2362
|
-
],
|
|
2363
|
-
},
|
|
2364
|
-
{ credentials: credentialCache, configFile: configFileCache },
|
|
2365
|
-
).catch((err) => {
|
|
2366
|
-
log.error({ err }, "Failed to register Telegram bot commands");
|
|
2367
|
-
});
|
|
2368
|
-
}
|
|
2369
|
-
|
|
2370
|
-
// ── Slack Socket Mode lifecycle ──
|
|
2371
|
-
let slackSocketClient: SlackSocketModeClient | null = null;
|
|
2372
|
-
const slackForwardQueue = createConversationTaskQueue();
|
|
2373
|
-
// Guards concurrent startSlackSocket calls: at boot both the credential
|
|
2374
|
-
// watcher's and the config-file watcher's initial polls fire it, and the
|
|
2375
|
-
// second call can pass the stop() guard while the first is still awaiting
|
|
2376
|
-
// credentials, leaving the first client running (open WebSocket, reconnect
|
|
2377
|
-
// loop, cleanup timer) with no reference to stop it.
|
|
2378
|
-
let slackStartGeneration = 0;
|
|
2379
|
-
|
|
2380
|
-
/** Fire-and-forget: notify the cloud of inbound Slack activity so the
|
|
2381
|
-
* idle-sleep timer is reset for this assistant.
|
|
2382
|
-
* Throttled to at most one outbound POST per 30 seconds. */
|
|
2383
|
-
let lastRecordActivityTs = 0;
|
|
2384
|
-
async function notifyRecordActivity(): Promise<void> {
|
|
2385
|
-
if (!areCloudFeaturesEnabled()) {
|
|
2386
|
-
log.debug("Platform features disabled — skipping record-activity");
|
|
2387
|
-
return;
|
|
2388
|
-
}
|
|
2389
|
-
|
|
2390
|
-
const now = Date.now();
|
|
2391
|
-
if (now - lastRecordActivityTs < 30_000) return;
|
|
2392
|
-
lastRecordActivityTs = now;
|
|
2393
|
-
|
|
2394
|
-
try {
|
|
2395
|
-
const [assistantApiKey, assistantId] = await Promise.all([
|
|
2396
|
-
credentialCache.get(credentialKey("cadet", "assistant_api_key")),
|
|
2397
|
-
resolveCloudAssistantIdOrUndefined(),
|
|
2398
|
-
]);
|
|
2399
|
-
const cloudBaseUrl = getCloudBaseUrl();
|
|
2400
|
-
|
|
2401
|
-
if (!cloudBaseUrl || !assistantApiKey || !assistantId) return;
|
|
2402
|
-
|
|
2403
|
-
const res = await fetchImpl(
|
|
2404
|
-
`${cloudBaseUrl}/v1/assistants/${assistantId}/record-activity/`,
|
|
2405
|
-
{
|
|
2406
|
-
method: "POST",
|
|
2407
|
-
headers: { Authorization: `Api-Key ${assistantApiKey.trim()}` },
|
|
2408
|
-
signal: AbortSignal.timeout(10_000),
|
|
2409
|
-
},
|
|
2410
|
-
);
|
|
2411
|
-
|
|
2412
|
-
if (!res.ok) {
|
|
2413
|
-
log.warn(
|
|
2414
|
-
{ status: res.status },
|
|
2415
|
-
"Non-OK response from record-activity endpoint",
|
|
2416
|
-
);
|
|
2417
|
-
}
|
|
2418
|
-
} catch (err) {
|
|
2419
|
-
log.debug(
|
|
2420
|
-
{ err },
|
|
2421
|
-
"Failed to notify platform of Slack activity for idle sleep",
|
|
2422
|
-
);
|
|
2423
|
-
}
|
|
2424
|
-
}
|
|
2425
|
-
|
|
2426
|
-
async function startSlackSocket(): Promise<void> {
|
|
2427
|
-
const generation = ++slackStartGeneration;
|
|
2428
|
-
if (slackSocketClient) {
|
|
2429
|
-
slackSocketClient.stop();
|
|
2430
|
-
slackSocketClient = null;
|
|
2431
|
-
}
|
|
2432
|
-
|
|
2433
|
-
const botToken = await credentialCache.get(
|
|
2434
|
-
credentialKey("slack_channel", "bot_token"),
|
|
2435
|
-
);
|
|
2436
|
-
const appToken = await credentialCache.get(
|
|
2437
|
-
credentialKey("slack_channel", "app_token"),
|
|
2438
|
-
);
|
|
2439
|
-
// A newer call started while we awaited credentials, so let it own the
|
|
2440
|
-
// client. Everything below is synchronous, so one check suffices.
|
|
2441
|
-
if (generation !== slackStartGeneration) {
|
|
2442
|
-
return;
|
|
2443
|
-
}
|
|
2444
|
-
if (!botToken || !appToken) return;
|
|
2445
|
-
|
|
2446
|
-
const threadModeRaw = configFileCache.getString("slack", "threadMode");
|
|
2447
|
-
const threadMode =
|
|
2448
|
-
threadModeRaw === "mention_only" ||
|
|
2449
|
-
threadModeRaw === "mention_then_thread"
|
|
2450
|
-
? threadModeRaw
|
|
2451
|
-
: "mention_then_thread";
|
|
2452
|
-
|
|
2453
|
-
slackSocketClient = createSlackSocketModeClient(
|
|
2454
|
-
{ appToken, botToken, gatewayConfig: config, threadMode },
|
|
2455
|
-
(normalized) => {
|
|
2456
|
-
// Notify the cloud of inbound activity so the idle-sleep timer
|
|
2457
|
-
// is reset for this assistant (fire-and-forget).
|
|
2458
|
-
notifyRecordActivity();
|
|
2459
|
-
|
|
2460
|
-
const { threadTs, channel } = normalized;
|
|
2461
|
-
const params = new URLSearchParams({ channel });
|
|
2462
|
-
if (threadTs) params.set("threadTs", threadTs);
|
|
2463
|
-
// For non-threaded DMs, pass the original message ts so the runtime
|
|
2464
|
-
// can target it for emoji-based thinking indicators.
|
|
2465
|
-
const origMessageTs = normalized.event.source.messageId;
|
|
2466
|
-
if (!threadTs && origMessageTs) params.set("messageTs", origMessageTs);
|
|
2467
|
-
const replyCallbackUrl = `${config.gatewayInternalBaseUrl}/deliver/slack?${params}`;
|
|
2468
|
-
|
|
2469
|
-
const refersToAnotherMessage = eventRefersToAnotherMessage(
|
|
2470
|
-
normalized.event.message,
|
|
2471
|
-
);
|
|
2472
|
-
const slackSourceMetadata = buildSlackSourceMetadata(normalized);
|
|
2473
|
-
|
|
2474
|
-
// Handle /new command — reset conversation before it reaches the runtime
|
|
2475
|
-
if (isNewCommand(normalized.event.message.content)) {
|
|
2476
|
-
handleNewCommand(
|
|
2477
|
-
config,
|
|
2478
|
-
"slack",
|
|
2479
|
-
normalized.event.message.conversationExternalId,
|
|
2480
|
-
async (text) => {
|
|
2481
|
-
await fetchImpl("https://slack.com/api/chat.postMessage", {
|
|
2482
|
-
method: "POST",
|
|
2483
|
-
headers: {
|
|
2484
|
-
Authorization: `Bearer ${botToken}`,
|
|
2485
|
-
"Content-Type": "application/json",
|
|
2486
|
-
},
|
|
2487
|
-
body: JSON.stringify({
|
|
2488
|
-
channel,
|
|
2489
|
-
text,
|
|
2490
|
-
...(threadTs ? { thread_ts: threadTs } : {}),
|
|
2491
|
-
}),
|
|
2492
|
-
});
|
|
2493
|
-
},
|
|
2494
|
-
log,
|
|
2495
|
-
threadTs,
|
|
2496
|
-
);
|
|
2497
|
-
return;
|
|
2498
|
-
}
|
|
2499
|
-
|
|
2500
|
-
const forward = async () => {
|
|
2501
|
-
// Seed contact channel for the Slack actor (dual-write, fire-and-forget).
|
|
2502
|
-
// Covers both DMs (externalChatId = DM channel) and workspace messages.
|
|
2503
|
-
// Bot/app senders are classified as 'assistant' contacts with a
|
|
2504
|
-
// provenance note instead of the default 'human'.
|
|
2505
|
-
// An unattributed event (a delete Slack names no human author for)
|
|
2506
|
-
// carries the channel's synthetic system id, not a person; seeding
|
|
2507
|
-
// a contact from it would mint a record for nobody.
|
|
2508
|
-
if (
|
|
2509
|
-
normalized.event.actor.actorExternalId &&
|
|
2510
|
-
!normalized.event.source.actorUnattributed
|
|
2511
|
-
) {
|
|
2512
|
-
void upsertContactChannel({
|
|
2513
|
-
sourceChannel: "slack",
|
|
2514
|
-
externalUserId: normalized.event.actor.actorExternalId,
|
|
2515
|
-
...(normalized.event.source.chatType === "im"
|
|
2516
|
-
? {
|
|
2517
|
-
externalChatId:
|
|
2518
|
-
normalized.event.message.conversationExternalId,
|
|
2519
|
-
}
|
|
2520
|
-
: {}),
|
|
2521
|
-
displayName: normalized.event.actor.displayName,
|
|
2522
|
-
username: normalized.event.actor.username,
|
|
2523
|
-
...(normalized.botSender
|
|
2524
|
-
? {
|
|
2525
|
-
contactType: "assistant" as const,
|
|
2526
|
-
notes: slackBotContactNote(normalized.botSender),
|
|
2527
|
-
}
|
|
2528
|
-
: {}),
|
|
2529
|
-
}).catch(() => {});
|
|
2530
|
-
}
|
|
2531
|
-
|
|
2532
|
-
try {
|
|
2533
|
-
// Download and upload attachments if present. An event that acts
|
|
2534
|
-
// on another message brings no media of its own.
|
|
2535
|
-
let attachmentIds: string[] | undefined;
|
|
2536
|
-
const eventAttachments = normalized.event.message.attachments;
|
|
2537
|
-
if (
|
|
2538
|
-
eventAttachments &&
|
|
2539
|
-
eventAttachments.length > 0 &&
|
|
2540
|
-
normalized.slackFiles &&
|
|
2541
|
-
!refersToAnotherMessage
|
|
2542
|
-
) {
|
|
2543
|
-
// Guardian-actor bypass: when the Slack sender is the
|
|
2544
|
-
// assistant's owner, the upload is marked trustedSource so the
|
|
2545
|
-
// assistant accepts arbitrary MIME types and extensions
|
|
2546
|
-
// (e.g. .mkv, .dmg) for downstream processing. Resolved once
|
|
2547
|
-
// per message — the assistant re-checks gateway-service auth
|
|
2548
|
-
// before honoring the flag, so impersonation is not possible.
|
|
2549
|
-
// Lookup failures (e.g. assistant.db unavailable) default to
|
|
2550
|
-
// strict handling so non-guardian uploads still flow through
|
|
2551
|
-
// the normal validation path instead of being dropped.
|
|
2552
|
-
const slackActorId = normalized.event.actor.actorExternalId;
|
|
2553
|
-
let isGuardianActor = false;
|
|
2554
|
-
if (slackActorId) {
|
|
2555
|
-
try {
|
|
2556
|
-
isGuardianActor = !!(await findGuardianForChannelActor(
|
|
2557
|
-
"slack",
|
|
2558
|
-
slackActorId,
|
|
2559
|
-
));
|
|
2560
|
-
} catch (err) {
|
|
2561
|
-
log.warn(
|
|
2562
|
-
{ err, slackActorId },
|
|
2563
|
-
"Guardian lookup failed; defaulting to strict attachment validation",
|
|
2564
|
-
);
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
|
|
2568
|
-
const result = await ingestAttachments(
|
|
2569
|
-
config,
|
|
2570
|
-
"slack",
|
|
2571
|
-
eventAttachments,
|
|
2572
|
-
log,
|
|
2573
|
-
{
|
|
2574
|
-
download: (att, maxBytes) => {
|
|
2575
|
-
const slackFile = normalized.slackFiles?.get(att.fileId);
|
|
2576
|
-
if (!slackFile) {
|
|
2577
|
-
throw new Error(
|
|
2578
|
-
`No SlackFile found for attachment ${att.fileId}`,
|
|
2579
|
-
);
|
|
2580
|
-
}
|
|
2581
|
-
return downloadSlackFile(slackFile, botToken, maxBytes);
|
|
2582
|
-
},
|
|
2583
|
-
upload: (downloaded) =>
|
|
2584
|
-
uploadAttachment(
|
|
2585
|
-
config,
|
|
2586
|
-
{ ...downloaded, trustedSource: isGuardianActor },
|
|
2587
|
-
{ skipCircuitBreaker: true },
|
|
2588
|
-
),
|
|
2589
|
-
failurePolicy: { mode: "skip" },
|
|
2590
|
-
},
|
|
2591
|
-
);
|
|
2592
|
-
attachmentIds = result.attachmentIds;
|
|
2593
|
-
normalized.event.message.content = appendFailedAttachmentNotice(
|
|
2594
|
-
normalized.event.message.content,
|
|
2595
|
-
result,
|
|
2596
|
-
);
|
|
2597
|
-
}
|
|
2598
|
-
|
|
2599
|
-
await handleInbound(config, normalized.event, {
|
|
2600
|
-
replyCallbackUrl,
|
|
2601
|
-
routingOverride: normalized.routing,
|
|
2602
|
-
...(Object.keys(slackSourceMetadata).length > 0
|
|
2603
|
-
? { sourceMetadata: slackSourceMetadata }
|
|
2604
|
-
: {}),
|
|
2605
|
-
...(attachmentIds && attachmentIds.length > 0
|
|
2606
|
-
? { attachmentIds }
|
|
2607
|
-
: {}),
|
|
2608
|
-
}).catch((err) => {
|
|
2609
|
-
log.error(
|
|
2610
|
-
{ err, channel, threadTs },
|
|
2611
|
-
"Failed to forward Slack event to runtime",
|
|
2612
|
-
);
|
|
2613
|
-
});
|
|
2614
|
-
} catch (err) {
|
|
2615
|
-
log.error(
|
|
2616
|
-
{ err, channel, threadTs },
|
|
2617
|
-
"Failed to process Slack event — delivering message without attachments",
|
|
2618
|
-
);
|
|
2619
|
-
await handleInbound(config, normalized.event, {
|
|
2620
|
-
replyCallbackUrl,
|
|
2621
|
-
routingOverride: normalized.routing,
|
|
2622
|
-
...(Object.keys(slackSourceMetadata).length > 0
|
|
2623
|
-
? { sourceMetadata: slackSourceMetadata }
|
|
2624
|
-
: {}),
|
|
2625
|
-
}).catch((fwdErr) => {
|
|
2626
|
-
log.error(
|
|
2627
|
-
{ err: fwdErr, channel, threadTs },
|
|
2628
|
-
"Failed to forward Slack event to runtime (fallback)",
|
|
2629
|
-
);
|
|
2630
|
-
});
|
|
2631
|
-
}
|
|
2632
|
-
};
|
|
2633
|
-
|
|
2634
|
-
// Slack thread/DM context is now assembled on the daemon from
|
|
2635
|
-
// persisted message rows (see `assembleSlackChronologicalMessages`
|
|
2636
|
-
// in the assistant), so the gateway no longer fetches per-turn
|
|
2637
|
-
// thread/DM context to inject as transport hints.
|
|
2638
|
-
void slackForwardQueue
|
|
2639
|
-
.enqueue(normalized.event.message.conversationExternalId, forward)
|
|
2640
|
-
.catch((err) => {
|
|
2641
|
-
log.error(
|
|
2642
|
-
{ err, channel, threadTs },
|
|
2643
|
-
"Unhandled error in Slack forward",
|
|
2644
|
-
);
|
|
2645
|
-
});
|
|
2646
|
-
|
|
2647
|
-
// Approval message replacement is handled by the assistant's
|
|
2648
|
-
// direct Slack delivery path (messaging/providers/slack/send.ts).
|
|
2649
|
-
},
|
|
2650
|
-
);
|
|
2651
|
-
|
|
2652
|
-
slackSocketClient.start().catch((err) => {
|
|
2653
|
-
log.error({ err }, "Failed to start Slack Socket Mode client");
|
|
2654
|
-
});
|
|
2655
|
-
log.info("Slack Socket Mode client started");
|
|
2656
|
-
}
|
|
2657
|
-
|
|
2658
|
-
// ── Discord Gateway lifecycle ──
|
|
2659
|
-
// Credential-gated: the client exists only while a
|
|
2660
|
-
// `discord_channel:bot_token` credential does. There is no feature flag, and
|
|
2661
|
-
// removing the credential tears the connection down on the next watcher
|
|
2662
|
-
// tick. Whether Discord is offered for setup is a separate question, decided
|
|
2663
|
-
// by BASE_AVAILABLE_CHANNELS in the daemon, which lists it: a channel can be
|
|
2664
|
-
// offered while no credential is stored, and the connection is what a stored
|
|
2665
|
-
// one buys.
|
|
2666
|
-
//
|
|
2667
|
-
// Startup is the credential watcher's initial poll: it diffs against an
|
|
2668
|
-
// empty baseline, so a token already stored at boot surfaces as
|
|
2669
|
-
// `changed.has("discord_channel")` and starts the client — the same path
|
|
2670
|
-
// the Slack socket boots through. This requires `discord_channel` to be
|
|
2671
|
-
// registered in ALL_CREDENTIAL_SPECS (credential-reader.ts); the watcher
|
|
2672
|
-
// only reads services listed there, and the registration is pinned by
|
|
2673
|
-
// credential-reader.test.ts.
|
|
2674
|
-
let discordGatewayClient: DiscordGatewayClient | null = null;
|
|
2675
|
-
const discordForwardQueue = createConversationTaskQueue();
|
|
2676
|
-
|
|
2677
|
-
async function startDiscordGateway(): Promise<void> {
|
|
2678
|
-
if (discordGatewayClient) {
|
|
2679
|
-
discordGatewayClient.stop();
|
|
2680
|
-
discordGatewayClient = null;
|
|
2681
|
-
}
|
|
2682
|
-
|
|
2683
|
-
const botToken = await credentialCache.get(
|
|
2684
|
-
credentialKey("discord_channel", "bot_token"),
|
|
2685
|
-
);
|
|
2686
|
-
if (!botToken) {
|
|
2687
|
-
return;
|
|
2688
|
-
}
|
|
2689
|
-
|
|
2690
|
-
// Room admission defers to Discord's own channel permissions. A
|
|
2691
|
-
// non-empty legacy allow-list is persisted operator intent, so it keeps
|
|
2692
|
-
// gating rooms until the operator clears it; the log names the way out.
|
|
2693
|
-
const readLegacyAllowedChannelIds = (): ReadonlySet<string> | undefined => {
|
|
2694
|
-
const ids =
|
|
2695
|
-
configFileCache.getStringArray("discord", "allowedChannelIds") ?? [];
|
|
2696
|
-
return ids.length > 0 ? new Set(ids) : undefined;
|
|
2697
|
-
};
|
|
2698
|
-
if (readLegacyAllowedChannelIds() !== undefined) {
|
|
2699
|
-
log.warn(
|
|
2700
|
-
"discord.allowedChannelIds is a legacy setting and is still " +
|
|
2701
|
-
"enforced: the bot answers mentions only in listed channels. To " +
|
|
2702
|
-
"adopt Discord's own permission model, scope the bot with View " +
|
|
2703
|
-
"Channel permissions in Discord and remove the config entry.",
|
|
2704
|
-
);
|
|
2705
|
-
}
|
|
2706
|
-
|
|
2707
|
-
discordGatewayClient = new DiscordGatewayClient(
|
|
2708
|
-
{
|
|
2709
|
-
botToken,
|
|
2710
|
-
readLegacyAllowedChannelIds,
|
|
2711
|
-
},
|
|
2712
|
-
createDiscordInboundEventHandler({
|
|
2713
|
-
config,
|
|
2714
|
-
log,
|
|
2715
|
-
notifyRecordActivity,
|
|
2716
|
-
forwardQueue: discordForwardQueue,
|
|
2717
|
-
}),
|
|
2718
|
-
);
|
|
2719
|
-
|
|
2720
|
-
discordGatewayClient.start().catch((err) => {
|
|
2721
|
-
log.error({ err }, "Failed to start Discord Gateway client");
|
|
2722
|
-
});
|
|
2723
|
-
log.info("Discord Gateway client started");
|
|
2724
|
-
}
|
|
2725
|
-
|
|
2726
|
-
/**
|
|
2727
|
-
* Fingerprint of the Telegram bot token the dedup cache's watermark belongs
|
|
2728
|
-
* to. Null while no token is stored, which is itself a bot change: the next
|
|
2729
|
-
* bot to arrive must not meet the departed one's mark.
|
|
2730
|
-
*/
|
|
2731
|
-
let lastTelegramTokenFingerprint: string | null = null;
|
|
2732
|
-
|
|
2733
|
-
const credentialWatcher = new CredentialWatcher((event) => {
|
|
2734
|
-
const changed = detectCredentialChanges(event, log);
|
|
2735
|
-
|
|
2736
|
-
// Invalidate the credential cache so subsequent reads pick up fresh values
|
|
2737
|
-
if (changed.size > 0) {
|
|
2738
|
-
credentialCache.invalidate();
|
|
2739
|
-
}
|
|
2740
|
-
|
|
2741
|
-
// Update integration readiness flags from the credential event
|
|
2742
|
-
const telegramCreds = event.credentials.get("telegram");
|
|
2743
|
-
telegramReady = !!(
|
|
2744
|
-
telegramCreds?.bot_token && telegramCreds?.webhook_secret
|
|
2745
|
-
);
|
|
2746
|
-
|
|
2747
|
-
const whatsappCreds = event.credentials.get("whatsapp");
|
|
2748
|
-
whatsappReady = !!(
|
|
2749
|
-
whatsappCreds?.phone_number_id && whatsappCreds?.access_token
|
|
2750
|
-
);
|
|
2751
|
-
|
|
2752
|
-
const cadetCreds = event.credentials.get("cadet");
|
|
2753
|
-
cadetReady = !!cadetCreds?.assistant_api_key;
|
|
2754
|
-
if (cadetReady) {
|
|
2755
|
-
// Re-run validate when the API key / base URL change so a warm-pool
|
|
2756
|
-
// claim does not keep the previous assistant's bound owner ids.
|
|
2757
|
-
void ensureCloudIdentityIds();
|
|
2758
|
-
}
|
|
2759
|
-
const twilioCreds = event.credentials.get("twilio");
|
|
2760
|
-
|
|
2761
|
-
// Side effects keyed by service name
|
|
2762
|
-
// `update_id` is a per-bot sequence, so a replacement bot starts below the
|
|
2763
|
-
// previous one's high-water mark and every inbound would be rejected as an
|
|
2764
|
-
// already-processed replay and answered 200. Forgetting the mark is what
|
|
2765
|
-
// keeps delivery working across a bot swap.
|
|
2766
|
-
//
|
|
2767
|
-
// Keyed on the token itself rather than on `changed`. Every `keys.enc`
|
|
2768
|
-
// write polls with `forceChanged`, which reports every configured service
|
|
2769
|
-
// as changed even when its plaintext is identical, so re-saving an
|
|
2770
|
-
// unrelated credential would otherwise clear replay protection for a bot
|
|
2771
|
-
// that never moved and let a delayed retry be processed twice.
|
|
2772
|
-
const telegramTokenFingerprint = telegramCreds?.bot_token
|
|
2773
|
-
? new Bun.CryptoHasher("sha256")
|
|
2774
|
-
.update(telegramCreds.bot_token)
|
|
2775
|
-
.digest("hex")
|
|
2776
|
-
: null;
|
|
2777
|
-
if (telegramTokenFingerprint !== lastTelegramTokenFingerprint) {
|
|
2778
|
-
lastTelegramTokenFingerprint = telegramTokenFingerprint;
|
|
2779
|
-
telegramDedupCache.reset();
|
|
2780
|
-
}
|
|
2781
|
-
if (changed.has("telegram") && telegramReady) {
|
|
2782
|
-
registerTelegramCommands();
|
|
2783
|
-
reconcileTelegramWebhook(telegramCaches).catch((err) => {
|
|
2784
|
-
log.error(
|
|
2785
|
-
{ err },
|
|
2786
|
-
"Failed to reconcile Telegram webhook after credential change",
|
|
2787
|
-
);
|
|
2788
|
-
});
|
|
2789
|
-
}
|
|
2790
|
-
if (changed.has("discord_channel")) {
|
|
2791
|
-
startDiscordGateway().catch((err) => {
|
|
2792
|
-
log.error(
|
|
2793
|
-
{ err },
|
|
2794
|
-
"Failed to restart Discord Gateway after credential change",
|
|
2795
|
-
);
|
|
2796
|
-
});
|
|
2797
|
-
}
|
|
2798
|
-
|
|
2799
|
-
if (changed.has("slack_channel")) {
|
|
2800
|
-
startSlackSocket().catch((err) => {
|
|
2801
|
-
log.error(
|
|
2802
|
-
{ err },
|
|
2803
|
-
"Failed to restart Slack Socket Mode after credential change",
|
|
2804
|
-
);
|
|
2805
|
-
});
|
|
2806
|
-
}
|
|
2807
|
-
|
|
2808
|
-
if (changed.has("twilio")) {
|
|
2809
|
-
maybeStartTunnelForTwilio("twilio credentials changed", twilioCreds);
|
|
2810
|
-
syncConfiguredTwilioPhoneNumberWebhooks({
|
|
2811
|
-
credentials: credentialCache,
|
|
2812
|
-
configFile: configFileCache,
|
|
2813
|
-
}).catch((err) => {
|
|
2814
|
-
log.warn({ err }, "Twilio webhook sync failed after credential change");
|
|
2815
|
-
});
|
|
2816
|
-
}
|
|
2817
|
-
|
|
2818
|
-
// Register email callback route with the cloud so inbound email
|
|
2819
|
-
// webhooks are forwarded to this gateway (same pattern as Telegram).
|
|
2820
|
-
// Fires on initial credential load and whenever cadet credentials change
|
|
2821
|
-
// (key rotation, late provisioning).
|
|
2822
|
-
if (changed.has("cadet")) {
|
|
2823
|
-
tunnelClient?.refreshCredentials("cadet credentials changed");
|
|
2824
|
-
registerEmailCallbackRoute({
|
|
2825
|
-
credentials: credentialCache,
|
|
2826
|
-
configFile: configFileCache,
|
|
2827
|
-
}).catch((err) => {
|
|
2828
|
-
log.error(
|
|
2829
|
-
{ err },
|
|
2830
|
-
"Failed to register email callback route after credential change",
|
|
2831
|
-
);
|
|
2832
|
-
});
|
|
825
|
+
const stopSlackClient = startSlackGateway();
|
|
2833
826
|
|
|
2834
|
-
|
|
2835
|
-
// the cloud callback fallback applies: a cloud connection arriving
|
|
2836
|
-
// or rotating after Telegram setup must repoint Telegram at the cloud
|
|
2837
|
-
// callback route without waiting for an unrelated Telegram or ingress
|
|
2838
|
-
// change, or a system wake. Skipped when telegram credentials changed in
|
|
2839
|
-
// the same event, since that branch already reconciled above.
|
|
2840
|
-
if (telegramReady && !changed.has("telegram")) {
|
|
2841
|
-
reconcileTelegramWebhook(telegramCaches).catch((err) => {
|
|
2842
|
-
log.error(
|
|
2843
|
-
{ err },
|
|
2844
|
-
"Failed to reconcile Telegram webhook after cadet credential change",
|
|
2845
|
-
);
|
|
2846
|
-
});
|
|
2847
|
-
}
|
|
2848
|
-
}
|
|
2849
|
-
});
|
|
827
|
+
const stopDiscordClient = startDiscordGateway();
|
|
2850
828
|
|
|
2851
829
|
const twilioStartupCredentials =
|
|
2852
830
|
await readTwilioCredentialsForTunnelStartup();
|
|
2853
|
-
if (tunnelClient) {
|
|
2854
|
-
await clearManagedPublicBaseUrl(configFileCache).catch((err) => {
|
|
2855
|
-
log.error({ err }, "Failed to clear stale Tunnel public URL");
|
|
2856
|
-
});
|
|
2857
|
-
}
|
|
2858
831
|
maybeStartTunnelForTwilio("startup", twilioStartupCredentials);
|
|
2859
832
|
// Tunnel is also the browser's ingress for web live voice, so bring the tunnel
|
|
2860
833
|
// up at startup for every assistant (not just for Twilio).
|
|
2861
834
|
startTunnelForLiveVoice("startup");
|
|
2862
835
|
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
const onlyTunnelPublicBaseUrlChanged =
|
|
2874
|
-
isOnlyTunnelPublicBaseUrlChange(event);
|
|
2875
|
-
// A Tunnel-only publicBaseUrl change is the tunnel registering. While
|
|
2876
|
-
// `tunnel-webhooks` is on that URL is what Telegram must be pointed at, so
|
|
2877
|
-
// the suppression that keeps a tunnel address out of provider config is
|
|
2878
|
-
// exactly what has to lift.
|
|
2879
|
-
const telegramSuppressed =
|
|
2880
|
-
onlyTunnelPublicBaseUrlChanged &&
|
|
2881
|
-
!isFeatureFlagEnabled("tunnel-webhooks");
|
|
2882
|
-
|
|
2883
|
-
if (
|
|
2884
|
-
event.changedKeys.has("ingress") &&
|
|
2885
|
-
!telegramSuppressed &&
|
|
2886
|
-
isTelegramConfigured()
|
|
2887
|
-
) {
|
|
2888
|
-
reconcileTelegramWebhook(telegramCaches).catch((err) => {
|
|
2889
|
-
log.error(
|
|
2890
|
-
{ err },
|
|
2891
|
-
"Failed to reconcile Telegram webhook after ingress URL change",
|
|
2892
|
-
);
|
|
2893
|
-
});
|
|
2894
|
-
}
|
|
2895
|
-
|
|
2896
|
-
if (shouldSyncTwilioPhoneWebhooksAfterConfigChange(event)) {
|
|
2897
|
-
syncConfiguredTwilioPhoneNumberWebhooks({
|
|
2898
|
-
credentials: credentialCache,
|
|
2899
|
-
configFile: configFileCache,
|
|
2900
|
-
}).catch((err) => {
|
|
2901
|
-
log.warn({ err }, "Twilio webhook sync failed after config change");
|
|
2902
|
-
});
|
|
2903
|
-
}
|
|
2904
|
-
|
|
2905
|
-
if (event.changedKeys.has("twilio")) {
|
|
2906
|
-
maybeStartTunnelForTwilio("twilio config changed");
|
|
2907
|
-
}
|
|
2908
|
-
|
|
2909
|
-
if (event.changedKeys.has("slack")) {
|
|
2910
|
-
startSlackSocket().catch((err) => {
|
|
2911
|
-
log.error(
|
|
2912
|
-
{ err },
|
|
2913
|
-
"Failed to restart Slack Socket Mode after config change",
|
|
2914
|
-
);
|
|
2915
|
-
});
|
|
2916
|
-
}
|
|
2917
|
-
|
|
2918
|
-
// Side effect: re-register email callback when ingress URL changes so
|
|
2919
|
-
// the cloud callback route points at the new self-hosted URL.
|
|
2920
|
-
if (
|
|
2921
|
-
event.changedKeys.has("ingress") &&
|
|
2922
|
-
!onlyTunnelPublicBaseUrlChanged &&
|
|
2923
|
-
cadetReady
|
|
2924
|
-
) {
|
|
2925
|
-
registerEmailCallbackRoute({
|
|
2926
|
-
credentials: credentialCache,
|
|
2927
|
-
configFile: configFileCache,
|
|
2928
|
-
}).catch((err) => {
|
|
2929
|
-
log.error(
|
|
2930
|
-
{ err },
|
|
2931
|
-
"Failed to re-register email callback route after ingress URL change",
|
|
2932
|
-
);
|
|
2933
|
-
});
|
|
2934
|
-
}
|
|
2935
|
-
});
|
|
2936
|
-
|
|
2937
|
-
configFileWatcher.start();
|
|
2938
|
-
|
|
2939
|
-
// ── IPC server ──
|
|
2940
|
-
const ipcServer = new GatewayIpcServer([
|
|
2941
|
-
...featureFlagRoutes,
|
|
2942
|
-
...contactRoutes,
|
|
2943
|
-
...inviteRoutes,
|
|
2944
|
-
...verificationSessionRoutes,
|
|
2945
|
-
...guardianRequestRoutes,
|
|
2946
|
-
...slackThreadRoutes,
|
|
2947
|
-
...thresholdRoutes,
|
|
2948
|
-
...admissionPolicyRoutes,
|
|
2949
|
-
...channelPermissionRoutes,
|
|
2950
|
-
...trustVerdictRoutes,
|
|
2951
|
-
...guardianDeliveryRoutes,
|
|
2952
|
-
...riskClassificationRoutes,
|
|
2953
|
-
...createLogTailRoutes(config),
|
|
2954
|
-
...createChannelSocketHealthRoutes({
|
|
2955
|
-
slack: () => slackSocketClient,
|
|
2956
|
-
discord: () => discordGatewayClient,
|
|
2957
|
-
}),
|
|
2958
|
-
...trustRulesRoutes,
|
|
2959
|
-
...createTunnelRoutes(tunnelClient),
|
|
2960
|
-
...createWebhookRouteRoutes(),
|
|
2961
|
-
...createCredentialRequestIpcRoutes(
|
|
2962
|
-
config,
|
|
2963
|
-
configFileCache,
|
|
2964
|
-
ensurePublicIngressLiveForCredentialLink,
|
|
2965
|
-
),
|
|
2966
|
-
]);
|
|
2967
|
-
ipcServer.start();
|
|
2968
|
-
|
|
2969
|
-
void refreshRouteSchema();
|
|
2970
|
-
|
|
2971
|
-
let tunnelWebhooksEnabled = isFeatureFlagEnabled("tunnel-webhooks");
|
|
2972
|
-
emitFlagChanged = () => {
|
|
2973
|
-
ipcServer.emit("feature_flags_changed");
|
|
2974
|
-
// The flag decides the shape of the advertised rules, so flipping it has
|
|
2975
|
-
// to re-advertise rather than wait out the periodic tunnel refresh.
|
|
2976
|
-
const enabled = isFeatureFlagEnabled("tunnel-webhooks");
|
|
2977
|
-
if (enabled !== tunnelWebhooksEnabled) {
|
|
2978
|
-
tunnelWebhooksEnabled = enabled;
|
|
2979
|
-
tunnelClient?.requestRulesRefresh("tunnel-webhooks-flag-changed");
|
|
2980
|
-
// The flag also decides which address a pod hands Telegram, and nothing
|
|
2981
|
-
// else re-runs the reconcile when it moves. One call covers a flip in
|
|
2982
|
-
// either direction because the resolver reads the new value.
|
|
2983
|
-
if (isTelegramConfigured()) {
|
|
2984
|
-
reconcileTelegramWebhook(telegramCaches).catch((err) => {
|
|
2985
|
-
log.error(
|
|
2986
|
-
{ err },
|
|
2987
|
-
"Failed to reconcile Telegram webhook after tunnel-webhooks flag change",
|
|
2988
|
-
);
|
|
2989
|
-
});
|
|
2990
|
-
}
|
|
2991
|
-
}
|
|
2992
|
-
};
|
|
2993
|
-
|
|
2994
|
-
const featureFlagWatcher = new FeatureFlagWatcher({
|
|
2995
|
-
onChanged: emitFlagChanged,
|
|
2996
|
-
});
|
|
2997
|
-
featureFlagWatcher.start();
|
|
2998
|
-
|
|
2999
|
-
// ── Sleep/wake detection ──
|
|
3000
|
-
// Detect system sleep/wake transitions and force-reconnect channels
|
|
3001
|
-
// that may have stale connections after the OS suspended the process.
|
|
3002
|
-
const sleepWakeDetector = new SleepWakeDetector(() => {
|
|
3003
|
-
log.info("System wake detected — reconnecting channels");
|
|
3004
|
-
|
|
3005
|
-
// Force-reconnect Slack WebSocket (may be half-open after sleep)
|
|
3006
|
-
slackSocketClient?.forceReconnect();
|
|
3007
|
-
|
|
3008
|
-
// Invalidate caches so next read picks up any config changes (e.g. a new tunnel URL)
|
|
3009
|
-
configFileCache.invalidate();
|
|
3010
|
-
credentialCache.invalidate();
|
|
3011
|
-
|
|
3012
|
-
// Re-register Telegram webhook with current ingress URL
|
|
3013
|
-
if (telegramReady) {
|
|
3014
|
-
reconcileTelegramWebhook(telegramCaches).catch((err) => {
|
|
3015
|
-
log.error({ err }, "Failed to reconcile Telegram webhook after wake");
|
|
3016
|
-
});
|
|
3017
|
-
}
|
|
3018
|
-
});
|
|
3019
|
-
sleepWakeDetector.start();
|
|
836
|
+
const tasks: (() => StopTask | Promise<StopTask>)[] = [
|
|
837
|
+
startCredentialWatcher,
|
|
838
|
+
startIpcServer,
|
|
839
|
+
startConfigFileWatcher,
|
|
840
|
+
startSleepWakeDetector,
|
|
841
|
+
startInboundEventExpirationCleanup,
|
|
842
|
+
];
|
|
843
|
+
const shutdownTasks: StopTask[] = await Promise.all(
|
|
844
|
+
tasks.map((task) => task()),
|
|
845
|
+
);
|
|
3020
846
|
|
|
3021
847
|
process.on("SIGTERM", () => {
|
|
3022
848
|
log.info("SIGTERM received, starting graceful shutdown");
|
|
3023
849
|
draining = true;
|
|
3024
|
-
const
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
3035
|
-
clearInterval(inboundDedupCleanup);
|
|
3036
|
-
if (slackSocketClient) {
|
|
3037
|
-
slackSocketClient.stop();
|
|
3038
|
-
slackSocketClient = null;
|
|
3039
|
-
}
|
|
3040
|
-
if (discordGatewayClient) {
|
|
3041
|
-
discordGatewayClient.stop();
|
|
3042
|
-
discordGatewayClient = null;
|
|
3043
|
-
}
|
|
850
|
+
const allShutdownTasks: StopTask[] = [
|
|
851
|
+
() => tunnelClient.stop(),
|
|
852
|
+
stopDiscordClient,
|
|
853
|
+
stopSlackClient,
|
|
854
|
+
() => telegramDedupCache.stopCleanup(),
|
|
855
|
+
() => whatsappDedupCache.stopCleanup(),
|
|
856
|
+
() => emailDedupCache.stopCleanup(),
|
|
857
|
+
...shutdownTasks,
|
|
858
|
+
];
|
|
859
|
+
|
|
860
|
+
const shutdownPromises = allShutdownTasks.map((stopTask) => stopTask());
|
|
3044
861
|
setTimeout(() => {
|
|
3045
862
|
log.info("Drain window elapsed, stopping server");
|
|
3046
|
-
void Promise.allSettled(
|
|
863
|
+
void Promise.allSettled(shutdownPromises).then(() => {
|
|
3047
864
|
server.stop(true);
|
|
3048
865
|
process.exit(0);
|
|
3049
866
|
});
|