Files
WebHooker/docs/zh/guide/deployment.md
T
翅膀喵andRhenCloud 978c53eeb3 fix(security): harden webhook delivery pipeline and group storage (#11)
* 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>
2026-10-24 16:19:06 +08:00

268 lines
17 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 部署
## Cloudflare 设置
`wrangler.jsonc` 中带有维护者的 `account_id` 与资源 id。请把 `account_id` 换成你自己的 Cloudflare 账号 id(`bunx wrangler whoami`),或删除该字段以部署到当前登录的账号,并按下面的步骤替换各资源 id。
### 1. 创建 KV 命名空间
```bash
bunx wrangler kv namespace create KV
```
这会输出一个命名空间 ID。更新 `wrangler.jsonc`,填入 ID:
```jsonc
{
"kv_namespaces": [
{
"binding": "KV",
"id": "your-namespace-id",
},
],
}
```
### 2. 设置密钥
```bash
bunx wrangler secret put GITHUB_WEBHOOK_SECRET
bunx wrangler secret put GITHUB_CLIENT_ID
bunx wrangler secret put GITHUB_CLIENT_SECRET
bunx wrangler secret put DISCORD_TOKEN
bunx wrangler secret put DISCORD_PUBLIC_KEY # Discord 应用的公钥(开发者门户获取),交互功能必需
bunx wrangler secret put TELEGRAM_TOKEN # Telegram Bot Token(BotFather 获取)—— Telegram 路由必需
bunx wrangler secret put FEISHU_APP_ID # 飞书应用 ID —— 飞书路由必需
bunx wrangler secret put FEISHU_APP_SECRET # 飞书应用密钥 —— 飞书路由必需
bunx wrangler secret put ADMIN_USER_IDS # 允许进入 Web UI 的 GitHub 用户 id,逗号分隔(建议写数字 id)
bunx wrangler secret put BASE_URL # worker 的公网地址——OAuth 回调与 Telegram webhook 同步都需要
```
::: tip 目标频道按路由配置
不存在全局频道密钥。每条路由在 [Web 控制台](/zh/guide/configuration#web-控制台) 中声明各自的目标频道(及可选的子区/thread),因此不需要 `DISCORD_CHANNEL_ID`。
:::
::: tip GitHub App ID / 私钥为可选
`GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)用于 [App 安装流程](#github-app-设置),在安装后选择页解析安装所属账号的登录名,并用于签发安装令牌做 API 增强——拉取 `workflow_run` 作业列表与 check-suite 构建日志。不设置时只有超级管理员能绑定安装——安装流程无法解析安装所属账号,也就无法核实登录用户是否管理该安装;公开仓库的作业列表仍会以匿名方式加载,私有仓库的构建日志则省略。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)。
### 3. 创建 D1 数据库并执行迁移
```bash
bunx wrangler d1 create webhooker
```
将返回的数据库 ID 填入 `wrangler.jsonc`:
```jsonc
{
"d1_databases": [
{
"binding": "DB",
"database_name": "webhooker",
"database_id": "your-database-id",
},
],
}
```
然后执行迁移:
```bash
bun run db:migrate:prod # 将迁移应用到远端 D1 数据库
bun run db:migrate # 将迁移应用到本地(Miniflare)数据库
```
`db:migrate` 脚本执行 `wrangler d1 migrations apply webhooker`(见 `package.json`),逐一应用 `migrations/` 下的 SQL 文件,并在 `d1_migrations` 表中记录已应用的版本。`bun run deploy` 会在部署前先执行 `db:migrate:prod`,因此之后新增的迁移会在下次部署时自动应用;已应用的会被跳过,迁移失败时不会继续部署。
::: tip 曾用 `d1 execute` 迁移过的数据库
如果数据库已有这些表/列(例如之前用 `wrangler d1 execute --file` 迁移过),可能缺少 `d1_migrations` 追踪表,`db:migrate:prod` 会尝试重新执行所有迁移;`0002_log_detail.sql` 中的 `ALTER TABLE ... ADD COLUMN` 语句会因列已存在而失败。此时请直接执行数据库尚未应用的文件(`ALTER TABLE ... ADD COLUMN` 的文件重复执行会失败,已应用的请跳过):
```bash
bunx wrangler d1 execute webhooker --remote --file ./migrations/0001_init.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0002_log_detail.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0003_telegram_links.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0004_add_group_id.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0005_audit_logs.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0006_config_d1.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0007_send_logs_index.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0008_storage_d1.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0010_fragments.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0011_feishu_links.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0012_route_position.sql
bunx wrangler d1 execute webhooker --remote --file ./migrations/0013_prune_indexes.sql
```
这类数据库没有迁移历史,`bun run deploy`(会先执行 `db:migrate:prod`)会再次尝试所有迁移并中止。请用 `bunx wrangler deploy` 部署,之后新增的迁移文件也按上面的方式手动执行。
:::
### 4. 创建 R2 Bucket(可选)
`PAYLOAD` 绑定将超大 webhook 负载暂存在 R2(`webhooker-payloads`)而非 KV。未设置时,超大负载回退到 KV 键 `queue:payload:*`。布局见[存储](/zh/guide/storage)。
```bash
bunx wrangler r2 bucket create webhooker-payloads
```
然后取消 `wrangler.jsonc` 中 `r2_buckets` 块的注释(默认是注释掉的);没有该绑定时,超大负载仍暂存在 KV。
### 5. 创建队列(可选)
`QUEUE` 绑定会通过 Cloudflare Queues 投递 webhook(异步分发,带重试退避与死信队列)。如需保持同步内联分发,请删除或注释掉 `wrangler.jsonc` 中的 `queues` 块;保留该块时两个队列都必须存在。
```bash
bunx wrangler queues create webhooker-delivery
bunx wrangler queues create webhooker-delivery-dlq
```
队列已在 `wrangler.jsonc` 中声明(`queues.producers` / `queues.consumers`),无需修改绑定。`webhooker-delivery` 消费者对可重试失败(5xx、429、网络错误、限流重试耗尽、飞书 token 错误)做指数退避重试(5s/30s/2m/10m),达到 `max_retries` 后消息进入 `webhooker-delivery-dlq` 并标记为 dead。重试按目标进行:已成功或已永久失败的目标会被记录且不再尝试,因此单个坏目标不会取消其他目标的重试,重试也不会重发已记录的目标(发送成功但记录写入失败的目标可能被重发)。每次消费者调用最多取 3 条消息,共享 12 分钟与 20 次目标发送的预算,因为 Workers 免费版的限额(50 次 D1 查询、50 个子请求)按单次调用计算:预算没轮到的消息会被重试,目标数超过预算的投递会以新的队列消息继续。只要过程中有任一目标永久失败,即使其余目标最终都已处理,该投递仍以 `failed` 结束。领取投递带 5 分钟租约,两个消费者不会同时分发同一投递。
> [!NOTE]
> R2 没有按对象的 TTL。暂存负载在分发后删除,定时任务 `storage-prune` 会清理超过五天的遗留对象;也可以为 `webhooks/` 前缀添加 bucket [生命周期规则](https://developers.cloudflare.com/r2/buckets/object-lifecycles/)。
### 6. 部署
```bash
bun run deploy # 先应用待执行的 D1 迁移,再执行 wrangler deploy
```
在终端中运行时,wrangler 会在应用待执行的迁移前请求确认;在 CI 中会直接继续。如果通过 Cloudflare 的 Git 集成(Workers Builds)部署,请把其部署命令设为 `bun run deploy`,以便同样自动应用迁移。
Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问。
### 7. 配置 GitHub Webhook
1. 进入 GitHub App 设置页面
2. 设置 **Webhook URL** 为 `https://webhooker.<your-subdomain>.workers.dev/webhook`
3. 设置 **Webhook secret** 与 `GITHUB_WEBHOOK_SECRET` 一致
### 8.(可选)配置 Gitea Webhook
1. 在 Gitea 仓库中进入 **设置 → Web 钩子 → 添加 Web 钩子 → Gitea**
2. 设置 **目标 URL** 为 `https://webhooker.<your-subdomain>.workers.dev/webhook`
3. 设置 **HTTP 方法** 为 `POST`、**Content Type** 为 `application/json`
4. 设置 **密钥** 与 `GITEA_WEBHOOK_SECRET` 一致
5. 选择要触发的事件(push、议题、拉取请求、发布等)
## GitHub App 设置
### 1. 创建 App
1. 打开 <https://github.com/settings/apps/new>
2. 填写:
- **GitHub App name**: `WebHooker`(或自定义名称)
- **Homepage URL**: 你的域名
- **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)、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`:安装流程需要它们核实安装者是否管理该安装(没有时只有超级管理员能绑定安装),私有仓库的 API 增强(作业列表、构建日志)也用它们鉴权(见上方提示)。
### 2. 安装 App
1. 创建后,进入 App 设置页面
2. 点击 "Install App" → 选择组织/用户
3. 选择要监控的仓库
### 3. 配置 OAuth
1. 进入 App → OAuth 设置
2. 设置 **Callback URL**: `https://your-domain/auth/github/callback`
3. 将 Client ID 和 Client Secret 复制到环境变量
## Discord Bot 设置
1. 打开 <https://discord.com/developers/applications>
2. 创建新应用 → 进入 Bot 部分
3. 将 Bot Token 复制到 `DISCORD_TOKEN`
4. 使用 `bot` 与 `applications.commands` 两个 scope 邀请 Bot,并勾选 `View Channels` + `Send Messages` + `Send Messages in Threads` 权限(组合整数 `274877910016`):
```text
https://discord.com/oauth2/authorize?client_id=YOUR_BOT_CLIENT_ID&permissions=274877910016&scope=bot+applications.commands
```
5. 在 Web UI(`/admin`)中**按路由**配置目标频道——无需全局频道 ID。
### Interactions Endpoint
消息通过 Discord **REST API** 发送,因此仅凭 `DISCORD_TOKEN` 即可推送。交互(斜杠命令、按钮、modal)则通过 HTTPS Interactions Endpoint 送达:
1. 在 Discord 开发者门户 → General Information 复制应用的 **Public Key**,填入 `DISCORD_PUBLIC_KEY`。
2. 将 **Interactions Endpoint URL** 设为 `https://your-domain/discord/interactions`。
3. 所有交互请求都使用 Ed25519 签名验证(`X-Signature-Ed25519` 覆盖 `X-Signature-Timestamp + body`)。
`/gh` 斜杠命令与 `GitHub: 添加/编辑/删除评论` 消息命令由定时任务(每 5 分钟)同步注册:按服务器即时可用(每轮最多 30 次 API 调用),同时全局注册(约 1 小时传播);命令定义变化时两者都会重新注册。Bot 从不连接 Discord Gateway,因此显示为**离线**——消息推送不受影响(始终走 REST)。
用户运行 `/gh login` 绑定自己的 GitHub 账号,即可以本人身份评论 issue/PR。完整命令说明见[机器人命令](/zh/guide/commands)。
## Telegram 机器人配置
1. 用 [@BotFather](https://t.me/BotFather) 创建机器人,将 Token 复制到 `TELEGRAM_TOKEN`。
2. (可选)设置 `TELEGRAM_WEBHOOK_SECRET`;webhook 注册时会作为 `secret_token` 传给 Telegram,`POST /telegram/webhook` 使用时间安全比较校验。未设置时改用由 `TELEGRAM_TOKEN` 派生的密钥,端点始终需要认证(下一次定时同步会用它重新注册 webhook)。
3. Worker 会在定时任务中自动同步 webhook(`setWebhook` 指向 `{BASE_URL}/telegram/webhook`,仅在注册内容变化时以及每天一次),因此无需手动调用 `setWebhook`——只需确保 `BASE_URL` 已设置。
4. 将机器人加入群组(或启用话题),在路由配置中用 `chatId` / `topicId` 指定目标。请使用数字 chat id(如 `-1001234567890`),不接受 `@username` 目标。
在 Telegram 中,`/gh` 命令(`/gh login`、`/gh logout`、`/gh comment <内容>`、`/gh merge`、`/gh close`)通过在通知消息上**回复**来使用——见[机器人命令](/zh/guide/commands)。
头像使用内置 `GET /api/richheader` 渲染为链接预览卡片(可用 `TELEGRAM_RICH_HEADER_HOST` 覆盖;未设置 `BASE_URL` 时直接以头像图片作为预览)。消息始终是文本消息,原地更新时仍有完整的 4096 字符上限。
## 飞书机器人配置
1. 进入[飞书开放平台](https://open.feishu.cn/app) → **创建应用** → 选择**企业自建应用** → 填写应用名称。
2. 在**凭证与基础信息**中复制 **App ID** 与 **App Secret**,分别填入 `FEISHU_APP_ID` 和 `FEISHU_APP_SECRET`。
3. 在**权限管理**中添加以下任一消息发送权限,用于发送(与读取)消息:
- `im:message`(读取和发送单聊与群聊消息)
- `im:message:send_as_bot`(以应用机器人身份发送消息)
- `im:message:send`(旧版发送消息权限)
4. 在**机器人**功能中启用机器人。将机器人添加到目标群聊(或创建新群),并在群设置中复制 **Chat ID**。
5. 在 WebHooker `/admin` 中创建或编辑路由,添加目标:`platform: "feishu"`,`chatId` 填写飞书 **Chat ID**(`oc_…`);飞书目标没有话题。
WebHooker 使用应用级凭证(`FEISHU_APP_ID` / `FEISHU_APP_SECRET`)请求 `tenant_access_token`(有效期约 2 小时),按应用缓存在内存与 KV 中、到期前不久为止,被飞书拒绝时立即丢弃,并以**卡片消息**(`interactive`)形式发送。`workflow_run` / `check_run` 的进度更新同样会调用飞书消息编辑接口,原地更新消息。
### 入站:指令与按钮
与 Discord、Telegram 一样,WebHooker 可接收飞书事件,让用户直接在聊天里操作 PR/Issue:
- `/gh login` —— 绑定 GitHub 账号(打开 OAuth 页面)。
- `/gh logout` —— 解绑 GitHub 账号。
- `/gh comment <PR/Issue 链接> <内容>` —— 以绑定的 GitHub 身份发表评论。
- `/gh merge <PR 链接>` / `/gh close <PR 链接>` —— 以绑定身份合并 / 关闭 PR。
- 卡片上的 **合并** / **关闭** 按钮触发相同操作。
开启入站:
1. 在应用的**事件订阅**中,把**请求地址**设为 `https://<你的-worker>/feishu/webhook`(飞书会发送 `url_verification` 校验,WebHooker 自动应答)。
2. 订阅以下事件:
- `im.message.receive_v1` —— 接收 `/gh` 指令(依赖 `im:message` 权限)。
- `card.action.trigger` —— 接收卡片按钮点击。
3. 在**事件与回调 → 加密策略**中,把 **Encrypt Key** 填入 `FEISHU_ENCRYPT_KEY`(WebHooker 会校验 `X-Lark-Signature`——timestamp + nonce + key + body 的 SHA-256——并解密加密回调),和/或把 **Verification Token** 填入 `FEISHU_VERIFICATION_TOKEN`。至少需要其中一个;都未设置时所有回调都会被拒绝。同一事件 id 只执行一次,飞书重试也不会重复执行。
4. `/gh login` 只能在与机器人的单聊(p2p)中使用;GitHub 用户需在同时显示双方账号的确认页上确认绑定。
### 所需权限
| 权限 | 用途 |
| ------------------------ | ------------------------------------------------- |
| `im:message` | 读取和发送单聊与群聊消息。 |
| `im:message:send_as_bot` | 以应用机器人身份发送消息(`im:message` 的替代)。 |
| `im:message:send` | 旧版发送消息权限(`im:message` 的替代)。 |
> [!NOTE]
> 不支持“自定义机器人”的群级 Webhook URL。WebHooker 统一使用**应用机器人**,以保持与 Discord、Telegram 一致的凭证管理、消息编辑、多群路由与入站指令能力。
## 自定义域名(可选)
要使用自定义域名替代 `*.workers.dev`:
1. 进入 Cloudflare Worker 设置
2. 添加自定义域名或路由
3. 更新 `BASE_URL` 以匹配
> [!NOTE]
> 本项目是一个 Cloudflare Worker,依赖 `wrangler.jsonc` 中声明的 KV 与 D1 绑定,无法作为独立的 Node/容器进程运行。Queues 绑定(`QUEUE`)可选——未绑定时 webhook 分发保持内联同步。