mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
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.
This commit is contained in:
1 parent
37d22f6907
commit
706737ca6b
2 files changed
+539
-67
No files matched your search
@@ -9,6 +9,7 @@ import {
|
||||
closePullRequestAsUser,
|
||||
} from "../../github/oauth";
|
||||
import { getDiscordLink, removeDiscordLink } from "../../github/store";
|
||||
import { idempotencyStore } from "../../lib/idempotency";
|
||||
import type { Env } from "../../types";
|
||||
import { MSG_CMD_ADD, MSG_CMD_EDIT, MSG_CMD_DEL } from "./commands";
|
||||
|
||||
@@ -22,16 +23,84 @@ const EPHEMERAL = 64;
|
||||
|
||||
// Modal custom_id encodings (delimiter '|' never appears in owner/repo).
|
||||
const MODAL_ADD = "ghc|add|"; // ghc|add|owner|repo|issueNumber
|
||||
const MODAL_EDIT = "ghc|edit|"; // ghc|edit|owner|repo|commentId
|
||||
const MODAL_EDIT = "ghc|edit|"; // ghc|edit|owner|repo|commentId (read for older modals)
|
||||
/** ghc|ed|owner|repo|commentId|base: an edit that remembers the text it was opened on. */
|
||||
const MODAL_EDIT_BASE = "ghc|ed|";
|
||||
/**
|
||||
* ghc|m|{context id}: the context kept in KV instead — only when the custom
|
||||
* id would pass Discord's 100 characters (a long owner/repo). KV writes are
|
||||
* scarce (Workers Free), so the context travels in the custom id whenever
|
||||
* it fits.
|
||||
*/
|
||||
const MODAL_CTX = "ghc|m|";
|
||||
const MAX_CUSTOM_ID = 100;
|
||||
/** Hex characters of the comment hash an edit modal remembers. */
|
||||
const BASE_HASH_LENGTH = 16;
|
||||
const MODAL_CTX_TTL_SECONDS = 86400;
|
||||
|
||||
interface ModalContext {
|
||||
op: "add" | "edit";
|
||||
owner: string;
|
||||
repo: string;
|
||||
/** Issue/PR number (add) or comment id (edit). */
|
||||
ref: string;
|
||||
/** SHA-256 (hex, possibly shortened) of the comment as the edit modal showed it. */
|
||||
base?: string;
|
||||
}
|
||||
|
||||
async function sha256Hex(text: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
async function modalCustomId(env: Env, context: ModalContext): Promise<string> {
|
||||
const inline =
|
||||
context.op === "add"
|
||||
? `${MODAL_ADD}${context.owner}|${context.repo}|${context.ref}`
|
||||
: `${MODAL_EDIT_BASE}${context.owner}|${context.repo}|${context.ref}|${context.base ?? ""}`;
|
||||
if (inline.length <= MAX_CUSTOM_ID) return inline;
|
||||
const contextId = crypto.randomUUID().replace(/-/g, "");
|
||||
await env.KV.put(`discord-modal:${contextId}`, JSON.stringify(context), {
|
||||
expirationTtl: MODAL_CTX_TTL_SECONDS,
|
||||
});
|
||||
return `${MODAL_CTX}${contextId}`;
|
||||
}
|
||||
|
||||
async function modalContext(env: Env, customId: string): Promise<ModalContext | null> {
|
||||
if (customId.startsWith(MODAL_CTX)) {
|
||||
return env.KV.get<ModalContext>(`discord-modal:${customId.slice(MODAL_CTX.length)}`, "json");
|
||||
}
|
||||
if (customId.startsWith(MODAL_EDIT_BASE)) {
|
||||
const rest = customId.slice(MODAL_EDIT_BASE.length);
|
||||
const cut = rest.lastIndexOf("|");
|
||||
const [owner, repo, ref] = splitThree(rest.slice(0, cut));
|
||||
const base = rest.slice(cut + 1);
|
||||
return cut > 0 && owner && repo && ref ? { op: "edit", owner, repo, ref, base } : null;
|
||||
}
|
||||
for (const [prefix, op] of [
|
||||
[MODAL_ADD, "add"],
|
||||
[MODAL_EDIT, "edit"],
|
||||
] as const) {
|
||||
if (!customId.startsWith(prefix)) continue;
|
||||
const [owner, repo, ref] = splitThree(customId.slice(prefix.length));
|
||||
return owner && repo && ref ? { op, owner, repo, ref } : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// PR notification button custom_id encodings.
|
||||
const BTN_MERGE = "ghpr|merge|"; // ghpr|merge|owner|repo|pullNumber
|
||||
const BTN_CLOSE = "ghpr|close|"; // ghpr|close|owner|repo|pullNumber
|
||||
|
||||
// Comment link (has the comment id); check this BEFORE the plain issue regex.
|
||||
// Both only accept github.com itself (not e.g. `evilgithub.com`): the actions
|
||||
// run against the GitHub API.
|
||||
const GITHUB_COMMENT_RE =
|
||||
/github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/\d+#issuecomment-(\d+)/;
|
||||
const GITHUB_ISSUE_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
||||
/https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/\d+#issuecomment-(\d+)/;
|
||||
const GITHUB_ISSUE_RE =
|
||||
/https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
||||
/** Discord caps a text input's value (and max_length) at 4000 characters. */
|
||||
const MAX_MODAL_TEXT = 4000;
|
||||
|
||||
/**
|
||||
* Split a pipe-delimited custom-id suffix into [owner, repo, number]. The
|
||||
@@ -46,13 +115,23 @@ function splitThree(rest: string): [string, string, string] {
|
||||
return [owner ?? "", repo ?? "", number ?? ""];
|
||||
}
|
||||
|
||||
interface DiscordUser {
|
||||
id?: string;
|
||||
username?: string;
|
||||
global_name?: string | null;
|
||||
}
|
||||
|
||||
interface Interaction {
|
||||
id: string;
|
||||
/** The application the interaction belongs to (follow-up webhooks use it). */
|
||||
application_id?: string;
|
||||
token: string;
|
||||
type: number;
|
||||
channel_id?: string;
|
||||
member?: { user?: { id?: string } };
|
||||
user?: { id?: string };
|
||||
member?: { user?: DiscordUser };
|
||||
user?: DiscordUser;
|
||||
/** The message a component (button) is attached to. */
|
||||
message?: { id?: string };
|
||||
data?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -146,6 +225,15 @@ export async function handleInteractionRequest(request: Request, env: Env): Prom
|
||||
});
|
||||
}
|
||||
|
||||
// Discord does not redeliver interactions, but a replayed request (same
|
||||
// signed body within the timestamp window) must not run its action twice.
|
||||
if (
|
||||
interaction.id &&
|
||||
!(await idempotencyStore(env.DB, env.KV).claim(`bot:discord:${interaction.id}`, 3600))
|
||||
) {
|
||||
return new Response(null, { status: 202 });
|
||||
}
|
||||
|
||||
// Handle the interaction via the callback webhook; respond 202 with no body
|
||||
// as required for interactions received over the HTTP endpoint.
|
||||
await handleInteraction(env, interaction).catch((err) =>
|
||||
@@ -155,19 +243,22 @@ export async function handleInteractionRequest(request: Request, env: Env): Prom
|
||||
}
|
||||
|
||||
async function handleInteraction(env: Env, interaction: Interaction): Promise<void> {
|
||||
const userId = interaction.member?.user?.id ?? interaction.user?.id ?? null;
|
||||
const user = interaction.member?.user ?? interaction.user;
|
||||
const userId = user?.id ?? null;
|
||||
const id = interaction.id;
|
||||
const token = interaction.token;
|
||||
const applicationId = interaction.application_id ?? env.DISCORD_APPLICATION_ID ?? "";
|
||||
|
||||
if (interaction.type === INTERACTION_TYPE.BUTTON) {
|
||||
const data = interaction.data as { custom_id?: string; message?: { id?: string } };
|
||||
const data = interaction.data as { custom_id?: string };
|
||||
return handleButton(
|
||||
env,
|
||||
id,
|
||||
token,
|
||||
applicationId,
|
||||
userId,
|
||||
interaction.channel_id,
|
||||
data.message?.id,
|
||||
interaction.message?.id,
|
||||
data.custom_id,
|
||||
);
|
||||
}
|
||||
@@ -203,13 +294,15 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
||||
if (!op) return;
|
||||
const target = data.target_id ? data.resolved?.messages?.[data.target_id] : undefined;
|
||||
const source = target?.embeds?.[0]?.url ?? target?.content ?? "";
|
||||
return commentOp(env, id, token, userId, op, source);
|
||||
return commentOp(env, id, token, applicationId, userId, op, source);
|
||||
}
|
||||
|
||||
// Slash command /gh ...
|
||||
if (data.name === "gh" && data.type === COMMAND_TYPE.CHAT_INPUT) {
|
||||
const top = data.options?.[0];
|
||||
if (top?.name === "login") return cmdLogin(env, id, token, userId);
|
||||
if (top?.name === "login") {
|
||||
return cmdLogin(env, id, token, userId, user?.global_name || user?.username);
|
||||
}
|
||||
if (top?.name === "logout") return cmdLogout(env, id, token, userId);
|
||||
if (top?.name === "comment") {
|
||||
const sub = top.options?.[0];
|
||||
@@ -223,7 +316,7 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
||||
: null;
|
||||
if (!op) return;
|
||||
const link = sub?.options?.find((o) => o.name === "link")?.value ?? "";
|
||||
return commentOp(env, id, token, userId, op, link);
|
||||
return commentOp(env, id, token, applicationId, userId, op, link);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -231,7 +324,7 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
||||
}
|
||||
|
||||
if (interaction.type === INTERACTION_TYPE.MODAL_SUBMIT) {
|
||||
return modalSubmit(env, id, token, userId, interaction.data);
|
||||
return modalSubmit(env, id, token, applicationId, userId, interaction.data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,12 +336,13 @@ async function respond(env: Env, id: string, token: string, content: string): Pr
|
||||
});
|
||||
}
|
||||
|
||||
/** Answer an interaction; whether Discord accepted the answer. */
|
||||
async function interactionCallback(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
body: unknown,
|
||||
): Promise<void> {
|
||||
): Promise<boolean> {
|
||||
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/callback`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -258,11 +352,23 @@ async function interactionCallback(
|
||||
const err = await res.text();
|
||||
log.warn({ status: res.status, err }, "Interaction callback failed");
|
||||
}
|
||||
return res.ok;
|
||||
}
|
||||
|
||||
/** Replace the deferred (ephemeral) response body with the final result. */
|
||||
async function updateOriginal(env: Env, id: string, token: string, content: string): Promise<void> {
|
||||
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/messages/@original`, {
|
||||
/**
|
||||
* Replace the deferred (ephemeral) response body with the final result. The
|
||||
* original response is edited through the application's follow-up webhook.
|
||||
*/
|
||||
async function updateOriginal(
|
||||
applicationId: string,
|
||||
token: string,
|
||||
content: string,
|
||||
): Promise<void> {
|
||||
if (!applicationId) {
|
||||
log.warn("Cannot update interaction response: application id unknown");
|
||||
return;
|
||||
}
|
||||
const res = await fetch(`${DISCORD_API}/webhooks/${applicationId}/${token}/messages/@original`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ content }),
|
||||
@@ -273,6 +379,35 @@ async function updateOriginal(env: Env, id: string, token: string, content: stri
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Acknowledge first (deferred, ephemeral), then run the GitHub action and
|
||||
* show its outcome: Discord fails an interaction not answered within 3
|
||||
* seconds, and a slow GitHub call must not leave a done action looking failed
|
||||
* (the user would submit it again).
|
||||
*/
|
||||
async function deferThen(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
applicationId: string,
|
||||
work: () => Promise<string>,
|
||||
): Promise<void> {
|
||||
// Not acknowledged: Discord shows the interaction as failed, so acting on
|
||||
// GitHub now would leave a done action looking failed (and resubmitted).
|
||||
const acked = await interactionCallback(env, id, token, {
|
||||
type: CALLBACK_TYPE.DEFERRED_MESSAGE,
|
||||
data: { flags: EPHEMERAL },
|
||||
});
|
||||
if (!acked) return;
|
||||
let content: string;
|
||||
try {
|
||||
content = await work();
|
||||
} catch (err) {
|
||||
content = errText(err);
|
||||
}
|
||||
await updateOriginal(applicationId, token, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* PR notification buttons: merge or close the PR as the clicker's linked
|
||||
* GitHub account. The clicker must have run `/gh login` first.
|
||||
@@ -281,6 +416,7 @@ async function handleButton(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
applicationId: string,
|
||||
userId: string | null,
|
||||
channelId: string | undefined,
|
||||
messageId: string | undefined,
|
||||
@@ -308,17 +444,18 @@ async function handleButton(
|
||||
if (!owner || !repo || !number) return;
|
||||
|
||||
// Acknowledge first (deferred, ephemeral) so the clicker sees a spinner
|
||||
// while the GitHub API call runs.
|
||||
await interactionCallback(env, id, token, {
|
||||
// while the GitHub API call runs; unacknowledged, nothing is done.
|
||||
const acked = await interactionCallback(env, id, token, {
|
||||
type: CALLBACK_TYPE.DEFERRED_MESSAGE,
|
||||
data: { flags: EPHEMERAL },
|
||||
});
|
||||
if (!acked) return;
|
||||
|
||||
try {
|
||||
if (op === "merge") {
|
||||
await mergePullRequestAsUser(env.KV, githubUserId, owner, repo, Number(number));
|
||||
await mergePullRequestAsUser(env, githubUserId, owner, repo, Number(number));
|
||||
} else {
|
||||
await closePullRequestAsUser(env.KV, githubUserId, owner, repo, Number(number));
|
||||
await closePullRequestAsUser(env, githubUserId, owner, repo, Number(number));
|
||||
}
|
||||
// Remove the buttons from the notification so nobody double-clicks.
|
||||
if (channelId && messageId) {
|
||||
@@ -332,13 +469,19 @@ async function handleButton(
|
||||
}).catch((err) => log.warn({ err: String(err) }, "Failed to strip PR buttons"));
|
||||
}
|
||||
const label = op === "merge" ? "合并" : "关闭";
|
||||
await updateOriginal(env, id, token, `✅ 已${label} PR ${owner}/${repo}#${number}`);
|
||||
await updateOriginal(applicationId, token, `✅ 已${label} PR ${owner}/${repo}#${number}`);
|
||||
} catch (err) {
|
||||
await updateOriginal(env, id, token, errText(err));
|
||||
await updateOriginal(applicationId, token, errText(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function cmdLogin(env: Env, id: string, token: string, userId: string | null): Promise<void> {
|
||||
async function cmdLogin(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
userId: string | null,
|
||||
name: string | undefined,
|
||||
): Promise<void> {
|
||||
if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。");
|
||||
const clientId = env.GITHUB_CLIENT_ID;
|
||||
if (!clientId) return respond(env, id, token, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。");
|
||||
@@ -346,7 +489,11 @@ async function cmdLogin(env: Env, id: string, token: string, userId: string | nu
|
||||
const state = crypto.randomUUID().replace(/-/g, "");
|
||||
await env.KV.put(
|
||||
`state:${state}`,
|
||||
JSON.stringify({ redirectTo: "/", discordUserId: userId, expiresAt: Date.now() + 600_000 }),
|
||||
JSON.stringify({
|
||||
redirectTo: "/",
|
||||
link: { platform: "discord", userId, name },
|
||||
expiresAt: Date.now() + 600_000,
|
||||
}),
|
||||
{ expirationTtl: 600 },
|
||||
);
|
||||
const url = getOAuthURL(clientId, state);
|
||||
@@ -386,6 +533,7 @@ async function commentOp(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
applicationId: string,
|
||||
userId: string | null,
|
||||
op: "add" | "edit" | "del",
|
||||
source: string,
|
||||
@@ -409,7 +557,7 @@ async function commentOp(
|
||||
env,
|
||||
id,
|
||||
token,
|
||||
`${MODAL_ADD}${m[1]}|${m[2]}|${m[3]}`,
|
||||
await modalCustomId(env, { op: "add", owner: m[1]!, repo: m[2]!, ref: m[3]! }),
|
||||
`评论 ${m[1]}/${m[2]}#${m[3]}`,
|
||||
);
|
||||
}
|
||||
@@ -427,27 +575,41 @@ async function commentOp(
|
||||
const [, owner, repo, commentId] = m;
|
||||
|
||||
if (op === "del") {
|
||||
try {
|
||||
await deleteCommentAsUser(env.KV, githubUserId, owner!, repo!, Number(commentId));
|
||||
return respond(env, id, token, `已删除评论 ${owner}/${repo}#issuecomment-${commentId}。`);
|
||||
} catch (err) {
|
||||
return respond(env, id, token, errText(err));
|
||||
}
|
||||
return deferThen(env, id, token, applicationId, async () => {
|
||||
await deleteCommentAsUser(env, githubUserId, owner!, repo!, Number(commentId));
|
||||
return `已删除评论 ${owner}/${repo}#issuecomment-${commentId}。`;
|
||||
});
|
||||
}
|
||||
|
||||
// edit: fetch current body to prefill the modal.
|
||||
let prefill = "";
|
||||
try {
|
||||
const { body } = await getCommentAsUser(env.KV, githubUserId, owner!, repo!, Number(commentId));
|
||||
const { body } = await getCommentAsUser(env, githubUserId, owner!, repo!, Number(commentId));
|
||||
prefill = body;
|
||||
} catch (err) {
|
||||
return respond(env, id, token, errText(err));
|
||||
}
|
||||
// The modal can only hold part of a longer comment, and saving it would
|
||||
// replace the whole comment with that part: such comments are edited on GitHub.
|
||||
if (prefill.length > MAX_MODAL_TEXT) {
|
||||
return respond(
|
||||
env,
|
||||
id,
|
||||
token,
|
||||
`这条评论超过 ${MAX_MODAL_TEXT} 字,无法在 Discord 中完整编辑,请到 GitHub 上编辑:${m[0]}`,
|
||||
);
|
||||
}
|
||||
return openCommentModal(
|
||||
env,
|
||||
id,
|
||||
token,
|
||||
`${MODAL_EDIT}${owner}|${repo}|${commentId}`,
|
||||
await modalCustomId(env, {
|
||||
op: "edit",
|
||||
owner: owner!,
|
||||
repo: repo!,
|
||||
ref: commentId!,
|
||||
base: (await sha256Hex(prefill)).slice(0, BASE_HASH_LENGTH),
|
||||
}),
|
||||
`编辑评论 #${commentId}`,
|
||||
prefill,
|
||||
);
|
||||
@@ -477,8 +639,8 @@ async function openCommentModal(
|
||||
label: "评论内容",
|
||||
style: 2,
|
||||
required: true,
|
||||
max_length: 2000,
|
||||
value: prefill.slice(0, 2000) || undefined,
|
||||
max_length: MAX_MODAL_TEXT,
|
||||
value: prefill || undefined,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -491,6 +653,7 @@ async function modalSubmit(
|
||||
env: Env,
|
||||
id: string,
|
||||
token: string,
|
||||
applicationId: string,
|
||||
userId: string | null,
|
||||
data: unknown,
|
||||
): Promise<void> {
|
||||
@@ -501,51 +664,47 @@ async function modalSubmit(
|
||||
const customId = d.custom_id;
|
||||
if (!userId || !customId) return;
|
||||
|
||||
const body = d.components?.[0]?.components?.find((c) => c.custom_id === "body")?.value?.trim();
|
||||
if (!body) return respond(env, id, token, "评论内容不能为空。");
|
||||
// Submitted as written (an indented first line is a Markdown code block):
|
||||
// blank only decides emptiness.
|
||||
const body = d.components?.[0]?.components?.find((c) => c.custom_id === "body")?.value ?? "";
|
||||
if (!body.trim()) return respond(env, id, token, "评论内容不能为空。");
|
||||
|
||||
const githubUserId = await getDiscordLink(env.DB, userId);
|
||||
if (!githubUserId) {
|
||||
return respond(env, id, token, "你还没有绑定 GitHub 账号,请先使用 `/gh login`。");
|
||||
}
|
||||
|
||||
// ghc|add|owner|repo|issueNumber
|
||||
if (customId.startsWith(MODAL_ADD)) {
|
||||
const [owner, repo, number] = splitThree(customId.slice(MODAL_ADD.length));
|
||||
if (!owner || !repo || !number)
|
||||
return respond(env, id, token, "内部错误:无法解析目标 issue。");
|
||||
try {
|
||||
const context = await modalContext(env, customId);
|
||||
if (!context) {
|
||||
return respond(env, id, token, "这个评论框已失效,请重新打开。");
|
||||
}
|
||||
const { owner, repo, ref } = context;
|
||||
|
||||
if (context.op === "add") {
|
||||
return deferThen(env, id, token, applicationId, async () => {
|
||||
const { htmlUrl, login } = await commentAsUser(
|
||||
env.KV,
|
||||
env,
|
||||
githubUserId,
|
||||
owner,
|
||||
repo,
|
||||
Number(number),
|
||||
Number(ref),
|
||||
body,
|
||||
);
|
||||
return respond(env, id, token, `已以 **@${login}** 身份评论:${htmlUrl}`);
|
||||
} catch (err) {
|
||||
return respond(env, id, token, errText(err));
|
||||
}
|
||||
return `已以 **@${login}** 身份评论:${htmlUrl}`;
|
||||
});
|
||||
}
|
||||
|
||||
// ghc|edit|owner|repo|commentId
|
||||
if (customId.startsWith(MODAL_EDIT)) {
|
||||
const [owner, repo, commentId] = splitThree(customId.slice(MODAL_EDIT.length));
|
||||
if (!owner || !repo || !commentId)
|
||||
return respond(env, id, token, "内部错误:无法解析目标评论。");
|
||||
try {
|
||||
const { htmlUrl } = await editCommentAsUser(
|
||||
env.KV,
|
||||
githubUserId,
|
||||
owner,
|
||||
repo,
|
||||
Number(commentId),
|
||||
body,
|
||||
);
|
||||
return respond(env, id, token, `已更新评论:${htmlUrl}`);
|
||||
} catch (err) {
|
||||
return respond(env, id, token, errText(err));
|
||||
return deferThen(env, id, token, applicationId, async () => {
|
||||
// Changed on GitHub since the modal showed it: saving would silently
|
||||
// replace those changes (GitHub has no conditional update — this check
|
||||
// narrows the window to the moment between it and the save).
|
||||
if (context.base) {
|
||||
const { body: current } = await getCommentAsUser(env, githubUserId, owner, repo, Number(ref));
|
||||
if ((await sha256Hex(current)).slice(0, context.base.length) !== context.base) {
|
||||
return "这条评论在你打开编辑框后已被修改。为避免覆盖这些修改,请重新打开编辑框。";
|
||||
}
|
||||
}
|
||||
}
|
||||
const { htmlUrl } = await editCommentAsUser(env, githubUserId, owner, repo, Number(ref), body);
|
||||
return `已更新评论:${htmlUrl}`;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { describe, it, expect, afterEach } from "bun:test";
|
||||
import { handleInteractionRequest } from "../server/lib/drivers/discord/interactions";
|
||||
import { saveToken } from "../server/lib/github/store";
|
||||
import { createMemoryKV, createSqliteD1 } from "./d1-sqlite";
|
||||
import type { Env } from "../server/lib/types";
|
||||
|
||||
const restoredFetch = globalThis.fetch;
|
||||
afterEach(() => {
|
||||
globalThis.fetch = restoredFetch;
|
||||
});
|
||||
|
||||
function hex(bytes: ArrayBuffer): string {
|
||||
return Array.from(new Uint8Array(bytes))
|
||||
.map((b) => b.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
async function setup(): Promise<{
|
||||
env: Env;
|
||||
send: (interaction: Record<string, unknown>) => Promise<Response>;
|
||||
}> {
|
||||
const keys = (await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
|
||||
"sign",
|
||||
"verify",
|
||||
])) as CryptoKeyPair;
|
||||
const publicKey = hex(await crypto.subtle.exportKey("raw", keys.publicKey));
|
||||
const { db, sqlite } = createSqliteD1();
|
||||
sqlite.exec("INSERT INTO discord_links (discord_user_id, github_user_id) VALUES ('d1', 'g1')");
|
||||
const { kv } = createMemoryKV();
|
||||
await saveToken(kv, "g1", "gho_token", 3600);
|
||||
const env: Env = { GITHUB_WEBHOOK_SECRET: "", KV: kv, DB: db, DISCORD_PUBLIC_KEY: publicKey };
|
||||
async function send(interaction: Record<string, unknown>): Promise<Response> {
|
||||
const body = JSON.stringify(interaction);
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
const signature = hex(
|
||||
await crypto.subtle.sign(
|
||||
"Ed25519",
|
||||
keys.privateKey,
|
||||
new TextEncoder().encode(timestamp + body),
|
||||
),
|
||||
);
|
||||
return handleInteractionRequest(
|
||||
new Request("https://x/discord/interactions", {
|
||||
method: "POST",
|
||||
headers: { "X-Signature-Ed25519": signature, "X-Signature-Timestamp": timestamp },
|
||||
body,
|
||||
}),
|
||||
env,
|
||||
);
|
||||
}
|
||||
return { env, send };
|
||||
}
|
||||
|
||||
describe("discord interactions", () => {
|
||||
it("edits the deferred reply through the application webhook and strips the clicked message", async () => {
|
||||
const calls: Array<{ method: string; url: string }> = [];
|
||||
globalThis.fetch = async (input, init): Promise<Response> => {
|
||||
calls.push({ method: init?.method ?? "GET", url: String(input) });
|
||||
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
const { send } = await setup();
|
||||
const res = await send({
|
||||
id: "i1",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 3,
|
||||
channel_id: "chan",
|
||||
member: { user: { id: "d1" } },
|
||||
message: { id: "msg9" },
|
||||
data: { custom_id: "ghpr|close|o|r|7" },
|
||||
});
|
||||
expect(res.status).toBe(202);
|
||||
expect(
|
||||
calls.some((c) => c.method === "PATCH" && c.url.endsWith("/channels/chan/messages/msg9")),
|
||||
).toBe(true);
|
||||
expect(
|
||||
calls.some(
|
||||
(c) => c.method === "PATCH" && c.url.endsWith("/webhooks/app1/tok/messages/@original"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("runs a replayed interaction only once", async () => {
|
||||
let callbacks = 0;
|
||||
globalThis.fetch = async (input): Promise<Response> => {
|
||||
if (String(input).includes("/callback")) callbacks++;
|
||||
return new Response("{}", { status: 200 });
|
||||
};
|
||||
const { send } = await setup();
|
||||
const interaction = {
|
||||
id: "i2",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 2,
|
||||
member: { user: { id: "d1" } },
|
||||
data: { name: "gh", type: 1, options: [{ name: "logout" }] },
|
||||
};
|
||||
await send(interaction);
|
||||
await send(interaction);
|
||||
expect(callbacks).toBe(1);
|
||||
});
|
||||
|
||||
it("refuses to edit a comment longer than the modal can hold", async () => {
|
||||
const bodies: string[] = [];
|
||||
globalThis.fetch = async (input, init): Promise<Response> => {
|
||||
const url = String(input);
|
||||
if (url.includes("/issues/comments/")) {
|
||||
return new Response(JSON.stringify({ body: "x".repeat(5000), user: { login: "a" } }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}
|
||||
if (url.includes("/callback")) bodies.push(String(init?.body));
|
||||
return new Response("{}", { status: 200 });
|
||||
};
|
||||
const { send } = await setup();
|
||||
await send({
|
||||
id: "i3",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 2,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
name: "gh",
|
||||
type: 1,
|
||||
options: [
|
||||
{
|
||||
name: "comment",
|
||||
options: [
|
||||
{
|
||||
name: "edit",
|
||||
options: [
|
||||
{ name: "link", value: "https://github.com/o/r/issues/1#issuecomment-55" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(bodies).toHaveLength(1);
|
||||
const reply = JSON.parse(bodies[0]!) as { type: number; data: { content?: string } };
|
||||
// A message (type 4) pointing to GitHub, not a modal (type 9) holding a cut-off copy.
|
||||
expect(reply.type).toBe(4);
|
||||
expect(reply.data.content).toContain("github.com/o/r/issues/1#issuecomment-55");
|
||||
});
|
||||
|
||||
it("acknowledges a comment modal before calling GitHub, then shows the outcome", async () => {
|
||||
const order: string[] = [];
|
||||
globalThis.fetch = async (input, init): Promise<Response> => {
|
||||
const url = String(input);
|
||||
if (url.includes("/callback")) {
|
||||
order.push(`callback:${(JSON.parse(String(init?.body)) as { type: number }).type}`);
|
||||
} else if (url.includes("api.github.com")) {
|
||||
order.push("github");
|
||||
return new Response(
|
||||
JSON.stringify({ html_url: "https://github.com/o/r/issues/7#c", user: { login: "a" } }),
|
||||
{ status: 201, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
} else if (url.endsWith("/messages/@original")) {
|
||||
order.push("original");
|
||||
}
|
||||
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
const { send } = await setup();
|
||||
await send({
|
||||
id: "i4",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 5,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
custom_id: "ghc|add|o|r|7",
|
||||
components: [{ components: [{ custom_id: "body", value: "hello" }] }],
|
||||
},
|
||||
});
|
||||
// Deferred (type 5) first: a slow GitHub call never fails the interaction.
|
||||
expect(order[0]).toBe("callback:5");
|
||||
expect(order.indexOf("github")).toBeGreaterThan(0);
|
||||
expect(order.at(-1)).toBe("original");
|
||||
});
|
||||
|
||||
it("leaves GitHub alone when Discord refused the acknowledgement", async () => {
|
||||
const calls: string[] = [];
|
||||
globalThis.fetch = async (input): Promise<Response> => {
|
||||
const url = String(input);
|
||||
calls.push(url);
|
||||
if (url.includes("/callback")) return new Response("unknown interaction", { status: 404 });
|
||||
return new Response(
|
||||
JSON.stringify({ html_url: "https://github.com/o/r/issues/7#c", user: { login: "a" } }),
|
||||
{ status: 201, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
};
|
||||
const { send } = await setup();
|
||||
await send({
|
||||
id: "i5",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 5,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
custom_id: "ghc|add|o|r|7",
|
||||
components: [{ components: [{ custom_id: "body", value: "hello" }] }],
|
||||
},
|
||||
});
|
||||
expect(calls.some((u) => u.includes("api.github.com"))).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses to save an edit over changes made on GitHub after the modal opened", async () => {
|
||||
let current = "original";
|
||||
const patches: string[] = [];
|
||||
const callbacks: string[] = [];
|
||||
const originals: string[] = [];
|
||||
globalThis.fetch = async (input, init): Promise<Response> => {
|
||||
const url = String(input);
|
||||
if (url.includes("/issues/comments/55")) {
|
||||
if ((init?.method ?? "GET") === "PATCH") patches.push(String(init?.body));
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
body: current,
|
||||
html_url: "https://github.com/o/r/issues/1#issuecomment-55",
|
||||
user: { login: "a" },
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
if (url.includes("/callback")) callbacks.push(String(init?.body));
|
||||
if (url.endsWith("/messages/@original")) originals.push(String(init?.body));
|
||||
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
const { send } = await setup();
|
||||
await send({
|
||||
id: "i6",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 2,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
name: "gh",
|
||||
type: 1,
|
||||
options: [
|
||||
{
|
||||
name: "comment",
|
||||
options: [
|
||||
{
|
||||
name: "edit",
|
||||
options: [
|
||||
{ name: "link", value: "https://github.com/o/r/issues/1#issuecomment-55" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const modal = JSON.parse(callbacks[0]!) as { type: number; data: { custom_id: string } };
|
||||
expect(modal.type).toBe(9);
|
||||
expect(modal.data.custom_id.length).toBeLessThanOrEqual(100);
|
||||
// Short enough: the context (with the text's hash) travels in the id — no KV write.
|
||||
expect(modal.data.custom_id.startsWith("ghc|ed|")).toBe(true);
|
||||
current = "changed on GitHub";
|
||||
await send({
|
||||
id: "i7",
|
||||
application_id: "app1",
|
||||
token: "tok2",
|
||||
type: 5,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
custom_id: modal.data.custom_id,
|
||||
components: [{ components: [{ custom_id: "body", value: "original, edited" }] }],
|
||||
},
|
||||
});
|
||||
expect(patches).toHaveLength(0);
|
||||
expect(originals.at(-1)).toContain("已被修改");
|
||||
});
|
||||
|
||||
it("keeps the custom id short for long repository names", async () => {
|
||||
const callbacks: string[] = [];
|
||||
globalThis.fetch = async (input, init): Promise<Response> => {
|
||||
if (String(input).includes("/callback")) callbacks.push(String(init?.body));
|
||||
return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
|
||||
};
|
||||
const { send } = await setup();
|
||||
const repo = "r".repeat(100);
|
||||
await send({
|
||||
id: "i8",
|
||||
application_id: "app1",
|
||||
token: "tok",
|
||||
type: 2,
|
||||
member: { user: { id: "d1" } },
|
||||
data: {
|
||||
name: "gh",
|
||||
type: 1,
|
||||
options: [
|
||||
{
|
||||
name: "comment",
|
||||
options: [
|
||||
{
|
||||
name: "add",
|
||||
options: [{ name: "link", value: `https://github.com/o/${repo}/issues/1` }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const modal = JSON.parse(callbacks[0]!) as { type: number; data: { custom_id: string } };
|
||||
expect(modal.type).toBe(9);
|
||||
expect(modal.data.custom_id.length).toBeLessThanOrEqual(100);
|
||||
// Too long to carry its context: kept in KV (the only case that writes).
|
||||
expect(modal.data.custom_id.startsWith("ghc|m|")).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user