From 7882701e1f5c382580027b8c740842cd1fe6652e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Fri, 23 Oct 2026 23:23:11 +0800 Subject: [PATCH] fix(telegram): keep completed commands claimed Redelivery after a completed write must never post another comment. Keep completion claims despite reply failures, scope updates per bot and only issue account-login links in private chats. --- server/lib/drivers/telegram/commands.ts | 268 +++++++++++++-- tests/telegram-commands.test.ts | 436 +++++++++++++++++++++++- 2 files changed, 672 insertions(+), 32 deletions(-) diff --git a/server/lib/drivers/telegram/commands.ts b/server/lib/drivers/telegram/commands.ts index 4fb3c65..b8a8198 100644 --- a/server/lib/drivers/telegram/commands.ts +++ b/server/lib/drivers/telegram/commands.ts @@ -4,13 +4,25 @@ import { commentAsUser, mergePullRequestAsUser, closePullRequestAsUser, + BeforeGitHubError, + CommandTakenError, + githubRefused, } from "../../github/oauth"; -import { getTelegramLink, removeTelegramLink } from "../../github/store"; +import { getTelegramLink, unlinkAsCommand } from "../../github/store"; +import { acceptedKey, claimOnce, confirmClaim, idempotencyStore } from "../../lib/idempotency"; import type { Env } from "../../types"; import { sendMessage } from "./rest"; +import { telegramWebhookSecret } from "./secret"; -const GITHUB_ISSUE_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/; -const GITHUB_PR_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/; +// github.com itself only (never e.g. `evilgithub.com`): actions hit the GitHub API. +/** An update is held this long while its command runs (then a redelivery may take it). */ +const COMMAND_CLAIM_SECONDS = 300; +/** Handled updates are remembered this long. */ +const COMMAND_DONE_SECONDS = 86400; + +const GITHUB_ISSUE_RE = + /^https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/; +const GITHUB_PR_RE = /^https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/; interface TelegramMessage { message_id?: number; @@ -23,6 +35,26 @@ interface TelegramMessage { reply_to_message?: TelegramMessage; } +let knownBotUsername: { token: string; name: string } | null = null; + +/** This bot's username (lower case), from `getMe`; remembered per isolate. */ +async function botUsername(env: Env): Promise { + const token = env.TELEGRAM_TOKEN ?? ""; + if (knownBotUsername?.token === token) return knownBotUsername.name; + const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, { + signal: AbortSignal.timeout(15_000), + }); + const data = (await res.json().catch(() => null)) as { + result?: { username?: string }; + } | null; + const name = data?.result?.username; + // Unknown: thrown, so Telegram redelivers the update rather than the + // command being dropped. + if (!res.ok || !name) throw new Error(`Telegram getMe failed (HTTP ${res.status})`); + knownBotUsername = { token, name: name.toLowerCase() }; + return knownBotUsername.name; +} + interface Target { owner: string; repo: string; @@ -54,13 +86,23 @@ function extractTarget(msg: TelegramMessage, prOnly = false): Target | null { return null; } +/** + * Send a reply. One that could not be sent for now throws, so the update is + * redelivered rather than confirmed unanswered (a login link never sent); + * a refusal that a retry cannot change (e.g. the bot was blocked) is logged. + */ async function reply( env: Env, chatId: string, topicId: string | undefined, text: string, ): Promise { - await sendMessage(env.TELEGRAM_TOKEN ?? "", chatId, text, topicId); + const result = await sendMessage(env.TELEGRAM_TOKEN ?? "", chatId, text, topicId); + if (result.ok) return; + log.warn({ chatId, err: result.error }, "Telegram reply failed"); + if (!result.status || result.status >= 500 || result.status === 429) { + throw new Error(`Telegram reply failed: ${result.error ?? "unknown"}`); + } } function errText(err: unknown): string { @@ -77,17 +119,23 @@ async function cmdLogin(env: Env, msg: TelegramMessage): Promise { if (!chatId || !telegramUserId) return; const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined; + // An authorization link posted in a group can be opened by anyone there; + // binding happens in the private chat with the bot only. + if (msg.chat?.type !== "private") { + return reply(env, chatId, topicId, "请私聊机器人发送 /gh login 绑定 GitHub 账号。"); + } + const clientId = env.GITHUB_CLIENT_ID; if (!clientId) return reply(env, chatId, topicId, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。"); + const name = msg.from?.username ? `@${msg.from.username}` : msg.from?.first_name; const state = crypto.randomUUID().replace(/-/g, ""); await env.KV.put( `state:${state}`, JSON.stringify({ redirectTo: "/", - telegramUserId, - telegramChatId: chatId, + link: { platform: "telegram", userId: telegramUserId, name, chatId }, expiresAt: Date.now() + 600_000, }), { expirationTtl: 600 }, @@ -97,20 +145,39 @@ async function cmdLogin(env: Env, msg: TelegramMessage): Promise { env, chatId, topicId, - `点击链接授权 GitHub,即可用**本人身份**评论(10 分钟内有效):\n${url}`, + `点击链接授权 GitHub,即可用本人身份评论(10 分钟内有效):\n${url}`, ); } -async function cmdLogout(env: Env, msg: TelegramMessage): Promise { +async function cmdLogout(env: Env, msg: TelegramMessage, run: CommandRun): Promise { const chatId = chatIdOf(msg); const telegramUserId = userIdOf(msg); if (!chatId || !telegramUserId) return; const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined; - await removeTelegramLink(env.DB, telegramUserId); + await unlinkAsCommand(env, "telegram", telegramUserId, run.done); + // Done from here: should the reply fail, a redelivery must not unlink again + // (by then it could remove a link made since). + run.acted = true; await reply(env, chatId, topicId, "已解绑你的 GitHub 账号。"); } -async function cmdComment(env: Env, msg: TelegramMessage, body: string): Promise { +/** Tracks whether a command reached GitHub, so a failed run knows if it may be retried. */ +interface CommandRun { + acted: boolean; + /** Records the command as done right before its GitHub write. */ + beforeWrite?: () => Promise; + /** This run wrote the "done" (only then may it give it back). */ + markedDone?: boolean; + /** The command's "done" record, for writes committed together with it. */ + done?: { key: string; ttl: number }; +} + +async function cmdComment( + env: Env, + msg: TelegramMessage, + body: string, + run: CommandRun, +): Promise { const chatId = chatIdOf(msg); const telegramUserId = userIdOf(msg); if (!chatId || !telegramUserId) return; @@ -134,20 +201,35 @@ async function cmdComment(env: Env, msg: TelegramMessage, body: string): Promise try { const { htmlUrl, login } = await commentAsUser( - env.KV, + env, githubUserId, target.owner, target.repo, target.number, body, + { beforeWrite: run.beforeWrite }, ); + run.acted = true; await reply(env, chatId, topicId, `已以 **@${login}** 身份评论:${htmlUrl}`); } catch (err) { + // Nothing reached GitHub yet: give the update back for a retry. + if (err instanceof BeforeGitHubError) throw err; + // Done, only its reply failed: the update must not run again. + if (run.acted) throw err; + // GitHub was called and may have acted (its answer lost): never run + // again. A refusal did nothing: should its reply fail, the command is + // given back and runs again. + if (!githubRefused(err)) run.acted = true; await reply(env, chatId, topicId, errText(err)); } } -async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "close"): Promise { +async function cmdMergeClose( + env: Env, + msg: TelegramMessage, + op: "merge" | "close", + run: CommandRun, +): Promise { const chatId = chatIdOf(msg); const telegramUserId = userIdOf(msg); if (!chatId || !telegramUserId) return; @@ -171,10 +253,23 @@ async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "clos try { if (op === "merge") { - await mergePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number); + await mergePullRequestAsUser( + env, + githubUserId, + target.owner, + target.repo, + target.number, + undefined, + { + beforeWrite: run.beforeWrite, + }, + ); } else { - await closePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number); + await closePullRequestAsUser(env, githubUserId, target.owner, target.repo, target.number, { + beforeWrite: run.beforeWrite, + }); } + run.acted = true; const label = op === "merge" ? "合并" : "关闭"; await reply( env, @@ -183,6 +278,14 @@ async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "clos `✅ 已${label} PR ${target.owner}/${target.repo}#${target.number}`, ); } catch (err) { + // Nothing reached GitHub yet: give the update back for a retry. + if (err instanceof BeforeGitHubError) throw err; + // Done, only its reply failed: the update must not run again. + if (run.acted) throw err; + // GitHub was called and may have acted (its answer lost): never run + // again. A refusal did nothing: should its reply fail, the command is + // given back and runs again. + if (!githubRefused(err)) run.acted = true; await reply(env, chatId, topicId, errText(err)); } } @@ -193,21 +296,45 @@ export async function syncTelegramWebhook(env: Env): Promise { if (!token) return; const baseUrl = env.BASE_URL; if (!baseUrl) return; - const secret = env.TELEGRAM_WEBHOOK_SECRET; + // Always registered with a secret (explicit or derived from the bot token), + // so the webhook endpoint can authenticate every call. + const secret = await telegramWebhookSecret(env); + const registration = { + url: `${baseUrl.replace(/\/$/, "")}/telegram/webhook`, + secret_token: secret, + allowed_updates: ["message"], + }; + // Registered again only when the registration changed (or once a day, to + // repair a webhook changed elsewhere): this runs every few minutes, and + // each run would otherwise be a subrequest. One KV read per run; a write + // only when it registers. + const digest = [ + ...new Uint8Array( + await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(`${token}|${JSON.stringify(registration)}`), + ), + ), + ] + .slice(0, 12) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + // One record per bot holding what it is registered with now: switching + // A -> B -> A registers A again (a record per digest would still hold A's). + const marker = `telegram:webhook:${token.split(":")[0]}`; + if ((await env.KV.get(marker).catch(() => null)) === digest) return; const res = await fetch(`https://api.telegram.org/bot${token}/setWebhook`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - url: `${baseUrl.replace(/\/$/, "")}/telegram/webhook`, - secret_token: secret || undefined, - allowed_updates: ["message"], - }), + body: JSON.stringify(registration), }); if (!res.ok) { const err = await res.text(); log.error({ status: res.status, err }, "Failed to set Telegram webhook"); + return; } + await env.KV.put(marker, digest, { expirationTtl: 86400 }).catch(() => undefined); } /** Handle a single Telegram update (message). Called from the webhook route. */ @@ -215,32 +342,113 @@ export async function handleTelegramUpdate(env: Env, update: unknown): Promise => { + // Taken: a run that outlived its claim finds another run's "done" here + // and writes nothing. + if (!(await claims.claim(acceptedKey(claimKey), COMMAND_DONE_SECONDS))) + throw new CommandTakenError(); + run.markedDone = true; + }; + } + + try { + await runCommand(env, message, sub, body, text, run); + } catch (err) { + // Finished by another run meanwhile: nothing to give back or repeat. + if (err instanceof CommandTakenError) return; + // Failed before reaching GitHub (e.g. a storage error) or refused by it: + // give the update back (an early "done" too), so Telegram's redelivery + // runs it. After GitHub may have acted, it is done for good — running + // again would repeat the comment / merge. + if (updateId != null) { + if (run.acted) { + // Done for good; a "done" written before the GitHub write needs no + // second write. + if (!run.markedDone) await confirmDone(); + } else { + // Only a "done" this run wrote: one another run wrote while this one + // outlived its claim stays. + if (run.markedDone) { + await claims.release(acceptedKey(claimKey)).catch(() => undefined); + } + await claims.release(claimKey).catch(() => undefined); + } + } + throw err; + } + // A "done" already written before the GitHub write needs no second write. + if (updateId != null && !run.markedDone) await confirmDone(); + + /** Best-effort: unconfirmed, the claim still holds off redeliveries until it expires. */ + async function confirmDone(): Promise { + await confirmClaim(claims, claimKey, COMMAND_DONE_SECONDS).catch((err: unknown) => + log.warn({ err, updateId }, "Failed to confirm a Telegram update"), + ); + } +} + +async function runCommand( + env: Env, + message: TelegramMessage, + sub: string | undefined, + body: string, + text: string, + run: CommandRun, +): Promise { switch (sub) { case "login": return cmdLogin(env, message); case "logout": - return cmdLogout(env, message); + return cmdLogout(env, message, run); case "comment": - if (!body) { + if (!body.trim()) { const chatId = chatIdOf(message); const topicId = message.message_thread_id != null ? String(message.message_thread_id) : undefined; if (chatId) await reply(env, chatId, topicId, "请附上评论内容:/gh comment 你的评论"); return; } - return cmdComment(env, message, body); + return cmdComment(env, message, body, run); case "merge": - return cmdMergeClose(env, message, "merge"); + return cmdMergeClose(env, message, "merge", run); case "close": - return cmdMergeClose(env, message, "close"); + return cmdMergeClose(env, message, "close", run); default: log.info({ text }, "Unhandled /gh command from Telegram"); } diff --git a/tests/telegram-commands.test.ts b/tests/telegram-commands.test.ts index ac8fbe4..594fd96 100644 --- a/tests/telegram-commands.test.ts +++ b/tests/telegram-commands.test.ts @@ -83,7 +83,7 @@ function reply(chatId: string, topicId?: number): Record { } describe("telegram-commands /gh login", () => { - it("stores state with telegramUserId and replies with OAuth URL", async () => { + it("only hands out the OAuth link in the private chat", async () => { let sentBody: Record | undefined; mockFetch((_url, init) => { sentBody = JSON.parse(String(init!.body)) as Record; @@ -94,10 +94,32 @@ describe("telegram-commands /gh login", () => { await handleTelegramUpdate(env, { message: { ...reply("-100123"), text: "/gh login" }, }); - expect(sentBody?.chat_id).toBe("-100123"); + expect(String(sentBody?.text)).not.toContain("github.com/login/oauth/authorize"); + + await handleTelegramUpdate(env, { + message: { + ...reply("42"), + chat: { id: 42, type: "private" }, + text: "/gh login", + }, + }); + expect(sentBody?.chat_id).toBe("42"); expect(String(sentBody?.text)).toContain("github.com/login/oauth/authorize"); }); + + it("runs a redelivered update only once", async () => { + let calls = 0; + mockFetch(() => { + calls++; + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { status: 200 }); + }); + const env = createEnv(); + const update = { update_id: 99, message: { ...reply("-100123"), text: "/gh logout" } }; + await handleTelegramUpdate(env, update); + await handleTelegramUpdate(env, update); + expect(calls).toBe(1); + }); }); describe("telegram-commands /gh logout", () => { @@ -207,3 +229,413 @@ describe("telegram-updates webhook", () => { expect(await res.text()).toBe("ok"); }); }); + +describe("telegram-commands addressed by bot name", () => { + it("runs `/gh@ThisBot` and ignores a command addressed to another bot", async () => { + const sent: string[] = []; + mockFetch((url, init) => { + if (url.endsWith("/getMe")) { + return new Response(JSON.stringify({ ok: true, result: { username: "ReviewBot" } }), { + status: 200, + }); + } + sent.push(String((JSON.parse(String(init!.body)) as Record).text)); + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { status: 200 }); + }); + const env = createEnv(); + await handleTelegramUpdate(env, { + message: { ...reply("-100123"), text: "/gh@reviewbot logout" }, + }); + expect(sent).toHaveLength(1); + await handleTelegramUpdate(env, { + message: { ...reply("-100123"), text: "/gh@OtherBot logout" }, + }); + expect(sent).toHaveLength(1); + }); +}); + +describe("telegram-commands replies", () => { + it("gives an update back when its reply could not be sent", async () => { + let sends = 0; + mockFetch(() => { + sends++; + return new Response(JSON.stringify({ ok: false, description: "Bad Gateway" }), { + status: 502, + }); + }); + const env = createEnv(); + const update = { + update_id: 501, + message: { ...reply("42"), chat: { id: 42, type: "private" }, text: "/gh login" }, + }; + await expect(handleTelegramUpdate(env, update)).rejects.toThrow(); + mockFetch(() => { + sends++; + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { status: 200 }); + }); + // Telegram's redelivery runs it again: the link is sent this time. + await handleTelegramUpdate(env, update); + expect(sends).toBeGreaterThan(1); + }); + + it("keeps a comment's line breaks and indentation", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + const calls: Array<{ url: string; body: string }> = []; + mockFetch((url, init) => { + calls.push({ url, body: String(init!.body) }); + if (String(url).endsWith("/sendMessage")) { + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ html_url: "https://github.com/acme/widget/issues/7#issuecomment-9" }), + { status: 200 }, + ); + }); + await handleTelegramUpdate(env, { + message: { + ...reply("-100123"), + text: "/gh comment first line\n indented\n\n- item", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }); + const ghCall = calls.find((c) => c.url.includes("/repos/")); + expect((JSON.parse(ghCall!.body) as { body: string }).body).toBe( + "first line\n indented\n\n- item", + ); + }); +}); + +describe("telegram-commands refusals and whitespace", () => { + it("gives back a command GitHub never ran when its error reply fails", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + // Linked, but no token: refused before any GitHub request. + await saveTelegramLink(env.DB, "111", "111980217"); + let replies = 0; + let github = 0; + mockFetch((url) => { + if (url.includes("api.github.com")) github++; + replies++; + return new Response(JSON.stringify({ ok: false, description: "Bad Gateway" }), { + status: 502, + }); + }); + const update = { + update_id: 777, + message: { + ...reply("-100123"), + text: "/gh comment hello", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }; + await expect(handleTelegramUpdate(env, update)).rejects.toThrow(); + // Not confirmed: the redelivery runs it (and replies) again. + await expect(handleTelegramUpdate(env, update)).rejects.toThrow(); + expect(github).toBe(0); + expect(replies).toBeGreaterThan(1); + }); + + it("keeps an indented first line of a comment", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + const calls: Array<{ url: string; body: string }> = []; + mockFetch((url, init) => { + calls.push({ url, body: String(init!.body) }); + if (String(url).endsWith("/sendMessage")) { + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ html_url: "https://github.com/acme/widget/issues/7#issuecomment-9" }), + { status: 200 }, + ); + }); + await handleTelegramUpdate(env, { + message: { + ...reply("-100123"), + text: "/gh comment\n code()", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }); + const ghCall = calls.find((c) => c.url.includes("/repos/")); + expect((JSON.parse(ghCall!.body) as { body: string }).body).toBe(" code()"); + }); +}); + +describe("telegram-commands done before the write", () => { + it("records the command as done before GitHub is written to", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + let doneAtWrite: unknown = "unset"; + // Storage touches of the "done" record (each is a quota operation). + let doneTouches = 0; + const kvGet = env.KV.get.bind(env.KV); + env.KV.get = (async (key: string, ...rest: unknown[]) => { + if (key === "accepted:bot:telegram:tg-token:888") doneTouches++; + return (kvGet as (...a: unknown[]) => Promise)(key, ...rest); + }) as KVNamespace["get"]; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input); + const method = input instanceof Request ? input.method : (init?.method ?? "GET"); + if (url.includes("/comments") && method === "POST") { + doneAtWrite = await kvGet("accepted:bot:telegram:tg-token:888"); + } + if (url.endsWith("/sendMessage")) { + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + login: "a", + html_url: "https://github.com/acme/widget/issues/7#issuecomment-9", + }), + { status: 200 }, + ); + }) as typeof fetch; + await handleTelegramUpdate(env, { + update_id: 888, + message: { + ...reply("-100123"), + text: "/gh comment hello", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }); + // A lost confirmation afterwards can no longer let a redelivery write again. + expect(doneAtWrite).not.toBeNull(); + expect(doneAtWrite).not.toBe("unset"); + // Written once, before the write — not confirmed a second time after it + // (which would touch the record once more). + expect(doneTouches).toBe(3); + }); +}); + +describe("telegram-commands outlived claims", () => { + it("writes nothing once another run finished the same update", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + let posted = 0; + // Meanwhile (this run outlived its claim, reading its token) another run + // finished it. + const kvGet = env.KV.get.bind(env.KV); + env.KV.get = (async (key: string, ...rest: unknown[]) => { + if (key === "token:111980217") + await env.KV.put("accepted:bot:telegram:tg-token:999", "other-run"); + return (kvGet as (...a: unknown[]) => Promise)(key, ...rest); + }) as KVNamespace["get"]; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input); + const method = input instanceof Request ? input.method : (init?.method ?? "GET"); + if (url.includes("/comments") && method === "POST") posted++; + if (url.endsWith("/sendMessage")) { + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { + status: 200, + }); + } + return new Response( + JSON.stringify({ + login: "a", + html_url: "https://github.com/acme/widget/issues/7#issuecomment-9", + }), + { status: 200 }, + ); + }) as typeof fetch; + await handleTelegramUpdate(env, { + update_id: 999, + message: { + ...reply("-100123"), + text: "/gh comment hello", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }); + expect(posted).toBe(0); + // The other run's "done" stays. + expect(await env.KV.get("accepted:bot:telegram:tg-token:999")).toBe("other-run"); + }); +}); + +describe("telegram-commands foreign done markers", () => { + it("never gives back a done another run wrote, even when its own read failed", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + // Another run finished meanwhile; this run's token read then fails + // (before anything is written). + const kvGet = env.KV.get.bind(env.KV); + env.KV.get = (async (key: string, ...rest: unknown[]) => { + if (key === "token:111980217") { + await env.KV.put("accepted:bot:telegram:tg-token:1001", "other-run"); + throw new Error("KV down"); + } + return (kvGet as (...a: unknown[]) => Promise)(key, ...rest); + }) as KVNamespace["get"]; + globalThis.fetch = (async () => { + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { + status: 200, + }); + }) as typeof fetch; + await expect( + handleTelegramUpdate(env, { + update_id: 1001, + message: { + ...reply("-100123"), + text: "/gh comment hello", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }), + ).rejects.toThrow(); + expect(await env.KV.get("accepted:bot:telegram:tg-token:1001")).toBe("other-run"); + }); +}); + +describe("telegram-commands logout and bot identity", () => { + it("never unlinks twice when the logout reply failed", async () => { + const env = createEnv(); + const { saveTelegramLink, getTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "old"); + mockFetch( + () => new Response(JSON.stringify({ ok: false, description: "down" }), { status: 502 }), + ); + const update = { update_id: 4242, message: { ...reply("-100123"), text: "/gh logout" } }; + await expect(handleTelegramUpdate(env, update)).rejects.toThrow(); + // Linked again since; the redelivered logout must leave the new link alone. + await saveTelegramLink(env.DB, "111", "new"); + mockFetch( + () => new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { status: 200 }), + ); + await handleTelegramUpdate(env, update); + expect(await getTelegramLink(env.DB, "111")).toBe("new"); + }); + + it("tells two bots' updates with the same number apart", async () => { + let sends = 0; + mockFetch(() => { + sends++; + return new Response(JSON.stringify({ ok: true, result: { message_id: 1 } }), { status: 200 }); + }); + const update = { update_id: 77, message: { ...reply("-100123"), text: "/gh logout" } }; + const kv = createMockKV(); + const db = createMockDB(); + await handleTelegramUpdate({ ...createEnv(), KV: kv, DB: db, TELEGRAM_TOKEN: "1:a" }, update); + await handleTelegramUpdate({ ...createEnv(), KV: kv, DB: db, TELEGRAM_TOKEN: "2:b" }, update); + expect(sends).toBe(2); + }); +}); + +describe("telegram-commands reply failure after the write", () => { + it("keeps the command done when the reply fails after the comment was written", async () => { + const env = createEnv(); + const { saveTelegramLink } = await import("../server/lib/github/store"); + await saveTelegramLink(env.DB, "111", "111980217"); + await env.KV.put( + "token:111980217", + JSON.stringify({ + userId: "111980217", + accessToken: "ghu_test", + expiresAt: Date.now() + 3600_000, + }), + ); + let comments = 0; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input instanceof Request ? input.url : input); + const method = input instanceof Request ? input.method : (init?.method ?? "GET"); + if (url.endsWith("/sendMessage")) return new Response("Bad Gateway", { status: 502 }); + if (url.includes("/comments") && method === "POST") comments++; + return new Response( + JSON.stringify({ + user: { login: "a" }, + html_url: "https://github.com/acme/widget/issues/7#issuecomment-9", + }), + { status: 201 }, + ); + }) as typeof fetch; + const update = { + update_id: 2024, + message: { + ...reply("-100123"), + text: "/gh comment hello", + reply_to_message: { + ...reply("-100123"), + text: "acme/widget#7: Add feature", + entities: [{ type: "text_link", url: "https://github.com/acme/widget/issues/7" }], + }, + }, + }; + // The reply fails: Telegram redelivers the update. + await handleTelegramUpdate(env, update).catch(() => undefined); + await handleTelegramUpdate(env, update).catch(() => undefined); + expect(comments).toBe(1); + }); +});