mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
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>
This commit is contained in:
1 parent
dbf162bf74
commit
978c53eeb3
163 files changed
+18459
-3607
No files matched your search
+11
-11
@@ -40,7 +40,7 @@ Creates a comment on an issue or pull request.
|
||||
| `issueNumber` | number | Yes | Issue or PR number |
|
||||
| `body` | string | Yes | Comment body (Markdown supported) |
|
||||
|
||||
**Response:** `200` with GitHub API response.
|
||||
**Response:** `200 { "ok": true }`.
|
||||
|
||||
### Merge Pull Request
|
||||
|
||||
@@ -68,7 +68,7 @@ Merges a pull request.
|
||||
| `pullNumber` | number | Yes | Pull request number |
|
||||
| `method` | string | No | `merge`, `squash`, or `rebase` (default: `squash`) |
|
||||
|
||||
**Response:** `200` with GitHub merge response.
|
||||
**Response:** `200 { "ok": true }`.
|
||||
|
||||
### Close Pull Request
|
||||
|
||||
@@ -94,7 +94,7 @@ Closes a pull request without merging.
|
||||
| `repo` | string | Yes | Repository name |
|
||||
| `pullNumber` | number | Yes | Pull request number |
|
||||
|
||||
**Response:** `200` with GitHub update response.
|
||||
**Response:** `200 { "ok": true }`.
|
||||
|
||||
### Add Reaction
|
||||
|
||||
@@ -102,7 +102,7 @@ Closes a pull request without merging.
|
||||
POST /api/react
|
||||
```
|
||||
|
||||
Adds an emoji reaction to an issue or comment.
|
||||
Adds an emoji reaction to an issue or pull request (not to a comment).
|
||||
|
||||
**Request Body:**
|
||||
|
||||
@@ -115,18 +115,18 @@ Adds an emoji reaction to an issue or comment.
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ------------- | ------ | -------- | ---------------------------- |
|
||||
| `owner` | string | Yes | Repository owner |
|
||||
| `repo` | string | Yes | Repository name |
|
||||
| `issueNumber` | number | Yes | Issue, PR, or comment number |
|
||||
| `reaction` | string | Yes | Reaction type (see below) |
|
||||
| Field | Type | Required | Description |
|
||||
| ------------- | ------ | -------- | ------------------------- |
|
||||
| `owner` | string | Yes | Repository owner |
|
||||
| `repo` | string | Yes | Repository name |
|
||||
| `issueNumber` | number | Yes | Issue or PR number |
|
||||
| `reaction` | string | Yes | Reaction type (see below) |
|
||||
|
||||
**Reaction Types:**
|
||||
|
||||
`+1`, `-1`, `laugh`, `confused`, `heart`, `hooray`, `rocket`, `eyes`
|
||||
|
||||
**Response:** `200` with GitHub reaction response.
|
||||
**Response:** `200 { "ok": true }`.
|
||||
|
||||
## Error Responses
|
||||
|
||||
|
||||
+42
-32
@@ -6,41 +6,51 @@ The console itself is served at `/admin`; its tabs are deep-linkable via the URL
|
||||
|
||||
## Endpoints
|
||||
|
||||
| Endpoint | Description |
|
||||
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `GET /admin` | Config console UI |
|
||||
| `GET /admin/login` | Start admin sign-in (GitHub OAuth) |
|
||||
| `GET /admin/logout` | Sign out and destroy the session |
|
||||
| `GET /admin/invite?token=…` | Accept a group invite (browser page) |
|
||||
| `GET /admin/api/me` | Current session, scope, groups, and roles |
|
||||
| `GET /admin/api/routes` | List routes (scoped to access) |
|
||||
| `PUT /admin/api/routes` | Replace routes (owner/admin per group) |
|
||||
| `GET /admin/api/groups` | List groups + the signed-in user's role in each |
|
||||
| `PUT /admin/api/groups` | Replace groups (super: all; owner: own only) |
|
||||
| `GET /admin/api/groups/:id/routes` | List a group's routes |
|
||||
| `PUT /admin/api/groups/:id/routes` | Replace a group's routes (owner/admin) |
|
||||
| `GET /admin/api/groups/:id/fragments` | List a group's named filter fragments |
|
||||
| `PUT /admin/api/groups/:id/fragments` | Replace a group's named filter fragments (owner/admin) |
|
||||
| `PUT /admin/api/groups/:id/rename` | Rename a group (owner); routes, webhook secret and invites follow (routes are moved before the group record is updated) |
|
||||
| `GET /admin/api/groups/:id/invites` | List pending invites (owner) |
|
||||
| `POST /admin/api/groups/:id/invites` | Create an invite link (owner) |
|
||||
| `DELETE /admin/api/invites/:token` | Revoke an invite (owner) |
|
||||
| `GET /admin/api/groups/:id/webhook` | Group webhook endpoint info (owner) |
|
||||
| `POST /admin/api/groups/:id/webhook/regenerate` | Generate/regenerate the group webhook secret (owner) |
|
||||
| `DELETE /admin/api/groups/:id/webhook` | Disable the group webhook ingress (owner) |
|
||||
| `GET /admin/api/logs` | Send logs (scoped to accessible routes) |
|
||||
| `GET /admin/api/logs/:id` | Single send-log entry (scoped) |
|
||||
| `GET /admin/api/audit` | Audit log (scoped to accessible groups) |
|
||||
| `GET /admin/api/metrics` | Delivery stats (totals, failure rate, per platform/event/status, recent failures); optional `?groupId=` scope; recent failures scoped to accessible groups for non-super |
|
||||
| `GET /admin/api/delivery/:deliveryId` | All send-log attempts for one delivery (group-scoped) |
|
||||
| `POST /admin/api/test-match` | Stateless filter dry-run — evaluate a filter node against a pasted JSON payload (no event is stored) |
|
||||
| Endpoint | Description |
|
||||
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `GET /admin` | Config console UI |
|
||||
| `GET /admin/login` | Start admin sign-in (GitHub OAuth) |
|
||||
| `GET /admin/logout` | Sign out and destroy the session |
|
||||
| `GET /admin/invite?token=…` | Accept a group invite (browser page) |
|
||||
| `GET /admin/api/me` | Current session, scope, groups, and roles |
|
||||
| `GET /admin/api/routes` | List routes (scoped to access) |
|
||||
| `PUT /admin/api/routes` | Replace routes (owner/admin per group) |
|
||||
| `GET /admin/api/groups` | List groups (each with its `revision`) + the signed-in user's role in each, plus the list `revision` |
|
||||
| `PUT /admin/api/groups` | Bulk write (legacy): super admins replace all groups, owners change/delete their own; only groups that differ are written |
|
||||
| `POST /admin/api/groups` | Create one group (super admins) — body `{ group }`; `409` when the id exists or was used recently |
|
||||
| `PUT /admin/api/groups/:id` | Update one group (owner) — body `{ group }`; `409` when its `revision` is stale |
|
||||
| `DELETE /admin/api/groups/:id` | Delete one group with its routes and fragments (owner) — query `revision`, `routesRevision` and `version` from the confirmation; `409` when anything changed since |
|
||||
| `GET /admin/api/groups/:id/routes` | List a group's routes, with the list's `revision`, the group `version` and `unreadable` |
|
||||
| `PUT /admin/api/groups/:id/routes` | Replace a group's routes (owner/admin) — `409` when the sent `revision` is stale |
|
||||
| `GET /admin/api/groups/:id/fragments` | List a group's named filter fragments, with the list's `revision` |
|
||||
| `PUT /admin/api/groups/:id/fragments` | Replace a group's named filter fragments (owner/admin) — body `{ fragments, revision? }`; `409` when the `revision` is stale |
|
||||
| `PUT /admin/api/groups/:id/rename` | Rename a group (owner) — body `{ newId, revision? }`; routes, fragments and history move in one transaction, the secret and invites stay with the group; the old id stays retired for a few days |
|
||||
| `GET /admin/api/groups/:id/invites` | List pending invites (owner) |
|
||||
| `POST /admin/api/groups/:id/invites` | Create an invite link (owner) — body `{ role, note? }` (`role` is `admin` or `viewer`) |
|
||||
| `DELETE /admin/api/invites/:token` | Revoke an invite (owner) |
|
||||
| `GET /admin/api/groups/:id/webhook` | Group webhook endpoint info (owner) |
|
||||
| `POST /admin/api/groups/:id/webhook/regenerate` | Generate/regenerate the group webhook secret (owner) |
|
||||
| `DELETE /admin/api/groups/:id/webhook` | Disable the group webhook ingress (owner) |
|
||||
| `GET /admin/api/logs` | Send logs of the accessible groups (filtered in SQL before the limit) |
|
||||
| `GET /admin/api/logs/:id` | Single send-log entry (scoped) |
|
||||
| `GET /admin/api/audit` | Audit log of the accessible groups (filtered in SQL before the limit) |
|
||||
| `GET /admin/api/metrics` | Delivery stats (totals, failure rate, per platform/event/status, recent failures); optional `?groupId=` scope; every aggregate is limited to the accessible groups |
|
||||
| `GET /admin/api/delivery/:deliveryId` | The attempts of one delivery that belong to the accessible groups; optional `?groupId=` (two groups' senders may use the same delivery id) |
|
||||
| `POST /admin/api/test-match` | Stateless filter dry-run — evaluate a filter node against a pasted JSON payload (no event is stored) |
|
||||
|
||||
## Validation
|
||||
|
||||
- `PUT /admin/api/routes` — Body `{ "routes": Route[] }`; validates each route (id pattern, unique id within its group, name, enabled, `groupId`, filters — empty only allowed for `fallback` routes — optional `discordRoleIds` (list of role id strings), and platform-aware targets: `target.channelId` for Discord, `target.chatId` for Telegram) and persists to D1 `d1_routes`. Returns `200 { ok, count }` or `400 { error }` / `401 { error }` / `403 { error }`. Unchanged routes skip the full validation. Route filters support the `field` type (a JSONPath `path` into `payload`, arrays expand so any element matches) and 12 `op` operators (`eq` default / `ne` / `contains` / `startsWith` / `endsWith` / `regex` / `gt` / `gte` / `lt` / `lte` / `in` / `exists`); a nested `ast` (`all` / `any` / `not`) takes precedence over `filters` when present.
|
||||
- `PUT /admin/api/groups` — Validates group ids, member roles (at least one `owner`), `providers` (`github` / `gitea`), and `installationId`.
|
||||
- `PUT /admin/api/routes` — Body `{ "routes": Route[] }`; validates each route (id pattern, unique id within its group, name, enabled, `groupId`, filters — an array, empty only for `fallback` routes or when a valid `ast` is present; patterns the matcher cannot compile — longer than 200 characters, or RE2-unsupported syntax such as backreferences or lookaround — are rejected; flat `filters` hold leaf conditions only (`all`/`any`/`not` belong in `ast`); `keyword` only supports the default `eq`; `exists` may omit `match` — optional `discordRoleIds` (at most 50 numeric Discord role ids), and platform-aware targets: `target.channelId` for Discord, `target.chatId` for Telegram/Feishu, with the id rules and duplicate-destination check in [Routes & Targets](../guide/routes)) and persists to D1 `d1_routes`, rewriting only the groups whose routes changed. A non-super admin pointing a target at a channel another group uses gets `403`. Returns `200 { ok, count }` or `400 { error }` / `401 { error }` / `403 { error }`. Unchanged routes skip the full validation. Route filters support the `field` type (a JSONPath `path` into `payload`, arrays expand so any element matches) and 12 `op` operators (`eq` default / `ne` / `contains` / `startsWith` / `endsWith` / `regex` / `gt` / `gte` / `lt` / `lte` / `in` / `exists`); a nested `ast` (`all` / `any` / `not`) takes precedence over `filters` when present.
|
||||
- `PUT /admin/api/groups` / `POST /admin/api/groups` / `PUT /admin/api/groups/:id` — Validate group ids, `members` (or legacy `adminIds`; a non-empty `members` list needs at least one `owner`), `forgeSources` (at most 20, `name` up to 50 characters, unique type + host), `providers` (`github` / `gitea` / `custom`), and `installationId`; unknown fields are dropped. The source-isolation fields `owners`, `installationId` and `isolated` are super-admin only: an owner's write keeps their stored values. New members' logins are resolved to GitHub user ids with the writer's token; the server-only fields (`instance`, the webhook secret, member user ids) can never be set by the client.
|
||||
- Every write re-checks the writer's role inside its transaction: a request authorized before the role was revoked is refused (`409` for route/fragment writes, `403` for group writes).
|
||||
- Optimistic concurrency — every list or group the API returns carries a `revision`. Send it back with the write (`group.revision`, or `revision` next to `routes` / `fragments` / `newId`, or the list `revision` of the bulk groups write) and the server refuses the write with `409` if the stored data changed since it was loaded, instead of overwriting the newer change. Writes without a `revision` are applied as before. In the bulk groups write, a group echoed back unedited is never written.
|
||||
- `PUT /admin/api/groups/:id/routes` — Optional `discardUnreadable: true` replaces stored routes that cannot be read (otherwise the save is refused while the group has any).
|
||||
- `PUT /admin/api/routes` — Optionally send `revisions` (the per-group map returned by `GET /admin/api/routes`): groups whose list comes back unedited are not written, groups the client never loaded are not touched, and edited groups must still be at their loaded revision (`409` otherwise). Each group is written in its own guarded transaction.
|
||||
- `PUT /admin/api/groups/:id/rename` — Optional `revision`; returns `{ ok, id, group, revision }` (the renamed group and its new revision). Ids starting with `inst-` or `u-` are reserved for super admins.
|
||||
- `DELETE /admin/api/groups/:id` — Requires `revision`, `routesRevision` and `version` as seen at confirmation (`400` when missing, `409` when the group, its routes or fragments changed, or when it has routes that cannot be read). Also revokes the group's invites and webhook secret, detaches its send logs and audit entries (they stay visible to super admins only), and retires the id for a few days so queued deliveries cannot reach a new group that reuses it.
|
||||
- `POST /admin/api/groups/:id/webhook/regenerate` — Returns `{ ok, url, secret, hasSecret }`; the secret is shown only in this response.
|
||||
- `POST /admin/api/test-match` — Body `{ "node": FilterNode | "filters": Filter[], "event"?: string, "payload": object }`; evaluates in memory and returns `{ matched, explanation }`. Nothing is persisted.
|
||||
- `GET/PUT /admin/api/groups/:id/fragments` — Named filter fragments (`{ id, groupId, name, node }`) stored in D1 `d1_fragments`; the editor inlines a fragment's `node` into a route's `ast` on insert (the matcher never resolves fragment references). `PUT` replaces the group's fragments and returns `200 { ok, count }`.
|
||||
- Limits: at most 200 routes and 100 groups per instance.
|
||||
- `GET/PUT /admin/api/groups/:id/fragments` — Named filter fragments (`{ id, groupId, name, node }`) stored in D1 `d1_fragments`; the editor inlines a fragment's `node` into a route's `ast` on insert (the matcher never resolves fragment references). `PUT` replaces the group's fragments (at most 200) and returns `200 { ok, count }`.
|
||||
- Limits: one save accepts at most 200 routes, 200 fragments per group, and 100 groups in the bulk groups write.
|
||||
|
||||
Schemas: [Routes & Targets](../guide/routes), [Groups & Access Control](../guide/groups).
|
||||
+14
-5
@@ -42,12 +42,21 @@ GitHub redirects here after authorization. Exchanges the code for an access toke
|
||||
| `code` | Authorization code |
|
||||
| `state` | State parameter for CSRF protection |
|
||||
|
||||
A sign-in started in the browser (`GET /auth/github`) must come back with the `wh_oauth_state` cookie that start set; otherwise the callback answers `400 Invalid or expired state`.
|
||||
|
||||
**Response:**
|
||||
|
||||
- **Browser flow** (`Accept: text/html`): sets an admin session cookie, then redirects to the `redirect` target. Users without admin access are redirected to `/admin?error=forbidden`.
|
||||
- **JSON flow**: returns `{ "userId": "...", "login": "...", "redirectTo": "..." }`.
|
||||
- **Discord link flow** (started with a pending `discordUserId`): links the Discord user to this GitHub account, returning `{ "ok": true, "discordUserId": "...", "login": "..." }` — or a success page in the browser.
|
||||
- **Telegram link flow** (started with a pending `telegramUserId`): links the Telegram user to this GitHub account, returns `{ "ok": true, "telegramUserId": "...", "login": "..." }`, and sends a confirmation message to the pending `telegramChatId`.
|
||||
- **Bot account link** (started by `/gh login` on Discord, Telegram or Feishu): nothing is linked yet. The callback answers with an HTML confirmation page that names both the GitHub account and the chat account; the link is written only when the GitHub user confirms it there.
|
||||
|
||||
### Confirm Bot Account Link
|
||||
|
||||
```
|
||||
POST /auth/github/link
|
||||
```
|
||||
|
||||
Submitted by the confirmation page (form field `nonce`, valid for 10 minutes and usable once). Links the chat account to the GitHub account and answers with an HTML result page; an unknown, expired or already used `nonce` gets `400` ("link expired").
|
||||
|
||||
### Revoke Token
|
||||
|
||||
@@ -55,7 +64,7 @@ GitHub redirects here after authorization. Exchanges the code for an access toke
|
||||
DELETE /auth/token/:userId
|
||||
```
|
||||
|
||||
Removes the stored OAuth token for a user.
|
||||
Removes the stored OAuth token for a user (your own, or any user's for a super admin). The revocation is recorded in D1, so the token stops working everywhere at once, even where KV has not caught up yet.
|
||||
|
||||
**Response:**
|
||||
|
||||
@@ -74,11 +83,11 @@ Tokens are stored in KV with key pattern `token:{userId}`:
|
||||
"userId": "12345",
|
||||
"accessToken": "gho_...",
|
||||
"expiresAt": 1735689600000,
|
||||
"refreshToken": "..."
|
||||
"live": true
|
||||
}
|
||||
```
|
||||
|
||||
`expiresAt` is a Unix timestamp in milliseconds. KV entries expire at 90% of the token's lifetime (minimum 60 seconds). A reverse index `token-reverse:{sha256 of token}` maps the access token back to its user id so Bearer-authenticated endpoints can resolve the caller. Discord users linked to a GitHub account are stored in the D1 `discord_links` table; Telegram users in the D1 `telegram_links` table.
|
||||
`expiresAt` is a Unix timestamp in milliseconds. A stored token is used for 10 hours; the KV entry expires after 9 hours (90%). Tokens are not refreshed — after that, sign in (or run `/gh login`) again. `live` marks a token whose "current token" record is kept in D1: signing in again or signing out invalidates the previous token everywhere at once. A reverse index `token-reverse:{sha256 of token}` maps the access token back to its user id so Bearer-authenticated endpoints can resolve the caller. Discord users linked to a GitHub account are stored in the D1 `discord_links` table; Telegram users in the D1 `telegram_links` table.
|
||||
|
||||
## Using Tokens
|
||||
|
||||
|
||||
+16
-10
@@ -17,9 +17,11 @@ https://your-worker.workers.dev
|
||||
| `POST` | `/webhook/:groupId` | Per-group secret | Per-group webhook ingress (only that group's routes fire) |
|
||||
| `POST` | `/discord/interactions` | Ed25519 signature | Discord interactions (slash commands, buttons, modals) |
|
||||
| `POST` | `/telegram/webhook` | Secret token | Telegram updates (bot `/gh` commands) |
|
||||
| `POST` | `/feishu/webhook` | Feishu signature | Feishu events (bot `/gh` commands, card buttons) |
|
||||
| `GET` | `/api/richheader` | None | Open Graph page for the Telegram avatar link-preview card |
|
||||
| `GET` | `/auth/github` | None | Start GitHub OAuth flow |
|
||||
| `GET` | `/auth/github/callback` | None | OAuth callback |
|
||||
| `POST` | `/auth/github/link` | Link nonce | Confirm a bot account link (from the confirmation page) |
|
||||
| `GET` | `/auth/github/install` | Admin session | Post-install choice page: bind the installation to a group |
|
||||
| `POST` | `/auth/github/install/bind` | Admin session | Provision the chosen installation binding |
|
||||
| `DELETE` | `/auth/token/:userId` | Admin session | Revoke user token |
|
||||
@@ -74,27 +76,31 @@ Accepts GitHub webhook payloads. Requires valid `X-Hub-Signature-256` header.
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true
|
||||
"ok": true,
|
||||
"requestId": "…"
|
||||
}
|
||||
```
|
||||
|
||||
When `X-GitHub-Delivery` is present and the same delivery was already processed within the last 5 minutes, the worker responds `200 { "ok": true, "duplicate": true }` without re-dispatching.
|
||||
`requestId` is the correlation id written to the worker's logs. With inline dispatch (no queue), an event whose targets failed permanently is still answered `200`, with `"failed": true` added.
|
||||
|
||||
When `X-GitHub-Delivery` is present and the same delivery was already accepted, the worker responds `200 { "ok": true, "duplicate": true }` without re-dispatching; while the first copy is still being processed, a redelivery gets `503` so the sender retries later.
|
||||
|
||||
**Error Responses:**
|
||||
|
||||
| Status | Body | Cause |
|
||||
| ------ | -------------------------------- | -------------------------------------- |
|
||||
| `401` | `{"error": "Invalid signature"}` | Signature verification failed |
|
||||
| `400` | `{"error": "Invalid event"}` | Missing event header or malformed body |
|
||||
| `413` | `{"error": "Request too large"}` | Body exceeds 1MB limit |
|
||||
| Status | Body | Cause |
|
||||
| ------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `401` | `{"error": "Invalid signature"}` | Signature verification failed |
|
||||
| `400` | `{"error": "Invalid event"}` | Missing event header or malformed body |
|
||||
| `413` | `{"error": "Request too large"}` | Body exceeds 1MB limit |
|
||||
| `503` | `{"error": …}` | Not accepted yet — the queue rejected the event, a target failed transiently (inline dispatch), the same delivery is still being processed, or storage failed; the sender should redeliver |
|
||||
|
||||
### Per-Group Webhook (`POST /webhook/:groupId`)
|
||||
|
||||
Verifies the payload against the **group's** secret (KV `tenant:{groupId}`, generated from the console — Webhook endpoint panel) instead of the global secrets, and dispatches only into that group's routes. Works for GitHub (`X-Hub-Signature-256`), Gitea (`X-Gitea-Signature`) and custom (`X-WebHooker-Signature`) senders. Returns `404` when the group does not exist or has no secret configured.
|
||||
Verifies the payload against the **group's** secret (stored with the group in D1, generated from the console — Webhook endpoint panel) instead of the global secrets, and dispatches only into that group's routes. Works for GitHub (`X-Hub-Signature-256`), Gitea (`X-Gitea-Signature`) and custom (`X-WebHooker-Signature`) senders. Returns `404` when the group does not exist or has no secret configured, and `503` when the group's stored configuration cannot be read.
|
||||
|
||||
### Custom Webhooks
|
||||
|
||||
Any JSON payload signed with `X-WebHooker-Signature: sha256=<hex>` (HMAC-SHA256 of the raw body, group or global secret) becomes a `custom` event. Route it with a route whose filter is `event: custom`. Optional `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` headers enable replay protection (signature over `{timestamp}.{nonce}.{body}`, ±5 min window, nonce dedup). Payload schema: see [Configuration → Custom webhooks](../guide/ingress.md#custom-webhooks).
|
||||
Any JSON object signed with `X-WebHooker-Signature: sha256=<hex>` (HMAC-SHA256 of the raw body, group or global secret) becomes a `custom` event. Route it with a route whose filter is `event: custom`. Optional `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` headers enable replay protection (signature over `{timestamp}.{nonce}.{body}`, ±5 min window, nonce dedup). Payload schema: see [Configuration → Custom webhooks](../guide/ingress.md#custom-webhooks).
|
||||
|
||||
### GitHub App Installation Events
|
||||
|
||||
@@ -109,7 +115,7 @@ The primary flow is the App's **Setup URL** — set it to `{BASE_URL}/auth/githu
|
||||
|
||||
## Error Format
|
||||
|
||||
All error responses follow the format:
|
||||
Error responses of the webhook, admin, OAuth and action endpoints follow the format below; the bot callbacks (`/discord/interactions`, `/telegram/webhook`, `/feishu/webhook`) answer errors with a plain-text body:
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -25,22 +25,24 @@ app/ # Vue 3 UI (Nuxt app dir)
|
||||
server/ # Nitro server (H3 handlers in server/routes/)
|
||||
├── routes/ # /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
|
||||
│ # /auth/github*, /admin/{login,logout,invite,api/**}, /api/{comment,merge,close,react,richheader}
|
||||
├── tasks/ # Scheduled (cron */5): discord-sync, telegram-sync, audit-prune
|
||||
├── tasks/ # Scheduled (cron */5): discord-sync, telegram-sync, audit-prune, storage-prune
|
||||
├── error-handler.ts # JSON error handler
|
||||
└── lib/
|
||||
├── types.ts # Env, Config, Route, Filter, Group, WebhookEvent, NeutralMessage
|
||||
├── config.ts # Loads routes from KV (returns [] if unset), builds Config from env
|
||||
├── config.ts # Binds the D1 config store, loads routes/groups (fresh or cached), builds Config from env
|
||||
├── core/
|
||||
│ └── dispatch.ts # Platform-neutral dispatch: match routes → formatEvent → getDriver().send/edit
|
||||
├── events/ # Provider-agnostic route matching
|
||||
│ └── match.ts # matchRoute, eventOwners, extractBranch, keyword filtering
|
||||
│ ├── match.ts # matchRoute, eventOwners
|
||||
│ └── filter-ast.ts # filter evaluation (flat filters + all/any/not AST), extractBranch, keyword search, RE2 patterns
|
||||
├── providers/ # Forge webhook providers (verify + parse/normalize)
|
||||
│ ├── types.ts # Provider interface (matches/verify/parse)
|
||||
│ ├── index.ts # detectProvider() registry (github, gitea, custom)
|
||||
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
||||
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature (normalized payloads)
|
||||
├── formatters/ # Platform-neutral formatters (produce NeutralMessage)
|
||||
│ ├── index.ts # formatEvent: 28-event switch + custom → NeutralMessage + re-exports
|
||||
│ ├── index.ts # formatEvent: builds the context, finds the formatter in the registry → NeutralMessage
|
||||
│ ├── registry.ts # eventFormatters[]: event names → formatter
|
||||
│ ├── colors.ts # GITHUB_COLORS + WORKFLOW_CONCLUSION_EMOJI
|
||||
│ ├── helpers.ts # emojiPrefix, T, buildMessage, commitLink/branchLink/tagLink
|
||||
│ └── *.ts # push, pull-request, issues, comments, workflow, release, create, repo,
|
||||
@@ -129,8 +131,8 @@ platform limits.
|
||||
1. Add the event type to `GITHUB_COLORS` in `server/lib/formatters/colors.ts` (if new color needed)
|
||||
2. Add action labels to the locale dictionaries in `server/lib/lib/locales/en.ts` and `server/lib/lib/locales/zh.ts` (if new actions)
|
||||
3. Create a `formatEventType` function in `server/lib/formatters/`
|
||||
4. Add the case to the `formatEvent` switch statement in `server/lib/formatters/index.ts`
|
||||
5. Update `extractBranch` in `server/lib/events/match.ts` if the event has branch info
|
||||
4. Register it in `eventFormatters` in `server/lib/formatters/registry.ts` (`{ events: ["your_event"], format: (c) => … }`)
|
||||
5. Update `extractBranch` in `server/lib/events/filter-ast.ts` if the event has branch info
|
||||
6. Add the event to the documentation in `docs/events/supported.md` and `docs/zh/events/supported.md`
|
||||
7. Add the event to the README (`README.md` and `README.zh.md`) event tables and the GitHub App event subscription list
|
||||
8. Subscribe to the event in your GitHub App settings
|
||||
|
||||
+19
-18
@@ -40,15 +40,16 @@ WebHooker supports 28 GitHub webhook event types, each with a dedicated formatte
|
||||
|
||||
Each event type uses a distinct color in the Discord embed (from `server/lib/formatters/colors.ts`):
|
||||
|
||||
| Color | Events |
|
||||
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Green (`#2da44e`) | push, PR opened / ready for review, issue opened, workflow success, release published, check success, review approved, deployment success, member added, milestone closed, discussion answered |
|
||||
| Red (`#f85149`) | PR closed, issue closed, workflow failure, release deleted, delete, check failure, review changes requested, deployment failure, member removed, code scanning / dependabot critical & high |
|
||||
| Purple (`#8957e5`) | PR merged, label, discussion |
|
||||
| Blue (`#1f6feb`) | PR (other actions), issue reopened, fork, milestone opened |
|
||||
| Yellow (`#d29922`) | workflow (queued/running/other), release prerelease, star, check (other), deployment pending, code scanning / dependabot medium |
|
||||
| Gray (`#6e7681`) | issue comment, commit comment, discussion comment |
|
||||
| Gray (`#8b949e`) | review commented, repository, code scanning / dependabot low, default |
|
||||
| Color | Events |
|
||||
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Green (`#2da44e`) | PR opened / ready for review, issue opened, workflow success, release published, check success, review approved, deployment success, member added, milestone closed, discussion answered |
|
||||
| Green (`#2ea44f`) | push |
|
||||
| Red (`#f85149`) | PR closed, issue closed, workflow failure, release deleted, delete, check failure, review changes requested, deployment failure, member removed, code scanning / dependabot critical & high |
|
||||
| Purple (`#8957e5`) | PR merged, label, discussion |
|
||||
| Blue (`#1f6feb`) | PR (other actions), issue reopened, fork, milestone opened |
|
||||
| Yellow (`#d29922`) | workflow (queued/running/other), release prerelease, star, check (other), deployment pending, code scanning / dependabot medium |
|
||||
| Gray (`#6e7681`) | issue comment, commit comment, discussion comment |
|
||||
| Gray (`#8b949e`) | review commented, repository, code scanning / dependabot low, default |
|
||||
|
||||
## Generic Fallback
|
||||
|
||||
@@ -60,7 +61,7 @@ Any event type without a dedicated formatter falls through to the generic format
|
||||
|
||||
## In-Place Message Updates
|
||||
|
||||
`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` 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. Each edit re-renders the whole message from the newest event. Check suites, deployments (and their statuses), issue comments, pull request reviews and review comments are edited in place the same way. Supported on Discord (`editMessage`), Telegram (`editMessageText` / `editMessageCaption`) and Feishu. `check_run` tracks by check suite (or app) + 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, while same-named checks of different workflows or apps keep separate messages. An older phase never overwrites a newer one, and a deleted comment or dismissed review stays shown as such.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -68,11 +69,11 @@ Any event type without a dedicated formatter falls through to the generic format
|
||||
|
||||
See the [Filter Tutorial](../guide/filters) for a hands-on guide with worked examples.
|
||||
|
||||
| Filter | Works With |
|
||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `event` | All events |
|
||||
| `repo` | All events |
|
||||
| `actor` | All events |
|
||||
| `action` | Events with `action` field in payload |
|
||||
| `branch` | push, pull_request, pull_request_review, pull_request_review_comment, create, delete, workflow_run, workflow_job, check_suite, deployment, code_scanning_alert |
|
||||
| `keyword` | All events (searches full payload body) |
|
||||
| Filter | Works With |
|
||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `event` | All events |
|
||||
| `repo` | All events |
|
||||
| `actor` | All events |
|
||||
| `action` | Events with `action` field in payload |
|
||||
| `branch` | push, pull_request, pull_request_review, pull_request_review_comment, create, delete, workflow_run, workflow_job, check_run, check_suite, deployment, deployment_status, code_scanning_alert |
|
||||
| `keyword` | All events (searches full payload body) |
|
||||
+17
-9
@@ -1,23 +1,27 @@
|
||||
# Bot Commands
|
||||
|
||||
After [linking your GitHub account](#linking-your-account), you can act on GitHub **as yourself** from both Discord and Telegram — comments are posted with your own OAuth token and GitHub enforces permission. If GitHub rejects an action (e.g. editing someone else's comment) the bot tells you so.
|
||||
After [linking your GitHub account](#linking-your-account), you can act on GitHub **as yourself** from Discord, Telegram and Feishu — comments are posted with your own OAuth token and GitHub enforces permission. If GitHub rejects an action (e.g. editing someone else's comment) the bot tells you so.
|
||||
|
||||
## Linking Your Account
|
||||
|
||||
You must link your GitHub account once before using any command:
|
||||
You must link your GitHub account before using any command. The authorization lasts 10 hours; after that, run `/gh login` again:
|
||||
|
||||
| Platform | Command | Effect |
|
||||
| -------- | --------------------------------- | ---------------------------------------------------------------- |
|
||||
| Discord | `/gh login` | Returns an ephemeral OAuth link to authorize your GitHub account |
|
||||
| Discord | `/gh logout` | Unlinks your GitHub account |
|
||||
| Telegram | `/gh login` (reply to a message) | Returns an OAuth link |
|
||||
| Telegram | `/gh login` (private chat only) | Returns an OAuth link |
|
||||
| Telegram | `/gh logout` (reply to a message) | Unlinks your GitHub account |
|
||||
|
||||
The link is stored server-side (KV) and mapped to your Discord/Telegram user id in D1.
|
||||
The link is stored server-side (KV) and mapped to your Discord/Telegram/Feishu user id in D1.
|
||||
|
||||
After authorizing on GitHub you see a confirmation page naming **both** accounts (your GitHub login and the chat account that requested the link); nothing is linked until you confirm. If you did not start the login yourself — e.g. someone forwarded you their link — just close the page. On Telegram and Feishu, `/gh login` is only answered in the private chat with the bot, so authorization links are never posted to a group.
|
||||
|
||||
Commands run once per platform event: a redelivered Telegram update, a retried Feishu event or a replayed Discord interaction does not repeat a comment, merge or close. A command that failed before reaching GitHub (for example a storage error) is given back to the platform and runs again on its redelivery; once a command may have reached GitHub it is never repeated — if the bot's reply then fails, check GitHub before sending the command again.
|
||||
|
||||
## Discord
|
||||
|
||||
Discord commands are **slash commands** and **message context-menu commands**, synced by the scheduled trigger (every 5 minutes): per-guild for instant availability, and globally (24h dedup, ~1h propagation). All replies are ephemeral (only you see them).
|
||||
Discord commands are **slash commands** and **message context-menu commands**, synced by the scheduled trigger (every 5 minutes): per-guild for instant availability (at most 30 Discord API calls per run, so a bot in many guilds catches up over several runs), and globally (~1h propagation). Both are registered again when the command definitions change, and the global set at least daily. All replies are ephemeral (only you see them).
|
||||
|
||||
### Comment on an issue / PR
|
||||
|
||||
@@ -32,11 +36,11 @@ Two equivalent ways:
|
||||
/gh comment del link:<comment url> url must contain #issuecomment-<id>
|
||||
```
|
||||
|
||||
For `edit` / `del`, copy the specific comment link on GitHub (comment ⋯ menu → **Copy link**). `add` / `edit` open a modal to enter/adjust the comment body (prefilled for edit).
|
||||
For `edit` / `del`, copy the specific comment link on GitHub (comment ⋯ menu → **Copy link**). `add` / `edit` open a modal to enter/adjust the comment body (prefilled for edit, up to Discord's 4000-character limit; longer comments must be edited on GitHub so nothing is cut off). Saving an edit is refused when the comment changed on GitHub after the modal opened — reopen it to start from the current text. The body is posted as typed (indentation and line breaks kept). Only `https://github.com/...` links are accepted.
|
||||
|
||||
### Merge / close a PR
|
||||
|
||||
Notifications for open PRs include **Merge / Close** buttons (labels follow the group's message language):
|
||||
Notifications for open PRs on github.com include **Merge / Close** buttons (labels follow the group's message language; Gitea and other forges get no buttons, since the actions call the GitHub API):
|
||||
|
||||
- Clicking a button merges (squash) or closes the PR as your linked GitHub account; GitHub enforces permission.
|
||||
- On success the buttons are removed from the notification and the result is shown in an ephemeral reply.
|
||||
@@ -54,9 +58,13 @@ Notifications for open PRs include **Merge / Close** buttons (labels follow the
|
||||
|
||||
Telegram `/gh` commands work by **replying to a notification message**:
|
||||
|
||||
- `/gh login` — link your GitHub account (returns an OAuth link)
|
||||
- `/gh login` — link your GitHub account (private chat with the bot only; returns an OAuth link)
|
||||
- `/gh logout` — unlink
|
||||
- `/gh comment <text>` — reply to an issue/PR notification to comment as yourself
|
||||
- `/gh merge` / `/gh close` — reply to a PR notification to merge/close it
|
||||
|
||||
The target issue/PR is parsed from the message you reply to (the notification embed links). Commands arrive via the Telegram webhook (`POST /telegram/webhook`, optionally verified with `TELEGRAM_WEBHOOK_SECRET`).
|
||||
The target issue/PR is parsed from the message you reply to (the notification embed links). In groups, the `/gh@YourBot …` form is accepted too (commands addressed to another bot are ignored). Comment text keeps its line breaks and indentation. Commands arrive via the Telegram webhook (`POST /telegram/webhook`), which always verifies the secret token — `TELEGRAM_WEBHOOK_SECRET`, or one derived from `TELEGRAM_TOKEN` when unset.
|
||||
|
||||
## Feishu
|
||||
|
||||
Feishu `/gh` commands are messages that start with `/gh` (after any @mention of the bot): `/gh login` (private chat only), `/gh logout`, `/gh comment <PR/Issue link> <text>`, `/gh merge <PR link>`, `/gh close <PR link>`; cards also carry **Merge** / **Close** buttons. Messages that merely mention `/gh` elsewhere are not commands. See [Feishu Bot Setup](./deployment#feishu-bot-setup) for the event subscription.
|
||||
+34
-23
@@ -27,29 +27,40 @@ WebHooker requires several secrets to function. For local development, store the
|
||||
| `FEISHU_APP_ID` | Feishu app ID (from the app Credentials page) — required for Feishu routes |
|
||||
| `FEISHU_APP_SECRET` | Feishu app secret — required for Feishu routes |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Inbound Feishu commands and card buttons (`POST /feishu/webhook`) require
|
||||
> `FEISHU_ENCRYPT_KEY` and/or `FEISHU_VERIFICATION_TOKEN` (the app's **Events &
|
||||
> Callbacks → Encryption Strategy** values). Without either, the endpoint refuses
|
||||
> every callback, since an unauthenticated request could act as any linked user.
|
||||
|
||||
<!-- separate the two alerts (MD028) -->
|
||||
|
||||
> [!NOTE]
|
||||
> `GITHUB_APP_ID` and `GITHUB_PRIVATE_KEY` (PKCS#8 PEM) are used by the GitHub App
|
||||
> **install flow** (`/auth/github/install`) to resolve the installing account's login
|
||||
> via an App JWT. They are optional — when unset, the install page still works but
|
||||
> shows an anonymous `inst-{installationId}` group without the account name. The
|
||||
> OAuth flow itself only needs `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`.
|
||||
> **install flow** (`/auth/github/install`) to resolve the installation's account via
|
||||
> an App JWT — which is also how the flow verifies that the signed-in user may manage
|
||||
> the installation. Without them only super admins can bind installations. The OAuth
|
||||
> flow itself only needs `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`; it requests the
|
||||
> `repo` and `read:org` scopes (the latter to check organization admin rights).
|
||||
|
||||
### Optional Secrets
|
||||
|
||||
| Variable | Description | Default |
|
||||
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
|
||||
| `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 |
|
||||
| `TELEGRAM_WEBHOOK_SECRET` | Secret token for `POST /telegram/webhook` verification (X-Telegram-Bot-Api-Secret-Token) | Disabled (no verification) |
|
||||
| `TELEGRAM_RICH_HEADER_HOST` | Base URL of an external rich-header service; when unset, the built-in `GET /api/richheader` serves the Telegram avatar card | Built-in `/api/richheader` |
|
||||
| `BASE_URL` | Public URL for OAuth callbacks | `http://localhost:8787` |
|
||||
| `ADMIN_USER_IDS` | Comma-separated GitHub user IDs (or logins) allowed to access the Web UI | Disabled |
|
||||
| `DEBUG_MODE` | Local development only: exact `true` bypasses all `/admin` authentication and grants full access | Disabled |
|
||||
| `ALLOW_SELF_SIGNUP` | When enabled (`1`/`true`), GitHub users without any group access get a personal group on first login instead of `403` | Disabled |
|
||||
| `AUDIT_RETENTION_DAYS` | Audit-log retention in days for the scheduled cleanup | `90` |
|
||||
| `NUXT_PUBLIC_DOCS_URL` | Docs site URL used by the landing page (client-side runtime config) | Landing page defaults |
|
||||
| `NUXT_PUBLIC_REPO_URL` | GitHub repo URL used by the landing page | Landing page defaults |
|
||||
| `NUXT_PUBLIC_LEGAL_CONTACT` | Contact shown on `/terms` and `/privacy` | Unset → placeholder text |
|
||||
| Variable | Description | Default |
|
||||
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
|
||||
| `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 |
|
||||
| `TELEGRAM_WEBHOOK_SECRET` | Secret token for `POST /telegram/webhook` verification (X-Telegram-Bot-Api-Secret-Token) | Derived from `TELEGRAM_TOKEN` |
|
||||
| `FEISHU_ENCRYPT_KEY` | Feishu event Encrypt Key: verifies `X-Lark-Signature` and decrypts encrypted callbacks | Unset |
|
||||
| `FEISHU_VERIFICATION_TOKEN` | Feishu event Verification Token, compared with the token in every callback | Unset |
|
||||
| `TELEGRAM_RICH_HEADER_HOST` | Base URL of an external rich-header service; when unset, the built-in `GET /api/richheader` serves the Telegram avatar card | Built-in `/api/richheader` |
|
||||
| `BASE_URL` | Public URL of the worker, for OAuth callbacks and the Telegram webhook sync | Unset — required in production |
|
||||
| `ADMIN_USER_IDS` | Comma-separated GitHub user IDs (or logins) allowed to access the Web UI; prefer numeric ids — a login is bound to the first account that signs in with it | Disabled |
|
||||
| `DEBUG_MODE` | Local development only: exact `true` bypasses all `/admin` authentication and grants full access | Disabled |
|
||||
| `ALLOW_SELF_SIGNUP` | When enabled (`1`/`true`), GitHub users without any group access get an isolated personal group on first login instead of `403` | Disabled |
|
||||
| `AUDIT_RETENTION_DAYS` | Audit-log retention in days for the scheduled cleanup | `90` |
|
||||
| `NUXT_PUBLIC_DOCS_URL` | Docs site URL used by the landing page (client-side runtime config) | Landing page defaults |
|
||||
| `NUXT_PUBLIC_REPO_URL` | GitHub repo URL used by the landing page | Landing page defaults |
|
||||
| `NUXT_PUBLIC_LEGAL_CONTACT` | Contact shown on `/terms` and `/privacy` | Unset → placeholder text |
|
||||
|
||||
## Web UI
|
||||
|
||||
@@ -57,7 +68,7 @@ WebHooker ships with a built-in config console at `/admin` for managing routes,
|
||||
|
||||
### Setup
|
||||
|
||||
1. Configure `ADMIN_USER_IDS` with the GitHub user IDs allowed to manage everything. Logins are also accepted, e.g. `ADMIN_USER_IDS=12345,RhenCloud`. If unset, the console is disabled (unless `ALLOW_SELF_SIGNUP` is enabled).
|
||||
1. Configure `ADMIN_USER_IDS` with the GitHub user IDs allowed to manage everything. Logins are also accepted, e.g. `ADMIN_USER_IDS=12345,RhenCloud`, but numeric ids are safer: GitHub logins can be renamed and re-registered, so a login is bound to the first account that signs in with it. If unset, there are no super admins: members of a group still reach the console for their groups, and `ALLOW_SELF_SIGNUP` gives other users a personal group.
|
||||
2. Open `/admin` and sign in with GitHub.
|
||||
3. Users without any access get `403`, except when `ALLOW_SELF_SIGNUP=1` (they receive a personal group) or when they follow a group [invite link](./groups#invites).
|
||||
|
||||
@@ -67,7 +78,7 @@ The console is served as an SPA at `/admin`; its tabs are deep-linkable via the
|
||||
|
||||
Destructive actions — deleting routes, groups, filter conditions, fragments, targets or forge hosts, removing members, revoking invites, disabling a group's webhook — ask for confirmation in an in-app dialog (empty, never-filled rows are removed directly). The route and group editors ignore clicks on the backdrop so unsaved input is never lost; close them with Cancel, ✕ or <kbd>Esc</kbd>.
|
||||
|
||||
All management endpoints (`/admin/api/*`) are documented in the [Admin API](../api/admin). Saved routes and groups are persisted to D1 (`d1_routes` / `d1_groups`) immediately, the KV cache is invalidated and the config cache is refreshed so the webhook pipeline picks them up on the next run.
|
||||
All management endpoints (`/admin/api/*`) are documented in the [Admin API](../api/admin). Saved routes and groups are persisted to D1 (`d1_routes` / `d1_groups`) immediately; webhook ingress and the queue consumer read the configuration fresh, so the next event already uses them.
|
||||
|
||||
## Filter Types
|
||||
|
||||
@@ -89,11 +100,11 @@ See the [Filter Tutorial](./filters) for a hands-on guide with worked examples.
|
||||
- Set `"exclude": true` on any filter to invert it (NOT logic)
|
||||
- Every filter type supports the same pattern forms: plain text, `*`/`?` **globs** (`*` = any run, `?` = one character), and `/regular expression/` — all case-insensitive
|
||||
- Field filters (`event`/`repo`/`actor`/`action`/`branch`/`field`) glob-match the whole value; `keyword` globs and regexes search anywhere in the payload; plain `keyword` text is a substring search
|
||||
- Every filter except `keyword` accepts an `op` operator — `eq` (default, classic behaviour), `ne`, `contains`, `startsWith`, `endsWith`, `regex`, `gt`, `gte`, `lt`, `lte`, `in`, `exists` — see the [Filter Tutorial](./filters#operators)
|
||||
- Every filter except `keyword` (which only supports the default `eq`) accepts an `op` operator — `eq` (default, classic behaviour), `ne`, `contains`, `startsWith`, `endsWith`, `regex`, `gt`, `gte`, `lt`, `lte`, `in`, `exists` — see the [Filter Tutorial](./filters#operators)
|
||||
- `field` filters use a dot-separated JSONPath `path` into the payload; arrays are expanded so any matching element satisfies the filter
|
||||
- Routes may nest filters in an `ast` node (`all` / `any` / `not`) instead of a flat `filters` list; `ast` takes precedence when present
|
||||
- Patterns longer than 200 characters are not compiled as glob/regex; an invalid `//`-wrapped regex matches nothing
|
||||
- `branch` filter works for push, pull_request, pull_request_review, pull_request_review_comment, create/delete, workflow_run, workflow_job, check_suite, deployment, and code_scanning_alert events
|
||||
- Globs and regexes run on the RE2 engine (linear time). A pattern the matcher cannot compile — longer than 200 characters, or using syntax RE2 lacks such as backreferences or lookaround — is rejected when saved; one stored before makes its route [unreadable](./routes#unreadable-routes) instead of silently never matching
|
||||
- `branch` filter works for push, pull_request, pull_request_review, pull_request_review_comment, create/delete, workflow_run, workflow_job, check_run, check_suite, deployment, deployment_status, and code_scanning_alert events
|
||||
|
||||
### Match Values
|
||||
|
||||
|
||||
+30
-18
@@ -2,6 +2,8 @@
|
||||
|
||||
## Cloudflare Setup
|
||||
|
||||
`wrangler.jsonc` ships with the maintainers' `account_id` and resource ids. Replace `account_id` with your own Cloudflare account id (`bunx wrangler whoami`), or remove the field to deploy to the account you are logged in with, and replace the ids in the steps below.
|
||||
|
||||
### 1. Create KV Namespace
|
||||
|
||||
```bash
|
||||
@@ -32,7 +34,8 @@ bunx wrangler secret put DISCORD_PUBLIC_KEY # Discord app public key (Develope
|
||||
bunx wrangler secret put TELEGRAM_TOKEN # Telegram bot token (BotFather) — required for Telegram routes
|
||||
bunx wrangler secret put FEISHU_APP_ID # Feishu app ID — required for Feishu routes
|
||||
bunx wrangler secret put FEISHU_APP_SECRET # Feishu app secret — required for Feishu routes
|
||||
bunx wrangler secret put ADMIN_USER_IDS # comma-separated GitHub IDs/logins allowed into the Web UI
|
||||
bunx wrangler secret put ADMIN_USER_IDS # comma-separated GitHub user ids allowed into the Web UI (numeric ids recommended)
|
||||
bunx wrangler secret put BASE_URL # public URL of the worker — OAuth callbacks and the Telegram webhook sync need it
|
||||
```
|
||||
|
||||
::: tip Target channels are configured per route
|
||||
@@ -40,7 +43,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 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`.
|
||||
`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. Without them only super admins can bind installations — the flow cannot resolve the installation's account, so it cannot verify that a signed-in user manages it — 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.
|
||||
@@ -72,10 +75,10 @@ bun run db:migrate:prod # apply migrations to the remote D1 database
|
||||
bun run db:migrate # apply migrations to the local (Miniflare) database
|
||||
```
|
||||
|
||||
The `db:migrate` scripts run `wrangler d1 migrations apply webhooker` (see `package.json`), which applies each SQL file in `migrations/` and records applied versions in the `d1_migrations` table.
|
||||
The `db:migrate` scripts run `wrangler d1 migrations apply webhooker` (see `package.json`), which applies each SQL file in `migrations/` and records applied versions in the `d1_migrations` table. `bun run deploy` runs `db:migrate:prod` before deploying, so migrations added later are applied on the next deploy; already-applied ones are skipped, and a failed migration stops the deploy.
|
||||
|
||||
::: tip Databases previously migrated with `d1 execute`
|
||||
If the database already has these tables/columns (e.g. previously migrated with `wrangler d1 execute --file`), the `d1_migrations` tracking table may be missing and `db:migrate:prod` will try to re-run every migration. The `ALTER TABLE ... ADD COLUMN` statements in `0002_log_detail.sql` then fail because the columns already exist. In that case run the files directly instead:
|
||||
If the database already has these tables/columns (e.g. previously migrated with `wrangler d1 execute --file`), the `d1_migrations` tracking table may be missing and `db:migrate:prod` will try to re-run every migration. The `ALTER TABLE ... ADD COLUMN` statements in `0002_log_detail.sql` then fail because the columns already exist. In that case apply the files your database does not have yet directly (the `ALTER TABLE ... ADD COLUMN` files fail when run twice, so skip those already applied):
|
||||
|
||||
```bash
|
||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0001_init.sql
|
||||
@@ -89,8 +92,11 @@ bunx wrangler d1 execute webhooker --remote --file ./migrations/0008_storage_d1.
|
||||
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
|
||||
```
|
||||
|
||||
Such a database has no migration history, so `bun run deploy` (which runs `db:migrate:prod` first) would try every migration again and stop. Deploy it with `bunx wrangler deploy`, and apply later migration files the same way.
|
||||
|
||||
:::
|
||||
|
||||
### 4. Create R2 Bucket (Optional)
|
||||
@@ -101,25 +107,30 @@ The `PAYLOAD` binding parks oversized webhook payloads in R2 (`webhooker-payload
|
||||
bunx wrangler r2 bucket create webhooker-payloads
|
||||
```
|
||||
|
||||
The bucket is already declared in `wrangler.jsonc` (`r2_buckets`), so no binding change is needed.
|
||||
Then uncomment the `r2_buckets` block in `wrangler.jsonc` (it ships commented out); without the binding, oversized payloads stay in KV.
|
||||
|
||||
### 5. Create Queues (Optional)
|
||||
|
||||
The `QUEUE` binding routes webhook delivery through Cloudflare Queues (async dispatch with retry backoff and a dead-letter queue). Skip this step to keep dispatch inline (synchronous).
|
||||
The `QUEUE` binding routes webhook delivery through Cloudflare Queues (async dispatch with retry backoff and a dead-letter queue). To keep dispatch inline (synchronous) instead, remove or comment out the `queues` block in `wrangler.jsonc`; while it is there, both queues must exist.
|
||||
|
||||
```bash
|
||||
bunx wrangler queues create webhooker-delivery
|
||||
bunx wrangler queues create webhooker-delivery-dlq
|
||||
```
|
||||
|
||||
The queues are already declared in `wrangler.jsonc` (`queues.producers` / `queues.consumers`), so no binding change is needed. The `webhooker-delivery` consumer retries retryable failures with exponential backoff (5s/30s/2m/10m) up to `max_retries`, after which the message is moved to `webhooker-delivery-dlq` and marked dead.
|
||||
The queues are already declared in `wrangler.jsonc` (`queues.producers` / `queues.consumers`), so no binding change is needed. The `webhooker-delivery` consumer retries retryable failures (5xx, 429, network, rate-limit exhaustion, Feishu token errors) with exponential backoff (5s/30s/2m/10m) up to `max_retries`, after which the message is moved to `webhooker-delivery-dlq` and marked dead. Retries are per target: targets that already succeeded — or failed permanently — are recorded and not attempted again, so one bad target never cancels the others' retries and a retry does not resend a recorded target (a send whose record could not be written may be repeated). Each consumer invocation takes at most 3 messages and shares a budget of 12 minutes and 20 target sends across them, because the Workers Free limits (50 D1 queries, 50 subrequests) apply per invocation: a message the budget did not reach is retried, and a delivery with more targets than the budget continues in a new queue message. A delivery whose every target was handled still ends as `failed` if any target failed permanently along the way. A delivery is taken with a 5-minute lease, so two consumers never dispatch the same delivery at once.
|
||||
|
||||
> [!NOTE]
|
||||
> R2 has no per-object TTL. Parked payloads are deleted after dispatch, and the scheduled `storage-prune` task removes orphans older than five days; you may also add a bucket [lifecycle rule](https://developers.cloudflare.com/r2/buckets/object-lifecycles/) for the `webhooks/` prefix.
|
||||
|
||||
### 6. Deploy
|
||||
|
||||
```bash
|
||||
bunx wrangler deploy
|
||||
bun run deploy # applies pending D1 migrations, then runs wrangler deploy
|
||||
```
|
||||
|
||||
Run from a terminal, wrangler asks for confirmation before applying pending migrations; in CI it proceeds. If you deploy through Cloudflare's Git integration (Workers Builds), set its deploy command to `bun run deploy` so migrations are applied there too.
|
||||
|
||||
Your worker is now live at `https://webhooker.<your-subdomain>.workers.dev`.
|
||||
|
||||
### 7. Configure GitHub Webhook
|
||||
@@ -151,7 +162,7 @@ Your worker is now live at `https://webhooker.<your-subdomain>.workers.dev`.
|
||||
- **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 and to authenticate API enrichment (workflow job lists, build logs) for private repositories (see the tip above).
|
||||
5. Generate a private key and set `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY`: the install flow needs them to verify that the installing user manages the installation (without them only super admins can bind installations), and API enrichment (workflow job lists, build logs) uses them for private repositories (see the tip above).
|
||||
|
||||
### 2. Install App
|
||||
|
||||
@@ -186,20 +197,20 @@ Messages are sent via the Discord **REST API**, so pushing works with just `DISC
|
||||
2. Set the **Interactions Endpoint URL** to `https://your-domain/discord/interactions`.
|
||||
3. Every interaction request is verified with Ed25519 signatures (`X-Signature-Ed25519` over `X-Signature-Timestamp + body`).
|
||||
|
||||
The `/gh` slash command and the `GitHub: 添加/编辑/删除评论` message commands are synced by the scheduled trigger (every 5 minutes): per-guild for instant availability, plus a global registration (24h dedup, ~1h propagation). The bot never connects to the Discord Gateway, so it shows as **offline** — messaging is unaffected (always REST).
|
||||
The `/gh` slash command and the `GitHub: 添加/编辑/删除评论` message commands are synced by the scheduled trigger (every 5 minutes): per-guild for instant availability (at most 30 API calls per run), plus a global registration (~1h propagation); both are registered again when the command definitions change. The bot never connects to the Discord Gateway, so it shows as **offline** — messaging is unaffected (always REST).
|
||||
|
||||
Users run `/gh login` to link their GitHub account and can then comment on issues/PRs as themselves. See the [Bot Commands](/guide/commands) page for the full command reference.
|
||||
|
||||
## Telegram Bot Setup
|
||||
|
||||
1. Create a bot with [@BotFather](https://t.me/BotFather) and copy its token to `TELEGRAM_TOKEN`.
|
||||
2. (Optional) Set `TELEGRAM_WEBHOOK_SECRET`; the webhook registration passes it to Telegram as `secret_token`, and `POST /telegram/webhook` verifies it with a timing-safe compare.
|
||||
3. The worker syncs the webhook from the scheduled trigger (`setWebhook` to `{BASE_URL}/telegram/webhook`), so no manual `setWebhook` call is needed — just make sure `BASE_URL` is set.
|
||||
4. Add the bot to a group (or enable topics) and route events to `chatId` / `topicId` in the route config.
|
||||
2. (Optional) Set `TELEGRAM_WEBHOOK_SECRET`; the webhook registration passes it to Telegram as `secret_token`, and `POST /telegram/webhook` verifies it with a timing-safe compare. When unset, a secret derived from `TELEGRAM_TOKEN` is used instead, so the endpoint is never left unauthenticated (the next scheduled sync re-registers the webhook with it).
|
||||
3. The worker syncs the webhook from the scheduled trigger (`setWebhook` to `{BASE_URL}/telegram/webhook`, only when the registration changed and once a day), so no manual `setWebhook` call is needed — just make sure `BASE_URL` is set.
|
||||
4. Add the bot to a group (or enable topics) and route events to `chatId` / `topicId` in the route config. Use the numeric chat id (e.g. `-1001234567890`); `@username` targets are not accepted.
|
||||
|
||||
In Telegram, `/gh` commands (`/gh login`, `/gh logout`, `/gh comment <text>`, `/gh merge`, `/gh close`) work by replying to a notification message — see the [Bot Commands](/guide/commands) page.
|
||||
In Telegram, `/gh` commands (`/gh login`, `/gh logout`, `/gh comment <text>`, `/gh merge`, `/gh close`) work by replying to a notification message — see the [Bot Commands](/guide/commands) page. `/gh login` only works in the private chat with the bot, and the GitHub user confirms the binding on a page that names both accounts.
|
||||
|
||||
Avatars are rendered as a link-preview card using the built-in `GET /api/richheader` (overridable with `TELEGRAM_RICH_HEADER_HOST`).
|
||||
Avatars are rendered as a link-preview card using the built-in `GET /api/richheader` (overridable with `TELEGRAM_RICH_HEADER_HOST`; without `BASE_URL` the avatar image itself is the preview). Messages are always text messages, so in-place updates keep the full 4096-character budget.
|
||||
|
||||
## Feishu Bot Setup
|
||||
|
||||
@@ -210,9 +221,9 @@ Avatars are rendered as a link-preview card using the built-in `GET /api/richhea
|
||||
- `im:message:send_as_bot` (send messages as an app)
|
||||
- `im:message:send` (historical version)
|
||||
4. In **Bot** tab, turn on the bot capability. Add the bot to the target group chat (or create a new group) and copy the **Chat ID** from the group settings.
|
||||
5. In WebHooker `/admin`, create or edit a route and add a target with `platform: "feishu"`, `chatId` set to the Feishu **Chat ID**, and optional `topicId` for a topic inside the chat.
|
||||
5. In WebHooker `/admin`, create or edit a route and add a target with `platform: "feishu"` and `chatId` set to the Feishu **Chat ID** (`oc_…`); Feishu targets have no topic.
|
||||
|
||||
WebHooker uses the app-level credentials (`FEISHU_APP_ID` / `FEISHU_APP_SECRET`) to request a `tenant_access_token`, caches it until expiry, and sends messages as an interactive card (`interactive` message type). The same token is used to edit messages in place for `workflow_run` / `check_run` progress updates.
|
||||
WebHooker uses the app-level credentials (`FEISHU_APP_ID` / `FEISHU_APP_SECRET`) to request a `tenant_access_token`, caches it per app (in memory and KV) until shortly before it expires, drops it as soon as Feishu refuses it, and sends messages as an interactive card (`interactive` message type). The same token is used to edit messages in place for `workflow_run` / `check_run` progress updates.
|
||||
|
||||
### Inbound: commands & buttons
|
||||
|
||||
@@ -230,7 +241,8 @@ To enable inbound:
|
||||
2. Subscribe to the events:
|
||||
- `im.message.receive_v1` — receive `/gh` commands (requires the `im:message` scope).
|
||||
- `card.action.trigger` — receive button clicks on cards.
|
||||
3. In **Credentials & Basic Info**, set the **App Secret** (already used for `FEISHU_APP_SECRET`) — it also signs the inbound callback via the `X-Lark-Signature` header, and WebHooker verifies it.
|
||||
3. In **Events & Callbacks → Encryption Strategy**, copy the **Encrypt Key** to `FEISHU_ENCRYPT_KEY` (WebHooker then verifies `X-Lark-Signature` — SHA-256 of timestamp + nonce + key + body — and decrypts encrypted callbacks) and/or the **Verification Token** to `FEISHU_VERIFICATION_TOKEN`. At least one is required; without them every callback is refused. Each event id runs once, even when Feishu retries it.
|
||||
4. `/gh login` only works in the private (p2p) chat with the bot; the GitHub user confirms the binding on a page that names both accounts.
|
||||
|
||||
### Required permissions
|
||||
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@ Branch deletions via `git push --delete` arrive as push events with `deleted: tr
|
||||
|
||||
## How do I point a group at its own webhook endpoint?
|
||||
|
||||
See [Per-group endpoint](./ingress#per-group-endpoint) — generate a secret from the group's **Webhook endpoint** panel (owner role), then use `POST /webhook/{groupId}` with the group secret.
|
||||
See [Per-group endpoint](./ingress#per-group-endpoint-post-webhook-groupid) — generate a secret from the group's **Webhook endpoint** panel (owner role), then use `POST /webhook/{groupId}` with the group secret.
|
||||
|
||||
## Can I run this outside Cloudflare Workers?
|
||||
|
||||
@@ -38,4 +38,4 @@ No — the worker requires the KV and D1 bindings declared in `wrangler.jsonc` a
|
||||
|
||||
## Where is data stored?
|
||||
|
||||
Configuration lives in D1 (`d1_routes`/`d1_groups`, with KV as a cache); webhook dedup, delivery state and message-update tracking also live in D1 with KV fallback; send/audit logs and platform↔GitHub links live in D1. R2 optionally parks oversized payloads. See [Storage Layout](./storage#storage-decisions).
|
||||
Configuration lives in D1 (`d1_routes`/`d1_groups`, cached in memory for at most 60 seconds); webhook dedup, delivery state and message-update tracking also live in D1 with KV fallback; send/audit logs and platform↔GitHub links live in D1. R2 optionally parks oversized payloads. See [Storage Layout](./storage#storage-decisions).
|
||||
+26
-21
@@ -124,16 +124,17 @@ This fires when a pull request is opened or reopened (and not on merge/close/edi
|
||||
|
||||
Matches the branch involved in the event. What counts as "the branch" depends on the event type:
|
||||
|
||||
| Event | Branch extracted |
|
||||
| --------------------------- | ------------------------------------------- |
|
||||
| `push` | The branch that was pushed to |
|
||||
| `pull_request` (and review) | The pull request's **head** (source) branch |
|
||||
| `create` / `delete` | The created/deleted branch or tag |
|
||||
| `workflow_run` | The `head_branch` the workflow ran on |
|
||||
| `workflow_job` | The `head_branch` the job ran on |
|
||||
| `check_suite` | The `head_branch` of the check suite |
|
||||
| `deployment` | The deployment ref (strips `refs/heads/`) |
|
||||
| `code_scanning_alert` | The branch the alert belongs to |
|
||||
| Event | Branch extracted |
|
||||
| ---------------------------------- | ------------------------------------------------------------------------------------ |
|
||||
| `push` | The branch that was pushed to |
|
||||
| `pull_request` (and review) | The pull request's **head** (source) branch |
|
||||
| `create` / `delete` | The created/deleted branch or tag |
|
||||
| `workflow_run` | The `head_branch` the workflow ran on |
|
||||
| `workflow_job` | The `head_branch` the job ran on |
|
||||
| `check_run` | The `head_branch` of the run's check suite |
|
||||
| `check_suite` | The `head_branch` of the check suite |
|
||||
| `deployment` / `deployment_status` | The deployment ref (`deployment.ref`, strips a leading `refs/heads/`) |
|
||||
| `code_scanning_alert` | The alert's ref, without a leading `refs/heads/` (use `main`, not `refs/heads/main`) |
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -179,8 +180,9 @@ Fires when the payload contains `deploy` anywhere. Because the payload is lowerc
|
||||
|
||||
Behavior details:
|
||||
|
||||
- Patterns longer than 200 characters are **not** compiled as glob/regex and fall back to plain matching.
|
||||
- A `//`-wrapped pattern that is not a valid regex matches **nothing** (the filter stays false) rather than erroring.
|
||||
- Patterns longer than 200 characters cannot be compiled as glob/regex; such patterns are rejected when saved.
|
||||
- Globs and regular expressions run on the RE2 engine, whose matching time is linear in the input — no pattern can stall the worker. RE2 syntax has no backreferences (`\1`) or lookaround (`(?=…)`, `(?<!…)`); the console and API reject such patterns.
|
||||
- A `//`-wrapped pattern that is not a valid regex is rejected when saved.
|
||||
- To search for text that is a glob or regex special character (e.g. `v1.2.3`), rely on the plain-text form — a pattern without `*`, `?`, or `//` wrapping matches literally.
|
||||
- The search covers the **entire** payload: commit messages, PR titles and bodies, labels, refs, even repository and sender names.
|
||||
|
||||
@@ -221,7 +223,7 @@ Field filters (and every filter type except `keyword`) accept an `op` to change
|
||||
| `gt` / `gte` | Numeric greater-than / greater-or-equal |
|
||||
| `lt` / `lte` | Numeric less-than / less-or-equal |
|
||||
| `in` | Value equals any of the listed patterns |
|
||||
| `exists` | The field is present (non-null); `match` is ignored |
|
||||
| `exists` | The field is present (non-null); `match` may be omitted |
|
||||
|
||||
```json
|
||||
{ "type": "field", "path": "pull_request.commits", "op": "gt", "match": "1" }
|
||||
@@ -239,6 +241,9 @@ A route can use a nested `ast` to combine filters with explicit grouping instead
|
||||
{
|
||||
"id": "grouped",
|
||||
"name": "Grouped",
|
||||
"enabled": true,
|
||||
"groupId": "eng",
|
||||
"filters": [],
|
||||
"ast": {
|
||||
"all": [
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
@@ -250,11 +255,11 @@ A route can use a nested `ast` to combine filters with explicit grouping instead
|
||||
}
|
||||
]
|
||||
},
|
||||
"targets": [{ "channelId": "..." }]
|
||||
"targets": [{ "platform": "discord", "channelId": "..." }]
|
||||
}
|
||||
```
|
||||
|
||||
When `ast` is present it takes precedence over `filters`. The admin console's route editor builds `ast` visually (all/any/not groups), shows a live explanation of the tree, and can test it against a pasted JSON payload via the **Test match** panel.
|
||||
When `ast` is present it takes precedence over `filters`; the route still carries a `filters` array (it may be empty). The admin console's route editor builds `ast` visually (all/any/not groups), shows a live explanation of the tree, and can test it against a pasted JSON payload via the **Test match** panel.
|
||||
|
||||
Values, field paths and the test event use searchable dropdowns. Suggestions come from GitHub's and Gitea's webhook definitions — events, the actions of the events the route filters on, common payload paths and their known values — each shown as its English key with a description in the console language; search matches the key first, then the English or Chinese description. Anything outside the list can still be typed and is validated before it is added; only values that can never match are rejected (an event name with spaces, a branch with characters git forbids, invalid regex syntax, a non-number for a comparison operator, …). Repository and actor values stay free-form because custom webhooks may carry any string. Text that is typed but not added with <kbd>Enter</kbd> blocks saving, fragment saving and test runs instead of being added or dropped silently. Several values can be typed or pasted at once, separated by commas or new lines; a `/regex/` keeps its own commas, and with the **matches regex** (`regex`) operator only new lines separate values (a raw pattern such as `^v{1,3}` may contain commas). Suggestions follow the operator: the substring operators compare text literally, so a glob suggestion becomes the text it implies (`release/*` → `release/` for **starts with**, `*[bot]` → `[bot]` for **ends with**), **matches regex** offers each suggestion as the escaped, anchored pattern it means (`^dependabot\[bot\]$`, `^release/`), and comparison operators get no suggestions. Switching between **equals** / **not equals** / **in** and **matches regex** rewrites `/x/` ↔ `x` in the values already added — both forms compile to the same regular expression, so the condition keeps matching exactly the same. Other values stay as typed (literal, glob and substring comparisons differ from regular expressions on line breaks and Unicode case folding), and values that can never match under the new operator are flagged. Arrays are expanded along a `field` path, but a path that **ends** on an array (e.g. `commits.modified`) is compared as a whole — match one of its elements with `contains`; the editor switches to `contains` when such a suggested path is picked.
|
||||
|
||||
@@ -275,13 +280,13 @@ Forward pull request activity, but ignore bot authors and draft PRs, to a `#prs`
|
||||
"filters": [
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
{ "type": "actor", "match": "dependabot[bot]", "exclude": true },
|
||||
{ "type": "keyword", "match": "\"draft\": true", "exclude": true }
|
||||
{ "type": "field", "path": "pull_request.draft", "match": "true", "exclude": true }
|
||||
],
|
||||
"target": { "channelId": "111111111111111111" }
|
||||
"targets": [{ "platform": "discord", "channelId": "111111111111111111" }]
|
||||
}
|
||||
```
|
||||
|
||||
The `"draft": true` pattern matches the `draft` field that GitHub includes in pull request payloads; combined with `exclude: true` it filters out draft PRs.
|
||||
The `field` filter reads `pull_request.draft` from the payload; combined with `exclude: true` it filters out draft PRs.
|
||||
|
||||
## Worked Example 2: Release-only channel
|
||||
|
||||
@@ -298,7 +303,7 @@ Forward only published releases from a specific repo:
|
||||
{ "type": "action", "match": "published" },
|
||||
{ "type": "repo", "match": "myorg/backend" }
|
||||
],
|
||||
"target": { "channelId": "222222222222222222" }
|
||||
"targets": [{ "platform": "discord", "channelId": "222222222222222222" }]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -317,14 +322,14 @@ Forward workflow runs that ended in failure on any branch, to a `#ci` channel:
|
||||
{ "type": "action", "match": "completed" },
|
||||
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
||||
],
|
||||
"target": { "channelId": "333333333333333333" }
|
||||
"targets": [{ "platform": "discord", "channelId": "333333333333333333" }]
|
||||
}
|
||||
```
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Wildcards are globs, not regex.** `repo: "myorg/*"` matches any repo under `myorg` (and `myorg/sub/backend`), but `repo: "myorg/.*"` matches literally. Use `//` wrapping for regex: `"/myorg\/.*/"`.
|
||||
- **A `//`-wrapped invalid regex never matches.** Unlike plain text, an unwrapped invalid pattern is matched literally — wrap patterns only when they are real regular expressions.
|
||||
- **A `//`-wrapped invalid regex is rejected.** The console and API refuse it when saved; a route stored with one before is reported as [unreadable](./routes#unreadable-routes) and its group's deliveries retry until it is fixed. Unlike `//`-wrapped text, an unwrapped pattern is matched literally — wrap patterns only when they are real regular expressions.
|
||||
- **An `action` filter on an action-less event never matches.** Check the event has an `action` field first (see [Filter Compatibility](../events/supported#filter-compatibility)).
|
||||
- **`branch` on an event without a branch never matches.** A `branch` filter on an `issues` event will always be false. Use `keyword` if you need branch-like matching there.
|
||||
- **`keyword` searches everything.** Because it scans the whole payload, a pattern like `"fix"` can match commit messages, issue titles, _and_ repository names. Be as specific as possible.
|
||||
|
||||
@@ -33,12 +33,12 @@ GITHUB_CLIENT_ID=your-client-id
|
||||
GITHUB_CLIENT_SECRET=your-client-secret
|
||||
DISCORD_TOKEN=your-bot-token
|
||||
DISCORD_PUBLIC_KEY=your-public-key
|
||||
ADMIN_USER_IDS=your-github-id,your-github-login
|
||||
ADMIN_USER_IDS=your-github-id
|
||||
BASE_URL=http://localhost:8787
|
||||
```
|
||||
|
||||
::: tip
|
||||
`GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` are optional and only used by the App install flow to resolve the installing account's login (the OAuth flow only needs the client ID/secret). Target channels are set per route in the Web UI, so no `DISCORD_CHANNEL_ID` is needed. To enable `/gh` commands locally, copy the **Public Key** from the Developer Portal into `DISCORD_PUBLIC_KEY` and set the Interactions Endpoint URL to `http://localhost:8787/discord/interactions`.
|
||||
`GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` are only needed for the GitHub App install flow and API enrichment: without them only super admins can bind installations, because the flow cannot verify that a signed-in user manages the installation (the OAuth flow itself only needs the client ID/secret). Target channels are set per route in the Web UI, so no `DISCORD_CHANNEL_ID` is needed. To enable `/gh` commands locally, copy the **Public Key** from the Developer Portal into `DISCORD_PUBLIC_KEY` and set the Interactions Endpoint URL to `http://localhost:8787/discord/interactions`.
|
||||
:::
|
||||
|
||||
::: warning
|
||||
@@ -48,10 +48,11 @@ BASE_URL=http://localhost:8787
|
||||
### 2. Start Dev Server
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
bun run db:migrate # first run: apply the D1 migrations to the local database
|
||||
bun run cf:dev # build, then serve the worker with wrangler dev (Miniflare)
|
||||
```
|
||||
|
||||
This starts a local Miniflare environment at `http://localhost:8787`.
|
||||
This serves the built worker at `http://localhost:8787`. Without the migrations the worker refuses to serve (`D1 migrations are incomplete`). For UI work, `bun run dev` starts the Nuxt dev server with HMR instead (`http://localhost:3000`; queue messages have no consumer there).
|
||||
|
||||
### 3. Verify
|
||||
|
||||
@@ -66,7 +67,7 @@ curl http://localhost:8787/health
|
||||
| ---------------------- | ------------------------------------------- |
|
||||
| `bun run dev` | Start Nuxt dev server (HMR) |
|
||||
| `bun run build` | Production build (cloudflare_module preset) |
|
||||
| `bun run deploy` | Deploy to Cloudflare |
|
||||
| `bun run deploy` | Apply pending D1 migrations and deploy |
|
||||
| `bun run typecheck` | TypeScript type checking |
|
||||
| `bun run lint` | ESLint |
|
||||
| `bun run lint:md` | Markdownlint |
|
||||
|
||||
+33
-18
@@ -1,6 +1,6 @@
|
||||
# Groups & Access Control
|
||||
|
||||
Routes belong to groups. Groups scope admin access and can restrict which events flow into them. They are stored in D1 (`d1_groups`, seeded from the legacy KV `config:groups` key on first load), managed via the [Web UI](./configuration#web-ui) or the [Admin API](../api/admin). At most **100 groups** can be saved per instance.
|
||||
Routes belong to groups. Groups scope admin access and can restrict which events flow into them. They are stored in D1 (`d1_groups`, seeded from the legacy KV `config:groups` key on first load), managed via the [Web UI](./configuration#web-ui) or the [Admin API](../api/admin). The bulk groups write accepts at most **100 groups** per save.
|
||||
|
||||
## Group Schema
|
||||
|
||||
@@ -20,19 +20,22 @@ Routes belong to groups. Groups scope admin access and can restrict which events
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | string | Yes | Lowercase id (`a-z0-9`, `-`); referenced by each route's `groupId`. Editable: renaming a group re-points its routes, per-group webhook secret and pending invites |
|
||||
| `name` | string | Yes | Human-readable group name |
|
||||
| `members` | object[] | No | `{ login, role }` entries; role is `owner`, `admin`, or `viewer` |
|
||||
| `adminIds` | string[] | No | Deprecated legacy field; treated as `members` with role `owner` when present |
|
||||
| `owners` | string[] | No | Org/user logins whose events are accepted into this group; empty = all |
|
||||
| `providers` | string[] | No | Source platforms allowed into this group (`github`, `gitea`); empty = all |
|
||||
| `installationId` | number | No | GitHub App installation id bound to this group; only that installation's events are accepted (empty = all) |
|
||||
| `emoji` | boolean | No | Whether to include emoji in this group's messages (default `true`) |
|
||||
| `forgeSources` | object[] | No | Forge hosts: `{ host, type, name? }` entries (`type` is `github` or `gitea`, `name` is an optional display label) that label this group's message footers; empty = no label |
|
||||
| `lang` | string | No | Message language for every route in this group (e.g. `en`, `zh`; custom via KV `i18n:<lang>`) — see [Message Language](./i18n) — defaults to `en` |
|
||||
| `logTarget` | object | No | Webhook log channel: a Discord `{ platform, channelId, threadId? }` or Telegram `{ platform, chatId, topicId? }` target that receives a summary of every webhook the group's routes dispatch |
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | string | Yes | Lowercase id (`a-z0-9`, `-`); referenced by each route's `groupId`. Editable: renaming re-points its routes, fragments, history, webhook secret and pending invites; a deleted or renamed id stays retired for a few days |
|
||||
| `name` | string | Yes | Human-readable group name |
|
||||
| `members` | object[] | Yes¹ | `{ login, role }` entries; role is `owner`, `admin`, or `viewer`. Each entry is bound to a GitHub user id by the server (resolved when the member is added, or at their first sign-in); a bound entry matches only that account, even after the login changes hands |
|
||||
| `adminIds` | string[] | No | Deprecated legacy field; treated as `members` with role `owner` when present |
|
||||
| `owners` | string[] | No | Org/user logins whose events are accepted into this group; empty = all |
|
||||
| `providers` | string[] | No | Source platforms allowed into this group (`github`, `gitea`, `custom`); empty = all |
|
||||
| `installationId` | number | No | GitHub App installation id bound to this group; only that installation's events are accepted (empty = all). Super-admin only (set by the verified install flow) |
|
||||
| `isolated` | boolean | No | Isolated groups (self sign-up personal groups) only receive events from their own `/webhook/{groupId}` ingress until a super admin binds a source (`installationId` or `owners`). Super-admin only |
|
||||
| `emoji` | boolean | No | Whether to include emoji in this group's messages (default `true`) |
|
||||
| `forgeSources` | object[] | No | Forge hosts: `{ host, type, name? }` entries (`type` is `github` or `gitea`, `name` is an optional display label) that label this group's message footers; empty = no label |
|
||||
| `lang` | string | No | Message language for every route in this group (e.g. `en`, `zh`; custom via KV `i18n:<lang>`) — see [Message Language](./i18n) — defaults to `en` |
|
||||
| `logTarget` | object | No | Webhook log channel: a Discord `{ platform, channelId, threadId? }`, Telegram `{ platform, chatId, topicId? }` or Feishu `{ platform, chatId }` target that receives a summary of every webhook the group's routes dispatch |
|
||||
|
||||
¹ `members` or the legacy `adminIds` must be present. A non-empty `members` list needs at least one `owner`; an empty list is allowed (only super admins manage such a group). `forgeSources` takes at most 20 entries, each `name` at most 50 characters, and no two entries with the same type and host.
|
||||
|
||||
## Roles
|
||||
|
||||
@@ -46,16 +49,21 @@ Every group member has one of three roles. Super admins (`ADMIN_USER_IDS`) alway
|
||||
|
||||
## Access Model
|
||||
|
||||
- **Super admins** (`ADMIN_USER_IDS`) see and edit every group and all routes; only they can edit a group's `owners` list.
|
||||
- **Super admins** (`ADMIN_USER_IDS`) see and edit every group and all routes; only they can edit a group's source-isolation fields (`owners`, `installationId`, `isolated`) — an owner's save keeps the stored values.
|
||||
- **Owners** manage their group's routes, members, invites, name, id, `emoji`, and `providers`. They cannot remove the last owner or demote themselves when no other owner remains.
|
||||
- **Admins** edit routes inside their groups and view logs; **viewers** get a read-only console.
|
||||
- Group admin endpoints operate on a single group at a time via `/admin/api/groups/:id/routes`; `groupId` is forced from the path parameter.
|
||||
- The `owners` list restricts which event actors (sender logins) the group's routes will dispatch at all.
|
||||
- The `owners` list restricts the group's routes to events of repositories owned by these users or organizations (`repository.owner.login` / `organization.login`); to filter by who triggered an event, use an `actor` filter.
|
||||
- A route whose group no longer exists never fires.
|
||||
- Every group write is a single-row, compare-and-swap update: two people editing different groups never overwrite each other, and an edit made from a stale copy of the same group is refused (`409`, the console reloads) instead of reverting the newer change. Route and fragment lists work the same way per group.
|
||||
- Roles are checked again inside the write itself: a request authorized before the writer lost their role (or was removed) is refused when it commits.
|
||||
- Deleting a group requires the confirmation snapshot the console shows (`revision`, `routesRevision` and the group `version`): anything added or changed after the confirmation — a route, a fragment, a setting — makes the delete fail with `409` instead of being deleted unseen. A group with routes that cannot be read is not deleted.
|
||||
- Delivery targets are owned: a non-super admin cannot point routes or the log channel at a channel/chat another group already delivers to, unless they may edit that group's routes too (`403`). A channel that two groups already shared before keeps working only where it is already used.
|
||||
- The `providers` list restricts which forge's events (`github`, `gitea`) the group's routes will dispatch. This lets you keep GitHub and Gitea groups separate even when org/user names collide.
|
||||
|
||||
## Webhook Log Channel
|
||||
|
||||
A group may set `logTarget` to a Discord channel/thread or Telegram chat/topic. Whenever the group's routes dispatch a webhook, a single summary message is sent there: the event type/action, the repo, the delivery id, and one line per route×target with an ✅/❌ outcome (including the error for failed sends; at most the first 10 lines are listed, the rest is summarized as `+N`). The message is green when every dispatch succeeded and red when any failed. The summary uses the group's message language. Log messages are sent best-effort and are not themselves recorded in the D1 send log.
|
||||
A group may set `logTarget` to a Discord channel/thread, Telegram chat/topic or Feishu chat. Whenever the group's routes dispatch a webhook, a single summary message is sent there: the event type/action, the repo, the delivery id, and one line per route×target with an ✅/❌ outcome (including the error for failed sends; targets finished by an earlier attempt are listed as such; at most the first 10 lines are listed, the rest is summarized as `+N`). The message is green when every dispatch succeeded, red when any failed, and gray when earlier attempts' outcomes are not known. A retried delivery with the same outcome does not send the summary again. The summary uses the group's message language. Log messages are sent best-effort and are not themselves recorded in the D1 send log.
|
||||
|
||||
## Forge Source Label
|
||||
|
||||
@@ -79,8 +87,15 @@ The label is independent of `Group.emoji` and follows every message that group d
|
||||
|
||||
## Invites
|
||||
|
||||
Owners (and super admins) can create single-use invite links valid for 7 days from the group's _Members_ panel. Accepting an invite adds the user with the invited role (`admin` or `viewer` — never `owner`); an existing `viewer` is upgraded to `admin`. Invites are stored in KV as `invite:{token}`.
|
||||
Owners (and super admins) can create single-use invite links valid for 7 days from the group's _Members_ panel. Accepting an invite adds the user with the invited role (`admin` or `viewer` — never `owner`); an existing `viewer` is upgraded to `admin`. Invites are stored in KV as `invite:{token}` for their whole lifetime; the "used" record commits in the same D1 transaction as the membership change, so a link can be used only once even when two people open it at the same time.
|
||||
|
||||
- An invite belongs to the group instance that issued it: a group later created under the same id never accepts it.
|
||||
- Revoking an invite is recorded in D1 and takes effect at once, even where KV still has the invite.
|
||||
- An invite stops working when its issuer is no longer an owner of the group.
|
||||
- If the login is still on a member entry bound to another GitHub account (the former holder of that login), accepting fails with a conflict and the invite stays usable; an owner first removes the stale entry.
|
||||
|
||||
## Self Sign-up
|
||||
|
||||
With `ALLOW_SELF_SIGNUP=1`, a GitHub user who has no group access gets a personal group (`u-{userId}`, owned by them) on first login instead of a `403`. This is the entry point for a fully self-service SaaS install; disable it to keep the console invite-only.
|
||||
|
||||
Personal groups are **isolated** (groups named `u-<digits>` created before the flag existed count as isolated too, unless a super admin sets `isolated: false`): the operator's global `POST /webhook` endpoint never dispatches to them, so a self-service user cannot receive other tenants' events by adding a catch-all route. They receive events through their own [per-group webhook](./ingress) — or from a GitHub App installation they prove they administer (the install flow checks it with the user's own GitHub token).
|
||||
+7
-5
@@ -8,17 +8,19 @@ Set `Group.lang` (e.g. `"zh"`) to choose the message language for every route in
|
||||
|
||||
## Custom Overrides
|
||||
|
||||
Translation overrides are merged from KV under the key `i18n:<lang>` as a flat JSON object of key → text. Any key from the built-in dictionaries (en/zh) can be overridden; unknown keys fall back to English.
|
||||
Additional message languages are read from KV under the key `i18n:<lang>`: a JSON object with the same nested structure as the built-in dictionaries (`server/lib/lib/locales/en.ts`). Every key you do not provide falls back to English. The built-in `en` and `zh` are never read from KV, so they cannot be overridden this way; use another language code (e.g. `zh-custom`) and set it as the group's `lang`.
|
||||
|
||||
```jsonc
|
||||
// KV key: i18n:zh
|
||||
// KV key: i18n:zh-custom
|
||||
{
|
||||
"events.push.title": "{repo}: 推送了 {count} 个提交到 {ref}",
|
||||
"events": {
|
||||
"push": { "title": "{repo}: 推送了 {count} 个提交到 {ref}" },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Overrides apply to group messages (and console UI where applicable). To add a brand-new language, store a full dictionary at `i18n:<lang>` — every key you do not provide falls back to English.
|
||||
A loaded dictionary stays cached in each worker instance until it restarts, so a changed override may take a while to apply; a language with no override is looked up again after 5 minutes. Overrides affect group messages only — the console has its own built-in translations.
|
||||
|
||||
## Emoji Toggle
|
||||
|
||||
`Group.emoji` (default `true`) controls whether event emoji appear in that group's messages. When disabled, all emoji are stripped from titles, descriptions, fields, and links. Milestone progress bars (🟢🟡🟠⬜) are data visualization and stay regardless of the toggle.
|
||||
`Group.emoji` (default `true`) controls whether event emoji appear in that group's messages. When disabled, the emoji the formatters add are left out of titles, descriptions, fields, and links; text taken from the payload (commit messages, issue titles, custom webhook fields) keeps any emoji it contains. Milestone progress bars (🟢🟡🟠⬜) are data visualization and stay regardless of the toggle.
|
||||
+27
-18
@@ -11,24 +11,29 @@ WebHooker ingests webhooks from multiple forges through the same `POST /webhook`
|
||||
|
||||
Delivery-id dedup uses `X-GitHub-Delivery` (GitHub) or `X-Gitea-Delivery` (Gitea) when present.
|
||||
|
||||
With the delivery queue enabled, a webhook is acknowledged (`200`) only after it was durably enqueued. If the queue rejects it, the endpoint answers `503` and releases the dedup claim, so the sender's redelivery is accepted instead of being dropped as a duplicate. A redelivery of a webhook that was already accepted answers `200 { "duplicate": true }`; one that arrives while the first copy is still being processed answers `503`, so the sender tries again later.
|
||||
|
||||
Without the queue binding, the webhook is dispatched inline and answered only once dispatch finished: `200` when every target was handled, `503` when a target failed transiently (the sender's redelivery then skips the targets that already succeeded). Inline dispatch stops sending after 8 minutes and answers `503` for the rest, so one request never outlives its dedup claim.
|
||||
|
||||
Gitea payloads are normalized to the same internal shape as GitHub events, so routes, filters, and the 28 formatters work unchanged. Unknown or unmapped Gitea events fall back to the generic formatter. Repository/commit/user links are derived from the payload's `repository.html_url`, so they point at your Gitea instance.
|
||||
|
||||
## Global Endpoint (`POST /webhook`)
|
||||
|
||||
The global endpoint verifies payloads against the operator's global secrets (`GITHUB_WEBHOOK_SECRET`, `GITEA_WEBHOOK_SECRET`) and dispatches into **all** routes. GitHub App installations deliver here; use `installationId` on groups to keep tenants isolated.
|
||||
The global endpoint verifies payloads against the operator's global secrets (`GITHUB_WEBHOOK_SECRET`, `GITEA_WEBHOOK_SECRET`) and dispatches into **all** routes — except those of [isolated groups](./groups#self-sign-up) without a bound source. GitHub App installations deliver here; use `installationId` on groups to keep tenants isolated.
|
||||
|
||||
## Per-Group Endpoint (`POST /webhook/{groupId}`)
|
||||
|
||||
Every group can opt into its own webhook ingress with an independent secret (generated from the group page — Webhook endpoint panel, owner role). Payloads are verified against the **group's** secret instead of the global ones, and only that group's routes are eligible. This is how SaaS users configure Gitea, classic GitHub, or custom webhooks without sharing (or knowing) the operator's secrets.
|
||||
|
||||
- Supported for any provider: GitHub (`X-Hub-Signature-256`), Gitea (`X-Gitea-Signature`), custom (`X-WebHooker-Signature`)
|
||||
- The secret is a 64-char hex string; regenerate from the console invalidates the old one immediately
|
||||
- Delivery-id dedup keys are provider- and tenant-scoped (`delivery:{provider}:{groupId}:{id}`)
|
||||
- When the group has no secret (or no longer exists) the endpoint returns `404`
|
||||
- The secret is a 64-char hex string stored with the group in D1 (it is never sent to the console after generation); regenerating invalidates the old one immediately, and only a current owner can rotate or remove it
|
||||
- Delivery-id dedup keys are provider- and tenant-scoped (`delivery:{provider}:@i:{instance}:{id}` — the group's immutable instance, so a rename keeps the scope and a group re-created under the same id never shares it; the global endpoint uses the scope `@global`)
|
||||
- When the group has no secret (or no longer exists) the endpoint returns `404`; when the group's stored configuration cannot be read it returns `503`
|
||||
- A tenant-signed payload is only as trustworthy as the tenant: its `installation.id` is ignored, so it never uses the operator's GitHub App credentials (no job/build-log enrichment) and never provisions or rebinds installation groups; the installation restriction does not apply to the group's own ingress
|
||||
|
||||
## Custom Webhooks
|
||||
|
||||
Post arbitrary JSON to `POST /webhook/{groupId}` (or the global endpoint) with the body signed as `X-WebHooker-Signature: sha256=<hmac-sha256 hex of the raw body>` using the group's secret. The payload becomes a `custom` event that flows through the normal route pipeline — create a route with `event: custom` (there is a console template) and it dispatches to that route's targets, records `send_logs`, and appears in the group's webhook log channel.
|
||||
Post a JSON object to `POST /webhook/{groupId}` (or the global endpoint) with the body signed as `X-WebHooker-Signature: sha256=<hmac-sha256 hex of the raw body>` using the group's secret (a top-level array or scalar is rejected with `400`). The payload becomes a `custom` event that flows through the normal route pipeline — create a route with `event: custom` (there is a console template) and it dispatches to that route's targets, records `send_logs`, and appears in the group's webhook log channel.
|
||||
|
||||
### Replay Protection
|
||||
|
||||
@@ -40,7 +45,7 @@ Custom webhooks support optional replay protection via two extra headers alongsi
|
||||
When **both** headers are present, the signature is computed over `{timestamp}.{nonce}.{rawBody}` instead of the raw body, and the request is accepted only if:
|
||||
|
||||
1. The timestamp is within ±5 minutes of the server clock (rejects replays and clock-drift abusers)
|
||||
2. The nonce has never been seen before (stored in KV for 10 minutes; a replayed nonce is rejected)
|
||||
2. The nonce has never been seen before for this secret (claimed atomically and kept for 10 minutes; a replayed nonce is rejected, while another tenant may use the same nonce). A nonce whose first request is still being processed, or a failure of the nonce store, answers `503` instead of `401`, so the sender retries
|
||||
|
||||
```bash
|
||||
input="${timestamp}.${nonce}.${body}"
|
||||
@@ -69,22 +74,26 @@ Payload schema:
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
|
||||
| `title` | string | Message title (falls back to "Custom message") |
|
||||
| `description` | string | Optional message body |
|
||||
| `color` | string | Optional embed color: a word (`red`, `green`, `yellow`, `blue`, `purple`, `orange`, `cyan`, `gray`) or `#rrggbb` |
|
||||
| `url` | string | Optional link for the title |
|
||||
| `repo` | string | Optional `owner/repo`; prefixes the title and is used as the footer |
|
||||
| `author` | object | Optional `{ name, iconUrl, url }` |
|
||||
| `fields` | object[] | Optional embed fields `{ name, value, inline }` |
|
||||
| `footer` | string | Optional footer override |
|
||||
| `deliveryId` | string | Optional id for sender-side dedup (retries) |
|
||||
| Field | Type | Description |
|
||||
| ------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `title` | string | Message title (falls back to "Custom message") |
|
||||
| `description` | string | Optional message body |
|
||||
| `color` | string | Optional embed color: a word (`red`, `green`, `yellow`, `blue`, `purple`, `orange`, `cyan`, `gray`) or `#rrggbb` |
|
||||
| `url` | string | Optional link for the title |
|
||||
| `repo` | string | Optional `owner/repo`; prefixes the title and is used as the footer |
|
||||
| `author` | object | Optional `{ name, iconUrl, url }` |
|
||||
| `fields` | object[] | Optional embed fields `{ name, value, inline }` |
|
||||
| `footer` | string | Optional footer override |
|
||||
| `deliveryId` | string | Optional id for sender-side dedup (retries). Without a `deliveryId` the nonce identifies the request; with neither, a retried request is delivered again |
|
||||
|
||||
## GitHub App Tenant Isolation
|
||||
|
||||
When the GitHub App is installed, its events arrive at the global endpoint for **every** installation. To keep tenants apart, bind each group to the installation id that should feed it: `"installationId": 12345678`. The id is visible in the App's installation webhook payload (`installation.id`) or on the GitHub App installation page URL. Events from any other installation are rejected for that group even if its `owners` list is empty. Groups without `installationId` keep the legacy behavior (`owners` filtering).
|
||||
|
||||
Binding is **auto-configured** — the GitHub App's _Setup URL_ should point to `{BASE_URL}/auth/github/install`. Right after a user installs the App, the browser lands there (the page requires a signed-in admin session — not signed in users are redirected through the OAuth flow first) and they choose where the installation binds: a **new group** (`inst-{installationId}`, default) or any **existing group they own** (owner role checked again on submit; `POST /auth/github/install/bind` performs the provisioning). No manual id entry is needed. As a fallback (e.g. when the Setup URL is not configured), the `installation.created` webhook event creates/binds the group automatically — existing groups whose `owners` match the installing account are bound, otherwise a dedicated `inst-{installationId}` group is created. Then just add routes/members in the console.
|
||||
Binding is **auto-configured** — the GitHub App's _Setup URL_ should point to `{BASE_URL}/auth/github/install`. Right after a user installs the App, the browser lands there (the page requires a signed-in admin session — not signed in users are redirected through the OAuth flow first) and they choose where the installation binds: a **new group** (`inst-{installationId}`, default) or any **existing group they own** (owner role checked again on submit; `POST /auth/github/install/bind` performs the provisioning). No manual id entry is needed.
|
||||
|
||||
The `installation_id` in the Setup URL can be set to anything, so both the page and the bind step first verify — with the signed-in user's own GitHub token — that the user may manage that installation: they are the installation's own account, or an active **admin** of its organization (merely having access to it as a collaborator is not enough). Otherwise they are sent back with `?error=install-forbidden`. Super admins may bind any installation. With `ALLOW_SELF_SIGNUP`, the installer becomes owner of the dedicated `inst-{installationId}` group only while it is bound to that installation and has no members yet — no other group is ever handed to a new owner this way. Ids starting with `inst-` or `u-` are reserved for these system groups: only super admins may create or rename groups to them, and an existing unbound `inst-*` group is never bound automatically.
|
||||
|
||||
As a fallback (e.g. when the Setup URL is not configured), the `installation.created` webhook event — on the global endpoint only — creates/binds the group automatically: existing groups whose `owners` match the installing account are bound, otherwise a dedicated `inst-{installationId}` group is created. Then just add routes/members in the console. The provisioning runs after the delivery's dedup check and is recorded per installation and per bound group for 7 days, so a redelivered event never re-binds a group a super admin has unbound since; if provisioning fails, the endpoint answers `503` so the event is redelivered.
|
||||
|
||||
To show the installing account's login on the choice page, set `GITHUB_APP_ID` and `GITHUB_PRIVATE_KEY` — see [Secrets](./configuration#secrets).
|
||||
@@ -22,7 +22,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
||||
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Cloudflare Worker** | HTTP ingress, signature verification, delivery dedup, event parsing, route matching, platform dispatch |
|
||||
| **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}`), admin sessions, per-group secrets, config cache, delivery dedup/state/message-tracking fallback when D1 is unavailable (`delivery:*`, `delivery-state:*`, `msg:*`), message-update locks (`msg:lock:*`) |
|
||||
| **KV** | Token storage (`token:{userId}`), OAuth state (`state:{hex}`), admin sessions, invites, delivery dedup/state/message-tracking fallback when D1 is unavailable (`delivery:*`, `delivery-state:*`, `msg:*`), message-update locks (`msg:lock:*`) |
|
||||
| **D1** | Routes/groups (`d1_routes`/`d1_groups`), send logs (`send_logs`), audit logs (`audit_logs`), dedup (`dedup_keys`), delivery state (`delivery_state`), message tracking (`message_tracking`), Discord↔GitHub links (`discord_links`), Telegram↔GitHub links (`telegram_links`), with R2 optionally parking oversized payloads |
|
||||
|
||||
### Data Flow
|
||||
@@ -40,7 +40,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
||||
- **Runtime**: Cloudflare Workers
|
||||
- **HTTP Framework**: Nuxt 4 / Nitro (H3)
|
||||
- **Discord delivery**: Discord REST API (interactions via an Ed25519-verified HTTPS Interactions Endpoint)
|
||||
- **Telegram delivery**: Telegram Bot API (webhook with optional secret-token verification)
|
||||
- **Telegram delivery**: Telegram Bot API (webhook calls always verified with a secret token — explicit, or derived from the bot token)
|
||||
- **Web UI**: Nuxt 4 (Vue 3 + Tailwind CSS v4 + `@elysola/ui`) — server-rendered home/legal pages, client-side `/admin` console
|
||||
- **Storage**: Cloudflare D1 (authoritative for config & logs) + KV (cache/transient state) + optional R2 (oversized payloads)
|
||||
- **Auth**: Web Crypto API (HMAC-SHA256, Ed25519), octokit (GitHub API)
|
||||
|
||||
+26
-20
@@ -4,27 +4,33 @@
|
||||
|
||||
Every dispatch attempt is recorded in the D1 `send_logs` table and browsable in the console (**Logs** tab). Fields:
|
||||
|
||||
| Field | Meaning |
|
||||
| ------------ | ---------------------------------------------------------------- |
|
||||
| `routeId` | Route that matched |
|
||||
| `groupId` | Route's group |
|
||||
| `event` | Event type (e.g. `push`, `pull_request`, `custom`) |
|
||||
| `repo` | Repository full name (when present) |
|
||||
| `target` | Target id the message was sent to |
|
||||
| `platform` | `discord`, `telegram` or `feishu` |
|
||||
| `ok` | Whether the send succeeded |
|
||||
| `status` | HTTP status from the platform API (when applicable) |
|
||||
| `error` | Error message (when failed) |
|
||||
| `errorCode` | Stable error code (e.g. `NO_TARGET`, `NO_TOKEN`, `RATE_LIMITED`) |
|
||||
| `attempts` | Send attempts including retries |
|
||||
| `durationMs` | Time spent sending |
|
||||
| `deliveryId` | Webhook delivery id (when provided) |
|
||||
| `messageId` | Platform message id (used for in-place edits) |
|
||||
| `actor` | Sender login |
|
||||
| `action` | Event action (when present) |
|
||||
| `detail` | Extra JSON details (when present) |
|
||||
| Field | Meaning |
|
||||
| ------------ | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `routeId` | Route that matched |
|
||||
| `groupId` | Route's group |
|
||||
| `event` | Event type (e.g. `push`, `pull_request`, `custom`) |
|
||||
| `repo` | Repository full name (when present) |
|
||||
| `target` | Target id the message was sent to |
|
||||
| `platform` | `discord`, `telegram` or `feishu` |
|
||||
| `ok` | Whether the send succeeded |
|
||||
| `status` | HTTP status from the platform API (when applicable) |
|
||||
| `error` | Error message (when failed) |
|
||||
| `errorCode` | Stable error code (e.g. `NO_TARGET`, `NO_TOKEN`, `RATE_LIMITED`, `FORMAT`, `PAYLOAD_MISSING`, `TELEGRAM_UNCERTAIN`) |
|
||||
| `attempts` | Send attempts including retries |
|
||||
| `durationMs` | Time spent sending |
|
||||
| `deliveryId` | Webhook delivery id (when provided) |
|
||||
| `messageId` | Platform message id (used for in-place edits) |
|
||||
| `actor` | Sender login |
|
||||
| `action` | Event action (when present) |
|
||||
| `detail` | Extra JSON details (when present) |
|
||||
|
||||
The console's **Logs** tab lists recent entries (filterable by group) and shows full details for a single entry. Entries are written best-effort — a failed insert never breaks dispatch.
|
||||
The console's **Logs** tab lists recent entries (filterable by group) and shows full details for a single entry. Entries are written best-effort — a failed insert is retried once and never breaks dispatch. `send_logs` is not pruned automatically.
|
||||
|
||||
Notable error codes:
|
||||
|
||||
- `PAYLOAD_MISSING` — the parked payload of a queued delivery is gone; the delivery stays retrying and the entry asks for the webhook to be redelivered from its source.
|
||||
- `TELEGRAM_UNCERTAIN` — Telegram answered `200` but the response could not be read; the message may or may not have been sent, so it is not retried (Telegram offers no idempotency key).
|
||||
- `FORMAT` — the event could not be formatted; nothing was sent for that route.
|
||||
|
||||
## Audit Log (`audit_logs`)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ The repo comes from `payload.repository.full_name` (falling back to a generic "r
|
||||
|
||||
Only the repo head is hyperlinked — never the whole title:
|
||||
|
||||
- **Discord** (embed titles cannot contain partial links): the title is the repo head `{repo}{#number}`, linked to the repository; the `: {subject}` text is rendered as the first line of the description, unlinked.
|
||||
- **Discord** (embed titles cannot contain partial links): the title is the repo head `{repo}{#number}`, linked to the event's object (the issue, PR, comment or run page); the `: {subject}` text is rendered as the first line of the description, unlinked.
|
||||
- **Telegram** (HTML supports inline links): the one-line title keeps the subject, with only the repo head wrapped in a link.
|
||||
|
||||
Messages whose title has no colon separator (a `:` followed by a space) keep the legacy whole-title link behavior.
|
||||
@@ -37,7 +37,7 @@ With `Group.forgeSources` (a list of `{ host, type, name? }` entries) the messag
|
||||
|
||||
## In-Place Updates
|
||||
|
||||
`workflow_run` and `check_run` messages are sent once and edited in place as the run progresses (queued → running → success/failure) — no duplicate messages. Tracking uses KV `msg:*` with a stable `updateKey` per run: `workflow_run` keys on the workflow id, while `check_run` keys on the check name + commit SHA (falling back to the run id) so deployments that emit a fresh run id per phase — e.g. Cloudflare Pages — still edit the same message.
|
||||
Messages about an object that changes over time are sent once and edited in place as it changes — `workflow_run` and `check_run` / `check_suite` as the run progresses (queued → running → success/failure), deployments and their statuses, issue comments, pull request reviews and review comments as they are edited or deleted — instead of posting a new message. Each edit re-renders the whole message from the newest event. Tracking uses D1 `message_tracking` (KV `msg:*` as fallback) with a stable `updateKey` per object: `workflow_run` keys on the run id, `check_suite` on the suite id, while `check_run` keys on the check suite (or app) + check name + commit SHA (falling back to the run id) so deployments that emit a fresh run id per phase — e.g. Cloudflare Pages — still edit the same message. The chain is also keyed by the forge (provider + repository host) and the target platform, so two Gitea instances with the same `owner/repo` never edit each other's messages. An event older than the state a message already shows (delivered late) does not overwrite it; a failed edit is reported as a failure rather than posting a second message — a new message is sent only when the old one no longer exists.
|
||||
|
||||
## Workflow Jobs
|
||||
|
||||
|
||||
+16
-6
@@ -1,8 +1,8 @@
|
||||
# Routes & Targets
|
||||
|
||||
Routes define which events get forwarded to which channel (Discord or Telegram). They are stored in D1 (`d1_routes`, seeded from the legacy KV `config:routes` key on first load), managed via the [Web UI](./configuration#web-ui), the [Admin API](../api/admin), or `config.example.yaml`.
|
||||
Routes define which events get forwarded to which channel (Discord or Telegram). They are stored in D1 (`d1_routes`, seeded from the legacy KV `config:routes` key on first load), managed via the [Web UI](./configuration#web-ui) or the [Admin API](../api/admin). `config.example.yaml` shows the schema as YAML; the worker does not load it.
|
||||
|
||||
There are **no default routes** — each route must define its own target. If no routes are configured, no events are forwarded. At most **200 routes** can be saved per instance.
|
||||
There are **no default routes** — each route must define its own target. If no routes are configured, no events are forwarded. One save accepts at most **200 routes**.
|
||||
|
||||
## Route Schema
|
||||
|
||||
@@ -29,14 +29,20 @@ There are **no default routes** — each route must define its own target. If no
|
||||
}
|
||||
```
|
||||
|
||||
Each entry of `targets` is a push destination, so one route can forward to several channels at once (e.g. a Discord channel **and** a Telegram group). `target.platform` selects the platform: `discord` (default), `telegram` or `feishu`. For **Discord**, `target.channelId` is required (a thread in `target.threadId` is optional). For **Telegram** and **Feishu**, `target.chatId` (the group/supergroup chat id, e.g. `-1001234567890`) is required and `target.topicId` (the `message_thread_id` of a topic, equivalent of a Discord thread) is optional. There is no fallback to a default channel.
|
||||
Each entry of `targets` is a push destination, so one route can forward to several channels at once (e.g. a Discord channel **and** a Telegram group). `target.platform` selects the platform: `discord` (default), `telegram` or `feishu`. For **Discord**, `target.channelId` is required (a thread in `target.threadId` is optional). For **Telegram**, `target.chatId` (the group/supergroup chat id, e.g. `-1001234567890`) is required and `target.topicId` (the `message_thread_id` of a topic, equivalent of a Discord thread) is optional. For **Feishu**, `target.chatId` (the group's chat id, `oc_…`) is required; Feishu targets have no topic. There is no fallback to a default channel.
|
||||
|
||||
Target ids are validated so that every destination has exactly one spelling (otherwise the cross-group ownership check could be bypassed):
|
||||
|
||||
- **Discord** — `channelId` / `threadId` use only `A–Z a–z 0–9 _ -` (up to 64 characters); numeric ids have no leading zero.
|
||||
- **Telegram** — `chatId` is the numeric chat id in canonical form (no leading zeros, at most 15 digits; `@username` is not accepted); `topicId` is a positive integer up to 2147483647.
|
||||
- A route cannot list the same destination twice: `{ "channelId": T }` and `{ "channelId": P, "threadId": T }` both send to thread `T` and count as one destination, as do Telegram topic ids written differently.
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
| ---------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `groupId` | string | Yes | Id of the [group](./groups) this route belongs to |
|
||||
| `fallback` | boolean | No | When `true`, fires only if no non-fallback route of the same group matched the event; its filters still apply |
|
||||
| `stop` | boolean | No | When `true` and this route matches, no further routes of the same group are evaluated for this event |
|
||||
| `discordRoleIds` | string[] | No | Discord role ids to ping when this route fires; applied to Discord targets only |
|
||||
| `discordRoleIds` | string[] | No | Discord role ids to ping when this route fires (at most 50); applied to Discord targets only |
|
||||
| `ast` | object | No | Boolean filter tree (`{all:[...]}` / `{any:[...]}` / `{not:{...}}`); takes precedence over `filters` when present |
|
||||
|
||||
## Route Order
|
||||
@@ -45,6 +51,10 @@ Routes are evaluated in the order the console shows them, group by group. `stop`
|
||||
|
||||
**Upgrade note:** If your configuration relied on `stop` in one group preventing routes in another group from running, or on a regular route match in one group suppressing fallback sends in another, review your existing routes when upgrading. These effects now apply only within the same group, so routes in other groups may start sending. Move routes that need to be mutually exclusive into the same group, then check their order and `stop` / `fallback` settings.
|
||||
|
||||
## Unreadable Routes
|
||||
|
||||
A stored route that cannot be read — corrupt JSON, a field of the wrong shape, an invalid filter, or a pattern the matcher cannot compile (for example a lookahead regex written for another engine) — is never treated as "no match". The group's deliveries fail visibly and are retried (every other group is unaffected), and `GET /admin/api/groups/:id/routes` reports `unreadable: true`. Saving the group's routes is refused while such a row exists, so it is never deleted unseen; to replace it on purpose, send the save with `discardUnreadable: true`.
|
||||
|
||||
## Discord Role Mentions
|
||||
|
||||
Set `discordRoleIds` on a route to ping one or more Discord roles (身份组) whenever that route fires. The mention (`<@&roleId>`) is prepended to the message content of every **Discord** target of the route; Telegram targets ignore this field. Mentions only trigger notifications when the bot has the `Mention Everyone` permission (or the role is marked mentionable), and the bot must be able to see the role.
|
||||
@@ -79,13 +89,13 @@ Every route carries a `filters` array (all must match — AND logic). When the r
|
||||
"filters": [
|
||||
{ "type": "repo", "match": "myorg/backend" },
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
{ "type": "actor", "match": "[bot]", "exclude": true }
|
||||
{ "type": "actor", "match": "*[bot]", "exclude": true }
|
||||
],
|
||||
"targets": [
|
||||
{
|
||||
"platform": "telegram",
|
||||
"chatId": "-1001234567890",
|
||||
"topicId": "9876543210"
|
||||
"topicId": "42"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+53
-37
@@ -4,58 +4,74 @@
|
||||
|
||||
KV keeps only cache data and short-lived/ephemeral state. High-frequency writes (webhook dedup, delivery state, message tracking) live in D1 and only fall back to KV when D1 is unavailable or not yet migrated (see [Storage decisions](./storage#storage-decisions)).
|
||||
|
||||
| Key Pattern | Value | TTL |
|
||||
| ------------------------------------------ | ----------------------------------------------------------------------------- | ------------------ |
|
||||
| `config:routes` | Route config cache (D1 `d1_routes` is authoritative) | 1 hour |
|
||||
| `config:groups` | Group config cache (D1 `d1_groups` is authoritative) | 1 hour |
|
||||
| `session:{id}` | Admin session `{ userId, login }` | 7 days |
|
||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, refreshToken? }` | 0.9 × token expiry |
|
||||
| `token-reverse:{sha256}` | User id for reverse lookup by token | 0.9 × token expiry |
|
||||
| `state:{hex}` | `{ redirectTo, expiresAt, discordUserId?, telegramUserId?, telegramChatId? }` | 600 seconds |
|
||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note? }` | 7 days |
|
||||
| `invite:group:{id}` | Token index per group (keeps invite listing consistent) | 7 days |
|
||||
| `delivery:{provider}:{groupId}:{id}` | Webhook delivery dedup fallback (D1 `dedup_keys` is primary) | 7 days |
|
||||
| `delivery-state:{provider}:{groupId}:{id}` | Queue delivery state fallback (D1 `delivery_state` is primary) | 1 hour |
|
||||
| `queue:payload:{provider}:{groupId}:{id}` | Oversized webhook payload parked for the queue consumer (R2 is primary) | 1 hour |
|
||||
| `nonce:{nonce}` | Custom-webhook replay protection nonce (single use) | 600 seconds |
|
||||
| `tenant:{groupId}` | Per-group webhook secret (64-char hex, generated from the console) | Permanent |
|
||||
| `msg:{routeId}:{key}:{target}` | Message id tracking fallback (D1 `message_tracking` is primary) | 1 day |
|
||||
| `cmd:guild:{id}` | Guild id whose commands were registered (dedup) | Permanent |
|
||||
| `cmd:registered:global` | Global command registration marker (dedup) | 1 day |
|
||||
| `config:discord-app-id` | Cached Discord application id | Permanent |
|
||||
| `i18n:{lang}` | Translation overrides merged on top of English | Permanent |
|
||||
| Key Pattern | Value | TTL |
|
||||
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
|
||||
| `config:routes` / `config:groups` | Legacy (pre-D1) configuration, read once to seed empty D1 tables | Permanent |
|
||||
| `config:d1-seeded` | Marks that D1 was seeded (an emptied D1 is never re-seeded) | Permanent |
|
||||
| `session:{id}` | Admin session `{ userId, login, loginTrusted }` | 1 day |
|
||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, live? }` (a token is used for 10 hours) | 9 hours |
|
||||
| `token-reverse:{sha256}` | User id for reverse lookup by token | 9 hours |
|
||||
| `state:{hex}` | `{ redirectTo, expiresAt, link? }` (`link`: the chat account a bot `/gh login` binds) | 600 seconds |
|
||||
| `link:{nonce}` | A bot account link waiting for the GitHub user's confirmation | 600 seconds |
|
||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note?, groupInstance, issuer }` | 7 days |
|
||||
| `invite:group:{id}` | Token index per group (keeps invite listing consistent) | 7 days |
|
||||
| `invite:by-group:{id}:{token}` / `invite:by-instance:{instance}:{token}` | Per-invite listing markers (by group id and by the issuing group's instance), so concurrent creates or a half-finished rename never hide an invite | Invite lifetime |
|
||||
| `login-owner:{login}` | GitHub user id of the first account seen with this login; another account using the login later is matched by user id only | Permanent |
|
||||
| `delivery:{provider}:{scope}:{id}` | Webhook delivery dedup fallback (D1 `dedup_keys` is primary); `scope` is `@global` for the global endpoint or `@i:{instance}` (the receiving group's immutable instance) for a group endpoint | 2–10 minutes |
|
||||
| `delivery-state:{provider}:{scope}:{id}` | Queue delivery state fallback (D1 `delivery_state` is primary) | 7 days |
|
||||
| `queue:payload:{provider}:{scope}:{id}:{uuid}` | Oversized webhook payload parked for the queue consumer when there is no R2 binding (one key per enqueue) | 4 days |
|
||||
| `tenant:{groupId}` / `tenant:i:{instance}` | Legacy per-group webhook secrets, read only for groups whose secret was never moved into their D1 row; removed on rotate/delete | Permanent |
|
||||
| `group:renamed:{oldId}` | KV-only deployments: where a renamed group went (with D1 this alias is a `dedup_keys` row written in the rename transaction) | 4 days |
|
||||
| `msg:{chain}:{platform}:{target}` | Message tracking fallback (D1 `message_tracking` is primary) | 30 days |
|
||||
| `msg:lock:…` | Lock serializing updates of one message chain when D1 is unavailable (with D1 it is a `dedup_keys` row) | 240 seconds |
|
||||
| `storage:kv-fallback` | Marks that state was written to KV while a D1 table was missing; while it lives, D1 misses are also looked up in KV | 35 days |
|
||||
| `cmd:guilds:{appId}` | Per Discord application: each guild's registered command hash and the sync cursor | Permanent |
|
||||
| `cmd:registered:global:{appId}` | Hash of the commands last registered globally (re-registered when it changes, and daily) | 1 day |
|
||||
| `config:discord-app-id:{tokenHash}` | Discord application id resolved for a bot token | Permanent |
|
||||
| `discord-modal:{id}` | Comment-modal context, only when it does not fit in the 100-character `custom_id` | 1 day |
|
||||
| `feishu:token:{appId}` | Feishu `tenant_access_token` per app (also held in memory) | Token expiry − 6 minutes |
|
||||
| `telegram:webhook:{botId}` | Hash of the webhook registration last set (`setWebhook` is skipped while it matches) | 1 day |
|
||||
| `i18n:{lang}` | Translation overrides merged on top of English | Permanent |
|
||||
| `config:identity-migrated` | KV-only deployments: group identities are managed by this server (the one-time identity migration ran) | Permanent |
|
||||
|
||||
## D1 Storage Layout
|
||||
|
||||
The D1 database (`DB` binding, database `webhooker`) holds the source of truth for configuration, delivery logs and high-frequency ephemeral state:
|
||||
|
||||
| Table | Purpose |
|
||||
| ------------------ | ---------------------------------------------------------------------------------------------- |
|
||||
| `d1_groups` | Groups (authoritative config, seeded from legacy KV `config:groups`) |
|
||||
| `d1_routes` | Routes per group (authoritative config, seeded from legacy KV `config:routes`) |
|
||||
| `send_logs` | One row per dispatch attempt (route id, event, target, ok/error, duration, error code, detail) |
|
||||
| `audit_logs` | One row per admin operation (login/logout, group/route/member/invite changes) |
|
||||
| `dedup_keys` | Webhook delivery dedup (atomic `INSERT ... ON CONFLICT` UPSERT, key + expiry) |
|
||||
| `delivery_state` | Queue delivery state (`pending`/`processing`/`delivered`/`retrying`/`failed`/`dead`) |
|
||||
| `message_tracking` | Message id tracking for in-place updates (`event_id` + `target_id` → `message_id`) |
|
||||
| `discord_links` | Maps `discord_user_id` → `github_user_id` for `/gh` Discord commands |
|
||||
| `telegram_links` | Maps `telegram_user_id` → `github_user_id` for `/gh` Telegram commands |
|
||||
| Table | Purpose |
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `d1_groups` | Groups (authoritative config, seeded from legacy KV `config:groups`). Each row also holds server-only fields that are never sent to the console: the immutable `instance` id, `legacyId`, and the group's webhook secret |
|
||||
| `d1_routes` | Routes per group (authoritative config, seeded from legacy KV `config:routes`) |
|
||||
| `send_logs` | One row per dispatch attempt (route id, event, target, ok/error, duration, error code, detail) |
|
||||
| `audit_logs` | One row per admin operation (login/logout, group/route/member/invite changes) |
|
||||
| `dedup_keys` | Atomic one-time claims and records (`INSERT ... ON CONFLICT` UPSERT, key + expiry): webhook delivery dedup and its confirmations (`accepted:*`), custom-webhook nonces (`nonce:{secret-scope}:{nonce}`), single-use and revoked invites (`invite-used:*`, `invite-revoked:*`), bot command/event dedup (`bot:{platform}:…`), revoked sessions and tokens and each user's live token (`session-revoked:*`, `token-revoked:*`, `token-live:*`), used account-link confirmations (`link-used:*`), retired group ids (`group-retired:*`) and rename aliases (`group-alias:*`), installation provisioning records (`installation-provisioned:*`, `installation-bound:*`), route × targets already finished or failed for good by a queued delivery (`delivery-target:*`, `delivery-failed:*`), group log summaries already sent, message-chain locks (`msg:lock:*`) and one-time setup markers |
|
||||
| `delivery_state` | Queue delivery state (`pending`/`processing`/`delivered`/`retrying`/`failed`/`dead`); taking a delivery is a conditional UPSERT (a lease), so two consumers never dispatch it at once |
|
||||
| `message_tracking` | Message tracking for in-place updates (`event_id` + `target_id` → message id and the version it shows); chains are keyed by the group's instance, so a group created later under the same id never edits its messages |
|
||||
| `d1_fragments` | Named filter fragments per group |
|
||||
| `feishu_links` | Maps `feishu_user_id` → `github_user_id` for `/gh` Feishu commands |
|
||||
| `discord_links` | Maps `discord_user_id` → `github_user_id` for `/gh` Discord commands |
|
||||
| `telegram_links` | Maps `telegram_user_id` → `github_user_id` for `/gh` Telegram commands |
|
||||
|
||||
`audit_logs` is pruned by the scheduled trigger after `AUDIT_RETENTION_DAYS` (default 90). The `storage-prune` task removes expired `dedup_keys`, `delivery_state` rows older than 7 days and `message_tracking` rows older than 30 days. See [Logs](./logs) for the log row fields.
|
||||
`audit_logs` is pruned by the scheduled trigger after `AUDIT_RETENTION_DAYS` (default 90). The `storage-prune` task removes expired `dedup_keys`, `delivery_state` rows older than 7 days, `message_tracking` rows not updated for 30 days (every edit refreshes a row) and orphaned R2 payloads. `send_logs` is not pruned automatically. See [Logs](./logs) for the log row fields.
|
||||
|
||||
Migration `0013_prune_indexes.sql` adds the indexes these reads rely on: `delivery_state(updated_at)` for the prune, two partial indexes on failed `send_logs` rows for the metrics page, and `audit_logs(group_id, ts)` in place of the single-column group index. Every index also costs a D1 row write when its columns are written, so only indexes whose reads would otherwise cost far more are added.
|
||||
|
||||
## R2 Storage Layout
|
||||
|
||||
R2 (`PAYLOAD` binding, bucket `webhooker-payloads`) stores oversized webhook payloads that are too large for a queue message or KV:
|
||||
|
||||
| Object Pattern | Purpose | Retention |
|
||||
| --------------------------------- | ----------------------------------------------- | ---------------------- |
|
||||
| `webhooks/YYYY/MM/DD/<uuid>.json` | Oversized payload parked for the queue consumer | deleted after dispatch |
|
||||
| Object Pattern | Purpose | Retention |
|
||||
| --------------------------------- | ----------------------------------------------- | --------------------------------------------------- |
|
||||
| `webhooks/YYYY/MM/DD/<uuid>.json` | Oversized payload parked for the queue consumer | deleted after dispatch; orphans pruned after 5 days |
|
||||
|
||||
When the `PAYLOAD` binding is absent, oversized payloads fall back to the KV key `queue:payload:{provider}:{groupId}:{id}` (1 hour TTL).
|
||||
A payload is parked when the queue message would exceed 120,000 bytes (UTF-8). When the `PAYLOAD` binding is absent, oversized payloads fall back to the KV key `queue:payload:{provider}:{scope}:{id}:{uuid}` (4 day TTL, matching the queue's message retention). If sending the queue message fails, the parked copy is kept (the queue may have accepted the message even though the call failed); unused copies expire or are pruned. A parked payload that is gone when the consumer needs it is never dispatched as an empty event: the delivery stays `retrying` and a `PAYLOAD_MISSING` send-log entry asks for the webhook to be redelivered from its source.
|
||||
|
||||
## Storage Decisions
|
||||
|
||||
- **D1 is authoritative** for config and delivery metadata; KV holds only caches and short-lived state.
|
||||
- The `canUseD1` probe (`server/lib/storage/d1.ts`, checks for `prepare` + `batch`) gates every D1 store: when D1 is unavailable or not yet migrated, all three high-frequency stores (dedup, delivery state, message tracking) transparently fall back to KV so behavior is unchanged during migration.
|
||||
- The `canUseD1` probe (`server/lib/storage/d1.ts`, checks for `prepare` + `batch`) gates every D1 store. The high-frequency stores (dedup and other one-time claims, delivery state, message tracking) also fall back to KV while their D1 table does not exist yet (an unmigrated database). Any other D1 failure propagates — the request answers with an error and the sender or queue retries — because switching stores per call would split a claim between D1 and KV.
|
||||
- When D1 configuration reads fail, the request answers with an error and the sender or queue retries; there is no KV copy of the configuration, and dispatch never treats unreadable configuration as empty. A stored route or group row that cannot be read only makes its own group's deliveries fail visibly (and retry) — see [Routes → Unreadable routes](./routes#unreadable-routes).
|
||||
- Configuration writes never fall back: with a D1 binding, a failed write is reported as an error instead of being parked in KV. Writes are per group (one row, or one group's routes/fragments in one transaction) with compare-and-swap on the group row, so concurrent edits of different groups never overwrite each other. Reads for access checks, read-modify-write paths, webhook ingress and the queue consumer bypass every cache (a revoked route or target stops at once); other reads are cached in memory for at most 60 seconds per isolate.
|
||||
- Legacy KV configuration is copied into D1 once, only while both D1 tables are empty, and never over existing rows; a marker prevents an emptied configuration from being resurrected.
|
||||
- This keeps per-event KV writes near zero on the Workers Free plan (1,000 writes/day): dedup, delivery state and message tracking now write D1 rows instead (D1 Free allows 100,000 rows written/day).
|
||||
- R2's free tier (10 GB-month storage, 1M Class A ops/month) comfortably absorbs payload parking without touching the KV write quota.
|
||||
+6
-6
@@ -2,11 +2,11 @@
|
||||
|
||||
WebHooker runs four maintenance tasks on the scheduled trigger (`*/5 * * * *`, every 5 minutes). They only run on the deployed worker (Cloudflare cron); local `wrangler dev` runs them when triggered via `wrangler dev --test-scheduled`.
|
||||
|
||||
| Task | Purpose |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `discord-sync` | Registers the Discord slash/context-menu commands: per-guild (instant) and globally (24h dedup, ~1h propagation) |
|
||||
| `telegram-sync` | Calls `setWebhook` to `{BASE_URL}/telegram/webhook` (with `TELEGRAM_WEBHOOK_SECRET` as `secret_token` when set) |
|
||||
| `audit-prune` | Deletes `audit_logs` entries older than `AUDIT_RETENTION_DAYS` (default 90) |
|
||||
| `storage-prune` | Deletes expired `dedup_keys` rows, `delivery_state` rows older than 7 days and `message_tracking` rows older than 30 days |
|
||||
| Task | Purpose |
|
||||
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `discord-sync` | Registers the Discord slash/context-menu commands per guild (instant; at most 30 API calls per run, resuming where the last run stopped) and globally (~1h propagation); registered again when the command definitions change |
|
||||
| `telegram-sync` | Calls `setWebhook` to `{BASE_URL}/telegram/webhook` with `TELEGRAM_WEBHOOK_SECRET` (or a secret derived from `TELEGRAM_TOKEN`) as `secret_token` — only when the registration changed, and once a day |
|
||||
| `audit-prune` | Deletes `audit_logs` entries older than `AUDIT_RETENTION_DAYS` (default 90) |
|
||||
| `storage-prune` | Deletes expired `dedup_keys` rows, `delivery_state` rows older than 7 days, `message_tracking` rows older than 30 days and orphaned R2 payloads |
|
||||
|
||||
There is nothing to configure beyond the secrets the tasks use (`DISCORD_TOKEN`, `DISCORD_APPLICATION_ID`, `TELEGRAM_TOKEN`, `BASE_URL`, `AUDIT_RETENTION_DAYS`).
|
||||
+11
-11
@@ -40,7 +40,7 @@ POST /api/comment
|
||||
| `issueNumber` | number | 是 | 议题或 PR 编号 |
|
||||
| `body` | string | 是 | 评论内容(支持 Markdown) |
|
||||
|
||||
**响应:** `200` 与 GitHub API 响应。
|
||||
**响应:** `200 { "ok": true }`。
|
||||
|
||||
### 合并拉取请求
|
||||
|
||||
@@ -68,7 +68,7 @@ POST /api/merge
|
||||
| `pullNumber` | number | 是 | 拉取请求编号 |
|
||||
| `method` | string | 否 | `merge`、`squash` 或 `rebase`(默认:`squash`) |
|
||||
|
||||
**响应:** `200` 与 GitHub 合并响应。
|
||||
**响应:** `200 { "ok": true }`。
|
||||
|
||||
### 关闭拉取请求
|
||||
|
||||
@@ -94,7 +94,7 @@ POST /api/close
|
||||
| `repo` | string | 是 | 仓库名称 |
|
||||
| `pullNumber` | number | 是 | 拉取请求编号 |
|
||||
|
||||
**响应:** `200` 与 GitHub 更新响应。
|
||||
**响应:** `200 { "ok": true }`。
|
||||
|
||||
### 添加反应
|
||||
|
||||
@@ -102,7 +102,7 @@ POST /api/close
|
||||
POST /api/react
|
||||
```
|
||||
|
||||
为议题或评论添加表情反应。
|
||||
为议题或拉取请求添加表情反应(不支持评论)。
|
||||
|
||||
**请求体:**
|
||||
|
||||
@@ -115,18 +115,18 @@ POST /api/react
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ------------- | ------ | ---- | ------------------- |
|
||||
| `owner` | string | 是 | 仓库所有者 |
|
||||
| `repo` | string | 是 | 仓库名称 |
|
||||
| `issueNumber` | number | 是 | 议题、PR 或评论编号 |
|
||||
| `reaction` | string | 是 | 反应类型(见下方) |
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ------------- | ------ | ---- | ------------------ |
|
||||
| `owner` | string | 是 | 仓库所有者 |
|
||||
| `repo` | string | 是 | 仓库名称 |
|
||||
| `issueNumber` | number | 是 | 议题或 PR 编号 |
|
||||
| `reaction` | string | 是 | 反应类型(见下方) |
|
||||
|
||||
**反应类型:**
|
||||
|
||||
`+1`、`-1`、`laugh`、`confused`、`heart`、`hooray`、`rocket`、`eyes`
|
||||
|
||||
**响应:** `200` 与 GitHub 反应响应。
|
||||
**响应:** `200 { "ok": true }`。
|
||||
|
||||
## 错误响应
|
||||
|
||||
|
||||
+43
-33
@@ -1,46 +1,56 @@
|
||||
# Admin API
|
||||
|
||||
管理端点用于管理路由、分组、成员、邀请、webhook 密钥、发送日志与审计日志。它们需要会话 Cookie,可通过 `GET /admin/login`(GitHub OAuth)获取;登录用户必须列在 `ADMIN_USER_IDS` 中,或管理某个分组。仅限本地开发,精确设置 `DEBUG_MODE=true` 会跳过认证并授予完整权限,绝不能在部署环境启用。设置方法见[配置 → Web 控制台](../guide/configuration.md#web-ui)。
|
||||
管理端点用于管理路由、分组、成员、邀请、webhook 密钥、发送日志与审计日志。它们需要会话 Cookie,可通过 `GET /admin/login`(GitHub OAuth)获取;登录用户必须列在 `ADMIN_USER_IDS` 中,或管理某个分组。仅限本地开发,精确设置 `DEBUG_MODE=true` 会跳过认证并授予完整权限,绝不能在部署环境启用。设置方法见[配置 → Web 控制台](../guide/configuration.md#web-控制台)。
|
||||
|
||||
控制台本身在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`)。
|
||||
|
||||
## 端点
|
||||
|
||||
| 端点 | 说明 |
|
||||
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `GET /admin` | 配置控制台页面 |
|
||||
| `GET /admin/login` | 开始管理员登录(GitHub OAuth) |
|
||||
| `GET /admin/logout` | 退出登录并销毁会话 |
|
||||
| `GET /admin/invite?token=…` | 接受分组邀请(浏览器页面) |
|
||||
| `GET /admin/api/me` | 当前会话、权限范围、分组与角色 |
|
||||
| `GET /admin/api/routes` | 列出路由(按权限过滤) |
|
||||
| `PUT /admin/api/routes` | 替换路由(按分组 owner/admin) |
|
||||
| `GET /admin/api/groups` | 列出分组 + 当前用户在各分组的角色 |
|
||||
| `PUT /admin/api/groups` | 替换分组(超级管理员全部;owner 仅自己的) |
|
||||
| `GET /admin/api/groups/:id/routes` | 列出某分组的路由 |
|
||||
| `PUT /admin/api/groups/:id/routes` | 替换某分组的路由(owner/admin) |
|
||||
| `GET /admin/api/groups/:id/fragments` | 列出某分组的命名过滤器片段 |
|
||||
| `PUT /admin/api/groups/:id/fragments` | 替换某分组的命名过滤器片段(owner/admin) |
|
||||
| `PUT /admin/api/groups/:id/rename` | 重命名分组(owner);路由、webhook secret 与邀请自动跟随 |
|
||||
| `GET /admin/api/groups/:id/invites` | 列出待处理的邀请(owner) |
|
||||
| `POST /admin/api/groups/:id/invites` | 创建邀请链接(owner) |
|
||||
| `DELETE /admin/api/invites/:token` | 撤销邀请(owner) |
|
||||
| `GET /admin/api/groups/:id/webhook` | 分组 webhook 端点信息(owner) |
|
||||
| `POST /admin/api/groups/:id/webhook/regenerate` | 生成/重新生成分组 webhook secret(owner) |
|
||||
| `DELETE /admin/api/groups/:id/webhook` | 停用分组 webhook 入口(owner) |
|
||||
| `GET /admin/api/logs` | 发送日志(按可访问的路由过滤) |
|
||||
| `GET /admin/api/logs/:id` | 单条发送日志(按权限过滤) |
|
||||
| `GET /admin/api/audit` | 审计日志(按可访问的分组过滤) |
|
||||
| `GET /admin/api/metrics` | 投递统计(总计、失败率、按平台/事件/状态、最近失败);可选 `?groupId=` 按分组过滤;非超管按可访问分组过滤最近失败 |
|
||||
| `GET /admin/api/delivery/:deliveryId` | 单次投递的全部发送日志(按分组过滤) |
|
||||
| `POST /admin/api/test-match` | 无状态过滤器试匹配——将过滤器节点对粘贴的 JSON 载荷求值(不存储任何事件) |
|
||||
| 端点 | 说明 |
|
||||
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `GET /admin` | 配置控制台页面 |
|
||||
| `GET /admin/login` | 开始管理员登录(GitHub OAuth) |
|
||||
| `GET /admin/logout` | 退出登录并销毁会话 |
|
||||
| `GET /admin/invite?token=…` | 接受分组邀请(浏览器页面) |
|
||||
| `GET /admin/api/me` | 当前会话、权限范围、分组与角色 |
|
||||
| `GET /admin/api/routes` | 列出路由(按权限过滤) |
|
||||
| `PUT /admin/api/routes` | 替换路由(按分组 owner/admin) |
|
||||
| `GET /admin/api/groups` | 列出分组(各带 `revision`)+ 当前用户在各分组的角色,以及整个列表的 `revision` |
|
||||
| `PUT /admin/api/groups` | 批量写入(旧接口):超级管理员替换全部分组,owner 修改/删除自己的;只写入有变化的分组 |
|
||||
| `POST /admin/api/groups` | 创建单个分组(超级管理员)——请求体 `{ group }`;id 已存在或近期用过时返回 `409` |
|
||||
| `PUT /admin/api/groups/:id` | 更新单个分组(owner)——请求体 `{ group }`;`revision` 过期时返回 `409` |
|
||||
| `DELETE /admin/api/groups/:id` | 删除单个分组及其路由与片段(owner)——查询参数带上确认时的 `revision`、`routesRevision` 与 `version`;之后有任何变化时返回 `409` |
|
||||
| `GET /admin/api/groups/:id/routes` | 列出某分组的路由,附带列表的 `revision`、分组 `version` 与 `unreadable` |
|
||||
| `PUT /admin/api/groups/:id/routes` | 替换某分组的路由(owner/admin)——提交的 `revision` 过期时返回 `409` |
|
||||
| `GET /admin/api/groups/:id/fragments` | 列出某分组的命名过滤器片段,附带列表的 `revision` |
|
||||
| `PUT /admin/api/groups/:id/fragments` | 替换某分组的命名过滤器片段(owner/admin)——请求体 `{ fragments, revision? }`;`revision` 过期时返回 `409` |
|
||||
| `PUT /admin/api/groups/:id/rename` | 重命名分组(owner)——请求体 `{ newId, revision? }`;路由、片段与历史在同一事务中迁移,密钥与邀请随分组保留,旧 id 保留若干天不可复用 |
|
||||
| `GET /admin/api/groups/:id/invites` | 列出待处理的邀请(owner) |
|
||||
| `POST /admin/api/groups/:id/invites` | 创建邀请链接(owner)——请求体 `{ role, note? }`(`role` 为 `admin` 或 `viewer`) |
|
||||
| `DELETE /admin/api/invites/:token` | 撤销邀请(owner) |
|
||||
| `GET /admin/api/groups/:id/webhook` | 分组 webhook 端点信息(owner) |
|
||||
| `POST /admin/api/groups/:id/webhook/regenerate` | 生成/重新生成分组 webhook secret(owner) |
|
||||
| `DELETE /admin/api/groups/:id/webhook` | 停用分组 webhook 入口(owner) |
|
||||
| `GET /admin/api/logs` | 可访问分组的发送日志(在 SQL 中先过滤再取 limit) |
|
||||
| `GET /admin/api/logs/:id` | 单条发送日志(按权限过滤) |
|
||||
| `GET /admin/api/audit` | 可访问分组的审计日志(在 SQL 中先过滤再取 limit) |
|
||||
| `GET /admin/api/metrics` | 投递统计(总计、失败率、按平台/事件/状态、最近失败);可选 `?groupId=` 按分组过滤;所有汇总都只统计可访问的分组 |
|
||||
| `GET /admin/api/delivery/:deliveryId` | 单次投递中属于可访问分组的发送记录;可选 `?groupId=`(两个分组的发送方可能使用相同的投递 id) |
|
||||
| `POST /admin/api/test-match` | 无状态过滤器试匹配——将过滤器节点对粘贴的 JSON 载荷求值(不存储任何事件) |
|
||||
|
||||
## 校验
|
||||
|
||||
- `PUT /admin/api/routes` — 请求体为 `{ "routes": Route[] }`;校验每条路由(id 格式、组内唯一 id、name、enabled、groupId、过滤器——**仅 `fallback` 路由允许空过滤器**——可选的 `discordRoleIds`(身份组 id 字符串列表)、平台感知的 targets:Discord 需 `target.channelId`,Telegram 需 `target.chatId`)并持久化到 D1 `d1_routes`。返回 `200 { ok, count }` 或 `400 { error }` / `401 { error }` / `403 { error }`。未变更的路由跳过完整校验。路由过滤器支持 `field` 类型(指向 `payload` 的 JSONPath `path`,数组展开后任一元素匹配)与 12 个 `op` 操作符(`eq` 默认 / `ne` / `contains` / `startsWith` / `endsWith` / `regex` / `gt` / `gte` / `lt` / `lte` / `in` / `exists`);嵌套 `ast`(`all` / `any` / `not`)存在时优先于 `filters`。
|
||||
- `PUT /admin/api/groups` — 校验分组 id、成员角色(至少一个 `owner`)、`providers`(`github` / `gitea`)与 `installationId`。
|
||||
- `PUT /admin/api/routes` — 请求体为 `{ "routes": Route[] }`;校验每条路由(id 格式、组内唯一 id、name、enabled、groupId、过滤器——必须是数组,**仅 `fallback` 路由或带有效 `ast` 时允许为空**;匹配器无法编译的模式(超过 200 个字符,或反向引用、前后瞻等 RE2 不支持的语法)会被拒绝;扁平 `filters` 只能是叶子条件(`all`/`any`/`not` 应放在 `ast` 中);`keyword` 只支持默认的 `eq`;`exists` 可省略 `match`——可选的 `discordRoleIds`(最多 50 个数字形式的 Discord 身份组 id)、平台感知的 targets:Discord 需 `target.channelId`,Telegram / 飞书需 `target.chatId`,id 规则与重复目的地检查见[路由与目标](../guide/routes))并持久化到 D1 `d1_routes`,只重写路由有变化的分组。非超级管理员把目标指向其他分组正在使用的频道时返回 `403`。返回 `200 { ok, count }` 或 `400 { error }` / `401 { error }` / `403 { error }`。未变更的路由跳过完整校验。路由过滤器支持 `field` 类型(指向 `payload` 的 JSONPath `path`,数组展开后任一元素匹配)与 12 个 `op` 操作符(`eq` 默认 / `ne` / `contains` / `startsWith` / `endsWith` / `regex` / `gt` / `gte` / `lt` / `lte` / `in` / `exists`);嵌套 `ast`(`all` / `any` / `not`)存在时优先于 `filters`。
|
||||
- `PUT /admin/api/groups` / `POST /admin/api/groups` / `PUT /admin/api/groups/:id` — 校验分组 id、`members`(或旧字段 `adminIds`;非空的 `members` 列表至少要有一个 `owner`)、`forgeSources`(最多 20 项,`name` 最多 50 个字符,类型 + 主机不能重复)、`providers`(`github` / `gitea` / `custom`)与 `installationId`;未知字段会被丢弃。来源隔离字段 `owners`、`installationId`、`isolated` 仅超级管理员可改:owner 写入时保留其已存储的值。新成员的登录名会用写入者的 token 解析为 GitHub user id;服务端字段(`instance`、webhook 密钥、成员 user id)客户端无法设置。
|
||||
- 每次写入都会在事务内再次核对写入者的角色:在角色被撤销之前通过鉴权的请求会被拒绝(路由/片段写入返回 `409`,分组写入返回 `403`)。
|
||||
- 乐观并发——API 返回的每个列表或分组都带有 `revision`。写入时把它带回(`group.revision`,或与 `routes` / `fragments` / `newId` 并列的 `revision`,或批量分组写入的列表 `revision`),若数据在加载后已被他人修改,服务端以 `409` 拒绝,而不是覆盖较新的修改。不带 `revision` 的写入照旧执行。批量分组写入中原样回传、未被编辑的分组不会被写入。
|
||||
- `PUT /admin/api/groups/:id/routes` — 可选 `discardUnreadable: true`,用于替换无法读取的已存路由(否则分组含此类路由时保存会被拒绝)。
|
||||
- `PUT /admin/api/routes` — 可选地提交 `revisions`(`GET /admin/api/routes` 返回的按分组映射):原样回传、未编辑的分组不会写入,客户端从未加载的分组不会被改动,已编辑的分组必须仍处于加载时的 revision(否则 `409`)。每个分组在各自带保护的事务中写入。
|
||||
- `PUT /admin/api/groups/:id/rename` — 可选 `revision`;返回 `{ ok, id, group, revision }`(改名后的分组及其新 revision)。以 `inst-` 或 `u-` 开头的 id 仅超级管理员可用。
|
||||
- `DELETE /admin/api/groups/:id` — 需带上确认时看到的 `revision`、`routesRevision` 与 `version`(缺少时返回 `400`;分组、其路由或片段有变化,或含无法读取的路由时返回 `409`)。同时撤销该分组的邀请与 webhook secret,解除其发送日志与审计记录的分组归属(之后仅超级管理员可见),并在若干天内保留该 id 不可复用,避免排队中的投递落到复用该 id 的新分组。
|
||||
- `POST /admin/api/groups/:id/webhook/regenerate` — 返回 `{ ok, url, secret, hasSecret }`;密钥只在这次响应中出现。
|
||||
- `POST /admin/api/test-match` — 请求体 `{ "node": FilterNode | "filters": Filter[], "event"?: string, "payload": object }`;在内存中求值并返回 `{ matched, explanation }`,不持久化任何内容。
|
||||
- `GET/PUT /admin/api/groups/:id/fragments` — 命名过滤器片段(`{ id, groupId, name, node }`)存储于 D1 `d1_fragments`;编辑器在插入时将片段的 `node` 内联进路由的 `ast`(匹配器从不解析片段引用)。`PUT` 全量替换该分组的片段并返回 `200 { ok, count }`。
|
||||
- 上限:每个实例最多 200 条路由与 100 个分组。
|
||||
- `GET/PUT /admin/api/groups/:id/fragments` — 命名过滤器片段(`{ id, groupId, name, node }`)存储于 D1 `d1_fragments`;编辑器在插入时将片段的 `node` 内联进路由的 `ast`(匹配器从不解析片段引用)。`PUT` 全量替换该分组的片段(最多 200 个)并返回 `200 { ok, count }`。
|
||||
- 上限:单次保存最多 200 条路由、每个分组最多 200 个片段,批量保存分组单次最多 100 个。
|
||||
|
||||
模式:见[路由与目标](../guide/routes)、[分组与访问控制](../guide/groups)。
|
||||
+14
-5
@@ -42,12 +42,21 @@ GitHub 授权后重定向到此地址。将 code 交换为访问令牌并存储
|
||||
| `code` | 授权码 |
|
||||
| `state` | CSRF 保护的状态参数 |
|
||||
|
||||
在浏览器中发起(`GET /auth/github`)的登录,回调时必须带回发起时设置的 `wh_oauth_state` Cookie,否则返回 `400 Invalid or expired state`。
|
||||
|
||||
**响应:**
|
||||
|
||||
- **浏览器流程**(`Accept: text/html`):设置管理员会话 Cookie,然后重定向到 `redirect` 目标;无管理权限的用户被重定向到 `/admin?error=forbidden`。
|
||||
- **JSON 流程**:返回 `{ "userId": "...", "login": "...", "redirectTo": "..." }`。
|
||||
- **Discord 绑定流程**(以未决的 `discordUserId` 启动时):将 Discord 用户绑定到此 GitHub 账号,返回 `{ "ok": true, "discordUserId": "...", "login": "..." }`——浏览器中则显示成功页面。
|
||||
- **Telegram 绑定流程**(以未决的 `telegramUserId` 启动时):将 Telegram 用户绑定到此 GitHub 账号,返回 `{ "ok": true, "telegramUserId": "...", "login": "..." }`,并向未决的 `telegramChatId` 发送确认消息。
|
||||
- **机器人账号绑定**(由 Discord、Telegram 或飞书的 `/gh login` 发起):此时还不会绑定。回调返回一个同时列出 GitHub 账号与聊天账号的 HTML 确认页;只有 GitHub 用户在该页确认后才写入绑定。
|
||||
|
||||
### 确认机器人账号绑定
|
||||
|
||||
```
|
||||
POST /auth/github/link
|
||||
```
|
||||
|
||||
由确认页提交(表单字段 `nonce`,10 分钟内有效、只能使用一次)。把聊天账号绑定到 GitHub 账号并返回 HTML 结果页;未知、过期或已使用的 `nonce` 返回 `400`("链接已失效")。
|
||||
|
||||
### 撤销 Token
|
||||
|
||||
@@ -55,7 +64,7 @@ GitHub 授权后重定向到此地址。将 code 交换为访问令牌并存储
|
||||
DELETE /auth/token/:userId
|
||||
```
|
||||
|
||||
删除用户存储的 OAuth Token。
|
||||
删除用户存储的 OAuth Token(本人的,或超级管理员删除任意用户的)。撤销会记录在 D1 中,即使 KV 尚未同步,Token 也会在所有节点立即失效。
|
||||
|
||||
**响应:**
|
||||
|
||||
@@ -74,11 +83,11 @@ Token 以键模式 `token:{userId}` 存储在 KV 中:
|
||||
"userId": "12345",
|
||||
"accessToken": "gho_...",
|
||||
"expiresAt": 1735689600000,
|
||||
"refreshToken": "..."
|
||||
"live": true
|
||||
}
|
||||
```
|
||||
|
||||
`expiresAt` 是毫秒级 Unix 时间戳。KV 条目在 Token 有效期的 90% 时过期(至少 60 秒)。反向索引 `token-reverse:{sha256 of token}` 将访问令牌映射回用户 id,使 Bearer 鉴权的端点能解析调用者。与 GitHub 账号绑定的 Discord 用户存储在 D1 的 `discord_links` 表中;Telegram 用户存储在 D1 的 `telegram_links` 表中。
|
||||
`expiresAt` 是毫秒级 Unix 时间戳。保存的 Token 可使用 10 小时,KV 条目在 9 小时(90%)后过期。Token 不会自动刷新——过期后需要重新登录(或重新执行 `/gh login`)。`live` 表示该 Token 在 D1 中有"当前令牌"记录:重新登录或退出登录会让之前的 Token 在所有节点立即失效。反向索引 `token-reverse:{sha256 of token}` 将访问令牌映射回用户 id,使 Bearer 鉴权的端点能解析调用者。与 GitHub 账号绑定的 Discord 用户存储在 D1 的 `discord_links` 表中;Telegram 用户存储在 D1 的 `telegram_links` 表中。
|
||||
|
||||
## 使用 Token
|
||||
|
||||
|
||||
+17
-11
@@ -17,9 +17,11 @@ https://your-worker.workers.dev
|
||||
| `POST` | `/webhook/:groupId` | 分组 secret | 分组级 webhook 入口(只触发该分组的路由) |
|
||||
| `POST` | `/discord/interactions` | Ed25519 签名 | Discord 交互(斜杠命令、按钮、modal) |
|
||||
| `POST` | `/telegram/webhook` | Secret token | Telegram 更新(bot `/gh` 命令) |
|
||||
| `POST` | `/feishu/webhook` | 飞书签名 | 飞书事件(bot `/gh` 命令、卡片按钮) |
|
||||
| `GET` | `/api/richheader` | 无 | 用于 Telegram 头像链接预览卡片的 Open Graph 页面 |
|
||||
| `GET` | `/auth/github` | 无 | 启动 GitHub OAuth 流程 |
|
||||
| `GET` | `/auth/github/callback` | 无 | OAuth 回调 |
|
||||
| `POST` | `/auth/github/link` | 绑定 nonce | 确认机器人账号绑定(由确认页提交) |
|
||||
| `GET` | `/auth/github/install` | 管理员会话 | 安装后选择页:将安装绑定到某个分组 |
|
||||
| `POST` | `/auth/github/install/bind` | 管理员会话 | 执行选定的安装绑定 |
|
||||
| `DELETE` | `/auth/token/:userId` | 管理员会话 | 撤销用户 Token |
|
||||
@@ -36,7 +38,7 @@ https://your-worker.workers.dev
|
||||
|
||||
## 管理控制台
|
||||
|
||||
参见[配置 → Web 控制台](../guide/configuration.md#web-ui)了解设置方法,管理端点的完整参考见 [Admin API](./admin)。管理端点需要会话 Cookie,可通过 `GET /admin/login`(GitHub OAuth)获取;登录用户必须列在 `ADMIN_USER_IDS` 中,或管理某个分组。仅限本地开发,精确设置 `DEBUG_MODE=true` 会跳过认证并授予完整权限,绝不能在部署环境启用。
|
||||
参见[配置 → Web 控制台](../guide/configuration.md#web-控制台)了解设置方法,管理端点的完整参考见 [Admin API](./admin)。管理端点需要会话 Cookie,可通过 `GET /admin/login`(GitHub OAuth)获取;登录用户必须列在 `ADMIN_USER_IDS` 中,或管理某个分组。仅限本地开发,精确设置 `DEBUG_MODE=true` 会跳过认证并授予完整权限,绝不能在部署环境启用。
|
||||
|
||||
## 健康检查
|
||||
|
||||
@@ -74,27 +76,31 @@ POST /webhook
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true
|
||||
"ok": true,
|
||||
"requestId": "…"
|
||||
}
|
||||
```
|
||||
|
||||
当 `X-GitHub-Delivery` 存在且同一投递在最近 5 分钟内已被处理时,Worker 返回 `200 { "ok": true, "duplicate": true }`,不再重复分发。
|
||||
`requestId` 是写入 worker 日志的关联 id。内联分发(无队列)时,目标永久失败的事件仍返回 `200`,并附带 `"failed": true`。
|
||||
|
||||
当 `X-GitHub-Delivery` 存在且同一投递已被接受时,Worker 返回 `200 { "ok": true, "duplicate": true }`,不再重复分发;第一份仍在处理中时,重投会收到 `503`,由发送方稍后重试。
|
||||
|
||||
**错误响应:**
|
||||
|
||||
| 状态码 | 响应体 | 原因 |
|
||||
| ------ | -------------------------------- | ---------------------------- |
|
||||
| `401` | `{"error": "Invalid signature"}` | 签名验证失败 |
|
||||
| `400` | `{"error": "Invalid event"}` | 缺少事件头或格式错误的请求体 |
|
||||
| `413` | `{"error": "Request too large"}` | 请求体超过 1MB 限制 |
|
||||
| 状态码 | 响应体 | 原因 |
|
||||
| ------ | -------------------------------- | ---------------------------------------------------------------------------------------- |
|
||||
| `401` | `{"error": "Invalid signature"}` | 签名验证失败 |
|
||||
| `400` | `{"error": "Invalid event"}` | 缺少事件头或格式错误的请求体 |
|
||||
| `413` | `{"error": "Request too large"}` | 请求体超过 1MB 限制 |
|
||||
| `503` | `{"error": …}` | 尚未接受——队列拒收、目标暂时失败(内联分发)、同一投递仍在处理,或存储故障;发送方应重投 |
|
||||
|
||||
### 分组级 Webhook(`POST /webhook/:groupId`)
|
||||
|
||||
使用**分组的** secret(KV `tenant:{groupId}`,在控制台「Webhook 入口」面板生成)验签,并且只分发到该分组的路由。支持 GitHub(`X-Hub-Signature-256`)、Gitea(`X-Gitea-Signature`)和自定义(`X-WebHooker-Signature`)发送方。分组不存在或未配置 secret 时返回 `404`。
|
||||
使用**分组的** secret(与分组一起存于 D1,在控制台「Webhook 入口」面板生成)验签,并且只分发到该分组的路由。支持 GitHub(`X-Hub-Signature-256`)、Gitea(`X-Gitea-Signature`)和自定义(`X-WebHooker-Signature`)发送方。分组不存在或未配置 secret 时返回 `404`,分组存储的配置无法读取时返回 `503`。
|
||||
|
||||
### 自定义 Webhook
|
||||
|
||||
任意 JSON 载荷用 `X-WebHooker-Signature: sha256=<hex>`(对原始 body 的 HMAC-SHA256,使用分组或全局 secret)签名后即可成为 `custom` 事件。用 `event: custom` 过滤器的路由接收。可选的 `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` 请求头启用重放防护(对 `{timestamp}.{nonce}.{body}` 签名、±5 分钟窗口、nonce 去重)。载荷格式见[配置 → 自定义 Webhook](../guide/ingress.md#自定义-webhook)。
|
||||
任意 JSON 对象用 `X-WebHooker-Signature: sha256=<hex>`(对原始 body 的 HMAC-SHA256,使用分组或全局 secret)签名后即可成为 `custom` 事件。用 `event: custom` 过滤器的路由接收。可选的 `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` 请求头启用重放防护(对 `{timestamp}.{nonce}.{body}` 签名、±5 分钟窗口、nonce 去重)。载荷格式见[配置 → 自定义 Webhook](../guide/ingress.md#自定义-webhook)。
|
||||
|
||||
### GitHub App 安装事件
|
||||
|
||||
@@ -109,7 +115,7 @@ POST /webhook
|
||||
|
||||
## 错误格式
|
||||
|
||||
所有错误响应都遵循以下格式:
|
||||
webhook、管理、OAuth 与 Actions 端点的错误响应遵循以下格式;机器人回调(`/discord/interactions`、`/telegram/webhook`、`/feishu/webhook`)的错误响应为纯文本:
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -25,22 +25,24 @@ app/ # Vue 3 UI(Nuxt app 目录)
|
||||
server/ # Nitro 服务器(H3 处理器位于 server/routes/)
|
||||
├── routes/ # /health、/webhook[/:groupId]、/discord/interactions、/telegram/webhook、
|
||||
│ # /auth/github*、/admin/{login,logout,invite,api/**}、/api/{comment,merge,close,react,richheader}
|
||||
├── tasks/ # 定时任务 (cron */5):discord-sync、telegram-sync、audit-prune
|
||||
├── tasks/ # 定时任务 (cron */5):discord-sync、telegram-sync、audit-prune、storage-prune
|
||||
├── error-handler.ts # JSON 错误处理器
|
||||
└── lib/
|
||||
├── types.ts # Env、Config、Route、Filter、Group、WebhookEvent、NeutralMessage
|
||||
├── config.ts # 从 KV 加载路由(未设置时返回 []),从 env 构建 Config
|
||||
├── config.ts # 绑定 D1 配置存储,读取路由/分组(最新或缓存),从 env 构建 Config
|
||||
├── core/
|
||||
│ └── dispatch.ts # 平台中立分发:匹配路由 → formatEvent → getDriver().send/edit
|
||||
├── events/ # 与提供方无关的路由匹配
|
||||
│ └── match.ts # matchRoute、eventOwners、extractBranch、关键词过滤
|
||||
│ ├── match.ts # matchRoute、eventOwners
|
||||
│ └── filter-ast.ts # 过滤器求值(扁平过滤器 + all/any/not AST)、extractBranch、关键词搜索、RE2 模式
|
||||
├── providers/ # Forge webhook 提供方(验证 + 解析/归一化)
|
||||
│ ├── types.ts # Provider 接口(matches/verify/parse)
|
||||
│ ├── index.ts # detectProvider() 注册表(github、gitea、custom)
|
||||
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
||||
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature(归一化载荷)
|
||||
├── formatters/ # 平台中立格式化器(产出 NeutralMessage)
|
||||
│ ├── index.ts # formatEvent:28 事件 switch + custom → NeutralMessage + re-export
|
||||
│ ├── index.ts # formatEvent:构建上下文,从注册表找到格式化器 → NeutralMessage
|
||||
│ ├── registry.ts # eventFormatters[]:事件名 → 格式化器
|
||||
│ ├── colors.ts # GITHUB_COLORS + WORKFLOW_CONCLUSION_EMOJI
|
||||
│ ├── helpers.ts # emojiPrefix、T、buildMessage、commitLink/branchLink/tagLink
|
||||
│ └── *.ts # push、pull-request、issues、comments、workflow、release、create、repo、
|
||||
@@ -48,7 +50,7 @@ server/ # Nitro 服务器(H3 处理器位于 server/routes/
|
||||
│ # discussion、repository、security、generic、ping、custom
|
||||
├── drivers/ # 平台驱动(可插拔推送目标)
|
||||
│ ├── types.ts # PlatformDriver 接口 + SendResult(send + edit)
|
||||
│ ├── index.ts # getDriver() 注册表(discord + telegram)
|
||||
│ ├── index.ts # getDriver() 注册表(discord + telegram + feishu)
|
||||
│ ├── discord/ # index.ts (驱动)、render.ts (NeutralMessage → embed)、
|
||||
│ │ # rest.ts、interactions.ts、commands.ts
|
||||
│ └── telegram/ # index.ts (驱动)、render.ts (NeutralMessage → Telegram HTML)、
|
||||
@@ -127,8 +129,8 @@ curl http://localhost:8787/health
|
||||
1. 将事件类型添加到 `server/lib/formatters/colors.ts` 中的 `GITHUB_COLORS`(如果需要新颜色)
|
||||
2. 将操作标签添加到 `server/lib/lib/locales/en.ts` 与 `server/lib/lib/locales/zh.ts` 的翻译字典(如果有新操作)
|
||||
3. 在 `server/lib/formatters/` 中创建 `formatEventType` 函数
|
||||
4. 将 case 添加到 `server/lib/formatters/index.ts` 中的 `formatEvent` switch 语句
|
||||
5. 如果事件包含分支信息,更新 `server/lib/events/match.ts` 中的 `extractBranch`
|
||||
4. 在 `server/lib/formatters/registry.ts` 的 `eventFormatters` 中注册(`{ events: ["your_event"], format: (c) => … }`)
|
||||
5. 如果事件包含分支信息,更新 `server/lib/events/filter-ast.ts` 中的 `extractBranch`
|
||||
6. 将事件添加到 `docs/events/supported.md` 与 `docs/zh/events/supported.md` 文档中
|
||||
7. 将事件添加到 README(`README.md` 与 `README.zh.md`)的事件表与 GitHub App 事件订阅列表中
|
||||
8. 在 GitHub App 设置中订阅该事件
|
||||
|
||||
+11
-10
@@ -42,7 +42,8 @@ WebHooker 支持 28 种 GitHub webhook 事件类型,每种都有专用的格
|
||||
|
||||
| 颜色 | 事件 |
|
||||
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| 绿色 (`#2da44e`) | push、PR 打开/可审查、issue 打开、工作流成功、发布已发布、检查成功、审查已批准、部署成功、成员添加、里程碑关闭、讨论已回答 |
|
||||
| 绿色 (`#2da44e`) | PR 打开/可审查、issue 打开、工作流成功、发布已发布、检查成功、审查已批准、部署成功、成员添加、里程碑关闭、讨论已回答 |
|
||||
| 绿色 (`#2ea44f`) | push |
|
||||
| 红色 (`#f85149`) | PR 关闭、issue 关闭、工作流失败、发布已删除、delete、检查失败、审查请求修改、部署失败、成员移除、代码扫描/Dependabot 严重与高危 |
|
||||
| 紫色 (`#8957e5`) | PR 合并、label、discussion |
|
||||
| 蓝色 (`#1f6feb`) | PR(其他操作)、issue 重新打开、fork、里程碑打开 |
|
||||
@@ -60,7 +61,7 @@ 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` / `check_run` 事件(queued → running → success/failure)只发送一条消息,后续每个阶段会**原地编辑**该消息,而不是发送新消息。每次编辑都按最新事件重新渲染整条消息。检查套件、部署(及其状态)、issue 评论、PR 审核与审核评论也以同样方式原地编辑。Discord(`editMessage`)、Telegram(`editMessageText` / `editMessageCaption`)与飞书均支持。`check_run` 以检查套件(或 App)+ check 名 + commit SHA 追踪(回退到 run id),因此每个阶段都会换新 run id 的提供方(例如 Cloudflare Pages)仍会编辑同一条消息,而不同 workflow 或 App 的同名检查各自独立。较早的阶段不会覆盖较新的阶段,已删除的评论与已撤销的审核会保持为该状态。
|
||||
|
||||
`workflow_run` 消息还会附带带颜色的 **Jobs** 明细。由于 webhook 载荷本身不含作业列表(只有 `jobs_url`),Worker 会从 GitHub API 拉取——配置了 `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 时用 GitHub App 安装令牌鉴权,否则匿名请求(公开仓库)。因此 App 需要 **Actions: read** 仓库权限。
|
||||
|
||||
@@ -68,11 +69,11 @@ WebHooker 支持 28 种 GitHub webhook 事件类型,每种都有专用的格
|
||||
|
||||
实操指南见[过滤器教程](../guide/filters),包含完整示例。
|
||||
|
||||
| 过滤器 | 适用事件 |
|
||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `event` | 所有事件 |
|
||||
| `repo` | 所有事件 |
|
||||
| `actor` | 所有事件 |
|
||||
| `action` | 载荷中包含 `action` 字段的事件 |
|
||||
| `branch` | push、pull_request、pull_request_review、pull_request_review_comment、create、delete、workflow_run、workflow_job、check_suite、deployment、code_scanning_alert |
|
||||
| `keyword` | 所有事件(搜索完整载荷正文) |
|
||||
| 过滤器 | 适用事件 |
|
||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `event` | 所有事件 |
|
||||
| `repo` | 所有事件 |
|
||||
| `actor` | 所有事件 |
|
||||
| `action` | 载荷中包含 `action` 字段的事件 |
|
||||
| `branch` | push、pull_request、pull_request_review、pull_request_review_comment、create、delete、workflow_run、workflow_job、check_run、check_suite、deployment、deployment_status、code_scanning_alert |
|
||||
| `keyword` | 所有事件(搜索完整载荷正文) |
|
||||
@@ -1,23 +1,27 @@
|
||||
# 机器人命令
|
||||
|
||||
[绑定你的 GitHub 账号](#绑定账号)后,即可在 Discord 和 Telegram 上**以本人身份**操作 GitHub——评论使用你自己的 OAuth token 发布,权限由 GitHub 强制校验。若 GitHub 拒绝操作(例如编辑他人的评论),机器人会明确告知。
|
||||
[绑定你的 GitHub 账号](#绑定账号)后,即可在 Discord、Telegram 和飞书上**以本人身份**操作 GitHub——评论使用你自己的 OAuth token 发布,权限由 GitHub 强制校验。若 GitHub 拒绝操作(例如编辑他人的评论),机器人会明确告知。
|
||||
|
||||
## 绑定账号
|
||||
|
||||
使用任何命令前,需先绑定一次 GitHub 账号:
|
||||
使用任何命令前,需先绑定 GitHub 账号。授权有效期为 10 小时,过期后请重新执行 `/gh login`:
|
||||
|
||||
| 平台 | 命令 | 效果 |
|
||||
| -------- | ---------------------------- | --------------------------------------------------- |
|
||||
| Discord | `/gh login` | 返回一条仅你可见的 OAuth 链接,用于授权 GitHub 账号 |
|
||||
| Discord | `/gh logout` | 解除绑定 |
|
||||
| Telegram | `/gh login`(引用一条消息) | 返回 OAuth 链接 |
|
||||
| Telegram | `/gh login`(仅限私聊) | 返回 OAuth 链接 |
|
||||
| Telegram | `/gh logout`(引用一条消息) | 解除绑定 |
|
||||
|
||||
链接保存在服务端(KV),并在 D1 中映射到你的 Discord/Telegram 用户 ID。
|
||||
链接保存在服务端(KV),并在 D1 中映射到你的 Discord/Telegram/飞书用户 ID。
|
||||
|
||||
在 GitHub 授权后,你会看到一个同时显示**双方**账号(你的 GitHub 登录名与发起链接的聊天账号)的确认页;确认之前不会绑定任何东西。若登录并非你本人发起(例如别人把他们的链接转发给你),直接关闭该页面即可。在 Telegram 与飞书中,`/gh login` 只在与机器人的私聊中响应,授权链接不会发到群里。
|
||||
|
||||
每个平台事件只执行一次命令:Telegram 重投的 update、飞书重试的事件或重放的 Discord 交互都不会重复评论、合并或关闭。在调用 GitHub 之前就失败的命令(例如存储错误)会交还给平台,在其重投时再次执行;一旦命令可能已到达 GitHub 就不会再重复——此时如果机器人回复失败,请先到 GitHub 确认,再决定是否重发命令。
|
||||
|
||||
## Discord
|
||||
|
||||
Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任务同步(每 5 分钟):按服务器即时注册,并全局注册(24h 去重,约 1 小时传播)。所有回复均为临时消息(仅你可见)。
|
||||
Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任务同步(每 5 分钟):按服务器即时注册(每轮最多 30 次 Discord API 调用,加入大量服务器的机器人会分几轮补齐),并全局注册(约 1 小时传播)。命令定义变化时两者都会重新注册,全局注册至少每天一次。所有回复均为临时消息(仅你可见)。
|
||||
|
||||
### 评论 issue / PR
|
||||
|
||||
@@ -32,11 +36,11 @@ Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任
|
||||
/gh comment del link:<评论链接> 链接需包含 #issuecomment-<id>
|
||||
```
|
||||
|
||||
`edit` / `del` 需要在 GitHub 上复制具体评论链接(评论 ⋯ 菜单 → **复制链接**)。`add` / `edit` 会打开模态框输入/调整评论内容(edit 会预填)。
|
||||
`edit` / `del` 需要在 GitHub 上复制具体评论链接(评论 ⋯ 菜单 → **复制链接**)。`add` / `edit` 会打开模态框输入/调整评论内容(edit 会预填,上限为 Discord 的 4000 字;更长的评论需到 GitHub 上编辑,避免内容被截断)。如果模态框打开后该评论已在 GitHub 上被修改,保存编辑会被拒绝——请重新打开,以当前内容为基础修改。正文按输入原样提交(保留缩进与换行)。只接受 `https://github.com/...` 链接。
|
||||
|
||||
### 合并 / 关闭 PR
|
||||
|
||||
开放 PR 的通知附带 **合并 / 关闭** 按钮(文案跟随分组的消息语言):
|
||||
github.com 上开放 PR 的通知附带 **合并 / 关闭** 按钮(文案跟随分组的消息语言;Gitea 等其他平台不显示按钮,因为这些操作调用的是 GitHub API):
|
||||
|
||||
- 点击按钮即以你绑定的 GitHub 账号合并(squash)或关闭 PR;权限由 GitHub 强制校验。
|
||||
- 成功后按钮会从通知中移除,结果以临时消息展示。
|
||||
@@ -54,9 +58,13 @@ Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任
|
||||
|
||||
Telegram `/gh` 命令通过**引用一条通知消息**来使用:
|
||||
|
||||
- `/gh login` — 绑定 GitHub 账号(返回 OAuth 链接)
|
||||
- `/gh login` — 绑定 GitHub 账号(仅限与机器人私聊;返回 OAuth 链接)
|
||||
- `/gh logout` — 解除绑定
|
||||
- `/gh comment <文本>` — 引用 issue/PR 通知以本人身份评论
|
||||
- `/gh merge` / `/gh close` — 引用 PR 通知进行合并/关闭
|
||||
|
||||
目标 issue/PR 从你引用的消息(通知嵌入中的链接)解析。命令通过 Telegram webhook(`POST /telegram/webhook`,可用 `TELEGRAM_WEBHOOK_SECRET` 校验)送达。
|
||||
目标 issue/PR 从你引用的消息(通知嵌入中的链接)解析。群聊中也接受 `/gh@你的机器人 …` 的写法(发给其他机器人的命令会被忽略)。评论正文保留换行与缩进。命令通过 Telegram webhook(`POST /telegram/webhook`)送达,该端点始终校验 secret token——`TELEGRAM_WEBHOOK_SECRET`,未设置时使用由 `TELEGRAM_TOKEN` 派生的值。
|
||||
|
||||
## 飞书
|
||||
|
||||
飞书 `/gh` 命令是以 `/gh` 开头(可在前面 @ 机器人)的消息:`/gh login`(仅限私聊)、`/gh logout`、`/gh comment <PR/Issue 链接> <内容>`、`/gh merge <PR 链接>`、`/gh close <PR 链接>`;卡片上也有**合并** / **关闭**按钮。只是在其他位置提到 `/gh` 的消息不算命令。事件订阅见[飞书机器人配置](./deployment#飞书机器人配置)。
|
||||
@@ -27,28 +27,38 @@ WebHooker 的运行需要若干密钥。本地开发时放入 `.dev.vars`,生
|
||||
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
|
||||
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 飞书入站命令与卡片按钮(`POST /feishu/webhook`)需要配置 `FEISHU_ENCRYPT_KEY`
|
||||
> 和/或 `FEISHU_VERIFICATION_TOKEN`(即应用**事件与回调 → 加密策略**中的值)。两者都未设置时,
|
||||
> 该端点拒绝所有回调,因为未经认证的请求可以冒充任意已绑定用户。
|
||||
|
||||
<!-- separate the two alerts (MD028) -->
|
||||
|
||||
> [!NOTE]
|
||||
> `GITHUB_APP_ID` 与 `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)用于 GitHub App **安装流程**
|
||||
> (`/auth/github/install`),通过 App JWT 解析安装所属账号的登录名。两者均为可选——
|
||||
> 未设置时安装页仍可正常使用,但会显示无账号名的匿名 `inst-{installationId}` 分组。
|
||||
> OAuth 流程本身只需要 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`。
|
||||
> (`/auth/github/install`),通过 App JWT 解析安装所属账号——安装流程也借此验证登录用户
|
||||
> 是否有权管理该安装。未设置时只有超级管理员可以绑定安装。OAuth 流程本身只需要
|
||||
> `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`;它申请 `repo` 与 `read:org` 权限范围
|
||||
> (后者用于检查组织管理员身份)。
|
||||
|
||||
### 可选密钥
|
||||
|
||||
| 变量 | 说明 | 默认值 |
|
||||
| --------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------- |
|
||||
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取),交互功能必需 | 未设置时交互返回 401 |
|
||||
| `DISCORD_APPLICATION_ID` | Discord 应用 ID;省略时自动获取 | 自动获取 |
|
||||
| `TELEGRAM_WEBHOOK_SECRET` | `POST /telegram/webhook` 验签密钥(X-Telegram-Bot-Api-Secret-Token) | 未设置时不校验 |
|
||||
| `TELEGRAM_RICH_HEADER_HOST` | 外部 rich-header 服务的基础 URL;未设置时使用内置 `GET /api/richheader` 提供 Telegram 头像卡片 | 内置 `/api/richheader` |
|
||||
| `BASE_URL` | OAuth 回调的公共 URL | `http://localhost:8787` |
|
||||
| `ADMIN_USER_IDS` | 允许访问 WebUI 的 GitHub 用户 ID(或登录名),逗号分隔 | 未设置时 WebUI 关闭 |
|
||||
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证并授予完整权限 | 关闭 |
|
||||
| `ALLOW_SELF_SIGNUP` | 开启(`1`/`true`)后,没有任何分组权限的 GitHub 用户首次登录会自动获得个人分组而非 403 | 关闭 |
|
||||
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数 | `90` |
|
||||
| `NUXT_PUBLIC_DOCS_URL` | 落地页使用的文档站 URL(客户端运行时配置) | 落地页默认值 |
|
||||
| `NUXT_PUBLIC_REPO_URL` | 落地页使用的 GitHub 仓库 URL | 落地页默认值 |
|
||||
| `NUXT_PUBLIC_LEGAL_CONTACT` | `/terms` 与 `/privacy` 页面展示的联系方式 | 未设置时显示占位文本 |
|
||||
| 变量 | 说明 | 默认值 |
|
||||
| --------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------ |
|
||||
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取),交互功能必需 | 未设置时交互返回 401 |
|
||||
| `DISCORD_APPLICATION_ID` | Discord 应用 ID;省略时自动获取 | 自动获取 |
|
||||
| `TELEGRAM_WEBHOOK_SECRET` | `POST /telegram/webhook` 验签密钥(X-Telegram-Bot-Api-Secret-Token) | 由 `TELEGRAM_TOKEN` 派生 |
|
||||
| `FEISHU_ENCRYPT_KEY` | 飞书事件 Encrypt Key:校验 `X-Lark-Signature` 并解密加密回调 | 未设置 |
|
||||
| `FEISHU_VERIFICATION_TOKEN` | 飞书事件 Verification Token:与每个回调中的 token 比对 | 未设置 |
|
||||
| `TELEGRAM_RICH_HEADER_HOST` | 外部 rich-header 服务的基础 URL;未设置时使用内置 `GET /api/richheader` 提供 Telegram 头像卡片 | 内置 `/api/richheader` |
|
||||
| `BASE_URL` | worker 的公网地址,用于 OAuth 回调与 Telegram webhook 同步 | 未设置——生产环境必填 |
|
||||
| `ADMIN_USER_IDS` | 允许访问 WebUI 的 GitHub 用户 ID(或登录名),逗号分隔;建议写数字 ID——登录名会绑定到第一个用它登录的账号 | 未设置时 WebUI 关闭 |
|
||||
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证并授予完整权限 | 关闭 |
|
||||
| `ALLOW_SELF_SIGNUP` | 开启(`1`/`true`)后,没有任何分组权限的 GitHub 用户首次登录会自动获得隔离的个人分组而非 403 | 关闭 |
|
||||
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数 | `90` |
|
||||
| `NUXT_PUBLIC_DOCS_URL` | 落地页使用的文档站 URL(客户端运行时配置) | 落地页默认值 |
|
||||
| `NUXT_PUBLIC_REPO_URL` | 落地页使用的 GitHub 仓库 URL | 落地页默认值 |
|
||||
| `NUXT_PUBLIC_LEGAL_CONTACT` | `/terms` 与 `/privacy` 页面展示的联系方式 | 未设置时显示占位文本 |
|
||||
|
||||
## Web 控制台
|
||||
|
||||
@@ -56,7 +66,7 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
|
||||
|
||||
### 设置
|
||||
|
||||
1. 配置 `ADMIN_USER_IDS`,填写允许管理一切的 GitHub 用户 ID,也支持登录名,例如 `ADMIN_USER_IDS=12345,RhenCloud`。未设置时控制台禁用(除非开启 `ALLOW_SELF_SIGNUP`)。
|
||||
1. 配置 `ADMIN_USER_IDS`,填写允许管理一切的 GitHub 用户 ID,也支持登录名,例如 `ADMIN_USER_IDS=12345,RhenCloud`,但数字 ID 更安全:GitHub 登录名可以改名并被他人注册,登录名会绑定到第一个用它登录的账号。未设置时没有超级管理员:分组成员仍可在控制台管理各自的分组,`ALLOW_SELF_SIGNUP` 会为其他用户创建个人分组。
|
||||
2. 打开 `/admin` 并使用 GitHub 登录。
|
||||
3. 没有任何访问权限的用户会得到 `403`,除非 `ALLOW_SELF_SIGNUP=1`(获得个人分组)或跟随分组[邀请链接](./groups#邀请)。
|
||||
|
||||
@@ -66,7 +76,7 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
|
||||
|
||||
删除类操作——删除路由、分组、过滤条件、片段、目标或来源主机,移除成员,撤销邀请,停用分组 webhook——都会先弹出应用内确认框(从未填写过的空行直接删除)。路由与分组编辑弹窗点击遮罩不会关闭,避免丢失未保存的内容;请用「取消」、✕ 或 <kbd>Esc</kbd> 关闭。
|
||||
|
||||
所有管理端点(`/admin/api/*`)见 [Admin API](../api/admin)。保存的路由和分组会立即持久化到 D1(`d1_routes` / `d1_groups`),并使 KV 缓存失效、刷新配置缓存,下一次 webhook 处理即会生效。
|
||||
所有管理端点(`/admin/api/*`)见 [Admin API](../api/admin)。保存的路由和分组会立即持久化到 D1(`d1_routes` / `d1_groups`);webhook 入口与队列消费者读取最新配置,下一个事件即会生效。
|
||||
|
||||
## 过滤器类型
|
||||
|
||||
@@ -88,11 +98,11 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
|
||||
- 在任何过滤器上设置 `"exclude": true` 可反转匹配逻辑(NOT 逻辑)
|
||||
- 所有过滤器类型支持相同的模式形式:纯文本、`*`/`?` **通配符**(`*` 任意长度、`?` 单字符)以及 `/正则表达式/`——均不区分大小写
|
||||
- 字段过滤器(`event`/`repo`/`actor`/`action`/`branch`/`field`)的通配符匹配整个值;`keyword` 的通配符和正则搜索载荷任意位置;`keyword` 的纯文本为子串搜索
|
||||
- 除 `keyword` 外的每个过滤器都可加 `op` 操作符——`eq`(默认,经典行为)、`ne`、`contains`、`startsWith`、`endsWith`、`regex`、`gt`、`gte`、`lt`、`lte`、`in`、`exists`——见[过滤器教程](./filters#操作符)
|
||||
- 除 `keyword`(只支持默认的 `eq`)外的每个过滤器都可加 `op` 操作符——`eq`(默认,经典行为)、`ne`、`contains`、`startsWith`、`endsWith`、`regex`、`gt`、`gte`、`lt`、`lte`、`in`、`exists`——见[过滤器教程](./filters#操作符)
|
||||
- `field` 过滤器使用点号分隔的 JSONPath `path` 定位载荷字段;数组会自动展开,任一元素匹配即满足过滤器
|
||||
- 路由可将过滤器嵌套在 `ast` 节点(`all` / `any` / `not`)中,取代扁平的 `filters` 列表;存在 `ast` 时它优先
|
||||
- 超过 200 个字符的模式不编译为通配符/正则;`//` 包裹的非法正则匹配不到任何内容
|
||||
- `branch` 过滤器适用于 push、pull_request、pull_request_review、pull_request_review_comment、create/delete、workflow_run、workflow_job、check_suite、deployment 和 code_scanning_alert 事件
|
||||
- 通配符与正则在 RE2 引擎上执行(线性时间)。匹配器无法编译的模式——超过 200 个字符,或使用 RE2 不支持的语法(如反向引用、前后瞻)——在保存时被拒绝;此前已存的会让所在路由[不可读](./routes#不可读的路由),而不是静默地永不匹配
|
||||
- `branch` 过滤器适用于 push、pull_request、pull_request_review、pull_request_review_comment、create/delete、workflow_run、workflow_job、check_run、check_suite、deployment、deployment_status 和 code_scanning_alert 事件
|
||||
|
||||
### 匹配值
|
||||
|
||||
|
||||
+29
-17
@@ -2,6 +2,8 @@
|
||||
|
||||
## Cloudflare 设置
|
||||
|
||||
`wrangler.jsonc` 中带有维护者的 `account_id` 与资源 id。请把 `account_id` 换成你自己的 Cloudflare 账号 id(`bunx wrangler whoami`),或删除该字段以部署到当前登录的账号,并按下面的步骤替换各资源 id。
|
||||
|
||||
### 1. 创建 KV 命名空间
|
||||
|
||||
```bash
|
||||
@@ -32,7 +34,8 @@ 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 # 逗号分隔的 GitHub ID/登录名,允许进入 Web UI
|
||||
bunx wrangler secret put ADMIN_USER_IDS # 允许进入 Web UI 的 GitHub 用户 id,逗号分隔(建议写数字 id)
|
||||
bunx wrangler secret put BASE_URL # worker 的公网地址——OAuth 回调与 Telegram webhook 同步都需要
|
||||
```
|
||||
|
||||
::: tip 目标频道按路由配置
|
||||
@@ -40,7 +43,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-设置),在安装后选择页解析安装所属账号的登录名,并用于签发安装令牌做 API 增强——拉取 `workflow_run` 作业列表与 check-suite 构建日志。可以跳过不设——安装页会显示匿名 `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 构建日志。不设置时只有超级管理员能绑定安装——安装流程无法解析安装所属账号,也就无法核实登录用户是否管理该安装;公开仓库的作业列表仍会以匿名方式加载,私有仓库的构建日志则省略。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)。
|
||||
@@ -72,10 +75,10 @@ bun run db:migrate:prod # 将迁移应用到远端 D1 数据库
|
||||
bun run db:migrate # 将迁移应用到本地(Miniflare)数据库
|
||||
```
|
||||
|
||||
`db:migrate` 脚本执行 `wrangler d1 migrations apply webhooker`(见 `package.json`),逐一应用 `migrations/` 下的 SQL 文件,并在 `d1_migrations` 表中记录已应用的版本。
|
||||
`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` 语句会因列已存在而失败。此时请直接执行文件:
|
||||
如果数据库已有这些表/列(例如之前用 `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
|
||||
@@ -89,8 +92,11 @@ bunx wrangler d1 execute webhooker --remote --file ./migrations/0008_storage_d1.
|
||||
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(可选)
|
||||
@@ -101,25 +107,30 @@ bunx wrangler d1 execute webhooker --remote --file ./migrations/0012_route_posit
|
||||
bunx wrangler r2 bucket create webhooker-payloads
|
||||
```
|
||||
|
||||
bucket 已在 `wrangler.jsonc` 中声明(`r2_buckets`),无需修改绑定。
|
||||
然后取消 `wrangler.jsonc` 中 `r2_buckets` 块的注释(默认是注释掉的);没有该绑定时,超大负载仍暂存在 KV。
|
||||
|
||||
### 5. 创建队列(可选)
|
||||
|
||||
`QUEUE` 绑定会通过 Cloudflare Queues 投递 webhook(异步分发,带重试退避与死信队列)。跳过此步则保持同步内联分发。
|
||||
`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` 消费者对可重试失败做指数退避重试(5s/30s/2m/10m),达到 `max_retries` 后消息进入 `webhooker-delivery-dlq` 并标记为 dead。
|
||||
队列已在 `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
|
||||
bunx wrangler deploy
|
||||
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
|
||||
@@ -151,7 +162,7 @@ Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问
|
||||
- **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 增强(作业列表、构建日志)(见上方提示)。
|
||||
5. 生成私钥并设置 `GITHUB_APP_ID` + `GITHUB_PRIVATE_KEY`:安装流程需要它们核实安装者是否管理该安装(没有时只有超级管理员能绑定安装),私有仓库的 API 增强(作业列表、构建日志)也用它们鉴权(见上方提示)。
|
||||
|
||||
### 2. 安装 App
|
||||
|
||||
@@ -186,20 +197,20 @@ Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问
|
||||
2. 将 **Interactions Endpoint URL** 设为 `https://your-domain/discord/interactions`。
|
||||
3. 所有交互请求都使用 Ed25519 签名验证(`X-Signature-Ed25519` 覆盖 `X-Signature-Timestamp + body`)。
|
||||
|
||||
`/gh` 斜杠命令与 `GitHub: 添加/编辑/删除评论` 消息命令由定时任务(每 5 分钟)同步注册:按服务器即时可用,同时全局注册(24h 去重,约 1 小时传播)。Bot 从不连接 Discord Gateway,因此显示为**离线**——消息推送不受影响(始终走 REST)。
|
||||
`/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` 使用时间安全比较校验。
|
||||
3. Worker 会在定时任务中自动同步 webhook(`setWebhook` 指向 `{BASE_URL}/telegram/webhook`),因此无需手动调用 `setWebhook`——只需确保 `BASE_URL` 已设置。
|
||||
4. 将机器人加入群组(或启用话题),在路由配置中用 `chatId` / `topicId` 指定目标。
|
||||
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` 覆盖)。
|
||||
头像使用内置 `GET /api/richheader` 渲染为链接预览卡片(可用 `TELEGRAM_RICH_HEADER_HOST` 覆盖;未设置 `BASE_URL` 时直接以头像图片作为预览)。消息始终是文本消息,原地更新时仍有完整的 4096 字符上限。
|
||||
|
||||
## 飞书机器人配置
|
||||
|
||||
@@ -210,9 +221,9 @@ Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问
|
||||
- `im:message:send_as_bot`(以应用机器人身份发送消息)
|
||||
- `im:message:send`(旧版发送消息权限)
|
||||
4. 在**机器人**功能中启用机器人。将机器人添加到目标群聊(或创建新群),并在群设置中复制 **Chat ID**。
|
||||
5. 在 WebHooker `/admin` 中创建或编辑路由,添加目标:`platform: "feishu"`,`chatId` 填写飞书 **Chat ID**,子话题可填 `topicId`。
|
||||
5. 在 WebHooker `/admin` 中创建或编辑路由,添加目标:`platform: "feishu"`,`chatId` 填写飞书 **Chat ID**(`oc_…`);飞书目标没有话题。
|
||||
|
||||
WebHooker 使用应用级凭证(`FEISHU_APP_ID` / `FEISHU_APP_SECRET`)请求 `tenant_access_token`(有效期约 2 小时),缓存到期前复用,并以**卡片消息**(`interactive`)形式发送。`workflow_run` / `check_run` 的进度更新同样会调用飞书消息编辑接口,原地更新消息。
|
||||
WebHooker 使用应用级凭证(`FEISHU_APP_ID` / `FEISHU_APP_SECRET`)请求 `tenant_access_token`(有效期约 2 小时),按应用缓存在内存与 KV 中、到期前不久为止,被飞书拒绝时立即丢弃,并以**卡片消息**(`interactive`)形式发送。`workflow_run` / `check_run` 的进度更新同样会调用飞书消息编辑接口,原地更新消息。
|
||||
|
||||
### 入站:指令与按钮
|
||||
|
||||
@@ -230,7 +241,8 @@ WebHooker 使用应用级凭证(`FEISHU_APP_ID` / `FEISHU_APP_SECRET`)请求
|
||||
2. 订阅以下事件:
|
||||
- `im.message.receive_v1` —— 接收 `/gh` 指令(依赖 `im:message` 权限)。
|
||||
- `card.action.trigger` —— 接收卡片按钮点击。
|
||||
3. **凭证与基础信息**中的 **App Secret**(即 `FEISHU_APP_SECRET`)同时用于对入站回调做 `X-Lark-Signature` 签名,WebHooker 会校验它。
|
||||
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 用户需在同时显示双方账号的确认页上确认绑定。
|
||||
|
||||
### 所需权限
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
## 如何让分组使用自己的 webhook 端点?
|
||||
|
||||
见[分组端点](./ingress#分组端点)——在分组的 **Webhook 端点**面板(owner 角色)生成密钥,然后用 `POST /webhook/{groupId}` 与分组密钥发送。
|
||||
见[分组端点](./ingress#分组端点-post-webhook-groupid)——在分组的 **Webhook 端点**面板(owner 角色)生成密钥,然后用 `POST /webhook/{groupId}` 与分组密钥发送。
|
||||
|
||||
## 可以脱离 Cloudflare Workers 运行吗?
|
||||
|
||||
@@ -38,4 +38,4 @@
|
||||
|
||||
## 数据存储在哪里?
|
||||
|
||||
配置存于 D1(`d1_routes`/`d1_groups`,KV 仅作缓存);webhook 去重、投递状态与消息更新追踪同样存于 D1(KV 回退);发送/审计日志与平台↔GitHub 绑定存于 D1;超大负载可选存于 R2。见[存储布局](./storage#存储决策)。
|
||||
配置存于 D1(`d1_routes`/`d1_groups`,在内存中最多缓存 60 秒);webhook 去重、投递状态与消息更新追踪同样存于 D1(KV 回退);发送/审计日志与平台↔GitHub 绑定存于 D1;超大负载可选存于 R2。见[存储布局](./storage#存储决策)。
|
||||
+26
-21
@@ -124,16 +124,17 @@
|
||||
|
||||
匹配事件涉及的分支。何种字段算作「分支」取决于事件类型:
|
||||
|
||||
| 事件 | 提取的分支 |
|
||||
| --------------------------- | ----------------------------------- |
|
||||
| `push` | 推送到的目标分支 |
|
||||
| `pull_request`(及 review) | 拉取请求的 **head**(源)分支 |
|
||||
| `create` / `delete` | 创建/删除的分支或标签 |
|
||||
| `workflow_run` | 工作流运行所在的 `head_branch` |
|
||||
| `workflow_job` | 作业运行所在的 `head_branch` |
|
||||
| `check_suite` | 检查套件的 `head_branch` |
|
||||
| `deployment` | 部署引用(去除 `refs/heads/` 前缀) |
|
||||
| `code_scanning_alert` | 告警所属的分支 |
|
||||
| 事件 | 提取的分支 |
|
||||
| ---------------------------------- | --------------------------------------------------------------------------- |
|
||||
| `push` | 推送到的目标分支 |
|
||||
| `pull_request`(及 review) | 拉取请求的 **head**(源)分支 |
|
||||
| `create` / `delete` | 创建/删除的分支或标签 |
|
||||
| `workflow_run` | 工作流运行所在的 `head_branch` |
|
||||
| `workflow_job` | 作业运行所在的 `head_branch` |
|
||||
| `check_run` | 所属检查套件的 `head_branch` |
|
||||
| `check_suite` | 检查套件的 `head_branch` |
|
||||
| `deployment` / `deployment_status` | 部署引用(`deployment.ref`,去除开头的 `refs/heads/`) |
|
||||
| `code_scanning_alert` | 告警的 ref,去除开头的 `refs/heads/`(写 `main`,不要写 `refs/heads/main`) |
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -179,8 +180,9 @@
|
||||
|
||||
行为细节:
|
||||
|
||||
- 超过 200 个字符的模式**不**编译为通配符/正则,回退为纯文本匹配。
|
||||
- 被 `/` 包裹但**不是合法正则**的模式匹配**任何内容都不命中**(过滤器恒为 false),而不会报错。
|
||||
- 超过 200 个字符的模式无法编译为通配符/正则,保存时会被拒绝。
|
||||
- 通配符与正则表达式运行在 RE2 引擎上,匹配时间与输入长度成线性关系——任何模式都无法拖住 worker。RE2 语法不支持反向引用(`\1`)与环视(`(?=…)`、`(?<!…)`);控制台与 API 会拒绝此类模式。
|
||||
- 被 `/` 包裹但**不是合法正则**的模式在保存时会被拒绝。
|
||||
- 要搜索是通配符或正则特殊字符的文本(如 `v1.2.3`),使用纯文本形式即可——不含 `*`、`?` 且未被 `//` 包裹的模式按字面匹配。
|
||||
- 搜索覆盖**整个**载荷:提交信息、PR 标题与正文、标签、引用,甚至仓库名和发送者名。
|
||||
|
||||
@@ -221,7 +223,7 @@
|
||||
| `gt` / `gte` | 数值大于 / 大于等于 |
|
||||
| `lt` / `lte` | 数值小于 / 小于等于 |
|
||||
| `in` | 值等于任一列出的模式 |
|
||||
| `exists` | 字段存在(非 null);忽略 `match` |
|
||||
| `exists` | 字段存在(非 null);`match` 可省略 |
|
||||
|
||||
```json
|
||||
{ "type": "field", "path": "pull_request.commits", "op": "gt", "match": "1" }
|
||||
@@ -239,6 +241,9 @@
|
||||
{
|
||||
"id": "grouped",
|
||||
"name": "Grouped",
|
||||
"enabled": true,
|
||||
"groupId": "eng",
|
||||
"filters": [],
|
||||
"ast": {
|
||||
"all": [
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
@@ -250,11 +255,11 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"targets": [{ "channelId": "..." }]
|
||||
"targets": [{ "platform": "discord", "channelId": "..." }]
|
||||
}
|
||||
```
|
||||
|
||||
当 `ast` 存在时,它优先于 `filters`。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。
|
||||
当 `ast` 存在时,它优先于 `filters`;路由仍需带一个 `filters` 数组(可以为空)。管理后台的路由编辑器会以可视化方式构建 `ast`(all/any/not 分组)、实时展示树状解释,并可通过「测试匹配」面板粘贴 JSON 载荷进行试匹配。
|
||||
|
||||
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 GitHub 与 Gitea 的 webhook 定义——事件、路由所选事件的动作、常用载荷路径及其已知取值——以英文 key 展示,并附当前界面语言的说明;搜索优先匹配 key,其次匹配英文或中文说明。列表之外的值仍可直接输入,添加前会按匹配规则校验,只拒绝永远不可能匹配的值(含空格的事件名、含 git 禁用字符的分支、无效的正则、比较运算中的非数字等);仓库与操作者不做格式限制,因为自定义 webhook 可以携带任意字符串。已输入但未按<kbd>回车</kbd>添加的内容会阻止保存路由、存为片段和测试匹配,而不会被静默添加或丢弃。可一次输入或粘贴多个值,以逗号或换行分隔;`/正则/` 内的逗号会保留,选择「正则匹配」运算符时只按换行分隔(如 `^v{1,3}` 这样的原始模式可以包含逗号)。候选值会随运算符调整:「包含 / 开头是 / 结尾是」按字面比较,因此通配候选会换成其对应的文本(「开头是」用 `release/` 代替 `release/*`,「结尾是」用 `[bot]` 代替 `*[bot]`);「正则匹配」会把候选换成已转义并加锚点的等价正则(如 `^dependabot\[bot\]$`、`^release/`);比较运算符不提供候选。在「等于 / 不等于 / 属于」与「正则匹配」之间切换时,已添加的值会做 `/x/` ↔ `x` 改写——两种写法编译成同一个正则,匹配结果完全不变。其他值保持原样(字面、通配与按字面比较在换行和 Unicode 大小写折叠上与正则并不等价),在新运算符下永远无法匹配的值会被标出。`field` 路径中途的数组会被展开,但以数组**结尾**的路径(如 `commits.modified`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
|
||||
|
||||
@@ -275,13 +280,13 @@
|
||||
"filters": [
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
{ "type": "actor", "match": "dependabot[bot]", "exclude": true },
|
||||
{ "type": "keyword", "match": "\"draft\": true", "exclude": true }
|
||||
{ "type": "field", "path": "pull_request.draft", "match": "true", "exclude": true }
|
||||
],
|
||||
"target": { "channelId": "111111111111111111" }
|
||||
"targets": [{ "platform": "discord", "channelId": "111111111111111111" }]
|
||||
}
|
||||
```
|
||||
|
||||
`"draft": true` 模式匹配 GitHub 在拉取请求载荷中包含的 `draft` 字段;配合 `exclude: true` 即可过滤掉草稿 PR。
|
||||
`field` 过滤器读取载荷中的 `pull_request.draft`;配合 `exclude: true` 即可过滤掉草稿 PR。
|
||||
|
||||
## 示例 2:仅发布通知频道
|
||||
|
||||
@@ -298,7 +303,7 @@
|
||||
{ "type": "action", "match": "published" },
|
||||
{ "type": "repo", "match": "myorg/backend" }
|
||||
],
|
||||
"target": { "channelId": "222222222222222222" }
|
||||
"targets": [{ "platform": "discord", "channelId": "222222222222222222" }]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -317,14 +322,14 @@
|
||||
{ "type": "action", "match": "completed" },
|
||||
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
||||
],
|
||||
"target": { "channelId": "333333333333333333" }
|
||||
"targets": [{ "platform": "discord", "channelId": "333333333333333333" }]
|
||||
}
|
||||
```
|
||||
|
||||
## 常见陷阱
|
||||
|
||||
- **通配符是 glob,不是正则。** `repo: "myorg/*"` 匹配 `myorg` 下的任意仓库(含 `myorg/sub/backend`),但 `repo: "myorg/.*"` 按字面匹配。需要正则请用 `/` 包裹:`"/myorg\/.*/"`。
|
||||
- **被 `/` 包裹的非法正则永远不匹配。** 与纯文本不同——未包裹的非法模式按字面匹配。只有确定是真正的正则时才使用 `//` 包裹。
|
||||
- **被 `/` 包裹的非法正则会被拒绝。** 控制台与 API 在保存时拒绝它;此前已保存的路由会被报告为[不可读](./routes#不可读的路由),所在分组的投递会一直重试直到修复。与 `//` 包裹的文本不同——未包裹的模式按字面匹配。只有确定是真正的正则时才使用 `//` 包裹。
|
||||
- **`action` 过滤器遇到无 action 的事件永远不匹配。** 先确认该事件带有 `action` 字段(见[过滤器兼容性](../events/supported#过滤器兼容性))。
|
||||
- **`branch` 过滤器遇到无分支的事件永远不匹配。** 在 `issues` 事件上使用 `branch` 过滤器恒为假。此时需要类似分支的匹配可用 `keyword`。
|
||||
- **`keyword` 会搜索一切。** 因为它扫描整个载荷,`"fix"` 这样的模式可能同时匹配提交信息、issue 标题和仓库名。请尽量写得更具体。
|
||||
|
||||
@@ -33,12 +33,12 @@ GITHUB_CLIENT_ID=your-client-id
|
||||
GITHUB_CLIENT_SECRET=your-client-secret
|
||||
DISCORD_TOKEN=your-bot-token
|
||||
DISCORD_PUBLIC_KEY=your-public-key
|
||||
ADMIN_USER_IDS=your-github-id,your-github-login
|
||||
ADMIN_USER_IDS=your-github-id
|
||||
BASE_URL=http://localhost:8787
|
||||
```
|
||||
|
||||
::: tip
|
||||
`GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 为可选,仅用于 App 安装流程解析安装所属账号的登录名(OAuth 流程只需要 Client ID/Secret)。目标频道在 Web UI 中按路由设置,因此不需要 `DISCORD_CHANNEL_ID`。若要在本地启用 `/gh` 命令,请在开发者门户复制 **Public Key** 填入 `DISCORD_PUBLIC_KEY`,并把 Interactions Endpoint URL 设为 `http://localhost:8787/discord/interactions`。
|
||||
`GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 只在 GitHub App 安装流程与 API 增强中需要:没有它们时,安装流程无法核实登录用户是否管理该安装,只有超级管理员能绑定安装(OAuth 流程本身只需要 Client ID/Secret)。目标频道在 Web UI 中按路由设置,因此不需要 `DISCORD_CHANNEL_ID`。若要在本地启用 `/gh` 命令,请在开发者门户复制 **Public Key** 填入 `DISCORD_PUBLIC_KEY`,并把 Interactions Endpoint URL 设为 `http://localhost:8787/discord/interactions`。
|
||||
:::
|
||||
|
||||
::: warning
|
||||
@@ -48,10 +48,11 @@ BASE_URL=http://localhost:8787
|
||||
### 2. 启动开发服务器
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
bun run db:migrate # 首次运行:将 D1 迁移应用到本地数据库
|
||||
bun run cf:dev # 先构建,再用 wrangler dev(Miniflare)运行 worker
|
||||
```
|
||||
|
||||
这将在 `http://localhost:8787` 启动本地 Miniflare 环境。
|
||||
这会在 `http://localhost:8787` 运行构建后的 worker。未执行迁移时 worker 会拒绝服务(`D1 migrations are incomplete`)。开发界面时可改用 `bun run dev` 启动带 HMR 的 Nuxt 开发服务器(`http://localhost:3000`;其中队列消息没有消费者)。
|
||||
|
||||
### 3. 验证
|
||||
|
||||
@@ -66,7 +67,7 @@ curl http://localhost:8787/health
|
||||
| ---------------------- | ------------------------------------ |
|
||||
| `bun run dev` | 启动 Nuxt 开发服务器 (HMR) |
|
||||
| `bun run build` | 生产构建(cloudflare_module preset) |
|
||||
| `bun run deploy` | 部署到 Cloudflare |
|
||||
| `bun run deploy` | 应用待执行的 D1 迁移并部署 |
|
||||
| `bun run typecheck` | TypeScript 类型检查 |
|
||||
| `bun run lint` | ESLint |
|
||||
| `bun run lint:md` | Markdownlint |
|
||||
|
||||
+33
-18
@@ -1,6 +1,6 @@
|
||||
# 分组与访问控制
|
||||
|
||||
路由归属于分组。分组用于划分管理权限,并可限制进入其中的事件。它们存储在 D1(`d1_groups`,首次加载时从旧版 KV `config:groups` 键同步),可通过 [Web 控制台](./configuration#web-控制台)或 [Admin API](../api/admin) 管理。每个实例最多可保存 **100 个分组**。
|
||||
路由归属于分组。分组用于划分管理权限,并可限制进入其中的事件。它们存储在 D1(`d1_groups`,首次加载时从旧版 KV `config:groups` 键同步),可通过 [Web 控制台](./configuration#web-控制台)或 [Admin API](../api/admin) 管理。批量保存分组时单次最多 **100 个分组**。
|
||||
|
||||
## 分组模式
|
||||
|
||||
@@ -20,19 +20,22 @@
|
||||
}
|
||||
```
|
||||
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `id` | string | 是 | 小写 id(`a-z0-9`、`-`);被每条路由的 `groupId` 引用。可编辑:重命名分组会同步其路由、分组 webhook secret 与待处理邀请 |
|
||||
| `name` | string | 是 | 人类可读的分组名 |
|
||||
| `members` | object[] | 否 | `{ login, role }` 条目;角色为 `owner`、`admin` 或 `viewer` |
|
||||
| `adminIds` | string[] | 否 | 已废弃的旧字段;存在时视为角色为 `owner` 的 `members` |
|
||||
| `owners` | string[] | 否 | 允许进入该分组的事件所属组织/用户登录名;空 = 全部 |
|
||||
| `providers` | string[] | 否 | 允许进入该分组的来源平台(`github`、`gitea`);空 = 全部 |
|
||||
| `installationId` | number | 否 | 绑定到该分组的 GitHub App 安装 id;仅接受该安装的事件(空 = 全部) |
|
||||
| `emoji` | boolean | 否 | 该分组消息是否包含表情(默认 `true`) |
|
||||
| `forgeSources` | object[] | 否 | 来源主机:`{ host, type, name? }` 条目(`type` 为 `github` 或 `gitea`,`name` 为可选显示名称),用于标注该分组消息底部;空 = 不标注 |
|
||||
| `lang` | string | 否 | 该分组所有路由的消息语言(如 `en`、`zh`;可通过 KV `i18n:<lang>` 自定义)——见[消息语言](./i18n)——默认 `en` |
|
||||
| `logTarget` | object | 否 | Webhook 日志频道:Discord 目标 `{ platform, channelId, threadId? }` 或 Telegram 目标 `{ platform, chatId, topicId? }`,接收该分组路由每次分发 webhook 的摘要 |
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ---------------- | -------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | string | 是 | 小写 id(`a-z0-9`、`-`);被每条路由的 `groupId` 引用。可编辑:重命名会同步其路由、片段、历史记录、webhook secret 与待处理邀请;被删除或重命名的 id 会保留若干天不可复用 |
|
||||
| `name` | string | 是 | 人类可读的分组名 |
|
||||
| `members` | object[] | 是¹ | `{ login, role }` 条目;角色为 `owner`、`admin` 或 `viewer`。服务端会把每个条目绑定到 GitHub user id(添加成员时解析,或在其首次登录时绑定);绑定后只匹配该账号,即使登录名易主 |
|
||||
| `adminIds` | string[] | 否 | 已废弃的旧字段;存在时视为角色为 `owner` 的 `members` |
|
||||
| `owners` | string[] | 否 | 允许进入该分组的事件所属组织/用户登录名;空 = 全部 |
|
||||
| `providers` | string[] | 否 | 允许进入该分组的来源平台(`github`、`gitea`、`custom`);空 = 全部 |
|
||||
| `installationId` | number | 否 | 绑定到该分组的 GitHub App 安装 id;仅接受该安装的事件(空 = 全部)。仅超级管理员可改(由经过验证的安装流程设置) |
|
||||
| `isolated` | boolean | 否 | 隔离分组(自助注册的个人分组)只接收其自身 `/webhook/{groupId}` 入口的事件,直到超级管理员为其绑定来源(`installationId` 或 `owners`)。仅超级管理员可改 |
|
||||
| `emoji` | boolean | 否 | 该分组消息是否包含表情(默认 `true`) |
|
||||
| `forgeSources` | object[] | 否 | 来源主机:`{ host, type, name? }` 条目(`type` 为 `github` 或 `gitea`,`name` 为可选显示名称),用于标注该分组消息底部;空 = 不标注 |
|
||||
| `lang` | string | 否 | 该分组所有路由的消息语言(如 `en`、`zh`;可通过 KV `i18n:<lang>` 自定义)——见[消息语言](./i18n)——默认 `en` |
|
||||
| `logTarget` | object | 否 | Webhook 日志频道:Discord 目标 `{ platform, channelId, threadId? }`、Telegram 目标 `{ platform, chatId, topicId? }` 或飞书目标 `{ platform, chatId }`,接收该分组路由每次分发 webhook 的摘要 |
|
||||
|
||||
¹ 必须提供 `members` 或旧字段 `adminIds`。非空的 `members` 列表至少要有一个 `owner`;空列表也可以(这样的分组只能由超级管理员管理)。`forgeSources` 最多 20 项,每项 `name` 最多 50 个字符,不能有类型与主机都相同的两项。
|
||||
|
||||
## 角色
|
||||
|
||||
@@ -46,16 +49,21 @@
|
||||
|
||||
## 权限模型
|
||||
|
||||
- **超级管理员**(`ADMIN_USER_IDS`)可查看和编辑所有分组与全部路由;只有他们能编辑分组的 `owners` 列表。
|
||||
- **超级管理员**(`ADMIN_USER_IDS`)可查看和编辑所有分组与全部路由;只有他们能编辑分组的来源隔离字段(`owners`、`installationId`、`isolated`)——owner 保存时会保留已存储的值。
|
||||
- **Owner** 管理自己分组的路由、成员、邀请、名称、id、`emoji` 与 `providers`。不能移除最后一个 owner,也不能在没有其他 owner 时降级自己。
|
||||
- **Admin** 编辑自己分组内的路由并查看日志;**viewer** 只有只读控制台。
|
||||
- 分组管理端点通过 `/admin/api/groups/:id/routes` 一次操作一个分组;`groupId` 强制取自路径参数。
|
||||
- `owners` 列表限制该分组路由究竟会分发哪些事件操作者(发送者登录名)的事件。
|
||||
- `owners` 列表把该分组的路由限制为这些用户或组织所拥有仓库的事件(`repository.owner.login` / `organization.login`);要按事件触发者过滤,请使用 `actor` 过滤器。
|
||||
- 所属分组已不存在的路由永远不会触发。
|
||||
- 每次分组写入都是单行的比较并交换更新:两个人编辑不同分组时互不覆盖;基于过期副本对同一分组的编辑会被拒绝(`409`,控制台会重新加载),而不是回滚较新的修改。路由与片段列表也按分组以同样方式处理。
|
||||
- 写入提交时会再次核对角色:在操作者失去角色(或被移除)之前通过鉴权的请求,提交时会被拒绝。
|
||||
- 删除分组需要带上控制台确认时看到的快照(`revision`、`routesRevision` 与分组 `version`):确认之后新增或修改的任何内容(路由、片段、设置)都会让删除返回 `409`,而不会被一并删掉。含无法读取路由的分组不会被删除。
|
||||
- 投递目标有归属:非超级管理员不能把路由或日志频道指向另一个分组已在使用的频道/群聊,除非也能编辑那个分组的路由(否则返回 `403`)。此前已被两个分组共用的频道,只在原有用途中继续有效。
|
||||
- `providers` 列表限制该分组路由会分发哪个 forge(`github`、`gitea`)的事件。即使组织/用户名冲突,也可借此将 GitHub 与 Gitea 分组分开。
|
||||
|
||||
## Webhook 日志频道
|
||||
|
||||
分组可以设置 `logTarget` 指向一个 Discord 频道/子区或 Telegram 群组/话题。每当该分组的路由分发(dispatch)一个 webhook,就会向那里发送一条摘要消息:事件类型/动作、仓库、投递 ID,以及每条「路由 × 目标」一行的 ✅/❌ 结果(失败时附带错误信息;最多列出前 10 行,其余以 `+N` 汇总)。全部成功时消息为绿色,任一失败则为红色。摘要使用分组的消息语言。日志消息尽力发送,本身不会被记入 D1 发送日志。
|
||||
分组可以设置 `logTarget` 指向一个 Discord 频道/子区、Telegram 群组/话题或飞书群聊。每当该分组的路由分发(dispatch)一个 webhook,就会向那里发送一条摘要消息:事件类型/动作、仓库、投递 ID,以及每条「路由 × 目标」一行的 ✅/❌ 结果(失败时附带错误信息;之前尝试中已处理的目标会如实标注;最多列出前 10 行,其余以 `+N` 汇总)。全部成功时消息为绿色,任一失败为红色,含结果未知的之前尝试时为灰色。同一投递重试得到相同结果时不会再发摘要。摘要使用分组的消息语言。日志消息尽力发送,本身不会被记入 D1 发送日志。
|
||||
|
||||
## 来源平台标识
|
||||
|
||||
@@ -79,8 +87,15 @@
|
||||
|
||||
## 邀请
|
||||
|
||||
Owner(与超级管理员)可以在分组的 _成员_ 面板创建单次使用、有效期 7 天的邀请链接。接受邀请后,用户以被邀请的角色(`admin` 或 `viewer`——绝不会是 `owner`)加入;已有 `viewer` 会被升级为 `admin`。邀请存储在 KV 的 `invite:{token}` 键下。
|
||||
Owner(与超级管理员)可以在分组的 _成员_ 面板创建单次使用、有效期 7 天的邀请链接。接受邀请后,用户以被邀请的角色(`admin` 或 `viewer`——绝不会是 `owner`)加入;已有 `viewer` 会被升级为 `admin`。邀请在整个有效期内存储在 KV 的 `invite:{token}` 键下;"已使用"记录与成员变更在同一个 D1 事务中提交,因此即使两人同时打开同一链接,也只能使用一次。
|
||||
|
||||
- 邀请属于签发它的分组 instance:之后以同一 id 新建的分组不会接受它。
|
||||
- 撤销邀请会记录在 D1 中并立即生效,即使 KV 里仍有该邀请。
|
||||
- 签发人不再是该分组 owner 时,邀请失效。
|
||||
- 如果该登录名仍挂在一个绑定到其他 GitHub 账号的成员条目上(登录名的前任持有者),接受会因冲突失败且邀请保持可用;需 owner 先移除陈旧条目。
|
||||
|
||||
## 自助注册
|
||||
|
||||
设置 `ALLOW_SELF_SIGNUP=1` 后,没有分组权限的 GitHub 用户首次登录时会获得个人分组(`u-{userId}`,归其所有),而不是 `403`。这是完全自助式 SaaS 安装的入口;关闭它可保持控制台仅邀请制。
|
||||
|
||||
个人分组是**隔离的**(该字段出现前创建的 `u-<数字>` 分组同样视为隔离,除非超级管理员设置 `isolated: false`):运营者的全局 `POST /webhook` 入口永远不会分发到它们,因此自助用户无法通过添加通配路由收到其他租户的事件。它们通过自己的[分组 webhook](./ingress) 接收事件,或接收其能证明自己管理的 GitHub App 安装的事件(安装流程会用用户本人的 GitHub token 校验)。
|
||||
@@ -8,17 +8,19 @@
|
||||
|
||||
## 自定义覆盖
|
||||
|
||||
翻译覆盖从 KV 键 `i18n:<lang>` 读取,值为扁平的「键 → 文本」JSON 对象。内置字典(en/zh)中的任意键都可覆盖;未提供的键回退为英文。
|
||||
额外的消息语言从 KV 键 `i18n:<lang>` 读取:一个与内置字典(`server/lib/lib/locales/en.ts`)嵌套结构相同的 JSON 对象,未提供的键都会回退为英文。内置的 `en` 与 `zh` 不会从 KV 读取,因此不能这样覆盖;请使用其他语言代码(如 `zh-custom`),并把它设为分组的 `lang`。
|
||||
|
||||
```jsonc
|
||||
// KV 键:i18n:zh
|
||||
// KV 键:i18n:zh-custom
|
||||
{
|
||||
"events.push.title": "{repo}: 推送了 {count} 个提交到 {ref}",
|
||||
"events": {
|
||||
"push": { "title": "{repo}: 推送了 {count} 个提交到 {ref}" },
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
覆盖对分组消息(以及适用的控制台界面)生效。要新增一种语言,可在 `i18n:<lang>` 存放完整字典——未提供的键都会回退为英文。
|
||||
已加载的字典会在每个 worker 实例中一直缓存到实例重启,因此修改后的覆盖可能要过一段时间才生效;没有覆盖的语言 5 分钟后会再次查找。覆盖只影响分组消息——控制台使用其内置的翻译。
|
||||
|
||||
## 表情开关
|
||||
|
||||
`Group.emoji`(默认 `true`)控制该分组消息中是否显示事件表情。关闭后,标题、描述、字段与链接中的所有表情都会被去除。里程碑进度条(🟢🟡🟠⬜)属于数据可视化,不受该开关影响。
|
||||
`Group.emoji`(默认 `true`)控制该分组消息中是否显示事件表情。关闭后,格式化器添加到标题、描述、字段与链接中的表情都不会出现;取自载荷的文本(提交信息、issue 标题、自定义 webhook 字段)保留其中自带的表情。里程碑进度条(🟢🟡🟠⬜)属于数据可视化,不受该开关影响。
|
||||
@@ -11,24 +11,29 @@ WebHooker 通过同一个 `POST /webhook` 端点接收多个 forge 的 webhook
|
||||
|
||||
投递 id 去重使用 `X-GitHub-Delivery`(GitHub)或 `X-Gitea-Delivery`(Gitea)请求头(存在时)。
|
||||
|
||||
启用投递队列时,webhook 只有在持久入队后才返回 `200`。若队列拒收,端点返回 `503` 并释放去重占用,发送方的重投会被接受,而不会被当作重复丢弃。已被接受的 webhook 再次投递时返回 `200 { "duplicate": true }`;第一份仍在处理中时到达的重投返回 `503`,由发送方稍后重试。
|
||||
|
||||
未绑定队列时,webhook 内联分发,分发结束后才应答:所有目标都处理完返回 `200`,有目标暂时失败时返回 `503`(发送方重投时会跳过已成功的目标)。内联分发最多发送 8 分钟,其余目标返回 `503`,避免单个请求超过其去重占用的有效期。
|
||||
|
||||
Gitea 载荷会被归一化为与 GitHub 事件相同的内部结构,因此路由、过滤器与 28 个格式化器无需改动即可工作。未知或未映射的 Gitea 事件回退到通用格式化器。仓库/提交/用户链接取自载荷中的 `repository.html_url`,因此指向你的 Gitea 实例。
|
||||
|
||||
## 全局端点(`POST /webhook`)
|
||||
|
||||
全局端点使用运营者的全局密钥(`GITHUB_WEBHOOK_SECRET`、`GITEA_WEBHOOK_SECRET`)验签,并分发到**所有**路由。GitHub App 安装的事件都在此送达;在分组上设置 `installationId` 可保持租户隔离。
|
||||
全局端点使用运营者的全局密钥(`GITHUB_WEBHOOK_SECRET`、`GITEA_WEBHOOK_SECRET`)验签,并分发到**所有**路由——未绑定来源的[隔离分组](./groups#自助注册)除外。GitHub App 安装的事件都在此送达;在分组上设置 `installationId` 可保持租户隔离。
|
||||
|
||||
## 分组端点(`POST /webhook/{groupId}`)
|
||||
|
||||
每个分组都可以选择接入自己的 webhook 入口,使用独立的密钥(在分组页面的 _Webhook 端点_ 面板生成,owner 角色)。载荷使用**分组**的密钥验签,而不是全局密钥,并且只有该分组的路由会被触发。SaaS 用户以此配置 Gitea、经典 GitHub 或自定义 webhook,而无需共享(或知道)运营者的密钥。
|
||||
|
||||
- 支持任意提供方:GitHub(`X-Hub-Signature-256`)、Gitea(`X-Gitea-Signature`)、自定义(`X-WebHooker-Signature`)
|
||||
- 密钥为 64 位 hex 字符串;在控制台重新生成会立即失效旧密钥
|
||||
- 投递 id 去重键按提供方与租户隔离(`delivery:{provider}:{groupId}:{id}`)
|
||||
- 分组没有密钥(或已不存在)时端点返回 `404`
|
||||
- 密钥为 64 位 hex 字符串,与分组一起存于 D1(生成之后不再发给控制台);重新生成会立即失效旧密钥,只有当前 owner 能轮换或删除
|
||||
- 投递 id 去重键按提供方与租户隔离(`delivery:{provider}:@i:{instance}:{id}`——使用分组不可变的 instance,改名不改变作用域,以同一 id 新建的分组也不会共用;全局入口使用作用域 `@global`)
|
||||
- 租户签名的载荷只具备租户本身的可信度:其中的 `installation.id` 会被忽略,因此它不会使用运营者的 GitHub App 凭据(不做 job/构建日志补全),也不会创建或重新绑定安装分组;分组自身入口的事件不受安装限制约束
|
||||
- 分组没有密钥(或已不存在)时端点返回 `404`;分组存储的配置无法读取时返回 `503`
|
||||
|
||||
## 自定义 Webhook
|
||||
|
||||
向 `POST /webhook/{groupId}`(或全局端点)POST 任意 JSON,并使用分组密钥将原始 body 的 HMAC-SHA256 以 `X-WebHooker-Signature: sha256=<hex>` 签名。载荷会变成 `custom` 事件,走正常的路由管线——创建一条 `event: custom` 的路由(控制台有模板),即可分发到该路由的目标、记录 `send_logs`,并出现在分组的 webhook 日志频道中。
|
||||
向 `POST /webhook/{groupId}`(或全局端点)POST 一个 JSON 对象,并使用分组密钥将原始 body 的 HMAC-SHA256 以 `X-WebHooker-Signature: sha256=<hex>` 签名(顶层为数组或标量时返回 `400`)。载荷会变成 `custom` 事件,走正常的路由管线——创建一条 `event: custom` 的路由(控制台有模板),即可分发到该路由的目标、记录 `send_logs`,并出现在分组的 webhook 日志频道中。
|
||||
|
||||
### 重放防护
|
||||
|
||||
@@ -40,7 +45,7 @@ Gitea 载荷会被归一化为与 GitHub 事件相同的内部结构,因此路
|
||||
当**同时**提供这两个请求头时,签名改为对 `{timestamp}.{nonce}.{原始body}` 计算(而非仅原始 body),且仅当以下条件满足时才被接受:
|
||||
|
||||
1. 时间戳与服务器时钟相差不超过 ±5 分钟(拒绝重放与时钟漂移滥用)
|
||||
2. nonce 从未被使用过(存入 KV 保留 10 分钟;重放的 nonce 会被拒绝)
|
||||
2. 该 nonce 对此密钥从未被使用过(原子占用并保留 10 分钟;重放的 nonce 会被拒绝,其他租户可以使用相同 nonce)。第一次请求仍在处理中的 nonce,或 nonce 存储故障,返回 `503` 而不是 `401`,由发送方重试
|
||||
|
||||
```bash
|
||||
input="${timestamp}.${nonce}.${body}"
|
||||
@@ -79,12 +84,14 @@ signature="sha256=$(printf '%s' "$input" | openssl dgst -sha256 -hmac "$secret"
|
||||
| `author` | object | 可选 `{ name, iconUrl, url }` |
|
||||
| `fields` | object[] | 可选嵌入字段 `{ name, value, inline }` |
|
||||
| `footer` | string | 可选页脚覆盖 |
|
||||
| `deliveryId` | string | 可选的发送方去重 id(重试) |
|
||||
| `deliveryId` | string | 可选的发送方去重 id(重试)。没有 `deliveryId` 时以 nonce 标识请求;两者都没有时,重试的请求会被再次投递 |
|
||||
|
||||
## GitHub App 租户隔离
|
||||
|
||||
GitHub App 安装后,**所有**安装方的事件都会到达全局端点。要让租户互相隔离,请把每个分组绑定到应当为其提供事件的安装 ID:`"installationId": 12345678`。该 ID 可从 App 安装 webhook 载荷(`installation.id`)或 GitHub App 安装页 URL 看到。即使分组的 `owners` 为空,来自其它安装的事件也会被拒绝。未设置 `installationId` 的分组保持旧行为(`owners` 过滤)。
|
||||
|
||||
绑定是**自动配置**的 —— 将 GitHub App 的 _Setup URL_ 指向 `{BASE_URL}/auth/github/install`。用户安装 App 后浏览器立即跳转到该页面(页面需要已登录的管理员会话——未登录用户会先被重定向走 OAuth 流程),可选择将安装绑定到:**新分组**(`inst-{installationId}`,默认)或任意**自己拥有 owner 权限的已有分组**(提交时再次校验角色;由 `POST /auth/github/install/bind` 完成配置)。无需手动填写 ID。作为兜底(例如未配置 Setup URL 时),`installation.created` webhook 事件也会自动创建/绑定分组 —— `owners` 匹配安装账号的现有分组会被绑定,否则创建独立的 `inst-{installationId}` 分组。之后在控制台为分组添加路由和成员即可。
|
||||
绑定是**自动配置**的 —— 将 GitHub App 的 _Setup URL_ 指向 `{BASE_URL}/auth/github/install`。用户安装 App 后浏览器立即跳转到该页面(页面需要已登录的管理员会话——未登录用户会先被重定向走 OAuth 流程),可选择将安装绑定到:**新分组**(`inst-{installationId}`,默认)或任意**自己拥有 owner 权限的已有分组**(提交时再次校验角色;由 `POST /auth/github/install/bind` 完成配置)。无需手动填写 ID。Setup URL 中的 `installation_id` 可以被随意填写,因此页面与绑定步骤都会先用登录用户本人的 GitHub token 验证其有权管理该安装:用户就是安装所属账号,或是其组织的有效**管理员**(仅以协作者身份能访问该安装并不够)。否则会带 `?error=install-forbidden` 返回。超级管理员可以绑定任意安装。开启 `ALLOW_SELF_SIGNUP` 时,只有当专用的 `inst-{installationId}` 分组仍绑定该安装且尚无任何成员时,安装者才会成为其 owner——其他分组绝不会以这种方式交给新 owner。以 `inst-` 或 `u-` 开头的 id 为这些系统分组保留:只有超级管理员能创建或重命名为此类 id,已存在但未绑定的 `inst-*` 分组也不会被自动绑定。
|
||||
|
||||
作为兜底(例如未配置 Setup URL 时),`installation.created` webhook 事件(仅限全局入口)也会自动创建/绑定分组 —— `owners` 匹配安装账号的现有分组会被绑定,否则创建独立的 `inst-{installationId}` 分组。之后在控制台为分组添加路由和成员即可。自动配置在该投递完成去重检查之后执行,并按安装、按已绑定分组各记录 7 天,因此重投的事件不会重新绑定超级管理员已解除绑定的分组;配置失败时端点返回 `503`,让事件被重新投递。
|
||||
|
||||
要在选择页显示安装所属账号的登录名,请设置 `GITHUB_APP_ID` 与 `GITHUB_PRIVATE_KEY`——见[密钥](./configuration#密钥)。
|
||||
@@ -22,7 +22,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
||||
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Cloudflare Worker** | HTTP 入口、签名验证、投递去重、事件解析、路由匹配、平台分发 |
|
||||
| **Interactions Endpoint** | 验证 Ed25519 签名并处理 `/gh` 交互(斜杠命令、右键菜单、按钮、modal) |
|
||||
| **KV** | Token 存储 (`token:{userId}`)、OAuth 状态 (`state:{hex}`)、管理员会话、分组级 secret、配置缓存、投递去重/投递状态/消息更新追踪的回退(`delivery:*`、`delivery-state:*`、`msg:*`,仅在 D1 不可用时使用)、消息更新锁 (`msg:lock:*`) |
|
||||
| **KV** | Token 存储 (`token:{userId}`)、OAuth 状态 (`state:{hex}`)、管理员会话、邀请、投递去重/投递状态/消息更新追踪的回退(`delivery:*`、`delivery-state:*`、`msg:*`,仅在 D1 不可用时使用)、消息更新锁 (`msg:lock:*`) |
|
||||
| **D1** | 路由/分组 (`d1_routes`/`d1_groups`)、发送日志 (`send_logs`)、审计日志 (`audit_logs`)、去重 (`dedup_keys`)、投递状态 (`delivery_state`)、消息追踪 (`message_tracking`)、Discord↔GitHub 绑定 (`discord_links`)、Telegram↔GitHub 绑定 (`telegram_links`),超大负载可选的 R2 存储 |
|
||||
|
||||
### 数据流
|
||||
@@ -40,7 +40,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
||||
- **运行时**: Cloudflare Workers
|
||||
- **HTTP 框架**: Nuxt 4 / Nitro (H3)
|
||||
- **Discord 投递**: Discord REST API(交互通过 Ed25519 验签的 HTTPS Interactions Endpoint)
|
||||
- **Telegram 投递**: Telegram Bot API(webhook 带可选 secret-token 校验)
|
||||
- **Telegram 投递**: Telegram Bot API(webhook 调用始终用 secret token 校验——显式配置,或由 bot token 派生)
|
||||
- **Web UI**: Nuxt 4(Vue 3 + Tailwind CSS v4 + `@elysola/ui`)——首页/法律页面服务端渲染,`/admin` 控制台客户端渲染
|
||||
- **存储**: Cloudflare D1(配置与日志权威)+ KV(缓存/临时状态)+ 可选 R2(超大负载)
|
||||
- **鉴权**: Web Crypto API (HMAC-SHA256、Ed25519)、octokit (GitHub API)
|
||||
|
||||
+26
-20
@@ -4,27 +4,33 @@
|
||||
|
||||
每次分发尝试都会记录到 D1 `send_logs` 表,并可在控制台(**日志**标签页)查看。字段:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------ | -------------------------------------------------------- |
|
||||
| `routeId` | 匹配的路由 |
|
||||
| `groupId` | 路由所属分组 |
|
||||
| `event` | 事件类型(如 `push`、`pull_request`、`custom`) |
|
||||
| `repo` | 仓库全名(存在时) |
|
||||
| `target` | 消息发送到的目标 id |
|
||||
| `platform` | `discord`、`telegram` 或 `feishu` |
|
||||
| `ok` | 发送是否成功 |
|
||||
| `status` | 平台 API 的 HTTP 状态码(适用时) |
|
||||
| `error` | 失败时的错误信息 |
|
||||
| `errorCode` | 稳定错误码(如 `NO_TARGET`、`NO_TOKEN`、`RATE_LIMITED`) |
|
||||
| `attempts` | 含重试在内的发送次数 |
|
||||
| `durationMs` | 发送耗时 |
|
||||
| `deliveryId` | Webhook 投递 id(提供时) |
|
||||
| `messageId` | 平台消息 id(用于原地编辑) |
|
||||
| `actor` | 发送者登录名 |
|
||||
| `action` | 事件动作(存在时) |
|
||||
| `detail` | 附加 JSON 详情(存在时) |
|
||||
| 字段 | 含义 |
|
||||
| ------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||
| `routeId` | 匹配的路由 |
|
||||
| `groupId` | 路由所属分组 |
|
||||
| `event` | 事件类型(如 `push`、`pull_request`、`custom`) |
|
||||
| `repo` | 仓库全名(存在时) |
|
||||
| `target` | 消息发送到的目标 id |
|
||||
| `platform` | `discord`、`telegram` 或 `feishu` |
|
||||
| `ok` | 发送是否成功 |
|
||||
| `status` | 平台 API 的 HTTP 状态码(适用时) |
|
||||
| `error` | 失败时的错误信息 |
|
||||
| `errorCode` | 稳定错误码(如 `NO_TARGET`、`NO_TOKEN`、`RATE_LIMITED`、`FORMAT`、`PAYLOAD_MISSING`、`TELEGRAM_UNCERTAIN`) |
|
||||
| `attempts` | 含重试在内的发送次数 |
|
||||
| `durationMs` | 发送耗时 |
|
||||
| `deliveryId` | Webhook 投递 id(提供时) |
|
||||
| `messageId` | 平台消息 id(用于原地编辑) |
|
||||
| `actor` | 发送者登录名 |
|
||||
| `action` | 事件动作(存在时) |
|
||||
| `detail` | 附加 JSON 详情(存在时) |
|
||||
|
||||
控制台的**日志**标签页列出最近记录(可按分组过滤),并可查看单条完整详情。写入为尽力而为——插入失败不会中断分发。
|
||||
控制台的**日志**标签页列出最近记录(可按分组过滤),并可查看单条完整详情。写入为尽力而为——插入失败会重试一次,且不会中断分发。`send_logs` 不会自动清理。
|
||||
|
||||
需要留意的错误码:
|
||||
|
||||
- `PAYLOAD_MISSING` —— 排队投递暂存的负载已丢失;投递保持重试状态,该记录提示从源头重新投递 webhook。
|
||||
- `TELEGRAM_UNCERTAIN` —— Telegram 返回 `200` 但响应无法读取;消息可能已发出也可能没有,因此不会重试(Telegram 没有幂等键)。
|
||||
- `FORMAT` —— 事件无法格式化;该路由没有发送任何内容。
|
||||
|
||||
## 审计日志(`audit_logs`)
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
只有仓库头会被加超链接——整条标题永远不会整体链接:
|
||||
|
||||
- **Discord**(嵌入标题不支持局部链接):标题为仓库头 `{repo}{#number}`,链接到仓库;`: {subject}` 文本作为描述首行渲染,不带链接。
|
||||
- **Discord**(嵌入标题不支持局部链接):标题为仓库头 `{repo}{#number}`,链接到事件对象(issue、PR、评论或运行页面);`: {subject}` 文本作为描述首行渲染,不带链接。
|
||||
- **Telegram**(HTML 支持行内链接):单行标题保留描述文本,仅仓库头被包在链接中。
|
||||
|
||||
标题中不含冒号分隔符(`:` 后跟一个空格)的消息保持旧的整行链接行为。
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
## 原地更新
|
||||
|
||||
`workflow_run` 与 `check_run` 消息只发送一次,随运行进度原地编辑(queued → running → success/failure),不会重复发消息。追踪使用 KV `msg:*` 与每次运行的稳定 `updateKey`:`workflow_run` 以 workflow id 为键,`check_run` 则以 check 名 + commit SHA 为键(回退到 run id),因此每个阶段都换新 run id 的部署(例如 Cloudflare Pages)仍会编辑同一条消息。
|
||||
会随时间变化的对象只发送一条消息,之后原地编辑:`workflow_run` 与 `check_run` / `check_suite` 随运行进度(queued → running → success/failure),部署及其状态,以及 issue 评论、PR 审核与审核评论在编辑或删除时,都不会另发新消息。每次编辑都按最新事件重新渲染整条消息。追踪使用 D1 `message_tracking`(KV `msg:*` 为回退)与每个对象的稳定 `updateKey`:`workflow_run` 以 run id 为键,`check_suite` 以 suite id 为键,`check_run` 则以检查套件(或 App)+ check 名 + commit SHA 为键(回退到 run id),因此每个阶段都换新 run id 的部署(例如 Cloudflare Pages)仍会编辑同一条消息。消息链还按来源(provider + 仓库主机)和目标平台区分,两个拥有相同 `owner/repo` 的 Gitea 实例不会互相编辑对方的消息。比消息当前所示状态更旧的事件(迟到)不会覆盖它;编辑失败会记为失败而不是再发一条——只有旧消息已不存在时才发送新消息。
|
||||
|
||||
## Workflow 作业
|
||||
|
||||
|
||||
+16
-6
@@ -1,8 +1,8 @@
|
||||
# 路由与目标
|
||||
|
||||
路由决定哪些事件被转发到哪个频道(Discord 或 Telegram)。它们存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 键同步),可通过 [Web 控制台](./configuration#web-控制台)、[Admin API](../api/admin) 或 `config.example.yaml` 管理。
|
||||
路由决定哪些事件被转发到哪个频道(Discord 或 Telegram)。它们存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 键同步),可通过 [Web 控制台](./configuration#web-控制台)或 [Admin API](../api/admin) 管理。`config.example.yaml` 以 YAML 展示数据结构,worker 不会读取它。
|
||||
|
||||
**没有默认路由**——每条路由都必须定义自己的目标。未配置任何路由时不会转发任何事件。每个实例最多可保存 **200 条路由**。
|
||||
**没有默认路由**——每条路由都必须定义自己的目标。未配置任何路由时不会转发任何事件。单次保存最多 **200 条路由**。
|
||||
|
||||
## 路由模式
|
||||
|
||||
@@ -29,14 +29,20 @@
|
||||
}
|
||||
```
|
||||
|
||||
`targets` 的每一项都是一个推送目标,因此一条路由可同时转发到多个频道(例如一个 Discord 频道**和**一个 Telegram 群组)。`target.platform` 选择平台:`discord`(默认)、`telegram` 或 `feishu`。**Discord** 目标要求 `target.channelId`(可选 `target.threadId` 指定子区);**Telegram** 与 **飞书** 目标要求 `target.chatId`(群组/超级群组 id,如 `-1001234567890`),可选 `target.topicId`(话题的 `message_thread_id`,相当于 Discord 子区)。没有默认频道回退。
|
||||
`targets` 的每一项都是一个推送目标,因此一条路由可同时转发到多个频道(例如一个 Discord 频道**和**一个 Telegram 群组)。`target.platform` 选择平台:`discord`(默认)、`telegram` 或 `feishu`。**Discord** 目标要求 `target.channelId`(可选 `target.threadId` 指定子区);**Telegram** 目标要求 `target.chatId`(群组/超级群组 id,如 `-1001234567890`),可选 `target.topicId`(话题的 `message_thread_id`,相当于 Discord 子区);**飞书**目标要求 `target.chatId`(群聊 id,`oc_…`),没有话题。没有默认频道回退。
|
||||
|
||||
目标 id 会校验为唯一的写法(否则可以绕过跨分组归属检查):
|
||||
|
||||
- **Discord** —— `channelId` / `threadId` 只能包含 `A–Z a–z 0–9 _ -`(最多 64 个字符);纯数字 id 不能以 0 开头。
|
||||
- **Telegram** —— `chatId` 为规范写法的数字 chat id(无前导零,最多 15 位;不接受 `@username`);`topicId` 为不超过 2147483647 的正整数。
|
||||
- 同一路由不能重复列出同一目的地:`{ "channelId": T }` 与 `{ "channelId": P, "threadId": T }` 都发往子区 `T`,视为同一目的地;写法不同的 Telegram 话题 id 同理。
|
||||
|
||||
| 字段 | 类型 | 必需 | 说明 |
|
||||
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------- |
|
||||
| `groupId` | string | 是 | 路由所属[分组](./groups)的 id |
|
||||
| `fallback` | boolean | 否 | 为 `true` 时仅在本分组没有其他非 fallback 路由匹配时才触发;其过滤器仍会生效 |
|
||||
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估本分组的后续路由 |
|
||||
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id;仅对 Discord 目标生效 |
|
||||
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id(最多 50 个);仅对 Discord 目标生效 |
|
||||
| `ast` | object | 否 | 布尔过滤器树(`{all:[...]}` / `{any:[...]}` / `{not:{...}}`);存在时优先于 `filters` |
|
||||
|
||||
## 路由顺序
|
||||
@@ -45,6 +51,10 @@
|
||||
|
||||
**升级提示:** 如果现有配置依赖某个分组的 `stop` 阻止其他分组的路由执行,或依赖某个分组的普通路由匹配来抑制其他分组的兜底路由发送,请在升级时检查现有路由。这些行为现在仅在同一分组内生效,因此其他分组的路由可能开始发送消息。请将需要共同排他的路由移至同一分组,再检查它们的顺序及 `stop` / `fallback` 设置。
|
||||
|
||||
## 不可读的路由
|
||||
|
||||
存储中无法读取的路由——JSON 损坏、字段结构错误、过滤条件不合法,或匹配器无法编译的模式(例如为其他引擎写的前瞻正则)——绝不会被当作"不匹配"。该分组的投递会可见地失败并重试(其他分组不受影响),`GET /admin/api/groups/:id/routes` 会返回 `unreadable: true`。存在这类行时,保存该分组的路由会被拒绝,避免它在看不见的情况下被删除;如需有意替换,保存时带上 `discardUnreadable: true`。
|
||||
|
||||
## Discord 身份组提醒
|
||||
|
||||
在路由上设置 `discordRoleIds` 可在其触发时提醒一个或多个 Discord 身份组(角色)。提醒(`<@&roleId>`)会加在路由所有 **Discord** 目标的消息内容前;Telegram 目标忽略该字段。只有当机器人拥有 `Mention Everyone` 权限(或身份组标记为可提及)且能看到该身份组时,提醒才会触发通知。
|
||||
@@ -79,13 +89,13 @@
|
||||
"filters": [
|
||||
{ "type": "repo", "match": "myorg/backend" },
|
||||
{ "type": "event", "match": "pull_request" },
|
||||
{ "type": "actor", "match": "[bot]", "exclude": true }
|
||||
{ "type": "actor", "match": "*[bot]", "exclude": true }
|
||||
],
|
||||
"targets": [
|
||||
{
|
||||
"platform": "telegram",
|
||||
"chatId": "-1001234567890",
|
||||
"topicId": "9876543210"
|
||||
"topicId": "42"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+53
-37
@@ -4,58 +4,74 @@
|
||||
|
||||
KV 只保留缓存数据和短期/临时状态。高频写入(webhook 去重、投递状态、消息追踪)存放在 D1,仅在 D1 不可用或未迁移时才回退到 KV(见[存储决策](#存储决策))。
|
||||
|
||||
| 键模式 | 值 | TTL |
|
||||
| ------------------------------------------ | ----------------------------------------------------------------------------- | ------------------ |
|
||||
| `config:routes` | 路由配置缓存(D1 `d1_routes` 为权威数据源) | 1 小时 |
|
||||
| `config:groups` | 分组配置缓存(D1 `d1_groups` 为权威数据源) | 1 小时 |
|
||||
| `session:{id}` | 管理员会话 `{ userId, login }` | 7 天 |
|
||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, refreshToken? }` | 0.9 × Token 有效期 |
|
||||
| `token-reverse:{sha256}` | 用于按 Token 反查的用户 id | 0.9 × Token 有效期 |
|
||||
| `state:{hex}` | `{ redirectTo, expiresAt, discordUserId?, telegramUserId?, telegramChatId? }` | 600 秒 |
|
||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note? }` | 7 天 |
|
||||
| `invite:group:{id}` | 每组的 Token 索引(保证邀请列表一致性) | 7 天 |
|
||||
| `delivery:{provider}:{groupId}:{id}` | Webhook 投递去重回退(D1 `dedup_keys` 为主) | 7 天 |
|
||||
| `delivery-state:{provider}:{groupId}:{id}` | 队列投递状态回退(D1 `delivery_state` 为主) | 1 小时 |
|
||||
| `queue:payload:{provider}:{groupId}:{id}` | 暂存供队列消费者读取的超大 webhook 负载(R2 为主) | 1 小时 |
|
||||
| `nonce:{nonce}` | 自定义 webhook 重放防护 nonce(一次性) | 600 秒 |
|
||||
| `tenant:{groupId}` | 分组 webhook secret(64 位 hex,控制台生成) | 永久 |
|
||||
| `msg:{routeId}:{key}:{target}` | 消息 id 追踪回退(D1 `message_tracking` 为主) | 1 天 |
|
||||
| `cmd:guild:{id}` | 已注册命令的服务器 id(去重) | 永久 |
|
||||
| `cmd:registered:global` | 全局命令注册标记(去重) | 1 天 |
|
||||
| `config:discord-app-id` | 缓存的 Discord 应用 id | 永久 |
|
||||
| `i18n:{lang}` | 叠加在英文之上的翻译覆盖 | 永久 |
|
||||
| 键模式 | 值 | TTL |
|
||||
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
|
||||
| `config:routes` / `config:groups` | 旧版(D1 之前)配置,仅在 D1 表为空时读取一次用于播种 | 永久 |
|
||||
| `config:d1-seeded` | 标记 D1 已播种(已清空的 D1 不会被再次播种) | 永久 |
|
||||
| `session:{id}` | 管理员会话 `{ userId, login, loginTrusted }` | 1 天 |
|
||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, live? }`(Token 可使用 10 小时) | 9 小时 |
|
||||
| `token-reverse:{sha256}` | 用于按 Token 反查的用户 id | 9 小时 |
|
||||
| `state:{hex}` | `{ redirectTo, expiresAt, link? }`(`link`:机器人 `/gh login` 要绑定的聊天账号) | 600 秒 |
|
||||
| `link:{nonce}` | 等待 GitHub 用户确认的机器人账号绑定 | 600 秒 |
|
||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note?, groupInstance, issuer }` | 7 天 |
|
||||
| `invite:group:{id}` | 每组的 Token 索引(保证邀请列表一致性) | 7 天 |
|
||||
| `invite:by-group:{id}:{token}` / `invite:by-instance:{instance}:{token}` | 每个邀请的列表标记(按分组 id 与签发分组的 instance),并发创建或改名中断时邀请也不会从列表中消失 | 邀请有效期 |
|
||||
| `login-owner:{login}` | 第一个使用该登录名的 GitHub 账号 id;之后用同名登录的其他账号只按 user id 匹配 | 永久 |
|
||||
| `delivery:{provider}:{scope}:{id}` | Webhook 投递去重回退(D1 `dedup_keys` 为主);全局入口的 `scope` 为 `@global`,分组入口为 `@i:{instance}`(接收分组不可变的 instance) | 2~10 分钟 |
|
||||
| `delivery-state:{provider}:{scope}:{id}` | 队列投递状态回退(D1 `delivery_state` 为主) | 7 天 |
|
||||
| `queue:payload:{provider}:{scope}:{id}:{uuid}` | 未绑定 R2 时暂存供队列消费者读取的超大 webhook 负载(每次入队一个键) | 4 天 |
|
||||
| `tenant:{groupId}` / `tenant:i:{instance}` | 旧版分组 webhook secret,仅在密钥尚未存入 D1 分组行时作为回退读取;轮换或删除时清除 | 永久 |
|
||||
| `group:renamed:{oldId}` | 仅 KV 部署:分组改名后的新 id(有 D1 时该别名是改名事务中写入的 `dedup_keys` 行) | 4 天 |
|
||||
| `msg:{chain}:{platform}:{target}` | 消息追踪回退(D1 `message_tracking` 为主) | 30 天 |
|
||||
| `msg:lock:…` | D1 不可用时串行化同一消息链更新的锁(有 D1 时是 `dedup_keys` 行) | 240 秒 |
|
||||
| `storage:kv-fallback` | 标记曾在 D1 表缺失时把状态写入 KV;有效期内 D1 未命中时也会查 KV | 35 天 |
|
||||
| `cmd:guilds:{appId}` | 每个 Discord 应用一条:各服务器已注册命令的哈希与同步游标 | 永久 |
|
||||
| `cmd:registered:global:{appId}` | 最近一次全局注册的命令哈希(变化时重新注册,并每天一次) | 1 天 |
|
||||
| `config:discord-app-id:{tokenHash}` | 按 bot token 解析出的 Discord 应用 id | 永久 |
|
||||
| `discord-modal:{id}` | 评论模态框上下文,仅在放不进 100 字符的 `custom_id` 时写入 | 1 天 |
|
||||
| `feishu:token:{appId}` | 每个飞书应用的 `tenant_access_token`(内存中也会保留) | Token 有效期 − 6 分钟 |
|
||||
| `telegram:webhook:{botId}` | 最近一次 webhook 注册内容的哈希(相同时跳过 `setWebhook`) | 1 天 |
|
||||
| `i18n:{lang}` | 叠加在英文之上的翻译覆盖 | 永久 |
|
||||
| `config:identity-migrated` | 仅 KV 部署:分组身份已由本服务器管理(一次性身份迁移已执行) | 永久 |
|
||||
|
||||
## D1 存储布局
|
||||
|
||||
D1 数据库(`DB` 绑定,数据库 `webhooker`)保存配置、投递日志和高频临时状态的权威数据源:
|
||||
|
||||
| 表 | 用途 |
|
||||
| ------------------ | ----------------------------------------------------------------------------- |
|
||||
| `d1_groups` | 分组(权威配置,从旧版 KV `config:groups` 播种) |
|
||||
| `d1_routes` | 每组分组的路由(权威配置,从旧版 KV `config:routes` 播种) |
|
||||
| `send_logs` | 每次分发尝试一行(路由 id、事件、目标、ok/error、耗时、错误码、详情) |
|
||||
| `audit_logs` | 每次管理员操作一行(登录/登出、分组/路由/成员/邀请变更) |
|
||||
| `dedup_keys` | Webhook 投递去重(原子 `INSERT ... ON CONFLICT` UPSERT,键 + 过期时间) |
|
||||
| `delivery_state` | 队列投递状态(`pending`/`processing`/`delivered`/`retrying`/`failed`/`dead`) |
|
||||
| `message_tracking` | 原地更新用消息 id 追踪(`event_id` + `target_id` → `message_id`) |
|
||||
| `discord_links` | 映射 `discord_user_id` → `github_user_id`,供 `/gh` Discord 命令使用 |
|
||||
| `telegram_links` | 映射 `telegram_user_id` → `github_user_id`,供 `/gh` Telegram 命令使用 |
|
||||
| 表 | 用途 |
|
||||
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `d1_groups` | 分组(权威配置,从旧版 KV `config:groups` 播种)。每行还保存不会发给控制台的服务端字段:不可变的 `instance`、`legacyId` 以及分组 webhook 密钥 |
|
||||
| `d1_routes` | 每组分组的路由(权威配置,从旧版 KV `config:routes` 播种) |
|
||||
| `send_logs` | 每次分发尝试一行(路由 id、事件、目标、ok/error、耗时、错误码、详情) |
|
||||
| `audit_logs` | 每次管理员操作一行(登录/登出、分组/路由/成员/邀请变更) |
|
||||
| `dedup_keys` | 原子的一次性占用与记录(`INSERT ... ON CONFLICT` UPSERT,键 + 过期时间):webhook 投递去重及其确认(`accepted:*`)、自定义 webhook nonce(`nonce:{secret 作用域}:{nonce}`)、已使用与已撤销的邀请(`invite-used:*`、`invite-revoked:*`)、机器人命令/事件去重(`bot:{platform}:…`)、已撤销的会话与 token 及每个用户当前有效的 token(`session-revoked:*`、`token-revoked:*`、`token-live:*`)、已使用的账号绑定确认(`link-used:*`)、已退役的分组 id(`group-retired:*`)与改名别名(`group-alias:*`)、安装自动配置记录(`installation-provisioned:*`、`installation-bound:*`)、排队投递中已完成或已永久失败的路由 × 目标(`delivery-target:*`、`delivery-failed:*`)、已发送的分组日志摘要、消息链锁(`msg:lock:*`)以及一次性初始化标记 |
|
||||
| `delivery_state` | 队列投递状态(`pending`/`processing`/`delivered`/`retrying`/`failed`/`dead`);领取投递是一次条件 UPSERT(租约),两个消费者不会同时分发同一投递 |
|
||||
| `message_tracking` | 原地更新用消息追踪(`event_id` + `target_id` → 消息 id 及其所显示的版本);消息链按分组 instance 建键,之后以同一 id 新建的分组不会编辑这些消息 |
|
||||
| `d1_fragments` | 每个分组的命名过滤器片段 |
|
||||
| `feishu_links` | 映射 `feishu_user_id` → `github_user_id`,供 `/gh` 飞书命令使用 |
|
||||
| `discord_links` | 映射 `discord_user_id` → `github_user_id`,供 `/gh` Discord 命令使用 |
|
||||
| `telegram_links` | 映射 `telegram_user_id` → `github_user_id`,供 `/gh` Telegram 命令使用 |
|
||||
|
||||
`audit_logs` 由定时任务在 `AUDIT_RETENTION_DAYS`(默认 90)后自动清理。`storage-prune` 任务会清理过期的 `dedup_keys`、超过 7 天的 `delivery_state` 行以及超过 30 天的 `message_tracking` 行。日志行字段说明见[日志](./logs)。
|
||||
`audit_logs` 由定时任务在 `AUDIT_RETENTION_DAYS`(默认 90)后自动清理。`storage-prune` 任务会清理过期的 `dedup_keys`、超过 7 天的 `delivery_state` 行、30 天未更新的 `message_tracking` 行(每次编辑都会刷新)以及遗留的 R2 负载。`send_logs` 不会自动清理。日志行字段说明见[日志](./logs)。
|
||||
|
||||
迁移 `0013_prune_indexes.sql` 增加了这些读取依赖的索引:清理用的 `delivery_state(updated_at)`、统计页用的两个只含失败 `send_logs` 行的部分索引,以及替换单列分组索引的 `audit_logs(group_id, ts)`。索引列每次写入也会多计一行 D1 写入,因此只添加读取节省远大于写入成本的索引。
|
||||
|
||||
## R2 存储布局
|
||||
|
||||
R2(`PAYLOAD` 绑定,bucket `webhooker-payloads`)存储对队列消息或 KV 来说过大的 webhook 负载:
|
||||
|
||||
| 对象模式 | 用途 | 保留期 |
|
||||
| --------------------------------- | ------------------------------ | ---------- |
|
||||
| `webhooks/YYYY/MM/DD/<uuid>.json` | 暂存供队列消费者读取的超大负载 | 分发后删除 |
|
||||
| 对象模式 | 用途 | 保留期 |
|
||||
| --------------------------------- | ------------------------------ | ------------------------------- |
|
||||
| `webhooks/YYYY/MM/DD/<uuid>.json` | 暂存供队列消费者读取的超大负载 | 分发后删除;遗留对象 5 天后清理 |
|
||||
|
||||
当缺少 `PAYLOAD` 绑定时,超大负载回退到 KV 键 `queue:payload:{provider}:{groupId}:{id}`(1 小时 TTL)。
|
||||
队列消息超过 120,000 字节(UTF-8)时暂存负载。当缺少 `PAYLOAD` 绑定时,超大负载回退到 KV 键 `queue:payload:{provider}:{scope}:{id}:{uuid}`(4 天 TTL,与队列消息保留期一致)。发送队列消息失败时暂存副本会保留(调用失败时队列也可能已经收下消息);未被使用的副本会过期或被清理。消费者需要时暂存负载已丢失,绝不会以空事件分发:投递保持 `retrying`,并写入一条 `PAYLOAD_MISSING` 发送日志,提示从源头重新投递该 webhook。
|
||||
|
||||
## 存储决策
|
||||
|
||||
- **D1 是配置与投递元数据的权威数据源**;KV 只保存缓存和短期状态。
|
||||
- `canUseD1` 探测(`server/lib/storage/d1.ts`,检查 `prepare` + `batch`)为每个 D1 存储做门槛判定:当 D1 不可用或尚未迁移时,三种高频存储(去重、投递状态、消息追踪)都会透明回退到 KV,迁移期间行为不变。
|
||||
- `canUseD1` 探测(`server/lib/storage/d1.ts`,检查 `prepare` + `batch`)为每个 D1 存储做门槛判定。高频存储(去重及其他一次性占用、投递状态、消息追踪)在其 D1 表尚不存在时(数据库未迁移)回退到 KV。其他 D1 故障会直接抛出——请求返回错误,由发送方或队列重试——因为按调用切换存储会让同一占用分散在 D1 与 KV 两处。
|
||||
- D1 配置读取失败时,请求返回错误,由发送方或队列重试;配置没有 KV 副本,分发也绝不会把不可读的配置当作空配置。存储中无法读取的路由或分组行只会让所属分组的投递可见地失败并重试——见[路由 → 不可读的路由](./routes#不可读的路由)。
|
||||
- 配置写入从不回退:存在 D1 绑定时,写入失败会作为错误返回,而不是暂存到 KV。写入按分组进行(单行,或单个分组的路由/片段在一个事务中),分组行使用比较并交换,不同分组的并发编辑互不覆盖。权限检查、读改写路径、webhook 入口与队列消费者的读取绕过所有缓存(撤销的路由或目标立即停止投递);其他读取在每个 isolate 的内存中最多缓存 60 秒。
|
||||
- 旧版 KV 配置只在两张 D1 表都为空时复制一次,且从不覆盖已有行;标记位保证被清空的配置不会复活。
|
||||
- 这让 Workers 免费版的每事件 KV 写入趋近于零(每日 1000 次写):去重、投递状态和消息追踪改为写 D1 行(D1 免费版每日可写 10 万行)。
|
||||
- R2 免费额度(10 GB-月存储、每月 100 万次 A 类操作)可以轻松承载负载暂存,不占用 KV 写配额。
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
WebHooker 通过定时触发器(`*/5 * * * *`,每 5 分钟)运行四个维护任务。它们只在部署后的 Worker 上运行(Cloudflare cron);本地 `wrangler dev` 可用 `wrangler dev --test-scheduled` 触发。
|
||||
|
||||
| 任务 | 用途 |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
|
||||
| `discord-sync` | 注册 Discord 斜杠/右键菜单命令:按服务器即时注册,并全局注册(24h 去重,约 1 小时传播) |
|
||||
| `telegram-sync` | 调用 `setWebhook` 指向 `{BASE_URL}/telegram/webhook`(设置了 `TELEGRAM_WEBHOOK_SECRET` 时作为 `secret_token` 传入) |
|
||||
| `audit-prune` | 删除早于 `AUDIT_RETENTION_DAYS`(默认 90)天的 `audit_logs` 记录 |
|
||||
| `storage-prune` | 删除已过期的 `dedup_keys` 记录、超过 7 天的 `delivery_state` 记录和超过 30 天的 `message_tracking` 记录 |
|
||||
| 任务 | 用途 |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `discord-sync` | 注册 Discord 斜杠/右键菜单命令:按服务器即时注册(每轮最多 30 次 API 调用,从上一轮停下的位置继续),并全局注册(约 1 小时传播);命令定义变化时重新注册 |
|
||||
| `telegram-sync` | 调用 `setWebhook` 指向 `{BASE_URL}/telegram/webhook`,以 `TELEGRAM_WEBHOOK_SECRET`(或由 `TELEGRAM_TOKEN` 派生的值)作为 `secret_token`——仅在注册内容变化时,以及每天一次 |
|
||||
| `audit-prune` | 删除早于 `AUDIT_RETENTION_DAYS`(默认 90)天的 `audit_logs` 记录 |
|
||||
| `storage-prune` | 删除已过期的 `dedup_keys` 记录、超过 7 天的 `delivery_state` 记录、超过 30 天的 `message_tracking` 记录以及遗留的 R2 负载 |
|
||||
|
||||
除任务用到的密钥(`DISCORD_TOKEN`、`DISCORD_APPLICATION_ID`、`TELEGRAM_TOKEN`、`BASE_URL`、`AUDIT_RETENTION_DAYS`)外无需其他配置。
|
||||
Reference in new issue
Block a user