chore: auto-fix lint & formatting [skip ci]

This commit is contained in:
github-actions[bot] 2026-08-02 19:03:12 +00:00
parent d540d465d1
commit 7b341ff9f4
9 changed files with 117 additions and 115 deletions

View file

@ -43,7 +43,7 @@ npx wrangler dev # Start local dev server
### Secrets (`.dev.vars` for local, Worker Secrets for production) ### Secrets (`.dev.vars` for local, Worker Secrets for production)
| Variable | Description | | Variable | Description |
| ------------------------- | --------------------------------------------------------------------------------------------- | | ------------------------ | ---------------------------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub | | `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub |
| `GITHUB_APP_ID` | GitHub App ID | | `GITHUB_APP_ID` | GitHub App ID |
| `GITHUB_PRIVATE_KEY` | App private key (PEM) | | `GITHUB_PRIVATE_KEY` | App private key (PEM) |
@ -212,7 +212,7 @@ The bot registers native **slash** and **message context-menu** commands, synced
**Requirements:** **Requirements:**
| Item | How | | Item | How |
| ---------------- | ----------------------------------------------------------------- | | ------------ | --------------------------------------------------------------------- |
| Public key | `DISCORD_PUBLIC_KEY` set + Interactions Endpoint URL configured | | Public key | `DISCORD_PUBLIC_KEY` set + Interactions Endpoint URL configured |
| Invite scope | Bot invited with `applications.commands` (see invite URL above) | | Invite scope | Bot invited with `applications.commands` (see invite URL above) |
| OAuth | `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` and `BASE_URL` configured | | OAuth | `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` and `BASE_URL` configured |

View file

@ -43,7 +43,7 @@ npx wrangler dev # 启动本地开发服务器
### 密钥(本地用 `.dev.vars`,生产用 Worker Secrets ### 密钥(本地用 `.dev.vars`,生产用 Worker Secrets
| 变量 | 说明 | | 变量 | 说明 |
| ------------------------- | -------------------------------------------------------------------------- | | ------------------------ | --------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 | | `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 |
| `GITHUB_APP_ID` | GitHub App ID | | `GITHUB_APP_ID` | GitHub App ID |
| `GITHUB_PRIVATE_KEY` | App 私钥PEM | | `GITHUB_PRIVATE_KEY` | App 私钥PEM |
@ -211,7 +211,7 @@ bot 通过定时任务(每 5 分钟)同步注册原生的**斜杠命令**与
**要求:** **要求:**
| 项目 | 说明 | | 项目 | 说明 |
| ------------ | ---------------------------------------------------------------- | | ---------- | ---------------------------------------------------------------- |
| Public Key | 已配置 `DISCORD_PUBLIC_KEY` 且已设置 Interactions Endpoint URL | | Public Key | 已配置 `DISCORD_PUBLIC_KEY` 且已设置 Interactions Endpoint URL |
| 邀请 scope | 邀请时带上 `applications.commands`(见上方邀请链接) | | 邀请 scope | 邀请时带上 `applications.commands`(见上方邀请链接) |
| OAuth | 已配置 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET``BASE_URL` | | OAuth | 已配置 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET``BASE_URL` |

View file

@ -11,7 +11,7 @@ https://your-worker.workers.dev
## Endpoints ## Endpoints
| Method | Path | Auth | Description | | Method | Path | Auth | Description |
| -------- | ------------------------------ | -------------- | ------------------------ | | -------- | ------------------------------ | ----------------- | ------------------------------------------------------ |
| `GET` | `/health` | None | Health check | | `GET` | `/health` | None | Health check |
| `POST` | `/webhook` | HMAC signature | GitHub webhook ingestion | | `POST` | `/webhook` | HMAC signature | GitHub webhook ingestion |
| `POST` | `/discord/interactions` | Ed25519 signature | Discord interactions (slash commands, buttons, modals) | | `POST` | `/discord/interactions` | Ed25519 signature | Discord interactions (slash commands, buttons, modals) |

View file

@ -18,7 +18,7 @@ WebHooker requires several secrets to function. For local development, store the
### Optional Secrets ### Optional Secrets
| Variable | Description | Default | | Variable | Description | Default |
| ------------------------- | ----------------------------------------------------------------------------------------------------- | ----------------------- | | ------------------------ | ----------------------------------------------------------------------------- | --------------------------------- |
| `DISCORD_PUBLIC_KEY` | Discord application public key (Developer Portal) — required for interactions | Unset → interactions return `401` | | `DISCORD_PUBLIC_KEY` | Discord application public key (Developer Portal) — required for interactions | Unset → interactions return `401` |
| `DISCORD_APPLICATION_ID` | Discord application id; auto-resolved when omitted | Auto-resolved | | `DISCORD_APPLICATION_ID` | Discord application id; auto-resolved when omitted | Auto-resolved |
| `BASE_URL` | Public URL for OAuth callbacks | `http://localhost:8787` | | `BASE_URL` | Public URL for OAuth callbacks | `http://localhost:8787` |

View file

@ -18,7 +18,7 @@ POST /discord/interactions → verify (Ed25519) → handle /gh slash & context c
### Components ### Components
| Component | Role | | Component | Role |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| **Cloudflare Worker** | HTTP ingress, signature verification, delivery dedup, event parsing, route matching, REST send | | **Cloudflare Worker** | HTTP ingress, signature verification, delivery dedup, event parsing, route matching, REST send |
| **Interactions Endpoint** | Verifies Ed25519 signatures and handles `/gh` interactions (slash commands, context-menu commands, buttons, modals) | | **Interactions Endpoint** | Verifies Ed25519 signatures and handles `/gh` interactions (slash commands, context-menu commands, buttons, modals) |
| **KV** | Token storage (`token:{userId}`), OAuth state (`state:{hex}`), route config (`config:routes`), send logs, delivery dedup | | **KV** | Token storage (`token:{userId}`), OAuth state (`state:{hex}`), route config (`config:routes`), send logs, delivery dedup |

View file

@ -11,7 +11,7 @@ https://your-worker.workers.dev
## 端点 ## 端点
| 方法 | 路径 | 鉴权 | 说明 | | 方法 | 路径 | 鉴权 | 说明 |
| -------- | ------------------------------ | ------------ | ------------------------ | | -------- | ------------------------------ | ------------ | ------------------------------------- |
| `GET` | `/health` | 无 | 健康检查 | | `GET` | `/health` | 无 | 健康检查 |
| `POST` | `/webhook` | HMAC 签名 | GitHub webhook 接入 | | `POST` | `/webhook` | HMAC 签名 | GitHub webhook 接入 |
| `POST` | `/discord/interactions` | Ed25519 签名 | Discord 交互斜杠命令、按钮、modal | | `POST` | `/discord/interactions` | Ed25519 签名 | Discord 交互斜杠命令、按钮、modal |

View file

@ -18,7 +18,7 @@ POST /discord/interactions → 验证 (Ed25519) → 处理 /gh 斜杠与右键
### 组件 ### 组件
| 组件 | 职责 | | 组件 | 职责 |
| ----------------------------------- | --------------------------------------------------------------------------------------------------------- | | ------------------------- | --------------------------------------------------------------------------------------------------------- |
| **Cloudflare Worker** | HTTP 入口、签名验证、投递去重、事件解析、路由匹配、REST 发送 | | **Cloudflare Worker** | HTTP 入口、签名验证、投递去重、事件解析、路由匹配、REST 发送 |
| **Interactions Endpoint** | 验证 Ed25519 签名并处理 `/gh` 交互斜杠命令、右键菜单、按钮、modal | | **Interactions Endpoint** | 验证 Ed25519 签名并处理 `/gh` 交互斜杠命令、右键菜单、按钮、modal |
| **KV** | Token 存储 (`token:{userId}`)、OAuth 状态 (`state:{hex}`)、路由配置 (`config:routes`)、发送日志、投递去重 | | **KV** | Token 存储 (`token:{userId}`)、OAuth 状态 (`state:{hex}`)、路由配置 (`config:routes`)、发送日志、投递去重 |

View file

@ -165,7 +165,10 @@ export async function handleInteractionRequest(request: Request, env: Env): Prom
const signature = request.headers.get("X-Signature-Ed25519"); const signature = request.headers.get("X-Signature-Ed25519");
const timestamp = request.headers.get("X-Signature-Timestamp"); const timestamp = request.headers.get("X-Signature-Timestamp");
if (!signature || !timestamp || !env.DISCORD_PUBLIC_KEY) { if (!signature || !timestamp || !env.DISCORD_PUBLIC_KEY) {
log.warn({ hasSig: !!signature, hasTs: !!timestamp, hasKey: !!env.DISCORD_PUBLIC_KEY }, "Discord interaction missing signature"); log.warn(
{ hasSig: !!signature, hasTs: !!timestamp, hasKey: !!env.DISCORD_PUBLIC_KEY },
"Discord interaction missing signature",
);
return new Response("Invalid signature", { status: 401 }); return new Response("Invalid signature", { status: 401 });
} }
if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > TIMESTAMP_TOLERANCE_SECONDS) { if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > TIMESTAMP_TOLERANCE_SECONDS) {
@ -293,7 +296,12 @@ async function respond(env: Env, id: string, token: string, content: string): Pr
}); });
} }
async function interactionCallback(env: Env, id: string, token: string, body: unknown): Promise<void> { async function interactionCallback(
env: Env,
id: string,
token: string,
body: unknown,
): Promise<void> {
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/callback`, { const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/callback`, {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
@ -386,8 +394,7 @@ async function handleButton(
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): Promise<void> {
if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。"); if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。");
const clientId = env.GITHUB_CLIENT_ID; const clientId = env.GITHUB_CLIENT_ID;
if (!clientId) if (!clientId) return respond(env, id, token, "服务器未配置 GitHub OAuthGITHUB_CLIENT_ID。");
return respond(env, id, token, "服务器未配置 GitHub OAuthGITHUB_CLIENT_ID。");
const state = crypto.randomUUID().replace(/-/g, ""); const state = crypto.randomUUID().replace(/-/g, "");
await env.KV.put( await env.KV.put(
@ -404,7 +411,12 @@ async function cmdLogin(env: Env, id: string, token: string, userId: string | nu
); );
} }
async function cmdLogout(env: Env, id: string, token: string, userId: string | null): Promise<void> { async function cmdLogout(
env: Env,
id: string,
token: string,
userId: string | null,
): Promise<void> {
if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。"); if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。");
await removeDiscordLink(env.KV, userId); await removeDiscordLink(env.KV, userId);
await respond(env, id, token, "已解绑你的 GitHub 账号。"); await respond(env, id, token, "已解绑你的 GitHub 账号。");
@ -413,8 +425,7 @@ async function cmdLogout(env: Env, id: string, token: string, userId: string | n
/** Map a GitHub op error code to a user-facing (Chinese) message. */ /** Map a GitHub op error code to a user-facing (Chinese) message. */
function errText(err: unknown): string { function errText(err: unknown): string {
const t = err instanceof Error ? err.message : String(err); const t = err instanceof Error ? err.message : String(err);
if (t === "GITHUB_TOKEN_EXPIRED") if (t === "GITHUB_TOKEN_EXPIRED") return "GitHub 授权已过期或无效,请重新使用 `/gh login` 绑定。";
return "GitHub 授权已过期或无效,请重新使用 `/gh login` 绑定。";
if (t === "GITHUB_FORBIDDEN") return "GitHub 拒绝了此操作:你的账号没有权限修改/删除这条评论。"; if (t === "GITHUB_FORBIDDEN") return "GitHub 拒绝了此操作:你的账号没有权限修改/删除这条评论。";
if (t === "GITHUB_NOT_FOUND") return "找不到目标(可能评论已被删除或仓库不可访问)。"; if (t === "GITHUB_NOT_FOUND") return "找不到目标(可能评论已被删除或仓库不可访问)。";
return `操作失败:${t}`; return `操作失败:${t}`;
@ -480,13 +491,7 @@ async function commentOp(
// edit: fetch current body to prefill the modal. // edit: fetch current body to prefill the modal.
let prefill = ""; let prefill = "";
try { try {
const { body } = await getCommentAsUser( const { body } = await getCommentAsUser(env.KV, githubUserId, owner!, repo!, Number(commentId));
env.KV,
githubUserId,
owner!,
repo!,
Number(commentId),
);
prefill = body; prefill = body;
} catch (err) { } catch (err) {
return respond(env, id, token, errText(err)); return respond(env, id, token, errText(err));
@ -678,14 +683,11 @@ export async function syncGuildCommands(env: Env): Promise<void> {
for (const guild of guilds) { for (const guild of guilds) {
try { try {
if (await env.KV.get(`cmd:guild:${guild.id}`)) continue; if (await env.KV.get(`cmd:guild:${guild.id}`)) continue;
const r = await fetch( const r = await fetch(`${DISCORD_API}/applications/${appId}/guilds/${guild.id}/commands`, {
`${DISCORD_API}/applications/${appId}/guilds/${guild.id}/commands`,
{
method: "PUT", method: "PUT",
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" }, headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
body: JSON.stringify(APP_COMMANDS), body: JSON.stringify(APP_COMMANDS),
}, });
);
if (r.ok) { if (r.ok) {
await env.KV.put(`cmd:guild:${guild.id}`, "1"); await env.KV.put(`cmd:guild:${guild.id}`, "1");
log.info({ guildId: guild.id }, "Registered guild application commands"); log.info({ guildId: guild.id }, "Registered guild application commands");