Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 13 additions & 10 deletions gateway/src/__tests__/telegram-webhook-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe("reconcileTelegramWebhook", () => {
expect((calls[1].body as any).allowed_updates).toEqual(["message", "edited_message"]);
});

test("does not call setWebhook when URL already matches", async () => {
test("always calls setWebhook even when URL already matches (secret may have rotated)", async () => {
const calls: string[] = [];

globalThis.fetch = mock(async (input: string | URL | Request) => {
Expand All @@ -105,33 +105,36 @@ describe("reconcileTelegramWebhook", () => {
const config = makeConfig();
await reconcileTelegramWebhook(config);

expect(calls).toEqual(["getWebhookInfo"]);
expect(calls).toEqual(["getWebhookInfo", "setWebhook"]);
});

test("calls setWebhook when secret may have changed (forceUpdate)", async () => {
const calls: string[] = [];
test("normalizes trailing slash on ingress base URL", 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("getWebhookInfo");
calls.push({ method: "getWebhookInfo", body: null });
return makeTelegramResponse({
url: "https://example.ngrok.io/webhooks/telegram",
url: "",
has_custom_certificate: false,
pending_update_count: 0,
});
}
if (url.includes("/setWebhook")) {
calls.push("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, { forceUpdate: true });
const config = makeConfig({ ingressPublicBaseUrl: "https://example.ngrok.io/" });
await reconcileTelegramWebhook(config);

expect(calls).toEqual(["getWebhookInfo", "setWebhook"]);
expect(calls).toHaveLength(2);
expect((calls[1].body as any).url).toBe("https://example.ngrok.io/webhooks/telegram");
});

test("skips reconciliation when bot token is not configured", async () => {
Expand Down
2 changes: 1 addition & 1 deletion gateway/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ function main() {
config.telegramWebhookSecret = credentials.webhookSecret;
log.info("Telegram credentials loaded from credential vault");
registerTelegramCommands();
reconcileTelegramWebhook(config, { forceUpdate: true }).catch((err) => {
reconcileTelegramWebhook(config).catch((err) => {
log.error({ err }, "Failed to reconcile Telegram webhook after credential change");
});
} else {
Expand Down
34 changes: 10 additions & 24 deletions gateway/src/telegram/webhook-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,13 @@ 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.
* Always calls setWebhook because Telegram does not expose the current
* secret_token via getWebhookInfo — a secret rotation with an unchanged URL
* would be invisible to us, causing all deliveries to fail with 401.
* setWebhook is idempotent, so calling it unconditionally is safe.
*/
export async function reconcileTelegramWebhook(
config: GatewayConfig,
options?: { forceUpdate?: boolean },
): Promise<void> {
if (!config.telegramBotToken || !config.telegramWebhookSecret) {
log.debug("Skipping webhook reconciliation: Telegram credentials not configured");
Expand All @@ -38,31 +35,20 @@ export async function reconcileTelegramWebhook(
return;
}

const expectedUrl = `${config.ingressPublicBaseUrl}/webhooks/telegram`;
// Strip trailing slashes to avoid double-slash in the path
// (e.g. "https://example.com/" + "/webhooks/telegram" => "https://example.com//webhooks/telegram")
const baseUrl = config.ingressPublicBaseUrl.replace(/\/+$/, "");
const expectedUrl = `${baseUrl}/webhooks/telegram`;

const info = await callTelegramApi<WebhookInfo>(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,
urlMatches: info.url === expectedUrl,
},
"Telegram webhook state differs from expected, updating",
"Reconciling Telegram webhook",
);

await callTelegramApi(config, "setWebhook", {
Expand Down
Loading