diff --git a/server/lib/drivers/telegram/secret.ts b/server/lib/drivers/telegram/secret.ts new file mode 100644 index 0000000..941f5b2 --- /dev/null +++ b/server/lib/drivers/telegram/secret.ts @@ -0,0 +1,22 @@ +import type { Env } from "../../types"; + +/** + * The `secret_token` Telegram must send with every webhook call. It is + * `TELEGRAM_WEBHOOK_SECRET` when set, otherwise derived from the bot token + * (which is itself secret), so the webhook endpoint is never left + * unauthenticated. Empty when no bot token is configured. + */ +export async function telegramWebhookSecret(env: Env): Promise { + const explicit = env.TELEGRAM_WEBHOOK_SECRET?.trim(); + if (explicit) return explicit; + const token = env.TELEGRAM_TOKEN?.trim(); + if (!token) return ""; + const digest = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(`webhooker:telegram-webhook:${token}`), + ); + // Telegram allows 1-256 characters of A-Z, a-z, 0-9, `_` and `-`. + return Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} diff --git a/server/lib/drivers/telegram/updates.ts b/server/lib/drivers/telegram/updates.ts index 42506f4..4aab70b 100644 --- a/server/lib/drivers/telegram/updates.ts +++ b/server/lib/drivers/telegram/updates.ts @@ -1,5 +1,7 @@ import type { Env } from "../../types"; +import { log } from "../../lib/log"; import { handleTelegramUpdate } from "./commands"; +import { telegramWebhookSecret } from "./secret"; const MAX_BODY_SIZE = 1024 * 1024; @@ -19,12 +21,16 @@ export async function handleTelegramWebhookRequest(request: Request, env: Env): return new Response("Request too large", { status: 413 }); } - const secret = env.TELEGRAM_WEBHOOK_SECRET; - if (secret) { - const token = request.headers.get("X-Telegram-Bot-Api-Secret-Token"); - if (!token || !timingSafeEqual(token, secret)) { - return new Response("Invalid secret", { status: 401 }); - } + // Every call must carry the webhook secret. Without a bot token there is + // no secret to check and nothing to act with, so the endpoint stays closed. + const secret = await telegramWebhookSecret(env); + if (!secret) { + log.warn("Telegram webhook called but TELEGRAM_TOKEN is not configured"); + return new Response("Telegram is not configured", { status: 403 }); + } + const token = request.headers.get("X-Telegram-Bot-Api-Secret-Token"); + if (!token || !timingSafeEqual(token, secret)) { + return new Response("Invalid secret", { status: 401 }); } const rawBody = await request.text(); diff --git a/tests/telegram-webhook.test.ts b/tests/telegram-webhook.test.ts new file mode 100644 index 0000000..b54a9ba --- /dev/null +++ b/tests/telegram-webhook.test.ts @@ -0,0 +1,38 @@ +import { describe, it, expect } from "bun:test"; +import { handleTelegramWebhookRequest } from "../server/lib/drivers/telegram/updates"; +import { telegramWebhookSecret } from "../server/lib/drivers/telegram/secret"; +import { createMemoryKV } from "./d1-sqlite"; +import type { Env } from "../server/lib/types"; + +function env(overrides: Partial = {}): Env { + return { GITHUB_WEBHOOK_SECRET: "", KV: createMemoryKV().kv, DB: {} as D1Database, ...overrides }; +} + +function post(secret?: string): Request { + return new Request("https://x/telegram/webhook", { + method: "POST", + headers: secret ? { "X-Telegram-Bot-Api-Secret-Token": secret } : {}, + body: JSON.stringify({ update_id: 1 }), + }); +} + +describe("telegram webhook authentication", () => { + it("stays closed without a bot token", async () => { + expect((await handleTelegramWebhookRequest(post("anything"), env())).status).toBe(403); + }); + + it("derives a secret from the bot token when none is configured", async () => { + const e = env({ TELEGRAM_TOKEN: "123:abc" }); + const secret = await telegramWebhookSecret(e); + expect(secret).toMatch(/^[0-9a-f]{64}$/); + expect((await handleTelegramWebhookRequest(post(), e)).status).toBe(401); + expect((await handleTelegramWebhookRequest(post("wrong"), e)).status).toBe(401); + expect((await handleTelegramWebhookRequest(post(secret), e)).status).toBe(200); + }); + + it("prefers the configured secret", async () => { + const e = env({ TELEGRAM_TOKEN: "123:abc", TELEGRAM_WEBHOOK_SECRET: "explicit" }); + expect(await telegramWebhookSecret(e)).toBe("explicit"); + expect((await handleTelegramWebhookRequest(post("explicit"), e)).status).toBe(200); + }); +});