diff --git a/assistant/src/config/vellum-skills/telegram-setup/SKILL.md b/assistant/src/config/vellum-skills/telegram-setup/SKILL.md index 4dc81a4c1d9..68d5fd51e24 100644 --- a/assistant/src/config/vellum-skills/telegram-setup/SKILL.md +++ b/assistant/src/config/vellum-skills/telegram-setup/SKILL.md @@ -43,26 +43,13 @@ export default () => ({ secret: randomUUID() }); Save this value for the next steps. -### Step 3: Register the Webhook +### Step 3: Webhook Registration (Automatic) -Use `evaluate_typescript_code` to register the webhook with Telegram: +Manual webhook registration is no longer required. The gateway automatically reconciles the Telegram webhook on startup and whenever credentials change. It compares the current webhook URL against `${INGRESS_PUBLIC_BASE_URL}/webhooks/telegram` and updates it if needed, including the webhook secret and allowed updates. -```typescript -export default async (input: { token: string; url: string; secret: string }) => { - const res = await fetch(`https://api.telegram.org/bot${input.token}/setWebhook`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - url: input.url, - secret_token: input.secret, - allowed_updates: ['message', 'edited_message'], - }), - }); - return res.json(); -}; -``` +If the ingress URL or webhook secret changes (e.g., tunnel restart, secret rotation), the gateway will detect the drift and re-register the webhook automatically. -Verify the response has `ok: true`. +You can skip directly to storing credentials. ### Step 4: Register Bot Commands @@ -95,8 +82,8 @@ Use `credential_store` twice to securely save the credentials: Summarize what was done: - Bot verified: @username (ID: nnn) -- Webhook registered at the provided URL +- Webhook registration: handled automatically by the gateway - Bot commands registered: /new - Credentials stored securely in the vault -The gateway automatically detects credentials from the vault and will begin accepting Telegram webhooks shortly. No manual environment variable configuration is needed. +The gateway automatically detects credentials from the vault, reconciles the Telegram webhook registration, and begins accepting Telegram webhooks shortly. No manual environment variable configuration or webhook registration is needed. If the ingress URL or secret changes later, the gateway will automatically re-register the webhook. diff --git a/gateway/src/__tests__/telegram-webhook-manager.test.ts b/gateway/src/__tests__/telegram-webhook-manager.test.ts new file mode 100644 index 00000000000..7a2fea348cc --- /dev/null +++ b/gateway/src/__tests__/telegram-webhook-manager.test.ts @@ -0,0 +1,191 @@ +import { describe, test, expect, mock, afterEach } from "bun:test"; +import { reconcileTelegramWebhook } from "../telegram/webhook-manager.js"; +import type { GatewayConfig } from "../config.js"; + +function makeConfig(overrides: Partial = {}): GatewayConfig { + return { + telegramBotToken: "test-bot-token", + telegramWebhookSecret: "test-webhook-secret", + telegramApiBaseUrl: "https://api.telegram.org", + assistantRuntimeBaseUrl: "http://localhost:7821", + routingEntries: [], + defaultAssistantId: undefined, + unmappedPolicy: "reject", + port: 7830, + runtimeBearerToken: undefined, + runtimeProxyEnabled: false, + runtimeProxyRequireAuth: false, + runtimeProxyBearerToken: undefined, + shutdownDrainMs: 5000, + runtimeTimeoutMs: 30000, + runtimeMaxRetries: 2, + runtimeInitialBackoffMs: 500, + telegramInitialBackoffMs: 1000, + telegramMaxRetries: 0, + telegramTimeoutMs: 15000, + maxWebhookPayloadBytes: 1048576, + logFile: { dir: undefined, retentionDays: 30 }, + maxAttachmentBytes: 20971520, + maxAttachmentConcurrency: 3, + twilioAuthToken: undefined, + ingressPublicBaseUrl: "https://example.ngrok.io", + publicUrl: undefined, + ...overrides, + }; +} + +const originalFetch = globalThis.fetch; + +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +function makeTelegramResponse(result: unknown) { + return new Response(JSON.stringify({ ok: true, result }), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +describe("reconcileTelegramWebhook", () => { + test("calls setWebhook when URL does not match", async () => { + const calls: { method: string; body: unknown }[] = []; + + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/getWebhookInfo")) { + calls.push({ method: "getWebhookInfo", body: null }); + return makeTelegramResponse({ + url: "https://old-url.example.com/webhooks/telegram", + has_custom_certificate: false, + pending_update_count: 0, + }); + } + if (url.includes("/setWebhook")) { + const req = typeof input === "object" && "json" in input ? input : null; + const body = req ? await (req as Request).json() : null; + calls.push({ method: "setWebhook", body }); + return makeTelegramResponse(true); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const config = makeConfig(); + await reconcileTelegramWebhook(config); + + expect(calls).toHaveLength(2); + expect(calls[0].method).toBe("getWebhookInfo"); + expect(calls[1].method).toBe("setWebhook"); + expect((calls[1].body as any).url).toBe("https://example.ngrok.io/webhooks/telegram"); + expect((calls[1].body as any).secret_token).toBe("test-webhook-secret"); + expect((calls[1].body as any).allowed_updates).toEqual(["message", "edited_message"]); + }); + + test("does not call setWebhook when URL already matches", async () => { + const calls: string[] = []; + + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/getWebhookInfo")) { + calls.push("getWebhookInfo"); + return makeTelegramResponse({ + url: "https://example.ngrok.io/webhooks/telegram", + has_custom_certificate: false, + pending_update_count: 0, + }); + } + if (url.includes("/setWebhook")) { + calls.push("setWebhook"); + return makeTelegramResponse(true); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const config = makeConfig(); + await reconcileTelegramWebhook(config); + + expect(calls).toEqual(["getWebhookInfo"]); + }); + + test("calls setWebhook when secret may have changed (forceUpdate)", async () => { + const calls: string[] = []; + + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/getWebhookInfo")) { + calls.push("getWebhookInfo"); + return makeTelegramResponse({ + url: "https://example.ngrok.io/webhooks/telegram", + has_custom_certificate: false, + pending_update_count: 0, + }); + } + if (url.includes("/setWebhook")) { + calls.push("setWebhook"); + return makeTelegramResponse(true); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const config = makeConfig(); + await reconcileTelegramWebhook(config, { forceUpdate: true }); + + expect(calls).toEqual(["getWebhookInfo", "setWebhook"]); + }); + + test("skips reconciliation when bot token is not configured", async () => { + const fetchMock = mock(async () => new Response("", { status: 200 })); + globalThis.fetch = fetchMock as any; + + const config = makeConfig({ telegramBotToken: undefined }); + await reconcileTelegramWebhook(config); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("skips reconciliation when webhook secret is not configured", async () => { + const fetchMock = mock(async () => new Response("", { status: 200 })); + globalThis.fetch = fetchMock as any; + + const config = makeConfig({ telegramWebhookSecret: undefined }); + await reconcileTelegramWebhook(config); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("skips reconciliation when ingress URL is not configured", async () => { + const fetchMock = mock(async () => new Response("", { status: 200 })); + globalThis.fetch = fetchMock as any; + + const config = makeConfig({ ingressPublicBaseUrl: undefined }); + await reconcileTelegramWebhook(config); + + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test("calls setWebhook when current URL is empty", async () => { + const calls: string[] = []; + + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (url.includes("/getWebhookInfo")) { + calls.push("getWebhookInfo"); + return makeTelegramResponse({ + url: "", + has_custom_certificate: false, + pending_update_count: 0, + }); + } + if (url.includes("/setWebhook")) { + calls.push("setWebhook"); + return makeTelegramResponse(true); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const config = makeConfig(); + await reconcileTelegramWebhook(config); + + expect(calls).toEqual(["getWebhookInfo", "setWebhook"]); + }); +}); diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 93e1b39195a..d3283fbaf46 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -11,6 +11,7 @@ import { createOAuthCallbackHandler } from "./http/routes/oauth-callback.js"; import { getLogger, initLogger } from "./logger.js"; import { buildSchema } from "./schema.js"; import { callTelegramApi } from "./telegram/api.js"; +import { reconcileTelegramWebhook } from "./telegram/webhook-manager.js"; const log = getLogger("main"); @@ -131,6 +132,9 @@ function main() { if (isTelegramConfigured()) { registerTelegramCommands(); + reconcileTelegramWebhook(config).catch((err) => { + log.error({ err }, "Failed to reconcile Telegram webhook on startup"); + }); } const credentialWatcher = new CredentialWatcher((credentials) => { @@ -139,6 +143,9 @@ function main() { config.telegramWebhookSecret = credentials.webhookSecret; log.info("Telegram credentials loaded from credential vault"); registerTelegramCommands(); + reconcileTelegramWebhook(config, { forceUpdate: true }).catch((err) => { + log.error({ err }, "Failed to reconcile Telegram webhook after credential change"); + }); } else { config.telegramBotToken = undefined; config.telegramWebhookSecret = undefined; diff --git a/gateway/src/telegram/webhook-manager.ts b/gateway/src/telegram/webhook-manager.ts new file mode 100644 index 00000000000..f97b772aea6 --- /dev/null +++ b/gateway/src/telegram/webhook-manager.ts @@ -0,0 +1,75 @@ +import type { GatewayConfig } from "../config.js"; +import { callTelegramApi } from "./api.js"; +import { getLogger } from "../logger.js"; + +const log = getLogger("webhook-manager"); + +interface WebhookInfo { + url: string; + has_custom_certificate: boolean; + pending_update_count: number; + /** Telegram does not return the secret itself, but we can detect a mismatch by re-setting. */ +} + +const ALLOWED_UPDATES = ["message", "edited_message"]; + +/** + * Reconciles the Telegram webhook registration against the expected state + * derived from the gateway's ingress URL and current webhook secret. + * + * If the currently registered webhook URL differs from the expected URL, + * or if the secret may have changed (we always re-set when the URL matches + * but we can't verify the secret from getWebhookInfo), the webhook is + * re-registered via setWebhook. + * + * This is safe to call repeatedly; Telegram treats setWebhook as idempotent. + */ +export async function reconcileTelegramWebhook( + config: GatewayConfig, + options?: { forceUpdate?: boolean }, +): Promise { + if (!config.telegramBotToken || !config.telegramWebhookSecret) { + log.debug("Skipping webhook reconciliation: Telegram credentials not configured"); + return; + } + + if (!config.ingressPublicBaseUrl) { + log.debug("Skipping webhook reconciliation: INGRESS_PUBLIC_BASE_URL not set"); + return; + } + + const expectedUrl = `${config.ingressPublicBaseUrl}/webhooks/telegram`; + + const info = await callTelegramApi(config, "getWebhookInfo", {}); + + const urlMatches = info.url === expectedUrl; + + // Telegram does not expose the current secret_token via getWebhookInfo, + // so we cannot compare it directly. When credentials are refreshed + // (forceUpdate), we always re-set to ensure the secret is current. + if (urlMatches && !options?.forceUpdate) { + log.info( + { currentUrl: info.url, expectedUrl }, + "Telegram webhook URL matches expected state, no update needed", + ); + return; + } + + log.info( + { + currentUrl: info.url || "(none)", + expectedUrl, + forceUpdate: !!options?.forceUpdate, + urlMatches, + }, + "Telegram webhook state differs from expected, updating", + ); + + await callTelegramApi(config, "setWebhook", { + url: expectedUrl, + secret_token: config.telegramWebhookSecret, + allowed_updates: ALLOWED_UPDATES, + }); + + log.info({ url: expectedUrl }, "Telegram webhook registered successfully"); +}