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.
This commit is contained in:
翅膀 committed 2026-10-23 23:24:05 +08:00
1 parent a62044f359
commit 5fcb129170
47 files changed
+938 -660

No files matched your search

+6 -2
View File
@@ -15,15 +15,19 @@ DISCORD_APPLICATION_ID=your-application-id
# Telegram
TELEGRAM_TOKEN=your-bot-token
TELEGRAM_WEBHOOK_SECRET=your-webhook-secret
TELEGRAM_WEBHOOK_SECRET=your-webhook-secret # optional: derived from TELEGRAM_TOKEN when unset
# TELEGRAM_RICH_HEADER_HOST=https://your-domain
# Feishu (Lark / 飞书)
FEISHU_APP_ID=your-app-id
FEISHU_APP_SECRET=your-app-secret
# Inbound commands/buttons need at least one of these (Events & Callbacks → Encryption Strategy):
FEISHU_ENCRYPT_KEY=your-encrypt-key
FEISHU_VERIFICATION_TOKEN=your-verification-token
# Admin
ADMIN_USER_IDS=your-github-id,your-github-login
# Prefer numeric GitHub user ids: a login is bound to the first account that signs in with it
ADMIN_USER_IDS=your-github-id
# DEBUG_MODE=true # local development only: bypasses all admin authentication
# ALLOW_SELF_SIGNUP=1 # non-admin GitHub users get a personal group on first login (default off)
# AUDIT_RETENTION_DAYS=90 # audit log retention for the scheduled cleanup (default 90)
+74 -51
View File
@@ -8,24 +8,25 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
## Key Decisions
- Runtime: Cloudflare Workers via the Nitro `cloudflare_module` preset (`_worker.js`), H3 event handlers in `server/routes/`
- Runtime: Cloudflare Workers via the Nitro `cloudflare_module` preset (entry `.output/server/index.mjs`), H3 event handlers in `server/routes/`
- UI: Vue 3 + Tailwind CSS v4 (`@tailwindcss/vite`) + `@elysola/ui` (Nuxt module, `Rc` prefix); admin console is a client-side SPA (`routeRules: "/admin/**": { ssr: false }`), home/legal pages render server-side; app-level composites (`FilterCombobox`, `ConfirmDialog`) are built on the reka-ui primitives that `@elysola/ui` ships (same copy, pre-bundled via `vite.optimizeDeps.include` so dev keeps a single instance and dialogs/popovers stack correctly) and styled like their Rc counterparts
- Styling: Elysola UI supplies semantic components and blue theme tokens; `app/assets/css/main.css` retains `--wh-*` RGB-triplet aliases for app-specific Tailwind utilities and bespoke layouts (avoiding collision with Elysola's `--surface`/`--text`/`--border` hex tokens); theme switching supports auto/light/dark via `useTheme` / `ThemeToggle`, toggling `<html>.dark` with inline anti-flash head script
- Discord interactions: HTTPS Interactions Endpoint (`POST /discord/interactions`, Ed25519-signed) — no Discord Gateway / Durable Object; bot stays offline, messages always sent via REST
- Storage: D1 is the source of truth for config (routes/groups via `d1_routes`/`d1_groups`, see `server/lib/storage/config-store.ts`; each route's per-group order lives in `d1_routes.position` — migration 0012 — and routes load ordered by `group_id, position, id`, falling back to id order on an unmigrated database), send/audit logs, dedup (`dedup_keys`), delivery state (`delivery_state`) and message tracking (`message_tracking` via `server/lib/storage/d1.ts` `canUseD1` gate). KV keeps only cache + short-lived/ephemeral state (tokens, OAuth state, admin sessions, `msg:*`-adjacent locks, per-group secrets `tenant:*`, invites, i18n overrides) with explicit TTLs. R2 parks oversized queue payloads (`webhooks/YYYY/MM/DD/*.json`, `server/lib/storage/payload.ts`) instead of KV. A `storage-prune` scheduled task cleans up expired dedup/delivery/message-tracking rows
- Storage: D1 is the source of truth for config (routes/groups via `d1_routes`/`d1_groups`, see `server/lib/storage/config-store.ts`; each route's per-group order lives in `d1_routes.position` — migration 0012 — and routes load ordered by `group_id, position, id`, falling back to id order on an unmigrated database). Config writes are per group — one group row (`createGroup` insert-if-absent, `updateGroup` compare-and-swap on `d1_groups.version`), one group's routes or fragments in one transaction (`saveGroupRoutes`, `saveGroupFragments`), `renameGroup`/`deleteGroup` as single batches — and never fall back to KV: a failed D1 write is an error. Access checks, read-modify-write paths, webhook ingress and the queue consumer read with `{ fresh: true }` (no cache, so revoked routes/targets stop at once); other reads are cached in memory ≤60 s per isolate and `loadConfig` returns a fresh object per call. A stored route or group row that cannot be read (corrupt JSON, wrong shape, a pattern RE2 cannot compile) is reported as `unreadable` for its group only: that group's deliveries fail visibly and retry, and its routes cannot be replaced without `discardUnreadable`. Legacy KV `config:*` is seeded into D1 once (marker `config:d1-seeded`, only while both tables are empty); `server/middleware/config-store.ts` binds the D1 store on every request. The admin API returns a content `revision` for every group and per-group route/fragment list and answers `409` when a write's revision is stale; the check runs inside the write's transaction (`groupVersionGuard` aborts the D1 batch unless `d1_groups.version` is unchanged, and every route/fragment write bumps it), so two writes from the same revision can never both succeed. Rename/delete commit history moves/detachment and the retired-id marker in the same batch. Every group carries an immutable server-assigned `instance` (never sent to clients; existing groups got one in a one-time identity migration, which also sets `legacyId`): secrets, invites, delivery/dedup scopes (`@i:{instance}`), target ledgers, message-tracking chains and late send/audit rows follow the instance, so a group re-created under a reused id inherits nothing of the former one. Dispatch never treats unreadable configuration as empty (no KV copy → error → retry). Also in D1: send/audit logs, dedup (`dedup_keys`), delivery state (`delivery_state`) and message tracking (`message_tracking` via `server/lib/storage/d1.ts` `canUseD1` gate). KV keeps only short-lived/ephemeral state (tokens, OAuth state, admin sessions, invites, Feishu token / Discord command-sync / Telegram webhook records, i18n overrides; legacy `tenant:*` secrets are only read as a fallback) with explicit TTLs. R2 parks oversized queue payloads (`webhooks/YYYY/MM/DD/*.json`, `server/lib/storage/payload.ts`) instead of KV. A `storage-prune` scheduled task cleans up expired dedup/delivery/message-tracking rows
- Signature verification: Web Crypto API (HMAC-SHA256 for GitHub/Gitea, Ed25519 for Discord, timing-safe secret-token compare for Telegram)
- Webhook providers: pluggable forge adapters under `server/lib/providers/` (github, gitea) — each verifies its own signature format and normalizes its payload to a GitHub-shaped `WebhookEvent`; a `custom` provider accepts arbitrary signed JSON posts (`X-WebHooker-Signature`) as `custom` events; GitLab etc. can be added later
- Per-group webhook ingress: optional `POST /webhook/{groupId}` with a per-group secret in KV (`tenant:{groupId}`) — Gitea/classic-GitHub/custom webhooks are verified against the group's secret instead of the operator's global ones; only that group's routes fire. The legacy `POST /webhook` (global secrets, all routes) stays untouched
- GitHub App tenant isolation: `Group.installationId` binds a group to one GitHub App installation; events whose `payload.installation.id` differs are rejected at dispatch (hard isolation on top of the optional `owners` list). The App's Setup URL points at `GET /auth/github/install`, which renders a choice page (create `inst-{installationId}` or bind to a group the signed-in user owns, verified by role); `POST /auth/github/install/bind` performs the provisioning. `installation.created` webhook events auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account)
- Per-group webhook ingress: optional `POST /webhook/{groupId}` with a per-group secret stored in the group's D1 row (rotated/removed by CAS with an owner re-check; legacy KV `tenant:*` read as a fallback) — Gitea/classic-GitHub/custom webhooks are verified against the group's secret instead of the operator's global ones; only that group's routes fire. Tenant-signed payloads lose their `installationId` (no App-token enrichment, no installation provisioning; the installation check is skipped for the group's own ingress). The legacy `POST /webhook` (global secrets, all routes except isolated groups without a bound source) stays as before
- GitHub App tenant isolation: `Group.installationId` binds a group to one GitHub App installation; events whose `payload.installation.id` differs are rejected at dispatch (hard isolation on top of the optional `owners` list). The App's Setup URL points at `GET /auth/github/install`, which renders a choice page (create `inst-{installationId}` or bind to a group the signed-in user owns, verified by role); `POST /auth/github/install/bind` performs the provisioning. Both first verify with the user's own OAuth token (scopes `repo read:org`) that they manage the installation (`userManagesInstallation`: the installation's User account, or an active admin of its organization — mere access is not enough; needs `GITHUB_APP_ID`/`GITHUB_PRIVATE_KEY`; super admins bypass); self-signup only makes the installer owner of the dedicated `inst-{id}` group while it is bound to that installation and has no members. Ids `inst-*` / `u-*` are reserved for super admins, and an unbound existing `inst-*` group is never auto-bound. `installation.created` webhook events (global endpoint only) auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account)
- GitHub OAuth: octokit (token is stored hashed for reverse lookup)
- Admin WebUI: `/admin` config console, OAuth-session protected via `ADMIN_USER_IDS` whitelist (local-only `DEBUG_MODE=true` bypasses authentication); left sidebar navigation (Overview / Groups / Send Logs / Audit / Stats) + topbar, deep-linkable routes (`/admin` overview · `/admin/groups` · `/admin/groups/{groupId}` a group's routes, members and webhook · `/admin/logs` · `/admin/audit` · `/admin/metrics`, parsed by `app/utils/admin-path.ts`; the admin page's `validate` 404s any other path) — the page has a fixed `key`, so one console instance (and its in-flight saves) persists across these URLs while each view refreshes its data when shown; every page is a history entry, so the browser's back button returns from a group to the list (no in-page back button) and leaving with an open editor or an unsaved route order asks first; route switches/actions lock while a route write is in flight; sign-out asks for confirmation (sidebar, or a top-right button on narrow screens); editor dialogs open without focusing a field (`useDialogFocus`); the overview dashboard (`AdminHome.vue`) aggregates delivery KPIs, a routes table and recent send logs; the stats page (`MetricsPanel.vue`) renders KPI cards plus per-platform/per-event ok/failed bar legends and a per-status breakdown, and filters by group (`?groupId=`); the route/group editors (`RouteEditor.vue` / `GroupEditor.vue`) are centered, scrollable `RcDialog` forms with an eyebrow header and sectioned bodies
- Access control: every group has role-based members (`owner` / `admin` / `viewer`); super admins bypass; legacy `adminIds` are read as owners (backward compatible); owners manage members + invites; `owners` field stays super-only
- Invites: single-use 7-day links (`invite:{token}`) for joining a group as admin/viewer; `ALLOW_SELF_SIGNUP=1` gives access-less users a personal group on first login (self-service SaaS entry)
- Access control: every group has role-based members (`owner` / `admin` / `viewer`); super admins bypass; legacy `adminIds` are read as owners (backward compatible); owners manage members + invites; the source-isolation fields `owners`, `installationId` and `isolated` stay super-only (an owner's write keeps the stored values). Self-signup personal groups are `isolated: true` — the global endpoint never dispatches to them until a super admin binds a source (`groupAcceptsGlobalIngress`); routes whose group is missing never fire
- Invites: single-use 7-day links (`invite:{token}`, KV TTL derived from `expiresAt`) for joining a group as admin/viewer; an invite belongs to the issuing group's instance; acceptance holds a short claim and commits the `invite-used` record in the same D1 transaction as the CAS member update, guarded so a used or revoked invite (revocations are D1 records) or one whose issuer is no longer an owner never admits anyone; `ALLOW_SELF_SIGNUP=1` gives access-less users an isolated personal group on first login (self-service SaaS entry)
- Group lifecycle (`server/lib/web/group-lifecycle.ts`): delete detaches send/audit history (`group_id = NULL`), drops message tracking, revokes invites + webhook secret and retires the id (`group-retired:{id}` in the idempotency store, 4 days); rename moves routes + fragments and send/audit history atomically and records a `group-alias:*` row (D1, 4 days; KV `group:renamed:*` without D1) in the same transaction so queued tenant deliveries of pre-instance messages follow; secrets, invites and message tracking stay with the instance; the old id is retired
- Audit log: every admin operation (logins, group/route/member/invite changes) recorded in D1 `audit_logs`; pruned by the scheduled trigger after `AUDIT_RETENTION_DAYS` (default 90)
- Group webhook log channel: optional `Group.logTarget` (Discord channel/thread or Telegram chat/topic) receives one summary message per webhook the group's routes dispatched (event, repo, delivery id, per route×target ✅/❌ outcome, green/red color); best-effort, not recorded in `send_logs`
- Per-group forge branding: optional `Group.forgeSources` (a list of `{ host, type: "github" | "gitea", name? }` the group defines itself) labels each message's footer with the first entry whose type matches the event's provider and whose host matches the repository URL's hostname (GitHub matches `github.com`, so two Gitea instances can be `git1.example.com`/`git2.example.com`); the label is the entry's optional `name` (fallback: host); links are derived from the repo URL and footer icons use raster PNGs Discord renders (GitHub's `fluidicon.png`, Gitea's `/assets/img/favicon.png` — `.ico` favicons are silently ignored); Discord shows the footer icon + name, Telegram a linked name
- Delivery queue: when the `QUEUE` binding is present, webhook ingress enqueues one message per event (not per target) to a Cloudflare Queue (`webhooker-delivery`); a Nitro `cloudflare:queue` plugin consumes batches, dispatches, and retries retryable failures (5xx/network/429-exhaustion) with exponential backoff (5s/30s/2m/10m) up to the queue `max_retries`, after which the DLQ (`webhooker-delivery-dlq`) marks the delivery dead. Oversized payloads (>~100 KB) are parked in R2 (`webhooks/YYYY/MM/DD/*.json`, falling back to KV `queue:payload:*` without the R2 binding) and resolved by the consumer; delivery state is tracked as the D1 `delivery_state` table (KV `delivery-state:*` fallback). Without the `QUEUE` binding, dispatch stays inline (existing behavior)
- Storage quotas: the design avoids KV write pressure (Workers Free KV allows ~1,000 writes/day) by keeping high-frequency ephemeral writes in D1 instead — webhook dedup (`dedup_keys`, atomic `ON CONFLICT` UPSERT), delivery state and message tracking all use D1 rows via `canUseD1` (prepare+batch probe) with automatic KV fallback when D1 is unavailable or unmigrated. D1 Free allows 100,000 rows written/day, so the per-event KV write cost drops to ~0; config stays cached in memory + KV with D1 authoritative
- Delivery queue: when the `QUEUE` binding is present, webhook ingress enqueues one message per event (not per target) to a Cloudflare Queue (`webhooker-delivery`) and answers `200` only after the send succeeded (`503` + dedup claim released otherwise); a Nitro `cloudflare:queue` plugin consumes batches, takes each delivery with a 5-minute lease (`acquireDelivery`, conditional UPSERT on `delivery_state`), dispatches, and retries when any target failed transiently (5xx/429/network/rate-limit/`FEISHU_TOKEN`, a crashed route, an unreadable ledger, a busy update lock) with exponential backoff (5s/30s/2m/10m) up to the queue `max_retries`, after which the DLQ (`webhooker-delivery-dlq`) marks the delivery dead. Targets that succeeded or failed permanently are recorded (`delivery-target:*` in the idempotency store, keyed by the group's instance, written right after each target and read with one range query) and skipped on retries, so retries never duplicate and one bad target never cancels the others; a permanent failure is remembered (`delivery-failed:*`) so the delivery ends `failed`, not `delivered`. A message whose storage calls fail is retried on its own (the batch is never failed whole); pre-upgrade `delivery-state:{provider}:{groupId}:*` rows are honored only for the group that owned the id (`legacyId`), never for the global endpoint. The consumer runs `max_batch_size: 3` with one per-batch budget (12 minutes, 20 sends — the D1 query / subrequest limits are per invocation): a message left unstarted is retried (copied instead on its last retry if it was never started), and one that made progress continues in a new message. Oversized payloads (queue message over 120,000 UTF-8 bytes) are parked in R2 (`webhooks/YYYY/MM/DD/*.json`, falling back to KV `queue:payload:*` without the R2 binding, 4-day TTL; kept when the queue send fails, since the queue may have accepted it; orphans pruned by `storage-prune`) and resolved by the consumer — a missing/corrupt parked payload never dispatches `{}`: the delivery stays `retrying` with a `PAYLOAD_MISSING` send-log entry asking for a redelivery; delivery state is tracked as the D1 `delivery_state` table (KV `delivery-state:*` fallback). Without the `QUEUE` binding, dispatch stays inline (existing behavior)
- Storage quotas: the design avoids KV write pressure (Workers Free KV allows ~1,000 writes/day) by keeping high-frequency ephemeral writes in D1 instead — webhook dedup and every other one-time claim (`dedup_keys`, atomic `ON CONFLICT` UPSERT via `idempotencyStore` with `has`/`claim`/`release`), delivery state and message tracking all use D1 rows via `canUseD1` (prepare+batch probe) with automatic KV fallback when D1 is unavailable or a table is missing (`isMissingTable`, unmigrated); other D1 errors propagate so one claim never splits across D1 and KV. D1 Free allows 100,000 rows written/day, so the per-event KV write cost drops to ~0; config is cached in memory only, with D1 authoritative. In-flight work shared across concurrent requests (setup, fallback marker, Feishu / App tokens, translations) goes through `sharedFlight`, which waits on another request's run only for a bounded time (a canceled request's promise may never settle)
- Filter DSL: a route's flat `filters` can be replaced by a nested `ast` (`all`/`any`/`not` nodes, `server/lib/events/filter-ast.ts`) that takes precedence when present; the `field` filter type reads any payload value by JSONPath (`path`, arrays expand so any element matches) and 12 comparison operators (`op`: `eq`/`ne`/`contains`/`startsWith`/`endsWith`/`regex`/`gt`/`gte`/`lt`/`lte`/`in`/`exists`) extend the legacy glob/regex/case-insensitive-exact semantics; named filter fragments (D1 `d1_fragments` via `server/lib/fragments.ts`, per-group) are editor-side templates inlined into the route's `ast` on insert — the matcher never resolves fragment references; the route editor (`RouteEditor.vue`) exposes a recursive AST builder (`FilterNodeEditor.vue`: plain selects for filter type/operator, an all/any segmented toggle, NOT toggle + delete pinned per condition), searchable multi-value / path inputs (`FilterCombobox.vue`) fed by a bilingual suggestion catalog (`app/utils/filter-catalog.ts`: GitHub events/actions from `@octokit/webhooks` plus Gitea extras, common payload paths and their known values, English keys searchable in either language) where custom values are allowed but rejected when the matcher could never match them (`validateFilterValue`), a live explanation and a stateless `POST /admin/api/test-match` dry-run
- Local dev: wrangler + Miniflare
@@ -41,35 +42,42 @@ app/ # Vue 3 UI (Nuxt app dir)
│ # AST builder + FilterCombobox searchable inputs), GroupEditor, MembersPanel, WebhookPanel,
│ # ConfirmDialog (app-wide destructive-action confirm), SendLogs, AuditLog, MetricsPanel,
│ # AppToasts, LegalLayout
├── composables/ # useI18n, useToasts, useConfirm (promise-based confirm), useBackdropGuard (editor dialogs ignore
│ # backdrop clicks), useDialogFocus (editor dialogs open without focusing a field), useGroups, useGroupRoutes, useFilterNode (AST helpers), useFragments, useLogs,
├── composables/ # useApi (ApiError + isConflict for 409s), useI18n, useToasts, useConfirm (promise-based confirm), useBackdropGuard (editor dialogs ignore
│ # backdrop clicks), useDialogFocus (editor dialogs open without focusing a field), useGroups (per-group create/update/remove),
│ # useGroupRoutes + useFragments (send the loaded revision, reload on 409), useFilterNode (AST helpers), useLogs,
│ # useAudit, useInvites, useWebhook
├── types.ts # shared client types (Route, Group, Filter, ...)
└── utils/ # legal.ts (terms/privacy HTML bodies, zh/en), format.ts, admin-path.ts (console URL parsing),
# filter-catalog.ts (bilingual filter suggestions + value/path validators)
server/ # Nitro server
├── routes/ # H3 handlers: /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
│ # /auth/github*, /admin/{login,logout,invite,api/**}, /api/{comment,merge,close,react,richheader}
│ # /auth/github* (incl. POST /auth/github/link — bot account-link confirmation),
│ # /admin/{login,logout,invite,api/**}, /api/{comment,merge,close,react,richheader}
├── middleware/ # config-store (binds the D1 config store on every request)
├── tasks/ # scheduled (cron */5): discord-sync, telegram-sync, audit-prune, storage-prune
├── plugins/ # Nitro plugins: queue-consumer (hooks cloudflare:queue → handleQueueBatch)
├── error-handler.ts # JSON error handler
└── lib/
├── types.ts # Env, Config, Route, Filter, Group, WebhookEvent, NeutralMessage
├── config.ts # loadRoutes/saveRoutes (delegates to D1 ConfigStore when available, else KV config:routes), loadConfig from env
├── fragments.ts # named filter fragments (loadFragments/saveFragments — D1 d1_fragments, no KV)
├── config.ts # getConfigStore/initConfigStore (D1 store, else KV-only), loadRoutes/saveRoutes/saveGroupRoutes, loadConfig (fresh object per call)
├── fragments.ts # named filter fragments (loadFragments(groupId?)/saveGroupFragments — D1 d1_fragments, no KV; read errors propagate)
├── config/ # config schema + migration + validation
│ └── schema.ts # CONFIG_SCHEMA_VERSION, valibot route/group/filter schemas, migrateRoutes/Groups, validateRoutes/Groups (non-destructive), explainRoute
├── cf.ts # cfEnv(event) — env bindings from event.context.cloudflare
├── http.ts # shared HTTP helpers
├── webhook.ts # processWebhook/handleWebhook: tenant lookup, provider detect/verify/parse, dedup (D1/KV), enqueue (or inline dispatch)
├── webhook.ts # processWebhook/handleWebhook: tenant lookup, provider detect/verify/parse, tenant installation strip, dedup (D1/KV), awaited enqueue (503 + claim release on failure) or inline dispatch
├── queue/ # Cloudflare Queue delivery pipeline
│ ├── delivery.ts # DeliveryMessage, enqueueWebhook, retry backoff, delivery-state (D1 w/ KV fallback), payload-overflow parking (R2 → KV)
│ └── consumer.ts # handleQueueBatch: resolve payload → dispatch → classify → ack/retry/DLQ
│ ├── delivery.ts # DeliveryMessage, enqueueWebhook (byte-size check, parked-payload cleanup), classifyDelivery/isRetryableFailure, retry backoff,
│ │ # acquireDelivery lease, delivery-state (D1 w/ KV fallback), per-target done ledger, payload parking (R2 → KV), PayloadUnavailableError
│ └── consumer.ts # handleQueueBatch: lease → resolve payload → dispatch (tenant alias, skipTarget on retries) → classify → ack/retry/DLQ
├── core/
│ └── dispatch.ts # Platform-neutral dispatch: match routes → formatEvent → driver.send/edit (batched recordSend + group filter + per-group webhook log)
│ └── dispatch.ts # Platform-neutral dispatch: source checks (tenant/isolation/installation/owners/providers) → match routes → formatEvent (FORMAT
│ # failures recorded) → driver.send or deliverUpdate (locked, versioned, forge-origin-keyed edit chains) → batched recordSend + group log
├── events/
│ ├── match.ts # matchRoute, eventOwners; unified pattern syntax (*/? globs + //-wrapped regex)
│ └── filter-ast.ts # FilterNode evaluator (all/any/not + field JSONPath + 12 ops), containsKeyword, explainFilter/explainFilterNode; pattern helpers (regex/glob compile)
│ └── filter-ast.ts # FilterNode evaluator (all/any/not + field JSONPath + 12 ops), containsKeyword, explainFilter/explainFilterNode; pattern helpers
│ # (globs and user regexes compiled with RE2 via `re2js` — linear-time matching, no ReDoS; bounded cache with separate
│ # key spaces; regexSafetyIssue rejects patterns RE2 cannot compile, e.g. backreferences/lookaround)
├── providers/ # Forge webhook providers (verify + parse/normalize to GitHub-shaped events)
│ ├── types.ts # Provider interface (matches/verify/parse)
│ ├── hmac.ts # HMAC-SHA256 + timing-safe compare helpers
@@ -100,50 +108,61 @@ server/ # Nitro server
│ │ ├── interactions.ts # Ed25519 verify + interaction handlers (/gh, buttons, modals)
│ │ └── commands.ts # APP_COMMANDS + registerGlobalCommands/syncGuildCommands/syncCommands
│ └── telegram/
│ ├── index.ts # TelegramDriver: send/edit → renderNeutralMessage + rest.sendMessage (avatar rich-header card)
│ ├── index.ts # TelegramDriver: send/edit → renderNeutralMessage + rest.sendMessage/editMessageText (always text messages;
│ │ # avatar as link preview: rich-header card, or the avatar image without a host)
│ ├── render.ts # renderNeutralMessage: NeutralMessage → Telegram HTML (parse_mode HTML)
│ ├── rest.ts # Telegram Bot API sendMessage/sendPhoto/editMessage* (chat_id + message_thread_id), retry
│ ├── updates.ts # POST /telegram/webhook: secret-token verify + handleTelegramUpdate
│ └── commands.ts # Telegram /gh login|logout|comment|merge|close + reply-message parsing + syncTelegramWebhook
│ ├── updates.ts # POST /telegram/webhook: secret-token verify (always) + handleTelegramUpdate
│ ├── secret.ts # telegramWebhookSecret: TELEGRAM_WEBHOOK_SECRET or a secret derived from TELEGRAM_TOKEN
│ └── commands.ts # Telegram /gh login (private chat only)|logout|comment|merge|close + reply-message parsing + update_id dedup + syncTelegramWebhook
│ └── feishu/
│ ├── index.ts # FeishuDriver: send/edit → renderNeutralMessage + rest.sendMessage/updateMessage
│ ├── render.ts # renderNeutralMessage: NeutralMessage → Feishu interactive card
│ ├── rest.ts # getTenantAccessToken (KV cache) + sendMessage/updateMessage/sendText/updateCard, retry
│ └── updates.ts # X-Lark-Signature verify + url_verification + /gh commands + card.action.trigger buttons
│ ├── rest.ts # getTenantAccessToken (memory + KV cache per app, refused tokens dropped) + sendMessage/updateMessage/sendText/updateCard, retry
│ └── updates.ts # FEISHU_ENCRYPT_KEY signature verify + decrypt / FEISHU_VERIFICATION_TOKEN check (refuses all without either) + url_verification
│ # + event_id dedup + /gh commands (login p2p only) + card.action.trigger buttons
├── github/
│ ├── oauth.ts # OAuth URL, callback token exchange, getUserOctokit, comment/getComment/editComment/deleteComment/merge/close actions
│ ├── app-token.ts # createAppJwt-backed getInstallationToken + GITHUB_API_VERSION (shared App auth)
│ ├── oauth.ts # OAuth URL, callback token exchange, getUserOctokit, getInstallationDetails/userManagesInstallation, comment/getComment/editComment/deleteComment/merge/close actions
│ ├── app-token.ts # createAppJwt-backed getInstallationToken + GITHUB_API_VERSION (shared App auth) + githubApiUrl (only https://api.github.com/repos/* is fetched, no redirects)
│ ├── check-run.ts # getCheckSuiteBuildLogUrl: Check-suite build-log enrichment (installation token)
│ ├── workflow-jobs.ts # getWorkflowRunJobs: fetch a workflow_run's jobs via jobs_url (App token or unauthenticated)
│ └── store.ts # KV token CRUD + D1 discord-link/telegram-link mapping (was token-store.ts)
│ └── store.ts # KV token CRUD (rotation drops the old reverse key; findUserIdByToken checks the current stored token) + D1 discord/telegram/feishu links
├── web/ # HTTP UI/API logic (called from server/routes)
│ ├── oauth.ts # handleOAuthStart/Callback, install page + bind, personal-group self-signup
│ ├── oauth.ts # handleOAuthStart/Callback (state cookie for browser logins), bot-link confirmation page + handleLinkConfirm, install page + bind
│ │ # (installation access verified), isolated personal-group self-signup, token delete (own token or super admin)
│ ├── actions.ts # POST /api/comment|merge|close|react (Bearer token auth via shared middleware)
│ ├── admin.ts # adminLogin/Logout, adminApi* (routes|groups|me|logs|invites|audit|webhook|metrics|delivery)
│ ├── admin.ts # adminLogin/Logout, adminApi* (routes|groups|me|logs|invites|audit|webhook|metrics|delivery), per-group create/update/delete,
│ │ # revisions + 409 conflicts, super-only isolation fields, SQL-scoped logs/audit/metrics
│ ├── auth.ts # Shared auth middleware + guards: requireAnyAccess, requireGroup(Role), bearerUserId, clientIp
│ ├── invites.ts # Invite CRUD (KV invite:{token}, 7d TTL) + acceptInvite (join group as admin/viewer)
│ ├── session.ts # Session CRUD (KV session:{id}), isAdminUser, cookie helpers
│ ├── groups.ts # Group CRUD (config:groups), member roles (normalizeGroupMembers/memberRole), resolveScope + role helpers (roleAt/canEditRoutes/canEditGroup)
│ ├── tenants.ts # Per-group webhook secret CRUD (KV tenant:{groupId}, 32-byte random hex)
│ ├── groups.ts # Group CRUD wrappers (create/update CAS/delete/rename via the config store), member roles (normalizeGroupMembers/memberRole),
│ │ # source checks (groupAccepts*), ensureInstallationGroup (lock-free), resolveScope + role helpers (roleAt/canEditRoutes/canEditGroup)
│ ├── group-lifecycle.ts # retire/alias group ids, move/detach group history on rename/delete
│ ├── tenants.ts # Per-group webhook secret (32-byte random hex in the D1 group row, CAS + owner re-check; legacy KV tenant:* read fallback)
│ └── richheader.ts # GET /api/richheader: Open Graph page for Telegram avatar link-preview card
├── observability/ # delivery metrics aggregation
│ └── metrics.ts # DeliveryMetrics + getDeliveryMetrics (SQL GROUP BY over send_logs in one D1 batch: totals, per platform/event/status, duration, attempts, recent failures)
├── storage/ # storage primitives: canUseD1 probe, D1 config store (L1 memory → L2 KV cache → L3 D1), R2 payload store
├── storage/ # storage primitives: canUseD1 probe, D1 config store (memory cache ≤60 s → D1), R2 payload store
│ ├── d1.ts # canUseD1(db) — prepare+batch probe for D1 availability (falls back to KV)
│ ├── config-store.ts # ConfigStore (loadRoutes/saveRoutes/loadGroups/saveGroups/invalidateCache) backed by d1_groups/d1_routes (per-group `position` order when migrated), seeds from KV + syncs cache
│ ├── config-store.ts # ConfigStore: d1ConfigStore (per-group writes, CAS updateGroup, atomic rename/delete, one-time KV seed, one-time identity migration, unreadable-row isolation)
│ │ # and kvConfigStore (no D1); `position` order when migrated; ConfigConflictError
│ └── payload.ts # PayloadStore backed by R2 (webhooks/YYYY/MM/DD/*.json), no-binding stub throws
└── lib/ # shared infra
├── i18n.ts # loadTranslations (KV i18n:{lang} overrides), t() with param interpolation
├── idempotency.ts # IdempotencyStore interface + kvIdempotencyStore/d1IdempotencyStore (delivery dedup via claim/has, D1 atomic UPSERT w/ KV fallback) + deliveryKey
├── idempotency.ts # IdempotencyStore (has/claim/release) + kv/d1 stores (D1 atomic UPSERT, KV fallback only for a missing table) + tenantScope (`@global`) + deliveryKey
├── correlation.ts # newCorrelationId() — per-request/delivery correlation id for logs + responses
├── message-tracker.ts # MessageTracker interface + kvMessageTracker/d1MessageTracker (msg:{eventId}:{targetId} for workflow_run/check_run edits)
├── shared-flight.ts # sharedFlight: in-flight work shared by concurrent requests, waited on for a bounded time
├── message-tracker.ts # MessageTracker (versioned { messageId, version } entries, legacy bare ids read as version 0) + kv/d1 trackers with KV fallback
├── send-log.ts # SendRecord, recordSend/getSendLog/getSendLogById/getSendLogByDelivery/getFailedSendLog (D1 send_logs)
├── send-log-batch.ts # recordSendBatch (D1 batch INSERT for send_logs)
├── audit.ts # recordAudit/getAuditLog/pruneAuditLogs (D1 audit_logs, best-effort writes)
├── log.ts # JSON console logger (info/warn/error/fatal)
└── locales/ # en.ts, zh.ts translation dictionaries
tests/ # bun test unit tests (webhook, formatter, discord, telegram, admin, groups, invites, audit, send-log, token-store, ...)
tests/ # bun test unit tests (webhook, formatter, discord, telegram, admin, groups, invites, audit, send-log, token-store,
# data-integrity, ingress-dispatch, discord-interactions, telegram-webhook, ...)
tests/d1-sqlite.ts # in-memory SQLite behind the D1 API (all migrations applied, FKs on) + a Map-backed KV, for real-SQL tests
tests/fixtures/ # provider payload fixtures (github/gitea/custom) feeding provider + formatter tests
tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
```
@@ -152,16 +171,17 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
- Verify GitHub webhook signatures (Web Crypto HMAC-SHA256, `X-Hub-Signature-256`)
- Verify Gitea webhook signatures (Web Crypto HMAC-SHA256, plain hex `X-Gitea-Signature`)
- Verify custom webhook signatures (Web Crypto HMAC-SHA256, GitHub-style `sha256=` via `X-WebHooker-Signature`; optional replay protection via `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` — signature over `{timestamp}.{nonce}.{body}`, ±5 min window, nonce dedup in KV)
- Verify custom webhook signatures (Web Crypto HMAC-SHA256, GitHub-style `sha256=` via `X-WebHooker-Signature`; optional replay protection via `X-WebHooker-Timestamp` + `X-WebHooker-Nonce` — signature over `{timestamp}.{nonce}.{body}`, ±5 min window, nonces claimed in the idempotency store; only JSON objects are accepted)
- Normalize Gitea webhook payloads to a GitHub-shaped `WebhookEvent` (push `compare_url` → `compare`, `pull_request_comment` → `pull_request_review_comment`, ...)
- Verify Discord interactions (Web Crypto Ed25519, X-Signature-Ed25519 over timestamp + body)
- Verify Telegram webhook calls (X-Telegram-Bot-Api-Secret-Token when configured)
- Verify Telegram webhook calls (X-Telegram-Bot-Api-Secret-Token always: `TELEGRAM_WEBHOOK_SECRET` or a secret derived from `TELEGRAM_TOKEN`; closed without a token)
- Verify Feishu callbacks (`X-Lark-Signature` = SHA-256 of timestamp + nonce + `FEISHU_ENCRYPT_KEY` + body, AES-256-CBC decryption of encrypted bodies, and/or the `FEISHU_VERIFICATION_TOKEN` in the payload; all callbacks are refused when neither is configured)
- Filter events by: event type, repo name, actor, action, branch, keyword, or any payload field (`field` with a JSONPath `path` — arrays expand so any element matches) — every filter type supports `*`/`?` glob matching and `//`-wrapped regular expressions (case-insensitive) plus 12 comparison operators (`op`: `eq`/`ne`/`contains`/`startsWith`/`endsWith`/`regex`/`gt`/`gte`/`lt`/`lte`/`in`/`exists`)
- Combine filters into an AST (`Route.ast`: `all`/`any`/`not` nodes) that overrides the flat `filters` AND-list; `explainRoute`/`explainFilterNode` render a human-readable description of the tree
- Store named filter fragments (D1 `d1_fragments`, per group, `GET`/`PUT /admin/api/groups/:groupId/fragments`) as editor-side templates; inserting a fragment inlines its node into the route's `ast` — dispatch never resolves fragment references
- Offer a stateless filter dry-run (`POST /admin/api/test-match`, body `{ node | filters, event?, payload }`) that evaluates in memory and returns `{ matched, explanation }` — no event payload is stored
- Validate route/group config against valibot schemas on load (non-destructive: invalid entries log a warning but still load); `CONFIG_SCHEMA_VERSION` marks the schema version and `migrateRoutes`/`migrateGroups` migrate legacy shapes (e.g. `target` → `targets`)
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), and skip a group's fallback routes whenever a regular route of that group matched; stop evaluating the group's further routes when a matched route has `stop: true` (both scoped per group, so one group's routes never silence another's)
- Validate route/group config against valibot schemas (`validateRoutes`/`validateGroups` only log warnings; a D1 row that fails the shape checks on load is not loaded but reported as unreadable for its group); `CONFIG_SCHEMA_VERSION` marks the schema version and `migrateRoutes`/`migrateGroups` migrate legacy shapes (e.g. `target` → `targets`)
- Filter routes by group owner restriction (`Group.owners`), group source-platform restriction (`Group.providers`: github/gitea), GitHub App installation restriction (`Group.installationId`), isolation (`Group.isolated` groups take no global-endpoint events without a bound source) and group existence (routes of a missing group never fire) — all before any filter is evaluated — and skip a group's fallback routes whenever a regular route of that group matched; stop evaluating the group's further routes when a matched route has `stop: true` (both scoped per group, so one group's routes never silence another's)
- Auto-provision GitHub App installs: the App's Setup URL flow (`/auth/github/install` choice page + `POST /auth/github/install/bind`, owner-role verified for existing groups) and the `installation.created` webhook fallback both create `inst-{installationId}` groups or bind existing groups
- Enforce role-based access on every admin API: super admins bypass, `owner` manages the group (routes/members/invites/settings), `admin` edits routes, `viewer` is read-only; legacy `adminIds` groups resolve to `owner` members
- Issue single-use 7-day group invite links (`invite:{token}`); accepting joins as admin/viewer (never owner); `ALLOW_SELF_SIGNUP=1` creates a deterministic personal group (`u-{userId}`) on first login
@@ -170,17 +190,18 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
- Format 28 GitHub/Gitea event types plus `custom` webhooks as platform-neutral messages (Discord embeds + Telegram HTML)
- Show the forge source (named per `Group.forgeSources` host entries) in the message footer when the group defines a host matching the event's repository
- Route messages to Discord channels/threads and Telegram chats/topics via REST
- Edit already-sent messages in place for `workflow_run` / `check_run` progress (stable `updateKey`, `message_tracking` via D1 with KV `msg:*` fallback); `workflow_run` keys on the workflow id while `check_run` keys on check name + commit SHA (falling back to the run id) so providers that emit a fresh run id per phase — e.g. Cloudflare Pages — still edit the same message
- Edit already-sent messages in place for `workflow_run` / `check_run` progress (stable `updateKey`, chain keyed by group + route + forge origin (provider@host) + update key and target platform, `message_tracking` via D1 with KV `msg:*` fallback; older events never overwrite newer state, a transient edit failure is reported instead of posting a duplicate, a new message is sent only when the old one is gone); `workflow_run` keys on the run id while `check_run` keys on check suite (or app) + check name + commit SHA (falling back to the run id) so providers that emit a fresh run id per phase — e.g. Cloudflare Pages — still edit the same message
- Record every dispatch attempt to D1 `send_logs` (route id, event, target, ok/error, duration, error code)
- Aggregate delivery metrics (`server/lib/observability/metrics.ts`) from `send_logs` — totals, ok/failed counts + failure rate, per-platform/per-event/per-status breakdowns, average duration and attempts, recent failures; `getDeliveryMetrics(db, groupId?)` sends all seven queries as one D1 `batch` (a single round trip and a consistent snapshot) and scopes every query by `group_id` when a group is passed
- Expose admin observability endpoints — `GET /admin/api/metrics?groupId=` (delivery metrics, optional group scope; recent failures group-scoped for non-super) and `GET /admin/api/delivery/:deliveryId` (all send-log attempts for one delivery, group-scoped) — through the `/admin/api/[...slug]` catch-all route (`server/routes/admin/api/[...slug].ts`) that wires every admin API handler to its method+path
- Serve a per-group webhook ingress (`POST /webhook/{groupId}`, per-group secret in KV `tenant:{groupId}`) for Gitea/classic-GitHub/custom senders; only that group's routes fire; dedup keys are provider- and tenant-scoped (`delivery:{provider}:{groupId}:{id}` via `idempotencyStore`, D1 `dedup_keys` with KV fallback)
- Aggregate delivery metrics (`server/lib/observability/metrics.ts`) from `send_logs` — totals, ok/failed counts + failure rate, per-platform/per-event/per-status breakdowns, average duration and attempts, recent failures; `getDeliveryMetrics(db, groupId?)` sends all five queries as one D1 `batch` (totals, average duration and attempts share one scan) (a single round trip and a consistent snapshot) and scopes every query by `group_id` when a group is passed
- Expose admin observability endpoints — `GET /admin/api/metrics?groupId=` (delivery metrics; every aggregate is limited in SQL to the reader's groups, `getDeliveryMetrics(db, groupId | groupIds)`) and `GET /admin/api/delivery/:deliveryId` (the delivery's attempts that belong to the reader's groups); logs and audit are scoped in SQL before the limit — through the `/admin/api/[...slug]` catch-all route (`server/routes/admin/api/[...slug].ts`) that wires every admin API handler to its method+path
- Serve a per-group webhook ingress (`POST /webhook/{groupId}`, per-group secret in the group's D1 row) for Gitea/classic-GitHub/custom senders; only that group's routes fire; dedup keys are provider- and tenant-scoped (`delivery:{provider}:@i:{instance}:{id}` via `idempotencyStore`, D1 `dedup_keys` with KV fallback)
- Issue a per-request correlation id (`requestId`) in webhook responses and dispatch logs
- When the `QUEUE` binding is present, enqueue each verified webhook as a single Queue message (`webhooker-delivery`) instead of dispatching inline; the consumer resolves the payload, re-scopes routes to the tenant group, and dispatches; retryable failures (5xx/network/429-exhaustion) are retried with exponential backoff (5s/30s/2m/10m) up to the queue `max_retries`, then the DLQ marks the delivery dead
- Track delivery state in the D1 `delivery_state` table (`delivery-state:*` KV fallback: pending/processing/delivered/retrying/failed/dead) so redelivered messages are skipped idempotently; oversized payloads are parked in R2 (`webhooks/YYYY/MM/DD/*.json`, KV `queue:payload:*` fallback) and deleted after dispatch
- Prune expired D1 rows via the scheduled `storage-prune` task (dedup keys past expiry, delivery state older than 7 days, message tracking older than 30 days; audits via `audit-prune`)
- Send a per-event summary (event, repo, delivery id, per route×target ✅/❌ outcome) to the group's `logTarget` when configured
- Serve `/gh` slash commands + message context-menu commands + PR merge/close buttons + comment modals
- Serve `/gh` slash commands + message context-menu commands + PR merge/close buttons (github.com repositories only; deferred replies edited via `/webhooks/{application_id}/{token}/messages/@original`) + comment modals (comments over 4000 characters are edited on GitHub instead); every interaction id runs once
- Link chat accounts to GitHub only after the GitHub user confirms on a page naming both accounts (`POST /auth/github/link`); Telegram/Feishu `/gh login` answers only in private chats
- Serve Telegram `/gh` commands (login/logout/comment/merge/close) via reply-message parsing
- Serve Feishu `/gh` commands (login/logout/comment/merge/close) and card Merge/Close buttons via the `/feishu/webhook` endpoint (X-Lark-Signature verify + `url_verification` challenge)
- Sync application commands from the scheduled trigger (global ~1h propagation + per-guild instant)
@@ -202,7 +223,7 @@ tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
and inline comments use the same `{repo}{#number}: {title}` title as their parent object.
- All event-specific emoji live in `server/lib/formatters/` (via the `emojiPrefix` helper), never in
the locale files. Emoji is controlled per group through the `Group.emoji` toggle (default true);
`showEmoji=false` must strip every emoji from titles, descriptions, fields and links.
`showEmoji=false` must leave out every emoji the formatters add to titles, descriptions, fields and links (text taken from the payload keeps its own emoji).
- Milestone progress bars (🟢🟡🟠⬜) are data visualization and are exempt from the emoji toggle.
- `workflow_run` messages render a **Jobs** field as a Discord `diff` fenced code block
(`server/lib/formatters/workflow.ts`): one line per job, `${marker} ${name} ${emoji}${status}` plus
@@ -259,12 +280,13 @@ Rule: no functional change ships without its documentation; docs and code must n
- **Production**: `wrangler secret put <NAME>` for each secret
- **Routes**: config in D1 `d1_routes`/`d1_groups` (authoritative), seeded from legacy KV `config:routes`/`config:groups` on first load; cache-only KV keys
- **KV namespace**: Required binding for token/state/session/cache storage (dedup/delivery-state/message-tracking fall back to KV when D1 is unavailable)
- **D1 database**: Binding `DB` (database `webhooker`, id `214a0104-3235-47c0-b7bf-ddda95f3c8ac`) for `send_logs` + `audit_logs` + `discord_links` + `telegram_links` + `d1_groups` + `d1_routes` + `d1_fragments` + `dedup_keys` + `delivery_state` + `message_tracking` tables
- **D1 database**: Binding `DB` (database `webhooker`; its id is set in `wrangler.jsonc`) for `send_logs` + `audit_logs` + `discord_links` + `telegram_links` + `d1_groups` + `d1_routes` + `d1_fragments` + `dedup_keys` + `delivery_state` + `message_tracking` tables
- **Queue**: optional `QUEUE` producer binding plus consumers `webhooker-delivery` and its DLQ `webhooker-delivery-dlq` (declared in `wrangler.jsonc`); when absent, webhook dispatch stays inline
- **R2**: optional `PAYLOAD` binding (bucket `webhooker-payloads`) for oversized queue payloads; without it, oversized payloads fall back to KV `queue:payload:*`
- **Access control**: `ADMIN_USER_IDS` (super admins), `DEBUG_MODE=true` (local-only authentication bypass), `ALLOW_SELF_SIGNUP` (optional personal group on first login), `AUDIT_RETENTION_DAYS` (default 90) — all plain env vars, not secrets
- **Discord**: `DISCORD_PUBLIC_KEY` (Interactions Endpoint signature verification, from Discord Developer Portal) and `DISCORD_APPLICATION_ID` (optional, auto-resolved via `GET /oauth2/applications/@me` when omitted) are required for interactions
- **Telegram**: `TELEGRAM_TOKEN` (Bot API token from BotFather) required for Telegram routes; `TELEGRAM_WEBHOOK_SECRET` (optional secret token for `POST /telegram/webhook` verification); avatars are sent as a link-preview card via the built-in `GET /api/richheader` (overridable with `TELEGRAM_RICH_HEADER_HOST`)
- **Telegram**: `TELEGRAM_TOKEN` (Bot API token from BotFather) required for Telegram routes; `TELEGRAM_WEBHOOK_SECRET` (optional secret token for `POST /telegram/webhook` verification — derived from `TELEGRAM_TOKEN` when unset, never disabled); avatars are sent as a link-preview card via the built-in `GET /api/richheader` (overridable with `TELEGRAM_RICH_HEADER_HOST`)
- **Feishu**: `FEISHU_APP_ID` / `FEISHU_APP_SECRET` for sending; inbound commands/buttons need `FEISHU_ENCRYPT_KEY` and/or `FEISHU_VERIFICATION_TOKEN`
- **Webhook providers**: `GITEA_WEBHOOK_SECRET` (required to receive Gitea webhooks; Gitea signs `X-Gitea-Signature` with the hex HMAC-SHA256 of the body)
## Deployment
@@ -280,19 +302,20 @@ bunx wrangler d1 create webhooker
bunx wrangler queues create webhooker-delivery
bunx wrangler queues create webhooker-delivery-dlq
# Queues are declared in wrangler.jsonc (QUEUE binding); no env var needed
bun run db:migrate:prod # wrangler d1 migrations apply webhooker --remote (migrations/0001..0012)
bun run db:migrate:prod # wrangler d1 migrations apply webhooker --remote (migrations/0001..0013)
# R2 bucket for oversized payloads (P0): bunx wrangler r2 bucket create webhooker-payloads
bunx wrangler deploy
bun run deploy # db:migrate:prod (pending migrations only) && wrangler deploy
```
Full list of secrets used: `GITHUB_WEBHOOK_SECRET`, `GITEA_WEBHOOK_SECRET`,
`GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY`
(PKCS#8 PEM), `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `DISCORD_TOKEN`,
`DISCORD_PUBLIC_KEY`, `TELEGRAM_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`, `ADMIN_USER_IDS`, `DEBUG_MODE`,
`DISCORD_PUBLIC_KEY`, `TELEGRAM_TOKEN`, `TELEGRAM_WEBHOOK_SECRET`, `FEISHU_APP_ID`, `FEISHU_APP_SECRET`,
`FEISHU_ENCRYPT_KEY`, `FEISHU_VERIFICATION_TOKEN`, `ADMIN_USER_IDS`, `DEBUG_MODE`,
plus optional `BASE_URL`, `DISCORD_APPLICATION_ID`, `TELEGRAM_RICH_HEADER_HOST`,
`NUXT_PUBLIC_DOCS_URL`, `NUXT_PUBLIC_REPO_URL`, `NUXT_PUBLIC_LEGAL_CONTACT`. See `.env.example` and `docs/guide/configuration.md`.
## Notes
- Commands sync from the scheduled trigger (`*/5 * * * *`): registered per-guild for instant availability and globally (24h dedup, ~1h propagation).
- Commands sync from the scheduled trigger (`*/5 * * * *`): registered per-guild for instant availability (at most 30 API calls per run, resuming from a saved cursor) and globally (~1h propagation); both re-register when the command hash changes, the global set at least daily.
- The bot is always offline (no Discord Gateway); interactions arrive via the HTTP endpoint.
+33 -31
View File
@@ -39,8 +39,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
- **Cloudflare Worker** — HTTP ingress, signature verification, routing, platform dispatch
- **Interactions Endpoint** — HTTPS callback (no Discord Gateway connection, no Durable Object); the bot stays offline and commands are registered via the API
- **KV** — cache + ephemeral state: token storage (`token:{userId}`), OAuth state (`state:{hex}`), admin sessions (`session:{id}`), per-group webhook secrets (`tenant:{groupId}`), invites, config cache, delivery dedup/state/message-tracking **fallback** (`delivery:*`, `delivery-state:*`, `msg:*` used only when D1 is unavailable) and message-update locks (`msg:lock:*`)
- **D1** — source of truth for routes/groups (`d1_routes`/`d1_groups`), named filter fragments (`d1_fragments`), send logs (`send_logs`), audit logs (`audit_logs`), dedup (`dedup_keys`), delivery state (`delivery_state`), message-update tracking (`message_tracking`), Discord↔GitHub links (`discord_links`), Telegram↔GitHub links (`telegram_links`)
- **KV** — cache + ephemeral state: token storage (`token:{userId}`), OAuth state (`state:{hex}`), admin sessions (`session:{id}`), invites, delivery dedup/state/message-tracking **fallback** (`delivery:*`, `delivery-state:*`, `msg:*` used only when D1 is unavailable) and message-update locks (`msg:lock:*`)
- **D1** — source of truth for routes/groups (`d1_routes`/`d1_groups`, including each group's webhook secret), named filter fragments (`d1_fragments`), send logs (`send_logs`), audit logs (`audit_logs`), dedup (`dedup_keys`), delivery state (`delivery_state`), message-update tracking (`message_tracking`), Discord↔GitHub links (`discord_links`), Telegram↔GitHub links (`telegram_links`)
- **Queue** — async delivery when `QUEUE` is bound: `webhooker-delivery` (exponential retry) + DLQ `webhooker-delivery-dlq`; oversized payloads parked in R2 (`PAYLOAD` binding, `webhooks/YYYY/MM/DD/*.json`, falling back to KV `queue:payload:*`)
## Quick Start
@@ -48,42 +48,44 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
```bash
bun install # package manager is bun (lockfile: bun.lock)
cp .env.example .dev.vars # Fill in secrets for local dev
bun run build # Production build first (wrangler dev serves the built worker)
bunx wrangler dev # Start local dev server
bun run db:migrate # Apply the D1 migrations to the local database (first run)
bun run cf:dev # Build, then serve the worker locally with wrangler dev
```
## Configuration
### Secrets (`.dev.vars` for local, Worker Secrets for production)
| Variable | Description |
| --------------------------- | ---------------------------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub |
| `GITEA_WEBHOOK_SECRET` | Webhook secret from Gitea (required only to receive Gitea webhooks) |
| `GITHUB_APP_ID` | GitHub App ID (used by the App install flow to resolve the installing account) |
| `GITHUB_PRIVATE_KEY` | App private key (PKCS#8 PEM; used by the App install flow; optional) |
| `GITHUB_CLIENT_ID` | OAuth client ID |
| `GITHUB_CLIENT_SECRET` | OAuth client secret |
| `DISCORD_TOKEN` | Bot token |
| `DISCORD_PUBLIC_KEY` | Discord application public key (from the Developer Portal) — required for interactions |
| `DISCORD_APPLICATION_ID` | Discord application id (optional; auto-resolved via `GET /oauth2/applications/@me` if omitted) |
| `TELEGRAM_TOKEN` | Telegram bot token (from BotFather) — required for Telegram routes |
| `TELEGRAM_WEBHOOK_SECRET` | Optional secret token for `POST /telegram/webhook` verification |
| `TELEGRAM_RICH_HEADER_HOST` | Optional base URL overriding the built-in `GET /api/richheader` for Telegram avatar cards |
| `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 |
| `BASE_URL` | Public URL for OAuth callbacks and the Telegram webhook sync |
| `ADMIN_USER_IDS` | Comma-separated GitHub user IDs (or logins) allowed to access `/admin` |
| `DEBUG_MODE` | Local development only: set to exact `true` to bypass all `/admin` authentication |
| `ALLOW_SELF_SIGNUP` | `1` to give access-less GitHub users a personal group on first login (default off) |
| `AUDIT_RETENTION_DAYS` | Audit-log retention in days for the scheduled cleanup (default 90) |
| `NUXT_PUBLIC_DOCS_URL` | Optional docs site URL used by the landing page |
| `NUXT_PUBLIC_REPO_URL` | Optional GitHub repo URL used by the landing page |
| `NUXT_PUBLIC_LEGAL_CONTACT` | Optional contact shown on `/terms` and `/privacy` |
| Variable | Description |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub |
| `GITEA_WEBHOOK_SECRET` | Webhook secret from Gitea (required only to receive Gitea webhooks) |
| `GITHUB_APP_ID` | GitHub App ID — the App install flow needs it to verify the installer (otherwise only super admins can bind installations) |
| `GITHUB_PRIVATE_KEY` | App private key (PKCS#8 PEM) — needed together with `GITHUB_APP_ID`; also authenticates API enrichment |
| `GITHUB_CLIENT_ID` | OAuth client ID |
| `GITHUB_CLIENT_SECRET` | OAuth client secret |
| `DISCORD_TOKEN` | Bot token |
| `DISCORD_PUBLIC_KEY` | Discord application public key (from the Developer Portal) — required for interactions |
| `DISCORD_APPLICATION_ID` | Discord application id (optional; auto-resolved via `GET /oauth2/applications/@me` if omitted) |
| `TELEGRAM_TOKEN` | Telegram bot token (from BotFather) — required for Telegram routes |
| `TELEGRAM_WEBHOOK_SECRET` | Optional secret token for `POST /telegram/webhook` verification (derived from the token if unset) |
| `TELEGRAM_RICH_HEADER_HOST` | Optional base URL overriding the built-in `GET /api/richheader` for Telegram avatar cards |
| `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 |
| `FEISHU_ENCRYPT_KEY` | Feishu event Encrypt Key (signature check + decryption) — this or the token below is required for inbound Feishu commands |
| `FEISHU_VERIFICATION_TOKEN` | Feishu event Verification Token, checked on every inbound callback |
| `BASE_URL` | Public URL for OAuth callbacks and the Telegram webhook sync |
| `ADMIN_USER_IDS` | Comma-separated GitHub user IDs (or logins; numeric ids recommended) of super admins |
| `DEBUG_MODE` | Local development only: set to exact `true` to bypass all `/admin` authentication |
| `ALLOW_SELF_SIGNUP` | `1` to give access-less GitHub users a personal group on first login (default off) |
| `AUDIT_RETENTION_DAYS` | Audit-log retention in days for the scheduled cleanup (default 90) |
| `NUXT_PUBLIC_DOCS_URL` | Optional docs site URL used by the landing page |
| `NUXT_PUBLIC_REPO_URL` | Optional GitHub repo URL used by the landing page |
| `NUXT_PUBLIC_LEGAL_CONTACT` | Optional contact shown on `/terms` and `/privacy` |
### Routes
Routes are stored in D1 (`d1_routes`, seeded from legacy KV `config:routes` on first load). There are **no default routes** — every route (including its target) must be defined explicitly, either via the Web UI (`/admin`) or by storing a JSON array in D1. A route may carry multiple `targets`, so one rule can forward to several channels at once:
Routes are stored in D1 (`d1_routes`, seeded from legacy KV `config:routes` on first load). There are **no default routes** — every route (including its target) must be defined explicitly, via the Web UI (`/admin`) or the Admin API. A route may carry multiple `targets`, so one rule can forward to several channels at once:
```json
[
@@ -103,7 +105,7 @@ Routes are stored in D1 (`d1_routes`, seeded from legacy KV `config:routes` on f
]
```
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (optional `topicId` for a topic). A route may also set `stop: true` (skip later routes of its group). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
`target.platform` selects the push target: `discord` (default), `telegram`, or `feishu`. Discord targets require `target.channelId` (optional `threadId` for a thread); Telegram targets require a numeric `target.chatId` (optional `topicId` for a topic); Feishu targets require `target.chatId` (`oc_…`; no topics). A route may also set `stop: true` (skip later routes of its group). Routes belong to **groups** (D1 `d1_groups`, seeded from legacy KV `config:groups`) that scope admin access and can restrict which org/user events flow in. See the [Routes & Targets](https://webhooker.docs.elysola.org/guide/routes) and [Groups & Access Control](https://webhooker.docs.elysola.org/guide/groups) guides for the full schema.
### Web UI (`/admin`)
@@ -172,7 +174,7 @@ Every filter supports plain text, `*`/`?` globs, and `/regex/` patterns (case-in
### Bot Commands (comment on GitHub as yourself)
The bot registers native **slash** and **message context-menu** commands, synced by the scheduled trigger (every 5 minutes): per-guild for instant availability, and globally (24h dedup, ~1h propagation). After `/gh login` you can comment on issues/PRs as yourself, edit/delete your comments, and merge/close PRs via buttons — all replies are ephemeral and GitHub enforces permission.
The bot registers native **slash** and **message context-menu** commands, synced by the scheduled trigger (every 5 minutes): per-guild for instant availability, and globally (~1h propagation); both are re-registered when the command definitions change. After `/gh login` you can comment on issues/PRs as yourself, edit/delete your comments, and merge/close PRs via buttons — all replies are ephemeral and GitHub enforces permission.
```
/gh login /gh logout
+34 -31
View File
@@ -39,8 +39,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
- **Cloudflare Worker** — HTTP 入口、签名验证、路由分发
- **Interactions Endpoint** — HTTPS 回调(无 Discord Gateway 连接、无 Durable Object);bot 保持离线,命令通过 API 注册
- **KV** — 缓存 + 临时状态:Token 存储(`token:{userId}`)、OAuth state(`state:{hex}`)、管理员会话(`session:{id}`)、分组级 webhook secret(`tenant:{groupId}`)、邀请、配置缓存、投递去重/投递状态/消息更新追踪的回退(`delivery:*`、`delivery-state:*`、`msg:*` 仅在 D1 不可用时使用)与消息更新锁(`msg:lock:*`)
- **D1** — 路由/分组(`d1_routes`/`d1_groups`)、命名过滤器片段(`d1_fragments`)、发送日志(`send_logs`)、审计日志(`audit_logs`)、去重(`dedup_keys`)、投递状态(`delivery_state`)、消息更新追踪(`message_tracking`)、Discord↔GitHub 绑定(`discord_links`)、Telegram↔GitHub 绑定(`telegram_links`)
- **KV** — 缓存 + 临时状态:Token 存储(`token:{userId}`)、OAuth state(`state:{hex}`)、管理员会话(`session:{id}`)、邀请、投递去重/投递状态/消息更新追踪的回退(`delivery:*`、`delivery-state:*`、`msg:*` 仅在 D1 不可用时使用)与消息更新锁(`msg:lock:*`)
- **D1** — 路由/分组(`d1_routes`/`d1_groups`,含各分组的 webhook 密钥)、命名过滤器片段(`d1_fragments`)、发送日志(`send_logs`)、审计日志(`audit_logs`)、去重(`dedup_keys`)、投递状态(`delivery_state`)、消息更新追踪(`message_tracking`)、Discord↔GitHub 绑定(`discord_links`)、Telegram↔GitHub 绑定(`telegram_links`)
- **Queue** — 绑定 `QUEUE` 时异步投递:`webhooker-delivery`(指数退避重试)+ 死信队列 `webhooker-delivery-dlq`;超大负载暂存于 R2(`PAYLOAD` 绑定,`webhooks/YYYY/MM/DD/*.json`,回退 KV `queue:payload:*`)
## 快速开始
@@ -48,42 +48,44 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
```bash
bun install # 包管理器为 bun(锁文件:bun.lock)
cp .env.example .dev.vars # 填写本地开发密钥
bun run build # 先构建生产产物(wrangler dev 运行的是构建产物)
bunx wrangler dev # 启动本地开发服务器
bun run db:migrate # 将 D1 迁移应用到本地数据库(首次运行)
bun run cf:dev # 先构建,再用 wrangler dev 在本地运行 worker
```
## 配置
### 密钥(本地用 `.dev.vars`,生产用 Worker Secrets)
| 变量 | 说明 |
| --------------------------- | --------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 |
| `GITEA_WEBHOOK_SECRET` | Gitea webhook 密钥(仅接收 Gitea webhook 时需要) |
| `GITHUB_APP_ID` | GitHub App ID(用于 App 安装流程解析安装所属账号) |
| `GITHUB_PRIVATE_KEY` | App 私钥(PKCS#8 PEM;用于 App 安装流程,可选) |
| `GITHUB_CLIENT_ID` | OAuth Client ID |
| `GITHUB_CLIENT_SECRET` | OAuth Client Secret |
| `DISCORD_TOKEN` | 机器人 token |
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取)—— 交互功能必需 |
| `DISCORD_APPLICATION_ID` | Discord 应用 ID(可选;省略时通过 `GET /oauth2/applications/@me` 自动获取) |
| `TELEGRAM_TOKEN` | Telegram Bot Token(BotFather 获取)—— Telegram 路由必需 |
| `TELEGRAM_WEBHOOK_SECRET` | 可选;`POST /telegram/webhook` 的验签密钥 |
| `TELEGRAM_RICH_HEADER_HOST` | 可选;覆盖内置 `GET /api/richheader` 的 Telegram 头像卡片地址 |
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
| `BASE_URL` | 公网地址(用于 OAuth 回调与 Telegram webhook 同步) |
| `ADMIN_USER_IDS` | 允许访问 `/admin` 的 GitHub 用户 ID(或登录名),逗号分隔 |
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证 |
| `ALLOW_SELF_SIGNUP` | 设为 `1` 时,无权限的 GitHub 用户首次登录自动获得个人分组(默认关闭) |
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数(默认 90) |
| `NUXT_PUBLIC_DOCS_URL` | 可选;落地页使用的文档站点 URL |
| `NUXT_PUBLIC_REPO_URL` | 可选;落地页使用的 GitHub 仓库 URL |
| `NUXT_PUBLIC_LEGAL_CONTACT` | 可选;`/terms` 与 `/privacy` 页面展示的联系方式 |
| 变量 | 说明 |
| --------------------------- | ----------------------------------------------------------------------------- |
| `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 |
| `GITEA_WEBHOOK_SECRET` | Gitea webhook 密钥(仅接收 Gitea webhook 时需要) |
| `GITHUB_APP_ID` | GitHub App ID——App 安装流程需要它核实安装者(没有时只有超级管理员能绑定安装) |
| `GITHUB_PRIVATE_KEY` | App 私钥(PKCS#8 PEM)——需与 `GITHUB_APP_ID` 一起配置,也用于 API 增强鉴权 |
| `GITHUB_CLIENT_ID` | OAuth Client ID |
| `GITHUB_CLIENT_SECRET` | OAuth Client Secret |
| `DISCORD_TOKEN` | 机器人 token |
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取)—— 交互功能必需 |
| `DISCORD_APPLICATION_ID` | Discord 应用 ID(可选;省略时通过 `GET /oauth2/applications/@me` 自动获取) |
| `TELEGRAM_TOKEN` | Telegram Bot Token(BotFather 获取)—— Telegram 路由必需 |
| `TELEGRAM_WEBHOOK_SECRET` | 可选;`POST /telegram/webhook` 的验签密钥(未设置时由 token 派生) |
| `TELEGRAM_RICH_HEADER_HOST` | 可选;覆盖内置 `GET /api/richheader` 的 Telegram 头像卡片地址 |
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
| `FEISHU_ENCRYPT_KEY` | 飞书事件 Encrypt Key(验签 + 解密)—— 飞书入站命令需要它或下面的 token |
| `FEISHU_VERIFICATION_TOKEN` | 飞书事件 Verification Token,每个入站回调都会校验 |
| `BASE_URL` | 公网地址(用于 OAuth 回调与 Telegram webhook 同步) |
| `ADMIN_USER_IDS` | 超级管理员的 GitHub 用户 ID(或登录名,建议写数字 ID),逗号分隔 |
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证 |
| `ALLOW_SELF_SIGNUP` | 设为 `1` 时,无权限的 GitHub 用户首次登录自动获得个人分组(默认关闭) |
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数(默认 90) |
| `NUXT_PUBLIC_DOCS_URL` | 可选;落地页使用的文档站点 URL |
| `NUXT_PUBLIC_REPO_URL` | 可选;落地页使用的 GitHub 仓库 URL |
| `NUXT_PUBLIC_LEGAL_CONTACT` | 可选;`/terms` 与 `/privacy` 页面展示的联系方式 |
### 路由配置
路由存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 同步)。**没有默认路由**——每条路由(包括目标)都必须显式定义,可通过 Web 控制台(`/admin`)或直接向 D1 存储 JSON 数组。一条路由可携带多个 `targets`,因此一个规则可以同时转发到多个频道:
路由存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 同步)。**没有默认路由**——每条路由(包括目标)都必须显式定义,可通过 Web 控制台(`/admin`)或 Admin API 管理。一条路由可携带多个 `targets`,因此一个规则可以同时转发到多个频道:
```json
[
@@ -103,7 +105,7 @@ bunx wrangler dev # 启动本地开发服务器
]
```
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(可选 `topicId` 指向子话题)。路由还可设置 `stop: true`(跳过本分组的后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
`target.platform` 选择推送目标:`discord`(默认)、`telegram` 或 `feishu`。Discord 目标需 `target.channelId`(可选 `threadId` 指向子区);Telegram 目标需数字形式的 `target.chatId`(可选 `topicId` 指向话题);飞书目标需 `target.chatId`(`oc_…`;没有话题)。路由还可设置 `stop: true`(跳过本分组的后续路由)。路由隶属于**分组**(D1 `d1_groups`,首次加载时从旧版 KV `config:groups` 同步),分组用于限定管理权限,并可限制哪些组织/用户的事件流入。完整模式见[路由与目标](https://webhooker.docs.elysola.org/zh/guide/routes)与[分组与访问控制](https://webhooker.docs.elysola.org/zh/guide/groups)指南。
### Web 控制台(`/admin`)
@@ -167,11 +169,12 @@ bunx wrangler dev # 启动本地开发服务器
- **GitHub App** — 创建应用、订阅事件、配置 OAuth 与 _Setup URL_(租户隔离):见 [GitHub App 配置](https://webhooker.docs.elysola.org/zh/guide/deployment#github-app-设置)
- **Discord 机器人** — 创建机器人、以 `applications.commands` scope 邀请(组合权限整数 `274877910016`)、配置 Interactions Endpoint:见 [Discord Bot 配置](https://webhooker.docs.elysola.org/zh/guide/deployment#discord-bot-设置)。bot 从不连接 Discord Gateway,因此显示为**离线**——消息推送不受影响(始终走 REST)。
- **Telegram 机器人** — 用 [@BotFather](https://t.me/BotFather) 创建机器人,设置 `TELEGRAM_TOKEN`(可选 `TELEGRAM_WEBHOOK_SECRET`);webhook 由定时任务自动同步:见 [Telegram 机器人配置](https://webhooker.docs.elysola.org/zh/guide/deployment#telegram-机器人配置)
- **飞书机器人** — 创建自建应用、开启机器人能力、将机器人加入目标群聊,并设置 `FEISHU_APP_ID` + `FEISHU_APP_SECRET`:见[飞书机器人配置](https://webhooker.docs.elysola.org/zh/guide/deployment#飞书机器人配置)
- **部署** — KV 命名空间、D1 数据库与迁移(含 0008 存储表)、可选 R2 Bucket 与 Queues、密钥、部署:见[部署指南](https://webhooker.docs.elysola.org/zh/guide/deployment)
### Bot 指令(以本人身份评论 GitHub)
bot 通过定时任务(每 5 分钟)同步注册原生的**斜杠命令**与**消息右键菜单命令**:按服务器注册以获得即时可用性,并全局注册(24h 去重,约 1 小时传播)。执行 `/gh login` 后即可评论 issue/PR、编辑/删除自己的评论,并通过按钮合并/关闭 PR——所有回复均为临时消息(仅你可见),权限交由 GitHub 判定。
bot 通过定时任务(每 5 分钟)同步注册原生的**斜杠命令**与**消息右键菜单命令**:按服务器注册以获得即时可用性,并全局注册(约 1 小时传播);命令定义变化时两者都会重新注册。执行 `/gh login` 后即可评论 issue/PR、编辑/删除自己的评论,并通过按钮合并/关闭 PR——所有回复均为临时消息(仅你可见),权限交由 GitHub 判定。
```
/gh login /gh logout
+17 -14
View File
@@ -1,6 +1,8 @@
# Routes
# Example configuration — the schema of groups and routes, shown as YAML.
# The worker does not load this file: configuration lives in D1 and is managed
# from the console (/admin) or the Admin API, which accept the same fields as JSON.
# Each route defines a filter chain and one or more target destinations
# (Discord channel/thread and/or Telegram chat/topic). See docs/guide/configuration.md.
# (Discord channel/thread, Telegram chat/topic, Feishu chat). See docs/guide/routes.md.
# Groups scope admin access and can restrict which org/user events flow in.
groups:
@@ -11,7 +13,7 @@ groups:
- login: "your-github-id"
role: owner
# owners: ["myorg"] # restrict events to this org/user (optional)
# providers: ["github", "gitea"] # restrict to source platforms (optional; empty = all)
# providers: ["github", "gitea", "custom"] # restrict to source platforms (optional; empty = all)
# installationId: 12345678 # GitHub App installation binding (auto-created on installation.created)
# emoji: true # include emoji in messages (default true)
# Forge hosts: label message footers with the host an event came from
@@ -24,9 +26,9 @@ groups:
# type: gitea
# - host: "git2.example.com" # another one
# type: gitea
# lang: "en" # message language for this group's routes (en/zh, default en)
# Webhook log channel: a Discord channel/thread or Telegram chat/topic that
# receives a summary of every webhook this group's routes dispatch.
# lang: "en" # message language for this group's routes (en/zh or a KV i18n:<lang> override; default en)
# Webhook log channel: a Discord channel/thread, Telegram chat/topic or Feishu
# chat that receives a summary of every webhook this group's routes dispatch.
# logTarget:
# platform: discord
# channelId: "CHANNEL_ID_HERE"
@@ -61,11 +63,11 @@ routes:
# - platform: discord
# channelId: "CHANNEL_ID_HERE"
# threadId: "THREAD_ID_HERE"
# - platform: telegram
# chatId: "-1001234567890"
# topicId: "9876543210"
# - platform: feishu
# chatId: "oc_xxxxxxxxxxxxxxxx" # Feishu group chat_id
# - platform: telegram
# chatId: "-1001234567890" # numeric chat id (no @username)
# topicId: "42"
# - platform: feishu
# chatId: "oc_xxxxxxxxxxxxxxxx" # Feishu group chat_id (no topics)
# - id: exclude-bot
# name: "Exclude Bot Actions"
@@ -73,7 +75,7 @@ routes:
# groupId: default
# filters:
# - type: actor
# match: "[bot]"
# match: "*[bot]"
# exclude: true
# targets:
# - platform: discord
@@ -137,12 +139,13 @@ routes:
# - platform: discord
# channelId: "CHANNEL_ID_HERE"
# Nested `ast` groups (all / any / not) replace the flat filters list and take
# precedence over `filters` when both are present.
# Nested `ast` groups (all / any / not) take precedence over the flat `filters`
# list; the route still carries a `filters` list (it may be empty).
# - id: grouped-owners
# name: "PRs from either owner"
# enabled: true
# groupId: default
# filters: []
# ast:
# all:
# - type: event
+11 -11
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
{
+8 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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.
+6 -5
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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).
+2 -2
View File
@@ -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
View File
@@ -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`)
+2 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
{
+9 -7
View File
@@ -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
View File
@@ -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` | 所有事件(搜索完整载荷正文) |
+17 -9
View File
@@ -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#飞书机器人配置)。
+32 -22
View File
@@ -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
View File
@@ -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 用户需在同时显示双方账号的确认页上确认绑定。
### 所需权限
+2 -2
View File
@@ -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
View File
@@ -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 标题和仓库名。请尽量写得更具体。
+6 -5
View File
@@ -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
View File
@@ -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 校验)。
+7 -5
View File
@@ -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 字段)保留其中自带的表情。里程碑进度条(🟢🟡🟠⬜)属于数据可视化,不受该开关影响。
+15 -8
View File
@@ -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#密钥)。
+2 -2
View File
@@ -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
View File
@@ -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`)
+2 -2
View File
@@ -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
View File
@@ -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
View File
@@ -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 写配额。
+6 -6
View File
@@ -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`)外无需其他配置。