π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(gateway): let a gateway pull the connections it should hold (#18680)
Rdmclin271b0e4fc280b
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/gatewayDesiredConnections.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/gatewayDesiredConnections.test.tsnew file mode 100644index 00000000000..3f12ed76b7f--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/__tests__/gatewayDesiredConnections.test.ts@@ -0,0 +1,131 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { gatewayDesiredConnections } from '../gatewayDesiredConnections';++const { gatewayEnvState, hostConfigured, mockListDesired } = vi.hoisted(() => ({+ gatewayEnvState: {} as {+ MESSAGE_GATEWAY_ENABLED?: string;+ MESSAGE_GATEWAY_NODE_PULL_TOKEN?: string;+ MESSAGE_GATEWAY_SERVICE_TOKEN?: string;+ },+ hostConfigured: { value: true },+ mockListDesired: vi.fn(),+}));++vi.mock('@/envs/gateway', () => ({+ gatewayEnv: new Proxy(gatewayEnvState, {+ get: (target, prop: string) => target[prop as keyof typeof target],+ }),+}));++vi.mock('@/server/services/gateway', () => ({+ GatewayService: class {+ listDesiredConnectionsForHost = mockListDesired;+ },+}));++vi.mock('@/server/services/gateway/MessageGatewayClient', () => ({+ isMessageGatewayHostConfigured: () => hostConfigured.value,+}));++function buildContext(authHeader?: string) {+ return {+ body: (b: any, status: number) => new Response(b, { status }),+ json: (b: any, status = 200) => Response.json(b, { status }),+ req: {+ header: (name: string) => (name.toLowerCase() === 'authorization' ? authHeader : undefined),+ },+ } as any;+}++const PULL = 'Bearer node-pull-token';++describe('gatewayDesiredConnections', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ gatewayEnvState.MESSAGE_GATEWAY_ENABLED = '1';+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PULL_TOKEN = 'node-pull-token';+ gatewayEnvState.MESSAGE_GATEWAY_SERVICE_TOKEN = 'shared-service-token';+ hostConfigured.value = true;+ mockListDesired.mockResolvedValue({+ complete: true,+ connections: [],+ deferred: 0,+ excluded: 0,+ });+ });++ // The disabled short-circuit runs before the credential check on purpose: a+ // deployment with the gateway switched off should go quiet, not start 401-ing+ // a gateway that has not been told to stop yet.+ it('returns 204 when the gateway feature is off, before checking the credential', async () => {+ gatewayEnvState.MESSAGE_GATEWAY_ENABLED = undefined;+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PULL_TOKEN = undefined;++ const res = await gatewayDesiredConnections(buildContext());++ expect(res.status).toBe(204);+ expect(mockListDesired).not.toHaveBeenCalled();+ });++ it('returns a retryable 503 when no pull credential is configured', async () => {+ gatewayEnvState.MESSAGE_GATEWAY_NODE_PULL_TOKEN = undefined;++ const res = await gatewayDesiredConnections(buildContext(PULL));++ expect(res.status).toBe(503);+ expect(mockListDesired).not.toHaveBeenCalled();+ });++ // The point of the whole credential. The shared service token authenticates+ // the connection-management surface and is written into stored connect+ // payloads across the fleet; it must not open the one endpoint that returns+ // credentials rather than ids and states.+ it('rejects the shared service token', async () => {+ const res = await gatewayDesiredConnections(buildContext('Bearer shared-service-token'));++ expect(res.status).toBe(401);+ expect(mockListDesired).not.toHaveBeenCalled();+ });++ it.each([+ ['missing', undefined],+ ['wrong', 'Bearer nope'],+ ])('returns 401 on a %s credential', async (_label, authHeader) => {+ const res = await gatewayDesiredConnections(buildContext(authHeader));++ expect(res.status).toBe(401);+ expect(mockListDesired).not.toHaveBeenCalled();+ });++ // An empty list would tell the caller "hold nothing" and stop its retry.+ // "I do not route to you yet" is a different statement and has to stay+ // retryable, or a gateway that boots before its URL is configured never+ // recovers.+ it('returns a retryable 503 for a host this deployment does not route to', async () => {+ hostConfigured.value = false;++ const res = await gatewayDesiredConnections(buildContext(PULL));++ expect(res.status).toBe(503);+ expect(mockListDesired).not.toHaveBeenCalled();+ });++ // Nothing the caller writes picks the host. The credential does.+ it('serves the slice belonging to the credential that was presented', async () => {+ const payload = {+ complete: true,+ connections: [{ config: { connectionId: 'prov-1' }, ensure: true }],+ deferred: 0,+ excluded: 2,+ };+ mockListDesired.mockResolvedValue(payload);++ const res = await gatewayDesiredConnections(buildContext(PULL));++ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toEqual(payload);+ expect(mockListDesired).toHaveBeenCalledWith('node');+ });+});diff --git a/apps/server/src/router-hono/agent/handlers/gatewayDesiredConnections.ts b/apps/server/src/router-hono/agent/handlers/gatewayDesiredConnections.tsnew file mode 100644index 00000000000..e0ad2c02c3e--- /dev/null+++ b/apps/server/src/router-hono/agent/handlers/gatewayDesiredConnections.ts@@ -0,0 +1,91 @@+import debug from 'debug';+import type { Context } from 'hono';++import { gatewayEnv } from '@/envs/gateway';+import { GatewayService } from '@/server/services/gateway';+import {+ isMessageGatewayHostConfigured,+ type MessageGatewayHost,+} from '@/server/services/gateway/MessageGatewayClient';++const log = debug('lobe-server:agent:gateway-desired-connections');++/**+ * The host a presented credential speaks for.+ *+ * One credential, one host, and nothing the caller writes in the request takes+ * part. That is the whole mechanism: the server has to answer "which gateway+ * is asking" before it hands over that gateway's credentials, and a value the+ * caller supplies cannot answer it. A second pull-capable host gets its own+ * credential here β never a share of this one.+ */+function resolvePullHost(authorization: string | undefined): MessageGatewayHost | null {+ const nodeToken = gatewayEnv.MESSAGE_GATEWAY_NODE_PULL_TOKEN;+ if (nodeToken && authorization === `Bearer ${nodeToken}`) return 'node';+ return null;+}++/**+ * Hand a gateway the connect payloads it should currently be holding.+ *+ * This is how a gateway recovers from a restart. A container that just came+ * back up holds nothing, asks for this list, and rebuilds itself β the side+ * that establishes the connections is the same side that can see whether they+ * came up, so there is no reconciliation protocol to get wrong.+ *+ * The response body is exactly what the reconcile would have pushed:+ * `{ config, ensure }` per connection, the same shape as `POST /api/connections`+ * on the gateway. One builder feeds both paths on purpose β a second one would+ * drift, and the connection a gateway holds would then depend on who made it.+ *+ * Authenticated with a dedicated per-host credential rather than the shared+ * service token, because this is the one endpoint that returns credentials+ * rather than ids and states. The service token is written into every WeChat+ * connect payload as `webhookToken` and stored with the connection config, so+ * it lives across the gateway fleet's storage; making that same value a key+ * for reading every credential at once is a trade worth refusing for the cost+ * of one env var.+ *+ * Auth is inline, not a route middleware, so the disabled-feature 204+ * short-circuits before the credential check (same reasoning as+ * `gatewayCallback`).+ */+export async function gatewayDesiredConnections(c: Context): Promise<Response> {+ if (gatewayEnv.MESSAGE_GATEWAY_ENABLED !== '1') {+ return c.body(null, 204);+ }++ if (!gatewayEnv.MESSAGE_GATEWAY_NODE_PULL_TOKEN) {+ // Nothing can authenticate here yet. 503 keeps a gateway retrying until+ // the credential is configured, rather than reading a refusal as final.+ return c.json({ error: 'Service not configured' }, 503);+ }++ const host = resolvePullHost(c.req.header('authorization'));+ if (!host) {+ return c.json({ error: 'Unauthorized' }, 401);+ }++ // Configured to authenticate, but not to route anything here. An empty list+ // would say "hold nothing", which is a different claim from "I do not route+ // to you yet" β and the caller would stop retrying on it.+ if (!isMessageGatewayHostConfigured(host)) {+ log('host=%s is not configured on this deployment', host);+ return c.json({ error: `Message gateway host not configured: ${host}` }, 503);+ }++ const result = await new GatewayService().listDesiredConnectionsForHost(host);++ // Audit surface: the one place a host's whole credential set is handed out,+ // and the signal that the host restarted.+ log(+ 'gateway pull host=%s connections=%d excluded=%d deferred=%d complete=%s',+ host,+ result.connections.length,+ result.excluded,+ result.deferred,+ result.complete,+ );++ return c.json(result);+}diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.tsindex 987dab307a3..2bcb6f341f3 100644--- a/apps/server/src/router-hono/agent/index.ts+++ b/apps/server/src/router-hono/agent/index.ts@@ -5,6 +5,7 @@ import { execAgent } from './handlers/execAgent';import { finalizeAbandoned } from './handlers/finalizeAbandoned';import { gatewayCallback } from './handlers/gatewayCallback';import { gatewayCron } from './handlers/gatewayCron';+import { gatewayDesiredConnections } from './handlers/gatewayDesiredConnections';import { gatewayStart } from './handlers/gatewayStart';import { groupMemberCallback } from './handlers/groupMemberCallback';import { messengerInstall } from './handlers/messengerInstall';@@ -67,6 +68,11 @@ app.post(// (auth is inline so the disabled-feature 204 short-circuits before auth)app.post('/gateway/callback', gatewayCallback);+// POST /api/agent/gateway/desired-connections β a gateway pulls the connect+// payloads it should hold, so it can rebuild itself after a restart.+// (auth is inline for the same reason as the callback above)+app.post('/gateway/desired-connections', gatewayDesiredConnections);+// POST /api/agent/webhooks/bot-callback β agent step/completion webhooks (QStash)app.post('/webhooks/bot-callback', qstashAuth(), botCallback);diff --git a/apps/server/src/services/gateway/MessageGatewayClient.ts b/apps/server/src/services/gateway/MessageGatewayClient.tsindex cf4c0725a40..7a9b5cfe59a 100644--- a/apps/server/src/services/gateway/MessageGatewayClient.ts+++ b/apps/server/src/services/gateway/MessageGatewayClient.ts@@ -210,6 +210,25 @@ export class MessageGatewayClient {return res.json();}+ /**+ * What this gateway says it can do. Optional by design: the Cloudflare+ * gateway has no such endpoint, so anything unreachable, missing or+ * unparseable comes back as `null` β "makes no claim", never "claims+ * nothing". A caller must not read absence of information as a refusal.+ */+ async getCapabilities(): Promise<{ platforms?: string[] } | null> {+ try {+ const res = await this.fetch('/api/admin/capabilities');+ if (!res.ok) return null;+ const body = (await res.json()) as { platforms?: unknown };+ if (!Array.isArray(body?.platforms)) return null;+ return { platforms: body.platforms.filter((p): p is string => typeof p === 'string') };+ } catch (err) {+ log('Capabilities unavailable: %O', err);+ return null;+ }+ }+// βββ Internal HTTP βββprivate async fetch(path: string, init?: RequestInit): Promise<Response> {diff --git a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts b/apps/server/src/services/gateway/__tests__/GatewayService.test.tsindex f0e6b9d66e7..31335d3be76 100644--- a/apps/server/src/services/gateway/__tests__/GatewayService.test.ts+++ b/apps/server/src/services/gateway/__tests__/GatewayService.test.ts@@ -10,6 +10,7 @@ const mockGatewayClient = vi.hoisted(() => ({connect: vi.fn(),disconnect: vi.fn(),disconnectAll: vi.fn(),+ getCapabilities: vi.fn(),getRegisteredIds: vi.fn(),getStats: vi.fn(),getStatus: vi.fn(),@@ -29,6 +30,7 @@ const mockNodeGatewayClient = vi.hoisted(() => ({connect: vi.fn(),disconnect: vi.fn(),disconnectAll: vi.fn(),+ getCapabilities: vi.fn(),getRegisteredIds: vi.fn(),getStats: vi.fn(),getStatus: vi.fn(),@@ -201,6 +203,11 @@ describe('GatewayService', () => {mockFindByAgentId.mockResolvedValue([]);mockFindByIds.mockResolvedValue([]);mockFindEnabledByPlatformAndAppId.mockResolvedValue(null);+ // Default: neither host describes itself. The Cloudflare gateway has no+ // capabilities endpoint at all, so "makes no claim" is the normal case and+ // must never be read as "serves nothing".+ mockGatewayClient.getCapabilities.mockResolvedValue(null);+ mockNodeGatewayClient.getCapabilities.mockResolvedValue(null);// Default: admin snapshot unavailable β sync falls back to per-connection// getStatus and skips stale-connection cleanup (matches pre-reconciliation behavior).mockGatewayClient.getStats.mockRejectedValue(new Error('stats unavailable'));@@ -1540,4 +1547,459 @@ describe('GatewayService', () => {expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();});});++ // βββ Routing a platform to a host that cannot serve it βββ++ describe('platform capability guard', () => {+ const CONNECTION_ID = 'messenger:wechat:t1:user-u1';++ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockNodeGateway.configured = true;+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.isEnabled = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ });++ /** The default host is holding the WeChat poller; routing says it moves. */+ const defaultHostHoldsIt = () => {+ mockGatewayClient.getStats.mockResolvedValue({+ byPlatform: { wechat: 1 },+ connections: [+ {+ connectionId: CONNECTION_ID,+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });+ };++ // Draining into a host that rejects the platform is worse than doing+ // nothing: the connect meant to replace the connection fails, so it ends+ // up on neither host. A misrouted env var must be a no-op, not an outage.+ it('refuses to drain a platform off its host when the destination declines it', async () => {+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({+ platforms: ['whatsapp-baileys'],+ });+ defaultHostHoldsIt();++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).not.toHaveBeenCalled();+ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });++ // Same fixture, guard off β proves the case above is the guard talking and+ // not a setup that never had a teardown to begin with.+ it('performs the same move when the destination declares the platform', async () => {+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });+ defaultHostHoldsIt();++ await service.ensureRunning();++ expect(mockGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);+ });++ // The load-bearing half of the rule. The Cloudflare gateway has no+ // capabilities endpoint, so a rollback β clearing the platform list to+ // move connections BACK to it β targets a host that declares nothing.+ // Reading that silence as a refusal would make rollback impossible.+ it('does not treat a host that declares nothing as refusing anything', async () => {+ mockNodeGateway.platforms = [];+ mockGatewayClient.getCapabilities.mockResolvedValue(null);+ // The node host is the one still holding it β this is the rollback.+ mockNodeGatewayClient.getStats.mockResolvedValue({+ byPlatform: { wechat: 1 },+ connections: [+ {+ connectionId: CONNECTION_ID,+ platform: 'wechat',+ state: { status: 'connected' },+ userId: 'u1',+ },+ ],+ total: 1,+ });+ mockNodeGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [CONNECTION_ID] });+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.disconnect).toHaveBeenCalledWith(CONNECTION_ID);+ });++ it('skips the connect for a bot-channel platform the host declines', async () => {+ mockNodeGateway.platforms = ['discord'];+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({ platforms: ['wechat'] });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockFindAllLinksByPlatform.mockResolvedValue([]);+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: {},+ userId: 'u1',+ },+ ]+ : [],+ );+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });++ await service.ensureRunning();++ expect(mockNodeGatewayClient.connect).not.toHaveBeenCalled();+ });+ });++ // βββ listDesiredConnectionsForHost (restart recovery, pull side) βββ++ describe('listDesiredConnectionsForHost', () => {+ beforeEach(() => {+ mockGatewayClient.isEnabled = true;+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });+ mockResolveConnectionMode.mockReturnValue('websocket');+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ {+ applicationId: 'app-1',+ credentials: { token: 'x' },+ id: 'prov-1',+ settings: { watchKeywords: [{ keyword: 'hi' }] },+ userId: 'u1',+ },+ ]+ : [],+ );+ });++ // The whole point of sharing one builder: whichever side establishes a+ // connection, the gateway ends up holding the same config. A drifting+ // second builder would show up here and nowhere else.+ it('hands back exactly the payload the reconcile would have pushed', async () => {+ mockGatewayClient.connect.mockResolvedValue({ status: 'connecting' });++ await service.ensureRunning();+ const pushed = mockGatewayClient.connect.mock.calls[0][0];++ const { connections } = await service.listDesiredConnectionsForHost('default');++ expect(connections).toHaveLength(1);+ expect(connections[0]).toEqual({ config: pushed, ensure: true });+ });++ // A pull changes nothing and wakes nothing. It reads another host's+ // registry to see what is still held there β two admin requests, no+ // fan-out β but it must never mutate a gateway, and never probe a single+ // connection's status, which is what would drag a dormant one up.+ it('reads, but never mutates a gateway or probes a connection', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;++ await service.listDesiredConnectionsForHost('node');++ for (const client of [mockGatewayClient, mockNodeGatewayClient]) {+ expect(client.connect).not.toHaveBeenCalled();+ expect(client.disconnect).not.toHaveBeenCalled();+ expect(client.disconnectAll).not.toHaveBeenCalled();+ expect(client.getStatus).not.toHaveBeenCalled();+ }+ // Its own host is never queried β the answer comes from the database.+ expect(mockNodeGatewayClient.getStats).not.toHaveBeenCalled();+ });++ it('returns only the requested host slice', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'wechat'+ ? [+ {+ applicationId: 'wx-app',+ credentials: { token: 'w' },+ id: 'prov-wechat',+ settings: {},+ userId: 'u-wx',+ },+ ]+ : [+ {+ applicationId: 'dc-app',+ credentials: { token: 'd' },+ id: `prov-${platform}`,+ settings: {},+ userId: 'u-dc',+ },+ ],+ );++ const node = await service.listDesiredConnectionsForHost('node');+ const def = await service.listDesiredConnectionsForHost('default');++ expect(node.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-wechat']);+ expect(def.connections.map((entry) => entry.config.connectionId)).not.toContain(+ 'prov-wechat',+ );+ });++ // One unreadable row used to be able to fail the whole recovery. A row+ // that can never connect is data we exclude, not a reason to leave a+ // gateway empty.+ it('excludes an undecryptable row without failing the call', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) =>+ platform === 'discord'+ ? [+ { applicationId: 'app-1', credentials: {}, id: 'prov-1', settings: {}, userId: 'u1' },+ {+ applicationId: 'app-2',+ credentials: { token: 'x' },+ id: 'prov-2',+ settings: {},+ userId: 'u2',+ },+ ]+ : [],+ );++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(true);+ expect(result.excluded).toBe(1);+ expect(result.connections.map((entry) => entry.config.connectionId)).toEqual(['prov-2']);+ });++ it('reports complete:false when a platform fails to load', async () => {+ mockFindEnabledByPlatform.mockImplementation(async (_db: unknown, platform: string) => {+ if (platform === 'telegram') throw new Error('key vault unavailable');+ return [];+ });++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(false);+ });++ it('includes messenger polling links and excludes ones with no usable token', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ { applicationId: 'wx-app', credentials: {}, tenantId: 't2', userId: 'u2' },+ ]);++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.excluded).toBe(1);+ expect(result.connections).toHaveLength(1);+ expect(result.connections[0].config).toMatchObject({+ connectionId: 'messenger:wechat:t1:user-u1',+ connectionMode: 'polling',+ credentials: {+ baseUrl: 'https://ilink',+ botId: 'bot-1',+ botToken: 'tok-1',+ webhookToken: 'gateway-service-token',+ },+ webhookPath: '/api/agent/messenger/webhooks/wechat',+ });+ });++ // Routing a platform here does not mean this host can run it. Handing over+ // credentials for a connection it will reject arms nothing and exposes+ // them for no reason β and the reconcile already refuses to move such a+ // platform, so leaving the gap here would put the two out of step.+ it('withholds credentials for a platform this host says it cannot serve', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockNodeGatewayClient.getCapabilities.mockResolvedValue({+ platforms: ['whatsapp-baileys'],+ });+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ });++ // Today's production shape: the node URL is configured but no platform is+ // routed there yet. Deploying the node gateway must not drag the other+ // host's fleet over β it should be handed nothing at all.+ it('hands a host nothing while no platform is routed to it', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = [];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(0);+ });++ // Routing a platform here does not make its connections safe to build: the+ // host that owned them a moment ago is still polling. Handing one over+ // before that host is drained double-delivers every message.+ it('withholds a connection the previous host has not released yet', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ // The default host still holds it β mid-migration.+ mockGatewayClient.getRegisteredIds.mockResolvedValue({+ ids: ['messenger:wechat:t1:user-u1'],+ });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ // Partial answer, so the caller keeps asking rather than settling.+ expect(result.complete).toBe(false);+ });++ // A stats-only snapshot omits dormant registrations, so an id missing from+ // it proves nothing about whether the other host released it. Marking the+ // answer incomplete is not enough on its own: the caller applies what it+ // receives and only then asks again, so the flag would land after the+ // duplicate it was meant to prevent. The connection has to be withheld.+ it('withholds a connection the other host cannot be proven to have released', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ // Stats answered, registered-ids did not: a live host we can only half see.+ mockGatewayClient.getStats.mockResolvedValue({ byPlatform: {}, connections: [], total: 0 });+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('registry unavailable'));++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ expect(result.complete).toBe(false);+ });++ it('hands the connection over once the previous host has released it', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getRegisteredIds.mockResolvedValue({ ids: [] });++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toHaveLength(1);+ expect(result.deferred).toBe(0);+ expect(result.complete).toBe(true);+ });++ // Same rule from the other direction: a host we could not reach shows+ // nothing, which is no more proof of release than a half-seen one. Restart+ // recovery is an optimisation over the reconcile, so when it cannot be done+ // safely the right move is not to do it.+ it('withholds when the other host cannot be read at all', async () => {+ mockNodeGateway.configured = true;+ mockNodeGateway.platforms = ['wechat'];+ mockNodeGatewayClient.isConfigured = true;+ mockResolveConnectionMode.mockReturnValue('polling');+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockResolvedValue([+ {+ applicationId: 'wx-app',+ credentials: { baseUrl: 'https://ilink', botId: 'bot-1', botToken: 'tok-1' },+ tenantId: 't1',+ userId: 'u1',+ },+ ]);+ mockGatewayClient.getStats.mockRejectedValue(new Error('admin down'));+ mockGatewayClient.getRegisteredIds.mockRejectedValue(new Error('admin down'));++ const result = await service.listDesiredConnectionsForHost('node');++ expect(result.connections).toEqual([]);+ expect(result.deferred).toBe(1);+ });++ it('reports complete:false when messenger links fail to load', async () => {+ mockFindEnabledByPlatform.mockResolvedValue([]);+ mockFindAllLinksByPlatform.mockRejectedValue(new Error('link listing failed'));++ const result = await service.listDesiredConnectionsForHost('default');++ expect(result.complete).toBe(false);+ });+ });});diff --git a/apps/server/src/services/gateway/index.ts b/apps/server/src/services/gateway/index.tsindex d1c307050e4..81c0437a18f 100644--- a/apps/server/src/services/gateway/index.ts+++ b/apps/server/src/services/gateway/index.ts@@ -40,6 +40,7 @@ import {getMessageGatewayClientForHost,isAnyMessageGatewayEnabled,type MessageGatewayCapabilities,+ type MessageGatewayConnectionConfig,type MessageGatewayConnectionStatus,type MessageGatewayHost,resolveMessageGatewayHost,@@ -169,6 +170,71 @@ const resolveBotGatewayCapabilities = (messageMonitoring: { enabled: extractWatchKeywordEntries(settings ?? undefined).length > 0 },});+/**+ * The connect payload for one bot-channel provider.+ *+ * Extracted because two callers build it now: the periodic reconcile, which+ * pushes it to the gateway, and the gateway's own boot-time pull, which+ * receives it and connects itself. A second builder would drift, and the+ * connection the gateway ends up holding would then depend on which side+ * established it.+ *+ * Payload only, deliberately no side effects. The push path also writes a+ * runtime status from the connect result, but that belongs to whoever+ * actually connected: on the pull path the gateway does, so its state+ * callback is what reports the real status back. Guessing a status here would+ * record a connection as live that nothing has established yet.+ */+const buildBotProviderConnectConfig = ({+ connectionMode,+ platform,+ provider,+}: DesiredGatewayConnection): MessageGatewayConnectionConfig => ({+ applicationId: provider.applicationId,+ capabilities: resolveBotGatewayCapabilities(provider.settings),+ connectionId: provider.id,+ connectionMode,+ credentials: provider.credentials,+ platform,+ userId: provider.userId,+ webhookPath: `/api/agent/webhooks/${platform}/${provider.applicationId}`,+});++/** The connect payload for one messenger polling link. Same rationale as above. */+const buildMessengerPollingConnectConfig = ({+ connectionId,+ link,+ platform,+}: {+ connectionId: string;+ link: DecryptedMessengerAccountLink;+ platform: string;+}): MessageGatewayConnectionConfig => {+ const credentials = link.credentials as {+ baseUrl?: string;+ botId?: string;+ botToken?: string;+ };++ return {+ applicationId: link.applicationId!,+ // Messenger-owned connections never consume passive channel monitoring β+ // the shared bot only reacts to DMs and explicit mentions.+ capabilities: { messageMonitoring: { enabled: false } },+ connectionId,+ connectionMode: 'polling',+ credentials: {+ baseUrl: credentials.baseUrl,+ botId: credentials.botId,+ botToken: credentials.botToken,+ webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,+ },+ platform,+ userId: link.userId,+ webhookPath: `/api/agent/messenger/webhooks/${platform}`,+ };+};+const isVercel = !!process.env.VERCEL_ENV;export class GatewayService {@@ -235,17 +301,51 @@ export class GatewayService {const serverDB = await getServerDB();const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();- const { desired, desiredComplete, gated } = await this.buildDesiredConnections(- serverDB,- gateKeeper,- );-// Each configured host gets its own desired slice and its own actual// snapshot, then runs the full diff independently. Cross-host moves fall// out of the partition: a platform routed away from a host leaves its ids// absent from that host's desired slice β the stale pass disconnects them// there while the new host's connect pass builds them up.const hosts = getConfiguredMessageGatewayHosts();++ // A platform name nothing recognises is a typo, and its only visible+ // effect is that the migration silently does not happen β the name simply+ // never matches, so everything stays on the default host. Say so once per+ // round instead of leaving someone to wonder why the flip did nothing.+ const routedNames = (gatewayEnv.MESSAGE_GATEWAY_NODE_PLATFORMS ?? '')+ .split(',')+ .map((entry) => entry.trim())+ .filter(Boolean);+ if (routedNames.length > 0) {+ const known = new Set([+ ...platformRegistry.listPlatforms().map((definition) => definition.id),+ ...messengerPlatformRegistry.listPlatforms().map((definition) => definition.id),+ ]);+ const unknown = routedNames.filter((name) => !known.has(name));+ if (unknown.length > 0) {+ log(+ 'Gateway sync: MESSAGE_GATEWAY_NODE_PLATFORMS names %o, which match no known platform β those entries do nothing',+ unknown,+ );+ }+ }++ // What each host says it can serve. Routing a platform to a host it cannot+ // serve is otherwise an outage, not a no-op: the stale pass drains the+ // connections off their old host, and the connect that should replace them+ // is rejected β so they end up nowhere. One request per host per round.+ const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>();+ for (const host of hosts) {+ const capabilities = await getMessageGatewayClientForHost(host).getCapabilities();+ declaredPlatforms.set(host, capabilities ? new Set(capabilities.platforms ?? []) : null);+ }++ const { desired, desiredComplete, gated } = await this.buildDesiredConnections(+ serverDB,+ gateKeeper,+ hosts,+ );+const snapshots = new Map<MessageGatewayHost, ActualConnectionsSnapshot | null>();for (const host of hosts) {snapshots.set(host, await this.fetchActualConnections(getMessageGatewayClientForHost(host)));@@ -289,6 +389,7 @@ export class GatewayService {drainCounts.set(host,await this.drainHostConnections({+ declaredPlatforms,desired,desiredComplete,drainedThisRound,@@ -305,6 +406,7 @@ export class GatewayService {await this.connectHostConnections({counts: drainCounts.get(host) ?? { gatedDisconnected: 0, gatedSize: 0, stale: 0 },currentlyElsewhere,+ declaredPlatforms,desired,drainedThisRound,host,@@ -317,6 +419,7 @@ export class GatewayService {gateKeeper,snapshots,hostsReadyToReceive,+ declaredPlatforms,);log(@@ -338,6 +441,24 @@ export class GatewayService {);}+ /**+ * Whether `host` has told us it cannot serve `platform`.+ *+ * Only an explicit declaration counts. A gateway that does not describe+ * itself makes no claim, and absence of information must never be read as a+ * refusal β the Cloudflare gateway has no capabilities endpoint at all, and+ * treating that as "refuses everything" would block the rollback path,+ * where connections move BACK to it.+ */+ private hostRefusesPlatform(+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,+ host: MessageGatewayHost,+ platform: string,+ ): boolean {+ const declared = declaredPlatforms.get(host);+ return !!declared && !declared.has(platform);+ }+/** Slice of the gated set whose platforms route to `host`. */private hostGatedSlice(gated: Map<string, string>, host: MessageGatewayHost): Set<string> {return new Set(@@ -347,6 +468,196 @@ export class GatewayService {);}+ /**+ * The connect payloads one host should currently be holding.+ *+ * This is the read half of restart recovery: a gateway that just came back+ * up holds nothing, asks for this list, and builds it itself. Nothing here+ * calls a gateway, so it wakes no connection and can be retried freely β+ * the one write it does make is the runtime status of a paid-gated+ * provider, which `buildDesiredConnections` records on the way past and+ * which is true no matter who asked.+ *+ * `complete: false` means the desired set could not be computed in full (a+ * platform's rows failed to load, key vault unavailable). The caller should+ * apply what it got and ask again rather than treat a short list as the+ * whole truth. Refusing to answer at all would be worse: it leaves the+ * gateway holding nothing for the length of an unrelated outage.+ *+ * Rows that can never connect β credentials missing or undecryptable β are+ * counted into `excluded` and left out. They must not fail the call: a+ * single unreadable row would otherwise keep a whole gateway empty forever.+ *+ * Connections another host still holds are withheld and counted into+ * `deferred`. Routing alone does not make a connection safe to build: right+ * after a platform is routed here, the previous host is still polling it,+ * and handing it over before that host is drained double-delivers every+ * message until a later reconcile catches up. The periodic reconcile owns+ * the hand-off; this call only refuses to race it.+ */+ async listDesiredConnectionsForHost(host: MessageGatewayHost): Promise<{+ complete: boolean;+ connections: { config: MessageGatewayConnectionConfig; ensure: true }[];+ deferred: number;+ excluded: number;+ }> {+ const serverDB = await getServerDB();+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();++ const connections: { config: MessageGatewayConnectionConfig; ensure: true }[] = [];+ let excluded = 0;+ let deferred = 0;++ // What every OTHER host still holds. Read-only, and only two admin+ // requests per host β they reach the gateway's own registry, not the+ // individual connections, so asking wakes nothing.+ //+ // A host whose admin surface is unreachable is treated as holding+ // nothing, deliberately, and matching the reconcile's own rule: a+ // steady-state deployment has no connections on the wrong host at all, so+ // blocking every restart recovery on an unrelated host's outage costs far+ // more availability than the duplicate window it would avoid β and that+ // window only opens if the outage overlaps an actual migration.+ // What this host says it can serve. Routing a platform here does not mean+ // it can run it, and handing over credentials for a connection it will+ // reject is handing them over for nothing. The reconcile already refuses+ // to move such a platform; this refuses to arm it.+ const declared = await getMessageGatewayClientForHost(host).getCapabilities();+ const declaredPlatforms = new Map<MessageGatewayHost, Set<string> | null>([+ [host, declared ? new Set(declared.platforms ?? []) : null],+ ]);++ const elsewhere = new Set<string>();+ let peersProven = true;+ for (const other of getConfiguredMessageGatewayHosts()) {+ if (other === host) continue;+ const snapshot = await this.fetchActualConnections(getMessageGatewayClientForHost(other));++ // Absence is only evidence when the view was complete. A snapshot we+ // could not fetch shows nothing, and a stats-only one omits dormant+ // registrations β in both cases an id missing from it says nothing about+ // whether that host released it, so nothing here can be handed over.+ // Marking the answer incomplete does not substitute: the caller applies+ // what it receives and only then asks again, so a flag arrives after the+ // duplicate it was supposed to prevent.+ if (!snapshot?.complete) {+ peersProven = false;+ log(+ 'Gateway pull[%s]: %s host view is %s, cannot prove it released anything',+ host,+ other,+ snapshot ? 'incomplete' : 'unavailable',+ );+ }++ snapshot?.connections.forEach((_status, id) => elsewhere.add(id));+ }++ // Paid-gated providers never enter the desired set, so nothing here can+ // hand back a connection the next reconcile round would tear down again.+ const { desired, desiredComplete } = await this.buildDesiredConnections(serverDB, gateKeeper, [+ host,+ ]);+ let complete = desiredComplete;++ for (const entry of this.hostDesiredSlice(desired, host).values()) {+ if (this.hostRefusesPlatform(declaredPlatforms, host, entry.platform)) {+ excluded++;+ continue;+ }+ if (Object.keys(entry.provider.credentials).length === 0) {+ excluded++;+ continue;+ }+ if (!peersProven || elsewhere.has(entry.provider.id)) {+ deferred++;+ log(+ 'Gateway pull[%s]: %s not proven released elsewhere, withholding',+ host,+ entry.provider.id,+ );+ continue;+ }+ connections.push({ config: buildBotProviderConnectConfig(entry), ensure: true });+ }++ for (const definition of messengerPlatformRegistry.listPlatforms()) {+ if (definition.connectionMode !== 'polling') continue;+ const platform = definition.id;+ if (resolveMessageGatewayHost(platform) !== host) continue;+ if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {+ log(+ 'Gateway pull[%s]: host does not serve %s, withholding its credentials',+ host,+ platform,+ );+ continue;+ }++ let links: DecryptedMessengerAccountLink[];+ try {+ links = await MessengerAccountLinkModel.findAllByPlatformWithCredentials(+ serverDB,+ platform,+ gateKeeper,+ );+ } catch (err) {+ // Same rule as the desired set: a platform we could not read makes the+ // answer incomplete, not empty.+ complete = false;+ log('Gateway pull[%s]: messenger link listing failed for %s: %O', host, platform, err);+ continue;+ }++ for (const link of links) {+ const credentials = link.credentials as { botToken?: string };+ const connectionId = messengerConnectionIdForUser({+ connectionMode: 'polling',+ installationKey: `${platform}:${link.tenantId}`,+ userId: link.userId,+ });+ if (!link.applicationId || !credentials.botToken) {+ excluded++;+ continue;+ }+ if (!peersProven || elsewhere.has(connectionId)) {+ deferred++;+ log(+ 'Gateway pull[%s]: %s not proven released elsewhere, withholding',+ host,+ connectionId,+ );+ continue;+ }+ connections.push({+ config: buildMessengerPollingConnectConfig({ connectionId, link, platform }),+ ensure: true,+ });+ }+ }++ // Audit surface: this is the one place that hands out a host's whole+ // credential set, and it doubles as the signal that the host restarted.+ // Withheld entries make this a partial answer, so the caller keeps asking+ // instead of settling for the set it got. It will run out of attempts long+ // before a hand-off finishes β that is fine: finishing one is the periodic+ // reconcile's job, not this call's. Restart recovery is an optimisation+ // over that reconcile, so when it cannot be done safely the right move is+ // not to do it.+ if (deferred > 0) complete = false;++ log(+ 'Gateway pull[%s]: %d connection(s), excluded=%d, deferred=%d, complete=%s',+ host,+ connections.length,+ excluded,+ deferred,+ complete,+ );++ return { complete, connections, deferred, excluded };+ }+/*** Phase 1 for one host: remove what should no longer be there (paid-gated* connections, then stale ones). Runs for every host before any host's@@ -354,6 +665,7 @@ export class GatewayService {* is built on its new one.*/private async drainHostConnections(params: {+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;desired: Map<string, DesiredGatewayConnection>;desiredComplete: boolean;drainedThisRound: Set<string>;@@ -364,6 +676,7 @@ export class GatewayService {snapshot: ActualConnectionsSnapshot | null;}): Promise<HostDrainCounts> {const {+ declaredPlatforms,desiredComplete,drainedThisRound,host,@@ -391,6 +704,7 @@ export class GatewayService {host,hostsReadyToReceive,drainedThisRound,+ declaredPlatforms,);} else if (actual) {log('Gateway sync: desired set incomplete, skipping stale-connection cleanup this round');@@ -406,12 +720,20 @@ export class GatewayService {private async connectHostConnections(params: {counts: HostDrainCounts;currentlyElsewhere: Set<string>;+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>;desired: Map<string, DesiredGatewayConnection>;drainedThisRound: Set<string>;host: MessageGatewayHost;snapshot: ActualConnectionsSnapshot | null;}): Promise<void> {- const { counts, currentlyElsewhere, drainedThisRound, host, snapshot: actual } = params;+ const {+ counts,+ currentlyElsewhere,+ declaredPlatforms,+ drainedThisRound,+ host,+ snapshot: actual,+ } = params;const client = getMessageGatewayClientForHost(host);const desired = this.hostDesiredSlice(params.desired, host);@@ -442,6 +764,15 @@ export class GatewayService {desired.values(),async ({ connectionMode, platform, provider }) => {try {+ // Told us it cannot serve this platform. The connect would be+ // rejected anyway; skipping keeps one clear line in the log instead+ // of an error per connection, and pairs with the stale pass, which+ // leaves these running wherever they already are.+ if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {+ skipped++;+ return;+ }+// Credentials missing/undecryptable: the provider is still desired// (protected from the stale pass) but a connect attempt can only// fail β leave whatever connection state the gateway already holds.@@ -504,22 +835,12 @@ export class GatewayService {log('Gateway sync: %s reported disconnected in stats, reconnecting', provider.id);}- const webhookPath = `/api/agent/webhooks/${platform}/${provider.applicationId}`;// `ensure` marks this as a reconcile connect: the gateway preserves// its park/backoff state when the config is unchanged (a parked// connection answers 409 β counted as failed below), instead of// letting every sync round reset stuck connections to fast retry.const result = await client.connect(- {- applicationId: provider.applicationId,- capabilities: resolveBotGatewayCapabilities(provider.settings),- connectionId: provider.id,- connectionMode,- credentials: provider.credentials,- platform,- userId: provider.userId,- webhookPath,- },+ buildBotProviderConnectConfig({ connectionMode, platform, provider }),{ ensure: true },);@@ -588,6 +909,7 @@ export class GatewayService {gateKeeper: KeyVaultsGateKeeper,snapshots: Map<MessageGatewayHost, ActualConnectionsSnapshot | null>,hostsReadyToReceive: Set<MessageGatewayHost>,+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,): Promise<void> {for (const definition of messengerPlatformRegistry.listPlatforms()) {if (definition.connectionMode !== 'polling') continue;@@ -596,6 +918,19 @@ export class GatewayService {const client = getMessageGatewayClientForHost(host);if (!client.isEnabled) continue;+ // Routed to a host that says it cannot serve this platform. Skipping the+ // whole platform leaves every connection where it already runs β the+ // teardown below would otherwise strip them from their current host for+ // a destination that will reject them.+ if (this.hostRefusesPlatform(declaredPlatforms, host, platform)) {+ log(+ 'Gateway sync[%s]: host does not serve %s β leaving its connections where they are',+ host,+ platform,+ );+ continue;+ }+const prefix = `messenger:${platform}:`;// Load the links BEFORE touching any host. A migration that drains the@@ -765,27 +1100,8 @@ export class GatewayService {return;}try {- const credentials = link.credentials as {- baseUrl?: string;- botId?: string;- botToken?: string;- };await client.connect(- {- applicationId: link.applicationId!,- capabilities: { messageMonitoring: { enabled: false } },- connectionId,- connectionMode: 'polling',- credentials: {- baseUrl: credentials.baseUrl,- botId: credentials.botId,- botToken: credentials.botToken,- webhookToken: gatewayEnv.MESSAGE_GATEWAY_SERVICE_TOKEN,- },- platform,- userId: link.userId,- webhookPath: `/api/agent/messenger/webhooks/${platform}`,- },+ buildMessengerPollingConnectConfig({ connectionId, link, platform }),{ ensure: true },);connected++;@@ -845,6 +1161,7 @@ export class GatewayService {private async buildDesiredConnections(serverDB: Awaited<ReturnType<typeof getServerDB>>,gateKeeper: KeyVaultsGateKeeper,+ hosts: MessageGatewayHost[],): Promise<{desired: Map<string, DesiredGatewayConnection>;desiredComplete: boolean;@@ -857,6 +1174,12 @@ export class GatewayService {for (const definition of platformRegistry.listPlatforms()) {const platform = definition.id;++ // Only platforms owned by one of `hosts`. Loading the rest would decrypt+ // credentials for connections this call is never going to look at β pure+ // waste for a single-host pull, and a wider blast radius on failure.+ if (!hosts.includes(resolveMessageGatewayHost(platform))) continue;+try {// includeUndecryptable: rows whose credentials can't be decrypted stay// in the desired set (with empty credentials) so a KEY_VAULTS_SECRET@@ -1013,6 +1336,7 @@ export class GatewayService {host: MessageGatewayHost,hostsReadyToReceive: Set<MessageGatewayHost>,drainedThisRound: Set<string>,+ declaredPlatforms: Map<MessageGatewayHost, Set<string> | null>,): Promise<number> {const allStaleIds = [...actual.keys()].filter((id) => !desired.has(id) && !gated.has(id) && !isMessengerConnectionId(id),@@ -1079,6 +1403,21 @@ export class GatewayService {);return;}++ // Routed somewhere that has told us it cannot serve this platform.+ // Draining here would be worse than doing nothing: the connect+ // meant to replace it gets rejected, so the connection ends up on+ // neither host. Leave it running and let the misrouting be fixed.+ if (this.hostRefusesPlatform(declaredPlatforms, owner, row.platform)) {+ log(+ 'Gateway sync[%s]: %s is routed to the %s host, which does not serve %s β refusing to drain',+ host,+ id,+ owner,+ row.platform,+ );+ return;+ }}await client.disconnect(id);diff --git a/packages/env/src/gateway.ts b/packages/env/src/gateway.tsindex 521058fe41e..aa772d76c26 100644--- a/packages/env/src/gateway.ts+++ b/packages/env/src/gateway.ts@@ -8,6 +8,7 @@ export const getGatewayConfig = () => {DEVICE_GATEWAY_URL: process.env.DEVICE_GATEWAY_URL,MESSAGE_GATEWAY_ENABLED: process.env.MESSAGE_GATEWAY_ENABLED,MESSAGE_GATEWAY_NODE_PLATFORMS: process.env.MESSAGE_GATEWAY_NODE_PLATFORMS,+ MESSAGE_GATEWAY_NODE_PULL_TOKEN: process.env.MESSAGE_GATEWAY_NODE_PULL_TOKEN,MESSAGE_GATEWAY_NODE_URL: process.env.MESSAGE_GATEWAY_NODE_URL,MESSAGE_GATEWAY_SERVICE_TOKEN: process.env.MESSAGE_GATEWAY_SERVICE_TOKEN,MESSAGE_GATEWAY_URL: process.env.MESSAGE_GATEWAY_URL,@@ -24,11 +25,26 @@ export const getGatewayConfig = () => {* list and the next reconcile moves its connections back.*/MESSAGE_GATEWAY_NODE_PLATFORMS: z.string().optional(),+ /**+ * Credential the Node gateway presents to pull the connections it should+ * be holding. One credential, one host: presenting it IS the claim of+ * which gateway is asking, which is what lets the server answer that+ * question without trusting a field the caller filled in. A second+ * pull-capable host gets its own credential here, never a share of this+ * one.+ *+ * Deliberately not MESSAGE_GATEWAY_SERVICE_TOKEN. That value is written+ * into every WeChat connect payload as `webhookToken` and persisted with+ * the connection config, so it lives in the gateway fleet's storage, not+ * just in two env vars. Manipulating connections with it is the exposure+ * we already accept; reading every credential in one request is not.+ */+ MESSAGE_GATEWAY_NODE_PULL_TOKEN: z.string().optional(),/*** Base URL of the Node message gateway (long-polling / native-dep- * platforms). Both gateways share MESSAGE_GATEWAY_SERVICE_TOKEN β the- * inbound webhook/callback validation only accepts that one value, so a- * per-gateway token would not actually isolate anything.+ * platforms). Both gateways share MESSAGE_GATEWAY_SERVICE_TOKEN for the+ * connection-management surface, because inbound webhook and callback+ * validation only accepts that one value.*/MESSAGE_GATEWAY_NODE_URL: z.string().url().optional(),MESSAGE_GATEWAY_SERVICE_TOKEN: z.string().optional(),