mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
* fix(log): preserve structured error details Error objects lose their useful details when serialized as plain JSON. Keep the message, stack and cause in structured log output. * fix(runtime): bound shared in-flight waits A canceled request can leave its shared promise pending forever. Bound joins and coordinate a single replacement so later requests make progress without multiplying upstream work. * fix(bot): reject oversized callback bodies Reject declared oversized bot callbacks before reading their bodies. This keeps unauthenticated requests from wasting worker resources. * test(d1): exercise real sqlite transactions Exercise real foreign keys, transactions and conditional statements instead of mocks that cannot reproduce lost updates or cascades. * fix(storage): preserve claims across kv fallback Only missing tables justify KV fallback; other failures must surface. Remember fallback writes so migration to D1 cannot forget claims and replay completed work. Share marker checks without extra writes. * fix(filter): use isolated linear-time patterns Backtracking patterns can exhaust worker CPU on untrusted payloads. Use linear-time matching and separate bounded cache namespaces so glob and regex entries cannot corrupt each other. * fix(filter): read each event branch correctly Deployment and check branches live in event-specific nested fields. Read those fields and remove only the actual leading ref prefix. * fix(filter): read only own payload properties Inherited object properties are not webhook payload data. Read own properties only so JSONPath cannot traverse prototypes. * fix(filter): validate executable condition trees Malformed trees and unsupported patterns must not silently turn an exclude rule into a pass. Validate the shape and only the patterns the evaluator actually executes. * fix(i18n): bound and cache translation loads Repeated misses and simultaneous override loads spend KV reads for the same language. Cache confirmed misses and share bounded loads without caching read failures as missing translations. * i18n(bot): explain command and account failures Explain account linking, command failures and skipped delivery outcomes consistently in both supported languages. * fix(github): bound and reuse app token fetches Repeated token exchanges waste requests and JWT work for every event. Reuse valid installation tokens, share refreshes and back off briefly after failures while keeping every shared wait bounded. * fix(github): restrict enrichment request urls Webhook-provided URLs must never receive an installation token on another host. Restrict enrichment to GitHub repository API paths, reject redirects and bound optional requests. * fix(formatter): preserve invalid code points Out-of-range numeric entities can throw while formatting a delivery. Keep invalid code points verbatim instead of aborting the message. * fix(formatter): preserve bounded markdown text Code spans, fences, indentation and autolinks are Markdown content, not HTML tags to strip. Preserve them while bounding cleanup input and reusing results across routes for the same event. * fix(formatter): strip only leading ref prefixes A short branch or tag may itself contain refs/heads or refs/tags. Strip one leading full-ref prefix at the caller and keep short names unchanged when generating labels and links. * fix(gitea): link push authors to their forge A Gitea author is not the same-named GitHub account. Build author profile links from the originating forge. * fix(formatter): render deployment state values The deployment status object stringifies as [object Object]. Render its actual state in the status field. * fix(formatter): read security severity levels The scanner severity is not the security severity of an alert. Prefer the security level so critical and high alerts get the right label and color. * fix(formatter): hide actions on other forges Action buttons call the GitHub API as the linked user. Hide them for other forges to avoid operating on a same-named GitHub repository. * fix(check): isolate updates by check suite Same-named checks from different suites must not edit one message. Include the suite or app identity and retain the former key for controlled adoption of existing tracked messages. * fix(logs): scope queries before limiting results Filter authorized groups in SQL before LIMIT and aggregate only visible rows. Preserve current group attribution for late writes, surface read failures and combine related totals in one scan. * perf(d1): index pruning and failed send queries Pruning and failure views should not scan all historical rows. Index the high-value access paths without adding a write-heavy index for infrequent delivery-detail lookups. * fix(discord): bound individual api requests An unbounded API request can outlive an update-chain lock. Bound each request so another holder cannot race a late edit. * fix(discord): defer long rate-limit waits Long rate-limit sleeps block delivery progress inside a worker. Return a retryable 429 for the queue when the wait exceeds the bound. * fix(discord): encode channel path segments Stored channel and message ids are path segments, not URL paths. Encode them so aliases cannot address another Discord resource. * fix(discord): reuse nonces after lost responses A successful create may lose its response. Reuse a stable nonce with enforce_nonce so retries recover that message instead of posting duplicates or accepting an unreadable success. * fix(discord): constrain embeds and role mentions Respect combined embed and component limits as well as field caps. Restrict allowed mentions to validated route roles so payload text cannot notify everyone. * fix(discord): resume bounded command syncs Application changes, command rollbacks and large guild lists can leave commands stale indefinitely. Track the current hash per app and resume bounded paginated work without needless KV writes. * fix(github): verify installation management An installation id is user-controlled, and repository access is not installation management. Verify the owning account or an active organization admin using the user token and read:org scope. * fix(github): resolve immutable member ids A login can be renamed and reclaimed before its first sign-in. Resolve the current immutable user id when membership is granted so a future holder of the login cannot inherit access. * fix(auth): revoke stale sessions and tokens Revoked or rotated credentials must stop working despite stale KV replicas. Track the live token and revocations in D1 and preserve immutable identity bindings rather than trusting a recycled login. * fix(auth): bind sessions and tokens to identity Automatic retries can repeat non-idempotent user actions. Disable those retries and expose a write hook so bot handlers can record completion immediately before the GitHub write. * fix(discord): defer and deduplicate interactions Acknowledge slow actions before Discord times out and deduplicate interaction writes. Preserve comment text and reject edits whose source changed after the modal opened. * fix(telegram): always verify webhook secrets Webhook verification must not silently disable itself when the optional secret is absent. Derive a stable secret from the bot token and reject callbacks when verification is unavailable. * fix(telegram): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(telegram): honor nested rate-limit delays Telegram places retry_after inside parameters, not at the top level. Read that value and defer long waits to the delivery queue. * fix(telegram): report unreadable send results An unreadable successful response may already have sent the message. Report an explicit uncertain result instead of retrying a create without an idempotency key or pretending it succeeded. * fix(telegram): keep editable messages as text Guessing photo versus text from message content makes later edits use the wrong API and a smaller caption budget. Always send text and use the avatar as a link preview. * fix(telegram): render hard breaks as newlines Telegram HTML does not support br tags. Render Markdown hard breaks as plain newlines so otherwise valid messages are accepted. * fix(telegram): clamp visible html characters Telegram counts visible characters, not HTML source bytes. Truncate without splitting tags, entities or surrogate pairs. * fix(telegram): honor the author emoji toggle The author marker must obey the group emoji preference just like formatter-added decoration. * 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. * fix(feishu): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(feishu): classify retryable api failures Business error codes can be transient even in HTTP 200 responses. Classify token and rate-limit errors for retry and defer long waits. * fix(feishu): retry sends with stable uuids An unreadable response does not prove a send failed. Reuse the same uuid for retries so recovering the result cannot create a second Feishu message. * fix(feishu): refresh and evict tokens safely Separate app token caches, stop reusing refused tokens and share refreshes. Cache failures briefly and keep valid tokens in memory when a best-effort KV cache write fails. * fix(feishu): use the card update endpoint Delayed card updates use the card update endpoint; the config endpoint cannot update an interaction response. * fix(feishu): neutralize untrusted mentions Forge text is untrusted and can contain at-all tags. Neutralize mentions in card bodies and footers before rendering. * fix(feishu): authenticate and dedupe callbacks Authenticate signed or token-verified callbacks before dispatching commands. Decode encrypted envelopes and handle card actions using the correct fields without claiming irrelevant chat events. * fix(target): normalize actual destinations Different target spellings can name the same actual destination. Normalize channel, thread and topic identities for ownership checks and per-route duplicate suppression. * fix(config): transact per-group configuration Whole-table writes and cached snapshots can overwrite other groups or resurrect removed configuration. Use per-group guarded writes, one-time identity migration and explicit unreadable-row failures. * fix(group): preserve identity through lifecycle Group names are mutable and reusable, so they cannot own durable state. Preserve immutable identities across lifecycle operations and commit invite use with membership under transaction-time guards. * fix(oauth): confirm account links and installs A login link or installation id is not proof of account ownership. Verify installation management, bind browser state and require an explicit account-link confirmation before granting chat access. * fix(queue): fence leases and record target outcomes Retries must remember completed targets and distinguish active lease holders. Fence state updates, preserve permanent outcomes and reject missing parked payloads instead of dispatching empty data. * fix(dispatch): isolate and resume tenant sends Check tenant sources before filters and never dispatch orphan routes. Record each target outcome, isolate update chains by forge and group identity, and keep stale events from overwriting newer messages. * fix(queue): bound batches and resume deliveries A queue invocation has shared query and subrequest limits. Use a small batch and shared send budget, renew fenced leases and resume only unfinished work without exhausting unstarted messages. * fix(admin): guard revisions and tenant targets Read-time authorization alone cannot protect concurrent edits. Guard revisions, current roles and destination ownership in the write transaction, and use per-group endpoints for isolated changes. * fix(webhook): confirm only accepted deliveries Acknowledging before queue acceptance permanently loses deliveries. Confirm only accepted work, release failed claims, scope replay identities and strip tenant-supplied installation authority. * fix(storage): prune abandoned parked payloads Oversized payloads can remain after interrupted enqueue attempts. Prune objects beyond their retry lifetime without deleting payloads that a current delivery may still need. * fix(console): expose api conflict statuses Callers need the HTTP status to distinguish stale edits from other failures and reload current data after a conflict. * refactor(console): model group revisions Carry server revisions explicitly so console writes can reject changes based on an outdated group snapshot. * fix(console): send loaded route revisions Send the revision actually loaded with the route list and adopt the server response after a save. Reload on conflict instead of silently overwriting another editor. * fix(console): guard fragment saves by revision Fragments share a group version with other configuration writes. Submit the loaded revision and reload on conflict to preserve concurrent edits. * fix(console): save groups with guarded writes Whole-list saves can overwrite unrelated groups. Use per-group revision-aware writes, retain rename results and confirm deletion on the exact group, routes and version shown to the user. * fix(console): reject edits of stale routes A conflict reload can leave an older route editor open. Compare its original value before saving so it cannot overwrite the newly loaded route. * fix(console): show overview loading failures Failed overview requests must not look like an empty dashboard or a successful refresh. Show the reason while retaining prior data. * fix(console): explain rejected install bindings Explain why an installation binding was refused instead of silently returning to the console with no visible outcome. * fix(console): allow selecting a group named all The all sentinel collides with a valid group id. Use a value that cannot be a group id so that group stays selectable. * fix(console): discard stale log detail responses An older detail request can finish after a newer selection or close. Discard it so the dialog never shows the previously clicked record. * fix(console): retain legacy group owners Groups predating member roles store owners in adminIds. Load those as owners so adding a member never drops all old owners. * fix(console): lock member edits during saves Edits made during a save are overwritten by its result. Disable member controls and guard handlers until the write settles. * fix(console): show invite loading failures Failed invite loads must not look like no pending invites. Show the error and discard responses from a previously shown group. * fix(console): retain legacy discord log targets A stored log target without platform means Discord. Keep that meaning in the editor instead of clearing the target. * fix(console): retain undisplayed forge sources An editor that only displays some providers must preserve the others. Keep stored custom sources when saving unrelated group settings. * fix(console): lock the group editor while saving Prevent edits while a group save is in flight and make super-only installation settings readonly instead of silently ignoring edits. * fix(console): lock route edits and show failures Lock the route editor while saving and show fragment load failures with a retry action rather than presenting a false empty list. * fix(config): expose the legal contact override Declare the public runtime key so the documented environment override reaches legal pages in deployed Nuxt builds. * build(deploy): migrate d1 before deployment Apply pending D1 migrations before deploying code that requires them. Stop deployment when migration fails instead of running against an incomplete schema. * docs(worker): align guides with runtime behavior Synchronize both language guides, API references and examples with the implemented authorization, storage and delivery behavior. Document migration requirements and accepted operational limits. * fix(storage): repair orphaned KV routes Repair orphaned KV routes before serving KV-only configuration. * fix(security): fully escape forge HTML --------- Co-authored-by: RhenCloud <i@rhen.cloud>
656 lines
23 KiB
TypeScript
656 lines
23 KiB
TypeScript
import type { Env } from "../../types";
|
||
import { log } from "../../lib/log";
|
||
import {
|
||
getOAuthURL,
|
||
commentAsUser,
|
||
mergePullRequestAsUser,
|
||
closePullRequestAsUser,
|
||
BeforeGitHubError,
|
||
CommandTakenError,
|
||
githubRefused,
|
||
} from "../../github/oauth";
|
||
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;
|
||
|
||
// 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 {
|
||
sender_id?: { open_id?: string; union_id?: string };
|
||
}
|
||
interface FeishuMessage {
|
||
chat_id?: string;
|
||
/** "p2p" for the private chat with the bot, "group" otherwise. */
|
||
chat_type?: string;
|
||
content?: string;
|
||
}
|
||
interface FeishuAction {
|
||
action_id?: string;
|
||
value?: { v?: string };
|
||
}
|
||
interface FeishuEvent {
|
||
sender?: FeishuSender;
|
||
message?: FeishuMessage;
|
||
action?: FeishuAction;
|
||
/** `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<void>;
|
||
/** 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] {
|
||
const parts = rest.split("|");
|
||
const number = parts.pop() ?? "";
|
||
const repo = parts.pop() ?? "";
|
||
const owner = parts.pop() ?? "";
|
||
return [owner, repo, number];
|
||
}
|
||
|
||
function timingSafeEqual(a: string, b: string): boolean {
|
||
if (a.length !== b.length) return false;
|
||
let diff = 0;
|
||
for (let i = 0; i < a.length; i++) {
|
||
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||
}
|
||
return diff === 0;
|
||
}
|
||
|
||
async function sha256Hex(data: string): Promise<string> {
|
||
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(
|
||
encryptKey: string,
|
||
timestamp: string,
|
||
nonce: string,
|
||
body: string,
|
||
signature: string,
|
||
): Promise<boolean> {
|
||
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<string> {
|
||
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 {
|
||
if (err instanceof Error) {
|
||
const msg = err.message;
|
||
if (msg.includes("GITHUB_TOKEN_EXPIRED")) return "GitHub 绑定已过期,请重新用 /gh login 绑定。";
|
||
if (msg.includes("GITHUB_FORBIDDEN"))
|
||
return "没有权限操作该仓库(GitHub 返回 403),请确认你的账号权限。";
|
||
if (msg.includes("GITHUB_NOT_FOUND")) return "未找到对应的 GitHub 资源(404)。";
|
||
return msg || "操作失败";
|
||
}
|
||
return "操作失败";
|
||
}
|
||
|
||
function extractTarget(text: string): { owner: string; repo: string; number: number } | null {
|
||
const m = text.match(GITHUB_TARGET_RE);
|
||
if (!m) return null;
|
||
const number = Number(m[3] ?? "");
|
||
if (!Number.isInteger(number)) return null;
|
||
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<void> {
|
||
const tokenRes = await getTenantAccessToken(env);
|
||
if (!tokenRes.ok || !tokenRes.token) {
|
||
log.warn({ err: tokenRes.error }, "Feishu token unavailable for reply");
|
||
throw new Error("Feishu token unavailable for reply");
|
||
}
|
||
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,
|
||
chatType: string | undefined,
|
||
): Promise<void> {
|
||
// 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,
|
||
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);
|
||
await replyToken(
|
||
env,
|
||
chatId,
|
||
[
|
||
"点击下方链接绑定 GitHub 账号:",
|
||
url,
|
||
"绑定后可在飞书里用 /gh comment 评论、/gh merge 合并、/gh close 关闭 PR。",
|
||
].join("\n"),
|
||
);
|
||
}
|
||
|
||
async function handleLogout(
|
||
env: Env,
|
||
openId: string,
|
||
chatId: string,
|
||
run: CommandRun,
|
||
): Promise<void> {
|
||
const linked = await getFeishuLink(env.DB, openId);
|
||
if (!linked) {
|
||
await replyToken(env, chatId, "你还没有绑定 GitHub 账号。");
|
||
return;
|
||
}
|
||
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 账号。");
|
||
}
|
||
|
||
async function handleComment(
|
||
env: Env,
|
||
openId: string,
|
||
chatId: string,
|
||
text: string,
|
||
run: CommandRun,
|
||
): Promise<void> {
|
||
const githubUserId = await getFeishuLink(env.DB, openId);
|
||
if (!githubUserId) {
|
||
await replyToken(env, chatId, "请先 /gh login 绑定 GitHub 账号。");
|
||
return;
|
||
}
|
||
const target = extractTarget(text);
|
||
if (!target) {
|
||
await replyToken(
|
||
env,
|
||
chatId,
|
||
"请在消息里带上 PR/Issue 链接,例如:/gh comment https://github.com/o/r/pull/7 看起来不错",
|
||
);
|
||
return;
|
||
}
|
||
const ghIdx = text.indexOf("/gh");
|
||
// 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,
|
||
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)}`);
|
||
}
|
||
}
|
||
|
||
async function handleMergeOrClose(
|
||
env: Env,
|
||
openId: string,
|
||
chatId: string,
|
||
action: "merge" | "close",
|
||
body: string,
|
||
run: CommandRun,
|
||
): Promise<void> {
|
||
const githubUserId = await getFeishuLink(env.DB, openId);
|
||
if (!githubUserId) {
|
||
await replyToken(env, chatId, "请先 /gh login 绑定 GitHub 账号。");
|
||
return;
|
||
}
|
||
const target = extractTarget(body);
|
||
if (!target) {
|
||
await replyToken(
|
||
env,
|
||
chatId,
|
||
action === "merge"
|
||
? "请在消息里带上 PR 链接,例如:/gh merge https://github.com/o/r/pull/7"
|
||
: "请在消息里带上 PR 链接,例如:/gh close https://github.com/o/r/pull/7",
|
||
);
|
||
return;
|
||
}
|
||
try {
|
||
if (action === "merge") {
|
||
await mergePullRequestAsUser(
|
||
env,
|
||
githubUserId,
|
||
target.owner,
|
||
target.repo,
|
||
target.number,
|
||
undefined,
|
||
{
|
||
beforeWrite: run.beforeWrite,
|
||
},
|
||
);
|
||
} else {
|
||
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)}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 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 ?? {};
|
||
let text = "";
|
||
if (message.content) {
|
||
try {
|
||
const content = JSON.parse(message.content) as { text?: string };
|
||
text = content.text ?? "";
|
||
} catch {
|
||
text = "";
|
||
}
|
||
}
|
||
const command = text.replace(/^\s*(?:@\S+\s+)*/, "");
|
||
return /^\/gh(?:\s|$)/.test(command) ? command : null;
|
||
}
|
||
|
||
async function handleMessage(env: Env, event: FeishuEvent, run: CommandRun): Promise<void> {
|
||
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, message.chat_type);
|
||
break;
|
||
case "logout":
|
||
await handleLogout(env, openId, chatId, run);
|
||
break;
|
||
case "comment":
|
||
await handleComment(env, openId, chatId, command, run);
|
||
break;
|
||
case "merge":
|
||
await handleMergeOrClose(env, openId, chatId, "merge", command, run);
|
||
break;
|
||
case "close":
|
||
await handleMergeOrClose(env, openId, chatId, "close", command, run);
|
||
break;
|
||
default:
|
||
await replyToken(
|
||
env,
|
||
chatId,
|
||
"未知指令。可用:/gh login | logout | comment <链接> <内容> | merge <链接> | close <链接>",
|
||
);
|
||
}
|
||
}
|
||
|
||
function buildResultCard(ok: boolean, message: string): Record<string, unknown> {
|
||
return {
|
||
config: { wide_screen_mode: true },
|
||
elements: [
|
||
{
|
||
tag: "div",
|
||
text: { tag: "lark_md", content: ok ? `✅ ${message}` : `❌ ${message}` },
|
||
},
|
||
],
|
||
};
|
||
}
|
||
|
||
async function handleCardAction(
|
||
env: Env,
|
||
payload: Record<string, unknown>,
|
||
run: CommandRun,
|
||
): Promise<void> {
|
||
const event = (payload.event ?? {}) as FeishuEvent;
|
||
const action = event.action ?? {};
|
||
const actionId = action.action_id ?? action.value?.v ?? "";
|
||
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.context?.open_message_id ?? event.open_message_id ?? "";
|
||
|
||
if (!actionId.startsWith(BTN_PREFIX)) return;
|
||
|
||
const isMerge = actionId.startsWith(`${BTN_PREFIX}merge|`);
|
||
const isClose = actionId.startsWith(`${BTN_PREFIX}close|`);
|
||
|
||
if (isMerge || isClose) {
|
||
const [owner, repo, numberStr] = splitThree(actionId.slice(BTN_PREFIX.length));
|
||
const number = Number(numberStr);
|
||
if (!owner || !repo || !Number.isInteger(number)) {
|
||
await replyCard(env, cardToken, buildResultCard(false, "无效的按钮数据"));
|
||
return;
|
||
}
|
||
const githubUserId = await getFeishuLink(env.DB, openId);
|
||
if (!githubUserId) {
|
||
await replyCard(env, cardToken, buildResultCard(false, "请先 /gh login 绑定 GitHub 账号"));
|
||
return;
|
||
}
|
||
try {
|
||
if (isMerge) {
|
||
await mergePullRequestAsUser(env, githubUserId, owner, repo, number, undefined, {
|
||
beforeWrite: run.beforeWrite,
|
||
});
|
||
} else {
|
||
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;
|
||
}
|
||
|
||
if (openMessageId) {
|
||
await replyCard(env, cardToken, buildResultCard(false, "未知按钮"));
|
||
}
|
||
}
|
||
|
||
async function replyCard(
|
||
env: Env,
|
||
cardToken: string,
|
||
card: Record<string, unknown>,
|
||
): Promise<void> {
|
||
const tokenRes = await getTenantAccessToken(env);
|
||
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<Response> {
|
||
// 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<string, unknown>;
|
||
try {
|
||
payload = JSON.parse(rawBody);
|
||
} catch {
|
||
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<string, unknown> | undefined;
|
||
const eventPart = payload.event as Record<string, unknown> | 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) ?? "" });
|
||
}
|
||
|
||
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 });
|
||
}
|
||
}
|
||
|
||
const eventType = (header?.event_type as string) ?? eventPart?.type ?? type;
|
||
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<void> => {
|
||
// 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 });
|
||
}
|
||
|
||
export { FEISHU_API };
|