diff --git a/server/lib/drivers/feishu/updates.ts b/server/lib/drivers/feishu/updates.ts index 8bfdb68..732dcd4 100644 --- a/server/lib/drivers/feishu/updates.ts +++ b/server/lib/drivers/feishu/updates.ts @@ -5,13 +5,31 @@ import { commentAsUser, mergePullRequestAsUser, closePullRequestAsUser, + BeforeGitHubError, + CommandTakenError, + githubRefused, } from "../../github/oauth"; -import { getFeishuLink, removeFeishuLink } from "../../github/store"; -import { getTenantAccessToken, sendText, updateCard } from "./rest"; +import { getFeishuLink, unlinkAsCommand } from "../../github/store"; +import { acceptedKey, claimOnce, confirmClaim, idempotencyStore } from "../../lib/idempotency"; +import { forgetRejectedToken, getTenantAccessToken, sendText, updateCard } from "./rest"; const FEISHU_API = "https://open.feishu.cn"; +const MAX_BODY_SIZE = 1024 * 1024; +/** Handled event ids are remembered this long; replays of older requests are refused. */ +const EVENT_CLAIM_SECONDS = 86400; +/** An event is held this long while it runs (then a retry may take it). */ +const EVENT_PROCESSING_SECONDS = 300; +/** + * Oldest signed request accepted. It stays well inside the event claim, so a + * request old enough for its claim to have expired can never run again, + * while Feishu's own retries (spread over hours) still pass. + */ +const MAX_REQUEST_AGE_SECONDS = 12 * 3600; +const MAX_CLOCK_SKEW_SECONDS = 300; -const GITHUB_TARGET_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/; +// github.com itself only (never e.g. `evilgithub.com`): actions hit the GitHub API. +const GITHUB_TARGET_RE = + /https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/; const BTN_PREFIX = "ghpr|"; interface FeishuSender { @@ -19,6 +37,8 @@ interface FeishuSender { } interface FeishuMessage { chat_id?: string; + /** "p2p" for the private chat with the bot, "group" otherwise. */ + chat_type?: string; content?: string; } interface FeishuAction { @@ -29,9 +49,22 @@ interface FeishuEvent { sender?: FeishuSender; message?: FeishuMessage; action?: FeishuAction; - operator?: { operator_id?: { open_id?: string } }; + /** `card.action.trigger` (schema 2.0): the clicking user is `operator.open_id`. */ + operator?: { open_id?: string; operator_id?: { open_id?: string } }; token?: string; open_message_id?: string; + context?: { open_message_id?: string }; +} + +/** 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 }; } function splitThree(rest: string): [string, string, string] { @@ -51,31 +84,53 @@ function timingSafeEqual(a: string, b: string): boolean { return diff === 0; } -async function hmacSha256Base64(secret: string, payload: string): Promise { - const key = await crypto.subtle.importKey( - "raw", - new TextEncoder().encode(secret), - { name: "HMAC", hash: "SHA-256" }, - false, - ["sign"], - ); - const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload)); - let binary = ""; - const bytes = new Uint8Array(sig); - for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i] ?? 0); - return btoa(binary); +async function sha256Hex(data: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(data)); + return Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); } +/** + * Feishu event signature (when an Encrypt Key is configured): `X-Lark-Signature` + * is the hex SHA-256 of `timestamp + nonce + encryptKey + rawBody`, with the + * timestamp and nonce from `X-Lark-Request-Timestamp` / `X-Lark-Request-Nonce`. + */ export async function verifyFeishuSignature( - appSecret: string, + encryptKey: string, timestamp: string, nonce: string, body: string, signature: string, ): Promise { - const raw = `${timestamp}\n${nonce}\n${body}`; - const computed = await hmacSha256Base64(appSecret, raw); - return timingSafeEqual(computed, signature); + if (!signature) return false; + const computed = await sha256Hex(`${timestamp}${nonce}${encryptKey}${body}`); + return timingSafeEqual(computed, signature.toLowerCase()); +} + +function base64ToBytes(value: string): Uint8Array { + const bin = atob(value); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); + return bytes; +} + +/** + * Decrypt an `{"encrypt": "..."}` body: AES-256-CBC with key SHA-256(encryptKey) + * and the IV in the first 16 bytes of the base64-decoded ciphertext. + */ +export async function decryptFeishuPayload(encryptKey: string, encrypted: string): Promise { + const keyBytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(encryptKey)); + const data = base64ToBytes(encrypted); + const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-CBC" }, false, [ + "decrypt", + ]); + const plain = await crypto.subtle.decrypt( + { name: "AES-CBC", iv: data.slice(0, 16) }, + key, + data.slice(16), + ); + return new TextDecoder().decode(plain); } function describeError(err: unknown): string { @@ -98,22 +153,50 @@ function extractTarget(text: string): { owner: string; repo: string; number: num return { owner: m[1] ?? "", repo: m[2] ?? "", number }; } +/** Whether a failed reply may succeed later (then the event is given back). */ +function replyRetryable(result: { status?: number; errorCode?: string }): boolean { + if (!result.status || result.status >= 500 || result.status === 429) return true; + return result.errorCode === "FEISHU_TOKEN" || result.errorCode === "RATE_LIMITED"; +} + +/** + * Send a reply. One that could not be sent for now throws, so the event is + * retried rather than confirmed unanswered (a login link never sent); a + * refusal that a retry cannot change is logged. + */ async function replyToken(env: Env, chatId: string, text: string): Promise { const tokenRes = await getTenantAccessToken(env); if (!tokenRes.ok || !tokenRes.token) { log.warn({ err: tokenRes.error }, "Feishu token unavailable for reply"); - return; + throw new Error("Feishu token unavailable for reply"); } - await sendText(tokenRes.token, chatId, text); + const result = await forgetRejectedToken( + await sendText(tokenRes.token, chatId, text), + env, + tokenRes.token, + ); + if (result.ok) return; + log.warn({ chatId, err: result.error }, "Feishu reply failed"); + if (replyRetryable(result)) throw new Error(`Feishu reply failed: ${result.error ?? "unknown"}`); } -async function handleLogin(env: Env, openId: string, chatId: string): Promise { +async function handleLogin( + env: Env, + openId: string, + chatId: string, + chatType: string | undefined, +): Promise { + // An authorization link posted in a group can be opened by anyone there; + // binding happens in the private chat with the bot only. + if (chatType !== "p2p") { + await replyToken(env, chatId, "请私聊机器人发送 /gh login 绑定 GitHub 账号。"); + return; + } const state = crypto.randomUUID(); const pending = { redirectTo: "/admin", expiresAt: Date.now() + 10 * 60 * 1000, - feishuUserId: openId, - feishuChatId: chatId, + link: { platform: "feishu", userId: openId, chatId }, }; await env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: 600 }); const url = getOAuthURL(env.GITHUB_CLIENT_ID ?? "", state); @@ -128,13 +211,21 @@ async function handleLogin(env: Env, openId: string, chatId: string): Promise { +async function handleLogout( + env: Env, + openId: string, + chatId: string, + run: CommandRun, +): Promise { const linked = await getFeishuLink(env.DB, openId); if (!linked) { await replyToken(env, chatId, "你还没有绑定 GitHub 账号。"); return; } - await removeFeishuLink(env.DB, openId); + await unlinkAsCommand(env, "feishu", openId, run.done); + // Done from here: should the reply fail, a retry must not unlink again + // (by then it could remove a link made since). + run.acted = true; await replyToken(env, chatId, "已解绑 GitHub 账号。"); } @@ -143,6 +234,7 @@ async function handleComment( openId: string, chatId: string, text: string, + run: CommandRun, ): Promise { const githubUserId = await getFeishuLink(env.DB, openId); if (!githubUserId) { @@ -159,25 +251,37 @@ async function handleComment( return; } const ghIdx = text.indexOf("/gh"); - const rest = text.slice(ghIdx + 3).trim(); - const parts = rest.split(/\s+/); - const linkIdx = parts.findIndex((p) => p.includes("github.com")); - const body = - parts - .slice(linkIdx + 1) - .join(" ") - .trim() || "(来自飞书)"; + // Only leading space goes: a comment's trailing lines are its own. + const rest = text.slice(ghIdx + 3).replace(/^\s+/, ""); + // The comment is what follows the link, as written (line breaks and + // indentation kept). + const link = /\S*github\.com\S*/.exec(rest); + const written = (link ? rest.slice(link.index + link[0].length) : rest).replace( + /^[ \t]*\r?\n?/, + "", + ); + const body = written.trim() ? written : "(来自飞书)"; try { const res = await commentAsUser( - env.KV, + env, githubUserId, target.owner, target.repo, target.number, body, + { beforeWrite: run.beforeWrite }, ); + run.acted = true; await replyToken(env, chatId, `✅ 已评论:[查看](${res.htmlUrl})(@${res.login})`); } catch (err) { + // Nothing reached GitHub yet: give the event back for a retry. + if (err instanceof BeforeGitHubError) throw err; + // Done, only its reply failed: the event 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 replyToken(env, chatId, `❌ ${describeError(err)}`); } } @@ -188,6 +292,7 @@ async function handleMergeOrClose( chatId: string, action: "merge" | "close", body: string, + run: CommandRun, ): Promise { const githubUserId = await getFeishuLink(env.DB, openId); if (!githubUserId) { @@ -207,25 +312,48 @@ async function handleMergeOrClose( } try { if (action === "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; await replyToken( env, chatId, `✅ 已${action === "merge" ? "合并" : "关闭"} ${target.owner}/${target.repo}#${target.number}`, ); } catch (err) { + // Nothing reached GitHub yet: give the event back for a retry. + if (err instanceof BeforeGitHubError) throw err; + // Done, only its reply failed: the event 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 replyToken(env, chatId, `❌ ${describeError(err)}`); } } -async function handleMessage(env: Env, event: FeishuEvent): Promise { - const sender = event.sender ?? {}; - const openId = sender.sender_id?.open_id ?? sender.sender_id?.union_id ?? ""; +/** + * The `/gh` command a message carries, or null: only a message that is a + * command — `/gh` first, after any @mentions of the bot — runs one; quoting + * or discussing a command never does. + */ +function commandOf(event: FeishuEvent): string | null { const message = event.message ?? {}; - const chatId = message.chat_id ?? ""; let text = ""; if (message.content) { try { @@ -235,25 +363,34 @@ async function handleMessage(env: Env, event: FeishuEvent): Promise { text = ""; } } - const idx = text.indexOf("/gh"); - if (idx < 0) return; - const rest = text.slice(idx + 3).trim(); + const command = text.replace(/^\s*(?:@\S+\s+)*/, ""); + return /^\/gh(?:\s|$)/.test(command) ? command : null; +} + +async function handleMessage(env: Env, event: FeishuEvent, run: CommandRun): Promise { + const sender = event.sender ?? {}; + const openId = sender.sender_id?.open_id ?? sender.sender_id?.union_id ?? ""; + const message = event.message ?? {}; + const chatId = message.chat_id ?? ""; + const command = commandOf(event); + if (!command) return; + const rest = command.slice(3).trim(); const sub = rest.split(/\s+/)[0] ?? ""; switch (sub) { case "login": - await handleLogin(env, openId, chatId); + await handleLogin(env, openId, chatId, message.chat_type); break; case "logout": - await handleLogout(env, openId, chatId); + await handleLogout(env, openId, chatId, run); break; case "comment": - await handleComment(env, openId, chatId, text); + await handleComment(env, openId, chatId, command, run); break; case "merge": - await handleMergeOrClose(env, openId, chatId, "merge", text); + await handleMergeOrClose(env, openId, chatId, "merge", command, run); break; case "close": - await handleMergeOrClose(env, openId, chatId, "close", text); + await handleMergeOrClose(env, openId, chatId, "close", command, run); break; default: await replyToken( @@ -276,13 +413,21 @@ function buildResultCard(ok: boolean, message: string): Record }; } -async function handleCardAction(env: Env, payload: Record): Promise { +async function handleCardAction( + env: Env, + payload: Record, + run: CommandRun, +): Promise { const event = (payload.event ?? {}) as FeishuEvent; const action = event.action ?? {}; const actionId = action.action_id ?? action.value?.v ?? ""; - const openId = event.operator?.operator_id?.open_id ?? event.sender?.sender_id?.open_id ?? ""; + const openId = + event.operator?.open_id ?? + event.operator?.operator_id?.open_id ?? + event.sender?.sender_id?.open_id ?? + ""; const cardToken = event.token ?? ""; - const openMessageId = event.open_message_id ?? ""; + const openMessageId = event.context?.open_message_id ?? event.open_message_id ?? ""; if (!actionId.startsWith(BTN_PREFIX)) return; @@ -303,16 +448,28 @@ async function handleCardAction(env: Env, payload: Record): Pro } try { if (isMerge) { - await mergePullRequestAsUser(env.KV, githubUserId, owner, repo, number); + await mergePullRequestAsUser(env, githubUserId, owner, repo, number, undefined, { + beforeWrite: run.beforeWrite, + }); } else { - await closePullRequestAsUser(env.KV, githubUserId, owner, repo, number); + await closePullRequestAsUser(env, githubUserId, owner, repo, number, { + beforeWrite: run.beforeWrite, + }); } + run.acted = true; await replyCard( env, cardToken, buildResultCard(true, `${isMerge ? "已合并" : "已关闭"} ${owner}/${repo}#${number}`), ); } catch (err) { + if (err instanceof BeforeGitHubError) throw err; + // Done, only its card update failed: the event 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 replyCard(env, cardToken, buildResultCard(false, describeError(err))); } return; @@ -329,12 +486,40 @@ async function replyCard( card: Record, ): Promise { const tokenRes = await getTenantAccessToken(env); - if (!tokenRes.ok || !tokenRes.token) return; - await updateCard(tokenRes.token, cardToken, card); + if (!tokenRes.ok || !tokenRes.token) { + log.warn({ err: tokenRes.error }, "Feishu token unavailable for card update"); + throw new Error("Feishu token unavailable for card update"); + } + const result = await forgetRejectedToken( + await updateCard(tokenRes.token, cardToken, card), + env, + tokenRes.token, + ); + if (result.ok) return; + log.warn({ err: result.error }, "Failed to update the Feishu card"); + if (replyRetryable(result)) + throw new Error(`Feishu card update failed: ${result.error ?? "unknown"}`); } +/** + * Inbound Feishu callbacks (events and card actions). Every request must be + * authenticated by the app's own credentials before anything runs: + * - with `FEISHU_ENCRYPT_KEY`, the `X-Lark-Signature` must verify and an + * encrypted body is decrypted with that key; + * - with `FEISHU_VERIFICATION_TOKEN`, the token inside the payload must match. + * At least one of them is required; without either the endpoint refuses all + * requests, since an unauthenticated one could act as any linked user. + */ export async function handleFeishuWebhookRequest(request: Request, env: Env): Promise { + // Unauthenticated until verified below: bound what is read and parsed. + const contentLength = Number(request.headers.get("content-length") ?? 0); + if (contentLength > MAX_BODY_SIZE) { + return new Response("Request too large", { status: 413 }); + } const rawBody = await request.text(); + if (rawBody.length > MAX_BODY_SIZE) { + return new Response("Request too large", { status: 413 }); + } let payload: Record; try { payload = JSON.parse(rawBody); @@ -342,20 +527,54 @@ export async function handleFeishuWebhookRequest(request: Request, env: Env): Pr return new Response("invalid json", { status: 400 }); } + const encryptKey = env.FEISHU_ENCRYPT_KEY?.trim() ?? ""; + const verificationToken = env.FEISHU_VERIFICATION_TOKEN?.trim() ?? ""; + if (!encryptKey && !verificationToken) { + log.warn("Feishu callback refused: FEISHU_ENCRYPT_KEY / FEISHU_VERIFICATION_TOKEN not set"); + return new Response("Feishu callback verification is not configured", { status: 403 }); + } + + if (encryptKey && typeof payload.encrypt === "string") { + try { + payload = JSON.parse(await decryptFeishuPayload(encryptKey, payload.encrypt)); + } catch (err) { + log.warn({ err: String(err) }, "Feishu payload decryption failed"); + return new Response("invalid payload", { status: 400 }); + } + } + const header = payload.header as Record | undefined; const eventPart = payload.event as Record | undefined; const type = (payload.type as string) ?? header?.event_type ?? eventPart?.type ?? ""; + // The verification token travels inside the (decrypted) payload: in + // `header.token` for schema 2.0 events, at the top level otherwise. + const token = String(header?.token ?? payload.token ?? ""); + if (verificationToken && !timingSafeEqual(token, verificationToken)) { + log.warn("Feishu verification token mismatch"); + return new Response("invalid token", { status: 401 }); + } + if (type === "url_verification") { return Response.json({ challenge: (payload.challenge as string) ?? "" }); } - const appSecret = env.FEISHU_APP_SECRET?.trim() ?? ""; - const signature = request.headers.get("x-lark-signature") ?? ""; - const timestamp = request.headers.get("x-lark-timestamp") ?? ""; - const nonce = request.headers.get("x-lark-nonce") ?? ""; - if (appSecret && signature) { - const ok = await verifyFeishuSignature(appSecret, timestamp, nonce, rawBody, signature); + if (encryptKey) { + const timestamp = request.headers.get("x-lark-request-timestamp") ?? ""; + // The signature covers the timestamp: a stale one marks a replay that + // may outlive the event claim below. + const age = Math.floor(Date.now() / 1000) - Number(timestamp); + if (!Number.isFinite(age) || age > MAX_REQUEST_AGE_SECONDS || age < -MAX_CLOCK_SKEW_SECONDS) { + log.warn({ timestamp }, "Feishu callback refused: request timestamp out of range"); + return new Response("stale request", { status: 401 }); + } + const ok = await verifyFeishuSignature( + encryptKey, + timestamp, + request.headers.get("x-lark-request-nonce") ?? "", + rawBody, + request.headers.get("x-lark-signature") ?? "", + ); if (!ok) { log.warn("Feishu signature verification failed"); return new Response("invalid signature", { status: 401 }); @@ -363,16 +582,73 @@ export async function handleFeishuWebhookRequest(request: Request, env: Env): Pr } const eventType = (header?.event_type as string) ?? eventPart?.type ?? type; - try { - if (eventType === "im.message.receive_v1" || eventType === "message") { - await handleMessage(env, (payload.event ?? payload) as FeishuEvent); - } else if (eventType === "card.action.trigger") { - await handleCardAction(env, payload); - } - } catch (err) { - log.error({ err }, "Feishu webhook handling failed"); + const isMessage = eventType === "im.message.receive_v1" || eventType === "message"; + // Nothing to do for an ordinary chat message (no `/gh` command) or an + // event type not handled: answered at once, with no dedup records written + // (each would be D1 writes for an event that has no side effect). + if ( + (isMessage && !commandOf((payload.event ?? payload) as FeishuEvent)) || + (!isMessage && eventType !== "card.action.trigger") + ) { + return new Response("ok", { status: 200 }); } + // Feishu retries a callback it considers failed; run each event once. An + // event whose earlier run is unconfirmed is retried later, never dropped. + const eventId = String(header?.event_id ?? payload.uuid ?? ""); + const claims = idempotencyStore(env.DB, env.KV); + const claimKey = `bot:feishu:${eventId}`; + if (eventId) { + const state = await claimOnce(claims, claimKey, EVENT_PROCESSING_SECONDS); + if (state === "done") return new Response("ok", { status: 200 }); + if (state === "pending") return new Response("temporarily unavailable", { status: 503 }); + } + + const run: CommandRun = { acted: false }; + // Done on record before GitHub is written to: should the confirmation + // after it fail, a retry still never repeats the write. + if (eventId) { + run.done = { key: acceptedKey(claimKey), ttl: EVENT_CLAIM_SECONDS }; + run.beforeWrite = async (): Promise => { + // Taken: a run that outlived its claim finds another run's "done" here + // and writes nothing. + if (!(await claims.claim(acceptedKey(claimKey), EVENT_CLAIM_SECONDS))) + throw new CommandTakenError(); + run.markedDone = true; + }; + } + try { + if (isMessage) { + await handleMessage(env, (payload.event ?? payload) as FeishuEvent, run); + } else if (eventType === "card.action.trigger") { + await handleCardAction(env, payload, run); + } + } catch (err) { + // Finished by another run meanwhile: nothing to give back or repeat. + if (err instanceof CommandTakenError) return new Response("ok", { status: 200 }); + log.error({ err }, "Feishu webhook handling failed"); + // Failed before reaching GitHub: give the event back and answer with an + // error, so Feishu's retry runs it. After GitHub acted it stays claimed. + if (!run.acted) { + if (eventId) { + // An early "done" this run wrote (right before a write GitHub + // refused) too — never one another run wrote meanwhile. + if (run.markedDone) { + await claims.release(acceptedKey(claimKey)).catch(() => undefined); + } + await claims.release(claimKey).catch(() => undefined); + } + return new Response("temporarily unavailable", { status: 503 }); + } + } + + // A "done" already written before the GitHub write needs no second write. + if (eventId && !run.markedDone) { + // Best-effort: unconfirmed, the claim still holds off retries until it expires. + await confirmClaim(claims, claimKey, EVENT_CLAIM_SECONDS).catch((err: unknown) => + log.warn({ err, eventId }, "Failed to confirm a Feishu event"), + ); + } return new Response("ok", { status: 200 }); } diff --git a/server/lib/types.ts b/server/lib/types.ts index 59ddedb..304bba6 100644 --- a/server/lib/types.ts +++ b/server/lib/types.ts @@ -16,6 +16,14 @@ export interface Env { TELEGRAM_RICH_HEADER_HOST?: string; FEISHU_APP_ID?: string; FEISHU_APP_SECRET?: string; + /** + * Feishu event "Encrypt Key": verifies `X-Lark-Signature` and decrypts + * encrypted callbacks. This or FEISHU_VERIFICATION_TOKEN is required for + * inbound Feishu commands and card buttons. + */ + FEISHU_ENCRYPT_KEY?: string; + /** Feishu event "Verification Token", checked against every callback payload. */ + FEISHU_VERIFICATION_TOKEN?: string; /** * When enabled ("1"/"true"), GitHub users without any group access get a * personal group on first login instead of being blocked. diff --git a/tests/feishu-inbound.test.ts b/tests/feishu-inbound.test.ts index c798dd1..a78e990 100644 --- a/tests/feishu-inbound.test.ts +++ b/tests/feishu-inbound.test.ts @@ -1,86 +1,217 @@ import { describe, it, expect } from "bun:test"; import type { Env } from "../server/lib/types"; import { + decryptFeishuPayload, verifyFeishuSignature, handleFeishuWebhookRequest, } from "../server/lib/drivers/feishu/updates"; +import { createMemoryKV } from "./d1-sqlite"; -function sign(secret: string, timestamp: string, nonce: string, body: string): Promise { - return (async () => { - const key = await crypto.subtle.importKey( - "raw", - new TextEncoder().encode(secret), - { name: "HMAC", hash: "SHA-256" }, - false, - ["sign"], - ); - const sig = await crypto.subtle.sign( - "HMAC", - key, - new TextEncoder().encode(`${timestamp}\n${nonce}\n${body}`), - ); - let binary = ""; - const bytes = new Uint8Array(sig); - for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i] ?? 0); - return btoa(binary); - })(); +async function sha256Hex(data: string): Promise { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(data)); + return Array.from(new Uint8Array(digest)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); } -const stubKV = { - get: async () => null, - put: async () => undefined, - delete: async () => undefined, -} as unknown as KVNamespace; -const stubDB = {} as unknown as D1Database; -const stubEnv: Env = { - GITHUB_WEBHOOK_SECRET: "", - FEISHU_APP_ID: "", - FEISHU_APP_SECRET: "", - KV: stubKV, - DB: stubDB, -}; +/** Feishu's event signature: hex SHA-256 of timestamp + nonce + encryptKey + body. */ +function sign(encryptKey: string, timestamp: string, nonce: string, body: string): Promise { + return sha256Hex(`${timestamp}${nonce}${encryptKey}${body}`); +} + +/** Encrypt like Feishu: AES-256-CBC, key SHA-256(encryptKey), IV prepended. */ +async function encrypt(encryptKey: string, plaintext: string): Promise { + const keyBytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(encryptKey)); + const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-CBC" }, false, [ + "encrypt", + ]); + const iv = crypto.getRandomValues(new Uint8Array(16)); + const ct = new Uint8Array( + await crypto.subtle.encrypt({ name: "AES-CBC", iv }, key, new TextEncoder().encode(plaintext)), + ); + const all = new Uint8Array(16 + ct.length); + all.set(iv); + all.set(ct, 16); + let bin = ""; + for (const b of all) bin += String.fromCharCode(b); + return btoa(bin); +} + +function env(overrides: Partial = {}): Env { + return { + GITHUB_WEBHOOK_SECRET: "", + FEISHU_APP_ID: "", + FEISHU_APP_SECRET: "", + KV: createMemoryKV().kv, + DB: {} as D1Database, + ...overrides, + }; +} + +function post(body: string, headers: Record = {}): Request { + return new Request("https://x/feishu/webhook", { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body, + }); +} describe("feishu signature", () => { it("verifies a correct signature", async () => { - const secret = "s3cr3t"; - const ts = "1700000000"; - const nonce = "abc"; const body = JSON.stringify({ hello: "world" }); - const sig = await sign(secret, ts, nonce, body); - expect(await verifyFeishuSignature(secret, ts, nonce, body, sig)).toBe(true); + const sig = await sign("key", "1700000000", "abc", body); + expect(await verifyFeishuSignature("key", "1700000000", "abc", body, sig)).toBe(true); }); - it("rejects a wrong signature", async () => { - const secret = "s3cr3t"; + it("rejects a wrong or missing signature", async () => { const body = JSON.stringify({ hello: "world" }); const sig = await sign("other", "1", "2", body); - expect(await verifyFeishuSignature(secret, "1", "2", body, sig)).toBe(false); + expect(await verifyFeishuSignature("key", "1", "2", body, sig)).toBe(false); + expect(await verifyFeishuSignature("key", "1", "2", body, "")).toBe(false); + }); + + it("decrypts an encrypted payload", async () => { + const encrypted = await encrypt("key", JSON.stringify({ a: 1 })); + expect(JSON.parse(await decryptFeishuPayload("key", encrypted))).toEqual({ a: 1 }); }); }); describe("feishu webhook", () => { - it("answers the url_verification challenge", async () => { - const body = JSON.stringify({ type: "url_verification", challenge: "xyz123" }); - const req = new Request("https://x/feishu/webhook", { - method: "POST", - headers: { "content-type": "application/json" }, - body, - }); - const res = await handleFeishuWebhookRequest(req, stubEnv); - expect(res.status).toBe(200); - const json = await res.json(); - expect(json.challenge).toBe("xyz123"); + it("refuses every request when no verification is configured", async () => { + const body = JSON.stringify({ type: "url_verification", challenge: "xyz" }); + const res = await handleFeishuWebhookRequest(post(body), env()); + expect(res.status).toBe(403); }); - it("rejects a bad signature with 401 when a secret is configured", async () => { - const env = { ...stubEnv, FEISHU_APP_SECRET: "s3cr3t" }; - const body = JSON.stringify({ type: "other", challenge: "x" }); - const req = new Request("https://x/feishu/webhook", { - method: "POST", - headers: { "content-type": "application/json", "x-lark-signature": "deadbeef" }, - body, + it("answers the url_verification challenge with a matching token", async () => { + const body = JSON.stringify({ type: "url_verification", challenge: "xyz123", token: "vt" }); + const res = await handleFeishuWebhookRequest( + post(body), + env({ FEISHU_VERIFICATION_TOKEN: "vt" }), + ); + expect(res.status).toBe(200); + expect(((await res.json()) as { challenge: string }).challenge).toBe("xyz123"); + }); + + it("rejects a wrong verification token", async () => { + const body = JSON.stringify({ + schema: "2.0", + header: { event_type: "im.message.receive_v1", token: "nope" }, + event: {}, }); - const res = await handleFeishuWebhookRequest(req, env); + const res = await handleFeishuWebhookRequest( + post(body), + env({ FEISHU_VERIFICATION_TOKEN: "vt" }), + ); expect(res.status).toBe(401); }); + + it("rejects a missing or bad signature when an encrypt key is set", async () => { + const body = JSON.stringify({ schema: "2.0", header: { event_type: "x" }, event: {} }); + const e = env({ FEISHU_ENCRYPT_KEY: "key" }); + expect((await handleFeishuWebhookRequest(post(body), e)).status).toBe(401); + expect( + (await handleFeishuWebhookRequest(post(body, { "x-lark-signature": "deadbeef" }), e)).status, + ).toBe(401); + }); + + it("accepts a correctly signed, encrypted event once", async () => { + const inner = JSON.stringify({ + schema: "2.0", + header: { event_id: "ev-1", event_type: "unknown.event" }, + event: {}, + }); + const body = JSON.stringify({ encrypt: await encrypt("key", inner) }); + const ts = String(Math.floor(Date.now() / 1000)); + const nonce = "n1"; + const headers = { + "x-lark-request-timestamp": ts, + "x-lark-request-nonce": nonce, + "x-lark-signature": await sign("key", ts, nonce, body), + }; + const e = env({ FEISHU_ENCRYPT_KEY: "key" }); + expect((await handleFeishuWebhookRequest(post(body, headers), e)).status).toBe(200); + // The retried delivery of the same event is acknowledged without running again. + expect((await handleFeishuWebhookRequest(post(body, headers), e)).status).toBe(200); + }); + + it("refuses a correctly signed request whose timestamp is stale", async () => { + const inner = JSON.stringify({ + schema: "2.0", + header: { event_id: "ev-old", event_type: "unknown.event" }, + event: {}, + }); + const body = JSON.stringify({ encrypt: await encrypt("key", inner) }); + // Older than any event claim could still remember. + const ts = String(Math.floor(Date.now() / 1000) - 13 * 3600); + const headers = { + "x-lark-request-timestamp": ts, + "x-lark-request-nonce": "n2", + "x-lark-signature": await sign("key", ts, "n2", body), + }; + const e = env({ FEISHU_ENCRYPT_KEY: "key" }); + expect((await handleFeishuWebhookRequest(post(body, headers), e)).status).toBe(401); + }); + + it("refuses an oversized body before parsing it", async () => { + const body = JSON.stringify({ pad: "x".repeat(1024 * 1024) }); + const e = env({ FEISHU_VERIFICATION_TOKEN: "vt" }); + expect((await handleFeishuWebhookRequest(post(body), e)).status).toBe(413); + }); +}); + +describe("feishu command parsing", () => { + it("never runs a command merely quoted inside a message", async () => { + const e = env({ FEISHU_VERIFICATION_TOKEN: "vt" }); + // Any account lookup would fail loudly: a parsed command would answer 503. + e.DB = { + prepare: (): never => { + throw new Error("command ran"); + }, + } as unknown as D1Database; + const body = JSON.stringify({ + schema: "2.0", + header: { event_id: "ev-q", event_type: "im.message.receive_v1", token: "vt" }, + event: { + sender: { sender_id: { open_id: "ou_1" } }, + message: { + chat_id: "oc_1", + content: JSON.stringify({ + text: "please do not run /gh merge https://github.com/o/r/pull/7", + }), + }, + }, + }); + expect((await handleFeishuWebhookRequest(post(body), e)).status).toBe(200); + }); +}); + +describe("feishu command retries", () => { + it("answers 503 and releases the event when it failed before reaching GitHub", async () => { + const e = env({ FEISHU_VERIFICATION_TOKEN: "vt" }); + // A D1 binding whose link lookup fails: the command never reaches GitHub. + e.DB = { + prepare: (): unknown => ({ + bind: (): unknown => ({ + all: async (): Promise => { + throw new Error("D1 down"); + }, + }), + }), + } as unknown as D1Database; + const body = JSON.stringify({ + schema: "2.0", + header: { event_id: "ev-9", event_type: "im.message.receive_v1", token: "vt" }, + event: { + sender: { sender_id: { open_id: "ou_1" } }, + message: { + chat_id: "oc_1", + content: JSON.stringify({ text: "/gh merge https://github.com/o/r/pull/1" }), + }, + }, + }); + expect((await handleFeishuWebhookRequest(post(body), e)).status).toBe(503); + // The retry is not swallowed as a duplicate. + expect((await handleFeishuWebhookRequest(post(body), e)).status).toBe(503); + }); });