diff --git a/AGENTS.md b/AGENTS.md index 0173fc6..cce49e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,6 +108,9 @@ server/ # Nitro server │ └── updates.ts # X-Lark-Signature verify + url_verification + /gh commands + card.action.trigger buttons ├── github/ │ ├── oauth.ts # OAuth URL, callback token exchange, getUserOctokit, comment/getComment/editComment/deleteComment/merge/close actions + │ ├── app-token.ts # createAppJwt-backed getInstallationToken + GITHUB_API_VERSION (shared App auth) + │ ├── check-run.ts # getCheckSuiteBuildLogUrl: Check-suite build-log enrichment (installation token) + │ ├── workflow-jobs.ts # getWorkflowRunJobs: fetch a workflow_run's jobs via jobs_url (App token or unauthenticated) │ └── store.ts # KV token CRUD + D1 discord-link/telegram-link mapping (was token-store.ts) ├── web/ # HTTP UI/API logic (called from server/routes) │ ├── oauth.ts # handleOAuthStart/Callback, install page + bind, personal-group self-signup diff --git a/docs/events/supported.md b/docs/events/supported.md index 3245b07..f4aa556 100644 --- a/docs/events/supported.md +++ b/docs/events/supported.md @@ -62,6 +62,8 @@ Any event type without a dedicated formatter falls through to the generic format `workflow_run` and `check_run` events (queued → running → success/failure) are sent once and then **edited in place** for each subsequent phase instead of posting a new message. The original message's link preview, author, and field layout are preserved; only the status, conclusion emoji, duration, and title are refreshed. Supported on both Discord (`editMessage`) and Telegram (`editMessageText` / `editMessageCaption`). `check_run` tracks by check name + commit SHA (falling back to the run id), so providers that issue a new run id per phase — e.g. Cloudflare Pages — still edit the same message. +`workflow_run` messages also carry a colored **Jobs** breakdown. Because the webhook payload itself has no job list (only a `jobs_url`), the worker fetches it from the GitHub API — authenticated with a GitHub App installation token when `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` are set, otherwise unauthenticated (public repositories). The App therefore needs the **Actions: read** repository permission. + ## Filter Compatibility See the [Filter Tutorial](../guide/filters) for a hands-on guide with worked examples. diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 5e91bbb..356f6cb 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -40,7 +40,7 @@ There is no global channel secret. Each route in the [Web UI](/guide/configurati ::: ::: tip GitHub App ID / private key are optional -`GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` (PKCS#8 PEM) are only used by the [App install flow](#github-app-setup) to resolve the installing account's login on the post-install choice page. You can skip them — the page then shows an anonymous `inst-{installationId}` group. The OAuth flow only needs `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`. +`GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` (PKCS#8 PEM) are used by the [App install flow](#github-app-setup) to resolve the installing account's login on the post-install choice page, and to mint installation tokens for API enrichment — fetching `workflow_run` job lists and check-suite build logs. You can skip them — the install page then shows an anonymous `inst-{installationId}` group, workflow job lists still load for public repositories (unauthenticated), and private-repo build logs are omitted. The OAuth flow only needs `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`. ::: Discord interactions arrive via the HTTPS Interactions Endpoint, so set `DISCORD_PUBLIC_KEY` and point the **Interactions Endpoint URL** at `https://your-domain/discord/interactions`. See [Interactions Endpoint](#interactions-endpoint) below. @@ -144,11 +144,11 @@ Your worker is now live at `https://webhooker..workers.dev`. - **Webhook URL**: `https://your-domain/webhook` - **Webhook secret**: generate and copy to `GITHUB_WEBHOOK_SECRET` 3. Set permissions: - - **Repository permissions**: Contents (read), Issues (write), Pull requests (write), Metadata (read), Checks (read), Deployments (read), Discussions (read), Code scanning alerts (read), Dependabot alerts (read) + - **Repository permissions**: Contents (read), Issues (write), Pull requests (write), Metadata (read), Checks (read), Actions (read), Deployments (read), Discussions (read), Code scanning alerts (read), Dependabot alerts (read) - **Organization permissions**: Members (read) — if needed 4. Subscribe to events (all 28 supported): - Push, Pull request, Issues, Issue comment, Workflow run, Workflow job, Status, Deployment, Deployment status, Ping, Release, Create, Delete, Star, Fork, Check run, Check suite, Pull request review, Pull request review comment, Commit comment, Member, Label, Milestone, Discussion, Discussion comment, Repository, Code scanning alert, Dependabot alert -5. Generate private key — optional; set `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` to show the installing account's login on the post-install page (see the tip above). +5. Generate private key — optional; set `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` to show the installing account's login on the post-install page and to authenticate API enrichment (workflow job lists, build logs) for private repositories (see the tip above). ### 2. Install App diff --git a/docs/guide/message-format.md b/docs/guide/message-format.md index 32e569f..a683562 100644 --- a/docs/guide/message-format.md +++ b/docs/guide/message-format.md @@ -47,3 +47,5 @@ With `Group.forgeSources` (a list of `{ host, type, name? }` entries) the messag ``` Each line is `{name} {emoji}{status}` plus the job duration when it has completed. Successful jobs are prefixed with `+` (green), failed/other finished jobs with `-` (red), and running/queued/pending jobs use a plain space (no color). The job name is clamped to 200 chars and the whole field to the platform field limit. Drivers without diff support (Telegram, Feishu) render the block as a single inline code span. + +The `workflow_run` webhook payload itself carries no job list — only a `jobs_url`. The worker fetches the jobs from that URL (one GitHub API call per delivery, skipped when no route matches): authenticated with a GitHub App installation token when `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` are configured, otherwise unauthenticated (public repositories only). The App therefore needs the **Actions: read** repository permission. If the fetch fails (missing permission, private repo without App creds, rate limit) the message simply omits the Jobs field. diff --git a/docs/zh/events/supported.md b/docs/zh/events/supported.md index a40329a..296830a 100644 --- a/docs/zh/events/supported.md +++ b/docs/zh/events/supported.md @@ -62,6 +62,8 @@ WebHooker 支持 28 种 GitHub webhook 事件类型,每种都有专用的格 `workflow_run` / `check_run` 事件(queued → running → success/failure)只发送一条消息,后续每个阶段会**原地编辑**该消息,而不是发送新消息。消息的链接预览、作者和字段布局保持不变,仅刷新状态、结论 emoji、耗时和标题。Discord(`editMessage`)和 Telegram(`editMessageText` / `editMessageCaption`)均支持。`check_run` 以 check 名 + commit SHA 追踪(回退到 run id),因此每个阶段都会换新 run id 的提供方(例如 Cloudflare Pages)仍会编辑同一条消息。 +`workflow_run` 消息还会附带带颜色的 **Jobs** 明细。由于 webhook 载荷本身不含作业列表(只有 `jobs_url`),Worker 会从 GitHub API 拉取——配置了 `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 时用 GitHub App 安装令牌鉴权,否则匿名请求(公开仓库)。因此 App 需要 **Actions: read** 仓库权限。 + ## 过滤器兼容性 实操指南见[过滤器教程](../guide/filters),包含完整示例。 diff --git a/docs/zh/guide/deployment.md b/docs/zh/guide/deployment.md index 19233ca..eb8b0d6 100644 --- a/docs/zh/guide/deployment.md +++ b/docs/zh/guide/deployment.md @@ -40,7 +40,7 @@ bunx wrangler secret put ADMIN_USER_IDS # 逗号分隔的 GitHub ID/登录 ::: ::: tip GitHub App ID / 私钥为可选 -`GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)仅用于 [App 安装流程](#github-app-设置),在安装后选择页解析安装所属账号的登录名。可以跳过不设——页面会显示匿名 `inst-{installationId}` 分组。OAuth 流程只需要 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`。 +`GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)用于 [App 安装流程](#github-app-设置),在安装后选择页解析安装所属账号的登录名,并用于签发安装令牌做 API 增强——拉取 `workflow_run` 作业列表与 check-suite 构建日志。可以跳过不设——安装页会显示匿名 `inst-{installationId}` 分组,公开仓库的作业列表仍会以匿名方式加载,私有仓库的构建日志则省略。OAuth 流程只需要 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`。 ::: Discord 交互通过 HTTPS Interactions Endpoint 送达,需要设置 `DISCORD_PUBLIC_KEY` 并把 **Interactions Endpoint URL** 指向 `https://your-domain/discord/interactions`。参见下方 [Interactions Endpoint](#interactions-endpoint)。 @@ -144,11 +144,11 @@ Worker 现在可通过 `https://webhooker..workers.dev` 访问 - **Webhook URL**: `https://your-domain/webhook` - **Webhook secret**: 生成并复制到 `GITHUB_WEBHOOK_SECRET` 3. 设置权限: - - **Repository permissions**: Contents (read)、Issues (write)、Pull requests (write)、Metadata (read)、Checks (read)、Deployments (read)、Discussions (read)、Code scanning alerts (read)、Dependabot alerts (read) + - **Repository permissions**: Contents (read)、Issues (write)、Pull requests (write)、Metadata (read)、Checks (read)、Actions (read)、Deployments (read)、Discussions (read)、Code scanning alerts (read)、Dependabot alerts (read) - **Organization permissions**: Members (read) —— 如果需要 4. 订阅事件(全部 28 种支持的事件): - Push、Pull request、Issues、Issue comment、Workflow run、Workflow job、Status、Deployment、Deployment status、Ping、Release、Create、Delete、Star、Fork、Check run、Check suite、Pull request review、Pull request review comment、Commit comment、Member、Label、Milestone、Discussion、Discussion comment、Repository、Code scanning alert、Dependabot alert -5. 生成私钥 — 可选;设置 `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` 后,安装后页面会显示安装所属账号的登录名(见上方提示)。 +5. 生成私钥 — 可选;设置 `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY` 后,安装后页面会显示安装所属账号的登录名,并以安装令牌鉴权私有仓库的 API 增强(作业列表、构建日志)(见上方提示)。 ### 2. 安装 App diff --git a/docs/zh/guide/message-format.md b/docs/zh/guide/message-format.md index f6f8dd8..c2a73c9 100644 --- a/docs/zh/guide/message-format.md +++ b/docs/zh/guide/message-format.md @@ -47,3 +47,5 @@ ``` 每行格式为 `{作业名} {emoji}{状态}`,作业完成后追加耗时。成功的作业以 `+` 前缀(绿色),失败/其他已结束的作业以 `-` 前缀(红色),运行中/排队中/待定的作业使用普通空格(无颜色)。作业名截断至 200 字符,整个字段截断至平台字段上限。不支持 diff 的驱动(Telegram、飞书)会把该代码块渲染为单个行内代码片段。 + +`workflow_run` 的 webhook 载荷本身不含作业列表,只有 `jobs_url`。Worker 会从该 URL 拉取作业(每次投递一次 GitHub API 调用,没有路由命中时跳过):配置了 `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 时用 GitHub App 安装令牌鉴权,否则匿名请求(仅公开仓库)。因此 App 需要 **Actions: read** 仓库权限。若拉取失败(缺少权限、私有仓库且未配置 App 凭据、触发限流),消息直接省略 Jobs 字段。 diff --git a/server/lib/core/dispatch.ts b/server/lib/core/dispatch.ts index c719e29..5bd39e6 100644 --- a/server/lib/core/dispatch.ts +++ b/server/lib/core/dispatch.ts @@ -18,6 +18,7 @@ import { getDriver } from "../drivers"; import type { SendResult } from "../drivers/types"; import type { DispatchFailure, DispatchSummary } from "../queue/delivery"; import { getCheckSuiteBuildLogUrl } from "../github/check-run"; +import { getWorkflowRunJobs } from "../github/workflow-jobs"; /** One dispatch attempt (route × target), collected for the group webhook log. */ interface DispatchAttempt { @@ -163,10 +164,31 @@ export async function dispatchEvent( } } + let workflowJobsPromise: Promise | undefined; + function ensureWorkflowJobs(): Promise { + if (event.event !== "workflow_run") return Promise.resolve(); + workflowJobsPromise ??= (async (): Promise => { + const run = event.payload.workflow_run as + | { jobs_url?: string; jobs?: unknown[] } + | undefined; + if (!run?.jobs_url || run.jobs?.length) return; + const jobs = await getWorkflowRunJobs( + run.jobs_url, + env.GITHUB_APP_ID, + env.GITHUB_PRIVATE_KEY, + event.installationId, + ); + if (jobs) run.jobs = jobs; + })(); + return workflowJobsPromise; + } + async function processRoute(route: Route): Promise { const targets = route.targets && route.targets.length > 0 ? route.targets : []; if (targets.length === 0) return; + await ensureWorkflowJobs(); + const group = route.groupId ? groupById.get(route.groupId) : undefined; const tr = trMap.get(group?.lang ?? "en")!; const showEmoji = group?.emoji !== false; diff --git a/server/lib/github/app-token.ts b/server/lib/github/app-token.ts new file mode 100644 index 0000000..f473ad2 --- /dev/null +++ b/server/lib/github/app-token.ts @@ -0,0 +1,35 @@ +import { createAppJwt } from "./oauth"; + +export const GITHUB_API_VERSION = "2022-11-28"; + +/** + * Mint a short-lived installation access token for a GitHub App installation. + * Returns undefined when the App credentials are missing or the exchange + * fails. Best-effort: callers must not depend on it. + */ +export async function getInstallationToken( + appId: string | undefined, + privateKey: string | undefined, + installationId: number | undefined, +): Promise { + if (!appId || !privateKey || !installationId) return undefined; + try { + const jwt = await createAppJwt(appId, privateKey); + const res = await fetch( + `https://api.github.com/app/installations/${installationId}/access_tokens`, + { + method: "POST", + headers: { + Authorization: `Bearer ${jwt}`, + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": GITHUB_API_VERSION, + }, + }, + ); + if (!res.ok) return undefined; + const { token } = (await res.json()) as { token?: string }; + return token ?? undefined; + } catch { + return undefined; + } +} diff --git a/server/lib/github/check-run.ts b/server/lib/github/check-run.ts index 37ffca0..8b1cdba 100644 --- a/server/lib/github/check-run.ts +++ b/server/lib/github/check-run.ts @@ -1,6 +1,5 @@ -import { createAppJwt } from "./oauth"; +import { getInstallationToken, GITHUB_API_VERSION } from "./app-token"; -const API_VERSION = "2022-11-28"; const CLOUDFLARE_SLUG = "cloudflare-workers-and-pages"; /** @@ -21,27 +20,14 @@ export async function getCheckSuiteBuildLogUrl( ): Promise { if (!checkRunsUrl || !appId || !privateKey || !installationId) return undefined; try { - const jwt = await createAppJwt(appId, privateKey); - const tokRes = await fetch( - `https://api.github.com/app/installations/${installationId}/access_tokens`, - { - method: "POST", - headers: { - Authorization: `Bearer ${jwt}`, - Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": API_VERSION, - }, - }, - ); - if (!tokRes.ok) return undefined; - const { token } = (await tokRes.json()) as { token?: string }; + const token = await getInstallationToken(appId, privateKey, installationId); if (!token) return undefined; const runsRes = await fetch(checkRunsUrl, { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", - "X-GitHub-Api-Version": API_VERSION, + "X-GitHub-Api-Version": GITHUB_API_VERSION, }, }); if (!runsRes.ok) return undefined; diff --git a/server/lib/github/workflow-jobs.ts b/server/lib/github/workflow-jobs.ts new file mode 100644 index 0000000..87a01ad --- /dev/null +++ b/server/lib/github/workflow-jobs.ts @@ -0,0 +1,44 @@ +import { getInstallationToken, GITHUB_API_VERSION } from "./app-token"; + +export interface WorkflowJob { + name?: string; + status?: string; + conclusion?: string | null; + started_at?: string; + completed_at?: string; +} + +/** + * Fetch the jobs of a workflow run from its `jobs_url`. The `workflow_run` + * webhook payload only carries `jobs_url`, never the jobs themselves, so this + * enrichment is required for the formatter's Jobs field. + * + * Uses an App installation token when the credentials are available (required + * for private repos); otherwise falls back to an unauthenticated request, + * which works for public repositories at a lower rate limit. Best-effort: + * returns undefined on any failure. + */ +export async function getWorkflowRunJobs( + jobsUrl: string | undefined, + appId: string | undefined, + privateKey: string | undefined, + installationId: number | undefined, +): Promise { + if (!jobsUrl) return undefined; + try { + const token = await getInstallationToken(appId, privateKey, installationId); + const url = new URL(jobsUrl); + url.searchParams.set("per_page", "100"); + const headers: Record = { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": GITHUB_API_VERSION, + }; + if (token) headers.Authorization = `Bearer ${token}`; + const res = await fetch(url.toString(), { headers }); + if (!res.ok) return undefined; + const data = (await res.json()) as { jobs?: WorkflowJob[] }; + return data.jobs?.length ? data.jobs : undefined; + } catch { + return undefined; + } +} diff --git a/tests/github-workflow-jobs.test.ts b/tests/github-workflow-jobs.test.ts new file mode 100644 index 0000000..d80bcf3 --- /dev/null +++ b/tests/github-workflow-jobs.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, afterEach } from "bun:test"; +import { getWorkflowRunJobs } from "../server/lib/github/workflow-jobs"; + +function bufToPem(buf: ArrayBuffer): string { + const bytes = new Uint8Array(buf); + let s = ""; + for (const b of bytes) s += String.fromCharCode(b); + const b64 = btoa(s); + return `-----BEGIN PRIVATE KEY-----\n${b64.replace(/(.{64})/g, "$1\n")}\n-----END PRIVATE KEY-----`; +} + +async function makeAppKeyPair(): Promise<{ appId: string; pem: string }> { + const pair = await crypto.subtle.generateKey( + { + name: "RSASSA-PKCS1-v1_5", + modulusLength: 2048, + publicExponent: new Uint8Array([1, 0, 1]), + hash: "SHA-256", + }, + true, + ["sign", "verify"], + ); + const pkcs8 = await crypto.subtle.exportKey("pkcs8", pair.privateKey); + return { appId: "12345", pem: bufToPem(pkcs8) }; +} + +const JOBS_URL = "https://api.github.com/repos/acme/widget/actions/runs/42/jobs"; + +describe("getWorkflowRunJobs", () => { + const restoredFetch = globalThis.fetch; + + afterEach(() => { + globalThis.fetch = restoredFetch; + }); + + function mockFetch( + handler: (url: string, init?: RequestInit) => Response | Promise, + ): string[] { + const urls: string[] = []; + globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + urls.push(url); + return Promise.resolve(handler(url, init)); + }) as typeof fetch; + return urls; + } + + it("mints an installation token then lists the jobs", async () => { + const { appId, pem } = await makeAppKeyPair(); + const jobs = [{ name: "build", status: "completed", conclusion: "success" }]; + const urls = mockFetch((url) => { + if (url.includes("/access_tokens")) { + return new Response(JSON.stringify({ token: "ghs_test" }), { status: 201 }); + } + return new Response(JSON.stringify({ jobs }), { status: 200 }); + }); + + const result = await getWorkflowRunJobs(JOBS_URL, appId, pem, 555); + expect(result).toEqual(jobs); + expect(urls[0]).toContain("/app/installations/555/access_tokens"); + expect(urls[1]).toContain(JOBS_URL); + expect(urls[1]).toContain("per_page=100"); + }); + + it("falls back to an unauthenticated request without App credentials", async () => { + const jobs = [{ name: "test", status: "in_progress" }]; + let sawAuth: string | undefined; + mockFetch((_url, init) => { + sawAuth = (init?.headers as Record | undefined)?.Authorization; + return new Response(JSON.stringify({ jobs }), { status: 200 }); + }); + + const result = await getWorkflowRunJobs(JOBS_URL, undefined, undefined, undefined); + expect(result).toEqual(jobs); + expect(sawAuth).toBeUndefined(); + }); + + it("returns undefined when jobs_url is missing", async () => { + let called = false; + mockFetch(() => { + called = true; + return new Response("{}", { status: 200 }); + }); + expect(await getWorkflowRunJobs(undefined, undefined, undefined, undefined)).toBeUndefined(); + expect(called).toBe(false); + }); + + it("returns undefined when the API responds with an error", async () => { + mockFetch(() => new Response("{}", { status: 403 })); + expect(await getWorkflowRunJobs(JOBS_URL, undefined, undefined, undefined)).toBeUndefined(); + }); + + it("returns undefined for an empty jobs list", async () => { + mockFetch(() => new Response(JSON.stringify({ jobs: [] }), { status: 200 })); + expect(await getWorkflowRunJobs(JOBS_URL, undefined, undefined, undefined)).toBeUndefined(); + }); + + it("returns undefined when the request throws", async () => { + globalThis.fetch = (() => Promise.reject(new Error("network"))) as typeof fetch; + expect(await getWorkflowRunJobs(JOBS_URL, undefined, undefined, undefined)).toBeUndefined(); + }); +});