mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
fix(security): harden webhook delivery pipeline and group storage (#11)
* fix(log): preserve structured error details Error objects lose their useful details when serialized as plain JSON. Keep the message, stack and cause in structured log output. * fix(runtime): bound shared in-flight waits A canceled request can leave its shared promise pending forever. Bound joins and coordinate a single replacement so later requests make progress without multiplying upstream work. * fix(bot): reject oversized callback bodies Reject declared oversized bot callbacks before reading their bodies. This keeps unauthenticated requests from wasting worker resources. * test(d1): exercise real sqlite transactions Exercise real foreign keys, transactions and conditional statements instead of mocks that cannot reproduce lost updates or cascades. * fix(storage): preserve claims across kv fallback Only missing tables justify KV fallback; other failures must surface. Remember fallback writes so migration to D1 cannot forget claims and replay completed work. Share marker checks without extra writes. * fix(filter): use isolated linear-time patterns Backtracking patterns can exhaust worker CPU on untrusted payloads. Use linear-time matching and separate bounded cache namespaces so glob and regex entries cannot corrupt each other. * fix(filter): read each event branch correctly Deployment and check branches live in event-specific nested fields. Read those fields and remove only the actual leading ref prefix. * fix(filter): read only own payload properties Inherited object properties are not webhook payload data. Read own properties only so JSONPath cannot traverse prototypes. * fix(filter): validate executable condition trees Malformed trees and unsupported patterns must not silently turn an exclude rule into a pass. Validate the shape and only the patterns the evaluator actually executes. * fix(i18n): bound and cache translation loads Repeated misses and simultaneous override loads spend KV reads for the same language. Cache confirmed misses and share bounded loads without caching read failures as missing translations. * i18n(bot): explain command and account failures Explain account linking, command failures and skipped delivery outcomes consistently in both supported languages. * fix(github): bound and reuse app token fetches Repeated token exchanges waste requests and JWT work for every event. Reuse valid installation tokens, share refreshes and back off briefly after failures while keeping every shared wait bounded. * fix(github): restrict enrichment request urls Webhook-provided URLs must never receive an installation token on another host. Restrict enrichment to GitHub repository API paths, reject redirects and bound optional requests. * fix(formatter): preserve invalid code points Out-of-range numeric entities can throw while formatting a delivery. Keep invalid code points verbatim instead of aborting the message. * fix(formatter): preserve bounded markdown text Code spans, fences, indentation and autolinks are Markdown content, not HTML tags to strip. Preserve them while bounding cleanup input and reusing results across routes for the same event. * fix(formatter): strip only leading ref prefixes A short branch or tag may itself contain refs/heads or refs/tags. Strip one leading full-ref prefix at the caller and keep short names unchanged when generating labels and links. * fix(gitea): link push authors to their forge A Gitea author is not the same-named GitHub account. Build author profile links from the originating forge. * fix(formatter): render deployment state values The deployment status object stringifies as [object Object]. Render its actual state in the status field. * fix(formatter): read security severity levels The scanner severity is not the security severity of an alert. Prefer the security level so critical and high alerts get the right label and color. * fix(formatter): hide actions on other forges Action buttons call the GitHub API as the linked user. Hide them for other forges to avoid operating on a same-named GitHub repository. * fix(check): isolate updates by check suite Same-named checks from different suites must not edit one message. Include the suite or app identity and retain the former key for controlled adoption of existing tracked messages. * fix(logs): scope queries before limiting results Filter authorized groups in SQL before LIMIT and aggregate only visible rows. Preserve current group attribution for late writes, surface read failures and combine related totals in one scan. * perf(d1): index pruning and failed send queries Pruning and failure views should not scan all historical rows. Index the high-value access paths without adding a write-heavy index for infrequent delivery-detail lookups. * fix(discord): bound individual api requests An unbounded API request can outlive an update-chain lock. Bound each request so another holder cannot race a late edit. * fix(discord): defer long rate-limit waits Long rate-limit sleeps block delivery progress inside a worker. Return a retryable 429 for the queue when the wait exceeds the bound. * fix(discord): encode channel path segments Stored channel and message ids are path segments, not URL paths. Encode them so aliases cannot address another Discord resource. * fix(discord): reuse nonces after lost responses A successful create may lose its response. Reuse a stable nonce with enforce_nonce so retries recover that message instead of posting duplicates or accepting an unreadable success. * fix(discord): constrain embeds and role mentions Respect combined embed and component limits as well as field caps. Restrict allowed mentions to validated route roles so payload text cannot notify everyone. * fix(discord): resume bounded command syncs Application changes, command rollbacks and large guild lists can leave commands stale indefinitely. Track the current hash per app and resume bounded paginated work without needless KV writes. * fix(github): verify installation management An installation id is user-controlled, and repository access is not installation management. Verify the owning account or an active organization admin using the user token and read:org scope. * fix(github): resolve immutable member ids A login can be renamed and reclaimed before its first sign-in. Resolve the current immutable user id when membership is granted so a future holder of the login cannot inherit access. * fix(auth): revoke stale sessions and tokens Revoked or rotated credentials must stop working despite stale KV replicas. Track the live token and revocations in D1 and preserve immutable identity bindings rather than trusting a recycled login. * fix(auth): bind sessions and tokens to identity Automatic retries can repeat non-idempotent user actions. Disable those retries and expose a write hook so bot handlers can record completion immediately before the GitHub write. * fix(discord): defer and deduplicate interactions Acknowledge slow actions before Discord times out and deduplicate interaction writes. Preserve comment text and reject edits whose source changed after the modal opened. * fix(telegram): always verify webhook secrets Webhook verification must not silently disable itself when the optional secret is absent. Derive a stable secret from the bot token and reject callbacks when verification is unavailable. * fix(telegram): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(telegram): honor nested rate-limit delays Telegram places retry_after inside parameters, not at the top level. Read that value and defer long waits to the delivery queue. * fix(telegram): report unreadable send results An unreadable successful response may already have sent the message. Report an explicit uncertain result instead of retrying a create without an idempotency key or pretending it succeeded. * fix(telegram): keep editable messages as text Guessing photo versus text from message content makes later edits use the wrong API and a smaller caption budget. Always send text and use the avatar as a link preview. * fix(telegram): render hard breaks as newlines Telegram HTML does not support br tags. Render Markdown hard breaks as plain newlines so otherwise valid messages are accepted. * fix(telegram): clamp visible html characters Telegram counts visible characters, not HTML source bytes. Truncate without splitting tags, entities or surrogate pairs. * fix(telegram): honor the author emoji toggle The author marker must obey the group emoji preference just like formatter-added decoration. * fix(telegram): keep completed commands claimed Redelivery after a completed write must never post another comment. Keep completion claims despite reply failures, scope updates per bot and only issue account-login links in private chats. * fix(feishu): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(feishu): classify retryable api failures Business error codes can be transient even in HTTP 200 responses. Classify token and rate-limit errors for retry and defer long waits. * fix(feishu): retry sends with stable uuids An unreadable response does not prove a send failed. Reuse the same uuid for retries so recovering the result cannot create a second Feishu message. * fix(feishu): refresh and evict tokens safely Separate app token caches, stop reusing refused tokens and share refreshes. Cache failures briefly and keep valid tokens in memory when a best-effort KV cache write fails. * fix(feishu): use the card update endpoint Delayed card updates use the card update endpoint; the config endpoint cannot update an interaction response. * fix(feishu): neutralize untrusted mentions Forge text is untrusted and can contain at-all tags. Neutralize mentions in card bodies and footers before rendering. * fix(feishu): authenticate and dedupe callbacks Authenticate signed or token-verified callbacks before dispatching commands. Decode encrypted envelopes and handle card actions using the correct fields without claiming irrelevant chat events. * fix(target): normalize actual destinations Different target spellings can name the same actual destination. Normalize channel, thread and topic identities for ownership checks and per-route duplicate suppression. * fix(config): transact per-group configuration Whole-table writes and cached snapshots can overwrite other groups or resurrect removed configuration. Use per-group guarded writes, one-time identity migration and explicit unreadable-row failures. * fix(group): preserve identity through lifecycle Group names are mutable and reusable, so they cannot own durable state. Preserve immutable identities across lifecycle operations and commit invite use with membership under transaction-time guards. * fix(oauth): confirm account links and installs A login link or installation id is not proof of account ownership. Verify installation management, bind browser state and require an explicit account-link confirmation before granting chat access. * fix(queue): fence leases and record target outcomes Retries must remember completed targets and distinguish active lease holders. Fence state updates, preserve permanent outcomes and reject missing parked payloads instead of dispatching empty data. * fix(dispatch): isolate and resume tenant sends Check tenant sources before filters and never dispatch orphan routes. Record each target outcome, isolate update chains by forge and group identity, and keep stale events from overwriting newer messages. * fix(queue): bound batches and resume deliveries A queue invocation has shared query and subrequest limits. Use a small batch and shared send budget, renew fenced leases and resume only unfinished work without exhausting unstarted messages. * fix(admin): guard revisions and tenant targets Read-time authorization alone cannot protect concurrent edits. Guard revisions, current roles and destination ownership in the write transaction, and use per-group endpoints for isolated changes. * fix(webhook): confirm only accepted deliveries Acknowledging before queue acceptance permanently loses deliveries. Confirm only accepted work, release failed claims, scope replay identities and strip tenant-supplied installation authority. * fix(storage): prune abandoned parked payloads Oversized payloads can remain after interrupted enqueue attempts. Prune objects beyond their retry lifetime without deleting payloads that a current delivery may still need. * fix(console): expose api conflict statuses Callers need the HTTP status to distinguish stale edits from other failures and reload current data after a conflict. * refactor(console): model group revisions Carry server revisions explicitly so console writes can reject changes based on an outdated group snapshot. * fix(console): send loaded route revisions Send the revision actually loaded with the route list and adopt the server response after a save. Reload on conflict instead of silently overwriting another editor. * fix(console): guard fragment saves by revision Fragments share a group version with other configuration writes. Submit the loaded revision and reload on conflict to preserve concurrent edits. * fix(console): save groups with guarded writes Whole-list saves can overwrite unrelated groups. Use per-group revision-aware writes, retain rename results and confirm deletion on the exact group, routes and version shown to the user. * fix(console): reject edits of stale routes A conflict reload can leave an older route editor open. Compare its original value before saving so it cannot overwrite the newly loaded route. * fix(console): show overview loading failures Failed overview requests must not look like an empty dashboard or a successful refresh. Show the reason while retaining prior data. * fix(console): explain rejected install bindings Explain why an installation binding was refused instead of silently returning to the console with no visible outcome. * fix(console): allow selecting a group named all The all sentinel collides with a valid group id. Use a value that cannot be a group id so that group stays selectable. * fix(console): discard stale log detail responses An older detail request can finish after a newer selection or close. Discard it so the dialog never shows the previously clicked record. * fix(console): retain legacy group owners Groups predating member roles store owners in adminIds. Load those as owners so adding a member never drops all old owners. * fix(console): lock member edits during saves Edits made during a save are overwritten by its result. Disable member controls and guard handlers until the write settles. * fix(console): show invite loading failures Failed invite loads must not look like no pending invites. Show the error and discard responses from a previously shown group. * fix(console): retain legacy discord log targets A stored log target without platform means Discord. Keep that meaning in the editor instead of clearing the target. * fix(console): retain undisplayed forge sources An editor that only displays some providers must preserve the others. Keep stored custom sources when saving unrelated group settings. * fix(console): lock the group editor while saving Prevent edits while a group save is in flight and make super-only installation settings readonly instead of silently ignoring edits. * fix(console): lock route edits and show failures Lock the route editor while saving and show fragment load failures with a retry action rather than presenting a false empty list. * fix(config): expose the legal contact override Declare the public runtime key so the documented environment override reaches legal pages in deployed Nuxt builds. * build(deploy): migrate d1 before deployment Apply pending D1 migrations before deploying code that requires them. Stop deployment when migration fails instead of running against an incomplete schema. * docs(worker): align guides with runtime behavior Synchronize both language guides, API references and examples with the implemented authorization, storage and delivery behavior. Document migration requirements and accepted operational limits. * fix(storage): repair orphaned KV routes Repair orphaned KV routes before serving KV-only configuration. * fix(security): fully escape forge HTML --------- Co-authored-by: RhenCloud <i@rhen.cloud>
This commit is contained in:
1 parent
dbf162bf74
commit
978c53eeb3
163 files changed
+17562
-2710
No files matched your search
+6
-2
@@ -15,15 +15,19 @@ DISCORD_APPLICATION_ID=your-application-id
|
|||||||
|
|
||||||
# Telegram
|
# Telegram
|
||||||
TELEGRAM_TOKEN=your-bot-token
|
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
|
# TELEGRAM_RICH_HEADER_HOST=https://your-domain
|
||||||
|
|
||||||
# Feishu (Lark / 飞书)
|
# Feishu (Lark / 飞书)
|
||||||
FEISHU_APP_ID=your-app-id
|
FEISHU_APP_ID=your-app-id
|
||||||
FEISHU_APP_SECRET=your-app-secret
|
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
|
||||||
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
|
# 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)
|
# 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)
|
# AUDIT_RETENTION_DAYS=90 # audit log retention for the scheduled cleanup (default 90)
|
||||||
|
|||||||
@@ -8,24 +8,25 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
|
|||||||
|
|
||||||
## Key Decisions
|
## 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
|
- 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
|
- 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
|
- 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)
|
- 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
|
- 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
|
- 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. `installation.created` webhook events auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account)
|
- 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)
|
- 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
|
- 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
|
- 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}`) 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)
|
- 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)
|
- 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`
|
- 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
|
- 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)
|
- 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 (`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
|
- 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
|
- 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
|
- Local dev: wrangler + Miniflare
|
||||||
|
|
||||||
@@ -41,35 +42,42 @@ app/ # Vue 3 UI (Nuxt app dir)
|
|||||||
│ # AST builder + FilterCombobox searchable inputs), GroupEditor, MembersPanel, WebhookPanel,
|
│ # AST builder + FilterCombobox searchable inputs), GroupEditor, MembersPanel, WebhookPanel,
|
||||||
│ # ConfirmDialog (app-wide destructive-action confirm), SendLogs, AuditLog, MetricsPanel,
|
│ # ConfirmDialog (app-wide destructive-action confirm), SendLogs, AuditLog, MetricsPanel,
|
||||||
│ # AppToasts, LegalLayout
|
│ # AppToasts, LegalLayout
|
||||||
├── composables/ # useI18n, useToasts, useConfirm (promise-based confirm), useBackdropGuard (editor dialogs ignore
|
├── 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, useGroupRoutes, useFilterNode (AST helpers), useFragments, useLogs,
|
│ # 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
|
│ # useAudit, useInvites, useWebhook
|
||||||
├── types.ts # shared client types (Route, Group, Filter, ...)
|
├── 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),
|
└── 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)
|
# filter-catalog.ts (bilingual filter suggestions + value/path validators)
|
||||||
server/ # Nitro server
|
server/ # Nitro server
|
||||||
├── routes/ # H3 handlers: /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
|
├── 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
|
├── tasks/ # scheduled (cron */5): discord-sync, telegram-sync, audit-prune, storage-prune
|
||||||
├── plugins/ # Nitro plugins: queue-consumer (hooks cloudflare:queue → handleQueueBatch)
|
├── plugins/ # Nitro plugins: queue-consumer (hooks cloudflare:queue → handleQueueBatch)
|
||||||
├── error-handler.ts # JSON error handler
|
├── error-handler.ts # JSON error handler
|
||||||
└── lib/
|
└── lib/
|
||||||
├── types.ts # Env, Config, Route, Filter, Group, WebhookEvent, NeutralMessage
|
├── 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
|
├── config.ts # getConfigStore/initConfigStore (D1 store, else KV-only), loadRoutes/saveRoutes/saveGroupRoutes, loadConfig (fresh object per call)
|
||||||
├── fragments.ts # named filter fragments (loadFragments/saveFragments — D1 d1_fragments, no KV)
|
├── fragments.ts # named filter fragments (loadFragments(groupId?)/saveGroupFragments — D1 d1_fragments, no KV; read errors propagate)
|
||||||
├── config/ # config schema + migration + validation
|
├── config/ # config schema + migration + validation
|
||||||
│ └── schema.ts # CONFIG_SCHEMA_VERSION, valibot route/group/filter schemas, migrateRoutes/Groups, validateRoutes/Groups (non-destructive), explainRoute
|
│ └── 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
|
├── cf.ts # cfEnv(event) — env bindings from event.context.cloudflare
|
||||||
├── http.ts # shared HTTP helpers
|
├── 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
|
├── queue/ # Cloudflare Queue delivery pipeline
|
||||||
│ ├── delivery.ts # DeliveryMessage, enqueueWebhook, retry backoff, delivery-state (D1 w/ KV fallback), payload-overflow parking (R2 → KV)
|
│ ├── delivery.ts # DeliveryMessage, enqueueWebhook (byte-size check, parked-payload cleanup), classifyDelivery/isRetryableFailure, retry backoff,
|
||||||
│ └── consumer.ts # handleQueueBatch: resolve payload → dispatch → classify → ack/retry/DLQ
|
│ │ # 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/
|
├── 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/
|
├── events/
|
||||||
│ ├── match.ts # matchRoute, eventOwners; unified pattern syntax (*/? globs + //-wrapped regex)
|
│ ├── 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)
|
├── providers/ # Forge webhook providers (verify + parse/normalize to GitHub-shaped events)
|
||||||
│ ├── types.ts # Provider interface (matches/verify/parse)
|
│ ├── types.ts # Provider interface (matches/verify/parse)
|
||||||
│ ├── hmac.ts # HMAC-SHA256 + timing-safe compare helpers
|
│ ├── hmac.ts # HMAC-SHA256 + timing-safe compare helpers
|
||||||
@@ -100,50 +108,61 @@ server/ # Nitro server
|
|||||||
│ │ ├── interactions.ts # Ed25519 verify + interaction handlers (/gh, buttons, modals)
|
│ │ ├── interactions.ts # Ed25519 verify + interaction handlers (/gh, buttons, modals)
|
||||||
│ │ └── commands.ts # APP_COMMANDS + registerGlobalCommands/syncGuildCommands/syncCommands
|
│ │ └── commands.ts # APP_COMMANDS + registerGlobalCommands/syncGuildCommands/syncCommands
|
||||||
│ └── telegram/
|
│ └── 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)
|
│ ├── render.ts # renderNeutralMessage: NeutralMessage → Telegram HTML (parse_mode HTML)
|
||||||
│ ├── rest.ts # Telegram Bot API sendMessage/sendPhoto/editMessage* (chat_id + message_thread_id), retry
|
│ ├── rest.ts # Telegram Bot API sendMessage/sendPhoto/editMessage* (chat_id + message_thread_id), retry
|
||||||
│ ├── updates.ts # POST /telegram/webhook: secret-token verify + handleTelegramUpdate
|
│ ├── updates.ts # POST /telegram/webhook: secret-token verify (always) + handleTelegramUpdate
|
||||||
│ └── commands.ts # Telegram /gh login|logout|comment|merge|close + reply-message parsing + syncTelegramWebhook
|
│ ├── 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/
|
│ └── feishu/
|
||||||
│ ├── index.ts # FeishuDriver: send/edit → renderNeutralMessage + rest.sendMessage/updateMessage
|
│ ├── index.ts # FeishuDriver: send/edit → renderNeutralMessage + rest.sendMessage/updateMessage
|
||||||
│ ├── render.ts # renderNeutralMessage: NeutralMessage → Feishu interactive card
|
│ ├── render.ts # renderNeutralMessage: NeutralMessage → Feishu interactive card
|
||||||
│ ├── rest.ts # getTenantAccessToken (KV cache) + sendMessage/updateMessage/sendText/updateCard, retry
|
│ ├── rest.ts # getTenantAccessToken (memory + KV cache per app, refused tokens dropped) + sendMessage/updateMessage/sendText/updateCard, retry
|
||||||
│ └── updates.ts # X-Lark-Signature verify + url_verification + /gh commands + card.action.trigger buttons
|
│ └── 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/
|
├── github/
|
||||||
│ ├── oauth.ts # OAuth URL, callback token exchange, getUserOctokit, comment/getComment/editComment/deleteComment/merge/close actions
|
│ ├── 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)
|
│ ├── 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)
|
│ ├── 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)
|
│ ├── 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)
|
├── 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)
|
│ ├── 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
|
│ ├── 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)
|
│ ├── 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
|
│ ├── 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)
|
│ ├── groups.ts # Group CRUD wrappers (create/update CAS/delete/rename via the config store), member roles (normalizeGroupMembers/memberRole),
|
||||||
│ ├── tenants.ts # Per-group webhook secret CRUD (KV tenant:{groupId}, 32-byte random hex)
|
│ │ # 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
|
│ └── richheader.ts # GET /api/richheader: Open Graph page for Telegram avatar link-preview card
|
||||||
├── observability/ # delivery metrics aggregation
|
├── 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)
|
│ └── 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)
|
│ ├── 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
|
│ └── payload.ts # PayloadStore backed by R2 (webhooks/YYYY/MM/DD/*.json), no-binding stub throws
|
||||||
└── lib/ # shared infra
|
└── lib/ # shared infra
|
||||||
├── i18n.ts # loadTranslations (KV i18n:{lang} overrides), t() with param interpolation
|
├── 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
|
├── 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.ts # SendRecord, recordSend/getSendLog/getSendLogById/getSendLogByDelivery/getFailedSendLog (D1 send_logs)
|
||||||
├── send-log-batch.ts # recordSendBatch (D1 batch INSERT for send_logs)
|
├── send-log-batch.ts # recordSendBatch (D1 batch INSERT for send_logs)
|
||||||
├── audit.ts # recordAudit/getAuditLog/pruneAuditLogs (D1 audit_logs, best-effort writes)
|
├── audit.ts # recordAudit/getAuditLog/pruneAuditLogs (D1 audit_logs, best-effort writes)
|
||||||
├── log.ts # JSON console logger (info/warn/error/fatal)
|
├── log.ts # JSON console logger (info/warn/error/fatal)
|
||||||
└── locales/ # en.ts, zh.ts translation dictionaries
|
└── 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/fixtures/ # provider payload fixtures (github/gitea/custom) feeding provider + formatter tests
|
||||||
tests/__snapshots__/ # formatter snapshot golden files (toMatchSnapshot)
|
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 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 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`, ...)
|
- 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 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`)
|
- 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
|
- 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
|
- 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
|
- 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`)
|
- 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`), 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)
|
- 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
|
- 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
|
- 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
|
- 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)
|
- 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
|
- 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
|
- 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)
|
- 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
|
- 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, 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
|
- 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 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)
|
- 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
|
- 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
|
- 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
|
- 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`)
|
- 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
|
- 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 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)
|
- 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)
|
- 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.
|
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
|
- 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);
|
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.
|
- 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
|
- `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
|
(`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
|
- **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
|
- **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)
|
- **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
|
- **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:*`
|
- **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
|
- **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
|
- **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)
|
- **Webhook providers**: `GITEA_WEBHOOK_SECRET` (required to receive Gitea webhooks; Gitea signs `X-Gitea-Signature` with the hex HMAC-SHA256 of the body)
|
||||||
|
|
||||||
## Deployment
|
## Deployment
|
||||||
@@ -280,19 +302,20 @@ bunx wrangler d1 create webhooker
|
|||||||
bunx wrangler queues create webhooker-delivery
|
bunx wrangler queues create webhooker-delivery
|
||||||
bunx wrangler queues create webhooker-delivery-dlq
|
bunx wrangler queues create webhooker-delivery-dlq
|
||||||
# Queues are declared in wrangler.jsonc (QUEUE binding); no env var needed
|
# 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
|
# 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`,
|
Full list of secrets used: `GITHUB_WEBHOOK_SECRET`, `GITEA_WEBHOOK_SECRET`,
|
||||||
`GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY`
|
`GITHUB_APP_ID`, `GITHUB_PRIVATE_KEY`
|
||||||
(PKCS#8 PEM), `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `DISCORD_TOKEN`,
|
(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`,
|
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`.
|
`NUXT_PUBLIC_DOCS_URL`, `NUXT_PUBLIC_REPO_URL`, `NUXT_PUBLIC_LEGAL_CONTACT`. See `.env.example` and `docs/guide/configuration.md`.
|
||||||
|
|
||||||
## Notes
|
## 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.
|
- The bot is always offline (no Discord Gateway); interactions arrive via the HTTP endpoint.
|
||||||
@@ -39,8 +39,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
|
|
||||||
- **Cloudflare Worker** — HTTP ingress, signature verification, routing, platform dispatch
|
- **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
|
- **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:*`)
|
- **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`), 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`)
|
- **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:*`)
|
- **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
|
## Quick Start
|
||||||
@@ -48,8 +48,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
```bash
|
```bash
|
||||||
bun install # package manager is bun (lockfile: bun.lock)
|
bun install # package manager is bun (lockfile: bun.lock)
|
||||||
cp .env.example .dev.vars # Fill in secrets for local dev
|
cp .env.example .dev.vars # Fill in secrets for local dev
|
||||||
bun run build # Production build first (wrangler dev serves the built worker)
|
bun run db:migrate # Apply the D1 migrations to the local database (first run)
|
||||||
bunx wrangler dev # Start local dev server
|
bun run cf:dev # Build, then serve the worker locally with wrangler dev
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
@@ -57,23 +57,25 @@ bunx wrangler dev # Start local dev server
|
|||||||
### Secrets (`.dev.vars` for local, Worker Secrets for production)
|
### Secrets (`.dev.vars` for local, Worker Secrets for production)
|
||||||
|
|
||||||
| Variable | Description |
|
| Variable | Description |
|
||||||
| --------------------------- | ---------------------------------------------------------------------------------------------- |
|
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub |
|
| `GITHUB_WEBHOOK_SECRET` | Webhook secret from GitHub |
|
||||||
| `GITEA_WEBHOOK_SECRET` | Webhook secret from Gitea (required only to receive Gitea webhooks) |
|
| `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_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; used by the App install flow; optional) |
|
| `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_ID` | OAuth client ID |
|
||||||
| `GITHUB_CLIENT_SECRET` | OAuth client secret |
|
| `GITHUB_CLIENT_SECRET` | OAuth client secret |
|
||||||
| `DISCORD_TOKEN` | Bot token |
|
| `DISCORD_TOKEN` | Bot token |
|
||||||
| `DISCORD_PUBLIC_KEY` | Discord application public key (from the Developer Portal) — required for interactions |
|
| `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) |
|
| `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_TOKEN` | Telegram bot token (from BotFather) — required for Telegram routes |
|
||||||
| `TELEGRAM_WEBHOOK_SECRET` | Optional secret token for `POST /telegram/webhook` verification |
|
| `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 |
|
| `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_ID` | Feishu app ID (from the app Credentials page) — required for Feishu routes |
|
||||||
| `FEISHU_APP_SECRET` | Feishu app secret — 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 |
|
| `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` |
|
| `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 |
|
| `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) |
|
| `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) |
|
| `AUDIT_RETENTION_DAYS` | Audit-log retention in days for the scheduled cleanup (default 90) |
|
||||||
@@ -83,7 +85,7 @@ bunx wrangler dev # Start local dev server
|
|||||||
|
|
||||||
### Routes
|
### 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
|
```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`)
|
### 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)
|
### 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
|
/gh login /gh logout
|
||||||
|
|||||||
+15
-12
@@ -39,8 +39,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
|
|
||||||
- **Cloudflare Worker** — HTTP 入口、签名验证、路由分发
|
- **Cloudflare Worker** — HTTP 入口、签名验证、路由分发
|
||||||
- **Interactions Endpoint** — HTTPS 回调(无 Discord Gateway 连接、无 Durable Object);bot 保持离线,命令通过 API 注册
|
- **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:*`)
|
- **KV** — 缓存 + 临时状态:Token 存储(`token:{userId}`)、OAuth state(`state:{hex}`)、管理员会话(`session:{id}`)、邀请、投递去重/投递状态/消息更新追踪的回退(`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`)
|
- **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:*`)
|
- **Queue** — 绑定 `QUEUE` 时异步投递:`webhooker-delivery`(指数退避重试)+ 死信队列 `webhooker-delivery-dlq`;超大负载暂存于 R2(`PAYLOAD` 绑定,`webhooks/YYYY/MM/DD/*.json`,回退 KV `queue:payload:*`)
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
@@ -48,8 +48,8 @@ GitHub Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
```bash
|
```bash
|
||||||
bun install # 包管理器为 bun(锁文件:bun.lock)
|
bun install # 包管理器为 bun(锁文件:bun.lock)
|
||||||
cp .env.example .dev.vars # 填写本地开发密钥
|
cp .env.example .dev.vars # 填写本地开发密钥
|
||||||
bun run build # 先构建生产产物(wrangler dev 运行的是构建产物)
|
bun run db:migrate # 将 D1 迁移应用到本地数据库(首次运行)
|
||||||
bunx wrangler dev # 启动本地开发服务器
|
bun run cf:dev # 先构建,再用 wrangler dev 在本地运行 worker
|
||||||
```
|
```
|
||||||
|
|
||||||
## 配置
|
## 配置
|
||||||
@@ -57,23 +57,25 @@ bunx wrangler dev # 启动本地开发服务器
|
|||||||
### 密钥(本地用 `.dev.vars`,生产用 Worker Secrets)
|
### 密钥(本地用 `.dev.vars`,生产用 Worker Secrets)
|
||||||
|
|
||||||
| 变量 | 说明 |
|
| 变量 | 说明 |
|
||||||
| --------------------------- | --------------------------------------------------------------------------- |
|
| --------------------------- | ----------------------------------------------------------------------------- |
|
||||||
| `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 |
|
| `GITHUB_WEBHOOK_SECRET` | GitHub webhook 密钥 |
|
||||||
| `GITEA_WEBHOOK_SECRET` | Gitea webhook 密钥(仅接收 Gitea webhook 时需要) |
|
| `GITEA_WEBHOOK_SECRET` | Gitea webhook 密钥(仅接收 Gitea webhook 时需要) |
|
||||||
| `GITHUB_APP_ID` | GitHub App ID(用于 App 安装流程解析安装所属账号) |
|
| `GITHUB_APP_ID` | GitHub App ID——App 安装流程需要它核实安装者(没有时只有超级管理员能绑定安装) |
|
||||||
| `GITHUB_PRIVATE_KEY` | App 私钥(PKCS#8 PEM;用于 App 安装流程,可选) |
|
| `GITHUB_PRIVATE_KEY` | App 私钥(PKCS#8 PEM)——需与 `GITHUB_APP_ID` 一起配置,也用于 API 增强鉴权 |
|
||||||
| `GITHUB_CLIENT_ID` | OAuth Client ID |
|
| `GITHUB_CLIENT_ID` | OAuth Client ID |
|
||||||
| `GITHUB_CLIENT_SECRET` | OAuth Client Secret |
|
| `GITHUB_CLIENT_SECRET` | OAuth Client Secret |
|
||||||
| `DISCORD_TOKEN` | 机器人 token |
|
| `DISCORD_TOKEN` | 机器人 token |
|
||||||
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取)—— 交互功能必需 |
|
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取)—— 交互功能必需 |
|
||||||
| `DISCORD_APPLICATION_ID` | Discord 应用 ID(可选;省略时通过 `GET /oauth2/applications/@me` 自动获取) |
|
| `DISCORD_APPLICATION_ID` | Discord 应用 ID(可选;省略时通过 `GET /oauth2/applications/@me` 自动获取) |
|
||||||
| `TELEGRAM_TOKEN` | Telegram Bot Token(BotFather 获取)—— Telegram 路由必需 |
|
| `TELEGRAM_TOKEN` | Telegram Bot Token(BotFather 获取)—— Telegram 路由必需 |
|
||||||
| `TELEGRAM_WEBHOOK_SECRET` | 可选;`POST /telegram/webhook` 的验签密钥 |
|
| `TELEGRAM_WEBHOOK_SECRET` | 可选;`POST /telegram/webhook` 的验签密钥(未设置时由 token 派生) |
|
||||||
| `TELEGRAM_RICH_HEADER_HOST` | 可选;覆盖内置 `GET /api/richheader` 的 Telegram 头像卡片地址 |
|
| `TELEGRAM_RICH_HEADER_HOST` | 可选;覆盖内置 `GET /api/richheader` 的 Telegram 头像卡片地址 |
|
||||||
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
|
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
|
||||||
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
|
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
|
||||||
|
| `FEISHU_ENCRYPT_KEY` | 飞书事件 Encrypt Key(验签 + 解密)—— 飞书入站命令需要它或下面的 token |
|
||||||
|
| `FEISHU_VERIFICATION_TOKEN` | 飞书事件 Verification Token,每个入站回调都会校验 |
|
||||||
| `BASE_URL` | 公网地址(用于 OAuth 回调与 Telegram webhook 同步) |
|
| `BASE_URL` | 公网地址(用于 OAuth 回调与 Telegram webhook 同步) |
|
||||||
| `ADMIN_USER_IDS` | 允许访问 `/admin` 的 GitHub 用户 ID(或登录名),逗号分隔 |
|
| `ADMIN_USER_IDS` | 超级管理员的 GitHub 用户 ID(或登录名,建议写数字 ID),逗号分隔 |
|
||||||
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证 |
|
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证 |
|
||||||
| `ALLOW_SELF_SIGNUP` | 设为 `1` 时,无权限的 GitHub 用户首次登录自动获得个人分组(默认关闭) |
|
| `ALLOW_SELF_SIGNUP` | 设为 `1` 时,无权限的 GitHub 用户首次登录自动获得个人分组(默认关闭) |
|
||||||
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数(默认 90) |
|
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数(默认 90) |
|
||||||
@@ -83,7 +85,7 @@ bunx wrangler dev # 启动本地开发服务器
|
|||||||
|
|
||||||
### 路由配置
|
### 路由配置
|
||||||
|
|
||||||
路由存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 同步)。**没有默认路由**——每条路由(包括目标)都必须显式定义,可通过 Web 控制台(`/admin`)或直接向 D1 存储 JSON 数组。一条路由可携带多个 `targets`,因此一个规则可以同时转发到多个频道:
|
路由存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 同步)。**没有默认路由**——每条路由(包括目标)都必须显式定义,可通过 Web 控制台(`/admin`)或 Admin API 管理。一条路由可携带多个 `targets`,因此一个规则可以同时转发到多个频道:
|
||||||
|
|
||||||
```json
|
```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`)
|
### 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-设置)
|
- **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)。
|
- **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-机器人配置)
|
- **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)
|
- **部署** — KV 命名空间、D1 数据库与迁移(含 0008 存储表)、可选 R2 Bucket 与 Queues、密钥、部署:见[部署指南](https://webhooker.docs.elysola.org/zh/guide/deployment)
|
||||||
|
|
||||||
### Bot 指令(以本人身份评论 GitHub)
|
### 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
|
/gh login /gh logout
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ const props = defineProps<{
|
|||||||
groupsLoading: boolean;
|
groupsLoading: boolean;
|
||||||
logsLoading: boolean;
|
logsLoading: boolean;
|
||||||
metricsLoading: boolean;
|
metricsLoading: boolean;
|
||||||
|
/** Why the latest load failed (what is shown may be empty or older). */
|
||||||
|
error?: string;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -72,6 +74,7 @@ function fmtTime(ts: number): string {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
|
<p v-if="error" class="err">{{ t("overview.loadFailed", { error }) }}</p>
|
||||||
<!-- KPI cards -->
|
<!-- KPI cards -->
|
||||||
<section class="grid grid-cols-2 gap-4 xl:grid-cols-4">
|
<section class="grid grid-cols-2 gap-4 xl:grid-cols-4">
|
||||||
<RcCard v-for="k in kpis" :key="k.label" variant="outline" padding="md" class="p-5">
|
<RcCard v-for="k in kpis" :key="k.label" variant="outline" padding="md" class="p-5">
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<label class="filter-label">{{ t("audit.filterGroup") }}</label>
|
<label class="filter-label">{{ t("audit.filterGroup") }}</label>
|
||||||
<RcSelect
|
<RcSelect
|
||||||
class="filter-select"
|
class="filter-select"
|
||||||
:model-value="selectedGroupId || 'all'"
|
:model-value="selectedGroupId || '*'"
|
||||||
:options="groupOptions"
|
:options="groupOptions"
|
||||||
:disabled="loading"
|
:disabled="loading"
|
||||||
@update:model-value="onGroupFilter"
|
@update:model-value="onGroupFilter"
|
||||||
@@ -75,12 +75,12 @@ function refresh(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const groupOptions = computed(() => [
|
const groupOptions = computed(() => [
|
||||||
{ label: t("audit.allGroups"), value: "all" },
|
{ label: t("audit.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function onGroupFilter(value: string): void {
|
function onGroupFilter(value: string): void {
|
||||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||||
emit("filter");
|
emit("filter");
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
@@ -96,6 +96,7 @@
|
|||||||
:groups-loading="groupsLoading"
|
:groups-loading="groupsLoading"
|
||||||
:logs-loading="overviewLogsLoading"
|
:logs-loading="overviewLogsLoading"
|
||||||
:metrics-loading="overviewMetricsLoading"
|
:metrics-loading="overviewMetricsLoading"
|
||||||
|
:error="overviewError"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<template v-else-if="selectedGroup">
|
<template v-else-if="selectedGroup">
|
||||||
@@ -543,12 +544,22 @@ const { logs, loading: logsLoading, error: logsError, load: loadLogs } = useSend
|
|||||||
// Overview shows every group's latest sends and totals, apart from the Send
|
// Overview shows every group's latest sends and totals, apart from the Send
|
||||||
// Logs and Stats pages and their group filters (the console stays mounted, so
|
// Logs and Stats pages and their group filters (the console stays mounted, so
|
||||||
// shared state would carry one page's filter into the other).
|
// shared state would carry one page's filter into the other).
|
||||||
const { logs: overviewLogs, loading: overviewLogsLoading, load: loadOverviewLogs } = useSendLogs();
|
const {
|
||||||
|
logs: overviewLogs,
|
||||||
|
loading: overviewLogsLoading,
|
||||||
|
error: overviewLogsError,
|
||||||
|
load: loadOverviewLogs,
|
||||||
|
} = useSendLogs();
|
||||||
const {
|
const {
|
||||||
metrics: overviewMetrics,
|
metrics: overviewMetrics,
|
||||||
loading: overviewMetricsLoading,
|
loading: overviewMetricsLoading,
|
||||||
|
error: overviewMetricsError,
|
||||||
load: loadOverviewMetrics,
|
load: loadOverviewMetrics,
|
||||||
} = useMetrics();
|
} = useMetrics();
|
||||||
|
/** A failed overview load: shown, never passed off as "no data". */
|
||||||
|
const overviewError = computed(
|
||||||
|
() => groupsError.value || overviewLogsError.value || overviewMetricsError.value,
|
||||||
|
);
|
||||||
const {
|
const {
|
||||||
entries: auditEntries,
|
entries: auditEntries,
|
||||||
loading: auditLoading,
|
loading: auditLoading,
|
||||||
@@ -568,7 +579,9 @@ const {
|
|||||||
needLogin,
|
needLogin,
|
||||||
error: groupsError,
|
error: groupsError,
|
||||||
load: loadGroups,
|
load: loadGroups,
|
||||||
save: saveGroups,
|
update: updateGroup,
|
||||||
|
create: createGroup,
|
||||||
|
remove: removeGroup,
|
||||||
rename: groupsRename,
|
rename: groupsRename,
|
||||||
} = useGroupsApi();
|
} = useGroupsApi();
|
||||||
const {
|
const {
|
||||||
@@ -733,6 +746,7 @@ onMounted(() => {
|
|||||||
if (invite === "ok") push(t("members.inviteOk"));
|
if (invite === "ok") push(t("members.inviteOk"));
|
||||||
else if (invite != null && invite !== "ok") push(t("members.inviteBad"), "bad");
|
else if (invite != null && invite !== "ok") push(t("members.inviteBad"), "bad");
|
||||||
if (params.get("install") === "ok") push(t("install.ok"));
|
if (params.get("install") === "ok") push(t("install.ok"));
|
||||||
|
if (params.get("error") === "install-forbidden") push(t("install.forbidden"), "bad");
|
||||||
}
|
}
|
||||||
loadGroups();
|
loadGroups();
|
||||||
});
|
});
|
||||||
@@ -868,7 +882,8 @@ watch(
|
|||||||
async function refreshOverview(): Promise<void> {
|
async function refreshOverview(): Promise<void> {
|
||||||
refreshKey.value++;
|
refreshKey.value++;
|
||||||
await Promise.all([loadGroups(), loadOverviewLogs(50), loadOverviewMetrics()]);
|
await Promise.all([loadGroups(), loadOverviewLogs(50), loadOverviewMetrics()]);
|
||||||
push(t("overview.refreshed"));
|
if (overviewError.value) push(t("overview.refreshFailed"), "bad");
|
||||||
|
else push(t("overview.refreshed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
function enterGroup(group: Group): void {
|
function enterGroup(group: Group): void {
|
||||||
@@ -966,6 +981,13 @@ async function onSave(route: Route): Promise<void> {
|
|||||||
try {
|
try {
|
||||||
let next: Route[];
|
let next: Route[];
|
||||||
if (editing.value) {
|
if (editing.value) {
|
||||||
|
// The route must still be the one the editor opened: a version changed
|
||||||
|
// by someone else meanwhile would otherwise be overwritten silently.
|
||||||
|
const latest = groupRoutes.value.find((r) => r.id === editing.value!.id);
|
||||||
|
if (!latest || JSON.stringify(latest) !== JSON.stringify(editing.value)) {
|
||||||
|
push(t("toast.routeChanged"), "bad");
|
||||||
|
return;
|
||||||
|
}
|
||||||
next = groupRoutes.value.map((r) => (r.id === editing.value!.id ? route : r));
|
next = groupRoutes.value.map((r) => (r.id === editing.value!.id ? route : r));
|
||||||
} else {
|
} else {
|
||||||
if (groupRoutes.value.some((r) => r.id === route.id)) {
|
if (groupRoutes.value.some((r) => r.id === route.id)) {
|
||||||
@@ -1036,8 +1058,8 @@ function openEditGroup(group: Group): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Group writes replace the whole group list, so they run one at a time, each
|
* Group writes run one at a time, each built on what the previous one saved;
|
||||||
* built from the list the previous one saved; true when one may start.
|
* true when one may start.
|
||||||
*/
|
*/
|
||||||
function canWriteGroups(): boolean {
|
function canWriteGroups(): boolean {
|
||||||
if (!savingGroup.value) return true;
|
if (!savingGroup.value) return true;
|
||||||
@@ -1049,8 +1071,7 @@ async function onSaveGroupFromPanel(group: Group): Promise<void> {
|
|||||||
if (!canWriteGroups()) return;
|
if (!canWriteGroups()) return;
|
||||||
savingGroup.value = true;
|
savingGroup.value = true;
|
||||||
try {
|
try {
|
||||||
const next = groups.value.map((g) => (g.id === group.id ? group : g));
|
await updateGroup(group);
|
||||||
await saveGroups(next);
|
|
||||||
push(t("toast.groupSaved"));
|
push(t("toast.groupSaved"));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
||||||
@@ -1066,25 +1087,34 @@ async function onSaveGroup(group: Group): Promise<void> {
|
|||||||
savingGroup.value = true;
|
savingGroup.value = true;
|
||||||
try {
|
try {
|
||||||
const editing = editingGroup.value;
|
const editing = editingGroup.value;
|
||||||
let next: Group[];
|
|
||||||
if (editing) {
|
if (editing) {
|
||||||
|
// The editor does not show these fields; keep what the group has.
|
||||||
|
const edited: Group = { ...group, isolated: editing.isolated, revision: editing.revision };
|
||||||
if (group.id !== editing.id) {
|
if (group.id !== editing.id) {
|
||||||
// Id changed: rename first so routes/webhook secret/invites follow,
|
// Id changed: rename first so routes/webhook secret/invites follow
|
||||||
// then persist the remaining edits under the new id.
|
// (refused if the group changed since the editor opened), then
|
||||||
await groupsRename(editing.id, group.id);
|
// persist the remaining edits under the new id, on top of exactly the
|
||||||
// A list loaded meanwhile may already hold the new id as well.
|
// renamed group. If that second step fails, the editor already points
|
||||||
next = [...groups.value.filter((g) => g.id !== editing.id && g.id !== group.id), group];
|
// at the new id, so saving again only retries the update.
|
||||||
|
const renamed = await groupsRename(editing.id, group.id, editing.revision);
|
||||||
|
if (session === groupEditorSession) editingGroup.value = renamed;
|
||||||
|
// Server-decided fields (e.g. isolation made explicit by the rename)
|
||||||
|
// come from the renamed group, not from the editor's older copy.
|
||||||
|
await updateGroup({
|
||||||
|
...edited,
|
||||||
|
isolated: renamed.isolated,
|
||||||
|
revision: renamed.revision,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
next = groups.value.map((g) => (g.id === editing.id ? group : g));
|
await updateGroup(edited);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (groups.value.some((g) => g.id === group.id)) {
|
if (groups.value.some((g) => g.id === group.id)) {
|
||||||
push(t("toast.groupIdExists"), "bad");
|
push(t("toast.groupIdExists"), "bad");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
next = [...groups.value, group];
|
await createGroup(group);
|
||||||
}
|
}
|
||||||
await saveGroups(next);
|
|
||||||
if (session === groupEditorSession) groupEditorOpen.value = false;
|
if (session === groupEditorSession) groupEditorOpen.value = false;
|
||||||
push(t("toast.groupSaved"));
|
push(t("toast.groupSaved"));
|
||||||
await loadGroups();
|
await loadGroups();
|
||||||
@@ -1101,13 +1131,25 @@ async function onDeleteGroup(group: Group): Promise<void> {
|
|||||||
// Fetch the real route count for this group instead of relying on the
|
// Fetch the real route count for this group instead of relying on the
|
||||||
// routes of whichever group happens to be open in the detail view.
|
// routes of whichever group happens to be open in the detail view.
|
||||||
let used = 0;
|
let used = 0;
|
||||||
|
let routesRevision: string | undefined;
|
||||||
|
let version: number | null = null;
|
||||||
try {
|
try {
|
||||||
const data = await apiFetch<{ routes?: Route[] }>(
|
const data = await apiFetch<{ routes?: Route[]; revision?: string; version?: number | null }>(
|
||||||
`/admin/api/groups/${encodeURIComponent(group.id)}/routes`,
|
`/admin/api/groups/${encodeURIComponent(group.id)}/routes`,
|
||||||
);
|
);
|
||||||
used = (data.routes ?? []).length;
|
used = (data.routes ?? []).length;
|
||||||
} catch {
|
routesRevision = data.revision;
|
||||||
// Count is best-effort; proceed without the warning.
|
version = data.version ?? null;
|
||||||
|
} catch (err) {
|
||||||
|
// The deletion is confirmed on what the routes are now: without them,
|
||||||
|
// a route added meanwhile could be deleted unseen.
|
||||||
|
if (visit === pageVisit) {
|
||||||
|
push(
|
||||||
|
t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }),
|
||||||
|
"bad",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
// The list was left while the count loaded: never ask on another page.
|
// The list was left while the count loaded: never ask on another page.
|
||||||
if (visit !== pageVisit) return;
|
if (visit !== pageVisit) return;
|
||||||
@@ -1118,7 +1160,8 @@ async function onDeleteGroup(group: Group): Promise<void> {
|
|||||||
if (!confirmed || visit !== pageVisit || !canWriteGroups()) return;
|
if (!confirmed || visit !== pageVisit || !canWriteGroups()) return;
|
||||||
savingGroup.value = true;
|
savingGroup.value = true;
|
||||||
try {
|
try {
|
||||||
await saveGroups(groups.value.filter((g) => g.id !== group.id));
|
// Deletes the group as confirmed: a route added meanwhile makes it fail.
|
||||||
|
await removeGroup(group.id, group.revision, routesRevision, version);
|
||||||
push(t("toast.groupDeleted"));
|
push(t("toast.groupDeleted"));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
||||||
|
|||||||
@@ -14,6 +14,9 @@
|
|||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
<form class="editor-body" @submit.prevent="save">
|
<form class="editor-body" @submit.prevent="save">
|
||||||
|
<!-- Locked while saving: an edit made meanwhile would be lost when the
|
||||||
|
save closes the editor. -->
|
||||||
|
<fieldset :disabled="saving" class="contents">
|
||||||
<section class="editor-section">
|
<section class="editor-section">
|
||||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionBasic") }}</h3>
|
<h3 class="editor-section-title">{{ t("groupEditor.sectionBasic") }}</h3>
|
||||||
<div class="row2">
|
<div class="row2">
|
||||||
@@ -166,10 +169,14 @@
|
|||||||
<span class="lbl-note">{{ t("groupEditor.installationIdNote") }}</span></label
|
<span class="lbl-note">{{ t("groupEditor.installationIdNote") }}</span></label
|
||||||
>
|
>
|
||||||
<div class="ctl-md">
|
<div class="ctl-md">
|
||||||
|
<!-- Only super admins bind installations here (the server keeps
|
||||||
|
the stored value for anyone else); owners use the install flow. -->
|
||||||
<RcInput
|
<RcInput
|
||||||
v-model="form.installationId"
|
v-model="form.installationId"
|
||||||
type="text"
|
type="text"
|
||||||
inputmode="numeric"
|
inputmode="numeric"
|
||||||
|
:class="superAdmin ? '' : 'opacity-60'"
|
||||||
|
:disabled="!superAdmin"
|
||||||
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -233,6 +240,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<div class="err">{{ formError }}</div>
|
<div class="err">{{ formError }}</div>
|
||||||
|
</fieldset>
|
||||||
</form>
|
</form>
|
||||||
<template #footer>
|
<template #footer>
|
||||||
<div class="editor-foot">
|
<div class="editor-foot">
|
||||||
@@ -330,7 +338,8 @@ watch(
|
|||||||
form.emoji = g?.emoji ?? true;
|
form.emoji = g?.emoji ?? true;
|
||||||
form.forgeSources = (g?.forgeSources ?? []).map((s) => ({ ...s }));
|
form.forgeSources = (g?.forgeSources ?? []).map((s) => ({ ...s }));
|
||||||
form.lang = g?.lang ?? "";
|
form.lang = g?.lang ?? "";
|
||||||
form.logPlatform = lt?.platform ?? "";
|
// A stored target without a platform is a Discord one (as the server reads it).
|
||||||
|
form.logPlatform = lt ? (lt.platform ?? "discord") : "";
|
||||||
form.logChannelId = lt?.channelId ?? "";
|
form.logChannelId = lt?.channelId ?? "";
|
||||||
form.logThreadId = lt?.threadId ?? "";
|
form.logThreadId = lt?.threadId ?? "";
|
||||||
form.logChatId = lt?.chatId ?? "";
|
form.logChatId = lt?.chatId ?? "";
|
||||||
@@ -417,8 +426,13 @@ function save(): void {
|
|||||||
members,
|
members,
|
||||||
adminIds: members.filter((m) => m.role === "owner").map((m) => m.login),
|
adminIds: members.filter((m) => m.role === "owner").map((m) => m.login),
|
||||||
owners: props.superAdmin ? (owners.length ? owners : undefined) : props.group?.owners,
|
owners: props.superAdmin ? (owners.length ? owners : undefined) : props.group?.owners,
|
||||||
providers: form.providers.length ? form.providers : undefined,
|
// Sources the form does not offer (e.g. "custom") are kept as they were.
|
||||||
installationId,
|
providers: (() => {
|
||||||
|
const kept = (props.group?.providers ?? []).filter((p) => p !== "github" && p !== "gitea");
|
||||||
|
const all = [...form.providers, ...kept];
|
||||||
|
return all.length ? all : undefined;
|
||||||
|
})(),
|
||||||
|
installationId: props.superAdmin ? installationId : props.group?.installationId,
|
||||||
emoji: form.emoji,
|
emoji: form.emoji,
|
||||||
forgeSources: form.forgeSources.length
|
forgeSources: form.forgeSources.length
|
||||||
? form.forgeSources.map((s) => ({
|
? form.forgeSources.map((s) => ({
|
||||||
|
|||||||
@@ -46,11 +46,12 @@
|
|||||||
type="text"
|
type="text"
|
||||||
size="sm"
|
size="sm"
|
||||||
:placeholder="t('members.addPlaceholder')"
|
:placeholder="t('members.addPlaceholder')"
|
||||||
|
:disabled="saving"
|
||||||
@keydown.enter.prevent="addMember"
|
@keydown.enter.prevent="addMember"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="member-role">
|
<div class="member-role">
|
||||||
<RcSelect v-model="newRole" :options="roleOptions" />
|
<RcSelect v-model="newRole" :options="roleOptions" :disabled="saving" />
|
||||||
</div>
|
</div>
|
||||||
<RcButton type="button" size="sm" class="h-9" :disabled="saving" @click="addMember">
|
<RcButton type="button" size="sm" class="h-9" :disabled="saving" @click="addMember">
|
||||||
{{ t("members.addBtn") }}
|
{{ t("members.addBtn") }}
|
||||||
@@ -76,6 +77,9 @@
|
|||||||
{{ t("members.createInvite") }}
|
{{ t("members.createInvite") }}
|
||||||
</RcButton>
|
</RcButton>
|
||||||
</div>
|
</div>
|
||||||
|
<p v-if="invitesError" class="err">
|
||||||
|
{{ t("members.invitesFailed", { error: invitesError }) }}
|
||||||
|
</p>
|
||||||
<ul v-if="invites.length" class="invite-list">
|
<ul v-if="invites.length" class="invite-list">
|
||||||
<li v-for="inv in invites" :key="inv.token" class="invite-row">
|
<li v-for="inv in invites" :key="inv.token" class="invite-row">
|
||||||
<code class="invite-token">{{ shortToken(inv.token) }}</code>
|
<code class="invite-token">{{ shortToken(inv.token) }}</code>
|
||||||
@@ -93,7 +97,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</li>
|
</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p v-else class="empty-log">{{ t("members.noInvites") }}</p>
|
<p v-else-if="!invitesError" class="empty-log">{{ t("members.noInvites") }}</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="err">{{ formError }}</div>
|
<div class="err">{{ formError }}</div>
|
||||||
@@ -115,6 +119,8 @@ const emit = defineEmits<{ (e: "save", group: Group): void }>();
|
|||||||
const invitesApi = useInvitesApi();
|
const invitesApi = useInvitesApi();
|
||||||
const members = ref<GroupMember[]>([]);
|
const members = ref<GroupMember[]>([]);
|
||||||
const invites = ref<GroupInvite[]>([]);
|
const invites = ref<GroupInvite[]>([]);
|
||||||
|
/** The last list load failed (the list shown, if any, is the one before). */
|
||||||
|
const invitesError = ref("");
|
||||||
const newLogin = ref("");
|
const newLogin = ref("");
|
||||||
const newRole = ref<GroupRole>("admin");
|
const newRole = ref<GroupRole>("admin");
|
||||||
const inviteRole = ref<"admin" | "viewer">("admin");
|
const inviteRole = ref<"admin" | "viewer">("admin");
|
||||||
@@ -132,16 +138,34 @@ const inviteRoleOptions = computed(() =>
|
|||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.group,
|
() => props.group,
|
||||||
(g) => {
|
(g, prev) => {
|
||||||
members.value = (g.members ?? []).map((m) => ({ ...m }));
|
// A group from before member roles lists its owners in `adminIds` only:
|
||||||
|
// read as owners (as the server does), so a save never drops them.
|
||||||
|
members.value = g.members?.length
|
||||||
|
? g.members.map((m) => ({ ...m }))
|
||||||
|
: (g.adminIds ?? []).map((login) => ({ login, role: "owner" as const }));
|
||||||
formError.value = "";
|
formError.value = "";
|
||||||
|
// Another group's invites are never shown, not even while loading.
|
||||||
|
if (g.id !== prev?.id) {
|
||||||
|
invites.value = [];
|
||||||
|
invitesError.value = "";
|
||||||
|
}
|
||||||
if (props.canEdit) loadInvites();
|
if (props.canEdit) loadInvites();
|
||||||
},
|
},
|
||||||
{ immediate: true },
|
{ immediate: true },
|
||||||
);
|
);
|
||||||
|
|
||||||
async function loadInvites(): Promise<void> {
|
async function loadInvites(): Promise<void> {
|
||||||
invites.value = await invitesApi.list(props.group.id);
|
const groupId = props.group.id;
|
||||||
|
try {
|
||||||
|
const list = await invitesApi.list(groupId);
|
||||||
|
if (props.group.id !== groupId) return;
|
||||||
|
invites.value = list;
|
||||||
|
invitesError.value = "";
|
||||||
|
} catch (err) {
|
||||||
|
if (props.group.id !== groupId) return;
|
||||||
|
invitesError.value = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function ownerCount(): number {
|
function ownerCount(): number {
|
||||||
@@ -149,6 +173,9 @@ function ownerCount(): number {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onRoleChange(m: GroupMember, role: string): void {
|
function onRoleChange(m: GroupMember, role: string): void {
|
||||||
|
// One save at a time: a change made meanwhile would be overwritten by the
|
||||||
|
// first save's result (and the second save refused).
|
||||||
|
if (props.saving) return;
|
||||||
const nextRole = role as GroupRole;
|
const nextRole = role as GroupRole;
|
||||||
if (nextRole === "viewer" && m.role === "owner" && ownerCount() === 1) {
|
if (nextRole === "viewer" && m.role === "owner" && ownerCount() === 1) {
|
||||||
formError.value = t("members.errLastOwner");
|
formError.value = t("members.errLastOwner");
|
||||||
@@ -159,6 +186,7 @@ function onRoleChange(m: GroupMember, role: string): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function addMember(): void {
|
function addMember(): void {
|
||||||
|
if (props.saving) return;
|
||||||
const login = newLogin.value.trim();
|
const login = newLogin.value.trim();
|
||||||
if (!login) return;
|
if (!login) return;
|
||||||
if (members.value.some((m) => m.login.toLowerCase() === login.toLowerCase())) {
|
if (members.value.some((m) => m.login.toLowerCase() === login.toLowerCase())) {
|
||||||
@@ -180,7 +208,7 @@ async function removeMember(m: GroupMember): Promise<void> {
|
|||||||
title: t("confirm.removeMember", { name: m.login }),
|
title: t("confirm.removeMember", { name: m.login }),
|
||||||
confirmText: t("members.remove"),
|
confirmText: t("members.remove"),
|
||||||
});
|
});
|
||||||
if (!confirmed) return;
|
if (!confirmed || props.saving) return;
|
||||||
members.value = members.value.filter((x) => x !== m);
|
members.value = members.value.filter((x) => x !== m);
|
||||||
emitSave();
|
emitSave();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const emit = defineEmits<{
|
|||||||
const sortBy = ref<"total" | "failed" | "rate">("total");
|
const sortBy = ref<"total" | "failed" | "rate">("total");
|
||||||
|
|
||||||
const groupOptions = computed(() => [
|
const groupOptions = computed(() => [
|
||||||
{ label: t("metrics.allGroups"), value: "all" },
|
{ label: t("metrics.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ function pctOf(count: number, total: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onGroupFilter(value: string): void {
|
function onGroupFilter(value: string): void {
|
||||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||||
emit("filter");
|
emit("filter");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,7 +120,7 @@ function cycleSort(): void {
|
|||||||
<label class="filter-label">{{ t("metrics.filterGroup") }}</label>
|
<label class="filter-label">{{ t("metrics.filterGroup") }}</label>
|
||||||
<RcSelect
|
<RcSelect
|
||||||
class="filter-select"
|
class="filter-select"
|
||||||
:model-value="selectedGroupId || 'all'"
|
:model-value="selectedGroupId || '*'"
|
||||||
:options="groupOptions"
|
:options="groupOptions"
|
||||||
:disabled="loading"
|
:disabled="loading"
|
||||||
@update:model-value="onGroupFilter"
|
@update:model-value="onGroupFilter"
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ const eventSuggestions = computed(() => eventOptions(locale.value));
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
fragments,
|
fragments,
|
||||||
|
loading: fragmentsLoading,
|
||||||
|
error: fragmentsLoadError,
|
||||||
readyFor: fragmentsReadyFor,
|
readyFor: fragmentsReadyFor,
|
||||||
load: loadFragments,
|
load: loadFragments,
|
||||||
save: saveFragments,
|
save: saveFragments,
|
||||||
@@ -459,6 +461,9 @@ watch(
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<form ref="bodyEl" class="editor-body" @submit.prevent="save">
|
<form ref="bodyEl" class="editor-body" @submit.prevent="save">
|
||||||
|
<!-- Locked while saving: an edit made meanwhile would be lost when the
|
||||||
|
save closes the editor. -->
|
||||||
|
<fieldset :disabled="saving" class="contents">
|
||||||
<section class="editor-section">
|
<section class="editor-section">
|
||||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionBasic") }}</h3>
|
<h3 class="editor-section-title">{{ t("routeEditor.sectionBasic") }}</h3>
|
||||||
<div v-if="!isEdit" class="templates">
|
<div v-if="!isEdit" class="templates">
|
||||||
@@ -477,7 +482,11 @@ watch(
|
|||||||
<div class="row2">
|
<div class="row2">
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>{{ t("routeEditor.name") }}</label>
|
<label>{{ t("routeEditor.name") }}</label>
|
||||||
<RcInput v-model="form.name" :placeholder="t('routeEditor.namePlaceholder')" required />
|
<RcInput
|
||||||
|
v-model="form.name"
|
||||||
|
:placeholder="t('routeEditor.namePlaceholder')"
|
||||||
|
required
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div class="field">
|
<div class="field">
|
||||||
<label>{{ t("routeEditor.id") }}</label>
|
<label>{{ t("routeEditor.id") }}</label>
|
||||||
@@ -575,7 +584,21 @@ watch(
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="fragments-list">
|
<div class="fragments-list">
|
||||||
<div v-if="!fragments.length" class="hint">{{ t("routeEditor.fragmentsEmpty") }}</div>
|
<!-- A failed load is said so (never shown as "no fragments"). -->
|
||||||
|
<div v-if="fragmentsLoadError" class="err">
|
||||||
|
{{ t("routeEditor.fragmentsLoadFailed", { error: fragmentsLoadError }) }}
|
||||||
|
<RcButton
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
@click="groupId && loadFragments(groupId)"
|
||||||
|
>
|
||||||
|
{{ t("routeEditor.fragmentsRetry") }}
|
||||||
|
</RcButton>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!fragments.length && !fragmentsLoading" class="hint">
|
||||||
|
{{ t("routeEditor.fragmentsEmpty") }}
|
||||||
|
</div>
|
||||||
<div v-for="frag in fragments" :key="frag.id" class="fragment-row">
|
<div v-for="frag in fragments" :key="frag.id" class="fragment-row">
|
||||||
<span class="fragment-name">{{ frag.name }}</span>
|
<span class="fragment-name">{{ frag.name }}</span>
|
||||||
<RcButton
|
<RcButton
|
||||||
@@ -703,6 +726,7 @@ watch(
|
|||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div v-if="formError" class="err" data-save-error>{{ formError }}</div>
|
<div v-if="formError" class="err" data-save-error>{{ formError }}</div>
|
||||||
|
</fieldset>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
<label class="filter-label">{{ t("logs.filterGroup") }}</label>
|
<label class="filter-label">{{ t("logs.filterGroup") }}</label>
|
||||||
<RcSelect
|
<RcSelect
|
||||||
class="filter-select"
|
class="filter-select"
|
||||||
:model-value="selectedGroupId || 'all'"
|
:model-value="selectedGroupId || '*'"
|
||||||
:options="groupOptions"
|
:options="groupOptions"
|
||||||
:disabled="loading"
|
:disabled="loading"
|
||||||
@update:model-value="onGroupFilter"
|
@update:model-value="onGroupFilter"
|
||||||
@@ -101,7 +101,7 @@ const detailLoading = ref(false);
|
|||||||
const detailError = ref("");
|
const detailError = ref("");
|
||||||
|
|
||||||
const groupOptions = computed(() => [
|
const groupOptions = computed(() => [
|
||||||
{ label: t("logs.allGroups"), value: "all" },
|
{ label: t("logs.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -142,28 +142,37 @@ function refresh(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function onGroupFilter(value: string): void {
|
function onGroupFilter(value: string): void {
|
||||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||||
emit("filter");
|
emit("filter");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Bumped by every open/close: only the latest detail request may land. */
|
||||||
|
let detailRequest = 0;
|
||||||
|
|
||||||
async function openDetail(l: SendRecord): Promise<void> {
|
async function openDetail(l: SendRecord): Promise<void> {
|
||||||
if (l.id == null) return;
|
if (l.id == null) return;
|
||||||
|
const mine = ++detailRequest;
|
||||||
detailOpen.value = true;
|
detailOpen.value = true;
|
||||||
detail.value = null;
|
detail.value = null;
|
||||||
detailError.value = "";
|
detailError.value = "";
|
||||||
detailLoading.value = true;
|
detailLoading.value = true;
|
||||||
try {
|
try {
|
||||||
detail.value = await loadById(l.id);
|
const entry = await loadById(l.id);
|
||||||
|
if (mine === detailRequest) detail.value = entry;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (mine === detailRequest) {
|
||||||
detailError.value = err instanceof Error ? err.message : String(err);
|
detailError.value = err instanceof Error ? err.message : String(err);
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
detailLoading.value = false;
|
if (mine === detailRequest) detailLoading.value = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeDetail(): void {
|
function closeDetail(): void {
|
||||||
|
detailRequest++;
|
||||||
detailOpen.value = false;
|
detailOpen.value = false;
|
||||||
detail.value = null;
|
detail.value = null;
|
||||||
|
detailLoading.value = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function onDetailOpenChange(open: boolean): void {
|
function onDetailOpenChange(open: boolean): void {
|
||||||
|
|||||||
@@ -7,10 +7,26 @@ export function useAuthState() {
|
|||||||
return { needLogin };
|
return { needLogin };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A failed admin API call, with its HTTP status (409: changed meanwhile). */
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly status: number,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = "ApiError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The write lost against a concurrent change: the shown data is stale. */
|
||||||
|
export function isConflict(err: unknown): boolean {
|
||||||
|
return err instanceof ApiError && err.status === 409;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* JSON fetch for same-origin admin API calls: sends credentials, treats 401
|
* JSON fetch for same-origin admin API calls: sends credentials, treats 401
|
||||||
* as "not logged in" (flips the shared flag and throws), and surfaces the
|
* as "not logged in" (flips the shared flag and throws), and surfaces the
|
||||||
* server's `{ error }` message on failure.
|
* server's `{ error }` message (as an ApiError with the status) on failure.
|
||||||
*/
|
*/
|
||||||
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
const res = await fetch(path, {
|
const res = await fetch(path, {
|
||||||
@@ -32,11 +48,11 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
|||||||
});
|
});
|
||||||
if (res.status === 401) {
|
if (res.status === 401) {
|
||||||
useAuthState().needLogin.value = true;
|
useAuthState().needLogin.value = true;
|
||||||
throw new Error("unauthorized");
|
throw new ApiError("unauthorized", 401);
|
||||||
}
|
}
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
||||||
throw new Error(data.error ?? `HTTP ${res.status}`);
|
throw new ApiError(data.error ?? `HTTP ${res.status}`, res.status);
|
||||||
}
|
}
|
||||||
return (await res.json()) as T;
|
return (await res.json()) as T;
|
||||||
}
|
}
|
||||||
@@ -10,6 +10,8 @@ export function useFragmentsApi() {
|
|||||||
const shownGroupId = ref<string | null>(null);
|
const shownGroupId = ref<string | null>(null);
|
||||||
/** Group whose fragments were last loaded (or saved) successfully. */
|
/** Group whose fragments were last loaded (or saved) successfully. */
|
||||||
const loadedGroupId = ref<string | null>(null);
|
const loadedGroupId = ref<string | null>(null);
|
||||||
|
/** Server revision of the shown fragments, sent back to detect concurrent edits. */
|
||||||
|
let revision: string | undefined;
|
||||||
// Bumped by every load/save, so only the latest request may land.
|
// Bumped by every load/save, so only the latest request may land.
|
||||||
let request = 0;
|
let request = 0;
|
||||||
|
|
||||||
@@ -33,17 +35,19 @@ export function useFragmentsApi() {
|
|||||||
if (shownGroupId.value !== groupId) {
|
if (shownGroupId.value !== groupId) {
|
||||||
fragments.value = [];
|
fragments.value = [];
|
||||||
loadedGroupId.value = null;
|
loadedGroupId.value = null;
|
||||||
|
revision = undefined;
|
||||||
}
|
}
|
||||||
shownGroupId.value = groupId;
|
shownGroupId.value = groupId;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
needLogin.value = false;
|
needLogin.value = false;
|
||||||
try {
|
try {
|
||||||
const data = await apiFetch<{ fragments?: NamedFragment[] }>(
|
const data = await apiFetch<{ fragments?: NamedFragment[]; revision?: string }>(
|
||||||
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
||||||
);
|
);
|
||||||
if (mine !== request) return;
|
if (mine !== request) return;
|
||||||
fragments.value = data.fragments ?? [];
|
fragments.value = data.fragments ?? [];
|
||||||
|
revision = data.revision;
|
||||||
loadedGroupId.value = groupId;
|
loadedGroupId.value = groupId;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (mine === request && !needLogin.value)
|
if (mine === request && !needLogin.value)
|
||||||
@@ -55,11 +59,25 @@ export function useFragmentsApi() {
|
|||||||
|
|
||||||
async function save(groupId: string, next: NamedFragment[]): Promise<void> {
|
async function save(groupId: string, next: NamedFragment[]): Promise<void> {
|
||||||
saving.value = true;
|
saving.value = true;
|
||||||
|
let data: { fragments?: NamedFragment[]; revision?: string };
|
||||||
try {
|
try {
|
||||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
|
data = await apiFetch<{ fragments?: NamedFragment[]; revision?: string }>(
|
||||||
|
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
||||||
|
{
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
body: JSON.stringify({ fragments: next }),
|
body: JSON.stringify({
|
||||||
});
|
fragments: next,
|
||||||
|
revision: loadedGroupId.value === groupId ? revision : undefined,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
// Changed elsewhere meanwhile: reload so the next write builds on it.
|
||||||
|
if (isConflict(err) && shownGroupId.value === groupId) {
|
||||||
|
saving.value = false;
|
||||||
|
void load(groupId);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
saving.value = false;
|
saving.value = false;
|
||||||
}
|
}
|
||||||
@@ -67,7 +85,8 @@ export function useFragmentsApi() {
|
|||||||
request++;
|
request++;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
fragments.value = next;
|
fragments.value = data.fragments ?? next;
|
||||||
|
revision = data.revision;
|
||||||
loadedGroupId.value = groupId;
|
loadedGroupId.value = groupId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,12 @@ export function useGroupRoutesApi() {
|
|||||||
const groupId = ref<string | null>(null);
|
const groupId = ref<string | null>(null);
|
||||||
/** Group whose routes were last loaded (or saved) successfully. */
|
/** Group whose routes were last loaded (or saved) successfully. */
|
||||||
const loadedId = ref<string | null>(null);
|
const loadedId = ref<string | null>(null);
|
||||||
|
/**
|
||||||
|
* Server revision of the shown routes. Every save sends it back, so a save
|
||||||
|
* built on a list someone else has changed meanwhile is refused (409)
|
||||||
|
* instead of overwriting their change.
|
||||||
|
*/
|
||||||
|
let revision: string | undefined;
|
||||||
// Bumped by every load/clear, so only the latest request may land.
|
// Bumped by every load/clear, so only the latest request may land.
|
||||||
let request = 0;
|
let request = 0;
|
||||||
|
|
||||||
@@ -24,17 +30,19 @@ export function useGroupRoutesApi() {
|
|||||||
if (groupId.value !== id) {
|
if (groupId.value !== id) {
|
||||||
routes.value = [];
|
routes.value = [];
|
||||||
loadedId.value = null;
|
loadedId.value = null;
|
||||||
|
revision = undefined;
|
||||||
}
|
}
|
||||||
groupId.value = id;
|
groupId.value = id;
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
needLogin.value = false;
|
needLogin.value = false;
|
||||||
try {
|
try {
|
||||||
const data = await apiFetch<{ routes?: Route[] }>(
|
const data = await apiFetch<{ routes?: Route[]; revision?: string }>(
|
||||||
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
||||||
);
|
);
|
||||||
if (mine !== request) return;
|
if (mine !== request) return;
|
||||||
routes.value = data.routes ?? [];
|
routes.value = data.routes ?? [];
|
||||||
|
revision = data.revision;
|
||||||
loadedId.value = id;
|
loadedId.value = id;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (mine === request && !needLogin.value)
|
if (mine === request && !needLogin.value)
|
||||||
@@ -50,15 +58,29 @@ export function useGroupRoutesApi() {
|
|||||||
groupId.value = null;
|
groupId.value = null;
|
||||||
loadedId.value = null;
|
loadedId.value = null;
|
||||||
routes.value = [];
|
routes.value = [];
|
||||||
|
revision = undefined;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save(id: string, next: Route[]): Promise<void> {
|
async function save(id: string, next: Route[]): Promise<void> {
|
||||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(id)}/routes`, {
|
let data: { routes?: Route[]; revision?: string };
|
||||||
|
try {
|
||||||
|
data = await apiFetch<{ routes?: Route[]; revision?: string }>(
|
||||||
|
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
||||||
|
{
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
body: JSON.stringify({ routes: next }),
|
body: JSON.stringify({
|
||||||
});
|
routes: next,
|
||||||
|
revision: groupId.value === id ? revision : undefined,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (err) {
|
||||||
|
// Someone changed the routes meanwhile: show theirs, nothing was written.
|
||||||
|
if (isConflict(err) && groupId.value === id) void load(id);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
// The page may have moved on to another group while the request ran.
|
// The page may have moved on to another group while the request ran.
|
||||||
if (groupId.value !== id) return;
|
if (groupId.value !== id) return;
|
||||||
// What was just written is the newest state: a load of this group that
|
// What was just written is the newest state: a load of this group that
|
||||||
@@ -66,7 +88,8 @@ export function useGroupRoutesApi() {
|
|||||||
request++;
|
request++;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
routes.value = next;
|
routes.value = data.routes ?? next;
|
||||||
|
revision = data.revision;
|
||||||
loadedId.value = id;
|
loadedId.value = id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -52,22 +52,87 @@ export function useGroupsApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function save(next: Group[]): Promise<void> {
|
/** Apply a write's result locally; a load that started earlier must not land. */
|
||||||
await apiFetch("/admin/api/groups", {
|
function settle(next: Group[]): void {
|
||||||
method: "PUT",
|
|
||||||
body: JSON.stringify({ groups: next }),
|
|
||||||
});
|
|
||||||
request++;
|
request++;
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
groups.value = next;
|
groups.value = next;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rename a group; routes, webhook secret and invites follow automatically. */
|
/** Reload after a refused write (409): someone changed the group meanwhile. */
|
||||||
async function rename(oldId: string, newId: string): Promise<void> {
|
async function guard<T>(write: () => Promise<T>): Promise<T> {
|
||||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, {
|
try {
|
||||||
|
return await write();
|
||||||
|
} catch (err) {
|
||||||
|
if (isConflict(err)) void load();
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update one group. Its `revision` (from the last load) travels along, so an
|
||||||
|
* edit made from a stale copy is refused instead of reverting newer changes.
|
||||||
|
*/
|
||||||
|
async function update(group: Group): Promise<Group> {
|
||||||
|
const data = await guard(() =>
|
||||||
|
apiFetch<{ group: Group }>(`/admin/api/groups/${encodeURIComponent(group.id)}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
body: JSON.stringify({ newId }),
|
body: JSON.stringify({ group }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
settle(groups.value.map((g) => (g.id === data.group.id ? data.group : g)));
|
||||||
|
return data.group;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create one group (super admins). */
|
||||||
|
async function create(group: Group): Promise<Group> {
|
||||||
|
const data = await apiFetch<{ group: Group }>("/admin/api/groups", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ group }),
|
||||||
});
|
});
|
||||||
|
settle([...groups.value.filter((g) => g.id !== data.group.id), data.group]);
|
||||||
|
return data.group;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete one group with its routes. `revision` (the group) and
|
||||||
|
* `routesRevision` (its routes) are what the deletion was confirmed on: if
|
||||||
|
* either changed meanwhile, the server refuses (409) instead of deleting
|
||||||
|
* something nobody saw.
|
||||||
|
*/
|
||||||
|
async function remove(
|
||||||
|
id: string,
|
||||||
|
revision?: string,
|
||||||
|
routesRevision?: string,
|
||||||
|
version?: number | null,
|
||||||
|
): Promise<void> {
|
||||||
|
const query = new URLSearchParams();
|
||||||
|
if (revision) query.set("revision", revision);
|
||||||
|
if (routesRevision) query.set("routesRevision", routesRevision);
|
||||||
|
if (version != null) query.set("version", String(version));
|
||||||
|
const qs = query.toString();
|
||||||
|
await guard(() =>
|
||||||
|
apiFetch(`/admin/api/groups/${encodeURIComponent(id)}${qs ? `?${qs}` : ""}`, {
|
||||||
|
method: "DELETE",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
settle(groups.value.filter((g) => g.id !== id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rename a group; routes, webhook secret and invites follow automatically.
|
||||||
|
* `revision` is the group's revision the rename was decided on.
|
||||||
|
*/
|
||||||
|
async function rename(oldId: string, newId: string, revision?: string): Promise<Group> {
|
||||||
|
const data = await guard(() =>
|
||||||
|
apiFetch<{ group: Group }>(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify({ newId, revision }),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
// Show the group under its new id right away (a later step may still fail).
|
||||||
|
settle(groups.value.map((g) => (g.id === oldId ? data.group : g)));
|
||||||
|
return data.group;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -82,7 +147,9 @@ export function useGroupsApi() {
|
|||||||
needLogin,
|
needLogin,
|
||||||
error,
|
error,
|
||||||
load,
|
load,
|
||||||
save,
|
update,
|
||||||
|
create,
|
||||||
|
remove,
|
||||||
rename,
|
rename,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,9 @@ const en: Dict = {
|
|||||||
"overview.recent": "Recent deliveries",
|
"overview.recent": "Recent deliveries",
|
||||||
"overview.viewAll": "View all",
|
"overview.viewAll": "View all",
|
||||||
"overview.refreshed": "Refreshed",
|
"overview.refreshed": "Refreshed",
|
||||||
|
"overview.refreshFailed": "Refresh failed",
|
||||||
|
"overview.loadFailed":
|
||||||
|
"Some data could not be loaded; what is shown may be incomplete or out of date: {error}",
|
||||||
"overview.thRoute": "Route",
|
"overview.thRoute": "Route",
|
||||||
"overview.thGroup": "Group",
|
"overview.thGroup": "Group",
|
||||||
"overview.thEvents": "Events",
|
"overview.thEvents": "Events",
|
||||||
@@ -104,6 +107,7 @@ const en: Dict = {
|
|||||||
"members.copied": "Copied!",
|
"members.copied": "Copied!",
|
||||||
"members.revoke": "Revoke",
|
"members.revoke": "Revoke",
|
||||||
"members.noInvites": "No pending invites.",
|
"members.noInvites": "No pending invites.",
|
||||||
|
"members.invitesFailed": "Could not load invites: {error}",
|
||||||
"members.errSelfOwner": "You must remain an owner of this group.",
|
"members.errSelfOwner": "You must remain an owner of this group.",
|
||||||
"members.errOwner": "A group needs at least one owner.",
|
"members.errOwner": "A group needs at least one owner.",
|
||||||
"members.errLastOwner": "Cannot remove the last owner.",
|
"members.errLastOwner": "Cannot remove the last owner.",
|
||||||
@@ -111,6 +115,8 @@ const en: Dict = {
|
|||||||
"members.inviteBad": "This invite is invalid or expired.",
|
"members.inviteBad": "This invite is invalid or expired.",
|
||||||
"install.ok":
|
"install.ok":
|
||||||
"GitHub App installation registered — the group has been created and bound to this installation.",
|
"GitHub App installation registered — the group has been created and bound to this installation.",
|
||||||
|
"install.forbidden":
|
||||||
|
"Your GitHub account cannot manage this installation, so it was not bound. Sign in with an account that administers it.",
|
||||||
"webhook.title": "Webhook endpoint",
|
"webhook.title": "Webhook endpoint",
|
||||||
"webhook.note": "(per-group URL + secret)",
|
"webhook.note": "(per-group URL + secret)",
|
||||||
"webhook.empty": "Not configured. Generate a secret to enable the group's own webhook endpoint.",
|
"webhook.empty": "Not configured. Generate a secret to enable the group's own webhook endpoint.",
|
||||||
@@ -289,6 +295,8 @@ const en: Dict = {
|
|||||||
"routeEditor.fragments": "Fragments",
|
"routeEditor.fragments": "Fragments",
|
||||||
"routeEditor.fragmentsPresets": "Presets",
|
"routeEditor.fragmentsPresets": "Presets",
|
||||||
"routeEditor.fragmentsEmpty": "No fragments yet",
|
"routeEditor.fragmentsEmpty": "No fragments yet",
|
||||||
|
"routeEditor.fragmentsLoadFailed": "Fragments could not be loaded: {error}",
|
||||||
|
"routeEditor.fragmentsRetry": "Retry",
|
||||||
"routeEditor.fragmentsInsert": "Insert",
|
"routeEditor.fragmentsInsert": "Insert",
|
||||||
"routeEditor.fragmentsDelete": "Delete",
|
"routeEditor.fragmentsDelete": "Delete",
|
||||||
"routeEditor.fragmentsSave": "Save as fragment",
|
"routeEditor.fragmentsSave": "Save as fragment",
|
||||||
@@ -428,6 +436,8 @@ const en: Dict = {
|
|||||||
"toast.groupSaved": "Groups saved",
|
"toast.groupSaved": "Groups saved",
|
||||||
"toast.groupDeleted": "Group deleted",
|
"toast.groupDeleted": "Group deleted",
|
||||||
"toast.routeIdExists": "Route ID already exists",
|
"toast.routeIdExists": "Route ID already exists",
|
||||||
|
"toast.routeChanged":
|
||||||
|
"This route was changed by someone else since you opened it. Close the editor and open it again.",
|
||||||
"toast.groupIdExists": "Group ID already exists",
|
"toast.groupIdExists": "Group ID already exists",
|
||||||
"toast.saveFailed": "Save failed: {msg}",
|
"toast.saveFailed": "Save failed: {msg}",
|
||||||
"toast.deleteFailed": "Delete failed: {msg}",
|
"toast.deleteFailed": "Delete failed: {msg}",
|
||||||
@@ -473,6 +483,8 @@ const zh: Dict = {
|
|||||||
"overview.recent": "最近投递",
|
"overview.recent": "最近投递",
|
||||||
"overview.viewAll": "查看全部",
|
"overview.viewAll": "查看全部",
|
||||||
"overview.refreshed": "已刷新",
|
"overview.refreshed": "已刷新",
|
||||||
|
"overview.refreshFailed": "刷新失败",
|
||||||
|
"overview.loadFailed": "部分数据加载失败,当前显示的内容可能不完整或已过期:{error}",
|
||||||
"overview.thRoute": "路由",
|
"overview.thRoute": "路由",
|
||||||
"overview.thGroup": "分组",
|
"overview.thGroup": "分组",
|
||||||
"overview.thEvents": "事件",
|
"overview.thEvents": "事件",
|
||||||
@@ -552,12 +564,14 @@ const zh: Dict = {
|
|||||||
"members.copied": "已复制!",
|
"members.copied": "已复制!",
|
||||||
"members.revoke": "撤销",
|
"members.revoke": "撤销",
|
||||||
"members.noInvites": "暂无待接受的邀请。",
|
"members.noInvites": "暂无待接受的邀请。",
|
||||||
|
"members.invitesFailed": "邀请列表加载失败:{error}",
|
||||||
"members.errSelfOwner": "你必须保留本组的 owner 身份。",
|
"members.errSelfOwner": "你必须保留本组的 owner 身份。",
|
||||||
"members.errOwner": "分组至少需要一位 owner。",
|
"members.errOwner": "分组至少需要一位 owner。",
|
||||||
"members.errLastOwner": "不能移除最后一位 owner。",
|
"members.errLastOwner": "不能移除最后一位 owner。",
|
||||||
"members.inviteOk": "邀请已接受 —— 欢迎!",
|
"members.inviteOk": "邀请已接受 —— 欢迎!",
|
||||||
"members.inviteBad": "该邀请无效或已过期。",
|
"members.inviteBad": "该邀请无效或已过期。",
|
||||||
"install.ok": "GitHub App 安装已注册 —— 分组已创建并绑定到该安装。",
|
"install.ok": "GitHub App 安装已注册 —— 分组已创建并绑定到该安装。",
|
||||||
|
"install.forbidden": "你的 GitHub 账号无权管理该安装,未进行绑定。请使用该安装的管理员账号登录。",
|
||||||
"webhook.title": "Webhook 入口",
|
"webhook.title": "Webhook 入口",
|
||||||
"webhook.note": "(分组独立的 URL + secret)",
|
"webhook.note": "(分组独立的 URL + secret)",
|
||||||
"webhook.empty": "未配置。生成 secret 即可启用该分组的独立 webhook 入口。",
|
"webhook.empty": "未配置。生成 secret 即可启用该分组的独立 webhook 入口。",
|
||||||
@@ -733,6 +747,8 @@ const zh: Dict = {
|
|||||||
"routeEditor.fragments": "过滤器片段",
|
"routeEditor.fragments": "过滤器片段",
|
||||||
"routeEditor.fragmentsPresets": "预设",
|
"routeEditor.fragmentsPresets": "预设",
|
||||||
"routeEditor.fragmentsEmpty": "暂无片段",
|
"routeEditor.fragmentsEmpty": "暂无片段",
|
||||||
|
"routeEditor.fragmentsLoadFailed": "片段加载失败:{error}",
|
||||||
|
"routeEditor.fragmentsRetry": "重试",
|
||||||
"routeEditor.fragmentsInsert": "插入",
|
"routeEditor.fragmentsInsert": "插入",
|
||||||
"routeEditor.fragmentsDelete": "删除",
|
"routeEditor.fragmentsDelete": "删除",
|
||||||
"routeEditor.fragmentsSave": "存为片段",
|
"routeEditor.fragmentsSave": "存为片段",
|
||||||
@@ -870,6 +886,7 @@ const zh: Dict = {
|
|||||||
"toast.groupSaved": "分组已保存",
|
"toast.groupSaved": "分组已保存",
|
||||||
"toast.groupDeleted": "分组已删除",
|
"toast.groupDeleted": "分组已删除",
|
||||||
"toast.routeIdExists": "路由 ID 已存在",
|
"toast.routeIdExists": "路由 ID 已存在",
|
||||||
|
"toast.routeChanged": "该路由在你打开后已被他人修改。请关闭编辑器后重新打开。",
|
||||||
"toast.groupIdExists": "分组 ID 已存在",
|
"toast.groupIdExists": "分组 ID 已存在",
|
||||||
"toast.saveFailed": "保存失败:{msg}",
|
"toast.saveFailed": "保存失败:{msg}",
|
||||||
"toast.deleteFailed": "删除失败:{msg}",
|
"toast.deleteFailed": "删除失败:{msg}",
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export function useInvitesApi() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Throws when the list cannot be read: never shown as "no invites". */
|
||||||
async function list(groupId: string): Promise<GroupInvite[]> {
|
async function list(groupId: string): Promise<GroupInvite[]> {
|
||||||
loading.value = true;
|
loading.value = true;
|
||||||
error.value = "";
|
error.value = "";
|
||||||
@@ -31,7 +32,7 @@ export function useInvitesApi() {
|
|||||||
return data.invites ?? [];
|
return data.invites ?? [];
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error.value = err instanceof Error ? err.message : String(err);
|
error.value = err instanceof Error ? err.message : String(err);
|
||||||
return [];
|
throw err;
|
||||||
} finally {
|
} finally {
|
||||||
loading.value = false;
|
loading.value = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,6 +85,12 @@ export interface Group {
|
|||||||
owners?: string[];
|
owners?: string[];
|
||||||
providers?: ("github" | "gitea" | "gitlab")[];
|
providers?: ("github" | "gitea" | "gitlab")[];
|
||||||
installationId?: number;
|
installationId?: number;
|
||||||
|
/** Self-service group: only its own webhook ingress dispatches to it (super-only). */
|
||||||
|
isolated?: boolean;
|
||||||
|
/** Immutable server-assigned group identity (kept across renames). */
|
||||||
|
instance?: string;
|
||||||
|
/** Server revision of the stored group; sent back on update to detect stale edits. */
|
||||||
|
revision?: string;
|
||||||
emoji?: boolean;
|
emoji?: boolean;
|
||||||
forgeSources?: ForgeSource[];
|
forgeSources?: ForgeSource[];
|
||||||
lang?: string;
|
lang?: string;
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
{
|
{
|
||||||
"lockfileVersion": 1,
|
"lockfileVersion": 1,
|
||||||
"configVersion": 1,
|
|
||||||
"workspaces": {
|
"workspaces": {
|
||||||
"": {
|
"": {
|
||||||
"name": "webhooker",
|
"name": "webhooker",
|
||||||
@@ -10,6 +9,7 @@
|
|||||||
"markdown-it": "^15.0.0",
|
"markdown-it": "^15.0.0",
|
||||||
"nuxt": "^4.1.0",
|
"nuxt": "^4.1.0",
|
||||||
"octokit": "^4.1.0",
|
"octokit": "^4.1.0",
|
||||||
|
"re2js": "^2.8.8",
|
||||||
"valibot": "^1.4.2",
|
"valibot": "^1.4.2",
|
||||||
"vue": "^3.5.13",
|
"vue": "^3.5.13",
|
||||||
},
|
},
|
||||||
@@ -1557,6 +1557,8 @@
|
|||||||
|
|
||||||
"rc9": ["rc9@3.0.1", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],
|
"rc9": ["rc9@3.0.1", "", { "dependencies": { "defu": "^6.1.6", "destr": "^2.0.5" } }, "sha512-gMDyleLWVE+i6Sgtc0QbbY6pEKqYs97NGi6isHQPqYlLemPoO8dxQ3uGi0f4NiP98c+jMW6cG1Kx9dDwfvqARQ=="],
|
||||||
|
|
||||||
|
"re2js": ["re2js@2.8.8", "https://registry.npmmirror.com/re2js/-/re2js-2.8.8.tgz", {}, "sha512-E2FVgqD2mzJ+ZmMSHLnkOvZ7PiZ4FgMdfVCA3YsJWs9gtyoaKmUMxyVPCXS1yK209/mz3XkdT7kr3OlMWW2Fww=="],
|
||||||
|
|
||||||
"readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
|
"readable-stream": ["readable-stream@4.7.0", "", { "dependencies": { "abort-controller": "^3.0.0", "buffer": "^6.0.3", "events": "^3.3.0", "process": "^0.11.10", "string_decoder": "^1.3.0" } }, "sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg=="],
|
||||||
|
|
||||||
"readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
|
"readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
|
||||||
|
|||||||
+15
-12
@@ -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
|
# 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 scope admin access and can restrict which org/user events flow in.
|
||||||
groups:
|
groups:
|
||||||
@@ -11,7 +13,7 @@ groups:
|
|||||||
- login: "your-github-id"
|
- login: "your-github-id"
|
||||||
role: owner
|
role: owner
|
||||||
# owners: ["myorg"] # restrict events to this org/user (optional)
|
# 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)
|
# installationId: 12345678 # GitHub App installation binding (auto-created on installation.created)
|
||||||
# emoji: true # include emoji in messages (default true)
|
# emoji: true # include emoji in messages (default true)
|
||||||
# Forge hosts: label message footers with the host an event came from
|
# Forge hosts: label message footers with the host an event came from
|
||||||
@@ -24,9 +26,9 @@ groups:
|
|||||||
# type: gitea
|
# type: gitea
|
||||||
# - host: "git2.example.com" # another one
|
# - host: "git2.example.com" # another one
|
||||||
# type: gitea
|
# type: gitea
|
||||||
# lang: "en" # message language for this group's routes (en/zh, default en)
|
# 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 or Telegram chat/topic that
|
# Webhook log channel: a Discord channel/thread, Telegram chat/topic or Feishu
|
||||||
# receives a summary of every webhook this group's routes dispatch.
|
# chat that receives a summary of every webhook this group's routes dispatch.
|
||||||
# logTarget:
|
# logTarget:
|
||||||
# platform: discord
|
# platform: discord
|
||||||
# channelId: "CHANNEL_ID_HERE"
|
# channelId: "CHANNEL_ID_HERE"
|
||||||
@@ -62,10 +64,10 @@ routes:
|
|||||||
# channelId: "CHANNEL_ID_HERE"
|
# channelId: "CHANNEL_ID_HERE"
|
||||||
# threadId: "THREAD_ID_HERE"
|
# threadId: "THREAD_ID_HERE"
|
||||||
# - platform: telegram
|
# - platform: telegram
|
||||||
# chatId: "-1001234567890"
|
# chatId: "-1001234567890" # numeric chat id (no @username)
|
||||||
# topicId: "9876543210"
|
# topicId: "42"
|
||||||
# - platform: feishu
|
# - platform: feishu
|
||||||
# chatId: "oc_xxxxxxxxxxxxxxxx" # Feishu group chat_id
|
# chatId: "oc_xxxxxxxxxxxxxxxx" # Feishu group chat_id (no topics)
|
||||||
|
|
||||||
# - id: exclude-bot
|
# - id: exclude-bot
|
||||||
# name: "Exclude Bot Actions"
|
# name: "Exclude Bot Actions"
|
||||||
@@ -73,7 +75,7 @@ routes:
|
|||||||
# groupId: default
|
# groupId: default
|
||||||
# filters:
|
# filters:
|
||||||
# - type: actor
|
# - type: actor
|
||||||
# match: "[bot]"
|
# match: "*[bot]"
|
||||||
# exclude: true
|
# exclude: true
|
||||||
# targets:
|
# targets:
|
||||||
# - platform: discord
|
# - platform: discord
|
||||||
@@ -137,12 +139,13 @@ routes:
|
|||||||
# - platform: discord
|
# - platform: discord
|
||||||
# channelId: "CHANNEL_ID_HERE"
|
# channelId: "CHANNEL_ID_HERE"
|
||||||
|
|
||||||
# Nested `ast` groups (all / any / not) replace the flat filters list and take
|
# Nested `ast` groups (all / any / not) take precedence over the flat `filters`
|
||||||
# precedence over `filters` when both are present.
|
# list; the route still carries a `filters` list (it may be empty).
|
||||||
# - id: grouped-owners
|
# - id: grouped-owners
|
||||||
# name: "PRs from either owner"
|
# name: "PRs from either owner"
|
||||||
# enabled: true
|
# enabled: true
|
||||||
# groupId: default
|
# groupId: default
|
||||||
|
# filters: []
|
||||||
# ast:
|
# ast:
|
||||||
# all:
|
# all:
|
||||||
# - type: event
|
# - type: event
|
||||||
|
|||||||
+7
-7
@@ -40,7 +40,7 @@ Creates a comment on an issue or pull request.
|
|||||||
| `issueNumber` | number | Yes | Issue or PR number |
|
| `issueNumber` | number | Yes | Issue or PR number |
|
||||||
| `body` | string | Yes | Comment body (Markdown supported) |
|
| `body` | string | Yes | Comment body (Markdown supported) |
|
||||||
|
|
||||||
**Response:** `200` with GitHub API response.
|
**Response:** `200 { "ok": true }`.
|
||||||
|
|
||||||
### Merge Pull Request
|
### Merge Pull Request
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ Merges a pull request.
|
|||||||
| `pullNumber` | number | Yes | Pull request number |
|
| `pullNumber` | number | Yes | Pull request number |
|
||||||
| `method` | string | No | `merge`, `squash`, or `rebase` (default: `squash`) |
|
| `method` | string | No | `merge`, `squash`, or `rebase` (default: `squash`) |
|
||||||
|
|
||||||
**Response:** `200` with GitHub merge response.
|
**Response:** `200 { "ok": true }`.
|
||||||
|
|
||||||
### Close Pull Request
|
### Close Pull Request
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ Closes a pull request without merging.
|
|||||||
| `repo` | string | Yes | Repository name |
|
| `repo` | string | Yes | Repository name |
|
||||||
| `pullNumber` | number | Yes | Pull request number |
|
| `pullNumber` | number | Yes | Pull request number |
|
||||||
|
|
||||||
**Response:** `200` with GitHub update response.
|
**Response:** `200 { "ok": true }`.
|
||||||
|
|
||||||
### Add Reaction
|
### Add Reaction
|
||||||
|
|
||||||
@@ -102,7 +102,7 @@ Closes a pull request without merging.
|
|||||||
POST /api/react
|
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:**
|
**Request Body:**
|
||||||
|
|
||||||
@@ -116,17 +116,17 @@ Adds an emoji reaction to an issue or comment.
|
|||||||
```
|
```
|
||||||
|
|
||||||
| Field | Type | Required | Description |
|
| Field | Type | Required | Description |
|
||||||
| ------------- | ------ | -------- | ---------------------------- |
|
| ------------- | ------ | -------- | ------------------------- |
|
||||||
| `owner` | string | Yes | Repository owner |
|
| `owner` | string | Yes | Repository owner |
|
||||||
| `repo` | string | Yes | Repository name |
|
| `repo` | string | Yes | Repository name |
|
||||||
| `issueNumber` | number | Yes | Issue, PR, or comment number |
|
| `issueNumber` | number | Yes | Issue or PR number |
|
||||||
| `reaction` | string | Yes | Reaction type (see below) |
|
| `reaction` | string | Yes | Reaction type (see below) |
|
||||||
|
|
||||||
**Reaction Types:**
|
**Reaction Types:**
|
||||||
|
|
||||||
`+1`, `-1`, `laugh`, `confused`, `heart`, `hooray`, `rocket`, `eyes`
|
`+1`, `-1`, `laugh`, `confused`, `heart`, `hooray`, `rocket`, `eyes`
|
||||||
|
|
||||||
**Response:** `200` with GitHub reaction response.
|
**Response:** `200 { "ok": true }`.
|
||||||
|
|
||||||
## Error Responses
|
## Error Responses
|
||||||
|
|
||||||
|
|||||||
+27
-17
@@ -7,7 +7,7 @@ The console itself is served at `/admin`; its tabs are deep-linkable via the URL
|
|||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
| Endpoint | Description |
|
| Endpoint | Description |
|
||||||
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
| `GET /admin` | Config console UI |
|
| `GET /admin` | Config console UI |
|
||||||
| `GET /admin/login` | Start admin sign-in (GitHub OAuth) |
|
| `GET /admin/login` | Start admin sign-in (GitHub OAuth) |
|
||||||
| `GET /admin/logout` | Sign out and destroy the session |
|
| `GET /admin/logout` | Sign out and destroy the session |
|
||||||
@@ -15,32 +15,42 @@ The console itself is served at `/admin`; its tabs are deep-linkable via the URL
|
|||||||
| `GET /admin/api/me` | Current session, scope, groups, and roles |
|
| `GET /admin/api/me` | Current session, scope, groups, and roles |
|
||||||
| `GET /admin/api/routes` | List routes (scoped to access) |
|
| `GET /admin/api/routes` | List routes (scoped to access) |
|
||||||
| `PUT /admin/api/routes` | Replace routes (owner/admin per group) |
|
| `PUT /admin/api/routes` | Replace routes (owner/admin per group) |
|
||||||
| `GET /admin/api/groups` | List groups + the signed-in user's role in each |
|
| `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` | Replace groups (super: all; owner: own only) |
|
| `PUT /admin/api/groups` | Bulk write (legacy): super admins replace all groups, owners change/delete their own; only groups that differ are written |
|
||||||
| `GET /admin/api/groups/:id/routes` | List a group's routes |
|
| `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/routes` | Replace a group's routes (owner/admin) |
|
| `PUT /admin/api/groups/:id` | Update one group (owner) — body `{ group }`; `409` when its `revision` is stale |
|
||||||
| `GET /admin/api/groups/:id/fragments` | List a group's named filter fragments |
|
| `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 |
|
||||||
| `PUT /admin/api/groups/:id/fragments` | Replace a group's named filter fragments (owner/admin) |
|
| `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/rename` | Rename a group (owner); routes, webhook secret and invites follow (routes are moved before the group record is updated) |
|
| `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) |
|
| `GET /admin/api/groups/:id/invites` | List pending invites (owner) |
|
||||||
| `POST /admin/api/groups/:id/invites` | Create an invite link (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) |
|
| `DELETE /admin/api/invites/:token` | Revoke an invite (owner) |
|
||||||
| `GET /admin/api/groups/:id/webhook` | Group webhook endpoint info (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) |
|
| `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) |
|
| `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` | 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/logs/:id` | Single send-log entry (scoped) |
|
||||||
| `GET /admin/api/audit` | Audit log (scoped to accessible groups) |
|
| `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; recent failures scoped to accessible groups for non-super |
|
| `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` | All send-log attempts for one delivery (group-scoped) |
|
| `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) |
|
| `POST /admin/api/test-match` | Stateless filter dry-run — evaluate a filter node against a pasted JSON payload (no event is stored) |
|
||||||
|
|
||||||
## Validation
|
## 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/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` — Validates group ids, member roles (at least one `owner`), `providers` (`github` / `gitea`), and `installationId`.
|
- `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.
|
- `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 }`.
|
- `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: at most 200 routes and 100 groups per instance.
|
- 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).
|
Schemas: [Routes & Targets](../guide/routes), [Groups & Access Control](../guide/groups).
|
||||||
+14
-5
@@ -42,12 +42,21 @@ GitHub redirects here after authorization. Exchanges the code for an access toke
|
|||||||
| `code` | Authorization code |
|
| `code` | Authorization code |
|
||||||
| `state` | State parameter for CSRF protection |
|
| `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:**
|
**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`.
|
- **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": "..." }`.
|
- **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.
|
- **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.
|
||||||
- **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`.
|
|
||||||
|
### 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
|
### Revoke Token
|
||||||
|
|
||||||
@@ -55,7 +64,7 @@ GitHub redirects here after authorization. Exchanges the code for an access toke
|
|||||||
DELETE /auth/token/:userId
|
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:**
|
**Response:**
|
||||||
|
|
||||||
@@ -74,11 +83,11 @@ Tokens are stored in KV with key pattern `token:{userId}`:
|
|||||||
"userId": "12345",
|
"userId": "12345",
|
||||||
"accessToken": "gho_...",
|
"accessToken": "gho_...",
|
||||||
"expiresAt": 1735689600000,
|
"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
|
## Using Tokens
|
||||||
|
|
||||||
|
|||||||
+12
-6
@@ -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` | `/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` | `/discord/interactions` | Ed25519 signature | Discord interactions (slash commands, buttons, modals) |
|
||||||
| `POST` | `/telegram/webhook` | Secret token | Telegram updates (bot `/gh` commands) |
|
| `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` | `/api/richheader` | None | Open Graph page for the Telegram avatar link-preview card |
|
||||||
| `GET` | `/auth/github` | None | Start GitHub OAuth flow |
|
| `GET` | `/auth/github` | None | Start GitHub OAuth flow |
|
||||||
| `GET` | `/auth/github/callback` | None | OAuth callback |
|
| `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 |
|
| `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 |
|
| `POST` | `/auth/github/install/bind` | Admin session | Provision the chosen installation binding |
|
||||||
| `DELETE` | `/auth/token/:userId` | Admin session | Revoke user token |
|
| `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
|
```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:**
|
**Error Responses:**
|
||||||
|
|
||||||
| Status | Body | Cause |
|
| Status | Body | Cause |
|
||||||
| ------ | -------------------------------- | -------------------------------------- |
|
| ------ | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
| `401` | `{"error": "Invalid signature"}` | Signature verification failed |
|
| `401` | `{"error": "Invalid signature"}` | Signature verification failed |
|
||||||
| `400` | `{"error": "Invalid event"}` | Missing event header or malformed body |
|
| `400` | `{"error": "Invalid event"}` | Missing event header or malformed body |
|
||||||
| `413` | `{"error": "Request too large"}` | Body exceeds 1MB limit |
|
| `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`)
|
### 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
|
### 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
|
### 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
|
## 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
|
```json
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,22 +25,24 @@ app/ # Vue 3 UI (Nuxt app dir)
|
|||||||
server/ # Nitro server (H3 handlers in server/routes/)
|
server/ # Nitro server (H3 handlers in server/routes/)
|
||||||
├── routes/ # /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
|
├── routes/ # /health, /webhook[/:groupId], /discord/interactions, /telegram/webhook,
|
||||||
│ # /auth/github*, /admin/{login,logout,invite,api/**}, /api/{comment,merge,close,react,richheader}
|
│ # /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
|
├── error-handler.ts # JSON error handler
|
||||||
└── lib/
|
└── lib/
|
||||||
├── types.ts # Env, Config, Route, Filter, Group, WebhookEvent, NeutralMessage
|
├── 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/
|
├── core/
|
||||||
│ └── dispatch.ts # Platform-neutral dispatch: match routes → formatEvent → getDriver().send/edit
|
│ └── dispatch.ts # Platform-neutral dispatch: match routes → formatEvent → getDriver().send/edit
|
||||||
├── events/ # Provider-agnostic route matching
|
├── 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)
|
├── providers/ # Forge webhook providers (verify + parse/normalize)
|
||||||
│ ├── types.ts # Provider interface (matches/verify/parse)
|
│ ├── types.ts # Provider interface (matches/verify/parse)
|
||||||
│ ├── index.ts # detectProvider() registry (github, gitea, custom)
|
│ ├── index.ts # detectProvider() registry (github, gitea, custom)
|
||||||
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
||||||
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature (normalized payloads)
|
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature (normalized payloads)
|
||||||
├── formatters/ # Platform-neutral formatters (produce NeutralMessage)
|
├── 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
|
│ ├── colors.ts # GITHUB_COLORS + WORKFLOW_CONCLUSION_EMOJI
|
||||||
│ ├── helpers.ts # emojiPrefix, T, buildMessage, commitLink/branchLink/tagLink
|
│ ├── helpers.ts # emojiPrefix, T, buildMessage, commitLink/branchLink/tagLink
|
||||||
│ └── *.ts # push, pull-request, issues, comments, workflow, release, create, repo,
|
│ └── *.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)
|
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)
|
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/`
|
3. Create a `formatEventType` function in `server/lib/formatters/`
|
||||||
4. Add the case to the `formatEvent` switch statement in `server/lib/formatters/index.ts`
|
4. Register it in `eventFormatters` in `server/lib/formatters/registry.ts` (`{ events: ["your_event"], format: (c) => … }`)
|
||||||
5. Update `extractBranch` in `server/lib/events/match.ts` if the event has branch info
|
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`
|
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
|
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
|
8. Subscribe to the event in your GitHub App settings
|
||||||
|
|||||||
@@ -41,8 +41,9 @@ 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`):
|
Each event type uses a distinct color in the Discord embed (from `server/lib/formatters/colors.ts`):
|
||||||
|
|
||||||
| Color | Events |
|
| 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 |
|
| 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 |
|
| 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 |
|
| Purple (`#8957e5`) | PR merged, label, discussion |
|
||||||
| Blue (`#1f6feb`) | PR (other actions), issue reopened, fork, milestone opened |
|
| Blue (`#1f6feb`) | PR (other actions), issue reopened, fork, milestone opened |
|
||||||
@@ -60,7 +61,7 @@ Any event type without a dedicated formatter falls through to the generic format
|
|||||||
|
|
||||||
## In-Place Message Updates
|
## 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.
|
`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.
|
||||||
|
|
||||||
@@ -69,10 +70,10 @@ 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.
|
See the [Filter Tutorial](../guide/filters) for a hands-on guide with worked examples.
|
||||||
|
|
||||||
| Filter | Works With |
|
| Filter | Works With |
|
||||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `event` | All events |
|
| `event` | All events |
|
||||||
| `repo` | All events |
|
| `repo` | All events |
|
||||||
| `actor` | All events |
|
| `actor` | All events |
|
||||||
| `action` | Events with `action` field in payload |
|
| `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 |
|
| `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) |
|
| `keyword` | All events (searches full payload body) |
|
||||||
+17
-9
@@ -1,23 +1,27 @@
|
|||||||
# Bot Commands
|
# 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
|
## 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 |
|
| Platform | Command | Effect |
|
||||||
| -------- | --------------------------------- | ---------------------------------------------------------------- |
|
| -------- | --------------------------------- | ---------------------------------------------------------------- |
|
||||||
| Discord | `/gh login` | Returns an ephemeral OAuth link to authorize your GitHub account |
|
| Discord | `/gh login` | Returns an ephemeral OAuth link to authorize your GitHub account |
|
||||||
| Discord | `/gh logout` | Unlinks 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 |
|
| 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
|
||||||
|
|
||||||
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
|
### Comment on an issue / PR
|
||||||
|
|
||||||
@@ -32,11 +36,11 @@ Two equivalent ways:
|
|||||||
/gh comment del link:<comment url> url must contain #issuecomment-<id>
|
/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
|
### 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.
|
- 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.
|
- 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**:
|
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 logout` — unlink
|
||||||
- `/gh comment <text>` — reply to an issue/PR notification to comment as yourself
|
- `/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
|
- `/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.
|
||||||
+25
-14
@@ -27,25 +27,36 @@ 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_ID` | Feishu app ID (from the app Credentials page) — required for Feishu routes |
|
||||||
| `FEISHU_APP_SECRET` | Feishu app secret — 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]
|
> [!NOTE]
|
||||||
> `GITHUB_APP_ID` and `GITHUB_PRIVATE_KEY` (PKCS#8 PEM) are used by the GitHub App
|
> `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
|
> **install flow** (`/auth/github/install`) to resolve the installation's account via
|
||||||
> via an App JWT. They are optional — when unset, the install page still works but
|
> an App JWT — which is also how the flow verifies that the signed-in user may manage
|
||||||
> shows an anonymous `inst-{installationId}` group without the account name. The
|
> the installation. Without them only super admins can bind installations. The OAuth
|
||||||
> OAuth flow itself only needs `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`.
|
> 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
|
### Optional Secrets
|
||||||
|
|
||||||
| Variable | Description | Default |
|
| Variable | Description | Default |
|
||||||
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
|
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
|
||||||
| `DISCORD_PUBLIC_KEY` | Discord application public key (Developer Portal) — required for interactions | Unset → interactions return `401` |
|
| `DISCORD_PUBLIC_KEY` | Discord application public key (Developer Portal) — required for interactions | Unset → interactions return `401` |
|
||||||
| `DISCORD_APPLICATION_ID` | Discord application id; auto-resolved when omitted | Auto-resolved |
|
| `DISCORD_APPLICATION_ID` | Discord application id; auto-resolved when omitted | Auto-resolved |
|
||||||
| `TELEGRAM_WEBHOOK_SECRET` | Secret token for `POST /telegram/webhook` verification (X-Telegram-Bot-Api-Secret-Token) | Disabled (no verification) |
|
| `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` |
|
| `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` |
|
| `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 | Disabled |
|
| `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 |
|
| `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 |
|
| `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` |
|
| `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_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_REPO_URL` | GitHub repo URL used by the landing page | Landing page defaults |
|
||||||
@@ -57,7 +68,7 @@ WebHooker ships with a built-in config console at `/admin` for managing routes,
|
|||||||
|
|
||||||
### Setup
|
### 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.
|
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).
|
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>.
|
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
|
## 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)
|
- 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
|
- 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
|
- 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
|
- `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
|
- 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
|
- 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_suite, deployment, and code_scanning_alert events
|
- `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
|
### Match Values
|
||||||
|
|
||||||
|
|||||||
+30
-18
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Cloudflare Setup
|
## 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
|
### 1. Create KV Namespace
|
||||||
|
|
||||||
```bash
|
```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 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_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 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
|
::: 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
|
::: 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.
|
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
|
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`
|
::: 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
|
```bash
|
||||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0001_init.sql
|
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/0010_fragments.sql
|
||||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0011_feishu_links.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/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)
|
### 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
|
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)
|
### 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
|
```bash
|
||||||
bunx wrangler queues create webhooker-delivery
|
bunx wrangler queues create webhooker-delivery
|
||||||
bunx wrangler queues create webhooker-delivery-dlq
|
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
|
### 6. Deploy
|
||||||
|
|
||||||
```bash
|
```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`.
|
Your worker is now live at `https://webhooker.<your-subdomain>.workers.dev`.
|
||||||
|
|
||||||
### 7. Configure GitHub Webhook
|
### 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
|
- **Organization permissions**: Members (read) — if needed
|
||||||
4. Subscribe to events (all 28 supported):
|
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
|
- 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
|
### 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`.
|
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`).
|
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.
|
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
|
## Telegram Bot Setup
|
||||||
|
|
||||||
1. Create a bot with [@BotFather](https://t.me/BotFather) and copy its token to `TELEGRAM_TOKEN`.
|
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.
|
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`), so no manual `setWebhook` call is needed — just make sure `BASE_URL` is set.
|
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.
|
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
|
## 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_as_bot` (send messages as an app)
|
||||||
- `im:message:send` (historical version)
|
- `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.
|
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
|
### Inbound: commands & buttons
|
||||||
|
|
||||||
@@ -230,7 +241,8 @@ To enable inbound:
|
|||||||
2. Subscribe to the events:
|
2. Subscribe to the events:
|
||||||
- `im.message.receive_v1` — receive `/gh` commands (requires the `im:message` scope).
|
- `im.message.receive_v1` — receive `/gh` commands (requires the `im:message` scope).
|
||||||
- `card.action.trigger` — receive button clicks on cards.
|
- `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
|
### Required permissions
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -30,7 +30,7 @@ Branch deletions via `git push --delete` arrive as push events with `deleted: tr
|
|||||||
|
|
||||||
## How do I point a group at its own webhook endpoint?
|
## 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?
|
## 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?
|
## 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).
|
||||||
+19
-14
@@ -125,15 +125,16 @@ 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:
|
Matches the branch involved in the event. What counts as "the branch" depends on the event type:
|
||||||
|
|
||||||
| Event | Branch extracted |
|
| Event | Branch extracted |
|
||||||
| --------------------------- | ------------------------------------------- |
|
| ---------------------------------- | ------------------------------------------------------------------------------------ |
|
||||||
| `push` | The branch that was pushed to |
|
| `push` | The branch that was pushed to |
|
||||||
| `pull_request` (and review) | The pull request's **head** (source) branch |
|
| `pull_request` (and review) | The pull request's **head** (source) branch |
|
||||||
| `create` / `delete` | The created/deleted branch or tag |
|
| `create` / `delete` | The created/deleted branch or tag |
|
||||||
| `workflow_run` | The `head_branch` the workflow ran on |
|
| `workflow_run` | The `head_branch` the workflow ran on |
|
||||||
| `workflow_job` | The `head_branch` the job 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 |
|
| `check_suite` | The `head_branch` of the check suite |
|
||||||
| `deployment` | The deployment ref (strips `refs/heads/`) |
|
| `deployment` / `deployment_status` | The deployment ref (`deployment.ref`, strips a leading `refs/heads/`) |
|
||||||
| `code_scanning_alert` | The branch the alert belongs to |
|
| `code_scanning_alert` | The alert's ref, without a leading `refs/heads/` (use `main`, not `refs/heads/main`) |
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -179,8 +180,9 @@ Fires when the payload contains `deploy` anywhere. Because the payload is lowerc
|
|||||||
|
|
||||||
Behavior details:
|
Behavior details:
|
||||||
|
|
||||||
- Patterns longer than 200 characters are **not** compiled as glob/regex and fall back to plain matching.
|
- Patterns longer than 200 characters cannot be compiled as glob/regex; such patterns are rejected when saved.
|
||||||
- A `//`-wrapped pattern that is not a valid regex matches **nothing** (the filter stays false) rather than erroring.
|
- 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.
|
- 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.
|
- 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 |
|
| `gt` / `gte` | Numeric greater-than / greater-or-equal |
|
||||||
| `lt` / `lte` | Numeric less-than / less-or-equal |
|
| `lt` / `lte` | Numeric less-than / less-or-equal |
|
||||||
| `in` | Value equals any of the listed patterns |
|
| `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
|
```json
|
||||||
{ "type": "field", "path": "pull_request.commits", "op": "gt", "match": "1" }
|
{ "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",
|
"id": "grouped",
|
||||||
"name": "Grouped",
|
"name": "Grouped",
|
||||||
|
"enabled": true,
|
||||||
|
"groupId": "eng",
|
||||||
|
"filters": [],
|
||||||
"ast": {
|
"ast": {
|
||||||
"all": [
|
"all": [
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "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.
|
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": [
|
"filters": [
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "type": "event", "match": "pull_request" },
|
||||||
{ "type": "actor", "match": "dependabot[bot]", "exclude": true },
|
{ "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
|
## Worked Example 2: Release-only channel
|
||||||
|
|
||||||
@@ -298,7 +303,7 @@ Forward only published releases from a specific repo:
|
|||||||
{ "type": "action", "match": "published" },
|
{ "type": "action", "match": "published" },
|
||||||
{ "type": "repo", "match": "myorg/backend" }
|
{ "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": "action", "match": "completed" },
|
||||||
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
||||||
],
|
],
|
||||||
"target": { "channelId": "333333333333333333" }
|
"targets": [{ "platform": "discord", "channelId": "333333333333333333" }]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Common Pitfalls
|
## 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\/.*/"`.
|
- **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)).
|
- **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.
|
- **`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.
|
- **`keyword` searches everything.** Because it scans the whole payload, a pattern like `"fix"` can match commit messages, issue titles, _and_ repository names. Be as specific as possible.
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ GITHUB_CLIENT_ID=your-client-id
|
|||||||
GITHUB_CLIENT_SECRET=your-client-secret
|
GITHUB_CLIENT_SECRET=your-client-secret
|
||||||
DISCORD_TOKEN=your-bot-token
|
DISCORD_TOKEN=your-bot-token
|
||||||
DISCORD_PUBLIC_KEY=your-public-key
|
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
|
BASE_URL=http://localhost:8787
|
||||||
```
|
```
|
||||||
|
|
||||||
::: tip
|
::: 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
|
::: warning
|
||||||
@@ -48,10 +48,11 @@ BASE_URL=http://localhost:8787
|
|||||||
### 2. Start Dev Server
|
### 2. Start Dev Server
|
||||||
|
|
||||||
```bash
|
```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
|
### 3. Verify
|
||||||
|
|
||||||
@@ -66,7 +67,7 @@ curl http://localhost:8787/health
|
|||||||
| ---------------------- | ------------------------------------------- |
|
| ---------------------- | ------------------------------------------- |
|
||||||
| `bun run dev` | Start Nuxt dev server (HMR) |
|
| `bun run dev` | Start Nuxt dev server (HMR) |
|
||||||
| `bun run build` | Production build (cloudflare_module preset) |
|
| `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 typecheck` | TypeScript type checking |
|
||||||
| `bun run lint` | ESLint |
|
| `bun run lint` | ESLint |
|
||||||
| `bun run lint:md` | Markdownlint |
|
| `bun run lint:md` | Markdownlint |
|
||||||
|
|||||||
+26
-11
@@ -1,6 +1,6 @@
|
|||||||
# Groups & Access Control
|
# 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
|
## Group Schema
|
||||||
|
|
||||||
@@ -21,18 +21,21 @@ Routes belong to groups. Groups scope admin access and can restrict which events
|
|||||||
```
|
```
|
||||||
|
|
||||||
| Field | Type | Required | Description |
|
| 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 |
|
| `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 |
|
| `name` | string | Yes | Human-readable group name |
|
||||||
| `members` | object[] | No | `{ login, role }` entries; role is `owner`, `admin`, or `viewer` |
|
| `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 |
|
| `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 |
|
| `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 |
|
| `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) |
|
| `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`) |
|
| `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 |
|
| `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` |
|
| `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 |
|
| `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
|
## Roles
|
||||||
|
|
||||||
@@ -46,16 +49,21 @@ Every group member has one of three roles. Super admins (`ADMIN_USER_IDS`) alway
|
|||||||
|
|
||||||
## Access Model
|
## 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.
|
- **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.
|
- **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.
|
- 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.
|
- 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
|
## 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
|
## Forge Source Label
|
||||||
|
|
||||||
@@ -79,8 +87,15 @@ The label is independent of `Group.emoji` and follows every message that group d
|
|||||||
|
|
||||||
## Invites
|
## 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
|
## 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.
|
With `ALLOW_SELF_SIGNUP=1`, a GitHub user who has no group access gets a personal group (`u-{userId}`, owned by them) on first login instead of a `403`. This is the entry point for a fully self-service SaaS install; disable it to keep the console invite-only.
|
||||||
|
|
||||||
|
Personal groups are **isolated** (groups named `u-<digits>` created before the flag existed count as isolated too, unless a super admin sets `isolated: false`): the operator's global `POST /webhook` endpoint never dispatches to them, so a self-service user cannot receive other tenants' events by adding a catch-all route. They receive events through their own [per-group webhook](./ingress) — or from a GitHub App installation they prove they administer (the install flow checks it with the user's own GitHub token).
|
||||||
+7
-5
@@ -8,17 +8,19 @@ Set `Group.lang` (e.g. `"zh"`) to choose the message language for every route in
|
|||||||
|
|
||||||
## Custom Overrides
|
## 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
|
```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
|
## 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.
|
||||||
+18
-9
@@ -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.
|
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.
|
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`)
|
## 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}`)
|
## 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.
|
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`)
|
- 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
|
- 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}:{groupId}:{id}`)
|
- 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 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
|
## 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
|
### 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:
|
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)
|
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
|
```bash
|
||||||
input="${timestamp}.${nonce}.${body}"
|
input="${timestamp}.${nonce}.${body}"
|
||||||
@@ -70,7 +75,7 @@ Payload schema:
|
|||||||
```
|
```
|
||||||
|
|
||||||
| Field | Type | Description |
|
| Field | Type | Description |
|
||||||
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------- |
|
| ------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `title` | string | Message title (falls back to "Custom message") |
|
| `title` | string | Message title (falls back to "Custom message") |
|
||||||
| `description` | string | Optional message body |
|
| `description` | string | Optional message body |
|
||||||
| `color` | string | Optional embed color: a word (`red`, `green`, `yellow`, `blue`, `purple`, `orange`, `cyan`, `gray`) or `#rrggbb` |
|
| `color` | string | Optional embed color: a word (`red`, `green`, `yellow`, `blue`, `purple`, `orange`, `cyan`, `gray`) or `#rrggbb` |
|
||||||
@@ -79,12 +84,16 @@ Payload schema:
|
|||||||
| `author` | object | Optional `{ name, iconUrl, url }` |
|
| `author` | object | Optional `{ name, iconUrl, url }` |
|
||||||
| `fields` | object[] | Optional embed fields `{ name, value, inline }` |
|
| `fields` | object[] | Optional embed fields `{ name, value, inline }` |
|
||||||
| `footer` | string | Optional footer override |
|
| `footer` | string | Optional footer override |
|
||||||
| `deliveryId` | string | Optional id for sender-side dedup (retries) |
|
| `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
|
## 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).
|
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).
|
To show the installing account's login on the choice page, set `GITHUB_APP_ID` and `GITHUB_PRIVATE_KEY` — see [Secrets](./configuration#secrets).
|
||||||
@@ -22,7 +22,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| **Cloudflare Worker** | HTTP ingress, signature verification, delivery dedup, event parsing, route matching, platform dispatch |
|
| **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) |
|
| **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 |
|
| **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
|
### Data Flow
|
||||||
@@ -40,7 +40,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
- **Runtime**: Cloudflare Workers
|
- **Runtime**: Cloudflare Workers
|
||||||
- **HTTP Framework**: Nuxt 4 / Nitro (H3)
|
- **HTTP Framework**: Nuxt 4 / Nitro (H3)
|
||||||
- **Discord delivery**: Discord REST API (interactions via an Ed25519-verified HTTPS Interactions Endpoint)
|
- **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
|
- **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)
|
- **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)
|
- **Auth**: Web Crypto API (HMAC-SHA256, Ed25519), octokit (GitHub API)
|
||||||
|
|||||||
+9
-3
@@ -5,7 +5,7 @@
|
|||||||
Every dispatch attempt is recorded in the D1 `send_logs` table and browsable in the console (**Logs** tab). Fields:
|
Every dispatch attempt is recorded in the D1 `send_logs` table and browsable in the console (**Logs** tab). Fields:
|
||||||
|
|
||||||
| Field | Meaning |
|
| Field | Meaning |
|
||||||
| ------------ | ---------------------------------------------------------------- |
|
| ------------ | ------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `routeId` | Route that matched |
|
| `routeId` | Route that matched |
|
||||||
| `groupId` | Route's group |
|
| `groupId` | Route's group |
|
||||||
| `event` | Event type (e.g. `push`, `pull_request`, `custom`) |
|
| `event` | Event type (e.g. `push`, `pull_request`, `custom`) |
|
||||||
@@ -15,7 +15,7 @@ Every dispatch attempt is recorded in the D1 `send_logs` table and browsable in
|
|||||||
| `ok` | Whether the send succeeded |
|
| `ok` | Whether the send succeeded |
|
||||||
| `status` | HTTP status from the platform API (when applicable) |
|
| `status` | HTTP status from the platform API (when applicable) |
|
||||||
| `error` | Error message (when failed) |
|
| `error` | Error message (when failed) |
|
||||||
| `errorCode` | Stable error code (e.g. `NO_TARGET`, `NO_TOKEN`, `RATE_LIMITED`) |
|
| `errorCode` | Stable error code (e.g. `NO_TARGET`, `NO_TOKEN`, `RATE_LIMITED`, `FORMAT`, `PAYLOAD_MISSING`, `TELEGRAM_UNCERTAIN`) |
|
||||||
| `attempts` | Send attempts including retries |
|
| `attempts` | Send attempts including retries |
|
||||||
| `durationMs` | Time spent sending |
|
| `durationMs` | Time spent sending |
|
||||||
| `deliveryId` | Webhook delivery id (when provided) |
|
| `deliveryId` | Webhook delivery id (when provided) |
|
||||||
@@ -24,7 +24,13 @@ Every dispatch attempt is recorded in the D1 `send_logs` table and browsable in
|
|||||||
| `action` | Event action (when present) |
|
| `action` | Event action (when present) |
|
||||||
| `detail` | Extra JSON details (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`)
|
## Audit Log (`audit_logs`)
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ The repo comes from `payload.repository.full_name` (falling back to a generic "r
|
|||||||
|
|
||||||
Only the repo head is hyperlinked — never the whole title:
|
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.
|
- **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.
|
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
|
## 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
|
## Workflow Jobs
|
||||||
|
|
||||||
|
|||||||
+16
-6
@@ -1,8 +1,8 @@
|
|||||||
# Routes & Targets
|
# 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
|
## 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 |
|
| Field | Type | Required | Description |
|
||||||
| ---------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
|
| ---------------- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||||
| `groupId` | string | Yes | Id of the [group](./groups) this route belongs to |
|
| `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 |
|
| `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 |
|
| `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 |
|
| `ast` | object | No | Boolean filter tree (`{all:[...]}` / `{any:[...]}` / `{not:{...}}`); takes precedence over `filters` when present |
|
||||||
|
|
||||||
## Route Order
|
## 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.
|
**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
|
## 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.
|
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": [
|
"filters": [
|
||||||
{ "type": "repo", "match": "myorg/backend" },
|
{ "type": "repo", "match": "myorg/backend" },
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "type": "event", "match": "pull_request" },
|
||||||
{ "type": "actor", "match": "[bot]", "exclude": true }
|
{ "type": "actor", "match": "*[bot]", "exclude": true }
|
||||||
],
|
],
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"platform": "telegram",
|
"platform": "telegram",
|
||||||
"chatId": "-1001234567890",
|
"chatId": "-1001234567890",
|
||||||
"topicId": "9876543210"
|
"topicId": "42"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+43
-27
@@ -5,57 +5,73 @@
|
|||||||
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)).
|
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 |
|
| Key Pattern | Value | TTL |
|
||||||
| ------------------------------------------ | ----------------------------------------------------------------------------- | ------------------ |
|
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------ |
|
||||||
| `config:routes` | Route config cache (D1 `d1_routes` is authoritative) | 1 hour |
|
| `config:routes` / `config:groups` | Legacy (pre-D1) configuration, read once to seed empty D1 tables | Permanent |
|
||||||
| `config:groups` | Group config cache (D1 `d1_groups` is authoritative) | 1 hour |
|
| `config:d1-seeded` | Marks that D1 was seeded (an emptied D1 is never re-seeded) | Permanent |
|
||||||
| `session:{id}` | Admin session `{ userId, login }` | 7 days |
|
| `session:{id}` | Admin session `{ userId, login, loginTrusted }` | 1 day |
|
||||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, refreshToken? }` | 0.9 × token expiry |
|
| `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 | 0.9 × token expiry |
|
| `token-reverse:{sha256}` | User id for reverse lookup by token | 9 hours |
|
||||||
| `state:{hex}` | `{ redirectTo, expiresAt, discordUserId?, telegramUserId?, telegramChatId? }` | 600 seconds |
|
| `state:{hex}` | `{ redirectTo, expiresAt, link? }` (`link`: the chat account a bot `/gh login` binds) | 600 seconds |
|
||||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note? }` | 7 days |
|
| `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: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 |
|
| `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 |
|
||||||
| `delivery-state:{provider}:{groupId}:{id}` | Queue delivery state fallback (D1 `delivery_state` is primary) | 1 hour |
|
| `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 |
|
||||||
| `queue:payload:{provider}:{groupId}:{id}` | Oversized webhook payload parked for the queue consumer (R2 is primary) | 1 hour |
|
| `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 |
|
||||||
| `nonce:{nonce}` | Custom-webhook replay protection nonce (single use) | 600 seconds |
|
| `delivery-state:{provider}:{scope}:{id}` | Queue delivery state fallback (D1 `delivery_state` is primary) | 7 days |
|
||||||
| `tenant:{groupId}` | Per-group webhook secret (64-char hex, generated from the console) | Permanent |
|
| `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 |
|
||||||
| `msg:{routeId}:{key}:{target}` | Message id tracking fallback (D1 `message_tracking` is primary) | 1 day |
|
| `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 |
|
||||||
| `cmd:guild:{id}` | Guild id whose commands were registered (dedup) | 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 |
|
||||||
| `cmd:registered:global` | Global command registration marker (dedup) | 1 day |
|
| `msg:{chain}:{platform}:{target}` | Message tracking fallback (D1 `message_tracking` is primary) | 30 days |
|
||||||
| `config:discord-app-id` | Cached Discord application id | Permanent |
|
| `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 |
|
| `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
|
## D1 Storage Layout
|
||||||
|
|
||||||
The D1 database (`DB` binding, database `webhooker`) holds the source of truth for configuration, delivery logs and high-frequency ephemeral state:
|
The D1 database (`DB` binding, database `webhooker`) holds the source of truth for configuration, delivery logs and high-frequency ephemeral state:
|
||||||
|
|
||||||
| Table | Purpose |
|
| Table | Purpose |
|
||||||
| ------------------ | ---------------------------------------------------------------------------------------------- |
|
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `d1_groups` | Groups (authoritative config, seeded from legacy KV `config:groups`) |
|
| `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`) |
|
| `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) |
|
| `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) |
|
| `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) |
|
| `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`) |
|
| `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 id tracking for in-place updates (`event_id` + `target_id` → `message_id`) |
|
| `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 |
|
| `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 |
|
| `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 Storage Layout
|
||||||
|
|
||||||
R2 (`PAYLOAD` binding, bucket `webhooker-payloads`) stores oversized webhook payloads that are too large for a queue message or KV:
|
R2 (`PAYLOAD` binding, bucket `webhooker-payloads`) stores oversized webhook payloads that are too large for a queue message or KV:
|
||||||
|
|
||||||
| Object Pattern | Purpose | Retention |
|
| Object Pattern | Purpose | Retention |
|
||||||
| --------------------------------- | ----------------------------------------------- | ---------------------- |
|
| --------------------------------- | ----------------------------------------------- | --------------------------------------------------- |
|
||||||
| `webhooks/YYYY/MM/DD/<uuid>.json` | Oversized payload parked for the queue consumer | deleted after dispatch |
|
| `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
|
## Storage Decisions
|
||||||
|
|
||||||
- **D1 is authoritative** for config and delivery metadata; KV holds only caches and short-lived state.
|
- **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).
|
- 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.
|
- R2's free tier (10 GB-month storage, 1M Class A ops/month) comfortably absorbs payload parking without touching the KV write quota.
|
||||||
+4
-4
@@ -3,10 +3,10 @@
|
|||||||
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`.
|
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 |
|
| Task | Purpose |
|
||||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------- |
|
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `discord-sync` | Registers the Discord slash/context-menu commands: per-guild (instant) and globally (24h dedup, ~1h propagation) |
|
| `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` as `secret_token` when set) |
|
| `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) |
|
| `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 |
|
| `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`).
|
There is nothing to configure beyond the secrets the tasks use (`DISCORD_TOKEN`, `DISCORD_APPLICATION_ID`, `TELEGRAM_TOKEN`, `BASE_URL`, `AUDIT_RETENTION_DAYS`).
|
||||||
@@ -40,7 +40,7 @@ POST /api/comment
|
|||||||
| `issueNumber` | number | 是 | 议题或 PR 编号 |
|
| `issueNumber` | number | 是 | 议题或 PR 编号 |
|
||||||
| `body` | string | 是 | 评论内容(支持 Markdown) |
|
| `body` | string | 是 | 评论内容(支持 Markdown) |
|
||||||
|
|
||||||
**响应:** `200` 与 GitHub API 响应。
|
**响应:** `200 { "ok": true }`。
|
||||||
|
|
||||||
### 合并拉取请求
|
### 合并拉取请求
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ POST /api/merge
|
|||||||
| `pullNumber` | number | 是 | 拉取请求编号 |
|
| `pullNumber` | number | 是 | 拉取请求编号 |
|
||||||
| `method` | string | 否 | `merge`、`squash` 或 `rebase`(默认:`squash`) |
|
| `method` | string | 否 | `merge`、`squash` 或 `rebase`(默认:`squash`) |
|
||||||
|
|
||||||
**响应:** `200` 与 GitHub 合并响应。
|
**响应:** `200 { "ok": true }`。
|
||||||
|
|
||||||
### 关闭拉取请求
|
### 关闭拉取请求
|
||||||
|
|
||||||
@@ -94,7 +94,7 @@ POST /api/close
|
|||||||
| `repo` | string | 是 | 仓库名称 |
|
| `repo` | string | 是 | 仓库名称 |
|
||||||
| `pullNumber` | number | 是 | 拉取请求编号 |
|
| `pullNumber` | number | 是 | 拉取请求编号 |
|
||||||
|
|
||||||
**响应:** `200` 与 GitHub 更新响应。
|
**响应:** `200 { "ok": true }`。
|
||||||
|
|
||||||
### 添加反应
|
### 添加反应
|
||||||
|
|
||||||
@@ -102,7 +102,7 @@ POST /api/close
|
|||||||
POST /api/react
|
POST /api/react
|
||||||
```
|
```
|
||||||
|
|
||||||
为议题或评论添加表情反应。
|
为议题或拉取请求添加表情反应(不支持评论)。
|
||||||
|
|
||||||
**请求体:**
|
**请求体:**
|
||||||
|
|
||||||
@@ -116,17 +116,17 @@ POST /api/react
|
|||||||
```
|
```
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| 字段 | 类型 | 必需 | 说明 |
|
||||||
| ------------- | ------ | ---- | ------------------- |
|
| ------------- | ------ | ---- | ------------------ |
|
||||||
| `owner` | string | 是 | 仓库所有者 |
|
| `owner` | string | 是 | 仓库所有者 |
|
||||||
| `repo` | string | 是 | 仓库名称 |
|
| `repo` | string | 是 | 仓库名称 |
|
||||||
| `issueNumber` | number | 是 | 议题、PR 或评论编号 |
|
| `issueNumber` | number | 是 | 议题或 PR 编号 |
|
||||||
| `reaction` | string | 是 | 反应类型(见下方) |
|
| `reaction` | string | 是 | 反应类型(见下方) |
|
||||||
|
|
||||||
**反应类型:**
|
**反应类型:**
|
||||||
|
|
||||||
`+1`、`-1`、`laugh`、`confused`、`heart`、`hooray`、`rocket`、`eyes`
|
`+1`、`-1`、`laugh`、`confused`、`heart`、`hooray`、`rocket`、`eyes`
|
||||||
|
|
||||||
**响应:** `200` 与 GitHub 反应响应。
|
**响应:** `200 { "ok": true }`。
|
||||||
|
|
||||||
## 错误响应
|
## 错误响应
|
||||||
|
|
||||||
|
|||||||
+28
-18
@@ -1,13 +1,13 @@
|
|||||||
# Admin API
|
# 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`)。
|
控制台本身在 `/admin` 提供;其标签页可通过 URL 路径直达(`/admin/groups`、`/admin/logs`、`/admin/audit`)。
|
||||||
|
|
||||||
## 端点
|
## 端点
|
||||||
|
|
||||||
| 端点 | 说明 |
|
| 端点 | 说明 |
|
||||||
| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
| `GET /admin` | 配置控制台页面 |
|
| `GET /admin` | 配置控制台页面 |
|
||||||
| `GET /admin/login` | 开始管理员登录(GitHub OAuth) |
|
| `GET /admin/login` | 开始管理员登录(GitHub OAuth) |
|
||||||
| `GET /admin/logout` | 退出登录并销毁会话 |
|
| `GET /admin/logout` | 退出登录并销毁会话 |
|
||||||
@@ -15,32 +15,42 @@
|
|||||||
| `GET /admin/api/me` | 当前会话、权限范围、分组与角色 |
|
| `GET /admin/api/me` | 当前会话、权限范围、分组与角色 |
|
||||||
| `GET /admin/api/routes` | 列出路由(按权限过滤) |
|
| `GET /admin/api/routes` | 列出路由(按权限过滤) |
|
||||||
| `PUT /admin/api/routes` | 替换路由(按分组 owner/admin) |
|
| `PUT /admin/api/routes` | 替换路由(按分组 owner/admin) |
|
||||||
| `GET /admin/api/groups` | 列出分组 + 当前用户在各分组的角色 |
|
| `GET /admin/api/groups` | 列出分组(各带 `revision`)+ 当前用户在各分组的角色,以及整个列表的 `revision` |
|
||||||
| `PUT /admin/api/groups` | 替换分组(超级管理员全部;owner 仅自己的) |
|
| `PUT /admin/api/groups` | 批量写入(旧接口):超级管理员替换全部分组,owner 修改/删除自己的;只写入有变化的分组 |
|
||||||
| `GET /admin/api/groups/:id/routes` | 列出某分组的路由 |
|
| `POST /admin/api/groups` | 创建单个分组(超级管理员)——请求体 `{ group }`;id 已存在或近期用过时返回 `409` |
|
||||||
| `PUT /admin/api/groups/:id/routes` | 替换某分组的路由(owner/admin) |
|
| `PUT /admin/api/groups/:id` | 更新单个分组(owner)——请求体 `{ group }`;`revision` 过期时返回 `409` |
|
||||||
| `GET /admin/api/groups/:id/fragments` | 列出某分组的命名过滤器片段 |
|
| `DELETE /admin/api/groups/:id` | 删除单个分组及其路由与片段(owner)——查询参数带上确认时的 `revision`、`routesRevision` 与 `version`;之后有任何变化时返回 `409` |
|
||||||
| `PUT /admin/api/groups/:id/fragments` | 替换某分组的命名过滤器片段(owner/admin) |
|
| `GET /admin/api/groups/:id/routes` | 列出某分组的路由,附带列表的 `revision`、分组 `version` 与 `unreadable` |
|
||||||
| `PUT /admin/api/groups/:id/rename` | 重命名分组(owner);路由、webhook secret 与邀请自动跟随 |
|
| `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) |
|
| `GET /admin/api/groups/:id/invites` | 列出待处理的邀请(owner) |
|
||||||
| `POST /admin/api/groups/:id/invites` | 创建邀请链接(owner) |
|
| `POST /admin/api/groups/:id/invites` | 创建邀请链接(owner)——请求体 `{ role, note? }`(`role` 为 `admin` 或 `viewer`) |
|
||||||
| `DELETE /admin/api/invites/:token` | 撤销邀请(owner) |
|
| `DELETE /admin/api/invites/:token` | 撤销邀请(owner) |
|
||||||
| `GET /admin/api/groups/:id/webhook` | 分组 webhook 端点信息(owner) |
|
| `GET /admin/api/groups/:id/webhook` | 分组 webhook 端点信息(owner) |
|
||||||
| `POST /admin/api/groups/:id/webhook/regenerate` | 生成/重新生成分组 webhook secret(owner) |
|
| `POST /admin/api/groups/:id/webhook/regenerate` | 生成/重新生成分组 webhook secret(owner) |
|
||||||
| `DELETE /admin/api/groups/:id/webhook` | 停用分组 webhook 入口(owner) |
|
| `DELETE /admin/api/groups/:id/webhook` | 停用分组 webhook 入口(owner) |
|
||||||
| `GET /admin/api/logs` | 发送日志(按可访问的路由过滤) |
|
| `GET /admin/api/logs` | 可访问分组的发送日志(在 SQL 中先过滤再取 limit) |
|
||||||
| `GET /admin/api/logs/:id` | 单条发送日志(按权限过滤) |
|
| `GET /admin/api/logs/:id` | 单条发送日志(按权限过滤) |
|
||||||
| `GET /admin/api/audit` | 审计日志(按可访问的分组过滤) |
|
| `GET /admin/api/audit` | 可访问分组的审计日志(在 SQL 中先过滤再取 limit) |
|
||||||
| `GET /admin/api/metrics` | 投递统计(总计、失败率、按平台/事件/状态、最近失败);可选 `?groupId=` 按分组过滤;非超管按可访问分组过滤最近失败 |
|
| `GET /admin/api/metrics` | 投递统计(总计、失败率、按平台/事件/状态、最近失败);可选 `?groupId=` 按分组过滤;所有汇总都只统计可访问的分组 |
|
||||||
| `GET /admin/api/delivery/:deliveryId` | 单次投递的全部发送日志(按分组过滤) |
|
| `GET /admin/api/delivery/:deliveryId` | 单次投递中属于可访问分组的发送记录;可选 `?groupId=`(两个分组的发送方可能使用相同的投递 id) |
|
||||||
| `POST /admin/api/test-match` | 无状态过滤器试匹配——将过滤器节点对粘贴的 JSON 载荷求值(不存储任何事件) |
|
| `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/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` — 校验分组 id、成员角色(至少一个 `owner`)、`providers`(`github` / `gitea`)与 `installationId`。
|
- `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 }`,不持久化任何内容。
|
- `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 }`。
|
- `GET/PUT /admin/api/groups/:id/fragments` — 命名过滤器片段(`{ id, groupId, name, node }`)存储于 D1 `d1_fragments`;编辑器在插入时将片段的 `node` 内联进路由的 `ast`(匹配器从不解析片段引用)。`PUT` 全量替换该分组的片段(最多 200 个)并返回 `200 { ok, count }`。
|
||||||
- 上限:每个实例最多 200 条路由与 100 个分组。
|
- 上限:单次保存最多 200 条路由、每个分组最多 200 个片段,批量保存分组单次最多 100 个。
|
||||||
|
|
||||||
模式:见[路由与目标](../guide/routes)、[分组与访问控制](../guide/groups)。
|
模式:见[路由与目标](../guide/routes)、[分组与访问控制](../guide/groups)。
|
||||||
+14
-5
@@ -42,12 +42,21 @@ GitHub 授权后重定向到此地址。将 code 交换为访问令牌并存储
|
|||||||
| `code` | 授权码 |
|
| `code` | 授权码 |
|
||||||
| `state` | CSRF 保护的状态参数 |
|
| `state` | CSRF 保护的状态参数 |
|
||||||
|
|
||||||
|
在浏览器中发起(`GET /auth/github`)的登录,回调时必须带回发起时设置的 `wh_oauth_state` Cookie,否则返回 `400 Invalid or expired state`。
|
||||||
|
|
||||||
**响应:**
|
**响应:**
|
||||||
|
|
||||||
- **浏览器流程**(`Accept: text/html`):设置管理员会话 Cookie,然后重定向到 `redirect` 目标;无管理权限的用户被重定向到 `/admin?error=forbidden`。
|
- **浏览器流程**(`Accept: text/html`):设置管理员会话 Cookie,然后重定向到 `redirect` 目标;无管理权限的用户被重定向到 `/admin?error=forbidden`。
|
||||||
- **JSON 流程**:返回 `{ "userId": "...", "login": "...", "redirectTo": "..." }`。
|
- **JSON 流程**:返回 `{ "userId": "...", "login": "...", "redirectTo": "..." }`。
|
||||||
- **Discord 绑定流程**(以未决的 `discordUserId` 启动时):将 Discord 用户绑定到此 GitHub 账号,返回 `{ "ok": true, "discordUserId": "...", "login": "..." }`——浏览器中则显示成功页面。
|
- **机器人账号绑定**(由 Discord、Telegram 或飞书的 `/gh login` 发起):此时还不会绑定。回调返回一个同时列出 GitHub 账号与聊天账号的 HTML 确认页;只有 GitHub 用户在该页确认后才写入绑定。
|
||||||
- **Telegram 绑定流程**(以未决的 `telegramUserId` 启动时):将 Telegram 用户绑定到此 GitHub 账号,返回 `{ "ok": true, "telegramUserId": "...", "login": "..." }`,并向未决的 `telegramChatId` 发送确认消息。
|
|
||||||
|
### 确认机器人账号绑定
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /auth/github/link
|
||||||
|
```
|
||||||
|
|
||||||
|
由确认页提交(表单字段 `nonce`,10 分钟内有效、只能使用一次)。把聊天账号绑定到 GitHub 账号并返回 HTML 结果页;未知、过期或已使用的 `nonce` 返回 `400`("链接已失效")。
|
||||||
|
|
||||||
### 撤销 Token
|
### 撤销 Token
|
||||||
|
|
||||||
@@ -55,7 +64,7 @@ GitHub 授权后重定向到此地址。将 code 交换为访问令牌并存储
|
|||||||
DELETE /auth/token/:userId
|
DELETE /auth/token/:userId
|
||||||
```
|
```
|
||||||
|
|
||||||
删除用户存储的 OAuth Token。
|
删除用户存储的 OAuth Token(本人的,或超级管理员删除任意用户的)。撤销会记录在 D1 中,即使 KV 尚未同步,Token 也会在所有节点立即失效。
|
||||||
|
|
||||||
**响应:**
|
**响应:**
|
||||||
|
|
||||||
@@ -74,11 +83,11 @@ Token 以键模式 `token:{userId}` 存储在 KV 中:
|
|||||||
"userId": "12345",
|
"userId": "12345",
|
||||||
"accessToken": "gho_...",
|
"accessToken": "gho_...",
|
||||||
"expiresAt": 1735689600000,
|
"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
|
## 使用 Token
|
||||||
|
|
||||||
|
|||||||
+13
-7
@@ -17,9 +17,11 @@ https://your-worker.workers.dev
|
|||||||
| `POST` | `/webhook/:groupId` | 分组 secret | 分组级 webhook 入口(只触发该分组的路由) |
|
| `POST` | `/webhook/:groupId` | 分组 secret | 分组级 webhook 入口(只触发该分组的路由) |
|
||||||
| `POST` | `/discord/interactions` | Ed25519 签名 | Discord 交互(斜杠命令、按钮、modal) |
|
| `POST` | `/discord/interactions` | Ed25519 签名 | Discord 交互(斜杠命令、按钮、modal) |
|
||||||
| `POST` | `/telegram/webhook` | Secret token | Telegram 更新(bot `/gh` 命令) |
|
| `POST` | `/telegram/webhook` | Secret token | Telegram 更新(bot `/gh` 命令) |
|
||||||
|
| `POST` | `/feishu/webhook` | 飞书签名 | 飞书事件(bot `/gh` 命令、卡片按钮) |
|
||||||
| `GET` | `/api/richheader` | 无 | 用于 Telegram 头像链接预览卡片的 Open Graph 页面 |
|
| `GET` | `/api/richheader` | 无 | 用于 Telegram 头像链接预览卡片的 Open Graph 页面 |
|
||||||
| `GET` | `/auth/github` | 无 | 启动 GitHub OAuth 流程 |
|
| `GET` | `/auth/github` | 无 | 启动 GitHub OAuth 流程 |
|
||||||
| `GET` | `/auth/github/callback` | 无 | OAuth 回调 |
|
| `GET` | `/auth/github/callback` | 无 | OAuth 回调 |
|
||||||
|
| `POST` | `/auth/github/link` | 绑定 nonce | 确认机器人账号绑定(由确认页提交) |
|
||||||
| `GET` | `/auth/github/install` | 管理员会话 | 安装后选择页:将安装绑定到某个分组 |
|
| `GET` | `/auth/github/install` | 管理员会话 | 安装后选择页:将安装绑定到某个分组 |
|
||||||
| `POST` | `/auth/github/install/bind` | 管理员会话 | 执行选定的安装绑定 |
|
| `POST` | `/auth/github/install/bind` | 管理员会话 | 执行选定的安装绑定 |
|
||||||
| `DELETE` | `/auth/token/:userId` | 管理员会话 | 撤销用户 Token |
|
| `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
|
```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"}` | 签名验证失败 |
|
| `401` | `{"error": "Invalid signature"}` | 签名验证失败 |
|
||||||
| `400` | `{"error": "Invalid event"}` | 缺少事件头或格式错误的请求体 |
|
| `400` | `{"error": "Invalid event"}` | 缺少事件头或格式错误的请求体 |
|
||||||
| `413` | `{"error": "Request too large"}` | 请求体超过 1MB 限制 |
|
| `413` | `{"error": "Request too large"}` | 请求体超过 1MB 限制 |
|
||||||
|
| `503` | `{"error": …}` | 尚未接受——队列拒收、目标暂时失败(内联分发)、同一投递仍在处理,或存储故障;发送方应重投 |
|
||||||
|
|
||||||
### 分组级 Webhook(`POST /webhook/:groupId`)
|
### 分组级 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
|
### 自定义 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 安装事件
|
### GitHub App 安装事件
|
||||||
|
|
||||||
@@ -109,7 +115,7 @@ POST /webhook
|
|||||||
|
|
||||||
## 错误格式
|
## 错误格式
|
||||||
|
|
||||||
所有错误响应都遵循以下格式:
|
webhook、管理、OAuth 与 Actions 端点的错误响应遵循以下格式;机器人回调(`/discord/interactions`、`/telegram/webhook`、`/feishu/webhook`)的错误响应为纯文本:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -25,22 +25,24 @@ app/ # Vue 3 UI(Nuxt app 目录)
|
|||||||
server/ # Nitro 服务器(H3 处理器位于 server/routes/)
|
server/ # Nitro 服务器(H3 处理器位于 server/routes/)
|
||||||
├── routes/ # /health、/webhook[/:groupId]、/discord/interactions、/telegram/webhook、
|
├── routes/ # /health、/webhook[/:groupId]、/discord/interactions、/telegram/webhook、
|
||||||
│ # /auth/github*、/admin/{login,logout,invite,api/**}、/api/{comment,merge,close,react,richheader}
|
│ # /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 错误处理器
|
├── error-handler.ts # JSON 错误处理器
|
||||||
└── lib/
|
└── lib/
|
||||||
├── types.ts # Env、Config、Route、Filter、Group、WebhookEvent、NeutralMessage
|
├── types.ts # Env、Config、Route、Filter、Group、WebhookEvent、NeutralMessage
|
||||||
├── config.ts # 从 KV 加载路由(未设置时返回 []),从 env 构建 Config
|
├── config.ts # 绑定 D1 配置存储,读取路由/分组(最新或缓存),从 env 构建 Config
|
||||||
├── core/
|
├── core/
|
||||||
│ └── dispatch.ts # 平台中立分发:匹配路由 → formatEvent → getDriver().send/edit
|
│ └── dispatch.ts # 平台中立分发:匹配路由 → formatEvent → getDriver().send/edit
|
||||||
├── events/ # 与提供方无关的路由匹配
|
├── events/ # 与提供方无关的路由匹配
|
||||||
│ └── match.ts # matchRoute、eventOwners、extractBranch、关键词过滤
|
│ ├── match.ts # matchRoute、eventOwners
|
||||||
|
│ └── filter-ast.ts # 过滤器求值(扁平过滤器 + all/any/not AST)、extractBranch、关键词搜索、RE2 模式
|
||||||
├── providers/ # Forge webhook 提供方(验证 + 解析/归一化)
|
├── providers/ # Forge webhook 提供方(验证 + 解析/归一化)
|
||||||
│ ├── types.ts # Provider 接口(matches/verify/parse)
|
│ ├── types.ts # Provider 接口(matches/verify/parse)
|
||||||
│ ├── index.ts # detectProvider() 注册表(github、gitea、custom)
|
│ ├── index.ts # detectProvider() 注册表(github、gitea、custom)
|
||||||
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
│ ├── github/ # X-GitHub-Event + X-Hub-Signature-256
|
||||||
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature(归一化载荷)
|
│ └── gitea/ # X-Gitea-Event + X-Gitea-Signature(归一化载荷)
|
||||||
├── formatters/ # 平台中立格式化器(产出 NeutralMessage)
|
├── 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
|
│ ├── colors.ts # GITHUB_COLORS + WORKFLOW_CONCLUSION_EMOJI
|
||||||
│ ├── helpers.ts # emojiPrefix、T、buildMessage、commitLink/branchLink/tagLink
|
│ ├── helpers.ts # emojiPrefix、T、buildMessage、commitLink/branchLink/tagLink
|
||||||
│ └── *.ts # push、pull-request、issues、comments、workflow、release、create、repo、
|
│ └── *.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
|
│ # discussion、repository、security、generic、ping、custom
|
||||||
├── drivers/ # 平台驱动(可插拔推送目标)
|
├── drivers/ # 平台驱动(可插拔推送目标)
|
||||||
│ ├── types.ts # PlatformDriver 接口 + SendResult(send + edit)
|
│ ├── types.ts # PlatformDriver 接口 + SendResult(send + edit)
|
||||||
│ ├── index.ts # getDriver() 注册表(discord + telegram)
|
│ ├── index.ts # getDriver() 注册表(discord + telegram + feishu)
|
||||||
│ ├── discord/ # index.ts (驱动)、render.ts (NeutralMessage → embed)、
|
│ ├── discord/ # index.ts (驱动)、render.ts (NeutralMessage → embed)、
|
||||||
│ │ # rest.ts、interactions.ts、commands.ts
|
│ │ # rest.ts、interactions.ts、commands.ts
|
||||||
│ └── telegram/ # index.ts (驱动)、render.ts (NeutralMessage → Telegram HTML)、
|
│ └── 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`(如果需要新颜色)
|
1. 将事件类型添加到 `server/lib/formatters/colors.ts` 中的 `GITHUB_COLORS`(如果需要新颜色)
|
||||||
2. 将操作标签添加到 `server/lib/lib/locales/en.ts` 与 `server/lib/lib/locales/zh.ts` 的翻译字典(如果有新操作)
|
2. 将操作标签添加到 `server/lib/lib/locales/en.ts` 与 `server/lib/lib/locales/zh.ts` 的翻译字典(如果有新操作)
|
||||||
3. 在 `server/lib/formatters/` 中创建 `formatEventType` 函数
|
3. 在 `server/lib/formatters/` 中创建 `formatEventType` 函数
|
||||||
4. 将 case 添加到 `server/lib/formatters/index.ts` 中的 `formatEvent` switch 语句
|
4. 在 `server/lib/formatters/registry.ts` 的 `eventFormatters` 中注册(`{ events: ["your_event"], format: (c) => … }`)
|
||||||
5. 如果事件包含分支信息,更新 `server/lib/events/match.ts` 中的 `extractBranch`
|
5. 如果事件包含分支信息,更新 `server/lib/events/filter-ast.ts` 中的 `extractBranch`
|
||||||
6. 将事件添加到 `docs/events/supported.md` 与 `docs/zh/events/supported.md` 文档中
|
6. 将事件添加到 `docs/events/supported.md` 与 `docs/zh/events/supported.md` 文档中
|
||||||
7. 将事件添加到 README(`README.md` 与 `README.zh.md`)的事件表与 GitHub App 事件订阅列表中
|
7. 将事件添加到 README(`README.md` 与 `README.zh.md`)的事件表与 GitHub App 事件订阅列表中
|
||||||
8. 在 GitHub App 设置中订阅该事件
|
8. 在 GitHub App 设置中订阅该事件
|
||||||
|
|||||||
@@ -42,7 +42,8 @@ WebHooker 支持 28 种 GitHub webhook 事件类型,每种都有专用的格
|
|||||||
|
|
||||||
| 颜色 | 事件 |
|
| 颜色 | 事件 |
|
||||||
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| 绿色 (`#2da44e`) | push、PR 打开/可审查、issue 打开、工作流成功、发布已发布、检查成功、审查已批准、部署成功、成员添加、里程碑关闭、讨论已回答 |
|
| 绿色 (`#2da44e`) | PR 打开/可审查、issue 打开、工作流成功、发布已发布、检查成功、审查已批准、部署成功、成员添加、里程碑关闭、讨论已回答 |
|
||||||
|
| 绿色 (`#2ea44f`) | push |
|
||||||
| 红色 (`#f85149`) | PR 关闭、issue 关闭、工作流失败、发布已删除、delete、检查失败、审查请求修改、部署失败、成员移除、代码扫描/Dependabot 严重与高危 |
|
| 红色 (`#f85149`) | PR 关闭、issue 关闭、工作流失败、发布已删除、delete、检查失败、审查请求修改、部署失败、成员移除、代码扫描/Dependabot 严重与高危 |
|
||||||
| 紫色 (`#8957e5`) | PR 合并、label、discussion |
|
| 紫色 (`#8957e5`) | PR 合并、label、discussion |
|
||||||
| 蓝色 (`#1f6feb`) | PR(其他操作)、issue 重新打开、fork、里程碑打开 |
|
| 蓝色 (`#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** 仓库权限。
|
`workflow_run` 消息还会附带带颜色的 **Jobs** 明细。由于 webhook 载荷本身不含作业列表(只有 `jobs_url`),Worker 会从 GitHub API 拉取——配置了 `GITHUB_APP_ID` / `GITHUB_PRIVATE_KEY` 时用 GitHub App 安装令牌鉴权,否则匿名请求(公开仓库)。因此 App 需要 **Actions: read** 仓库权限。
|
||||||
|
|
||||||
@@ -69,10 +70,10 @@ WebHooker 支持 28 种 GitHub webhook 事件类型,每种都有专用的格
|
|||||||
实操指南见[过滤器教程](../guide/filters),包含完整示例。
|
实操指南见[过滤器教程](../guide/filters),包含完整示例。
|
||||||
|
|
||||||
| 过滤器 | 适用事件 |
|
| 过滤器 | 适用事件 |
|
||||||
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `event` | 所有事件 |
|
| `event` | 所有事件 |
|
||||||
| `repo` | 所有事件 |
|
| `repo` | 所有事件 |
|
||||||
| `actor` | 所有事件 |
|
| `actor` | 所有事件 |
|
||||||
| `action` | 载荷中包含 `action` 字段的事件 |
|
| `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 |
|
| `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` | 所有事件(搜索完整载荷正文) |
|
| `keyword` | 所有事件(搜索完整载荷正文) |
|
||||||
@@ -1,23 +1,27 @@
|
|||||||
# 机器人命令
|
# 机器人命令
|
||||||
|
|
||||||
[绑定你的 GitHub 账号](#绑定账号)后,即可在 Discord 和 Telegram 上**以本人身份**操作 GitHub——评论使用你自己的 OAuth token 发布,权限由 GitHub 强制校验。若 GitHub 拒绝操作(例如编辑他人的评论),机器人会明确告知。
|
[绑定你的 GitHub 账号](#绑定账号)后,即可在 Discord、Telegram 和飞书上**以本人身份**操作 GitHub——评论使用你自己的 OAuth token 发布,权限由 GitHub 强制校验。若 GitHub 拒绝操作(例如编辑他人的评论),机器人会明确告知。
|
||||||
|
|
||||||
## 绑定账号
|
## 绑定账号
|
||||||
|
|
||||||
使用任何命令前,需先绑定一次 GitHub 账号:
|
使用任何命令前,需先绑定 GitHub 账号。授权有效期为 10 小时,过期后请重新执行 `/gh login`:
|
||||||
|
|
||||||
| 平台 | 命令 | 效果 |
|
| 平台 | 命令 | 效果 |
|
||||||
| -------- | ---------------------------- | --------------------------------------------------- |
|
| -------- | ---------------------------- | --------------------------------------------------- |
|
||||||
| Discord | `/gh login` | 返回一条仅你可见的 OAuth 链接,用于授权 GitHub 账号 |
|
| Discord | `/gh login` | 返回一条仅你可见的 OAuth 链接,用于授权 GitHub 账号 |
|
||||||
| Discord | `/gh logout` | 解除绑定 |
|
| Discord | `/gh logout` | 解除绑定 |
|
||||||
| Telegram | `/gh login`(引用一条消息) | 返回 OAuth 链接 |
|
| Telegram | `/gh login`(仅限私聊) | 返回 OAuth 链接 |
|
||||||
| Telegram | `/gh logout`(引用一条消息) | 解除绑定 |
|
| 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
|
||||||
|
|
||||||
Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任务同步(每 5 分钟):按服务器即时注册,并全局注册(24h 去重,约 1 小时传播)。所有回复均为临时消息(仅你可见)。
|
Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任务同步(每 5 分钟):按服务器即时注册(每轮最多 30 次 Discord API 调用,加入大量服务器的机器人会分几轮补齐),并全局注册(约 1 小时传播)。命令定义变化时两者都会重新注册,全局注册至少每天一次。所有回复均为临时消息(仅你可见)。
|
||||||
|
|
||||||
### 评论 issue / PR
|
### 评论 issue / PR
|
||||||
|
|
||||||
@@ -32,11 +36,11 @@ Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任
|
|||||||
/gh comment del link:<评论链接> 链接需包含 #issuecomment-<id>
|
/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
|
||||||
|
|
||||||
开放 PR 的通知附带 **合并 / 关闭** 按钮(文案跟随分组的消息语言):
|
github.com 上开放 PR 的通知附带 **合并 / 关闭** 按钮(文案跟随分组的消息语言;Gitea 等其他平台不显示按钮,因为这些操作调用的是 GitHub API):
|
||||||
|
|
||||||
- 点击按钮即以你绑定的 GitHub 账号合并(squash)或关闭 PR;权限由 GitHub 强制校验。
|
- 点击按钮即以你绑定的 GitHub 账号合并(squash)或关闭 PR;权限由 GitHub 强制校验。
|
||||||
- 成功后按钮会从通知中移除,结果以临时消息展示。
|
- 成功后按钮会从通知中移除,结果以临时消息展示。
|
||||||
@@ -54,9 +58,13 @@ Discord 命令为**斜杠命令**与**消息右键菜单命令**,由定时任
|
|||||||
|
|
||||||
Telegram `/gh` 命令通过**引用一条通知消息**来使用:
|
Telegram `/gh` 命令通过**引用一条通知消息**来使用:
|
||||||
|
|
||||||
- `/gh login` — 绑定 GitHub 账号(返回 OAuth 链接)
|
- `/gh login` — 绑定 GitHub 账号(仅限与机器人私聊;返回 OAuth 链接)
|
||||||
- `/gh logout` — 解除绑定
|
- `/gh logout` — 解除绑定
|
||||||
- `/gh comment <文本>` — 引用 issue/PR 通知以本人身份评论
|
- `/gh comment <文本>` — 引用 issue/PR 通知以本人身份评论
|
||||||
- `/gh merge` / `/gh close` — 引用 PR 通知进行合并/关闭
|
- `/gh merge` / `/gh close` — 引用 PR 通知进行合并/关闭
|
||||||
|
|
||||||
目标 issue/PR 从你引用的消息(通知嵌入中的链接)解析。命令通过 Telegram webhook(`POST /telegram/webhook`,可用 `TELEGRAM_WEBHOOK_SECRET` 校验)送达。
|
目标 issue/PR 从你引用的消息(通知嵌入中的链接)解析。群聊中也接受 `/gh@你的机器人 …` 的写法(发给其他机器人的命令会被忽略)。评论正文保留换行与缩进。命令通过 Telegram webhook(`POST /telegram/webhook`)送达,该端点始终校验 secret token——`TELEGRAM_WEBHOOK_SECRET`,未设置时使用由 `TELEGRAM_TOKEN` 派生的值。
|
||||||
|
|
||||||
|
## 飞书
|
||||||
|
|
||||||
|
飞书 `/gh` 命令是以 `/gh` 开头(可在前面 @ 机器人)的消息:`/gh login`(仅限私聊)、`/gh logout`、`/gh comment <PR/Issue 链接> <内容>`、`/gh merge <PR 链接>`、`/gh close <PR 链接>`;卡片上也有**合并** / **关闭**按钮。只是在其他位置提到 `/gh` 的消息不算命令。事件订阅见[飞书机器人配置](./deployment#飞书机器人配置)。
|
||||||
@@ -27,24 +27,34 @@ WebHooker 的运行需要若干密钥。本地开发时放入 `.dev.vars`,生
|
|||||||
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
|
| `FEISHU_APP_ID` | 飞书应用 ID(应用凭证页获取)—— 飞书路由必需 |
|
||||||
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
|
| `FEISHU_APP_SECRET` | 飞书应用密钥 —— 飞书路由必需 |
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> 飞书入站命令与卡片按钮(`POST /feishu/webhook`)需要配置 `FEISHU_ENCRYPT_KEY`
|
||||||
|
> 和/或 `FEISHU_VERIFICATION_TOKEN`(即应用**事件与回调 → 加密策略**中的值)。两者都未设置时,
|
||||||
|
> 该端点拒绝所有回调,因为未经认证的请求可以冒充任意已绑定用户。
|
||||||
|
|
||||||
|
<!-- separate the two alerts (MD028) -->
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> `GITHUB_APP_ID` 与 `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)用于 GitHub App **安装流程**
|
> `GITHUB_APP_ID` 与 `GITHUB_PRIVATE_KEY`(PKCS#8 PEM)用于 GitHub App **安装流程**
|
||||||
> (`/auth/github/install`),通过 App JWT 解析安装所属账号的登录名。两者均为可选——
|
> (`/auth/github/install`),通过 App JWT 解析安装所属账号——安装流程也借此验证登录用户
|
||||||
> 未设置时安装页仍可正常使用,但会显示无账号名的匿名 `inst-{installationId}` 分组。
|
> 是否有权管理该安装。未设置时只有超级管理员可以绑定安装。OAuth 流程本身只需要
|
||||||
> OAuth 流程本身只需要 `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`。
|
> `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET`;它申请 `repo` 与 `read:org` 权限范围
|
||||||
|
> (后者用于检查组织管理员身份)。
|
||||||
|
|
||||||
### 可选密钥
|
### 可选密钥
|
||||||
|
|
||||||
| 变量 | 说明 | 默认值 |
|
| 变量 | 说明 | 默认值 |
|
||||||
| --------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------- |
|
| --------------------------- | --------------------------------------------------------------------------------------------------------- | ------------------------ |
|
||||||
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取),交互功能必需 | 未设置时交互返回 401 |
|
| `DISCORD_PUBLIC_KEY` | Discord 应用的公钥(开发者门户获取),交互功能必需 | 未设置时交互返回 401 |
|
||||||
| `DISCORD_APPLICATION_ID` | Discord 应用 ID;省略时自动获取 | 自动获取 |
|
| `DISCORD_APPLICATION_ID` | Discord 应用 ID;省略时自动获取 | 自动获取 |
|
||||||
| `TELEGRAM_WEBHOOK_SECRET` | `POST /telegram/webhook` 验签密钥(X-Telegram-Bot-Api-Secret-Token) | 未设置时不校验 |
|
| `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` |
|
| `TELEGRAM_RICH_HEADER_HOST` | 外部 rich-header 服务的基础 URL;未设置时使用内置 `GET /api/richheader` 提供 Telegram 头像卡片 | 内置 `/api/richheader` |
|
||||||
| `BASE_URL` | OAuth 回调的公共 URL | `http://localhost:8787` |
|
| `BASE_URL` | worker 的公网地址,用于 OAuth 回调与 Telegram webhook 同步 | 未设置——生产环境必填 |
|
||||||
| `ADMIN_USER_IDS` | 允许访问 WebUI 的 GitHub 用户 ID(或登录名),逗号分隔 | 未设置时 WebUI 关闭 |
|
| `ADMIN_USER_IDS` | 允许访问 WebUI 的 GitHub 用户 ID(或登录名),逗号分隔;建议写数字 ID——登录名会绑定到第一个用它登录的账号 | 未设置时 WebUI 关闭 |
|
||||||
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证并授予完整权限 | 关闭 |
|
| `DEBUG_MODE` | 仅本地开发:精确设为 `true` 时跳过全部 `/admin` 身份验证并授予完整权限 | 关闭 |
|
||||||
| `ALLOW_SELF_SIGNUP` | 开启(`1`/`true`)后,没有任何分组权限的 GitHub 用户首次登录会自动获得个人分组而非 403 | 关闭 |
|
| `ALLOW_SELF_SIGNUP` | 开启(`1`/`true`)后,没有任何分组权限的 GitHub 用户首次登录会自动获得隔离的个人分组而非 403 | 关闭 |
|
||||||
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数 | `90` |
|
| `AUDIT_RETENTION_DAYS` | 定时清理时审计日志的保留天数 | `90` |
|
||||||
| `NUXT_PUBLIC_DOCS_URL` | 落地页使用的文档站 URL(客户端运行时配置) | 落地页默认值 |
|
| `NUXT_PUBLIC_DOCS_URL` | 落地页使用的文档站 URL(客户端运行时配置) | 落地页默认值 |
|
||||||
| `NUXT_PUBLIC_REPO_URL` | 落地页使用的 GitHub 仓库 URL | 落地页默认值 |
|
| `NUXT_PUBLIC_REPO_URL` | 落地页使用的 GitHub 仓库 URL | 落地页默认值 |
|
||||||
@@ -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 登录。
|
2. 打开 `/admin` 并使用 GitHub 登录。
|
||||||
3. 没有任何访问权限的用户会得到 `403`,除非 `ALLOW_SELF_SIGNUP=1`(获得个人分组)或跟随分组[邀请链接](./groups#邀请)。
|
3. 没有任何访问权限的用户会得到 `403`,除非 `ALLOW_SELF_SIGNUP=1`(获得个人分组)或跟随分组[邀请链接](./groups#邀请)。
|
||||||
|
|
||||||
@@ -66,7 +76,7 @@ WebHooker 在 `/admin` 提供内置配置控制台,可在浏览器中管理路
|
|||||||
|
|
||||||
删除类操作——删除路由、分组、过滤条件、片段、目标或来源主机,移除成员,撤销邀请,停用分组 webhook——都会先弹出应用内确认框(从未填写过的空行直接删除)。路由与分组编辑弹窗点击遮罩不会关闭,避免丢失未保存的内容;请用「取消」、✕ 或 <kbd>Esc</kbd> 关闭。
|
删除类操作——删除路由、分组、过滤条件、片段、目标或来源主机,移除成员,撤销邀请,停用分组 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 逻辑)
|
- 在任何过滤器上设置 `"exclude": true` 可反转匹配逻辑(NOT 逻辑)
|
||||||
- 所有过滤器类型支持相同的模式形式:纯文本、`*`/`?` **通配符**(`*` 任意长度、`?` 单字符)以及 `/正则表达式/`——均不区分大小写
|
- 所有过滤器类型支持相同的模式形式:纯文本、`*`/`?` **通配符**(`*` 任意长度、`?` 单字符)以及 `/正则表达式/`——均不区分大小写
|
||||||
- 字段过滤器(`event`/`repo`/`actor`/`action`/`branch`/`field`)的通配符匹配整个值;`keyword` 的通配符和正则搜索载荷任意位置;`keyword` 的纯文本为子串搜索
|
- 字段过滤器(`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` 定位载荷字段;数组会自动展开,任一元素匹配即满足过滤器
|
- `field` 过滤器使用点号分隔的 JSONPath `path` 定位载荷字段;数组会自动展开,任一元素匹配即满足过滤器
|
||||||
- 路由可将过滤器嵌套在 `ast` 节点(`all` / `any` / `not`)中,取代扁平的 `filters` 列表;存在 `ast` 时它优先
|
- 路由可将过滤器嵌套在 `ast` 节点(`all` / `any` / `not`)中,取代扁平的 `filters` 列表;存在 `ast` 时它优先
|
||||||
- 超过 200 个字符的模式不编译为通配符/正则;`//` 包裹的非法正则匹配不到任何内容
|
- 通配符与正则在 RE2 引擎上执行(线性时间)。匹配器无法编译的模式——超过 200 个字符,或使用 RE2 不支持的语法(如反向引用、前后瞻)——在保存时被拒绝;此前已存的会让所在路由[不可读](./routes#不可读的路由),而不是静默地永不匹配
|
||||||
- `branch` 过滤器适用于 push、pull_request、pull_request_review、pull_request_review_comment、create/delete、workflow_run、workflow_job、check_suite、deployment 和 code_scanning_alert 事件
|
- `branch` 过滤器适用于 push、pull_request、pull_request_review、pull_request_review_comment、create/delete、workflow_run、workflow_job、check_run、check_suite、deployment、deployment_status 和 code_scanning_alert 事件
|
||||||
|
|
||||||
### 匹配值
|
### 匹配值
|
||||||
|
|
||||||
|
|||||||
+29
-17
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Cloudflare 设置
|
## Cloudflare 设置
|
||||||
|
|
||||||
|
`wrangler.jsonc` 中带有维护者的 `account_id` 与资源 id。请把 `account_id` 换成你自己的 Cloudflare 账号 id(`bunx wrangler whoami`),或删除该字段以部署到当前登录的账号,并按下面的步骤替换各资源 id。
|
||||||
|
|
||||||
### 1. 创建 KV 命名空间
|
### 1. 创建 KV 命名空间
|
||||||
|
|
||||||
```bash
|
```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 TELEGRAM_TOKEN # Telegram Bot Token(BotFather 获取)—— Telegram 路由必需
|
||||||
bunx wrangler secret put FEISHU_APP_ID # 飞书应用 ID —— 飞书路由必需
|
bunx wrangler secret put FEISHU_APP_ID # 飞书应用 ID —— 飞书路由必需
|
||||||
bunx wrangler secret put FEISHU_APP_SECRET # 飞书应用密钥 —— 飞书路由必需
|
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 目标频道按路由配置
|
::: tip 目标频道按路由配置
|
||||||
@@ -40,7 +43,7 @@ bunx wrangler secret put ADMIN_USER_IDS # 逗号分隔的 GitHub ID/登录
|
|||||||
:::
|
:::
|
||||||
|
|
||||||
::: tip GitHub App 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)。
|
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)数据库
|
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` 迁移过的数据库
|
::: 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
|
```bash
|
||||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0001_init.sql
|
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/0010_fragments.sql
|
||||||
bunx wrangler d1 execute webhooker --remote --file ./migrations/0011_feishu_links.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/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(可选)
|
### 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
|
bunx wrangler r2 bucket create webhooker-payloads
|
||||||
```
|
```
|
||||||
|
|
||||||
bucket 已在 `wrangler.jsonc` 中声明(`r2_buckets`),无需修改绑定。
|
然后取消 `wrangler.jsonc` 中 `r2_buckets` 块的注释(默认是注释掉的);没有该绑定时,超大负载仍暂存在 KV。
|
||||||
|
|
||||||
### 5. 创建队列(可选)
|
### 5. 创建队列(可选)
|
||||||
|
|
||||||
`QUEUE` 绑定会通过 Cloudflare Queues 投递 webhook(异步分发,带重试退避与死信队列)。跳过此步则保持同步内联分发。
|
`QUEUE` 绑定会通过 Cloudflare Queues 投递 webhook(异步分发,带重试退避与死信队列)。如需保持同步内联分发,请删除或注释掉 `wrangler.jsonc` 中的 `queues` 块;保留该块时两个队列都必须存在。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
bunx wrangler queues create webhooker-delivery
|
bunx wrangler queues create webhooker-delivery
|
||||||
bunx wrangler queues create webhooker-delivery-dlq
|
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. 部署
|
### 6. 部署
|
||||||
|
|
||||||
```bash
|
```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` 访问。
|
Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问。
|
||||||
|
|
||||||
### 7. 配置 GitHub Webhook
|
### 7. 配置 GitHub Webhook
|
||||||
@@ -151,7 +162,7 @@ Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问
|
|||||||
- **Organization permissions**: Members (read) —— 如果需要
|
- **Organization permissions**: Members (read) —— 如果需要
|
||||||
4. 订阅事件(全部 28 种支持的事件):
|
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
|
- 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
|
### 2. 安装 App
|
||||||
|
|
||||||
@@ -186,20 +197,20 @@ Worker 现在可通过 `https://webhooker.<your-subdomain>.workers.dev` 访问
|
|||||||
2. 将 **Interactions Endpoint URL** 设为 `https://your-domain/discord/interactions`。
|
2. 将 **Interactions Endpoint URL** 设为 `https://your-domain/discord/interactions`。
|
||||||
3. 所有交互请求都使用 Ed25519 签名验证(`X-Signature-Ed25519` 覆盖 `X-Signature-Timestamp + body`)。
|
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)。
|
用户运行 `/gh login` 绑定自己的 GitHub 账号,即可以本人身份评论 issue/PR。完整命令说明见[机器人命令](/zh/guide/commands)。
|
||||||
|
|
||||||
## Telegram 机器人配置
|
## Telegram 机器人配置
|
||||||
|
|
||||||
1. 用 [@BotFather](https://t.me/BotFather) 创建机器人,将 Token 复制到 `TELEGRAM_TOKEN`。
|
1. 用 [@BotFather](https://t.me/BotFather) 创建机器人,将 Token 复制到 `TELEGRAM_TOKEN`。
|
||||||
2. (可选)设置 `TELEGRAM_WEBHOOK_SECRET`;webhook 注册时会作为 `secret_token` 传给 Telegram,`POST /telegram/webhook` 使用时间安全比较校验。
|
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` 已设置。
|
3. Worker 会在定时任务中自动同步 webhook(`setWebhook` 指向 `{BASE_URL}/telegram/webhook`,仅在注册内容变化时以及每天一次),因此无需手动调用 `setWebhook`——只需确保 `BASE_URL` 已设置。
|
||||||
4. 将机器人加入群组(或启用话题),在路由配置中用 `chatId` / `topicId` 指定目标。
|
4. 将机器人加入群组(或启用话题),在路由配置中用 `chatId` / `topicId` 指定目标。请使用数字 chat id(如 `-1001234567890`),不接受 `@username` 目标。
|
||||||
|
|
||||||
在 Telegram 中,`/gh` 命令(`/gh login`、`/gh logout`、`/gh comment <内容>`、`/gh merge`、`/gh close`)通过在通知消息上**回复**来使用——见[机器人命令](/zh/guide/commands)。
|
在 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_as_bot`(以应用机器人身份发送消息)
|
||||||
- `im:message:send`(旧版发送消息权限)
|
- `im:message:send`(旧版发送消息权限)
|
||||||
4. 在**机器人**功能中启用机器人。将机器人添加到目标群聊(或创建新群),并在群设置中复制 **Chat ID**。
|
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. 订阅以下事件:
|
2. 订阅以下事件:
|
||||||
- `im.message.receive_v1` —— 接收 `/gh` 指令(依赖 `im:message` 权限)。
|
- `im.message.receive_v1` —— 接收 `/gh` 指令(依赖 `im:message` 权限)。
|
||||||
- `card.action.trigger` —— 接收卡片按钮点击。
|
- `card.action.trigger` —— 接收卡片按钮点击。
|
||||||
3. **凭证与基础信息**中的 **App Secret**(即 `FEISHU_APP_SECRET`)同时用于对入站回调做 `X-Lark-Signature` 签名,WebHooker 会校验它。
|
3. 在**事件与回调 → 加密策略**中,把 **Encrypt Key** 填入 `FEISHU_ENCRYPT_KEY`(WebHooker 会校验 `X-Lark-Signature`——timestamp + nonce + key + body 的 SHA-256——并解密加密回调),和/或把 **Verification Token** 填入 `FEISHU_VERIFICATION_TOKEN`。至少需要其中一个;都未设置时所有回调都会被拒绝。同一事件 id 只执行一次,飞书重试也不会重复执行。
|
||||||
|
4. `/gh login` 只能在与机器人的单聊(p2p)中使用;GitHub 用户需在同时显示双方账号的确认页上确认绑定。
|
||||||
|
|
||||||
### 所需权限
|
### 所需权限
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@
|
|||||||
|
|
||||||
## 如何让分组使用自己的 webhook 端点?
|
## 如何让分组使用自己的 webhook 端点?
|
||||||
|
|
||||||
见[分组端点](./ingress#分组端点)——在分组的 **Webhook 端点**面板(owner 角色)生成密钥,然后用 `POST /webhook/{groupId}` 与分组密钥发送。
|
见[分组端点](./ingress#分组端点-post-webhook-groupid)——在分组的 **Webhook 端点**面板(owner 角色)生成密钥,然后用 `POST /webhook/{groupId}` 与分组密钥发送。
|
||||||
|
|
||||||
## 可以脱离 Cloudflare Workers 运行吗?
|
## 可以脱离 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#存储决策)。
|
||||||
+19
-14
@@ -125,15 +125,16 @@
|
|||||||
匹配事件涉及的分支。何种字段算作「分支」取决于事件类型:
|
匹配事件涉及的分支。何种字段算作「分支」取决于事件类型:
|
||||||
|
|
||||||
| 事件 | 提取的分支 |
|
| 事件 | 提取的分支 |
|
||||||
| --------------------------- | ----------------------------------- |
|
| ---------------------------------- | --------------------------------------------------------------------------- |
|
||||||
| `push` | 推送到的目标分支 |
|
| `push` | 推送到的目标分支 |
|
||||||
| `pull_request`(及 review) | 拉取请求的 **head**(源)分支 |
|
| `pull_request`(及 review) | 拉取请求的 **head**(源)分支 |
|
||||||
| `create` / `delete` | 创建/删除的分支或标签 |
|
| `create` / `delete` | 创建/删除的分支或标签 |
|
||||||
| `workflow_run` | 工作流运行所在的 `head_branch` |
|
| `workflow_run` | 工作流运行所在的 `head_branch` |
|
||||||
| `workflow_job` | 作业运行所在的 `head_branch` |
|
| `workflow_job` | 作业运行所在的 `head_branch` |
|
||||||
|
| `check_run` | 所属检查套件的 `head_branch` |
|
||||||
| `check_suite` | 检查套件的 `head_branch` |
|
| `check_suite` | 检查套件的 `head_branch` |
|
||||||
| `deployment` | 部署引用(去除 `refs/heads/` 前缀) |
|
| `deployment` / `deployment_status` | 部署引用(`deployment.ref`,去除开头的 `refs/heads/`) |
|
||||||
| `code_scanning_alert` | 告警所属的分支 |
|
| `code_scanning_alert` | 告警的 ref,去除开头的 `refs/heads/`(写 `main`,不要写 `refs/heads/main`) |
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
@@ -179,8 +180,9 @@
|
|||||||
|
|
||||||
行为细节:
|
行为细节:
|
||||||
|
|
||||||
- 超过 200 个字符的模式**不**编译为通配符/正则,回退为纯文本匹配。
|
- 超过 200 个字符的模式无法编译为通配符/正则,保存时会被拒绝。
|
||||||
- 被 `/` 包裹但**不是合法正则**的模式匹配**任何内容都不命中**(过滤器恒为 false),而不会报错。
|
- 通配符与正则表达式运行在 RE2 引擎上,匹配时间与输入长度成线性关系——任何模式都无法拖住 worker。RE2 语法不支持反向引用(`\1`)与环视(`(?=…)`、`(?<!…)`);控制台与 API 会拒绝此类模式。
|
||||||
|
- 被 `/` 包裹但**不是合法正则**的模式在保存时会被拒绝。
|
||||||
- 要搜索是通配符或正则特殊字符的文本(如 `v1.2.3`),使用纯文本形式即可——不含 `*`、`?` 且未被 `//` 包裹的模式按字面匹配。
|
- 要搜索是通配符或正则特殊字符的文本(如 `v1.2.3`),使用纯文本形式即可——不含 `*`、`?` 且未被 `//` 包裹的模式按字面匹配。
|
||||||
- 搜索覆盖**整个**载荷:提交信息、PR 标题与正文、标签、引用,甚至仓库名和发送者名。
|
- 搜索覆盖**整个**载荷:提交信息、PR 标题与正文、标签、引用,甚至仓库名和发送者名。
|
||||||
|
|
||||||
@@ -221,7 +223,7 @@
|
|||||||
| `gt` / `gte` | 数值大于 / 大于等于 |
|
| `gt` / `gte` | 数值大于 / 大于等于 |
|
||||||
| `lt` / `lte` | 数值小于 / 小于等于 |
|
| `lt` / `lte` | 数值小于 / 小于等于 |
|
||||||
| `in` | 值等于任一列出的模式 |
|
| `in` | 值等于任一列出的模式 |
|
||||||
| `exists` | 字段存在(非 null);忽略 `match` |
|
| `exists` | 字段存在(非 null);`match` 可省略 |
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{ "type": "field", "path": "pull_request.commits", "op": "gt", "match": "1" }
|
{ "type": "field", "path": "pull_request.commits", "op": "gt", "match": "1" }
|
||||||
@@ -239,6 +241,9 @@
|
|||||||
{
|
{
|
||||||
"id": "grouped",
|
"id": "grouped",
|
||||||
"name": "Grouped",
|
"name": "Grouped",
|
||||||
|
"enabled": true,
|
||||||
|
"groupId": "eng",
|
||||||
|
"filters": [],
|
||||||
"ast": {
|
"ast": {
|
||||||
"all": [
|
"all": [
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "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`)会作为整体比较——要匹配其中某个元素请用「包含」;在编辑器中选择这类候选路径时会自动切换为「包含」。
|
匹配值、字段路径与测试事件均为可搜索的下拉框。候选项来自 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": [
|
"filters": [
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "type": "event", "match": "pull_request" },
|
||||||
{ "type": "actor", "match": "dependabot[bot]", "exclude": true },
|
{ "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:仅发布通知频道
|
## 示例 2:仅发布通知频道
|
||||||
|
|
||||||
@@ -298,7 +303,7 @@
|
|||||||
{ "type": "action", "match": "published" },
|
{ "type": "action", "match": "published" },
|
||||||
{ "type": "repo", "match": "myorg/backend" }
|
{ "type": "repo", "match": "myorg/backend" }
|
||||||
],
|
],
|
||||||
"target": { "channelId": "222222222222222222" }
|
"targets": [{ "platform": "discord", "channelId": "222222222222222222" }]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -317,14 +322,14 @@
|
|||||||
{ "type": "action", "match": "completed" },
|
{ "type": "action", "match": "completed" },
|
||||||
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
{ "type": "keyword", "match": "\"conclusion\":\"failure\"" }
|
||||||
],
|
],
|
||||||
"target": { "channelId": "333333333333333333" }
|
"targets": [{ "platform": "discord", "channelId": "333333333333333333" }]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## 常见陷阱
|
## 常见陷阱
|
||||||
|
|
||||||
- **通配符是 glob,不是正则。** `repo: "myorg/*"` 匹配 `myorg` 下的任意仓库(含 `myorg/sub/backend`),但 `repo: "myorg/.*"` 按字面匹配。需要正则请用 `/` 包裹:`"/myorg\/.*/"`。
|
- **通配符是 glob,不是正则。** `repo: "myorg/*"` 匹配 `myorg` 下的任意仓库(含 `myorg/sub/backend`),但 `repo: "myorg/.*"` 按字面匹配。需要正则请用 `/` 包裹:`"/myorg\/.*/"`。
|
||||||
- **被 `/` 包裹的非法正则永远不匹配。** 与纯文本不同——未包裹的非法模式按字面匹配。只有确定是真正的正则时才使用 `//` 包裹。
|
- **被 `/` 包裹的非法正则会被拒绝。** 控制台与 API 在保存时拒绝它;此前已保存的路由会被报告为[不可读](./routes#不可读的路由),所在分组的投递会一直重试直到修复。与 `//` 包裹的文本不同——未包裹的模式按字面匹配。只有确定是真正的正则时才使用 `//` 包裹。
|
||||||
- **`action` 过滤器遇到无 action 的事件永远不匹配。** 先确认该事件带有 `action` 字段(见[过滤器兼容性](../events/supported#过滤器兼容性))。
|
- **`action` 过滤器遇到无 action 的事件永远不匹配。** 先确认该事件带有 `action` 字段(见[过滤器兼容性](../events/supported#过滤器兼容性))。
|
||||||
- **`branch` 过滤器遇到无分支的事件永远不匹配。** 在 `issues` 事件上使用 `branch` 过滤器恒为假。此时需要类似分支的匹配可用 `keyword`。
|
- **`branch` 过滤器遇到无分支的事件永远不匹配。** 在 `issues` 事件上使用 `branch` 过滤器恒为假。此时需要类似分支的匹配可用 `keyword`。
|
||||||
- **`keyword` 会搜索一切。** 因为它扫描整个载荷,`"fix"` 这样的模式可能同时匹配提交信息、issue 标题和仓库名。请尽量写得更具体。
|
- **`keyword` 会搜索一切。** 因为它扫描整个载荷,`"fix"` 这样的模式可能同时匹配提交信息、issue 标题和仓库名。请尽量写得更具体。
|
||||||
|
|||||||
@@ -33,12 +33,12 @@ GITHUB_CLIENT_ID=your-client-id
|
|||||||
GITHUB_CLIENT_SECRET=your-client-secret
|
GITHUB_CLIENT_SECRET=your-client-secret
|
||||||
DISCORD_TOKEN=your-bot-token
|
DISCORD_TOKEN=your-bot-token
|
||||||
DISCORD_PUBLIC_KEY=your-public-key
|
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
|
BASE_URL=http://localhost:8787
|
||||||
```
|
```
|
||||||
|
|
||||||
::: tip
|
::: 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
|
::: warning
|
||||||
@@ -48,10 +48,11 @@ BASE_URL=http://localhost:8787
|
|||||||
### 2. 启动开发服务器
|
### 2. 启动开发服务器
|
||||||
|
|
||||||
```bash
|
```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. 验证
|
### 3. 验证
|
||||||
|
|
||||||
@@ -66,7 +67,7 @@ curl http://localhost:8787/health
|
|||||||
| ---------------------- | ------------------------------------ |
|
| ---------------------- | ------------------------------------ |
|
||||||
| `bun run dev` | 启动 Nuxt 开发服务器 (HMR) |
|
| `bun run dev` | 启动 Nuxt 开发服务器 (HMR) |
|
||||||
| `bun run build` | 生产构建(cloudflare_module preset) |
|
| `bun run build` | 生产构建(cloudflare_module preset) |
|
||||||
| `bun run deploy` | 部署到 Cloudflare |
|
| `bun run deploy` | 应用待执行的 D1 迁移并部署 |
|
||||||
| `bun run typecheck` | TypeScript 类型检查 |
|
| `bun run typecheck` | TypeScript 类型检查 |
|
||||||
| `bun run lint` | ESLint |
|
| `bun run lint` | ESLint |
|
||||||
| `bun run lint:md` | Markdownlint |
|
| `bun run lint:md` | Markdownlint |
|
||||||
|
|||||||
+26
-11
@@ -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 个分组**。
|
||||||
|
|
||||||
## 分组模式
|
## 分组模式
|
||||||
|
|
||||||
@@ -21,18 +21,21 @@
|
|||||||
```
|
```
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| 字段 | 类型 | 必需 | 说明 |
|
||||||
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
| ---------------- | -------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `id` | string | 是 | 小写 id(`a-z0-9`、`-`);被每条路由的 `groupId` 引用。可编辑:重命名分组会同步其路由、分组 webhook secret 与待处理邀请 |
|
| `id` | string | 是 | 小写 id(`a-z0-9`、`-`);被每条路由的 `groupId` 引用。可编辑:重命名会同步其路由、片段、历史记录、webhook secret 与待处理邀请;被删除或重命名的 id 会保留若干天不可复用 |
|
||||||
| `name` | string | 是 | 人类可读的分组名 |
|
| `name` | string | 是 | 人类可读的分组名 |
|
||||||
| `members` | object[] | 否 | `{ login, role }` 条目;角色为 `owner`、`admin` 或 `viewer` |
|
| `members` | object[] | 是¹ | `{ login, role }` 条目;角色为 `owner`、`admin` 或 `viewer`。服务端会把每个条目绑定到 GitHub user id(添加成员时解析,或在其首次登录时绑定);绑定后只匹配该账号,即使登录名易主 |
|
||||||
| `adminIds` | string[] | 否 | 已废弃的旧字段;存在时视为角色为 `owner` 的 `members` |
|
| `adminIds` | string[] | 否 | 已废弃的旧字段;存在时视为角色为 `owner` 的 `members` |
|
||||||
| `owners` | string[] | 否 | 允许进入该分组的事件所属组织/用户登录名;空 = 全部 |
|
| `owners` | string[] | 否 | 允许进入该分组的事件所属组织/用户登录名;空 = 全部 |
|
||||||
| `providers` | string[] | 否 | 允许进入该分组的来源平台(`github`、`gitea`);空 = 全部 |
|
| `providers` | string[] | 否 | 允许进入该分组的来源平台(`github`、`gitea`、`custom`);空 = 全部 |
|
||||||
| `installationId` | number | 否 | 绑定到该分组的 GitHub App 安装 id;仅接受该安装的事件(空 = 全部) |
|
| `installationId` | number | 否 | 绑定到该分组的 GitHub App 安装 id;仅接受该安装的事件(空 = 全部)。仅超级管理员可改(由经过验证的安装流程设置) |
|
||||||
|
| `isolated` | boolean | 否 | 隔离分组(自助注册的个人分组)只接收其自身 `/webhook/{groupId}` 入口的事件,直到超级管理员为其绑定来源(`installationId` 或 `owners`)。仅超级管理员可改 |
|
||||||
| `emoji` | boolean | 否 | 该分组消息是否包含表情(默认 `true`) |
|
| `emoji` | boolean | 否 | 该分组消息是否包含表情(默认 `true`) |
|
||||||
| `forgeSources` | object[] | 否 | 来源主机:`{ host, type, name? }` 条目(`type` 为 `github` 或 `gitea`,`name` 为可选显示名称),用于标注该分组消息底部;空 = 不标注 |
|
| `forgeSources` | object[] | 否 | 来源主机:`{ host, type, name? }` 条目(`type` 为 `github` 或 `gitea`,`name` 为可选显示名称),用于标注该分组消息底部;空 = 不标注 |
|
||||||
| `lang` | string | 否 | 该分组所有路由的消息语言(如 `en`、`zh`;可通过 KV `i18n:<lang>` 自定义)——见[消息语言](./i18n)——默认 `en` |
|
| `lang` | string | 否 | 该分组所有路由的消息语言(如 `en`、`zh`;可通过 KV `i18n:<lang>` 自定义)——见[消息语言](./i18n)——默认 `en` |
|
||||||
| `logTarget` | object | 否 | Webhook 日志频道:Discord 目标 `{ platform, channelId, threadId? }` 或 Telegram 目标 `{ platform, chatId, topicId? }`,接收该分组路由每次分发 webhook 的摘要 |
|
| `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 时降级自己。
|
- **Owner** 管理自己分组的路由、成员、邀请、名称、id、`emoji` 与 `providers`。不能移除最后一个 owner,也不能在没有其他 owner 时降级自己。
|
||||||
- **Admin** 编辑自己分组内的路由并查看日志;**viewer** 只有只读控制台。
|
- **Admin** 编辑自己分组内的路由并查看日志;**viewer** 只有只读控制台。
|
||||||
- 分组管理端点通过 `/admin/api/groups/:id/routes` 一次操作一个分组;`groupId` 强制取自路径参数。
|
- 分组管理端点通过 `/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 分组分开。
|
- `providers` 列表限制该分组路由会分发哪个 forge(`github`、`gitea`)的事件。即使组织/用户名冲突,也可借此将 GitHub 与 Gitea 分组分开。
|
||||||
|
|
||||||
## Webhook 日志频道
|
## 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 安装的入口;关闭它可保持控制台仅邀请制。
|
设置 `ALLOW_SELF_SIGNUP=1` 后,没有分组权限的 GitHub 用户首次登录时会获得个人分组(`u-{userId}`,归其所有),而不是 `403`。这是完全自助式 SaaS 安装的入口;关闭它可保持控制台仅邀请制。
|
||||||
|
|
||||||
|
个人分组是**隔离的**(该字段出现前创建的 `u-<数字>` 分组同样视为隔离,除非超级管理员设置 `isolated: false`):运营者的全局 `POST /webhook` 入口永远不会分发到它们,因此自助用户无法通过添加通配路由收到其他租户的事件。它们通过自己的[分组 webhook](./ingress) 接收事件,或接收其能证明自己管理的 GitHub App 安装的事件(安装流程会用用户本人的 GitHub token 校验)。
|
||||||
@@ -8,17 +8,19 @@
|
|||||||
|
|
||||||
## 自定义覆盖
|
## 自定义覆盖
|
||||||
|
|
||||||
翻译覆盖从 KV 键 `i18n:<lang>` 读取,值为扁平的「键 → 文本」JSON 对象。内置字典(en/zh)中的任意键都可覆盖;未提供的键回退为英文。
|
额外的消息语言从 KV 键 `i18n:<lang>` 读取:一个与内置字典(`server/lib/lib/locales/en.ts`)嵌套结构相同的 JSON 对象,未提供的键都会回退为英文。内置的 `en` 与 `zh` 不会从 KV 读取,因此不能这样覆盖;请使用其他语言代码(如 `zh-custom`),并把它设为分组的 `lang`。
|
||||||
|
|
||||||
```jsonc
|
```jsonc
|
||||||
// KV 键:i18n:zh
|
// KV 键:i18n:zh-custom
|
||||||
{
|
{
|
||||||
"events.push.title": "{repo}: 推送了 {count} 个提交到 {ref}",
|
"events": {
|
||||||
|
"push": { "title": "{repo}: 推送了 {count} 个提交到 {ref}" },
|
||||||
|
},
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
覆盖对分组消息(以及适用的控制台界面)生效。要新增一种语言,可在 `i18n:<lang>` 存放完整字典——未提供的键都会回退为英文。
|
已加载的字典会在每个 worker 实例中一直缓存到实例重启,因此修改后的覆盖可能要过一段时间才生效;没有覆盖的语言 5 分钟后会再次查找。覆盖只影响分组消息——控制台使用其内置的翻译。
|
||||||
|
|
||||||
## 表情开关
|
## 表情开关
|
||||||
|
|
||||||
`Group.emoji`(默认 `true`)控制该分组消息中是否显示事件表情。关闭后,标题、描述、字段与链接中的所有表情都会被去除。里程碑进度条(🟢🟡🟠⬜)属于数据可视化,不受该开关影响。
|
`Group.emoji`(默认 `true`)控制该分组消息中是否显示事件表情。关闭后,格式化器添加到标题、描述、字段与链接中的表情都不会出现;取自载荷的文本(提交信息、issue 标题、自定义 webhook 字段)保留其中自带的表情。里程碑进度条(🟢🟡🟠⬜)属于数据可视化,不受该开关影响。
|
||||||
@@ -11,24 +11,29 @@ WebHooker 通过同一个 `POST /webhook` 端点接收多个 forge 的 webhook
|
|||||||
|
|
||||||
投递 id 去重使用 `X-GitHub-Delivery`(GitHub)或 `X-Gitea-Delivery`(Gitea)请求头(存在时)。
|
投递 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 实例。
|
Gitea 载荷会被归一化为与 GitHub 事件相同的内部结构,因此路由、过滤器与 28 个格式化器无需改动即可工作。未知或未映射的 Gitea 事件回退到通用格式化器。仓库/提交/用户链接取自载荷中的 `repository.html_url`,因此指向你的 Gitea 实例。
|
||||||
|
|
||||||
## 全局端点(`POST /webhook`)
|
## 全局端点(`POST /webhook`)
|
||||||
|
|
||||||
全局端点使用运营者的全局密钥(`GITHUB_WEBHOOK_SECRET`、`GITEA_WEBHOOK_SECRET`)验签,并分发到**所有**路由。GitHub App 安装的事件都在此送达;在分组上设置 `installationId` 可保持租户隔离。
|
全局端点使用运营者的全局密钥(`GITHUB_WEBHOOK_SECRET`、`GITEA_WEBHOOK_SECRET`)验签,并分发到**所有**路由——未绑定来源的[隔离分组](./groups#自助注册)除外。GitHub App 安装的事件都在此送达;在分组上设置 `installationId` 可保持租户隔离。
|
||||||
|
|
||||||
## 分组端点(`POST /webhook/{groupId}`)
|
## 分组端点(`POST /webhook/{groupId}`)
|
||||||
|
|
||||||
每个分组都可以选择接入自己的 webhook 入口,使用独立的密钥(在分组页面的 _Webhook 端点_ 面板生成,owner 角色)。载荷使用**分组**的密钥验签,而不是全局密钥,并且只有该分组的路由会被触发。SaaS 用户以此配置 Gitea、经典 GitHub 或自定义 webhook,而无需共享(或知道)运营者的密钥。
|
每个分组都可以选择接入自己的 webhook 入口,使用独立的密钥(在分组页面的 _Webhook 端点_ 面板生成,owner 角色)。载荷使用**分组**的密钥验签,而不是全局密钥,并且只有该分组的路由会被触发。SaaS 用户以此配置 Gitea、经典 GitHub 或自定义 webhook,而无需共享(或知道)运营者的密钥。
|
||||||
|
|
||||||
- 支持任意提供方:GitHub(`X-Hub-Signature-256`)、Gitea(`X-Gitea-Signature`)、自定义(`X-WebHooker-Signature`)
|
- 支持任意提供方:GitHub(`X-Hub-Signature-256`)、Gitea(`X-Gitea-Signature`)、自定义(`X-WebHooker-Signature`)
|
||||||
- 密钥为 64 位 hex 字符串;在控制台重新生成会立即失效旧密钥
|
- 密钥为 64 位 hex 字符串,与分组一起存于 D1(生成之后不再发给控制台);重新生成会立即失效旧密钥,只有当前 owner 能轮换或删除
|
||||||
- 投递 id 去重键按提供方与租户隔离(`delivery:{provider}:{groupId}:{id}`)
|
- 投递 id 去重键按提供方与租户隔离(`delivery:{provider}:@i:{instance}:{id}`——使用分组不可变的 instance,改名不改变作用域,以同一 id 新建的分组也不会共用;全局入口使用作用域 `@global`)
|
||||||
- 分组没有密钥(或已不存在)时端点返回 `404`
|
- 租户签名的载荷只具备租户本身的可信度:其中的 `installation.id` 会被忽略,因此它不会使用运营者的 GitHub App 凭据(不做 job/构建日志补全),也不会创建或重新绑定安装分组;分组自身入口的事件不受安装限制约束
|
||||||
|
- 分组没有密钥(或已不存在)时端点返回 `404`;分组存储的配置无法读取时返回 `503`
|
||||||
|
|
||||||
## 自定义 Webhook
|
## 自定义 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),且仅当以下条件满足时才被接受:
|
当**同时**提供这两个请求头时,签名改为对 `{timestamp}.{nonce}.{原始body}` 计算(而非仅原始 body),且仅当以下条件满足时才被接受:
|
||||||
|
|
||||||
1. 时间戳与服务器时钟相差不超过 ±5 分钟(拒绝重放与时钟漂移滥用)
|
1. 时间戳与服务器时钟相差不超过 ±5 分钟(拒绝重放与时钟漂移滥用)
|
||||||
2. nonce 从未被使用过(存入 KV 保留 10 分钟;重放的 nonce 会被拒绝)
|
2. 该 nonce 对此密钥从未被使用过(原子占用并保留 10 分钟;重放的 nonce 会被拒绝,其他租户可以使用相同 nonce)。第一次请求仍在处理中的 nonce,或 nonce 存储故障,返回 `503` 而不是 `401`,由发送方重试
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
input="${timestamp}.${nonce}.${body}"
|
input="${timestamp}.${nonce}.${body}"
|
||||||
@@ -79,12 +84,14 @@ signature="sha256=$(printf '%s' "$input" | openssl dgst -sha256 -hmac "$secret"
|
|||||||
| `author` | object | 可选 `{ name, iconUrl, url }` |
|
| `author` | object | 可选 `{ name, iconUrl, url }` |
|
||||||
| `fields` | object[] | 可选嵌入字段 `{ name, value, inline }` |
|
| `fields` | object[] | 可选嵌入字段 `{ name, value, inline }` |
|
||||||
| `footer` | string | 可选页脚覆盖 |
|
| `footer` | string | 可选页脚覆盖 |
|
||||||
| `deliveryId` | string | 可选的发送方去重 id(重试) |
|
| `deliveryId` | string | 可选的发送方去重 id(重试)。没有 `deliveryId` 时以 nonce 标识请求;两者都没有时,重试的请求会被再次投递 |
|
||||||
|
|
||||||
## GitHub App 租户隔离
|
## GitHub App 租户隔离
|
||||||
|
|
||||||
GitHub App 安装后,**所有**安装方的事件都会到达全局端点。要让租户互相隔离,请把每个分组绑定到应当为其提供事件的安装 ID:`"installationId": 12345678`。该 ID 可从 App 安装 webhook 载荷(`installation.id`)或 GitHub App 安装页 URL 看到。即使分组的 `owners` 为空,来自其它安装的事件也会被拒绝。未设置 `installationId` 的分组保持旧行为(`owners` 过滤)。
|
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#密钥)。
|
要在选择页显示安装所属账号的登录名,请设置 `GITHUB_APP_ID` 与 `GITHUB_PRIVATE_KEY`——见[密钥](./configuration#密钥)。
|
||||||
@@ -22,7 +22,7 @@ GitHub / Gitea Webhook → Cloudflare Worker (Nuxt 4 / Nitro)
|
|||||||
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| **Cloudflare Worker** | HTTP 入口、签名验证、投递去重、事件解析、路由匹配、平台分发 |
|
| **Cloudflare Worker** | HTTP 入口、签名验证、投递去重、事件解析、路由匹配、平台分发 |
|
||||||
| **Interactions Endpoint** | 验证 Ed25519 签名并处理 `/gh` 交互(斜杠命令、右键菜单、按钮、modal) |
|
| **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 存储 |
|
| **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
|
- **运行时**: Cloudflare Workers
|
||||||
- **HTTP 框架**: Nuxt 4 / Nitro (H3)
|
- **HTTP 框架**: Nuxt 4 / Nitro (H3)
|
||||||
- **Discord 投递**: Discord REST API(交互通过 Ed25519 验签的 HTTPS Interactions Endpoint)
|
- **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` 控制台客户端渲染
|
- **Web UI**: Nuxt 4(Vue 3 + Tailwind CSS v4 + `@elysola/ui`)——首页/法律页面服务端渲染,`/admin` 控制台客户端渲染
|
||||||
- **存储**: Cloudflare D1(配置与日志权威)+ KV(缓存/临时状态)+ 可选 R2(超大负载)
|
- **存储**: Cloudflare D1(配置与日志权威)+ KV(缓存/临时状态)+ 可选 R2(超大负载)
|
||||||
- **鉴权**: Web Crypto API (HMAC-SHA256、Ed25519)、octokit (GitHub API)
|
- **鉴权**: Web Crypto API (HMAC-SHA256、Ed25519)、octokit (GitHub API)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
每次分发尝试都会记录到 D1 `send_logs` 表,并可在控制台(**日志**标签页)查看。字段:
|
每次分发尝试都会记录到 D1 `send_logs` 表,并可在控制台(**日志**标签页)查看。字段:
|
||||||
|
|
||||||
| 字段 | 含义 |
|
| 字段 | 含义 |
|
||||||
| ------------ | -------------------------------------------------------- |
|
| ------------ | ----------------------------------------------------------------------------------------------------------- |
|
||||||
| `routeId` | 匹配的路由 |
|
| `routeId` | 匹配的路由 |
|
||||||
| `groupId` | 路由所属分组 |
|
| `groupId` | 路由所属分组 |
|
||||||
| `event` | 事件类型(如 `push`、`pull_request`、`custom`) |
|
| `event` | 事件类型(如 `push`、`pull_request`、`custom`) |
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
| `ok` | 发送是否成功 |
|
| `ok` | 发送是否成功 |
|
||||||
| `status` | 平台 API 的 HTTP 状态码(适用时) |
|
| `status` | 平台 API 的 HTTP 状态码(适用时) |
|
||||||
| `error` | 失败时的错误信息 |
|
| `error` | 失败时的错误信息 |
|
||||||
| `errorCode` | 稳定错误码(如 `NO_TARGET`、`NO_TOKEN`、`RATE_LIMITED`) |
|
| `errorCode` | 稳定错误码(如 `NO_TARGET`、`NO_TOKEN`、`RATE_LIMITED`、`FORMAT`、`PAYLOAD_MISSING`、`TELEGRAM_UNCERTAIN`) |
|
||||||
| `attempts` | 含重试在内的发送次数 |
|
| `attempts` | 含重试在内的发送次数 |
|
||||||
| `durationMs` | 发送耗时 |
|
| `durationMs` | 发送耗时 |
|
||||||
| `deliveryId` | Webhook 投递 id(提供时) |
|
| `deliveryId` | Webhook 投递 id(提供时) |
|
||||||
@@ -24,7 +24,13 @@
|
|||||||
| `action` | 事件动作(存在时) |
|
| `action` | 事件动作(存在时) |
|
||||||
| `detail` | 附加 JSON 详情(存在时) |
|
| `detail` | 附加 JSON 详情(存在时) |
|
||||||
|
|
||||||
控制台的**日志**标签页列出最近记录(可按分组过滤),并可查看单条完整详情。写入为尽力而为——插入失败不会中断分发。
|
控制台的**日志**标签页列出最近记录(可按分组过滤),并可查看单条完整详情。写入为尽力而为——插入失败会重试一次,且不会中断分发。`send_logs` 不会自动清理。
|
||||||
|
|
||||||
|
需要留意的错误码:
|
||||||
|
|
||||||
|
- `PAYLOAD_MISSING` —— 排队投递暂存的负载已丢失;投递保持重试状态,该记录提示从源头重新投递 webhook。
|
||||||
|
- `TELEGRAM_UNCERTAIN` —— Telegram 返回 `200` 但响应无法读取;消息可能已发出也可能没有,因此不会重试(Telegram 没有幂等键)。
|
||||||
|
- `FORMAT` —— 事件无法格式化;该路由没有发送任何内容。
|
||||||
|
|
||||||
## 审计日志(`audit_logs`)
|
## 审计日志(`audit_logs`)
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
只有仓库头会被加超链接——整条标题永远不会整体链接:
|
只有仓库头会被加超链接——整条标题永远不会整体链接:
|
||||||
|
|
||||||
- **Discord**(嵌入标题不支持局部链接):标题为仓库头 `{repo}{#number}`,链接到仓库;`: {subject}` 文本作为描述首行渲染,不带链接。
|
- **Discord**(嵌入标题不支持局部链接):标题为仓库头 `{repo}{#number}`,链接到事件对象(issue、PR、评论或运行页面);`: {subject}` 文本作为描述首行渲染,不带链接。
|
||||||
- **Telegram**(HTML 支持行内链接):单行标题保留描述文本,仅仓库头被包在链接中。
|
- **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 作业
|
## Workflow 作业
|
||||||
|
|
||||||
|
|||||||
+16
-6
@@ -1,8 +1,8 @@
|
|||||||
# 路由与目标
|
# 路由与目标
|
||||||
|
|
||||||
路由决定哪些事件被转发到哪个频道(Discord 或 Telegram)。它们存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 键同步),可通过 [Web 控制台](./configuration#web-控制台)、[Admin API](../api/admin) 或 `config.example.yaml` 管理。
|
路由决定哪些事件被转发到哪个频道(Discord 或 Telegram)。它们存储在 D1(`d1_routes`,首次加载时从旧版 KV `config:routes` 键同步),可通过 [Web 控制台](./configuration#web-控制台)或 [Admin API](../api/admin) 管理。`config.example.yaml` 以 YAML 展示数据结构,worker 不会读取它。
|
||||||
|
|
||||||
**没有默认路由**——每条路由都必须定义自己的目标。未配置任何路由时不会转发任何事件。每个实例最多可保存 **200 条路由**。
|
**没有默认路由**——每条路由都必须定义自己的目标。未配置任何路由时不会转发任何事件。单次保存最多 **200 条路由**。
|
||||||
|
|
||||||
## 路由模式
|
## 路由模式
|
||||||
|
|
||||||
@@ -29,14 +29,20 @@
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`targets` 的每一项都是一个推送目标,因此一条路由可同时转发到多个频道(例如一个 Discord 频道**和**一个 Telegram 群组)。`target.platform` 选择平台:`discord`(默认)、`telegram` 或 `feishu`。**Discord** 目标要求 `target.channelId`(可选 `target.threadId` 指定子区);**Telegram** 与 **飞书** 目标要求 `target.chatId`(群组/超级群组 id,如 `-1001234567890`),可选 `target.topicId`(话题的 `message_thread_id`,相当于 Discord 子区)。没有默认频道回退。
|
`targets` 的每一项都是一个推送目标,因此一条路由可同时转发到多个频道(例如一个 Discord 频道**和**一个 Telegram 群组)。`target.platform` 选择平台:`discord`(默认)、`telegram` 或 `feishu`。**Discord** 目标要求 `target.channelId`(可选 `target.threadId` 指定子区);**Telegram** 目标要求 `target.chatId`(群组/超级群组 id,如 `-1001234567890`),可选 `target.topicId`(话题的 `message_thread_id`,相当于 Discord 子区);**飞书**目标要求 `target.chatId`(群聊 id,`oc_…`),没有话题。没有默认频道回退。
|
||||||
|
|
||||||
|
目标 id 会校验为唯一的写法(否则可以绕过跨分组归属检查):
|
||||||
|
|
||||||
|
- **Discord** —— `channelId` / `threadId` 只能包含 `A–Z a–z 0–9 _ -`(最多 64 个字符);纯数字 id 不能以 0 开头。
|
||||||
|
- **Telegram** —— `chatId` 为规范写法的数字 chat id(无前导零,最多 15 位;不接受 `@username`);`topicId` 为不超过 2147483647 的正整数。
|
||||||
|
- 同一路由不能重复列出同一目的地:`{ "channelId": T }` 与 `{ "channelId": P, "threadId": T }` 都发往子区 `T`,视为同一目的地;写法不同的 Telegram 话题 id 同理。
|
||||||
|
|
||||||
| 字段 | 类型 | 必需 | 说明 |
|
| 字段 | 类型 | 必需 | 说明 |
|
||||||
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------- |
|
| ---------------- | -------- | ---- | ------------------------------------------------------------------------------------- |
|
||||||
| `groupId` | string | 是 | 路由所属[分组](./groups)的 id |
|
| `groupId` | string | 是 | 路由所属[分组](./groups)的 id |
|
||||||
| `fallback` | boolean | 否 | 为 `true` 时仅在本分组没有其他非 fallback 路由匹配时才触发;其过滤器仍会生效 |
|
| `fallback` | boolean | 否 | 为 `true` 时仅在本分组没有其他非 fallback 路由匹配时才触发;其过滤器仍会生效 |
|
||||||
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估本分组的后续路由 |
|
| `stop` | boolean | 否 | 为 `true` 且该路由匹配时,不再评估本分组的后续路由 |
|
||||||
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id;仅对 Discord 目标生效 |
|
| `discordRoleIds` | string[] | 否 | 路由触发时要提醒的 Discord 身份组 id(最多 50 个);仅对 Discord 目标生效 |
|
||||||
| `ast` | object | 否 | 布尔过滤器树(`{all:[...]}` / `{any:[...]}` / `{not:{...}}`);存在时优先于 `filters` |
|
| `ast` | object | 否 | 布尔过滤器树(`{all:[...]}` / `{any:[...]}` / `{not:{...}}`);存在时优先于 `filters` |
|
||||||
|
|
||||||
## 路由顺序
|
## 路由顺序
|
||||||
@@ -45,6 +51,10 @@
|
|||||||
|
|
||||||
**升级提示:** 如果现有配置依赖某个分组的 `stop` 阻止其他分组的路由执行,或依赖某个分组的普通路由匹配来抑制其他分组的兜底路由发送,请在升级时检查现有路由。这些行为现在仅在同一分组内生效,因此其他分组的路由可能开始发送消息。请将需要共同排他的路由移至同一分组,再检查它们的顺序及 `stop` / `fallback` 设置。
|
**升级提示:** 如果现有配置依赖某个分组的 `stop` 阻止其他分组的路由执行,或依赖某个分组的普通路由匹配来抑制其他分组的兜底路由发送,请在升级时检查现有路由。这些行为现在仅在同一分组内生效,因此其他分组的路由可能开始发送消息。请将需要共同排他的路由移至同一分组,再检查它们的顺序及 `stop` / `fallback` 设置。
|
||||||
|
|
||||||
|
## 不可读的路由
|
||||||
|
|
||||||
|
存储中无法读取的路由——JSON 损坏、字段结构错误、过滤条件不合法,或匹配器无法编译的模式(例如为其他引擎写的前瞻正则)——绝不会被当作"不匹配"。该分组的投递会可见地失败并重试(其他分组不受影响),`GET /admin/api/groups/:id/routes` 会返回 `unreadable: true`。存在这类行时,保存该分组的路由会被拒绝,避免它在看不见的情况下被删除;如需有意替换,保存时带上 `discardUnreadable: true`。
|
||||||
|
|
||||||
## Discord 身份组提醒
|
## Discord 身份组提醒
|
||||||
|
|
||||||
在路由上设置 `discordRoleIds` 可在其触发时提醒一个或多个 Discord 身份组(角色)。提醒(`<@&roleId>`)会加在路由所有 **Discord** 目标的消息内容前;Telegram 目标忽略该字段。只有当机器人拥有 `Mention Everyone` 权限(或身份组标记为可提及)且能看到该身份组时,提醒才会触发通知。
|
在路由上设置 `discordRoleIds` 可在其触发时提醒一个或多个 Discord 身份组(角色)。提醒(`<@&roleId>`)会加在路由所有 **Discord** 目标的消息内容前;Telegram 目标忽略该字段。只有当机器人拥有 `Mention Everyone` 权限(或身份组标记为可提及)且能看到该身份组时,提醒才会触发通知。
|
||||||
@@ -79,13 +89,13 @@
|
|||||||
"filters": [
|
"filters": [
|
||||||
{ "type": "repo", "match": "myorg/backend" },
|
{ "type": "repo", "match": "myorg/backend" },
|
||||||
{ "type": "event", "match": "pull_request" },
|
{ "type": "event", "match": "pull_request" },
|
||||||
{ "type": "actor", "match": "[bot]", "exclude": true }
|
{ "type": "actor", "match": "*[bot]", "exclude": true }
|
||||||
],
|
],
|
||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"platform": "telegram",
|
"platform": "telegram",
|
||||||
"chatId": "-1001234567890",
|
"chatId": "-1001234567890",
|
||||||
"topicId": "9876543210"
|
"topicId": "42"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
+43
-27
@@ -5,57 +5,73 @@
|
|||||||
KV 只保留缓存数据和短期/临时状态。高频写入(webhook 去重、投递状态、消息追踪)存放在 D1,仅在 D1 不可用或未迁移时才回退到 KV(见[存储决策](#存储决策))。
|
KV 只保留缓存数据和短期/临时状态。高频写入(webhook 去重、投递状态、消息追踪)存放在 D1,仅在 D1 不可用或未迁移时才回退到 KV(见[存储决策](#存储决策))。
|
||||||
|
|
||||||
| 键模式 | 值 | TTL |
|
| 键模式 | 值 | TTL |
|
||||||
| ------------------------------------------ | ----------------------------------------------------------------------------- | ------------------ |
|
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
| `config:routes` | 路由配置缓存(D1 `d1_routes` 为权威数据源) | 1 小时 |
|
| `config:routes` / `config:groups` | 旧版(D1 之前)配置,仅在 D1 表为空时读取一次用于播种 | 永久 |
|
||||||
| `config:groups` | 分组配置缓存(D1 `d1_groups` 为权威数据源) | 1 小时 |
|
| `config:d1-seeded` | 标记 D1 已播种(已清空的 D1 不会被再次播种) | 永久 |
|
||||||
| `session:{id}` | 管理员会话 `{ userId, login }` | 7 天 |
|
| `session:{id}` | 管理员会话 `{ userId, login, loginTrusted }` | 1 天 |
|
||||||
| `token:{userId}` | `{ userId, accessToken, expiresAt, refreshToken? }` | 0.9 × Token 有效期 |
|
| `token:{userId}` | `{ userId, accessToken, expiresAt, live? }`(Token 可使用 10 小时) | 9 小时 |
|
||||||
| `token-reverse:{sha256}` | 用于按 Token 反查的用户 id | 0.9 × Token 有效期 |
|
| `token-reverse:{sha256}` | 用于按 Token 反查的用户 id | 9 小时 |
|
||||||
| `state:{hex}` | `{ redirectTo, expiresAt, discordUserId?, telegramUserId?, telegramChatId? }` | 600 秒 |
|
| `state:{hex}` | `{ redirectTo, expiresAt, link? }`(`link`:机器人 `/gh login` 要绑定的聊天账号) | 600 秒 |
|
||||||
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note? }` | 7 天 |
|
| `link:{nonce}` | 等待 GitHub 用户确认的机器人账号绑定 | 600 秒 |
|
||||||
|
| `invite:{token}` | `{ groupId, role, expiresAt, createdBy, note?, groupInstance, issuer }` | 7 天 |
|
||||||
| `invite:group:{id}` | 每组的 Token 索引(保证邀请列表一致性) | 7 天 |
|
| `invite:group:{id}` | 每组的 Token 索引(保证邀请列表一致性) | 7 天 |
|
||||||
| `delivery:{provider}:{groupId}:{id}` | Webhook 投递去重回退(D1 `dedup_keys` 为主) | 7 天 |
|
| `invite:by-group:{id}:{token}` / `invite:by-instance:{instance}:{token}` | 每个邀请的列表标记(按分组 id 与签发分组的 instance),并发创建或改名中断时邀请也不会从列表中消失 | 邀请有效期 |
|
||||||
| `delivery-state:{provider}:{groupId}:{id}` | 队列投递状态回退(D1 `delivery_state` 为主) | 1 小时 |
|
| `login-owner:{login}` | 第一个使用该登录名的 GitHub 账号 id;之后用同名登录的其他账号只按 user id 匹配 | 永久 |
|
||||||
| `queue:payload:{provider}:{groupId}:{id}` | 暂存供队列消费者读取的超大 webhook 负载(R2 为主) | 1 小时 |
|
| `delivery:{provider}:{scope}:{id}` | Webhook 投递去重回退(D1 `dedup_keys` 为主);全局入口的 `scope` 为 `@global`,分组入口为 `@i:{instance}`(接收分组不可变的 instance) | 2~10 分钟 |
|
||||||
| `nonce:{nonce}` | 自定义 webhook 重放防护 nonce(一次性) | 600 秒 |
|
| `delivery-state:{provider}:{scope}:{id}` | 队列投递状态回退(D1 `delivery_state` 为主) | 7 天 |
|
||||||
| `tenant:{groupId}` | 分组 webhook secret(64 位 hex,控制台生成) | 永久 |
|
| `queue:payload:{provider}:{scope}:{id}:{uuid}` | 未绑定 R2 时暂存供队列消费者读取的超大 webhook 负载(每次入队一个键) | 4 天 |
|
||||||
| `msg:{routeId}:{key}:{target}` | 消息 id 追踪回退(D1 `message_tracking` 为主) | 1 天 |
|
| `tenant:{groupId}` / `tenant:i:{instance}` | 旧版分组 webhook secret,仅在密钥尚未存入 D1 分组行时作为回退读取;轮换或删除时清除 | 永久 |
|
||||||
| `cmd:guild:{id}` | 已注册命令的服务器 id(去重) | 永久 |
|
| `group:renamed:{oldId}` | 仅 KV 部署:分组改名后的新 id(有 D1 时该别名是改名事务中写入的 `dedup_keys` 行) | 4 天 |
|
||||||
| `cmd:registered:global` | 全局命令注册标记(去重) | 1 天 |
|
| `msg:{chain}:{platform}:{target}` | 消息追踪回退(D1 `message_tracking` 为主) | 30 天 |
|
||||||
| `config:discord-app-id` | 缓存的 Discord 应用 id | 永久 |
|
| `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}` | 叠加在英文之上的翻译覆盖 | 永久 |
|
| `i18n:{lang}` | 叠加在英文之上的翻译覆盖 | 永久 |
|
||||||
|
| `config:identity-migrated` | 仅 KV 部署:分组身份已由本服务器管理(一次性身份迁移已执行) | 永久 |
|
||||||
|
|
||||||
## D1 存储布局
|
## D1 存储布局
|
||||||
|
|
||||||
D1 数据库(`DB` 绑定,数据库 `webhooker`)保存配置、投递日志和高频临时状态的权威数据源:
|
D1 数据库(`DB` 绑定,数据库 `webhooker`)保存配置、投递日志和高频临时状态的权威数据源:
|
||||||
|
|
||||||
| 表 | 用途 |
|
| 表 | 用途 |
|
||||||
| ------------------ | ----------------------------------------------------------------------------- |
|
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `d1_groups` | 分组(权威配置,从旧版 KV `config:groups` 播种) |
|
| `d1_groups` | 分组(权威配置,从旧版 KV `config:groups` 播种)。每行还保存不会发给控制台的服务端字段:不可变的 `instance`、`legacyId` 以及分组 webhook 密钥 |
|
||||||
| `d1_routes` | 每组分组的路由(权威配置,从旧版 KV `config:routes` 播种) |
|
| `d1_routes` | 每组分组的路由(权威配置,从旧版 KV `config:routes` 播种) |
|
||||||
| `send_logs` | 每次分发尝试一行(路由 id、事件、目标、ok/error、耗时、错误码、详情) |
|
| `send_logs` | 每次分发尝试一行(路由 id、事件、目标、ok/error、耗时、错误码、详情) |
|
||||||
| `audit_logs` | 每次管理员操作一行(登录/登出、分组/路由/成员/邀请变更) |
|
| `audit_logs` | 每次管理员操作一行(登录/登出、分组/路由/成员/邀请变更) |
|
||||||
| `dedup_keys` | Webhook 投递去重(原子 `INSERT ... ON CONFLICT` UPSERT,键 + 过期时间) |
|
| `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`) |
|
| `delivery_state` | 队列投递状态(`pending`/`processing`/`delivered`/`retrying`/`failed`/`dead`);领取投递是一次条件 UPSERT(租约),两个消费者不会同时分发同一投递 |
|
||||||
| `message_tracking` | 原地更新用消息 id 追踪(`event_id` + `target_id` → `message_id`) |
|
| `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 命令使用 |
|
| `discord_links` | 映射 `discord_user_id` → `github_user_id`,供 `/gh` Discord 命令使用 |
|
||||||
| `telegram_links` | 映射 `telegram_user_id` → `github_user_id`,供 `/gh` Telegram 命令使用 |
|
| `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 存储布局
|
||||||
|
|
||||||
R2(`PAYLOAD` 绑定,bucket `webhooker-payloads`)存储对队列消息或 KV 来说过大的 webhook 负载:
|
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 只保存缓存和短期状态。
|
- **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 万行)。
|
- 这让 Workers 免费版的每事件 KV 写入趋近于零(每日 1000 次写):去重、投递状态和消息追踪改为写 D1 行(D1 免费版每日可写 10 万行)。
|
||||||
- R2 免费额度(10 GB-月存储、每月 100 万次 A 类操作)可以轻松承载负载暂存,不占用 KV 写配额。
|
- R2 免费额度(10 GB-月存储、每月 100 万次 A 类操作)可以轻松承载负载暂存,不占用 KV 写配额。
|
||||||
@@ -3,10 +3,10 @@
|
|||||||
WebHooker 通过定时触发器(`*/5 * * * *`,每 5 分钟)运行四个维护任务。它们只在部署后的 Worker 上运行(Cloudflare cron);本地 `wrangler dev` 可用 `wrangler dev --test-scheduled` 触发。
|
WebHooker 通过定时触发器(`*/5 * * * *`,每 5 分钟)运行四个维护任务。它们只在部署后的 Worker 上运行(Cloudflare cron);本地 `wrangler dev` 可用 `wrangler dev --test-scheduled` 触发。
|
||||||
|
|
||||||
| 任务 | 用途 |
|
| 任务 | 用途 |
|
||||||
| --------------- | ------------------------------------------------------------------------------------------------------------------- |
|
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `discord-sync` | 注册 Discord 斜杠/右键菜单命令:按服务器即时注册,并全局注册(24h 去重,约 1 小时传播) |
|
| `discord-sync` | 注册 Discord 斜杠/右键菜单命令:按服务器即时注册(每轮最多 30 次 API 调用,从上一轮停下的位置继续),并全局注册(约 1 小时传播);命令定义变化时重新注册 |
|
||||||
| `telegram-sync` | 调用 `setWebhook` 指向 `{BASE_URL}/telegram/webhook`(设置了 `TELEGRAM_WEBHOOK_SECRET` 时作为 `secret_token` 传入) |
|
| `telegram-sync` | 调用 `setWebhook` 指向 `{BASE_URL}/telegram/webhook`,以 `TELEGRAM_WEBHOOK_SECRET`(或由 `TELEGRAM_TOKEN` 派生的值)作为 `secret_token`——仅在注册内容变化时,以及每天一次 |
|
||||||
| `audit-prune` | 删除早于 `AUDIT_RETENTION_DAYS`(默认 90)天的 `audit_logs` 记录 |
|
| `audit-prune` | 删除早于 `AUDIT_RETENTION_DAYS`(默认 90)天的 `audit_logs` 记录 |
|
||||||
| `storage-prune` | 删除已过期的 `dedup_keys` 记录、超过 7 天的 `delivery_state` 记录和超过 30 天的 `message_tracking` 记录 |
|
| `storage-prune` | 删除已过期的 `dedup_keys` 记录、超过 7 天的 `delivery_state` 记录、超过 30 天的 `message_tracking` 记录以及遗留的 R2 负载 |
|
||||||
|
|
||||||
除任务用到的密钥(`DISCORD_TOKEN`、`DISCORD_APPLICATION_ID`、`TELEGRAM_TOKEN`、`BASE_URL`、`AUDIT_RETENTION_DAYS`)外无需其他配置。
|
除任务用到的密钥(`DISCORD_TOKEN`、`DISCORD_APPLICATION_ID`、`TELEGRAM_TOKEN`、`BASE_URL`、`AUDIT_RETENTION_DAYS`)外无需其他配置。
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- Every index also costs a D1 row write whenever its columns are written, so
|
||||||
|
-- only indexes whose reads would otherwise cost far more are added here:
|
||||||
|
-- delivery state changes a few times per delivery, the failure indexes are
|
||||||
|
-- written for failed sends only, and the audit index replaces another.
|
||||||
|
|
||||||
|
-- The storage-prune task (every 5 minutes) deletes delivery state by age:
|
||||||
|
-- an index on updated_at keeps it from scanning the whole table each run.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_delivery_state_updated_at ON delivery_state (updated_at);
|
||||||
|
|
||||||
|
-- The metrics page lists the latest failed sends: failures are rare, so
|
||||||
|
-- without these (partial, failures only) indexes the query walks every
|
||||||
|
-- successful row in time order before finding them.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_send_logs_failed_ts ON send_logs (ts DESC) WHERE ok = 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_send_logs_failed_group_ts ON send_logs (group_id, ts DESC) WHERE ok = 0;
|
||||||
|
|
||||||
|
-- A group's audit log is read newest first: (group_id, ts) serves it in order
|
||||||
|
-- (and every lookup by group_id), so the single-column index is replaced.
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_audit_group_ts ON audit_logs (group_id, ts DESC);
|
||||||
|
DROP INDEX IF EXISTS idx_audit_group;
|
||||||
+3
-1
@@ -50,10 +50,12 @@ export default defineNuxtConfig({
|
|||||||
},
|
},
|
||||||
devtools: { enabled: false },
|
devtools: { enabled: false },
|
||||||
runtimeConfig: {
|
runtimeConfig: {
|
||||||
// Overridable via NUXT_PUBLIC_DOCS_URL / NUXT_PUBLIC_REPO_URL.
|
// Overridable via NUXT_PUBLIC_DOCS_URL / NUXT_PUBLIC_REPO_URL /
|
||||||
|
// NUXT_PUBLIC_LEGAL_CONTACT.
|
||||||
public: {
|
public: {
|
||||||
docsUrl: "",
|
docsUrl: "",
|
||||||
repoUrl: "",
|
repoUrl: "",
|
||||||
|
legalContact: "",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
// The config console stays a client-side SPA (same behavior as the old
|
// The config console stays a client-side SPA (same behavior as the old
|
||||||
|
|||||||
+2
-1
@@ -8,7 +8,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "nuxt dev",
|
"dev": "nuxt dev",
|
||||||
"build": "nuxt build",
|
"build": "nuxt build",
|
||||||
"deploy": "wrangler deploy",
|
"deploy": "bun run db:migrate:prod && wrangler deploy",
|
||||||
"cf:dev": "nuxt build && wrangler dev",
|
"cf:dev": "nuxt build && wrangler dev",
|
||||||
"preview": "nuxt preview",
|
"preview": "nuxt preview",
|
||||||
"typecheck": "nuxt typecheck",
|
"typecheck": "nuxt typecheck",
|
||||||
@@ -29,6 +29,7 @@
|
|||||||
"markdown-it": "^15.0.0",
|
"markdown-it": "^15.0.0",
|
||||||
"nuxt": "^4.1.0",
|
"nuxt": "^4.1.0",
|
||||||
"octokit": "^4.1.0",
|
"octokit": "^4.1.0",
|
||||||
|
"re2js": "^2.8.8",
|
||||||
"valibot": "^1.4.2",
|
"valibot": "^1.4.2",
|
||||||
"vue": "^3.5.13"
|
"vue": "^3.5.13"
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -56,3 +56,16 @@ export function headersFrom(event: H3Event): Record<string, string> {
|
|||||||
});
|
});
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Largest body the bot callback routes read (each handler checks it again). */
|
||||||
|
export const MAX_CALLBACK_BODY = 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A body declared larger than `max` bytes: answered 413 before the route
|
||||||
|
* reads (and copies) it. Bodies without a declared length are still checked
|
||||||
|
* by the handler once read.
|
||||||
|
*/
|
||||||
|
export function declaresBodyOver(event: H3Event, max = MAX_CALLBACK_BODY): boolean {
|
||||||
|
const length = Number(event.headers.get("content-length"));
|
||||||
|
return Number.isFinite(length) && length > max;
|
||||||
|
}
|
||||||
+71
-50
@@ -1,19 +1,31 @@
|
|||||||
import type { Env, Config, Route } from "./types";
|
import type { Env, Config, Group, Route } from "./types";
|
||||||
import { log } from "./lib/log";
|
import {
|
||||||
import { migrateRoutes, validateRoutes } from "./config/schema";
|
createConfigStore,
|
||||||
import { d1ConfigStore, type ConfigStore } from "./storage/config-store";
|
kvConfigStore,
|
||||||
|
type ConfigStore,
|
||||||
|
type GuardedWrite,
|
||||||
|
type LoadOptions,
|
||||||
|
} from "./storage/config-store";
|
||||||
|
import { canUseD1 } from "./storage/d1";
|
||||||
|
|
||||||
const CONFIG_CACHE_TTL = 300_000;
|
|
||||||
const ROUTES_KEY = "config:routes";
|
|
||||||
let configCache: { config: Config; expiresAt: number } | null = null;
|
|
||||||
const configStores = new WeakMap<KVNamespace, ConfigStore>();
|
const configStores = new WeakMap<KVNamespace, ConfigStore>();
|
||||||
|
|
||||||
export function getConfigStore(kv: KVNamespace): ConfigStore | null {
|
/**
|
||||||
return configStores.get(kv) ?? null;
|
* The configuration store bound to this KV namespace. Every request, queue
|
||||||
|
* batch and scheduled task registers the D1-backed store first (see
|
||||||
|
* `initConfigStore`); a namespace that was never registered — a test, or a
|
||||||
|
* deployment without D1 — reads and writes the KV-only store.
|
||||||
|
*/
|
||||||
|
export function getConfigStore(kv: KVNamespace): ConfigStore {
|
||||||
|
return configStores.get(kv) ?? kvConfigStore(kv);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function initConfigStore(env: Env): ConfigStore {
|
export function initConfigStore(env: Env): ConfigStore {
|
||||||
return ensureStore(env);
|
const existing = configStores.get(env.KV);
|
||||||
|
if (existing && (existing.kind === "d1" || !canUseD1(env.DB))) return existing;
|
||||||
|
const store = createConfigStore(env.DB, env.KV);
|
||||||
|
configStores.set(env.KV, store);
|
||||||
|
return store;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resetConfigStore(kv?: KVNamespace): void {
|
export function resetConfigStore(kv?: KVNamespace): void {
|
||||||
@@ -23,52 +35,64 @@ export function resetConfigStore(kv?: KVNamespace): void {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureStore(env: Env): ConfigStore {
|
export async function loadRoutes(kv: KVNamespace, opts?: LoadOptions): Promise<Route[]> {
|
||||||
let store = configStores.get(env.KV);
|
return getConfigStore(kv).loadRoutes(opts);
|
||||||
if (!store) {
|
|
||||||
store = d1ConfigStore(env.DB, env.KV);
|
|
||||||
configStores.set(env.KV, store);
|
|
||||||
}
|
|
||||||
return store;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function loadRoutes(kv: KVNamespace): Promise<Route[]> {
|
|
||||||
const store = configStores.get(kv);
|
|
||||||
if (store) return store.loadRoutes();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stored = await kv.get<Route[]>(ROUTES_KEY, "json");
|
|
||||||
if (stored) return validateRoutes(migrateRoutes(stored));
|
|
||||||
} catch (err) {
|
|
||||||
log.warn({ err }, "Failed to load routes from KV");
|
|
||||||
}
|
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveRoutes(kv: KVNamespace, routes: Route[]): Promise<void> {
|
export async function saveRoutes(kv: KVNamespace, routes: Route[]): Promise<void> {
|
||||||
const store = configStores.get(kv);
|
await getConfigStore(kv).saveRoutes(routes);
|
||||||
if (store) {
|
|
||||||
await store.saveRoutes(routes);
|
|
||||||
configCache = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await kv.put(ROUTES_KEY, JSON.stringify(routes));
|
|
||||||
configCache = null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function invalidateConfigCache(): void {
|
export async function saveGroupRoutes(
|
||||||
configCache = null;
|
kv: KVNamespace,
|
||||||
|
groupId: string,
|
||||||
|
routes: Route[],
|
||||||
|
opts?: GuardedWrite<Route[]>,
|
||||||
|
): Promise<Route[]> {
|
||||||
|
return getConfigStore(kv).saveGroupRoutes(groupId, routes, opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Drop every cached configuration snapshot held by this isolate. */
|
||||||
|
export function invalidateConfigCache(kv?: KVNamespace): void {
|
||||||
|
if (kv) configStores.get(kv)?.invalidateCache();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One group, read fresh (its row alone): see `ConfigStore.loadGroup`. */
|
||||||
|
export function loadGroupFresh(
|
||||||
|
env: Env,
|
||||||
|
id: string,
|
||||||
|
): Promise<{ group: Group | null; unreadable: boolean }> {
|
||||||
|
return initConfigStore(env).loadGroup(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration and groups of one consistent moment, for a dispatch that
|
||||||
|
* needs both (routes of a renamed group must never meet its old id, nor new
|
||||||
|
* targets meet stale source restrictions).
|
||||||
|
*/
|
||||||
|
export async function loadConfigSnapshot(
|
||||||
|
env: Env,
|
||||||
|
opts?: LoadOptions,
|
||||||
|
): Promise<{ config: Config; groups: Group[] }> {
|
||||||
|
const store = initConfigStore(env);
|
||||||
|
const { routes, groups, unreadable } = await store.loadSnapshot(opts);
|
||||||
|
const config = buildConfig(env, routes);
|
||||||
|
if (unreadable?.length) config.unreadableGroups = unreadable;
|
||||||
|
return { config, groups };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The configuration for one dispatch. Each call returns a fresh object with
|
||||||
|
* its own `routes` array, so a caller narrowing the routes (tenant scoping)
|
||||||
|
* can never leak that change into another request served by this isolate.
|
||||||
|
*/
|
||||||
export async function loadConfig(env: Env): Promise<Config> {
|
export async function loadConfig(env: Env): Promise<Config> {
|
||||||
if (configCache && Date.now() < configCache.expiresAt) {
|
initConfigStore(env);
|
||||||
return configCache.config;
|
return buildConfig(env, await loadRoutes(env.KV));
|
||||||
}
|
}
|
||||||
|
|
||||||
ensureStore(env);
|
function buildConfig(env: Env, routes: Route[]): Config {
|
||||||
const routes = await loadRoutes(env.KV);
|
return {
|
||||||
|
|
||||||
const config: Config = {
|
|
||||||
baseUrl: env.BASE_URL ?? "https://webhooker.example.workers.dev",
|
baseUrl: env.BASE_URL ?? "https://webhooker.example.workers.dev",
|
||||||
github: {
|
github: {
|
||||||
webhookSecret: env.GITHUB_WEBHOOK_SECRET,
|
webhookSecret: env.GITHUB_WEBHOOK_SECRET,
|
||||||
@@ -80,9 +104,6 @@ export async function loadConfig(env: Env): Promise<Config> {
|
|||||||
discord: {
|
discord: {
|
||||||
token: env.DISCORD_TOKEN ?? "",
|
token: env.DISCORD_TOKEN ?? "",
|
||||||
},
|
},
|
||||||
routes,
|
routes: [...routes],
|
||||||
};
|
};
|
||||||
|
|
||||||
configCache = { config, expiresAt: Date.now() + CONFIG_CACHE_TTL };
|
|
||||||
return config;
|
|
||||||
}
|
}
|
||||||
@@ -61,6 +61,7 @@ export const routeSchema = v.object({
|
|||||||
export const groupMemberSchema = v.object({
|
export const groupMemberSchema = v.object({
|
||||||
login: v.string(),
|
login: v.string(),
|
||||||
role: v.picklist(["owner", "admin", "viewer"]),
|
role: v.picklist(["owner", "admin", "viewer"]),
|
||||||
|
userId: v.optional(v.string()),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const forgeSourceSchema = v.object({
|
export const forgeSourceSchema = v.object({
|
||||||
@@ -77,6 +78,11 @@ export const groupSchema = v.object({
|
|||||||
owners: v.optional(v.array(v.string())),
|
owners: v.optional(v.array(v.string())),
|
||||||
providers: v.optional(v.array(v.picklist(["github", "gitea", "gitlab", "custom"]))),
|
providers: v.optional(v.array(v.picklist(["github", "gitea", "gitlab", "custom"]))),
|
||||||
installationId: v.optional(v.number()),
|
installationId: v.optional(v.number()),
|
||||||
|
isolated: v.optional(v.boolean()),
|
||||||
|
instance: v.optional(v.string()),
|
||||||
|
instanceBackfilled: v.optional(v.boolean()),
|
||||||
|
legacyId: v.optional(v.string()),
|
||||||
|
webhookSecret: v.optional(v.nullable(v.string())),
|
||||||
emoji: v.optional(v.boolean()),
|
emoji: v.optional(v.boolean()),
|
||||||
forgeSources: v.optional(v.array(forgeSourceSchema)),
|
forgeSources: v.optional(v.array(forgeSourceSchema)),
|
||||||
lang: v.optional(v.string()),
|
lang: v.optional(v.string()),
|
||||||
|
|||||||
+756
-227
File diff suppressed because it is too large.
Load diff
@@ -75,16 +75,44 @@ export const APP_COMMANDS = [
|
|||||||
{ name: MSG_CMD_DEL, type: COMMAND_TYPE.MESSAGE },
|
{ name: MSG_CMD_DEL, type: COMMAND_TYPE.MESSAGE },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
async function shortHash(text: string): Promise<string> {
|
||||||
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||||
|
return [...new Uint8Array(digest).slice(0, 8)]
|
||||||
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registration markers are kept per application (and guild) and hold the hash
|
||||||
|
* of the command definitions last registered there: another application, or
|
||||||
|
* definitions that differ from the registered ones — newer or rolled back —
|
||||||
|
* register again instead of being skipped.
|
||||||
|
*/
|
||||||
|
function commandsHash(): Promise<string> {
|
||||||
|
return shortHash(JSON.stringify(APP_COMMANDS));
|
||||||
|
}
|
||||||
|
|
||||||
|
const applicationIds = new Map<string, string>();
|
||||||
|
|
||||||
export async function getApplicationId(env: Env): Promise<string | null> {
|
export async function getApplicationId(env: Env): Promise<string | null> {
|
||||||
if (env.DISCORD_APPLICATION_ID) return env.DISCORD_APPLICATION_ID;
|
if (env.DISCORD_APPLICATION_ID) return env.DISCORD_APPLICATION_ID;
|
||||||
|
const token = env.DISCORD_TOKEN ?? "";
|
||||||
|
if (!token) return null;
|
||||||
|
// Cached per bot token: a token of another application never gets the
|
||||||
|
// id resolved for the previous one. Held in memory too (one KV read per
|
||||||
|
// isolate, not one per sync run).
|
||||||
|
const cacheKey = `config:discord-app-id:${await shortHash(token)}`;
|
||||||
|
const known = applicationIds.get(cacheKey);
|
||||||
|
if (known) return known;
|
||||||
try {
|
try {
|
||||||
const cached = await env.KV.get("config:discord-app-id");
|
const cached = await env.KV.get(cacheKey);
|
||||||
if (cached) return cached;
|
if (cached) {
|
||||||
|
applicationIds.set(cacheKey, cached);
|
||||||
|
return cached;
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// fall through to the API
|
// fall through to the API
|
||||||
}
|
}
|
||||||
const token = env.DISCORD_TOKEN ?? "";
|
|
||||||
if (!token) return null;
|
|
||||||
const res = await fetch(`${DISCORD_API}/oauth2/applications/@me`, {
|
const res = await fetch(`${DISCORD_API}/oauth2/applications/@me`, {
|
||||||
headers: { Authorization: `Bot ${token}` },
|
headers: { Authorization: `Bot ${token}` },
|
||||||
});
|
});
|
||||||
@@ -95,7 +123,8 @@ export async function getApplicationId(env: Env): Promise<string | null> {
|
|||||||
const app = (await res.json()) as { id?: string };
|
const app = (await res.json()) as { id?: string };
|
||||||
if (app.id) {
|
if (app.id) {
|
||||||
try {
|
try {
|
||||||
await env.KV.put("config:discord-app-id", app.id);
|
applicationIds.set(cacheKey, app.id);
|
||||||
|
await env.KV.put(cacheKey, app.id);
|
||||||
} catch {
|
} catch {
|
||||||
// cache is best-effort
|
// cache is best-effort
|
||||||
}
|
}
|
||||||
@@ -107,13 +136,15 @@ export async function getApplicationId(env: Env): Promise<string | null> {
|
|||||||
export async function registerGlobalCommands(env: Env): Promise<void> {
|
export async function registerGlobalCommands(env: Env): Promise<void> {
|
||||||
const token = env.DISCORD_TOKEN ?? "";
|
const token = env.DISCORD_TOKEN ?? "";
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
|
const appId = await getApplicationId(env);
|
||||||
|
if (!appId) return;
|
||||||
|
const marker = `cmd:registered:global:${appId}`;
|
||||||
|
const hash = await commandsHash();
|
||||||
try {
|
try {
|
||||||
if (await env.KV.get("cmd:registered:global")) return;
|
if ((await env.KV.get(marker)) === hash) return;
|
||||||
} catch {
|
} catch {
|
||||||
// fall through and register
|
// fall through and register
|
||||||
}
|
}
|
||||||
const appId = await getApplicationId(env);
|
|
||||||
if (!appId) return;
|
|
||||||
const res = await fetch(`${DISCORD_API}/applications/${appId}/commands`, {
|
const res = await fetch(`${DISCORD_API}/applications/${appId}/commands`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
||||||
@@ -121,7 +152,7 @@ export async function registerGlobalCommands(env: Env): Promise<void> {
|
|||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
try {
|
try {
|
||||||
await env.KV.put("cmd:registered:global", "1", { expirationTtl: 86400 });
|
await env.KV.put(marker, hash, { expirationTtl: 86400 });
|
||||||
} catch {
|
} catch {
|
||||||
// best-effort
|
// best-effort
|
||||||
}
|
}
|
||||||
@@ -132,30 +163,82 @@ export async function registerGlobalCommands(env: Env): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const GUILD_PAGE_SIZE = 200;
|
||||||
|
/**
|
||||||
|
* Discord calls one run makes for guild commands — pages listed and
|
||||||
|
* registrations together — well within a Worker invocation's subrequest
|
||||||
|
* limit (50 on the Free plan, shared with the run's other work). A run picks
|
||||||
|
* up where the previous one stopped, so a bot in any number of guilds keeps
|
||||||
|
* making progress.
|
||||||
|
*/
|
||||||
|
const GUILD_CALLS_PER_RUN = 30;
|
||||||
|
|
||||||
|
/** Per application: which guild holds which definitions, and where the walk is. */
|
||||||
|
interface GuildRecord {
|
||||||
|
hashes: Record<string, string>;
|
||||||
|
/** The guild after which the next run continues ("" from the start). */
|
||||||
|
after: string;
|
||||||
|
}
|
||||||
|
|
||||||
export async function syncGuildCommands(env: Env): Promise<void> {
|
export async function syncGuildCommands(env: Env): Promise<void> {
|
||||||
const token = env.DISCORD_TOKEN ?? "";
|
const token = env.DISCORD_TOKEN ?? "";
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
const appId = await getApplicationId(env);
|
const appId = await getApplicationId(env);
|
||||||
if (!appId) return;
|
if (!appId) return;
|
||||||
const res = await fetch(`${DISCORD_API}/users/@me/guilds`, {
|
const hash = await commandsHash();
|
||||||
headers: { Authorization: `Bot ${token}` },
|
// One KV record per application, read and written once per run (not one
|
||||||
});
|
// read per guild).
|
||||||
|
const recordKey = `cmd:guilds:${appId}`;
|
||||||
|
const stored = await env.KV.get<GuildRecord | Record<string, string>>(recordKey, "json").catch(
|
||||||
|
() => null,
|
||||||
|
);
|
||||||
|
const record: GuildRecord =
|
||||||
|
stored && typeof stored === "object" && "hashes" in stored
|
||||||
|
? {
|
||||||
|
hashes: { ...(stored as GuildRecord).hashes },
|
||||||
|
after: (stored as GuildRecord).after ?? "",
|
||||||
|
}
|
||||||
|
: { hashes: { ...((stored as Record<string, string> | null) ?? {}) }, after: "" };
|
||||||
|
const startedAfter = record.after;
|
||||||
|
let calls = GUILD_CALLS_PER_RUN;
|
||||||
|
let changed = false;
|
||||||
|
/** Stopped at a guild still to register: where to resume must be kept. */
|
||||||
|
let pending = false;
|
||||||
|
/** A guild needed registering this run (successful or not). */
|
||||||
|
let attempted = false;
|
||||||
|
walk: while (calls > 0) {
|
||||||
|
calls--;
|
||||||
|
const res = await fetch(
|
||||||
|
`${DISCORD_API}/users/@me/guilds?limit=${GUILD_PAGE_SIZE}${record.after ? `&after=${record.after}` : ""}`,
|
||||||
|
{ headers: { Authorization: `Bot ${token}` } },
|
||||||
|
);
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.text();
|
const err = await res.text();
|
||||||
log.warn({ status: res.status, err }, "Failed to list guilds");
|
log.warn({ status: res.status, err }, "Failed to list guilds");
|
||||||
return;
|
break;
|
||||||
}
|
}
|
||||||
const guilds = (await res.json()) as Array<{ id: string }>;
|
const page = (await res.json()) as Array<{ id: string }>;
|
||||||
for (const guild of guilds) {
|
for (const guild of page) {
|
||||||
|
if (record.hashes[guild.id] !== hash) {
|
||||||
|
attempted = true;
|
||||||
|
// Out of calls: the next run resumes at this guild.
|
||||||
|
if (calls <= 0) {
|
||||||
|
pending = true;
|
||||||
|
break walk;
|
||||||
|
}
|
||||||
|
calls--;
|
||||||
try {
|
try {
|
||||||
if (await env.KV.get(`cmd:guild:${guild.id}`)) continue;
|
const r = await fetch(
|
||||||
const r = await fetch(`${DISCORD_API}/applications/${appId}/guilds/${guild.id}/commands`, {
|
`${DISCORD_API}/applications/${appId}/guilds/${guild.id}/commands`,
|
||||||
|
{
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
headers: { Authorization: `Bot ${token}`, "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(APP_COMMANDS),
|
body: JSON.stringify(APP_COMMANDS),
|
||||||
});
|
},
|
||||||
|
);
|
||||||
if (r.ok) {
|
if (r.ok) {
|
||||||
await env.KV.put(`cmd:guild:${guild.id}`, "1");
|
record.hashes[guild.id] = hash;
|
||||||
|
changed = true;
|
||||||
log.info({ guildId: guild.id }, "Registered guild application commands");
|
log.info({ guildId: guild.id }, "Registered guild application commands");
|
||||||
} else {
|
} else {
|
||||||
const err = await r.text();
|
const err = await r.text();
|
||||||
@@ -165,6 +248,26 @@ export async function syncGuildCommands(env: Env): Promise<void> {
|
|||||||
log.warn({ guildId: guild.id, err: String(err) }, "Command registration failed");
|
log.warn({ guildId: guild.id, err: String(err) }, "Command registration failed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
record.after = guild.id;
|
||||||
|
}
|
||||||
|
if (page.length < GUILD_PAGE_SIZE) {
|
||||||
|
// The end of the list: the next run starts over (picking up guilds
|
||||||
|
// joined meanwhile, and redoing ones whose registration failed).
|
||||||
|
record.after = "";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Out of calls right after a full page, with work found on the way: the
|
||||||
|
// walk must resume past it (or the guilds after it would never be reached).
|
||||||
|
if (calls <= 0 && record.after !== "" && attempted) pending = true;
|
||||||
|
// Written only when something changed — a registration, a walk stopped
|
||||||
|
// with work left, or the cursor reset after one: a run that only checked
|
||||||
|
// writes nothing (KV writes are scarce; this runs every few minutes).
|
||||||
|
if (changed || pending || (record.after === "" && startedAfter !== "")) {
|
||||||
|
await env.KV.put(recordKey, JSON.stringify(record)).catch((err: unknown) =>
|
||||||
|
log.warn({ err: String(err) }, "Failed to record guild command registrations"),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function syncCommands(env: Env): Promise<void> {
|
export async function syncCommands(env: Env): Promise<void> {
|
||||||
|
|||||||
@@ -12,7 +12,13 @@ export class DiscordDriver implements PlatformDriver {
|
|||||||
return { ok: false, error: "target.channelId is required", errorCode: "NO_TARGET" };
|
return { ok: false, error: "target.channelId is required", errorCode: "NO_TARGET" };
|
||||||
}
|
}
|
||||||
const token = env.DISCORD_TOKEN ?? "";
|
const token = env.DISCORD_TOKEN ?? "";
|
||||||
return sendMessage(token, channelId, renderNeutralMessage(message), target.threadId);
|
return sendMessage(
|
||||||
|
token,
|
||||||
|
channelId,
|
||||||
|
renderNeutralMessage(message),
|
||||||
|
target.threadId,
|
||||||
|
message.sendKey,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async edit(
|
async edit(
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
closePullRequestAsUser,
|
closePullRequestAsUser,
|
||||||
} from "../../github/oauth";
|
} from "../../github/oauth";
|
||||||
import { getDiscordLink, removeDiscordLink } from "../../github/store";
|
import { getDiscordLink, removeDiscordLink } from "../../github/store";
|
||||||
|
import { idempotencyStore } from "../../lib/idempotency";
|
||||||
import type { Env } from "../../types";
|
import type { Env } from "../../types";
|
||||||
import { MSG_CMD_ADD, MSG_CMD_EDIT, MSG_CMD_DEL } from "./commands";
|
import { MSG_CMD_ADD, MSG_CMD_EDIT, MSG_CMD_DEL } from "./commands";
|
||||||
|
|
||||||
@@ -22,16 +23,84 @@ const EPHEMERAL = 64;
|
|||||||
|
|
||||||
// Modal custom_id encodings (delimiter '|' never appears in owner/repo).
|
// Modal custom_id encodings (delimiter '|' never appears in owner/repo).
|
||||||
const MODAL_ADD = "ghc|add|"; // ghc|add|owner|repo|issueNumber
|
const MODAL_ADD = "ghc|add|"; // ghc|add|owner|repo|issueNumber
|
||||||
const MODAL_EDIT = "ghc|edit|"; // ghc|edit|owner|repo|commentId
|
const MODAL_EDIT = "ghc|edit|"; // ghc|edit|owner|repo|commentId (read for older modals)
|
||||||
|
/** ghc|ed|owner|repo|commentId|base: an edit that remembers the text it was opened on. */
|
||||||
|
const MODAL_EDIT_BASE = "ghc|ed|";
|
||||||
|
/**
|
||||||
|
* ghc|m|{context id}: the context kept in KV instead — only when the custom
|
||||||
|
* id would pass Discord's 100 characters (a long owner/repo). KV writes are
|
||||||
|
* scarce (Workers Free), so the context travels in the custom id whenever
|
||||||
|
* it fits.
|
||||||
|
*/
|
||||||
|
const MODAL_CTX = "ghc|m|";
|
||||||
|
const MAX_CUSTOM_ID = 100;
|
||||||
|
/** Hex characters of the comment hash an edit modal remembers. */
|
||||||
|
const BASE_HASH_LENGTH = 16;
|
||||||
|
const MODAL_CTX_TTL_SECONDS = 86400;
|
||||||
|
|
||||||
|
interface ModalContext {
|
||||||
|
op: "add" | "edit";
|
||||||
|
owner: string;
|
||||||
|
repo: string;
|
||||||
|
/** Issue/PR number (add) or comment id (edit). */
|
||||||
|
ref: string;
|
||||||
|
/** SHA-256 (hex, possibly shortened) of the comment as the edit modal showed it. */
|
||||||
|
base?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sha256Hex(text: string): Promise<string> {
|
||||||
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
|
||||||
|
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
async function modalCustomId(env: Env, context: ModalContext): Promise<string> {
|
||||||
|
const inline =
|
||||||
|
context.op === "add"
|
||||||
|
? `${MODAL_ADD}${context.owner}|${context.repo}|${context.ref}`
|
||||||
|
: `${MODAL_EDIT_BASE}${context.owner}|${context.repo}|${context.ref}|${context.base ?? ""}`;
|
||||||
|
if (inline.length <= MAX_CUSTOM_ID) return inline;
|
||||||
|
const contextId = crypto.randomUUID().replace(/-/g, "");
|
||||||
|
await env.KV.put(`discord-modal:${contextId}`, JSON.stringify(context), {
|
||||||
|
expirationTtl: MODAL_CTX_TTL_SECONDS,
|
||||||
|
});
|
||||||
|
return `${MODAL_CTX}${contextId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function modalContext(env: Env, customId: string): Promise<ModalContext | null> {
|
||||||
|
if (customId.startsWith(MODAL_CTX)) {
|
||||||
|
return env.KV.get<ModalContext>(`discord-modal:${customId.slice(MODAL_CTX.length)}`, "json");
|
||||||
|
}
|
||||||
|
if (customId.startsWith(MODAL_EDIT_BASE)) {
|
||||||
|
const rest = customId.slice(MODAL_EDIT_BASE.length);
|
||||||
|
const cut = rest.lastIndexOf("|");
|
||||||
|
const [owner, repo, ref] = splitThree(rest.slice(0, cut));
|
||||||
|
const base = rest.slice(cut + 1);
|
||||||
|
return cut > 0 && owner && repo && ref ? { op: "edit", owner, repo, ref, base } : null;
|
||||||
|
}
|
||||||
|
for (const [prefix, op] of [
|
||||||
|
[MODAL_ADD, "add"],
|
||||||
|
[MODAL_EDIT, "edit"],
|
||||||
|
] as const) {
|
||||||
|
if (!customId.startsWith(prefix)) continue;
|
||||||
|
const [owner, repo, ref] = splitThree(customId.slice(prefix.length));
|
||||||
|
return owner && repo && ref ? { op, owner, repo, ref } : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
// PR notification button custom_id encodings.
|
// PR notification button custom_id encodings.
|
||||||
const BTN_MERGE = "ghpr|merge|"; // ghpr|merge|owner|repo|pullNumber
|
const BTN_MERGE = "ghpr|merge|"; // ghpr|merge|owner|repo|pullNumber
|
||||||
const BTN_CLOSE = "ghpr|close|"; // ghpr|close|owner|repo|pullNumber
|
const BTN_CLOSE = "ghpr|close|"; // ghpr|close|owner|repo|pullNumber
|
||||||
|
|
||||||
// Comment link (has the comment id); check this BEFORE the plain issue regex.
|
// Comment link (has the comment id); check this BEFORE the plain issue regex.
|
||||||
|
// Both only accept github.com itself (not e.g. `evilgithub.com`): the actions
|
||||||
|
// run against the GitHub API.
|
||||||
const GITHUB_COMMENT_RE =
|
const GITHUB_COMMENT_RE =
|
||||||
/github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/\d+#issuecomment-(\d+)/;
|
/https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/\d+#issuecomment-(\d+)/;
|
||||||
const GITHUB_ISSUE_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
const GITHUB_ISSUE_RE =
|
||||||
|
/https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
||||||
|
/** Discord caps a text input's value (and max_length) at 4000 characters. */
|
||||||
|
const MAX_MODAL_TEXT = 4000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Split a pipe-delimited custom-id suffix into [owner, repo, number]. The
|
* Split a pipe-delimited custom-id suffix into [owner, repo, number]. The
|
||||||
@@ -46,13 +115,23 @@ function splitThree(rest: string): [string, string, string] {
|
|||||||
return [owner ?? "", repo ?? "", number ?? ""];
|
return [owner ?? "", repo ?? "", number ?? ""];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface DiscordUser {
|
||||||
|
id?: string;
|
||||||
|
username?: string;
|
||||||
|
global_name?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
interface Interaction {
|
interface Interaction {
|
||||||
id: string;
|
id: string;
|
||||||
|
/** The application the interaction belongs to (follow-up webhooks use it). */
|
||||||
|
application_id?: string;
|
||||||
token: string;
|
token: string;
|
||||||
type: number;
|
type: number;
|
||||||
channel_id?: string;
|
channel_id?: string;
|
||||||
member?: { user?: { id?: string } };
|
member?: { user?: DiscordUser };
|
||||||
user?: { id?: string };
|
user?: DiscordUser;
|
||||||
|
/** The message a component (button) is attached to. */
|
||||||
|
message?: { id?: string };
|
||||||
data?: Record<string, unknown>;
|
data?: Record<string, unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,6 +225,15 @@ export async function handleInteractionRequest(request: Request, env: Env): Prom
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Discord does not redeliver interactions, but a replayed request (same
|
||||||
|
// signed body within the timestamp window) must not run its action twice.
|
||||||
|
if (
|
||||||
|
interaction.id &&
|
||||||
|
!(await idempotencyStore(env.DB, env.KV).claim(`bot:discord:${interaction.id}`, 3600))
|
||||||
|
) {
|
||||||
|
return new Response(null, { status: 202 });
|
||||||
|
}
|
||||||
|
|
||||||
// Handle the interaction via the callback webhook; respond 202 with no body
|
// Handle the interaction via the callback webhook; respond 202 with no body
|
||||||
// as required for interactions received over the HTTP endpoint.
|
// as required for interactions received over the HTTP endpoint.
|
||||||
await handleInteraction(env, interaction).catch((err) =>
|
await handleInteraction(env, interaction).catch((err) =>
|
||||||
@@ -155,19 +243,22 @@ export async function handleInteractionRequest(request: Request, env: Env): Prom
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleInteraction(env: Env, interaction: Interaction): Promise<void> {
|
async function handleInteraction(env: Env, interaction: Interaction): Promise<void> {
|
||||||
const userId = interaction.member?.user?.id ?? interaction.user?.id ?? null;
|
const user = interaction.member?.user ?? interaction.user;
|
||||||
|
const userId = user?.id ?? null;
|
||||||
const id = interaction.id;
|
const id = interaction.id;
|
||||||
const token = interaction.token;
|
const token = interaction.token;
|
||||||
|
const applicationId = interaction.application_id ?? env.DISCORD_APPLICATION_ID ?? "";
|
||||||
|
|
||||||
if (interaction.type === INTERACTION_TYPE.BUTTON) {
|
if (interaction.type === INTERACTION_TYPE.BUTTON) {
|
||||||
const data = interaction.data as { custom_id?: string; message?: { id?: string } };
|
const data = interaction.data as { custom_id?: string };
|
||||||
return handleButton(
|
return handleButton(
|
||||||
env,
|
env,
|
||||||
id,
|
id,
|
||||||
token,
|
token,
|
||||||
|
applicationId,
|
||||||
userId,
|
userId,
|
||||||
interaction.channel_id,
|
interaction.channel_id,
|
||||||
data.message?.id,
|
interaction.message?.id,
|
||||||
data.custom_id,
|
data.custom_id,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -203,13 +294,15 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
|||||||
if (!op) return;
|
if (!op) return;
|
||||||
const target = data.target_id ? data.resolved?.messages?.[data.target_id] : undefined;
|
const target = data.target_id ? data.resolved?.messages?.[data.target_id] : undefined;
|
||||||
const source = target?.embeds?.[0]?.url ?? target?.content ?? "";
|
const source = target?.embeds?.[0]?.url ?? target?.content ?? "";
|
||||||
return commentOp(env, id, token, userId, op, source);
|
return commentOp(env, id, token, applicationId, userId, op, source);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Slash command /gh ...
|
// Slash command /gh ...
|
||||||
if (data.name === "gh" && data.type === COMMAND_TYPE.CHAT_INPUT) {
|
if (data.name === "gh" && data.type === COMMAND_TYPE.CHAT_INPUT) {
|
||||||
const top = data.options?.[0];
|
const top = data.options?.[0];
|
||||||
if (top?.name === "login") return cmdLogin(env, id, token, userId);
|
if (top?.name === "login") {
|
||||||
|
return cmdLogin(env, id, token, userId, user?.global_name || user?.username);
|
||||||
|
}
|
||||||
if (top?.name === "logout") return cmdLogout(env, id, token, userId);
|
if (top?.name === "logout") return cmdLogout(env, id, token, userId);
|
||||||
if (top?.name === "comment") {
|
if (top?.name === "comment") {
|
||||||
const sub = top.options?.[0];
|
const sub = top.options?.[0];
|
||||||
@@ -223,7 +316,7 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
|||||||
: null;
|
: null;
|
||||||
if (!op) return;
|
if (!op) return;
|
||||||
const link = sub?.options?.find((o) => o.name === "link")?.value ?? "";
|
const link = sub?.options?.find((o) => o.name === "link")?.value ?? "";
|
||||||
return commentOp(env, id, token, userId, op, link);
|
return commentOp(env, id, token, applicationId, userId, op, link);
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -231,7 +324,7 @@ async function handleInteraction(env: Env, interaction: Interaction): Promise<vo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (interaction.type === INTERACTION_TYPE.MODAL_SUBMIT) {
|
if (interaction.type === INTERACTION_TYPE.MODAL_SUBMIT) {
|
||||||
return modalSubmit(env, id, token, userId, interaction.data);
|
return modalSubmit(env, id, token, applicationId, userId, interaction.data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -243,12 +336,13 @@ async function respond(env: Env, id: string, token: string, content: string): Pr
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Answer an interaction; whether Discord accepted the answer. */
|
||||||
async function interactionCallback(
|
async function interactionCallback(
|
||||||
env: Env,
|
env: Env,
|
||||||
id: string,
|
id: string,
|
||||||
token: string,
|
token: string,
|
||||||
body: unknown,
|
body: unknown,
|
||||||
): Promise<void> {
|
): Promise<boolean> {
|
||||||
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/callback`, {
|
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/callback`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
@@ -258,11 +352,23 @@ async function interactionCallback(
|
|||||||
const err = await res.text();
|
const err = await res.text();
|
||||||
log.warn({ status: res.status, err }, "Interaction callback failed");
|
log.warn({ status: res.status, err }, "Interaction callback failed");
|
||||||
}
|
}
|
||||||
|
return res.ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Replace the deferred (ephemeral) response body with the final result. */
|
/**
|
||||||
async function updateOriginal(env: Env, id: string, token: string, content: string): Promise<void> {
|
* Replace the deferred (ephemeral) response body with the final result. The
|
||||||
const res = await fetch(`${DISCORD_API}/interactions/${id}/${token}/messages/@original`, {
|
* original response is edited through the application's follow-up webhook.
|
||||||
|
*/
|
||||||
|
async function updateOriginal(
|
||||||
|
applicationId: string,
|
||||||
|
token: string,
|
||||||
|
content: string,
|
||||||
|
): Promise<void> {
|
||||||
|
if (!applicationId) {
|
||||||
|
log.warn("Cannot update interaction response: application id unknown");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const res = await fetch(`${DISCORD_API}/webhooks/${applicationId}/${token}/messages/@original`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ content }),
|
body: JSON.stringify({ content }),
|
||||||
@@ -273,6 +379,35 @@ async function updateOriginal(env: Env, id: string, token: string, content: stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Acknowledge first (deferred, ephemeral), then run the GitHub action and
|
||||||
|
* show its outcome: Discord fails an interaction not answered within 3
|
||||||
|
* seconds, and a slow GitHub call must not leave a done action looking failed
|
||||||
|
* (the user would submit it again).
|
||||||
|
*/
|
||||||
|
async function deferThen(
|
||||||
|
env: Env,
|
||||||
|
id: string,
|
||||||
|
token: string,
|
||||||
|
applicationId: string,
|
||||||
|
work: () => Promise<string>,
|
||||||
|
): Promise<void> {
|
||||||
|
// Not acknowledged: Discord shows the interaction as failed, so acting on
|
||||||
|
// GitHub now would leave a done action looking failed (and resubmitted).
|
||||||
|
const acked = await interactionCallback(env, id, token, {
|
||||||
|
type: CALLBACK_TYPE.DEFERRED_MESSAGE,
|
||||||
|
data: { flags: EPHEMERAL },
|
||||||
|
});
|
||||||
|
if (!acked) return;
|
||||||
|
let content: string;
|
||||||
|
try {
|
||||||
|
content = await work();
|
||||||
|
} catch (err) {
|
||||||
|
content = errText(err);
|
||||||
|
}
|
||||||
|
await updateOriginal(applicationId, token, content);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* PR notification buttons: merge or close the PR as the clicker's linked
|
* PR notification buttons: merge or close the PR as the clicker's linked
|
||||||
* GitHub account. The clicker must have run `/gh login` first.
|
* GitHub account. The clicker must have run `/gh login` first.
|
||||||
@@ -281,6 +416,7 @@ async function handleButton(
|
|||||||
env: Env,
|
env: Env,
|
||||||
id: string,
|
id: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
applicationId: string,
|
||||||
userId: string | null,
|
userId: string | null,
|
||||||
channelId: string | undefined,
|
channelId: string | undefined,
|
||||||
messageId: string | undefined,
|
messageId: string | undefined,
|
||||||
@@ -308,17 +444,18 @@ async function handleButton(
|
|||||||
if (!owner || !repo || !number) return;
|
if (!owner || !repo || !number) return;
|
||||||
|
|
||||||
// Acknowledge first (deferred, ephemeral) so the clicker sees a spinner
|
// Acknowledge first (deferred, ephemeral) so the clicker sees a spinner
|
||||||
// while the GitHub API call runs.
|
// while the GitHub API call runs; unacknowledged, nothing is done.
|
||||||
await interactionCallback(env, id, token, {
|
const acked = await interactionCallback(env, id, token, {
|
||||||
type: CALLBACK_TYPE.DEFERRED_MESSAGE,
|
type: CALLBACK_TYPE.DEFERRED_MESSAGE,
|
||||||
data: { flags: EPHEMERAL },
|
data: { flags: EPHEMERAL },
|
||||||
});
|
});
|
||||||
|
if (!acked) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (op === "merge") {
|
if (op === "merge") {
|
||||||
await mergePullRequestAsUser(env.KV, githubUserId, owner, repo, Number(number));
|
await mergePullRequestAsUser(env, githubUserId, owner, repo, Number(number));
|
||||||
} else {
|
} else {
|
||||||
await closePullRequestAsUser(env.KV, githubUserId, owner, repo, Number(number));
|
await closePullRequestAsUser(env, githubUserId, owner, repo, Number(number));
|
||||||
}
|
}
|
||||||
// Remove the buttons from the notification so nobody double-clicks.
|
// Remove the buttons from the notification so nobody double-clicks.
|
||||||
if (channelId && messageId) {
|
if (channelId && messageId) {
|
||||||
@@ -332,13 +469,19 @@ async function handleButton(
|
|||||||
}).catch((err) => log.warn({ err: String(err) }, "Failed to strip PR buttons"));
|
}).catch((err) => log.warn({ err: String(err) }, "Failed to strip PR buttons"));
|
||||||
}
|
}
|
||||||
const label = op === "merge" ? "合并" : "关闭";
|
const label = op === "merge" ? "合并" : "关闭";
|
||||||
await updateOriginal(env, id, token, `✅ 已${label} PR ${owner}/${repo}#${number}`);
|
await updateOriginal(applicationId, token, `✅ 已${label} PR ${owner}/${repo}#${number}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
await updateOriginal(env, id, token, errText(err));
|
await updateOriginal(applicationId, token, errText(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cmdLogin(env: Env, id: string, token: string, userId: string | null): Promise<void> {
|
async function cmdLogin(
|
||||||
|
env: Env,
|
||||||
|
id: string,
|
||||||
|
token: string,
|
||||||
|
userId: string | null,
|
||||||
|
name: string | undefined,
|
||||||
|
): Promise<void> {
|
||||||
if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。");
|
if (!userId) return respond(env, id, token, "无法识别你的 Discord 账号。");
|
||||||
const clientId = env.GITHUB_CLIENT_ID;
|
const clientId = env.GITHUB_CLIENT_ID;
|
||||||
if (!clientId) return respond(env, id, token, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。");
|
if (!clientId) return respond(env, id, token, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。");
|
||||||
@@ -346,7 +489,11 @@ async function cmdLogin(env: Env, id: string, token: string, userId: string | nu
|
|||||||
const state = crypto.randomUUID().replace(/-/g, "");
|
const state = crypto.randomUUID().replace(/-/g, "");
|
||||||
await env.KV.put(
|
await env.KV.put(
|
||||||
`state:${state}`,
|
`state:${state}`,
|
||||||
JSON.stringify({ redirectTo: "/", discordUserId: userId, expiresAt: Date.now() + 600_000 }),
|
JSON.stringify({
|
||||||
|
redirectTo: "/",
|
||||||
|
link: { platform: "discord", userId, name },
|
||||||
|
expiresAt: Date.now() + 600_000,
|
||||||
|
}),
|
||||||
{ expirationTtl: 600 },
|
{ expirationTtl: 600 },
|
||||||
);
|
);
|
||||||
const url = getOAuthURL(clientId, state);
|
const url = getOAuthURL(clientId, state);
|
||||||
@@ -386,6 +533,7 @@ async function commentOp(
|
|||||||
env: Env,
|
env: Env,
|
||||||
id: string,
|
id: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
applicationId: string,
|
||||||
userId: string | null,
|
userId: string | null,
|
||||||
op: "add" | "edit" | "del",
|
op: "add" | "edit" | "del",
|
||||||
source: string,
|
source: string,
|
||||||
@@ -409,7 +557,7 @@ async function commentOp(
|
|||||||
env,
|
env,
|
||||||
id,
|
id,
|
||||||
token,
|
token,
|
||||||
`${MODAL_ADD}${m[1]}|${m[2]}|${m[3]}`,
|
await modalCustomId(env, { op: "add", owner: m[1]!, repo: m[2]!, ref: m[3]! }),
|
||||||
`评论 ${m[1]}/${m[2]}#${m[3]}`,
|
`评论 ${m[1]}/${m[2]}#${m[3]}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -427,27 +575,41 @@ async function commentOp(
|
|||||||
const [, owner, repo, commentId] = m;
|
const [, owner, repo, commentId] = m;
|
||||||
|
|
||||||
if (op === "del") {
|
if (op === "del") {
|
||||||
try {
|
return deferThen(env, id, token, applicationId, async () => {
|
||||||
await deleteCommentAsUser(env.KV, githubUserId, owner!, repo!, Number(commentId));
|
await deleteCommentAsUser(env, githubUserId, owner!, repo!, Number(commentId));
|
||||||
return respond(env, id, token, `已删除评论 ${owner}/${repo}#issuecomment-${commentId}。`);
|
return `已删除评论 ${owner}/${repo}#issuecomment-${commentId}。`;
|
||||||
} catch (err) {
|
});
|
||||||
return respond(env, id, token, errText(err));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// edit: fetch current body to prefill the modal.
|
// edit: fetch current body to prefill the modal.
|
||||||
let prefill = "";
|
let prefill = "";
|
||||||
try {
|
try {
|
||||||
const { body } = await getCommentAsUser(env.KV, githubUserId, owner!, repo!, Number(commentId));
|
const { body } = await getCommentAsUser(env, githubUserId, owner!, repo!, Number(commentId));
|
||||||
prefill = body;
|
prefill = body;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return respond(env, id, token, errText(err));
|
return respond(env, id, token, errText(err));
|
||||||
}
|
}
|
||||||
|
// The modal can only hold part of a longer comment, and saving it would
|
||||||
|
// replace the whole comment with that part: such comments are edited on GitHub.
|
||||||
|
if (prefill.length > MAX_MODAL_TEXT) {
|
||||||
|
return respond(
|
||||||
|
env,
|
||||||
|
id,
|
||||||
|
token,
|
||||||
|
`这条评论超过 ${MAX_MODAL_TEXT} 字,无法在 Discord 中完整编辑,请到 GitHub 上编辑:${m[0]}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
return openCommentModal(
|
return openCommentModal(
|
||||||
env,
|
env,
|
||||||
id,
|
id,
|
||||||
token,
|
token,
|
||||||
`${MODAL_EDIT}${owner}|${repo}|${commentId}`,
|
await modalCustomId(env, {
|
||||||
|
op: "edit",
|
||||||
|
owner: owner!,
|
||||||
|
repo: repo!,
|
||||||
|
ref: commentId!,
|
||||||
|
base: (await sha256Hex(prefill)).slice(0, BASE_HASH_LENGTH),
|
||||||
|
}),
|
||||||
`编辑评论 #${commentId}`,
|
`编辑评论 #${commentId}`,
|
||||||
prefill,
|
prefill,
|
||||||
);
|
);
|
||||||
@@ -477,8 +639,8 @@ async function openCommentModal(
|
|||||||
label: "评论内容",
|
label: "评论内容",
|
||||||
style: 2,
|
style: 2,
|
||||||
required: true,
|
required: true,
|
||||||
max_length: 2000,
|
max_length: MAX_MODAL_TEXT,
|
||||||
value: prefill.slice(0, 2000) || undefined,
|
value: prefill || undefined,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -491,6 +653,7 @@ async function modalSubmit(
|
|||||||
env: Env,
|
env: Env,
|
||||||
id: string,
|
id: string,
|
||||||
token: string,
|
token: string,
|
||||||
|
applicationId: string,
|
||||||
userId: string | null,
|
userId: string | null,
|
||||||
data: unknown,
|
data: unknown,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -501,51 +664,47 @@ async function modalSubmit(
|
|||||||
const customId = d.custom_id;
|
const customId = d.custom_id;
|
||||||
if (!userId || !customId) return;
|
if (!userId || !customId) return;
|
||||||
|
|
||||||
const body = d.components?.[0]?.components?.find((c) => c.custom_id === "body")?.value?.trim();
|
// Submitted as written (an indented first line is a Markdown code block):
|
||||||
if (!body) return respond(env, id, token, "评论内容不能为空。");
|
// blank only decides emptiness.
|
||||||
|
const body = d.components?.[0]?.components?.find((c) => c.custom_id === "body")?.value ?? "";
|
||||||
|
if (!body.trim()) return respond(env, id, token, "评论内容不能为空。");
|
||||||
|
|
||||||
const githubUserId = await getDiscordLink(env.DB, userId);
|
const githubUserId = await getDiscordLink(env.DB, userId);
|
||||||
if (!githubUserId) {
|
if (!githubUserId) {
|
||||||
return respond(env, id, token, "你还没有绑定 GitHub 账号,请先使用 `/gh login`。");
|
return respond(env, id, token, "你还没有绑定 GitHub 账号,请先使用 `/gh login`。");
|
||||||
}
|
}
|
||||||
|
|
||||||
// ghc|add|owner|repo|issueNumber
|
const context = await modalContext(env, customId);
|
||||||
if (customId.startsWith(MODAL_ADD)) {
|
if (!context) {
|
||||||
const [owner, repo, number] = splitThree(customId.slice(MODAL_ADD.length));
|
return respond(env, id, token, "这个评论框已失效,请重新打开。");
|
||||||
if (!owner || !repo || !number)
|
}
|
||||||
return respond(env, id, token, "内部错误:无法解析目标 issue。");
|
const { owner, repo, ref } = context;
|
||||||
try {
|
|
||||||
|
if (context.op === "add") {
|
||||||
|
return deferThen(env, id, token, applicationId, async () => {
|
||||||
const { htmlUrl, login } = await commentAsUser(
|
const { htmlUrl, login } = await commentAsUser(
|
||||||
env.KV,
|
env,
|
||||||
githubUserId,
|
githubUserId,
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
Number(number),
|
Number(ref),
|
||||||
body,
|
body,
|
||||||
);
|
);
|
||||||
return respond(env, id, token, `已以 **@${login}** 身份评论:${htmlUrl}`);
|
return `已以 **@${login}** 身份评论:${htmlUrl}`;
|
||||||
} catch (err) {
|
});
|
||||||
return respond(env, id, token, errText(err));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ghc|edit|owner|repo|commentId
|
return deferThen(env, id, token, applicationId, async () => {
|
||||||
if (customId.startsWith(MODAL_EDIT)) {
|
// Changed on GitHub since the modal showed it: saving would silently
|
||||||
const [owner, repo, commentId] = splitThree(customId.slice(MODAL_EDIT.length));
|
// replace those changes (GitHub has no conditional update — this check
|
||||||
if (!owner || !repo || !commentId)
|
// narrows the window to the moment between it and the save).
|
||||||
return respond(env, id, token, "内部错误:无法解析目标评论。");
|
if (context.base) {
|
||||||
try {
|
const { body: current } = await getCommentAsUser(env, githubUserId, owner, repo, Number(ref));
|
||||||
const { htmlUrl } = await editCommentAsUser(
|
if ((await sha256Hex(current)).slice(0, context.base.length) !== context.base) {
|
||||||
env.KV,
|
return "这条评论在你打开编辑框后已被修改。为避免覆盖这些修改,请重新打开编辑框。";
|
||||||
githubUserId,
|
|
||||||
owner,
|
|
||||||
repo,
|
|
||||||
Number(commentId),
|
|
||||||
body,
|
|
||||||
);
|
|
||||||
return respond(env, id, token, `已更新评论:${htmlUrl}`);
|
|
||||||
} catch (err) {
|
|
||||||
return respond(env, id, token, errText(err));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const { htmlUrl } = await editCommentAsUser(env, githubUserId, owner, repo, Number(ref), body);
|
||||||
|
return `已更新评论:${htmlUrl}`;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,54 @@ import {
|
|||||||
splitMessageTitle,
|
splitMessageTitle,
|
||||||
} from "../../formatters/helpers";
|
} from "../../formatters/helpers";
|
||||||
|
|
||||||
|
/** Discord's cap on the combined characters of all embeds in a message. */
|
||||||
|
const MAX_EMBED_TOTAL = 6000;
|
||||||
|
/** Discord's caps on a button's custom_id and label. */
|
||||||
|
const MAX_CUSTOM_ID = 100;
|
||||||
|
const MAX_BUTTON_LABEL = 80;
|
||||||
|
|
||||||
|
type Embed = NonNullable<FormattedMessage["embeds"]>[number];
|
||||||
|
|
||||||
|
function embedLength(embed: Embed): number {
|
||||||
|
return (
|
||||||
|
(embed.title?.length ?? 0) +
|
||||||
|
(embed.description?.length ?? 0) +
|
||||||
|
(embed.author?.name.length ?? 0) +
|
||||||
|
(embed.footer?.text.length ?? 0) +
|
||||||
|
(embed.fields ?? []).reduce((n, f) => n + f.name.length + f.value.length, 0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Description length kept before any field is given up. */
|
||||||
|
const MIN_DESCRIPTION = 1024;
|
||||||
|
|
||||||
|
/** Shorten the description by `over` characters (never below `floor`); returns what is left over. */
|
||||||
|
function shrinkDescription(embed: Embed, over: number, floor: number): number {
|
||||||
|
const text = embed.description;
|
||||||
|
if (!text || over <= 0 || text.length <= floor) return over;
|
||||||
|
const keep = Math.max(floor, text.length - over - 1);
|
||||||
|
embed.description = keep > 0 ? `${text.slice(0, keep)}…` : undefined;
|
||||||
|
return over - (text.length - (embed.description?.length ?? 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fit an embed into the 6000-character total so the request is never
|
||||||
|
* rejected whole: a long description shrinks first (down to 1024 characters),
|
||||||
|
* then trailing fields are dropped, then the description shrinks further.
|
||||||
|
*/
|
||||||
|
function fitEmbed(embed: Embed): Embed {
|
||||||
|
let over = embedLength(embed) - MAX_EMBED_TOTAL;
|
||||||
|
if (over <= 0) return embed;
|
||||||
|
const out: Embed = { ...embed, fields: embed.fields ? [...embed.fields] : undefined };
|
||||||
|
over = shrinkDescription(out, over, MIN_DESCRIPTION);
|
||||||
|
while (over > 0 && out.fields && out.fields.length > 0) {
|
||||||
|
const f = out.fields.pop()!;
|
||||||
|
over -= f.name.length + f.value.length;
|
||||||
|
}
|
||||||
|
shrinkDescription(out, over, 0);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
function toStyle(style: NeutralActionStyle): number {
|
function toStyle(style: NeutralActionStyle): number {
|
||||||
switch (style) {
|
switch (style) {
|
||||||
case "primary":
|
case "primary":
|
||||||
@@ -20,10 +68,16 @@ function toStyle(style: NeutralActionStyle): number {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Most roles one message mentions: well within Discord's 100 allowed-mention
|
||||||
|
* roles and 2000 content characters (a mention takes at most 24 with its
|
||||||
|
* space). Routes are validated against it; this is the safety net.
|
||||||
|
*/
|
||||||
|
export const MAX_ROLE_MENTIONS = 50;
|
||||||
|
|
||||||
export function renderNeutralMessage(message: NeutralMessage): FormattedMessage {
|
export function renderNeutralMessage(message: NeutralMessage): FormattedMessage {
|
||||||
const content = message.mentionRoleIds?.length
|
const roleIds = [...new Set(message.mentionRoleIds ?? [])].slice(0, MAX_ROLE_MENTIONS);
|
||||||
? message.mentionRoleIds.map((id) => `<@&${id}>`).join(" ")
|
const content = roleIds.length ? roleIds.map((id) => `<@&${id}>`).join(" ") : undefined;
|
||||||
: undefined;
|
|
||||||
|
|
||||||
// Discord embed titles can only be linked as a whole, so only the repo head
|
// Discord embed titles can only be linked as a whole, so only the repo head
|
||||||
// goes into the title (linked to the event's object URL); the `: subject`
|
// goes into the title (linked to the event's object URL); the `: subject`
|
||||||
@@ -41,10 +95,16 @@ export function renderNeutralMessage(message: NeutralMessage): FormattedMessage
|
|||||||
[message.forge?.name, message.footer].filter(Boolean).join(" · "),
|
[message.forge?.name, message.footer].filter(Boolean).join(" · "),
|
||||||
MAX_FOOTER,
|
MAX_FOOTER,
|
||||||
);
|
);
|
||||||
|
// Buttons whose id would exceed Discord's limit (very long repo names) are
|
||||||
|
// left out rather than failing the whole message.
|
||||||
|
const actions = (message.actions ?? []).filter((a) => a.id.length <= MAX_CUSTOM_ID);
|
||||||
return {
|
return {
|
||||||
content,
|
content,
|
||||||
|
// Only the route's own roles may ping — never @everyone, @here or users,
|
||||||
|
// whatever text ends up in the message.
|
||||||
|
allowed_mentions: { parse: [], roles: roleIds },
|
||||||
embeds: [
|
embeds: [
|
||||||
{
|
fitEmbed({
|
||||||
title: cap(head, MAX_TITLE),
|
title: cap(head, MAX_TITLE),
|
||||||
url: message.url,
|
url: message.url,
|
||||||
color: message.color,
|
color: message.color,
|
||||||
@@ -63,16 +123,16 @@ export function renderNeutralMessage(message: NeutralMessage): FormattedMessage
|
|||||||
})),
|
})),
|
||||||
footer: footerText ? { text: footerText, icon_url: message.forge?.iconUrl } : undefined,
|
footer: footerText ? { text: footerText, icon_url: message.forge?.iconUrl } : undefined,
|
||||||
timestamp: message.timestamp,
|
timestamp: message.timestamp,
|
||||||
},
|
}),
|
||||||
],
|
],
|
||||||
components: message.actions?.length
|
components: actions.length
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
type: 1,
|
type: 1,
|
||||||
components: message.actions.map((action) => ({
|
components: actions.map((action) => ({
|
||||||
type: 2,
|
type: 2,
|
||||||
style: toStyle(action.style),
|
style: toStyle(action.style),
|
||||||
label: action.label,
|
label: cap(action.label, MAX_BUTTON_LABEL),
|
||||||
custom_id: action.id,
|
custom_id: action.id,
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -7,6 +7,18 @@ interface DiscordMessage {
|
|||||||
id?: string;
|
id?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest rate-limit wait (seconds) slept inside one request; a longer one is
|
||||||
|
* returned as a 429 failure so the delivery queue retries it later instead.
|
||||||
|
*/
|
||||||
|
const MAX_INLINE_RETRY_AFTER = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest a single API call may take. Bounded, so a message edit always ends
|
||||||
|
* well within the update-chain lock it runs under (see `deliverUpdate`).
|
||||||
|
*/
|
||||||
|
export const REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
async function request(
|
async function request(
|
||||||
url: string,
|
url: string,
|
||||||
method: string,
|
method: string,
|
||||||
@@ -23,13 +35,24 @@ async function request(
|
|||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(message),
|
body: JSON.stringify(message),
|
||||||
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.status === 429) {
|
if (res.status === 429) {
|
||||||
const rateLimit = (await res.json()) as { retry_after?: number };
|
const rateLimit = (await res.json().catch(() => ({}))) as { retry_after?: number };
|
||||||
const retryAfter = (rateLimit.retry_after ?? 1) * 1000;
|
const seconds = Number(rateLimit.retry_after);
|
||||||
|
const retryAfter = Number.isFinite(seconds) && seconds > 0 ? seconds : 1;
|
||||||
log.warn({ retryAfter, attempt }, "Rate limited");
|
log.warn({ retryAfter, attempt }, "Rate limited");
|
||||||
await new Promise((r) => setTimeout(r, retryAfter));
|
if (retryAfter > MAX_INLINE_RETRY_AFTER || attempt === 2) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: `Rate limited (retry_after=${retryAfter})`,
|
||||||
|
errorCode: "RATE_LIMITED",
|
||||||
|
status: 429,
|
||||||
|
attempts: attempt + 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,15 +81,11 @@ async function request(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let messageId: string | undefined;
|
// A success whose body cannot be read (cut off, timed out) is not known
|
||||||
try {
|
// to have happened: tried again — a create carries its nonce, so it is
|
||||||
const data = (await res.json()) as DiscordMessage;
|
// never doubled.
|
||||||
messageId = data.id;
|
const data = (await res.json()) as DiscordMessage | null;
|
||||||
} catch {
|
return { ok: true, status: res.status, messageId: data?.id, attempts: attempt + 1 };
|
||||||
// ignore malformed success body
|
|
||||||
}
|
|
||||||
|
|
||||||
return { ok: true, status: res.status, messageId, attempts: attempt + 1 };
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.error({ err, attempt, channelId }, "Failed to send message");
|
log.error({ err, attempt, channelId }, "Failed to send message");
|
||||||
if (attempt === 2)
|
if (attempt === 2)
|
||||||
@@ -83,11 +102,19 @@ export async function sendMessage(
|
|||||||
channelId: string,
|
channelId: string,
|
||||||
message: unknown,
|
message: unknown,
|
||||||
threadId?: string,
|
threadId?: string,
|
||||||
|
sendKey?: string,
|
||||||
): Promise<SendResult> {
|
): Promise<SendResult> {
|
||||||
const url = threadId
|
// Ids are path segments: encoded, so no stored value can address another
|
||||||
? `${DISCORD_API}/channels/${threadId}/messages`
|
// resource (`x/../123` is never the channel `123`).
|
||||||
: `${DISCORD_API}/channels/${channelId}/messages`;
|
const url = `${DISCORD_API}/channels/${encodeURIComponent(threadId || channelId)}/messages`;
|
||||||
return request(url, "POST", token, message, channelId);
|
// One nonce for every attempt of this send — and, given a `sendKey`, for
|
||||||
|
// every attempt of the delivery: when a create went through but its
|
||||||
|
// response was lost, Discord answers the retry with that same message
|
||||||
|
// instead of posting a second one (`enforce_nonce`, a few minutes' window).
|
||||||
|
const nonce = (sendKey ?? crypto.randomUUID().replace(/-/g, "")).slice(0, 25);
|
||||||
|
const body =
|
||||||
|
message && typeof message === "object" ? { ...message, nonce, enforce_nonce: true } : message;
|
||||||
|
return request(url, "POST", token, body, channelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function editMessage(
|
export async function editMessage(
|
||||||
@@ -97,7 +124,7 @@ export async function editMessage(
|
|||||||
message: unknown,
|
message: unknown,
|
||||||
threadId?: string,
|
threadId?: string,
|
||||||
): Promise<SendResult> {
|
): Promise<SendResult> {
|
||||||
const base = threadId ?? channelId;
|
const base = encodeURIComponent(threadId || channelId);
|
||||||
const url = `${DISCORD_API}/channels/${base}/messages/${messageId}`;
|
const url = `${DISCORD_API}/channels/${base}/messages/${encodeURIComponent(messageId)}`;
|
||||||
return request(url, "PATCH", token, message, channelId);
|
return request(url, "PATCH", token, message, channelId);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { RouteTarget, Env, NeutralMessage } from "../../types";
|
import type { RouteTarget, Env, NeutralMessage } from "../../types";
|
||||||
import type { PlatformDriver, SendResult } from "../types";
|
import type { PlatformDriver, SendResult } from "../types";
|
||||||
import { getTenantAccessToken, sendMessage, updateMessage } from "./rest";
|
import { forgetRejectedToken, getTenantAccessToken, sendMessage, updateMessage } from "./rest";
|
||||||
import { renderNeutralMessage } from "./render";
|
import { renderNeutralMessage } from "./render";
|
||||||
|
|
||||||
export class FeishuDriver implements PlatformDriver {
|
export class FeishuDriver implements PlatformDriver {
|
||||||
@@ -17,9 +17,14 @@ export class FeishuDriver implements PlatformDriver {
|
|||||||
ok: false,
|
ok: false,
|
||||||
error: tokenRes.error ?? "No token",
|
error: tokenRes.error ?? "No token",
|
||||||
errorCode: tokenRes.errorCode ?? "NO_TOKEN",
|
errorCode: tokenRes.errorCode ?? "NO_TOKEN",
|
||||||
|
status: tokenRes.status,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return sendMessage(tokenRes.token, chatId, renderNeutralMessage(message));
|
return forgetRejectedToken(
|
||||||
|
await sendMessage(tokenRes.token, chatId, renderNeutralMessage(message), message.sendKey),
|
||||||
|
env,
|
||||||
|
tokenRes.token,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async edit(
|
async edit(
|
||||||
@@ -38,8 +43,13 @@ export class FeishuDriver implements PlatformDriver {
|
|||||||
ok: false,
|
ok: false,
|
||||||
error: tokenRes.error ?? "No token",
|
error: tokenRes.error ?? "No token",
|
||||||
errorCode: tokenRes.errorCode ?? "NO_TOKEN",
|
errorCode: tokenRes.errorCode ?? "NO_TOKEN",
|
||||||
|
status: tokenRes.status,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
return updateMessage(tokenRes.token, messageId, renderNeutralMessage(message));
|
return forgetRejectedToken(
|
||||||
|
await updateMessage(tokenRes.token, messageId, renderNeutralMessage(message)),
|
||||||
|
env,
|
||||||
|
tokenRes.token,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -26,8 +26,21 @@ function colorToTemplate(color?: number): FeishuTemplate {
|
|||||||
return "blue";
|
return "blue";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Text from the forge (titles, bodies, names) is anyone's to write: an
|
||||||
|
* `<at id=all></at>` in an issue title would make the bot notify the whole
|
||||||
|
* chat. The card never mentions anyone itself, so every `<at` tag is broken
|
||||||
|
* up (a zero-width space after `<`) and shows as text.
|
||||||
|
*/
|
||||||
|
function noMentions(content: string): string {
|
||||||
|
// Escape every angle bracket, not only `<at`. Replacing just the mention
|
||||||
|
// prefix still leaves values such as `<script` in Feishu markdown, where an
|
||||||
|
// incomplete tag can be interpreted as HTML by the client.
|
||||||
|
return content.replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
function mdText(content: string): { tag: "lark_md"; content: string } {
|
function mdText(content: string): { tag: "lark_md"; content: string } {
|
||||||
return { tag: "lark_md", content: cap(content, MAX_MARKDOWN) };
|
return { tag: "lark_md", content: cap(noMentions(content), MAX_MARKDOWN) };
|
||||||
}
|
}
|
||||||
|
|
||||||
function divMarkdown(content: string): { tag: "div"; text: { tag: "lark_md"; content: string } } {
|
function divMarkdown(content: string): { tag: "div"; text: { tag: "lark_md"; content: string } } {
|
||||||
@@ -92,7 +105,7 @@ export function renderNeutralMessage(message: NeutralMessage): Record<string, un
|
|||||||
if (elements.length) elements.push({ tag: "hr" });
|
if (elements.length) elements.push({ tag: "hr" });
|
||||||
elements.push({
|
elements.push({
|
||||||
tag: "note",
|
tag: "note",
|
||||||
elements: [{ tag: "lark_md", content: cap(meta.join(" · "), MAX_NOTE) }],
|
elements: [{ tag: "lark_md", content: cap(noMentions(meta.join(" · ")), MAX_NOTE) }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,16 @@
|
|||||||
import { log } from "../../lib/log";
|
import { log } from "../../lib/log";
|
||||||
|
import { sharedFlight, type Flight } from "../../lib/shared-flight";
|
||||||
import type { Env } from "../../types";
|
import type { Env } from "../../types";
|
||||||
import type { SendResult } from "../types";
|
import type { SendResult } from "../types";
|
||||||
|
|
||||||
const FEISHU_API = "https://open.feishu.cn";
|
const FEISHU_API = "https://open.feishu.cn";
|
||||||
const TOKEN_KEY = "feishu:token";
|
/**
|
||||||
|
* The cached tenant token of the configured app: switching apps (another
|
||||||
|
* FEISHU_APP_ID) never sends with the previous app's token.
|
||||||
|
*/
|
||||||
|
export function tokenKey(env: Env): string {
|
||||||
|
return `feishu:token:${env.FEISHU_APP_ID?.trim() ?? ""}`;
|
||||||
|
}
|
||||||
|
|
||||||
interface FeishuResponse {
|
interface FeishuResponse {
|
||||||
code?: number;
|
code?: number;
|
||||||
@@ -12,6 +19,29 @@ interface FeishuResponse {
|
|||||||
error?: { message?: string };
|
error?: { message?: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Feishu business codes for "slow down" (group message rate limit, API frequency limit). */
|
||||||
|
const RATE_LIMIT_CODES = new Set([230020, 99991400]);
|
||||||
|
/** Feishu business codes for an invalid or expired tenant access token. */
|
||||||
|
const TOKEN_CODES = new Set([99991661, 99991663, 99991664, 99991668]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The error code of a failed call: transient business codes map to the codes
|
||||||
|
* the delivery queue retries (`RATE_LIMITED`, `FEISHU_TOKEN`), whatever HTTP
|
||||||
|
* status Feishu answered with.
|
||||||
|
*/
|
||||||
|
function errorCodeOf(status: number, code: number | undefined): string {
|
||||||
|
if (code != null && RATE_LIMIT_CODES.has(code)) return "RATE_LIMITED";
|
||||||
|
if (code != null && TOKEN_CODES.has(code)) return "FEISHU_TOKEN";
|
||||||
|
if (status >= 500) return "FEISHU_5XX";
|
||||||
|
return code != null && code !== 0 ? `FEISHU_${code}` : "FEISHU_ERROR";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest a single API call may take. Bounded, so a message edit always ends
|
||||||
|
* well within the update-chain lock it runs under (see `deliverUpdate`).
|
||||||
|
*/
|
||||||
|
export const REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
async function feishuRequest(
|
async function feishuRequest(
|
||||||
url: string,
|
url: string,
|
||||||
method: string,
|
method: string,
|
||||||
@@ -33,18 +63,35 @@ async function feishuRequest(
|
|||||||
method,
|
method,
|
||||||
headers,
|
headers,
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
lastStatus = res.status;
|
lastStatus = res.status;
|
||||||
|
|
||||||
if (res.status === 429) {
|
if (res.status === 429) {
|
||||||
const retryAfter = Number(res.headers.get("retry-after") || "1");
|
const header = Number(res.headers.get("retry-after") || "1");
|
||||||
|
const retryAfter = Number.isFinite(header) && header > 0 ? header : 1;
|
||||||
lastError = `Rate limited (retry_after=${retryAfter})`;
|
lastError = `Rate limited (retry_after=${retryAfter})`;
|
||||||
log.warn({ retryAfter, attempt, label }, "Feishu rate limited");
|
log.warn({ retryAfter, attempt, label }, "Feishu rate limited");
|
||||||
|
if (retryAfter > 10 || attempt === 2) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: lastError,
|
||||||
|
errorCode: "RATE_LIMITED",
|
||||||
|
status: 429,
|
||||||
|
attempts: attempt + 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await res.json().catch(() => null)) as FeishuResponse | null;
|
const data = (await res.json().catch(() => null)) as FeishuResponse | null;
|
||||||
|
// A 200 whose body cannot be read (or carries no result code) is not
|
||||||
|
// known to have succeeded: tried again (the request's uuid keeps a
|
||||||
|
// send from doubling).
|
||||||
|
if (res.ok && (!data || typeof data.code !== "number")) {
|
||||||
|
throw new Error("Feishu answered without a result code");
|
||||||
|
}
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
lastError = data?.msg ?? data?.error?.message ?? `HTTP ${res.status}`;
|
lastError = data?.msg ?? data?.error?.message ?? `HTTP ${res.status}`;
|
||||||
@@ -55,7 +102,7 @@ async function feishuRequest(
|
|||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: lastError,
|
error: lastError,
|
||||||
errorCode: res.status >= 500 ? "FEISHU_5XX" : "FEISHU_ERROR",
|
errorCode: errorCodeOf(res.status, data?.code),
|
||||||
status: res.status,
|
status: res.status,
|
||||||
attempts: attempt + 1,
|
attempts: attempt + 1,
|
||||||
};
|
};
|
||||||
@@ -70,7 +117,7 @@ async function feishuRequest(
|
|||||||
return {
|
return {
|
||||||
ok: false,
|
ok: false,
|
||||||
error: lastError,
|
error: lastError,
|
||||||
errorCode: `FEISHU_${data.code}`,
|
errorCode: errorCodeOf(res.status, data.code),
|
||||||
status: res.status,
|
status: res.status,
|
||||||
attempts: attempt + 1,
|
attempts: attempt + 1,
|
||||||
};
|
};
|
||||||
@@ -107,6 +154,15 @@ async function feishuRequest(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** How long this isolate uses a token before reading KV again. */
|
||||||
|
const HELD_TOKEN_MS = 5 * 60_000;
|
||||||
|
/**
|
||||||
|
* A failed token request is answered from memory this long: targets sent one
|
||||||
|
* after another in the same delivery then fail at once instead of each
|
||||||
|
* reading KV and asking Feishu again (the delivery is retried later anyway).
|
||||||
|
*/
|
||||||
|
const FAILED_TOKEN_MS = 5_000;
|
||||||
|
|
||||||
interface TokenResult {
|
interface TokenResult {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
token?: string;
|
token?: string;
|
||||||
@@ -115,6 +171,52 @@ interface TokenResult {
|
|||||||
status?: number;
|
status?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tokens this isolate holds (per cache key), and refreshes in flight: routes
|
||||||
|
* sending in parallel share one token request and one KV write instead of
|
||||||
|
* each fetching and storing its own.
|
||||||
|
*/
|
||||||
|
const heldTokens = new Map<string, { token: string; until: number }>();
|
||||||
|
const refreshing = new Map<string, Flight<TokenResult>>();
|
||||||
|
const failedTokens = new Map<string, { result: TokenResult; until: number }>();
|
||||||
|
/** Tokens Feishu refused (bounded): never taken from KV again. */
|
||||||
|
const rejected = new Set<string>();
|
||||||
|
/** Refused tokens whose KV copy this isolate removed (or is removing). */
|
||||||
|
const cleared = new Set<string>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A rejected token is dropped from the cache, so the retry fetches a new one.
|
||||||
|
* From memory every time; from KV once per isolate (every target refused
|
||||||
|
* with it would otherwise delete the same key again) — tried again by the
|
||||||
|
* next refusal when that delete fails — and never a newer token another
|
||||||
|
* request stored meanwhile.
|
||||||
|
*/
|
||||||
|
export async function forgetRejectedToken(
|
||||||
|
result: SendResult,
|
||||||
|
env: Env,
|
||||||
|
token: string,
|
||||||
|
): Promise<SendResult> {
|
||||||
|
if (result.errorCode !== "FEISHU_TOKEN") return result;
|
||||||
|
const key = tokenKey(env);
|
||||||
|
if (heldTokens.get(key)?.token === token) heldTokens.delete(key);
|
||||||
|
if (!rejected.has(token)) {
|
||||||
|
if (rejected.size >= 100) {
|
||||||
|
rejected.clear();
|
||||||
|
cleared.clear();
|
||||||
|
}
|
||||||
|
rejected.add(token);
|
||||||
|
}
|
||||||
|
if (!cleared.has(token)) {
|
||||||
|
cleared.add(token);
|
||||||
|
try {
|
||||||
|
if ((await env.KV.get(key)) === token) await env.KV.delete(key);
|
||||||
|
} catch {
|
||||||
|
cleared.delete(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
export async function getTenantAccessToken(env: Env): Promise<TokenResult> {
|
export async function getTenantAccessToken(env: Env): Promise<TokenResult> {
|
||||||
const appId = env.FEISHU_APP_ID?.trim();
|
const appId = env.FEISHU_APP_ID?.trim();
|
||||||
const appSecret = env.FEISHU_APP_SECRET?.trim();
|
const appSecret = env.FEISHU_APP_SECRET?.trim();
|
||||||
@@ -126,8 +228,39 @@ export async function getTenantAccessToken(env: Env): Promise<TokenResult> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const cached = await env.KV.get(TOKEN_KEY);
|
const key = tokenKey(env);
|
||||||
if (cached) return { ok: true, token: cached };
|
const held = heldTokens.get(key);
|
||||||
|
if (held && Date.now() < held.until) return { ok: true, token: held.token };
|
||||||
|
const failed = failedTokens.get(key);
|
||||||
|
if (failed && Date.now() < failed.until) return failed.result;
|
||||||
|
return sharedFlight(
|
||||||
|
refreshing,
|
||||||
|
key,
|
||||||
|
async () => {
|
||||||
|
const result = await fetchTenantAccessToken(env, appId, appSecret);
|
||||||
|
if (result.ok) failedTokens.delete(key);
|
||||||
|
else failedTokens.set(key, { result, until: Date.now() + FAILED_TOKEN_MS });
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
REQUEST_TIMEOUT_MS + 5_000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchTenantAccessToken(
|
||||||
|
env: Env,
|
||||||
|
appId: string,
|
||||||
|
appSecret: string,
|
||||||
|
): Promise<TokenResult> {
|
||||||
|
const key = tokenKey(env);
|
||||||
|
const cached = await env.KV.get(key);
|
||||||
|
// A copy Feishu already refused (its KV delete failed or has not spread
|
||||||
|
// yet) is not used again: a new token is requested instead.
|
||||||
|
if (cached && !rejected.has(cached)) {
|
||||||
|
// Held a few minutes here: KV is read again now and then, so a token
|
||||||
|
// another isolate replaced is picked up.
|
||||||
|
heldTokens.set(key, { token: cached, until: Date.now() + HELD_TOKEN_MS });
|
||||||
|
return { ok: true, token: cached };
|
||||||
|
}
|
||||||
|
|
||||||
const url = `${FEISHU_API}/open-apis/auth/v3/tenant_access_token/internal`;
|
const url = `${FEISHU_API}/open-apis/auth/v3/tenant_access_token/internal`;
|
||||||
try {
|
try {
|
||||||
@@ -135,6 +268,7 @@ export async function getTenantAccessToken(env: Env): Promise<TokenResult> {
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
|
body: JSON.stringify({ app_id: appId, app_secret: appSecret }),
|
||||||
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
const data = (await res.json().catch(() => null)) as {
|
const data = (await res.json().catch(() => null)) as {
|
||||||
code?: number;
|
code?: number;
|
||||||
@@ -146,8 +280,24 @@ export async function getTenantAccessToken(env: Env): Promise<TokenResult> {
|
|||||||
const err = data?.msg ?? `HTTP ${res.status}`;
|
const err = data?.msg ?? `HTTP ${res.status}`;
|
||||||
return { ok: false, error: err, errorCode: "FEISHU_TOKEN", status: res.status };
|
return { ok: false, error: err, errorCode: "FEISHU_TOKEN", status: res.status };
|
||||||
}
|
}
|
||||||
const ttl = Math.max(60, (data.expire ?? 7200) - 60);
|
// Kept in KV until a held copy (read from KV just before it expires
|
||||||
await env.KV.put(TOKEN_KEY, data.tenant_access_token, { expirationTtl: ttl });
|
// there, then held HELD_TOKEN_MS) still ends ahead of the token itself.
|
||||||
|
const ttl = Math.max(60, (data.expire ?? 7200) - 60 - HELD_TOKEN_MS / 1000);
|
||||||
|
heldTokens.set(key, {
|
||||||
|
token: data.tenant_access_token,
|
||||||
|
until: Date.now() + Math.min(HELD_TOKEN_MS, ttl * 1000),
|
||||||
|
});
|
||||||
|
// Shared with other isolates when it can be: a failed KV write (say, the
|
||||||
|
// daily write quota spent) never throws away a valid token — it is then
|
||||||
|
// held here until it nears expiry, instead of being fetched (and its
|
||||||
|
// write retried) again every few minutes.
|
||||||
|
const token = data.tenant_access_token;
|
||||||
|
// Feishu handing out a token refused before means it is valid after all.
|
||||||
|
rejected.delete(token);
|
||||||
|
cleared.delete(token);
|
||||||
|
await env.KV.put(key, token, { expirationTtl: ttl }).catch(() => {
|
||||||
|
heldTokens.set(key, { token, until: Date.now() + ttl * 1000 });
|
||||||
|
});
|
||||||
return { ok: true, token: data.tenant_access_token };
|
return { ok: true, token: data.tenant_access_token };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return {
|
return {
|
||||||
@@ -162,12 +312,17 @@ export async function sendMessage(
|
|||||||
token: string,
|
token: string,
|
||||||
chatId: string,
|
chatId: string,
|
||||||
content: Record<string, unknown>,
|
content: Record<string, unknown>,
|
||||||
|
sendKey?: string,
|
||||||
): Promise<SendResult> {
|
): Promise<SendResult> {
|
||||||
const url = `${FEISHU_API}/open-apis/im/v1/messages?receive_id_type=chat_id`;
|
const url = `${FEISHU_API}/open-apis/im/v1/messages?receive_id_type=chat_id`;
|
||||||
|
// One `uuid` for every attempt of this send (of the delivery, given a
|
||||||
|
// `sendKey`): Feishu delivers at most one message per uuid within an hour,
|
||||||
|
// so a retry after a lost response never posts a duplicate.
|
||||||
const body: Record<string, unknown> = {
|
const body: Record<string, unknown> = {
|
||||||
receive_id: chatId,
|
receive_id: chatId,
|
||||||
msg_type: "interactive",
|
msg_type: "interactive",
|
||||||
content: JSON.stringify(content),
|
content: JSON.stringify(content),
|
||||||
|
uuid: (sendKey ?? crypto.randomUUID()).slice(0, 50),
|
||||||
};
|
};
|
||||||
return feishuRequest(url, "POST", token, body, chatId);
|
return feishuRequest(url, "POST", token, body, chatId);
|
||||||
}
|
}
|
||||||
@@ -188,6 +343,7 @@ export async function sendText(token: string, chatId: string, text: string): Pro
|
|||||||
receive_id: chatId,
|
receive_id: chatId,
|
||||||
msg_type: "text",
|
msg_type: "text",
|
||||||
content: JSON.stringify({ text }),
|
content: JSON.stringify({ text }),
|
||||||
|
uuid: crypto.randomUUID(),
|
||||||
};
|
};
|
||||||
return feishuRequest(url, "POST", token, body, chatId);
|
return feishuRequest(url, "POST", token, body, chatId);
|
||||||
}
|
}
|
||||||
@@ -197,7 +353,8 @@ export async function updateCard(
|
|||||||
cardToken: string,
|
cardToken: string,
|
||||||
card: Record<string, unknown>,
|
card: Record<string, unknown>,
|
||||||
): Promise<SendResult> {
|
): Promise<SendResult> {
|
||||||
const url = `${FEISHU_API}/open-apis/interactive/v1/config/update`;
|
// Delayed update of an interactive card after a callback (`token` from it).
|
||||||
|
const url = `${FEISHU_API}/open-apis/interactive/v1/card/update`;
|
||||||
const body: Record<string, unknown> = { token: cardToken, card };
|
const body: Record<string, unknown> = { token: cardToken, card };
|
||||||
return feishuRequest(url, "POST", token, body, "card");
|
return feishuRequest(url, "POST", token, body, "card");
|
||||||
}
|
}
|
||||||
@@ -5,13 +5,31 @@ import {
|
|||||||
commentAsUser,
|
commentAsUser,
|
||||||
mergePullRequestAsUser,
|
mergePullRequestAsUser,
|
||||||
closePullRequestAsUser,
|
closePullRequestAsUser,
|
||||||
|
BeforeGitHubError,
|
||||||
|
CommandTakenError,
|
||||||
|
githubRefused,
|
||||||
} from "../../github/oauth";
|
} from "../../github/oauth";
|
||||||
import { getFeishuLink, removeFeishuLink } from "../../github/store";
|
import { getFeishuLink, unlinkAsCommand } from "../../github/store";
|
||||||
import { getTenantAccessToken, sendText, updateCard } from "./rest";
|
import { acceptedKey, claimOnce, confirmClaim, idempotencyStore } from "../../lib/idempotency";
|
||||||
|
import { forgetRejectedToken, getTenantAccessToken, sendText, updateCard } from "./rest";
|
||||||
|
|
||||||
const FEISHU_API = "https://open.feishu.cn";
|
const FEISHU_API = "https://open.feishu.cn";
|
||||||
|
const MAX_BODY_SIZE = 1024 * 1024;
|
||||||
|
/** Handled event ids are remembered this long; replays of older requests are refused. */
|
||||||
|
const EVENT_CLAIM_SECONDS = 86400;
|
||||||
|
/** An event is held this long while it runs (then a retry may take it). */
|
||||||
|
const EVENT_PROCESSING_SECONDS = 300;
|
||||||
|
/**
|
||||||
|
* Oldest signed request accepted. It stays well inside the event claim, so a
|
||||||
|
* request old enough for its claim to have expired can never run again,
|
||||||
|
* while Feishu's own retries (spread over hours) still pass.
|
||||||
|
*/
|
||||||
|
const MAX_REQUEST_AGE_SECONDS = 12 * 3600;
|
||||||
|
const MAX_CLOCK_SKEW_SECONDS = 300;
|
||||||
|
|
||||||
const GITHUB_TARGET_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
// github.com itself only (never e.g. `evilgithub.com`): actions hit the GitHub API.
|
||||||
|
const GITHUB_TARGET_RE =
|
||||||
|
/https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
||||||
const BTN_PREFIX = "ghpr|";
|
const BTN_PREFIX = "ghpr|";
|
||||||
|
|
||||||
interface FeishuSender {
|
interface FeishuSender {
|
||||||
@@ -19,6 +37,8 @@ interface FeishuSender {
|
|||||||
}
|
}
|
||||||
interface FeishuMessage {
|
interface FeishuMessage {
|
||||||
chat_id?: string;
|
chat_id?: string;
|
||||||
|
/** "p2p" for the private chat with the bot, "group" otherwise. */
|
||||||
|
chat_type?: string;
|
||||||
content?: string;
|
content?: string;
|
||||||
}
|
}
|
||||||
interface FeishuAction {
|
interface FeishuAction {
|
||||||
@@ -29,9 +49,22 @@ interface FeishuEvent {
|
|||||||
sender?: FeishuSender;
|
sender?: FeishuSender;
|
||||||
message?: FeishuMessage;
|
message?: FeishuMessage;
|
||||||
action?: FeishuAction;
|
action?: FeishuAction;
|
||||||
operator?: { operator_id?: { open_id?: string } };
|
/** `card.action.trigger` (schema 2.0): the clicking user is `operator.open_id`. */
|
||||||
|
operator?: { open_id?: string; operator_id?: { open_id?: string } };
|
||||||
token?: string;
|
token?: string;
|
||||||
open_message_id?: string;
|
open_message_id?: string;
|
||||||
|
context?: { open_message_id?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tracks whether a command reached GitHub, so a failed run knows if it may be retried. */
|
||||||
|
interface CommandRun {
|
||||||
|
acted: boolean;
|
||||||
|
/** Records the command as done right before its GitHub write. */
|
||||||
|
beforeWrite?: () => Promise<void>;
|
||||||
|
/** This run wrote the "done" (only then may it give it back). */
|
||||||
|
markedDone?: boolean;
|
||||||
|
/** The command's "done" record, for writes committed together with it. */
|
||||||
|
done?: { key: string; ttl: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
function splitThree(rest: string): [string, string, string] {
|
function splitThree(rest: string): [string, string, string] {
|
||||||
@@ -51,31 +84,53 @@ function timingSafeEqual(a: string, b: string): boolean {
|
|||||||
return diff === 0;
|
return diff === 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function hmacSha256Base64(secret: string, payload: string): Promise<string> {
|
async function sha256Hex(data: string): Promise<string> {
|
||||||
const key = await crypto.subtle.importKey(
|
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(data));
|
||||||
"raw",
|
return Array.from(new Uint8Array(digest))
|
||||||
new TextEncoder().encode(secret),
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
{ name: "HMAC", hash: "SHA-256" },
|
.join("");
|
||||||
false,
|
|
||||||
["sign"],
|
|
||||||
);
|
|
||||||
const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(payload));
|
|
||||||
let binary = "";
|
|
||||||
const bytes = new Uint8Array(sig);
|
|
||||||
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i] ?? 0);
|
|
||||||
return btoa(binary);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feishu event signature (when an Encrypt Key is configured): `X-Lark-Signature`
|
||||||
|
* is the hex SHA-256 of `timestamp + nonce + encryptKey + rawBody`, with the
|
||||||
|
* timestamp and nonce from `X-Lark-Request-Timestamp` / `X-Lark-Request-Nonce`.
|
||||||
|
*/
|
||||||
export async function verifyFeishuSignature(
|
export async function verifyFeishuSignature(
|
||||||
appSecret: string,
|
encryptKey: string,
|
||||||
timestamp: string,
|
timestamp: string,
|
||||||
nonce: string,
|
nonce: string,
|
||||||
body: string,
|
body: string,
|
||||||
signature: string,
|
signature: string,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const raw = `${timestamp}\n${nonce}\n${body}`;
|
if (!signature) return false;
|
||||||
const computed = await hmacSha256Base64(appSecret, raw);
|
const computed = await sha256Hex(`${timestamp}${nonce}${encryptKey}${body}`);
|
||||||
return timingSafeEqual(computed, signature);
|
return timingSafeEqual(computed, signature.toLowerCase());
|
||||||
|
}
|
||||||
|
|
||||||
|
function base64ToBytes(value: string): Uint8Array {
|
||||||
|
const bin = atob(value);
|
||||||
|
const bytes = new Uint8Array(bin.length);
|
||||||
|
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decrypt an `{"encrypt": "..."}` body: AES-256-CBC with key SHA-256(encryptKey)
|
||||||
|
* and the IV in the first 16 bytes of the base64-decoded ciphertext.
|
||||||
|
*/
|
||||||
|
export async function decryptFeishuPayload(encryptKey: string, encrypted: string): Promise<string> {
|
||||||
|
const keyBytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(encryptKey));
|
||||||
|
const data = base64ToBytes(encrypted);
|
||||||
|
const key = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-CBC" }, false, [
|
||||||
|
"decrypt",
|
||||||
|
]);
|
||||||
|
const plain = await crypto.subtle.decrypt(
|
||||||
|
{ name: "AES-CBC", iv: data.slice(0, 16) },
|
||||||
|
key,
|
||||||
|
data.slice(16),
|
||||||
|
);
|
||||||
|
return new TextDecoder().decode(plain);
|
||||||
}
|
}
|
||||||
|
|
||||||
function describeError(err: unknown): string {
|
function describeError(err: unknown): string {
|
||||||
@@ -98,22 +153,50 @@ function extractTarget(text: string): { owner: string; repo: string; number: num
|
|||||||
return { owner: m[1] ?? "", repo: m[2] ?? "", number };
|
return { owner: m[1] ?? "", repo: m[2] ?? "", number };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Whether a failed reply may succeed later (then the event is given back). */
|
||||||
|
function replyRetryable(result: { status?: number; errorCode?: string }): boolean {
|
||||||
|
if (!result.status || result.status >= 500 || result.status === 429) return true;
|
||||||
|
return result.errorCode === "FEISHU_TOKEN" || result.errorCode === "RATE_LIMITED";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a reply. One that could not be sent for now throws, so the event is
|
||||||
|
* retried rather than confirmed unanswered (a login link never sent); a
|
||||||
|
* refusal that a retry cannot change is logged.
|
||||||
|
*/
|
||||||
async function replyToken(env: Env, chatId: string, text: string): Promise<void> {
|
async function replyToken(env: Env, chatId: string, text: string): Promise<void> {
|
||||||
const tokenRes = await getTenantAccessToken(env);
|
const tokenRes = await getTenantAccessToken(env);
|
||||||
if (!tokenRes.ok || !tokenRes.token) {
|
if (!tokenRes.ok || !tokenRes.token) {
|
||||||
log.warn({ err: tokenRes.error }, "Feishu token unavailable for reply");
|
log.warn({ err: tokenRes.error }, "Feishu token unavailable for reply");
|
||||||
return;
|
throw new Error("Feishu token unavailable for reply");
|
||||||
}
|
}
|
||||||
await sendText(tokenRes.token, chatId, text);
|
const result = await forgetRejectedToken(
|
||||||
|
await sendText(tokenRes.token, chatId, text),
|
||||||
|
env,
|
||||||
|
tokenRes.token,
|
||||||
|
);
|
||||||
|
if (result.ok) return;
|
||||||
|
log.warn({ chatId, err: result.error }, "Feishu reply failed");
|
||||||
|
if (replyRetryable(result)) throw new Error(`Feishu reply failed: ${result.error ?? "unknown"}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleLogin(env: Env, openId: string, chatId: string): Promise<void> {
|
async function handleLogin(
|
||||||
|
env: Env,
|
||||||
|
openId: string,
|
||||||
|
chatId: string,
|
||||||
|
chatType: string | undefined,
|
||||||
|
): Promise<void> {
|
||||||
|
// An authorization link posted in a group can be opened by anyone there;
|
||||||
|
// binding happens in the private chat with the bot only.
|
||||||
|
if (chatType !== "p2p") {
|
||||||
|
await replyToken(env, chatId, "请私聊机器人发送 /gh login 绑定 GitHub 账号。");
|
||||||
|
return;
|
||||||
|
}
|
||||||
const state = crypto.randomUUID();
|
const state = crypto.randomUUID();
|
||||||
const pending = {
|
const pending = {
|
||||||
redirectTo: "/admin",
|
redirectTo: "/admin",
|
||||||
expiresAt: Date.now() + 10 * 60 * 1000,
|
expiresAt: Date.now() + 10 * 60 * 1000,
|
||||||
feishuUserId: openId,
|
link: { platform: "feishu", userId: openId, chatId },
|
||||||
feishuChatId: chatId,
|
|
||||||
};
|
};
|
||||||
await env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: 600 });
|
await env.KV.put(`state:${state}`, JSON.stringify(pending), { expirationTtl: 600 });
|
||||||
const url = getOAuthURL(env.GITHUB_CLIENT_ID ?? "", state);
|
const url = getOAuthURL(env.GITHUB_CLIENT_ID ?? "", state);
|
||||||
@@ -128,13 +211,21 @@ async function handleLogin(env: Env, openId: string, chatId: string): Promise<vo
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleLogout(env: Env, openId: string, chatId: string): Promise<void> {
|
async function handleLogout(
|
||||||
|
env: Env,
|
||||||
|
openId: string,
|
||||||
|
chatId: string,
|
||||||
|
run: CommandRun,
|
||||||
|
): Promise<void> {
|
||||||
const linked = await getFeishuLink(env.DB, openId);
|
const linked = await getFeishuLink(env.DB, openId);
|
||||||
if (!linked) {
|
if (!linked) {
|
||||||
await replyToken(env, chatId, "你还没有绑定 GitHub 账号。");
|
await replyToken(env, chatId, "你还没有绑定 GitHub 账号。");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
await removeFeishuLink(env.DB, openId);
|
await unlinkAsCommand(env, "feishu", openId, run.done);
|
||||||
|
// Done from here: should the reply fail, a retry must not unlink again
|
||||||
|
// (by then it could remove a link made since).
|
||||||
|
run.acted = true;
|
||||||
await replyToken(env, chatId, "已解绑 GitHub 账号。");
|
await replyToken(env, chatId, "已解绑 GitHub 账号。");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,6 +234,7 @@ async function handleComment(
|
|||||||
openId: string,
|
openId: string,
|
||||||
chatId: string,
|
chatId: string,
|
||||||
text: string,
|
text: string,
|
||||||
|
run: CommandRun,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const githubUserId = await getFeishuLink(env.DB, openId);
|
const githubUserId = await getFeishuLink(env.DB, openId);
|
||||||
if (!githubUserId) {
|
if (!githubUserId) {
|
||||||
@@ -159,25 +251,37 @@ async function handleComment(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const ghIdx = text.indexOf("/gh");
|
const ghIdx = text.indexOf("/gh");
|
||||||
const rest = text.slice(ghIdx + 3).trim();
|
// Only leading space goes: a comment's trailing lines are its own.
|
||||||
const parts = rest.split(/\s+/);
|
const rest = text.slice(ghIdx + 3).replace(/^\s+/, "");
|
||||||
const linkIdx = parts.findIndex((p) => p.includes("github.com"));
|
// The comment is what follows the link, as written (line breaks and
|
||||||
const body =
|
// indentation kept).
|
||||||
parts
|
const link = /\S*github\.com\S*/.exec(rest);
|
||||||
.slice(linkIdx + 1)
|
const written = (link ? rest.slice(link.index + link[0].length) : rest).replace(
|
||||||
.join(" ")
|
/^[ \t]*\r?\n?/,
|
||||||
.trim() || "(来自飞书)";
|
"",
|
||||||
|
);
|
||||||
|
const body = written.trim() ? written : "(来自飞书)";
|
||||||
try {
|
try {
|
||||||
const res = await commentAsUser(
|
const res = await commentAsUser(
|
||||||
env.KV,
|
env,
|
||||||
githubUserId,
|
githubUserId,
|
||||||
target.owner,
|
target.owner,
|
||||||
target.repo,
|
target.repo,
|
||||||
target.number,
|
target.number,
|
||||||
body,
|
body,
|
||||||
|
{ beforeWrite: run.beforeWrite },
|
||||||
);
|
);
|
||||||
|
run.acted = true;
|
||||||
await replyToken(env, chatId, `✅ 已评论:[查看](${res.htmlUrl})(@${res.login})`);
|
await replyToken(env, chatId, `✅ 已评论:[查看](${res.htmlUrl})(@${res.login})`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Nothing reached GitHub yet: give the event back for a retry.
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
// Done, only its reply failed: the event must not run again.
|
||||||
|
if (run.acted) throw err;
|
||||||
|
// GitHub was called and may have acted (its answer lost): never run
|
||||||
|
// again. A refusal did nothing: should its reply fail, the command is
|
||||||
|
// given back and runs again.
|
||||||
|
if (!githubRefused(err)) run.acted = true;
|
||||||
await replyToken(env, chatId, `❌ ${describeError(err)}`);
|
await replyToken(env, chatId, `❌ ${describeError(err)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -188,6 +292,7 @@ async function handleMergeOrClose(
|
|||||||
chatId: string,
|
chatId: string,
|
||||||
action: "merge" | "close",
|
action: "merge" | "close",
|
||||||
body: string,
|
body: string,
|
||||||
|
run: CommandRun,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const githubUserId = await getFeishuLink(env.DB, openId);
|
const githubUserId = await getFeishuLink(env.DB, openId);
|
||||||
if (!githubUserId) {
|
if (!githubUserId) {
|
||||||
@@ -207,25 +312,48 @@ async function handleMergeOrClose(
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (action === "merge") {
|
if (action === "merge") {
|
||||||
await mergePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number);
|
await mergePullRequestAsUser(
|
||||||
|
env,
|
||||||
|
githubUserId,
|
||||||
|
target.owner,
|
||||||
|
target.repo,
|
||||||
|
target.number,
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
},
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
await closePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number);
|
await closePullRequestAsUser(env, githubUserId, target.owner, target.repo, target.number, {
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
run.acted = true;
|
||||||
await replyToken(
|
await replyToken(
|
||||||
env,
|
env,
|
||||||
chatId,
|
chatId,
|
||||||
`✅ 已${action === "merge" ? "合并" : "关闭"} ${target.owner}/${target.repo}#${target.number}`,
|
`✅ 已${action === "merge" ? "合并" : "关闭"} ${target.owner}/${target.repo}#${target.number}`,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Nothing reached GitHub yet: give the event back for a retry.
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
// Done, only its reply failed: the event must not run again.
|
||||||
|
if (run.acted) throw err;
|
||||||
|
// GitHub was called and may have acted (its answer lost): never run
|
||||||
|
// again. A refusal did nothing: should its reply fail, the command is
|
||||||
|
// given back and runs again.
|
||||||
|
if (!githubRefused(err)) run.acted = true;
|
||||||
await replyToken(env, chatId, `❌ ${describeError(err)}`);
|
await replyToken(env, chatId, `❌ ${describeError(err)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleMessage(env: Env, event: FeishuEvent): Promise<void> {
|
/**
|
||||||
const sender = event.sender ?? {};
|
* The `/gh` command a message carries, or null: only a message that is a
|
||||||
const openId = sender.sender_id?.open_id ?? sender.sender_id?.union_id ?? "";
|
* command — `/gh` first, after any @mentions of the bot — runs one; quoting
|
||||||
|
* or discussing a command never does.
|
||||||
|
*/
|
||||||
|
function commandOf(event: FeishuEvent): string | null {
|
||||||
const message = event.message ?? {};
|
const message = event.message ?? {};
|
||||||
const chatId = message.chat_id ?? "";
|
|
||||||
let text = "";
|
let text = "";
|
||||||
if (message.content) {
|
if (message.content) {
|
||||||
try {
|
try {
|
||||||
@@ -235,25 +363,34 @@ async function handleMessage(env: Env, event: FeishuEvent): Promise<void> {
|
|||||||
text = "";
|
text = "";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const idx = text.indexOf("/gh");
|
const command = text.replace(/^\s*(?:@\S+\s+)*/, "");
|
||||||
if (idx < 0) return;
|
return /^\/gh(?:\s|$)/.test(command) ? command : null;
|
||||||
const rest = text.slice(idx + 3).trim();
|
}
|
||||||
|
|
||||||
|
async function handleMessage(env: Env, event: FeishuEvent, run: CommandRun): Promise<void> {
|
||||||
|
const sender = event.sender ?? {};
|
||||||
|
const openId = sender.sender_id?.open_id ?? sender.sender_id?.union_id ?? "";
|
||||||
|
const message = event.message ?? {};
|
||||||
|
const chatId = message.chat_id ?? "";
|
||||||
|
const command = commandOf(event);
|
||||||
|
if (!command) return;
|
||||||
|
const rest = command.slice(3).trim();
|
||||||
const sub = rest.split(/\s+/)[0] ?? "";
|
const sub = rest.split(/\s+/)[0] ?? "";
|
||||||
switch (sub) {
|
switch (sub) {
|
||||||
case "login":
|
case "login":
|
||||||
await handleLogin(env, openId, chatId);
|
await handleLogin(env, openId, chatId, message.chat_type);
|
||||||
break;
|
break;
|
||||||
case "logout":
|
case "logout":
|
||||||
await handleLogout(env, openId, chatId);
|
await handleLogout(env, openId, chatId, run);
|
||||||
break;
|
break;
|
||||||
case "comment":
|
case "comment":
|
||||||
await handleComment(env, openId, chatId, text);
|
await handleComment(env, openId, chatId, command, run);
|
||||||
break;
|
break;
|
||||||
case "merge":
|
case "merge":
|
||||||
await handleMergeOrClose(env, openId, chatId, "merge", text);
|
await handleMergeOrClose(env, openId, chatId, "merge", command, run);
|
||||||
break;
|
break;
|
||||||
case "close":
|
case "close":
|
||||||
await handleMergeOrClose(env, openId, chatId, "close", text);
|
await handleMergeOrClose(env, openId, chatId, "close", command, run);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
await replyToken(
|
await replyToken(
|
||||||
@@ -276,13 +413,21 @@ function buildResultCard(ok: boolean, message: string): Record<string, unknown>
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function handleCardAction(env: Env, payload: Record<string, unknown>): Promise<void> {
|
async function handleCardAction(
|
||||||
|
env: Env,
|
||||||
|
payload: Record<string, unknown>,
|
||||||
|
run: CommandRun,
|
||||||
|
): Promise<void> {
|
||||||
const event = (payload.event ?? {}) as FeishuEvent;
|
const event = (payload.event ?? {}) as FeishuEvent;
|
||||||
const action = event.action ?? {};
|
const action = event.action ?? {};
|
||||||
const actionId = action.action_id ?? action.value?.v ?? "";
|
const actionId = action.action_id ?? action.value?.v ?? "";
|
||||||
const openId = event.operator?.operator_id?.open_id ?? event.sender?.sender_id?.open_id ?? "";
|
const openId =
|
||||||
|
event.operator?.open_id ??
|
||||||
|
event.operator?.operator_id?.open_id ??
|
||||||
|
event.sender?.sender_id?.open_id ??
|
||||||
|
"";
|
||||||
const cardToken = event.token ?? "";
|
const cardToken = event.token ?? "";
|
||||||
const openMessageId = event.open_message_id ?? "";
|
const openMessageId = event.context?.open_message_id ?? event.open_message_id ?? "";
|
||||||
|
|
||||||
if (!actionId.startsWith(BTN_PREFIX)) return;
|
if (!actionId.startsWith(BTN_PREFIX)) return;
|
||||||
|
|
||||||
@@ -303,16 +448,28 @@ async function handleCardAction(env: Env, payload: Record<string, unknown>): Pro
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
if (isMerge) {
|
if (isMerge) {
|
||||||
await mergePullRequestAsUser(env.KV, githubUserId, owner, repo, number);
|
await mergePullRequestAsUser(env, githubUserId, owner, repo, number, undefined, {
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
await closePullRequestAsUser(env.KV, githubUserId, owner, repo, number);
|
await closePullRequestAsUser(env, githubUserId, owner, repo, number, {
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
run.acted = true;
|
||||||
await replyCard(
|
await replyCard(
|
||||||
env,
|
env,
|
||||||
cardToken,
|
cardToken,
|
||||||
buildResultCard(true, `${isMerge ? "已合并" : "已关闭"} ${owner}/${repo}#${number}`),
|
buildResultCard(true, `${isMerge ? "已合并" : "已关闭"} ${owner}/${repo}#${number}`),
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
// Done, only its card update failed: the event must not run again.
|
||||||
|
if (run.acted) throw err;
|
||||||
|
// GitHub was called and may have acted (its answer lost): never run
|
||||||
|
// again. A refusal did nothing: should its reply fail, the command is
|
||||||
|
// given back and runs again.
|
||||||
|
if (!githubRefused(err)) run.acted = true;
|
||||||
await replyCard(env, cardToken, buildResultCard(false, describeError(err)));
|
await replyCard(env, cardToken, buildResultCard(false, describeError(err)));
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
@@ -329,12 +486,40 @@ async function replyCard(
|
|||||||
card: Record<string, unknown>,
|
card: Record<string, unknown>,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const tokenRes = await getTenantAccessToken(env);
|
const tokenRes = await getTenantAccessToken(env);
|
||||||
if (!tokenRes.ok || !tokenRes.token) return;
|
if (!tokenRes.ok || !tokenRes.token) {
|
||||||
await updateCard(tokenRes.token, cardToken, card);
|
log.warn({ err: tokenRes.error }, "Feishu token unavailable for card update");
|
||||||
|
throw new Error("Feishu token unavailable for card update");
|
||||||
|
}
|
||||||
|
const result = await forgetRejectedToken(
|
||||||
|
await updateCard(tokenRes.token, cardToken, card),
|
||||||
|
env,
|
||||||
|
tokenRes.token,
|
||||||
|
);
|
||||||
|
if (result.ok) return;
|
||||||
|
log.warn({ err: result.error }, "Failed to update the Feishu card");
|
||||||
|
if (replyRetryable(result))
|
||||||
|
throw new Error(`Feishu card update failed: ${result.error ?? "unknown"}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inbound Feishu callbacks (events and card actions). Every request must be
|
||||||
|
* authenticated by the app's own credentials before anything runs:
|
||||||
|
* - with `FEISHU_ENCRYPT_KEY`, the `X-Lark-Signature` must verify and an
|
||||||
|
* encrypted body is decrypted with that key;
|
||||||
|
* - with `FEISHU_VERIFICATION_TOKEN`, the token inside the payload must match.
|
||||||
|
* At least one of them is required; without either the endpoint refuses all
|
||||||
|
* requests, since an unauthenticated one could act as any linked user.
|
||||||
|
*/
|
||||||
export async function handleFeishuWebhookRequest(request: Request, env: Env): Promise<Response> {
|
export async function handleFeishuWebhookRequest(request: Request, env: Env): Promise<Response> {
|
||||||
|
// Unauthenticated until verified below: bound what is read and parsed.
|
||||||
|
const contentLength = Number(request.headers.get("content-length") ?? 0);
|
||||||
|
if (contentLength > MAX_BODY_SIZE) {
|
||||||
|
return new Response("Request too large", { status: 413 });
|
||||||
|
}
|
||||||
const rawBody = await request.text();
|
const rawBody = await request.text();
|
||||||
|
if (rawBody.length > MAX_BODY_SIZE) {
|
||||||
|
return new Response("Request too large", { status: 413 });
|
||||||
|
}
|
||||||
let payload: Record<string, unknown>;
|
let payload: Record<string, unknown>;
|
||||||
try {
|
try {
|
||||||
payload = JSON.parse(rawBody);
|
payload = JSON.parse(rawBody);
|
||||||
@@ -342,20 +527,54 @@ export async function handleFeishuWebhookRequest(request: Request, env: Env): Pr
|
|||||||
return new Response("invalid json", { status: 400 });
|
return new Response("invalid json", { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const encryptKey = env.FEISHU_ENCRYPT_KEY?.trim() ?? "";
|
||||||
|
const verificationToken = env.FEISHU_VERIFICATION_TOKEN?.trim() ?? "";
|
||||||
|
if (!encryptKey && !verificationToken) {
|
||||||
|
log.warn("Feishu callback refused: FEISHU_ENCRYPT_KEY / FEISHU_VERIFICATION_TOKEN not set");
|
||||||
|
return new Response("Feishu callback verification is not configured", { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (encryptKey && typeof payload.encrypt === "string") {
|
||||||
|
try {
|
||||||
|
payload = JSON.parse(await decryptFeishuPayload(encryptKey, payload.encrypt));
|
||||||
|
} catch (err) {
|
||||||
|
log.warn({ err: String(err) }, "Feishu payload decryption failed");
|
||||||
|
return new Response("invalid payload", { status: 400 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const header = payload.header as Record<string, unknown> | undefined;
|
const header = payload.header as Record<string, unknown> | undefined;
|
||||||
const eventPart = payload.event as Record<string, unknown> | undefined;
|
const eventPart = payload.event as Record<string, unknown> | undefined;
|
||||||
const type = (payload.type as string) ?? header?.event_type ?? eventPart?.type ?? "";
|
const type = (payload.type as string) ?? header?.event_type ?? eventPart?.type ?? "";
|
||||||
|
|
||||||
|
// The verification token travels inside the (decrypted) payload: in
|
||||||
|
// `header.token` for schema 2.0 events, at the top level otherwise.
|
||||||
|
const token = String(header?.token ?? payload.token ?? "");
|
||||||
|
if (verificationToken && !timingSafeEqual(token, verificationToken)) {
|
||||||
|
log.warn("Feishu verification token mismatch");
|
||||||
|
return new Response("invalid token", { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
if (type === "url_verification") {
|
if (type === "url_verification") {
|
||||||
return Response.json({ challenge: (payload.challenge as string) ?? "" });
|
return Response.json({ challenge: (payload.challenge as string) ?? "" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const appSecret = env.FEISHU_APP_SECRET?.trim() ?? "";
|
if (encryptKey) {
|
||||||
const signature = request.headers.get("x-lark-signature") ?? "";
|
const timestamp = request.headers.get("x-lark-request-timestamp") ?? "";
|
||||||
const timestamp = request.headers.get("x-lark-timestamp") ?? "";
|
// The signature covers the timestamp: a stale one marks a replay that
|
||||||
const nonce = request.headers.get("x-lark-nonce") ?? "";
|
// may outlive the event claim below.
|
||||||
if (appSecret && signature) {
|
const age = Math.floor(Date.now() / 1000) - Number(timestamp);
|
||||||
const ok = await verifyFeishuSignature(appSecret, timestamp, nonce, rawBody, signature);
|
if (!Number.isFinite(age) || age > MAX_REQUEST_AGE_SECONDS || age < -MAX_CLOCK_SKEW_SECONDS) {
|
||||||
|
log.warn({ timestamp }, "Feishu callback refused: request timestamp out of range");
|
||||||
|
return new Response("stale request", { status: 401 });
|
||||||
|
}
|
||||||
|
const ok = await verifyFeishuSignature(
|
||||||
|
encryptKey,
|
||||||
|
timestamp,
|
||||||
|
request.headers.get("x-lark-request-nonce") ?? "",
|
||||||
|
rawBody,
|
||||||
|
request.headers.get("x-lark-signature") ?? "",
|
||||||
|
);
|
||||||
if (!ok) {
|
if (!ok) {
|
||||||
log.warn("Feishu signature verification failed");
|
log.warn("Feishu signature verification failed");
|
||||||
return new Response("invalid signature", { status: 401 });
|
return new Response("invalid signature", { status: 401 });
|
||||||
@@ -363,16 +582,73 @@ export async function handleFeishuWebhookRequest(request: Request, env: Env): Pr
|
|||||||
}
|
}
|
||||||
|
|
||||||
const eventType = (header?.event_type as string) ?? eventPart?.type ?? type;
|
const eventType = (header?.event_type as string) ?? eventPart?.type ?? type;
|
||||||
try {
|
const isMessage = eventType === "im.message.receive_v1" || eventType === "message";
|
||||||
if (eventType === "im.message.receive_v1" || eventType === "message") {
|
// Nothing to do for an ordinary chat message (no `/gh` command) or an
|
||||||
await handleMessage(env, (payload.event ?? payload) as FeishuEvent);
|
// event type not handled: answered at once, with no dedup records written
|
||||||
} else if (eventType === "card.action.trigger") {
|
// (each would be D1 writes for an event that has no side effect).
|
||||||
await handleCardAction(env, payload);
|
if (
|
||||||
}
|
(isMessage && !commandOf((payload.event ?? payload) as FeishuEvent)) ||
|
||||||
} catch (err) {
|
(!isMessage && eventType !== "card.action.trigger")
|
||||||
log.error({ err }, "Feishu webhook handling failed");
|
) {
|
||||||
|
return new Response("ok", { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Feishu retries a callback it considers failed; run each event once. An
|
||||||
|
// event whose earlier run is unconfirmed is retried later, never dropped.
|
||||||
|
const eventId = String(header?.event_id ?? payload.uuid ?? "");
|
||||||
|
const claims = idempotencyStore(env.DB, env.KV);
|
||||||
|
const claimKey = `bot:feishu:${eventId}`;
|
||||||
|
if (eventId) {
|
||||||
|
const state = await claimOnce(claims, claimKey, EVENT_PROCESSING_SECONDS);
|
||||||
|
if (state === "done") return new Response("ok", { status: 200 });
|
||||||
|
if (state === "pending") return new Response("temporarily unavailable", { status: 503 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const run: CommandRun = { acted: false };
|
||||||
|
// Done on record before GitHub is written to: should the confirmation
|
||||||
|
// after it fail, a retry still never repeats the write.
|
||||||
|
if (eventId) {
|
||||||
|
run.done = { key: acceptedKey(claimKey), ttl: EVENT_CLAIM_SECONDS };
|
||||||
|
run.beforeWrite = async (): Promise<void> => {
|
||||||
|
// Taken: a run that outlived its claim finds another run's "done" here
|
||||||
|
// and writes nothing.
|
||||||
|
if (!(await claims.claim(acceptedKey(claimKey), EVENT_CLAIM_SECONDS)))
|
||||||
|
throw new CommandTakenError();
|
||||||
|
run.markedDone = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (isMessage) {
|
||||||
|
await handleMessage(env, (payload.event ?? payload) as FeishuEvent, run);
|
||||||
|
} else if (eventType === "card.action.trigger") {
|
||||||
|
await handleCardAction(env, payload, run);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Finished by another run meanwhile: nothing to give back or repeat.
|
||||||
|
if (err instanceof CommandTakenError) return new Response("ok", { status: 200 });
|
||||||
|
log.error({ err }, "Feishu webhook handling failed");
|
||||||
|
// Failed before reaching GitHub: give the event back and answer with an
|
||||||
|
// error, so Feishu's retry runs it. After GitHub acted it stays claimed.
|
||||||
|
if (!run.acted) {
|
||||||
|
if (eventId) {
|
||||||
|
// An early "done" this run wrote (right before a write GitHub
|
||||||
|
// refused) too — never one another run wrote meanwhile.
|
||||||
|
if (run.markedDone) {
|
||||||
|
await claims.release(acceptedKey(claimKey)).catch(() => undefined);
|
||||||
|
}
|
||||||
|
await claims.release(claimKey).catch(() => undefined);
|
||||||
|
}
|
||||||
|
return new Response("temporarily unavailable", { status: 503 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A "done" already written before the GitHub write needs no second write.
|
||||||
|
if (eventId && !run.markedDone) {
|
||||||
|
// Best-effort: unconfirmed, the claim still holds off retries until it expires.
|
||||||
|
await confirmClaim(claims, claimKey, EVENT_CLAIM_SECONDS).catch((err: unknown) =>
|
||||||
|
log.warn({ err, eventId }, "Failed to confirm a Feishu event"),
|
||||||
|
);
|
||||||
|
}
|
||||||
return new Response("ok", { status: 200 });
|
return new Response("ok", { status: 200 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,3 +16,20 @@ export function getDriver(target: RouteTarget): PlatformDriver {
|
|||||||
if (!driver) throw new Error(`No driver for platform "${platform}"`);
|
if (!driver) throw new Error(`No driver for platform "${platform}"`);
|
||||||
return driver;
|
return driver;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Where a target's messages actually go: two targets naming the same place
|
||||||
|
* (a Discord thread given alone, or with its parent channel) are one
|
||||||
|
* destination, and get one copy of each message.
|
||||||
|
*/
|
||||||
|
export function destinationOf(target: RouteTarget): string {
|
||||||
|
const platform = target.platform ?? "discord";
|
||||||
|
if (platform === "telegram") {
|
||||||
|
// Read as the driver sends it (a number): `01` and `1` are one topic.
|
||||||
|
const topic = target.topicId ?? "";
|
||||||
|
const id = topic && Number.isFinite(Number(topic)) ? String(Number(topic)) : topic;
|
||||||
|
return `telegram:${target.chatId ?? ""}/${id}`;
|
||||||
|
}
|
||||||
|
if (platform === "feishu") return `feishu:${target.chatId ?? ""}`;
|
||||||
|
return `discord:${target.threadId || target.channelId || ""}`;
|
||||||
|
}
|
||||||
@@ -4,13 +4,25 @@ import {
|
|||||||
commentAsUser,
|
commentAsUser,
|
||||||
mergePullRequestAsUser,
|
mergePullRequestAsUser,
|
||||||
closePullRequestAsUser,
|
closePullRequestAsUser,
|
||||||
|
BeforeGitHubError,
|
||||||
|
CommandTakenError,
|
||||||
|
githubRefused,
|
||||||
} from "../../github/oauth";
|
} from "../../github/oauth";
|
||||||
import { getTelegramLink, removeTelegramLink } from "../../github/store";
|
import { getTelegramLink, unlinkAsCommand } from "../../github/store";
|
||||||
|
import { acceptedKey, claimOnce, confirmClaim, idempotencyStore } from "../../lib/idempotency";
|
||||||
import type { Env } from "../../types";
|
import type { Env } from "../../types";
|
||||||
import { sendMessage } from "./rest";
|
import { sendMessage } from "./rest";
|
||||||
|
import { telegramWebhookSecret } from "./secret";
|
||||||
|
|
||||||
const GITHUB_ISSUE_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
// github.com itself only (never e.g. `evilgithub.com`): actions hit the GitHub API.
|
||||||
const GITHUB_PR_RE = /github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
|
/** An update is held this long while its command runs (then a redelivery may take it). */
|
||||||
|
const COMMAND_CLAIM_SECONDS = 300;
|
||||||
|
/** Handled updates are remembered this long. */
|
||||||
|
const COMMAND_DONE_SECONDS = 86400;
|
||||||
|
|
||||||
|
const GITHUB_ISSUE_RE =
|
||||||
|
/^https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/(?:issues|pull)\/(\d+)/;
|
||||||
|
const GITHUB_PR_RE = /^https?:\/\/(?:www\.)?github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
|
||||||
|
|
||||||
interface TelegramMessage {
|
interface TelegramMessage {
|
||||||
message_id?: number;
|
message_id?: number;
|
||||||
@@ -23,6 +35,26 @@ interface TelegramMessage {
|
|||||||
reply_to_message?: TelegramMessage;
|
reply_to_message?: TelegramMessage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let knownBotUsername: { token: string; name: string } | null = null;
|
||||||
|
|
||||||
|
/** This bot's username (lower case), from `getMe`; remembered per isolate. */
|
||||||
|
async function botUsername(env: Env): Promise<string> {
|
||||||
|
const token = env.TELEGRAM_TOKEN ?? "";
|
||||||
|
if (knownBotUsername?.token === token) return knownBotUsername.name;
|
||||||
|
const res = await fetch(`https://api.telegram.org/bot${token}/getMe`, {
|
||||||
|
signal: AbortSignal.timeout(15_000),
|
||||||
|
});
|
||||||
|
const data = (await res.json().catch(() => null)) as {
|
||||||
|
result?: { username?: string };
|
||||||
|
} | null;
|
||||||
|
const name = data?.result?.username;
|
||||||
|
// Unknown: thrown, so Telegram redelivers the update rather than the
|
||||||
|
// command being dropped.
|
||||||
|
if (!res.ok || !name) throw new Error(`Telegram getMe failed (HTTP ${res.status})`);
|
||||||
|
knownBotUsername = { token, name: name.toLowerCase() };
|
||||||
|
return knownBotUsername.name;
|
||||||
|
}
|
||||||
|
|
||||||
interface Target {
|
interface Target {
|
||||||
owner: string;
|
owner: string;
|
||||||
repo: string;
|
repo: string;
|
||||||
@@ -54,13 +86,23 @@ function extractTarget(msg: TelegramMessage, prOnly = false): Target | null {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a reply. One that could not be sent for now throws, so the update is
|
||||||
|
* redelivered rather than confirmed unanswered (a login link never sent);
|
||||||
|
* a refusal that a retry cannot change (e.g. the bot was blocked) is logged.
|
||||||
|
*/
|
||||||
async function reply(
|
async function reply(
|
||||||
env: Env,
|
env: Env,
|
||||||
chatId: string,
|
chatId: string,
|
||||||
topicId: string | undefined,
|
topicId: string | undefined,
|
||||||
text: string,
|
text: string,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
await sendMessage(env.TELEGRAM_TOKEN ?? "", chatId, text, topicId);
|
const result = await sendMessage(env.TELEGRAM_TOKEN ?? "", chatId, text, topicId);
|
||||||
|
if (result.ok) return;
|
||||||
|
log.warn({ chatId, err: result.error }, "Telegram reply failed");
|
||||||
|
if (!result.status || result.status >= 500 || result.status === 429) {
|
||||||
|
throw new Error(`Telegram reply failed: ${result.error ?? "unknown"}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function errText(err: unknown): string {
|
function errText(err: unknown): string {
|
||||||
@@ -77,17 +119,23 @@ async function cmdLogin(env: Env, msg: TelegramMessage): Promise<void> {
|
|||||||
if (!chatId || !telegramUserId) return;
|
if (!chatId || !telegramUserId) return;
|
||||||
const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined;
|
const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined;
|
||||||
|
|
||||||
|
// An authorization link posted in a group can be opened by anyone there;
|
||||||
|
// binding happens in the private chat with the bot only.
|
||||||
|
if (msg.chat?.type !== "private") {
|
||||||
|
return reply(env, chatId, topicId, "请私聊机器人发送 /gh login 绑定 GitHub 账号。");
|
||||||
|
}
|
||||||
|
|
||||||
const clientId = env.GITHUB_CLIENT_ID;
|
const clientId = env.GITHUB_CLIENT_ID;
|
||||||
if (!clientId)
|
if (!clientId)
|
||||||
return reply(env, chatId, topicId, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。");
|
return reply(env, chatId, topicId, "服务器未配置 GitHub OAuth(GITHUB_CLIENT_ID)。");
|
||||||
|
|
||||||
|
const name = msg.from?.username ? `@${msg.from.username}` : msg.from?.first_name;
|
||||||
const state = crypto.randomUUID().replace(/-/g, "");
|
const state = crypto.randomUUID().replace(/-/g, "");
|
||||||
await env.KV.put(
|
await env.KV.put(
|
||||||
`state:${state}`,
|
`state:${state}`,
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
redirectTo: "/",
|
redirectTo: "/",
|
||||||
telegramUserId,
|
link: { platform: "telegram", userId: telegramUserId, name, chatId },
|
||||||
telegramChatId: chatId,
|
|
||||||
expiresAt: Date.now() + 600_000,
|
expiresAt: Date.now() + 600_000,
|
||||||
}),
|
}),
|
||||||
{ expirationTtl: 600 },
|
{ expirationTtl: 600 },
|
||||||
@@ -97,20 +145,39 @@ async function cmdLogin(env: Env, msg: TelegramMessage): Promise<void> {
|
|||||||
env,
|
env,
|
||||||
chatId,
|
chatId,
|
||||||
topicId,
|
topicId,
|
||||||
`点击链接授权 GitHub,即可用**本人身份**评论(10 分钟内有效):\n${url}`,
|
`点击链接授权 GitHub,即可用<b>本人身份</b>评论(10 分钟内有效):\n${url}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cmdLogout(env: Env, msg: TelegramMessage): Promise<void> {
|
async function cmdLogout(env: Env, msg: TelegramMessage, run: CommandRun): Promise<void> {
|
||||||
const chatId = chatIdOf(msg);
|
const chatId = chatIdOf(msg);
|
||||||
const telegramUserId = userIdOf(msg);
|
const telegramUserId = userIdOf(msg);
|
||||||
if (!chatId || !telegramUserId) return;
|
if (!chatId || !telegramUserId) return;
|
||||||
const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined;
|
const topicId = msg.message_thread_id != null ? String(msg.message_thread_id) : undefined;
|
||||||
await removeTelegramLink(env.DB, telegramUserId);
|
await unlinkAsCommand(env, "telegram", telegramUserId, run.done);
|
||||||
|
// Done from here: should the reply fail, a redelivery must not unlink again
|
||||||
|
// (by then it could remove a link made since).
|
||||||
|
run.acted = true;
|
||||||
await reply(env, chatId, topicId, "已解绑你的 GitHub 账号。");
|
await reply(env, chatId, topicId, "已解绑你的 GitHub 账号。");
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cmdComment(env: Env, msg: TelegramMessage, body: string): Promise<void> {
|
/** Tracks whether a command reached GitHub, so a failed run knows if it may be retried. */
|
||||||
|
interface CommandRun {
|
||||||
|
acted: boolean;
|
||||||
|
/** Records the command as done right before its GitHub write. */
|
||||||
|
beforeWrite?: () => Promise<void>;
|
||||||
|
/** This run wrote the "done" (only then may it give it back). */
|
||||||
|
markedDone?: boolean;
|
||||||
|
/** The command's "done" record, for writes committed together with it. */
|
||||||
|
done?: { key: string; ttl: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cmdComment(
|
||||||
|
env: Env,
|
||||||
|
msg: TelegramMessage,
|
||||||
|
body: string,
|
||||||
|
run: CommandRun,
|
||||||
|
): Promise<void> {
|
||||||
const chatId = chatIdOf(msg);
|
const chatId = chatIdOf(msg);
|
||||||
const telegramUserId = userIdOf(msg);
|
const telegramUserId = userIdOf(msg);
|
||||||
if (!chatId || !telegramUserId) return;
|
if (!chatId || !telegramUserId) return;
|
||||||
@@ -134,20 +201,35 @@ async function cmdComment(env: Env, msg: TelegramMessage, body: string): Promise
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const { htmlUrl, login } = await commentAsUser(
|
const { htmlUrl, login } = await commentAsUser(
|
||||||
env.KV,
|
env,
|
||||||
githubUserId,
|
githubUserId,
|
||||||
target.owner,
|
target.owner,
|
||||||
target.repo,
|
target.repo,
|
||||||
target.number,
|
target.number,
|
||||||
body,
|
body,
|
||||||
|
{ beforeWrite: run.beforeWrite },
|
||||||
);
|
);
|
||||||
|
run.acted = true;
|
||||||
await reply(env, chatId, topicId, `已以 **@${login}** 身份评论:${htmlUrl}`);
|
await reply(env, chatId, topicId, `已以 **@${login}** 身份评论:${htmlUrl}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Nothing reached GitHub yet: give the update back for a retry.
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
// Done, only its reply failed: the update must not run again.
|
||||||
|
if (run.acted) throw err;
|
||||||
|
// GitHub was called and may have acted (its answer lost): never run
|
||||||
|
// again. A refusal did nothing: should its reply fail, the command is
|
||||||
|
// given back and runs again.
|
||||||
|
if (!githubRefused(err)) run.acted = true;
|
||||||
await reply(env, chatId, topicId, errText(err));
|
await reply(env, chatId, topicId, errText(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "close"): Promise<void> {
|
async function cmdMergeClose(
|
||||||
|
env: Env,
|
||||||
|
msg: TelegramMessage,
|
||||||
|
op: "merge" | "close",
|
||||||
|
run: CommandRun,
|
||||||
|
): Promise<void> {
|
||||||
const chatId = chatIdOf(msg);
|
const chatId = chatIdOf(msg);
|
||||||
const telegramUserId = userIdOf(msg);
|
const telegramUserId = userIdOf(msg);
|
||||||
if (!chatId || !telegramUserId) return;
|
if (!chatId || !telegramUserId) return;
|
||||||
@@ -171,10 +253,23 @@ async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "clos
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
if (op === "merge") {
|
if (op === "merge") {
|
||||||
await mergePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number);
|
await mergePullRequestAsUser(
|
||||||
|
env,
|
||||||
|
githubUserId,
|
||||||
|
target.owner,
|
||||||
|
target.repo,
|
||||||
|
target.number,
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
},
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
await closePullRequestAsUser(env.KV, githubUserId, target.owner, target.repo, target.number);
|
await closePullRequestAsUser(env, githubUserId, target.owner, target.repo, target.number, {
|
||||||
|
beforeWrite: run.beforeWrite,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
run.acted = true;
|
||||||
const label = op === "merge" ? "合并" : "关闭";
|
const label = op === "merge" ? "合并" : "关闭";
|
||||||
await reply(
|
await reply(
|
||||||
env,
|
env,
|
||||||
@@ -183,6 +278,14 @@ async function cmdMergeClose(env: Env, msg: TelegramMessage, op: "merge" | "clos
|
|||||||
`✅ 已${label} PR ${target.owner}/${target.repo}#${target.number}`,
|
`✅ 已${label} PR ${target.owner}/${target.repo}#${target.number}`,
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Nothing reached GitHub yet: give the update back for a retry.
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
// Done, only its reply failed: the update must not run again.
|
||||||
|
if (run.acted) throw err;
|
||||||
|
// GitHub was called and may have acted (its answer lost): never run
|
||||||
|
// again. A refusal did nothing: should its reply fail, the command is
|
||||||
|
// given back and runs again.
|
||||||
|
if (!githubRefused(err)) run.acted = true;
|
||||||
await reply(env, chatId, topicId, errText(err));
|
await reply(env, chatId, topicId, errText(err));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,21 +296,45 @@ export async function syncTelegramWebhook(env: Env): Promise<void> {
|
|||||||
if (!token) return;
|
if (!token) return;
|
||||||
const baseUrl = env.BASE_URL;
|
const baseUrl = env.BASE_URL;
|
||||||
if (!baseUrl) return;
|
if (!baseUrl) return;
|
||||||
const secret = env.TELEGRAM_WEBHOOK_SECRET;
|
// Always registered with a secret (explicit or derived from the bot token),
|
||||||
|
// so the webhook endpoint can authenticate every call.
|
||||||
|
const secret = await telegramWebhookSecret(env);
|
||||||
|
const registration = {
|
||||||
|
url: `${baseUrl.replace(/\/$/, "")}/telegram/webhook`,
|
||||||
|
secret_token: secret,
|
||||||
|
allowed_updates: ["message"],
|
||||||
|
};
|
||||||
|
// Registered again only when the registration changed (or once a day, to
|
||||||
|
// repair a webhook changed elsewhere): this runs every few minutes, and
|
||||||
|
// each run would otherwise be a subrequest. One KV read per run; a write
|
||||||
|
// only when it registers.
|
||||||
|
const digest = [
|
||||||
|
...new Uint8Array(
|
||||||
|
await crypto.subtle.digest(
|
||||||
|
"SHA-256",
|
||||||
|
new TextEncoder().encode(`${token}|${JSON.stringify(registration)}`),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.slice(0, 12)
|
||||||
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
|
.join("");
|
||||||
|
// One record per bot holding what it is registered with now: switching
|
||||||
|
// A -> B -> A registers A again (a record per digest would still hold A's).
|
||||||
|
const marker = `telegram:webhook:${token.split(":")[0]}`;
|
||||||
|
if ((await env.KV.get(marker).catch(() => null)) === digest) return;
|
||||||
|
|
||||||
const res = await fetch(`https://api.telegram.org/bot${token}/setWebhook`, {
|
const res = await fetch(`https://api.telegram.org/bot${token}/setWebhook`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify(registration),
|
||||||
url: `${baseUrl.replace(/\/$/, "")}/telegram/webhook`,
|
|
||||||
secret_token: secret || undefined,
|
|
||||||
allowed_updates: ["message"],
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.text();
|
const err = await res.text();
|
||||||
log.error({ status: res.status, err }, "Failed to set Telegram webhook");
|
log.error({ status: res.status, err }, "Failed to set Telegram webhook");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
await env.KV.put(marker, digest, { expirationTtl: 86400 }).catch(() => undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Handle a single Telegram update (message). Called from the webhook route. */
|
/** Handle a single Telegram update (message). Called from the webhook route. */
|
||||||
@@ -215,32 +342,113 @@ export async function handleTelegramUpdate(env: Env, update: unknown): Promise<v
|
|||||||
const message = (update as { message?: TelegramMessage })?.message;
|
const message = (update as { message?: TelegramMessage })?.message;
|
||||||
if (!message?.text) return;
|
if (!message?.text) return;
|
||||||
|
|
||||||
const text = message.text.trim();
|
// Only leading space goes: a comment's trailing lines are its own.
|
||||||
const m = text.match(/^\/gh(?:\s+|$)(.*)$/s);
|
const text = message.text.replace(/^\s+/, "");
|
||||||
|
// `/gh@BotName ...` is how group chats address one bot among several: run
|
||||||
|
// it only when the name is this bot's.
|
||||||
|
const m = text.match(/^\/gh(?:@(\w+))?(?:\s+|$)(.*)$/s);
|
||||||
if (!m) return;
|
if (!m) return;
|
||||||
|
if (m[1] && m[1].toLowerCase() !== (await botUsername(env))) return;
|
||||||
|
|
||||||
const rest = (m[1] ?? "").trim();
|
// Telegram redelivers an update until the webhook answers 200; a command
|
||||||
const [sub, ...args] = rest.split(/\s+/);
|
// that already ran (e.g. its reply failed afterwards) must not run again,
|
||||||
const body = args.join(" ").trim();
|
// and one whose run is unconfirmed is retried later, never dropped.
|
||||||
|
const updateId = (update as { update_id?: number }).update_id;
|
||||||
|
const claims = idempotencyStore(env.DB, env.KV);
|
||||||
|
// Update ids count per bot: the key names the bot (the id before the
|
||||||
|
// token's ":", stable across token changes), so another bot's update with
|
||||||
|
// the same number is never taken for this one.
|
||||||
|
const botId = (env.TELEGRAM_TOKEN ?? "").split(":")[0] ?? "";
|
||||||
|
const claimKey = `bot:telegram:${botId}:${updateId}`;
|
||||||
|
if (updateId != null) {
|
||||||
|
// Handled under the key used before bots were told apart (kept one day).
|
||||||
|
if (await claims.has(acceptedKey(`bot:telegram:${updateId}`))) return;
|
||||||
|
const state = await claimOnce(claims, claimKey, COMMAND_CLAIM_SECONDS);
|
||||||
|
if (state === "done") return;
|
||||||
|
if (state === "pending") throw new Error("Telegram update is already being processed");
|
||||||
|
}
|
||||||
|
|
||||||
|
const rest = (m[2] ?? "").replace(/^\s+/, "");
|
||||||
|
const sub = rest.split(/\s/, 1)[0] ?? "";
|
||||||
|
// The comment as written: line breaks and indentation kept (only the
|
||||||
|
// separator after the subcommand goes — up to its first line break).
|
||||||
|
const body = rest.slice(sub.length).replace(/^[ \t]*\r?\n?/, "");
|
||||||
|
const run: CommandRun = { acted: false };
|
||||||
|
// Done on record before GitHub is written to: should the confirmation
|
||||||
|
// after it fail, a redelivery still never repeats the write.
|
||||||
|
if (updateId != null) {
|
||||||
|
run.done = { key: acceptedKey(claimKey), ttl: COMMAND_DONE_SECONDS };
|
||||||
|
run.beforeWrite = async (): Promise<void> => {
|
||||||
|
// Taken: a run that outlived its claim finds another run's "done" here
|
||||||
|
// and writes nothing.
|
||||||
|
if (!(await claims.claim(acceptedKey(claimKey), COMMAND_DONE_SECONDS)))
|
||||||
|
throw new CommandTakenError();
|
||||||
|
run.markedDone = true;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await runCommand(env, message, sub, body, text, run);
|
||||||
|
} catch (err) {
|
||||||
|
// Finished by another run meanwhile: nothing to give back or repeat.
|
||||||
|
if (err instanceof CommandTakenError) return;
|
||||||
|
// Failed before reaching GitHub (e.g. a storage error) or refused by it:
|
||||||
|
// give the update back (an early "done" too), so Telegram's redelivery
|
||||||
|
// runs it. After GitHub may have acted, it is done for good — running
|
||||||
|
// again would repeat the comment / merge.
|
||||||
|
if (updateId != null) {
|
||||||
|
if (run.acted) {
|
||||||
|
// Done for good; a "done" written before the GitHub write needs no
|
||||||
|
// second write.
|
||||||
|
if (!run.markedDone) await confirmDone();
|
||||||
|
} else {
|
||||||
|
// Only a "done" this run wrote: one another run wrote while this one
|
||||||
|
// outlived its claim stays.
|
||||||
|
if (run.markedDone) {
|
||||||
|
await claims.release(acceptedKey(claimKey)).catch(() => undefined);
|
||||||
|
}
|
||||||
|
await claims.release(claimKey).catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
// A "done" already written before the GitHub write needs no second write.
|
||||||
|
if (updateId != null && !run.markedDone) await confirmDone();
|
||||||
|
|
||||||
|
/** Best-effort: unconfirmed, the claim still holds off redeliveries until it expires. */
|
||||||
|
async function confirmDone(): Promise<void> {
|
||||||
|
await confirmClaim(claims, claimKey, COMMAND_DONE_SECONDS).catch((err: unknown) =>
|
||||||
|
log.warn({ err, updateId }, "Failed to confirm a Telegram update"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runCommand(
|
||||||
|
env: Env,
|
||||||
|
message: TelegramMessage,
|
||||||
|
sub: string | undefined,
|
||||||
|
body: string,
|
||||||
|
text: string,
|
||||||
|
run: CommandRun,
|
||||||
|
): Promise<void> {
|
||||||
switch (sub) {
|
switch (sub) {
|
||||||
case "login":
|
case "login":
|
||||||
return cmdLogin(env, message);
|
return cmdLogin(env, message);
|
||||||
case "logout":
|
case "logout":
|
||||||
return cmdLogout(env, message);
|
return cmdLogout(env, message, run);
|
||||||
case "comment":
|
case "comment":
|
||||||
if (!body) {
|
if (!body.trim()) {
|
||||||
const chatId = chatIdOf(message);
|
const chatId = chatIdOf(message);
|
||||||
const topicId =
|
const topicId =
|
||||||
message.message_thread_id != null ? String(message.message_thread_id) : undefined;
|
message.message_thread_id != null ? String(message.message_thread_id) : undefined;
|
||||||
if (chatId) await reply(env, chatId, topicId, "请附上评论内容:/gh comment 你的评论");
|
if (chatId) await reply(env, chatId, topicId, "请附上评论内容:/gh comment 你的评论");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return cmdComment(env, message, body);
|
return cmdComment(env, message, body, run);
|
||||||
case "merge":
|
case "merge":
|
||||||
return cmdMergeClose(env, message, "merge");
|
return cmdMergeClose(env, message, "merge", run);
|
||||||
case "close":
|
case "close":
|
||||||
return cmdMergeClose(env, message, "close");
|
return cmdMergeClose(env, message, "close", run);
|
||||||
default:
|
default:
|
||||||
log.info({ text }, "Unhandled /gh command from Telegram");
|
log.info({ text }, "Unhandled /gh command from Telegram");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import MarkdownIt from "markdown-it";
|
import MarkdownIt from "markdown-it";
|
||||||
import type { RouteTarget, Env, NeutralMessage } from "../../types";
|
import type { RouteTarget, Env, NeutralMessage } from "../../types";
|
||||||
import type { PlatformDriver, SendResult } from "../types";
|
import type { PlatformDriver, SendResult } from "../types";
|
||||||
import { sendMessage, sendPhoto, editMessageText, editMessageCaption } from "./rest";
|
import { sendMessage, editMessageText } from "./rest";
|
||||||
import { renderNeutralMessage } from "./render";
|
import { renderNeutralMessage } from "./render";
|
||||||
|
|
||||||
const markdown = new MarkdownIt({ html: false, linkify: false, breaks: false, typographer: false });
|
const markdown = new MarkdownIt({ html: false, linkify: false, breaks: false, typographer: false });
|
||||||
@@ -23,6 +23,19 @@ function richHeaderUrl(message: NeutralMessage, avatar: string, host: string): s
|
|||||||
return `${host.replace(/\/+$/, "")}/api/richheader?${params.toString()}`;
|
return `${host.replace(/\/+$/, "")}/api/richheader?${params.toString()}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The avatar shown above the text as a link preview: the rich-header card
|
||||||
|
* when a host serves it, the plain (small) avatar image otherwise. Messages
|
||||||
|
* are always text messages (never photos with captions), so every edit is an
|
||||||
|
* `editMessageText` with the full 4096-character budget.
|
||||||
|
*/
|
||||||
|
function previewUrl(message: NeutralMessage, env: Env): string | undefined {
|
||||||
|
const avatar = message.author?.iconUrl;
|
||||||
|
if (!avatar) return undefined;
|
||||||
|
const richHeaderHost = env.TELEGRAM_RICH_HEADER_HOST ?? env.BASE_URL;
|
||||||
|
return richHeaderHost ? richHeaderUrl(message, avatar, richHeaderHost) : smallAvatar(avatar);
|
||||||
|
}
|
||||||
|
|
||||||
export class TelegramDriver implements PlatformDriver {
|
export class TelegramDriver implements PlatformDriver {
|
||||||
readonly id = "telegram";
|
readonly id = "telegram";
|
||||||
|
|
||||||
@@ -33,16 +46,7 @@ export class TelegramDriver implements PlatformDriver {
|
|||||||
}
|
}
|
||||||
const token = env.TELEGRAM_TOKEN ?? "";
|
const token = env.TELEGRAM_TOKEN ?? "";
|
||||||
const text = renderNeutralMessage(message);
|
const text = renderNeutralMessage(message);
|
||||||
const avatar = message.author?.iconUrl;
|
return sendMessage(token, chatId, text, target.topicId, previewUrl(message, env));
|
||||||
const richHeaderHost = env.TELEGRAM_RICH_HEADER_HOST ?? env.BASE_URL;
|
|
||||||
if (avatar && richHeaderHost) {
|
|
||||||
const rhUrl = richHeaderUrl(message, avatar, richHeaderHost);
|
|
||||||
return sendMessage(token, chatId, text, target.topicId, rhUrl);
|
|
||||||
}
|
|
||||||
if (avatar) {
|
|
||||||
return sendPhoto(token, chatId, smallAvatar(avatar), text, target.topicId);
|
|
||||||
}
|
|
||||||
return sendMessage(token, chatId, text, target.topicId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async edit(
|
async edit(
|
||||||
@@ -57,15 +61,15 @@ export class TelegramDriver implements PlatformDriver {
|
|||||||
}
|
}
|
||||||
const token = env.TELEGRAM_TOKEN ?? "";
|
const token = env.TELEGRAM_TOKEN ?? "";
|
||||||
const text = renderNeutralMessage(message);
|
const text = renderNeutralMessage(message);
|
||||||
const avatar = message.author?.iconUrl;
|
// A photo sent by an older version has no text to edit; Telegram's error
|
||||||
const richHeaderHost = env.TELEGRAM_RICH_HEADER_HOST ?? env.BASE_URL;
|
// then makes dispatch send a fresh message instead.
|
||||||
if (avatar && richHeaderHost) {
|
return editMessageText(
|
||||||
const rhUrl = richHeaderUrl(message, avatar, richHeaderHost);
|
token,
|
||||||
return editMessageText(token, chatId, messageId, text, target.topicId, rhUrl);
|
chatId,
|
||||||
}
|
messageId,
|
||||||
if (avatar) {
|
text,
|
||||||
return editMessageCaption(token, chatId, messageId, text, target.topicId);
|
target.topicId,
|
||||||
}
|
previewUrl(message, env),
|
||||||
return editMessageText(token, chatId, messageId, text, target.topicId);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,9 @@ md.renderer.rules.strong_open = (): string => "<b>";
|
|||||||
md.renderer.rules.strong_close = (): string => "</b>";
|
md.renderer.rules.strong_close = (): string => "</b>";
|
||||||
md.renderer.rules.em_open = (): string => "<i>";
|
md.renderer.rules.em_open = (): string => "<i>";
|
||||||
md.renderer.rules.em_close = (): string => "</i>";
|
md.renderer.rules.em_close = (): string => "</i>";
|
||||||
|
// Telegram's HTML has no <br>: a Markdown hard break ("two spaces, newline")
|
||||||
|
// would get the whole message rejected. A plain newline breaks the line there.
|
||||||
|
md.renderer.rules.hardbreak = (): string => "\n";
|
||||||
|
|
||||||
function mdToHtml(s: string): string {
|
function mdToHtml(s: string): string {
|
||||||
return md.renderInline(s);
|
return md.renderInline(s);
|
||||||
@@ -37,13 +40,21 @@ function formatTimestamp(ts?: string): string {
|
|||||||
* an incomplete trailing tag and closes every tag still open at the cut
|
* an incomplete trailing tag and closes every tag still open at the cut
|
||||||
* point, so parse_mode HTML never rejects the message.
|
* point, so parse_mode HTML never rejects the message.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Clamp HTML to `max` characters as Telegram counts them — the text shown,
|
||||||
|
* tags left out and an entity (`&`) as one character — keeping tags and
|
||||||
|
* entities whole and closing the tags still open (an ellipsis marks the cut).
|
||||||
|
*/
|
||||||
function capHtml(text: string, max: number): string {
|
function capHtml(text: string, max: number): string {
|
||||||
if (text.length <= max) return text;
|
|
||||||
let cut = text.slice(0, max).replace(/<[^>]*$/u, "");
|
|
||||||
const stack: string[] = [];
|
const stack: string[] = [];
|
||||||
const re = /<(\/?)([a-z]+)(?:\s[^>]*)?>/g;
|
let shown = 0;
|
||||||
let m: RegExpExecArray | null;
|
let i = 0;
|
||||||
while ((m = re.exec(cut)) !== null) {
|
while (i < text.length) {
|
||||||
|
if (text[i] === "<") {
|
||||||
|
const end = text.indexOf(">", i);
|
||||||
|
if (end < 0) break;
|
||||||
|
const m = /^<(\/?)([a-z]+)/.exec(text.slice(i, end + 1));
|
||||||
|
if (m) {
|
||||||
const tag = m[2]!;
|
const tag = m[2]!;
|
||||||
if (m[1] === "/") {
|
if (m[1] === "/") {
|
||||||
const open = stack.lastIndexOf(tag);
|
const open = stack.lastIndexOf(tag);
|
||||||
@@ -52,11 +63,30 @@ function capHtml(text: string, max: number): string {
|
|||||||
stack.push(tag);
|
stack.push(tag);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const closers = stack
|
i = end + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const entity =
|
||||||
|
text[i] === "&" ? /^&(?:#\d+|#x[0-9a-f]+|[a-z]+);/i.exec(text.slice(i, i + 12)) : null;
|
||||||
|
const code = text.charCodeAt(i);
|
||||||
|
// A surrogate pair counts (and is cut) as the two code units it is.
|
||||||
|
const step = entity ? entity[0].length : code >= 0xd800 && code <= 0xdbff ? 2 : 1;
|
||||||
|
const weight = entity ? 1 : step;
|
||||||
|
// One character is kept for the ellipsis.
|
||||||
|
if (shown + weight > max - 1) {
|
||||||
|
const rest = text.slice(i).replace(/<[^>]*>/g, "");
|
||||||
|
// What is left fits after all (no ellipsis needed).
|
||||||
|
if (shown + rest.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, "x").length <= max) return text;
|
||||||
|
const closers = [...stack]
|
||||||
.reverse()
|
.reverse()
|
||||||
.map((tag) => `</${tag}>`)
|
.map((tag) => `</${tag}>`)
|
||||||
.join("");
|
.join("");
|
||||||
return `${cut}…${closers}`;
|
return `${text.slice(0, i)}…${closers}`;
|
||||||
|
}
|
||||||
|
shown += weight;
|
||||||
|
i += step;
|
||||||
|
}
|
||||||
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderNeutralMessage(message: NeutralMessage): string {
|
export function renderNeutralMessage(message: NeutralMessage): string {
|
||||||
@@ -76,7 +106,7 @@ export function renderNeutralMessage(message: NeutralMessage): string {
|
|||||||
if (message.author) {
|
if (message.author) {
|
||||||
const name = mdToHtml(message.author.name);
|
const name = mdToHtml(message.author.name);
|
||||||
const author = message.author.url ? `<a href="${esc(message.author.url)}">${name}</a>` : name;
|
const author = message.author.url ? `<a href="${esc(message.author.url)}">${name}</a>` : name;
|
||||||
parts.push(`👤 ${author}`);
|
parts.push(message.emoji === false ? author : `👤 ${author}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.description) {
|
if (message.description) {
|
||||||
|
|||||||
@@ -7,8 +7,21 @@ interface TelegramResponse {
|
|||||||
ok?: boolean;
|
ok?: boolean;
|
||||||
description?: string;
|
description?: string;
|
||||||
result?: { message_id?: number };
|
result?: { message_id?: number };
|
||||||
|
parameters?: { retry_after?: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest rate-limit wait (seconds) slept inside one request; a longer one is
|
||||||
|
* returned as a 429 failure so the delivery queue retries it later instead.
|
||||||
|
*/
|
||||||
|
const MAX_INLINE_RETRY_AFTER = 10;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Longest a single API call may take. Bounded, so a message edit always ends
|
||||||
|
* well within the update-chain lock it runs under (see `deliverUpdate`).
|
||||||
|
*/
|
||||||
|
export const REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
async function post(
|
async function post(
|
||||||
token: string,
|
token: string,
|
||||||
method: string,
|
method: string,
|
||||||
@@ -25,13 +38,25 @@ async function post(
|
|||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(body),
|
||||||
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||||
});
|
});
|
||||||
lastStatus = res.status;
|
lastStatus = res.status;
|
||||||
const data = (await res.json().catch(() => null)) as TelegramResponse | null;
|
const data = (await res.json().catch(() => null)) as TelegramResponse | null;
|
||||||
|
|
||||||
if (res.status === 429) {
|
if (res.status === 429) {
|
||||||
const retryAfter = (data as { retry_after?: number })?.retry_after ?? 1;
|
// Telegram reports the wait in `parameters.retry_after` (seconds).
|
||||||
|
const raw = Number(data?.parameters?.retry_after);
|
||||||
|
const retryAfter = Number.isFinite(raw) && raw > 0 ? raw : 1;
|
||||||
lastError = data?.description ?? `Rate limited (retry_after=${retryAfter})`;
|
lastError = data?.description ?? `Rate limited (retry_after=${retryAfter})`;
|
||||||
|
if (retryAfter > MAX_INLINE_RETRY_AFTER || attempt === 2) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: lastError,
|
||||||
|
errorCode: "RATE_LIMITED",
|
||||||
|
status: 429,
|
||||||
|
attempts: attempt + 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
await new Promise((r) => setTimeout(r, retryAfter * 1000));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -51,10 +76,25 @@ async function post(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Accepted, but the answer is unreadable (cut off, timed out): the
|
||||||
|
// message may well exist, and Telegram has no idempotency key, so a
|
||||||
|
// retry could post it twice — a visible failure, not retried (and not
|
||||||
|
// a success without a message id, which an update chain would lose).
|
||||||
|
if (data?.ok !== true) {
|
||||||
|
log.error({ status: res.status, chatId }, "Unreadable Telegram response");
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
error: "Telegram accepted the request, but its answer could not be read",
|
||||||
|
errorCode: "TELEGRAM_UNCERTAIN",
|
||||||
|
status: res.status,
|
||||||
|
attempts: attempt + 1,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
status: res.status,
|
status: res.status,
|
||||||
messageId: data?.result?.message_id != null ? String(data.result.message_id) : undefined,
|
messageId: data.result?.message_id != null ? String(data.result.message_id) : undefined,
|
||||||
attempts: attempt + 1,
|
attempts: attempt + 1,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import type { Env } from "../../types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `secret_token` Telegram must send with every webhook call. It is
|
||||||
|
* `TELEGRAM_WEBHOOK_SECRET` when set, otherwise derived from the bot token
|
||||||
|
* (which is itself secret), so the webhook endpoint is never left
|
||||||
|
* unauthenticated. Empty when no bot token is configured.
|
||||||
|
*/
|
||||||
|
export async function telegramWebhookSecret(env: Env): Promise<string> {
|
||||||
|
const explicit = env.TELEGRAM_WEBHOOK_SECRET?.trim();
|
||||||
|
if (explicit) return explicit;
|
||||||
|
const token = env.TELEGRAM_TOKEN?.trim();
|
||||||
|
if (!token) return "";
|
||||||
|
const digest = await crypto.subtle.digest(
|
||||||
|
"SHA-256",
|
||||||
|
new TextEncoder().encode(`webhooker:telegram-webhook:${token}`),
|
||||||
|
);
|
||||||
|
// Telegram allows 1-256 characters of A-Z, a-z, 0-9, `_` and `-`.
|
||||||
|
return Array.from(new Uint8Array(digest))
|
||||||
|
.map((b) => b.toString(16).padStart(2, "0"))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import type { Env } from "../../types";
|
import type { Env } from "../../types";
|
||||||
|
import { log } from "../../lib/log";
|
||||||
import { handleTelegramUpdate } from "./commands";
|
import { handleTelegramUpdate } from "./commands";
|
||||||
|
import { telegramWebhookSecret } from "./secret";
|
||||||
|
|
||||||
const MAX_BODY_SIZE = 1024 * 1024;
|
const MAX_BODY_SIZE = 1024 * 1024;
|
||||||
|
|
||||||
@@ -19,13 +21,17 @@ export async function handleTelegramWebhookRequest(request: Request, env: Env):
|
|||||||
return new Response("Request too large", { status: 413 });
|
return new Response("Request too large", { status: 413 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const secret = env.TELEGRAM_WEBHOOK_SECRET;
|
// Every call must carry the webhook secret. Without a bot token there is
|
||||||
if (secret) {
|
// no secret to check and nothing to act with, so the endpoint stays closed.
|
||||||
|
const secret = await telegramWebhookSecret(env);
|
||||||
|
if (!secret) {
|
||||||
|
log.warn("Telegram webhook called but TELEGRAM_TOKEN is not configured");
|
||||||
|
return new Response("Telegram is not configured", { status: 403 });
|
||||||
|
}
|
||||||
const token = request.headers.get("X-Telegram-Bot-Api-Secret-Token");
|
const token = request.headers.get("X-Telegram-Bot-Api-Secret-Token");
|
||||||
if (!token || !timingSafeEqual(token, secret)) {
|
if (!token || !timingSafeEqual(token, secret)) {
|
||||||
return new Response("Invalid secret", { status: 401 });
|
return new Response("Invalid secret", { status: 401 });
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
const rawBody = await request.text();
|
const rawBody = await request.text();
|
||||||
if (rawBody.length > MAX_BODY_SIZE) {
|
if (rawBody.length > MAX_BODY_SIZE) {
|
||||||
|
|||||||
+132
-25
@@ -1,40 +1,93 @@
|
|||||||
|
import { RE2JS } from "re2js";
|
||||||
import type { WebhookEvent, Filter, FilterNode, FilterOp } from "../types";
|
import type { WebhookEvent, Filter, FilterNode, FilterOp } from "../types";
|
||||||
|
|
||||||
const regexCache = new Map<string, RegExp>();
|
/** A compiled user pattern; `test` searches (like `RegExp#test`). */
|
||||||
|
interface Pattern {
|
||||||
|
test(text: string): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const patternCache = new Map<string, Pattern | null>();
|
||||||
const keywordBodyCache = new WeakMap<WebhookEvent, string>();
|
const keywordBodyCache = new WeakMap<WebhookEvent, string>();
|
||||||
const MAX_PATTERN_LENGTH = 200;
|
const MAX_PATTERN_LENGTH = 200;
|
||||||
|
const MAX_CACHED_PATTERNS = 500;
|
||||||
|
|
||||||
function isWrappedRegex(pattern: string): boolean {
|
function isWrappedRegex(pattern: string): boolean {
|
||||||
return pattern.length >= 2 && pattern.startsWith("/") && pattern.endsWith("/");
|
return pattern.length >= 2 && pattern.startsWith("/") && pattern.endsWith("/");
|
||||||
}
|
}
|
||||||
|
|
||||||
function compileRegex(pattern: string): RegExp | null {
|
/**
|
||||||
if (pattern.length > MAX_PATTERN_LENGTH) return null;
|
* Compile with RE2 (re2js): matching runs in time linear in the input, so no
|
||||||
const cached = regexCache.get(pattern);
|
* pattern — however it nests or repeats — can stall a Worker on a crafted
|
||||||
if (cached) return cached;
|
* payload. RE2 has no backreferences or lookaround; such patterns are invalid.
|
||||||
|
*/
|
||||||
|
function compileRe2(source: string): Pattern {
|
||||||
|
const re = RE2JS.compile(source, RE2JS.CASE_INSENSITIVE);
|
||||||
|
return { test: (text: string): boolean => re.matcher(text).find() };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Why a user-supplied regex cannot be used, or null when it is fine. Patterns
|
||||||
|
* run on the linear-time RE2 engine, so only the length limit and the RE2
|
||||||
|
* syntax (no backreferences or lookaround) constrain them.
|
||||||
|
*/
|
||||||
|
export function regexSafetyIssue(source: string): string | null {
|
||||||
|
if (source.length > MAX_PATTERN_LENGTH) return "pattern is too long";
|
||||||
try {
|
try {
|
||||||
const re = new RegExp(pattern, "i");
|
compileRe2(source);
|
||||||
regexCache.set(pattern, re);
|
|
||||||
return re;
|
|
||||||
} catch {
|
|
||||||
return null;
|
return null;
|
||||||
|
} catch {
|
||||||
|
return "invalid or unsupported regular expression (RE2 syntax: no backreferences or lookaround)";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function compileGlob(pattern: string, anchored: boolean): RegExp | null {
|
function cached(key: string, build: () => Pattern | null): Pattern | null {
|
||||||
if (pattern.length > MAX_PATTERN_LENGTH) return null;
|
if (patternCache.has(key)) {
|
||||||
const cacheKey = `${anchored ? "a" : "s"}:${pattern}`;
|
// Most recently used last: the oldest unused pattern is evicted first.
|
||||||
const cached = regexCache.get(cacheKey);
|
const hit = patternCache.get(key) ?? null;
|
||||||
if (cached) return cached;
|
patternCache.delete(key);
|
||||||
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
patternCache.set(key, hit);
|
||||||
const body = escaped.replace(/\*/g, ".*").replace(/\?/g, ".");
|
return hit;
|
||||||
try {
|
}
|
||||||
const re = new RegExp(anchored ? `^${body}$` : body, "i");
|
// Bounded: patterns come from every group's routes and test requests. One
|
||||||
regexCache.set(cacheKey, re);
|
// pattern makes room at a time — clearing everything would recompile every
|
||||||
|
// pattern in use once the limit is reached.
|
||||||
|
if (patternCache.size >= MAX_CACHED_PATTERNS) {
|
||||||
|
patternCache.delete(patternCache.keys().next().value!);
|
||||||
|
}
|
||||||
|
const re = build();
|
||||||
|
patternCache.set(key, re);
|
||||||
return re;
|
return re;
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileRegex(pattern: string): Pattern | null {
|
||||||
|
// Regex and glob entries live under distinct prefixes: the regex `a:foo*`
|
||||||
|
// and the anchored glob `foo*` must never share a cache slot.
|
||||||
|
return cached(`r:${pattern}`, () => {
|
||||||
|
if (pattern.length > MAX_PATTERN_LENGTH) return null;
|
||||||
|
try {
|
||||||
|
return compileRe2(pattern);
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function compileGlob(pattern: string, anchored: boolean): Pattern | null {
|
||||||
|
if (pattern.length > MAX_PATTERN_LENGTH) return null;
|
||||||
|
// Repeated `*` match the same as one; an unanchored search needs no leading
|
||||||
|
// or trailing `*` at all.
|
||||||
|
let glob = pattern.replace(/\*+/g, "*");
|
||||||
|
if (!anchored) glob = glob.replace(/^\*+|\*+$/g, "");
|
||||||
|
return cached(`${anchored ? "a" : "s"}:${glob}`, () => {
|
||||||
|
const escaped = glob.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
||||||
|
// One pass: a sequential replace would rewrite the `?` of `(?s:` again.
|
||||||
|
const body = escaped.replace(/[*?]/g, (c) => (c === "*" ? "(?s:.*)" : "(?s:.)"));
|
||||||
|
try {
|
||||||
|
return compileRe2(anchored ? `^${body}$` : body);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function isGlob(pattern: string): boolean {
|
function isGlob(pattern: string): boolean {
|
||||||
@@ -77,7 +130,7 @@ function extractBranch(event: WebhookEvent): string | undefined {
|
|||||||
const p = event.payload;
|
const p = event.payload;
|
||||||
switch (event.event) {
|
switch (event.event) {
|
||||||
case "push":
|
case "push":
|
||||||
return typeof p.ref === "string" ? p.ref.replace("refs/heads/", "") : undefined;
|
return typeof p.ref === "string" ? p.ref.replace(/^refs\/heads\//, "") : undefined;
|
||||||
case "pull_request":
|
case "pull_request":
|
||||||
case "pull_request_review":
|
case "pull_request_review":
|
||||||
case "pull_request_review_comment":
|
case "pull_request_review_comment":
|
||||||
@@ -89,14 +142,22 @@ function extractBranch(event: WebhookEvent): string | undefined {
|
|||||||
return (p.workflow_run as { head_branch?: string } | undefined)?.head_branch;
|
return (p.workflow_run as { head_branch?: string } | undefined)?.head_branch;
|
||||||
case "check_suite":
|
case "check_suite":
|
||||||
return (p.check_suite as { head_branch?: string } | undefined)?.head_branch;
|
return (p.check_suite as { head_branch?: string } | undefined)?.head_branch;
|
||||||
|
case "check_run":
|
||||||
|
return (p.check_run as { check_suite?: { head_branch?: string } } | undefined)?.check_suite
|
||||||
|
?.head_branch;
|
||||||
case "workflow_job":
|
case "workflow_job":
|
||||||
return (p.workflow_job as { head_branch?: string } | undefined)?.head_branch;
|
return (p.workflow_job as { head_branch?: string } | undefined)?.head_branch;
|
||||||
case "deployment":
|
case "deployment":
|
||||||
return typeof p.ref === "string" ? p.ref.replace("refs/heads/", "") : undefined;
|
case "deployment_status": {
|
||||||
|
// The deployed ref lives on the deployment object (a top-level `ref` is
|
||||||
|
// only read as a fallback).
|
||||||
|
const ref = (p.deployment as { ref?: unknown } | undefined)?.ref ?? p.ref;
|
||||||
|
return typeof ref === "string" ? ref.replace(/^refs\/heads\//, "") : undefined;
|
||||||
|
}
|
||||||
case "commit_comment":
|
case "commit_comment":
|
||||||
return undefined;
|
return undefined;
|
||||||
case "code_scanning_alert":
|
case "code_scanning_alert":
|
||||||
return typeof p.ref === "string" ? p.ref : undefined;
|
return typeof p.ref === "string" ? p.ref.replace(/^refs\/heads\//, "") : undefined;
|
||||||
default:
|
default:
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
@@ -111,7 +172,8 @@ function stringify(value: unknown): string {
|
|||||||
if (typeof value === "string") return value;
|
if (typeof value === "string") return value;
|
||||||
if (value === undefined || value === null) return "";
|
if (value === undefined || value === null) return "";
|
||||||
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
||||||
return JSON.stringify(value);
|
// Payload values are JSON; anything else (should it appear) compares as "".
|
||||||
|
return JSON.stringify(value) ?? "";
|
||||||
}
|
}
|
||||||
|
|
||||||
function toNumber(value: unknown): number | null {
|
function toNumber(value: unknown): number | null {
|
||||||
@@ -142,8 +204,11 @@ function walkPath(node: unknown, parts: string[], index: number, out: unknown[])
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (node === null || node === undefined || typeof node !== "object") return;
|
if (node === null || node === undefined || typeof node !== "object") return;
|
||||||
const next = (node as Record<string, unknown>)[parts[index]!];
|
// Own properties only: `constructor`, `__proto__`, `toString`... are not
|
||||||
walkPath(next, parts, index + 1, out);
|
// payload data and must never reach the comparison.
|
||||||
|
const key = parts[index]!;
|
||||||
|
if (!Object.prototype.hasOwnProperty.call(node, key)) return;
|
||||||
|
walkPath((node as Record<string, unknown>)[key], parts, index + 1, out);
|
||||||
}
|
}
|
||||||
|
|
||||||
function valueList(filter: Filter, event: WebhookEvent): unknown[] {
|
function valueList(filter: Filter, event: WebhookEvent): unknown[] {
|
||||||
@@ -220,6 +285,48 @@ function matchFilter(filter: Filter, event: WebhookEvent, keywordBody?: string):
|
|||||||
return filter.exclude ? !matches : matches;
|
return filter.exclude ? !matches : matches;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a filter tree has the shape the evaluator assumes: every node is a
|
||||||
|
* leaf (`type`, no `all`/`any`/`not`) or exactly one combinator holding nodes
|
||||||
|
* of the same shape. A node mixing kinds (`{"all": 0, "any": [...]}`) passes
|
||||||
|
* a lenient schema but makes the evaluator throw.
|
||||||
|
*/
|
||||||
|
export function filterNodeWellFormed(node: unknown): boolean {
|
||||||
|
if (!node || typeof node !== "object" || Array.isArray(node)) return false;
|
||||||
|
const n = node as Record<string, unknown>;
|
||||||
|
const kinds = (["all", "any", "not"] as const).filter((k) => k in n);
|
||||||
|
if (kinds.length > 1) return false;
|
||||||
|
const kind = kinds[0];
|
||||||
|
if (kind === "all" || kind === "any") {
|
||||||
|
const list = n[kind];
|
||||||
|
return Array.isArray(list) && list.every(filterNodeWellFormed);
|
||||||
|
}
|
||||||
|
if (kind === "not") return filterNodeWellFormed(n.not);
|
||||||
|
return typeof n.type === "string";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether every pattern in a filter tree can actually run the way the matcher
|
||||||
|
* reads it — a regex compiles on the engine in use, a glob compiles within
|
||||||
|
* the length limit. One that cannot (written for another engine, e.g. with
|
||||||
|
* lookahead, or too long) would quietly never match — and flip an `exclude`
|
||||||
|
* into a pass. Literal comparisons (`contains`, `startsWith`, ...) are not
|
||||||
|
* patterns and always run.
|
||||||
|
*/
|
||||||
|
export function filterPatternsUsable(node: FilterNode): boolean {
|
||||||
|
if ("all" in node) return node.all.every(filterPatternsUsable);
|
||||||
|
if ("any" in node) return node.any.every(filterPatternsUsable);
|
||||||
|
if ("not" in node) return filterPatternsUsable(node.not);
|
||||||
|
const op = node.type === "keyword" ? "keyword" : (node.op ?? "eq");
|
||||||
|
return toPatterns(node).every((p) => {
|
||||||
|
if (op === "regex") return compileRegex(p) !== null;
|
||||||
|
if (op !== "eq" && op !== "in" && op !== "ne" && op !== "keyword") return true;
|
||||||
|
if (isWrappedRegex(p)) return compileRegex(p.slice(1, -1)) !== null;
|
||||||
|
if (isGlob(p)) return compileGlob(p, op !== "keyword") !== null;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export function containsKeyword(node: FilterNode): boolean {
|
export function containsKeyword(node: FilterNode): boolean {
|
||||||
if ("all" in node) return node.all.some(containsKeyword);
|
if ("all" in node) return node.all.some(containsKeyword);
|
||||||
if ("any" in node) return node.any.some(containsKeyword);
|
if ("any" in node) return node.any.some(containsKeyword);
|
||||||
|
|||||||
@@ -184,7 +184,13 @@ export function formatCheckRun(
|
|||||||
details_url?: string;
|
details_url?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
output?: { title?: string; summary?: string };
|
output?: { title?: string; summary?: string };
|
||||||
|
check_suite?: { id?: number };
|
||||||
|
app?: { id?: number };
|
||||||
};
|
};
|
||||||
|
// Phases of one check (a fresh run id each, as Cloudflare Pages sends them)
|
||||||
|
// share a suite; two checks of the same name from different workflows or
|
||||||
|
// apps do not — they never share a message.
|
||||||
|
const owner = checkRun.check_suite?.id ?? checkRun.app?.id;
|
||||||
|
|
||||||
const status = workflowStatus(checkRun.status, checkRun.conclusion);
|
const status = workflowStatus(checkRun.status, checkRun.conclusion);
|
||||||
const emoji = WORKFLOW_CONCLUSION_EMOJI[status] ?? "⏳";
|
const emoji = WORKFLOW_CONCLUSION_EMOJI[status] ?? "⏳";
|
||||||
@@ -226,9 +232,14 @@ export function formatCheckRun(
|
|||||||
url: checkRun.html_url,
|
url: checkRun.html_url,
|
||||||
color: GITHUB_COLORS[colorKey],
|
color: GITHUB_COLORS[colorKey],
|
||||||
fields,
|
fields,
|
||||||
|
// Chains tracked before the suite joined the key.
|
||||||
|
legacyUpdateKey:
|
||||||
|
repo && checkRun.name && checkRun.head_sha && owner != null
|
||||||
|
? `check_run:${repo}:${checkRun.name}:${checkRun.head_sha}`
|
||||||
|
: undefined,
|
||||||
updateKey:
|
updateKey:
|
||||||
repo && checkRun.name && checkRun.head_sha
|
repo && checkRun.name && checkRun.head_sha
|
||||||
? `check_run:${repo}:${checkRun.name}:${checkRun.head_sha}`
|
? `check_run:${repo}:${owner != null ? `${owner}:` : ""}${checkRun.name}:${checkRun.head_sha}`
|
||||||
: repo && checkRun.id != null
|
: repo && checkRun.id != null
|
||||||
? `check_run:${repo}:${checkRun.id}`
|
? `check_run:${repo}:${checkRun.id}`
|
||||||
: undefined,
|
: undefined,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
type T,
|
type T,
|
||||||
buildMessage,
|
buildMessage,
|
||||||
repoBaseUrl,
|
repoBaseUrl,
|
||||||
|
shortRef,
|
||||||
} from "./helpers";
|
} from "./helpers";
|
||||||
|
|
||||||
/** Shared "branch/tag + commit" fields for deployment events. */
|
/** Shared "branch/tag + commit" fields for deployment events. */
|
||||||
@@ -21,7 +22,10 @@ function addDeploymentRefFields(
|
|||||||
const isTag = deployment.ref.startsWith("refs/tags/");
|
const isTag = deployment.ref.startsWith("refs/tags/");
|
||||||
fields.push({
|
fields.push({
|
||||||
name: t("fields.branch_tag"),
|
name: t("fields.branch_tag"),
|
||||||
value: isTag ? tagLink(baseUrl, deployment.ref) : branchLink(baseUrl, deployment.ref),
|
// A deployment's ref may be a full ref: its one leading prefix goes.
|
||||||
|
value: isTag
|
||||||
|
? tagLink(baseUrl, shortRef(deployment.ref))
|
||||||
|
: branchLink(baseUrl, shortRef(deployment.ref)),
|
||||||
inline: true,
|
inline: true,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -133,7 +137,7 @@ export function formatDeploymentStatus(
|
|||||||
|
|
||||||
fields.push({
|
fields.push({
|
||||||
name: t("fields.status"),
|
name: t("fields.status"),
|
||||||
value: `${em(emoji)}${status}`,
|
value: `${em(emoji)}${state}`,
|
||||||
inline: true,
|
inline: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -67,30 +67,42 @@ export function commitLink(baseUrl: string | undefined, sha: string, short?: str
|
|||||||
return baseUrl ? `[\`${label}\`](${baseUrl}/commit/${encodeRefPath(sha)})` : `\`${label}\``;
|
return baseUrl ? `[\`${label}\`](${baseUrl}/commit/${encodeRefPath(sha)})` : `\`${label}\``;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Inline code + hyperlink for a branch (or bare ref), e.g. [`main`](.../tree/main). */
|
/**
|
||||||
|
* A ref's short name: only one leading `refs/heads/` or `refs/tags/` goes —
|
||||||
|
* a branch may itself contain such a path (`feature/refs/tags/test`).
|
||||||
|
*/
|
||||||
|
export function shortRef(ref: string): string {
|
||||||
|
return ref.replace(/^refs\/(?:heads|tags)\//, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inline code + hyperlink for a branch, e.g. [`main`](.../tree/main). Takes
|
||||||
|
* the short name, as written (a branch may well be called `refs/heads/x`);
|
||||||
|
* a full ref is shortened by the caller (`shortRef`).
|
||||||
|
*/
|
||||||
export function branchLink(baseUrl: string | undefined, branch: string, label?: string): string {
|
export function branchLink(baseUrl: string | undefined, branch: string, label?: string): string {
|
||||||
const clean = branch.replace("refs/heads/", "").replace("refs/tags/", "");
|
const clean = branch;
|
||||||
const display = label ?? clean;
|
const display = label ?? clean;
|
||||||
return baseUrl ? `[\`${display}\`](${baseUrl}/tree/${encodeRefPath(clean)})` : `\`${display}\``;
|
return baseUrl ? `[\`${display}\`](${baseUrl}/tree/${encodeRefPath(clean)})` : `\`${display}\``;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Inline code + hyperlink for a tag, e.g. [`v1.0`](.../releases/tag/v1.0). */
|
/** Inline code + hyperlink for a tag (its short name), e.g. [`v1.0`](.../releases/tag/v1.0). */
|
||||||
export function tagLink(baseUrl: string | undefined, tag: string, label?: string): string {
|
export function tagLink(baseUrl: string | undefined, tag: string, label?: string): string {
|
||||||
const clean = tag.replace("refs/tags/", "");
|
const clean = tag;
|
||||||
const display = label ?? clean;
|
const display = label ?? clean;
|
||||||
return baseUrl
|
return baseUrl
|
||||||
? `[\`${display}\`](${baseUrl}/releases/tag/${encodeRefPath(clean)})`
|
? `[\`${display}\`](${baseUrl}/releases/tag/${encodeRefPath(clean)})`
|
||||||
: `\`${display}\``;
|
: `\`${display}\``;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** URL for a branch or tag, when the repository base URL is available. */
|
/** URL for a branch or tag (its short name), when the repository base URL is available. */
|
||||||
export function refUrl(
|
export function refUrl(
|
||||||
baseUrl: string | undefined,
|
baseUrl: string | undefined,
|
||||||
ref: string,
|
ref: string,
|
||||||
type: "branch" | "tag",
|
type: "branch" | "tag",
|
||||||
): string | undefined {
|
): string | undefined {
|
||||||
if (!baseUrl) return undefined;
|
if (!baseUrl) return undefined;
|
||||||
const clean = ref.replace("refs/heads/", "").replace("refs/tags/", "");
|
const clean = ref;
|
||||||
return type === "tag"
|
return type === "tag"
|
||||||
? `${baseUrl}/releases/tag/${encodeRefPath(clean)}`
|
? `${baseUrl}/releases/tag/${encodeRefPath(clean)}`
|
||||||
: `${baseUrl}/tree/${encodeRefPath(clean)}`;
|
: `${baseUrl}/tree/${encodeRefPath(clean)}`;
|
||||||
@@ -110,28 +122,105 @@ export function cap(text: string, max: number): string {
|
|||||||
return text.length > max ? text.slice(0, max) : text;
|
return text.length > max ? text.slice(0, max) : text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A numeric character reference, kept verbatim when it names no valid code point. */
|
||||||
|
function codePoint(value: number, original: string): string {
|
||||||
|
if (!Number.isInteger(value) || value < 0 || value > 0x10ffff) return original;
|
||||||
|
if (value >= 0xd800 && value <= 0xdfff) return original;
|
||||||
|
return String.fromCodePoint(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Markdown code and autolinks, which are text as written (see `htmlToText`):
|
||||||
|
* - a fenced block — ``` or ~~~ (3 or more) at a line start, closed by a
|
||||||
|
* fence of that same character, at least as long, or by the end of the text;
|
||||||
|
* - an indented code block — lines indented by 4 spaces or a tab;
|
||||||
|
* - an inline span — a run of backticks closed by a run of the same length
|
||||||
|
* within 1000 characters (a shorter or longer run inside is content),
|
||||||
|
* possibly across lines — bounded, so unmatched runs cost little;
|
||||||
|
* - an autolink — `<scheme:…>` or an e-mail address `<name@host>`.
|
||||||
|
*/
|
||||||
|
const MARKDOWN_VERBATIM =
|
||||||
|
/^ {0,3}(?<fence>(?<fc>[`~])\k<fc>{2,})[^\n]*(?:\n[\s\S]*?(?:\n {0,3}\k<fence>\k<fc>*[ \t]*(?=\n|$(?![\s\S]))|$(?![\s\S]))|$(?![\s\S]))|^(?: {4}|\t)[^\n]*(?:\n(?: {4}|\t)[^\n]*)*|(?<!`)(?<tick>`+)(?!`)[\s\S]{0,1000}?(?<!`)\k<tick>(?!`)|<[a-z][a-z0-9+.-]*:[^\s<>]*>|<[^\s<>@]+@[^\s<>@]+>/gim;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Most of a body cleaned: callers keep a few hundred characters of the
|
||||||
|
* result, and an unbounded body (megabytes of markup) must not cost an
|
||||||
|
* unbounded amount of CPU on every delivery and retry.
|
||||||
|
*/
|
||||||
|
const MAX_HTML_INPUT = 10_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recent results: one event's body is summarized for every route it matches
|
||||||
|
* (each route formats its own message), so the same text is cleaned once.
|
||||||
|
*/
|
||||||
|
const htmlToTextCache = new Map<string, string>();
|
||||||
|
const HTML_TO_TEXT_CACHE_SIZE = 32;
|
||||||
|
|
||||||
export function htmlToText(input: string): string {
|
export function htmlToText(input: string): string {
|
||||||
if (!input) return "";
|
if (!input) return "";
|
||||||
|
const cached = htmlToTextCache.get(input);
|
||||||
|
if (cached !== undefined) return cached;
|
||||||
|
const result = htmlToTextUncached(input);
|
||||||
|
if (htmlToTextCache.size >= HTML_TO_TEXT_CACHE_SIZE) {
|
||||||
|
htmlToTextCache.delete(htmlToTextCache.keys().next().value!);
|
||||||
|
}
|
||||||
|
htmlToTextCache.set(input, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function htmlToTextUncached(input: string): string {
|
||||||
|
const text = input.length > MAX_HTML_INPUT ? input.slice(0, MAX_HTML_INPUT) : input;
|
||||||
|
// Markdown code and autolinks are text as written: `<T>` or
|
||||||
|
// `<MyComponent />` there is content, not HTML to strip, an entity there is
|
||||||
|
// literal, and its spacing (a leading indent included) is its own. Only the
|
||||||
|
// text around them is cleaned and trimmed.
|
||||||
|
const parts: Array<{ text: string; verbatim: boolean }> = [];
|
||||||
|
let last = 0;
|
||||||
|
for (const m of text.matchAll(MARKDOWN_VERBATIM)) {
|
||||||
|
parts.push({ text: clean(text.slice(last, m.index)), verbatim: false });
|
||||||
|
parts.push({ text: m[0], verbatim: true });
|
||||||
|
last = m.index + m[0].length;
|
||||||
|
}
|
||||||
|
parts.push({ text: clean(text.slice(last)), verbatim: false });
|
||||||
|
const first = parts.findIndex((p) => p.text.trim() !== "");
|
||||||
|
if (first < 0) return "";
|
||||||
|
const kept = parts.slice(first);
|
||||||
|
while (kept.length && kept[kept.length - 1]!.text.trim() === "") kept.pop();
|
||||||
|
if (!kept[0]!.verbatim) kept[0]!.text = kept[0]!.text.trimStart();
|
||||||
|
const end = kept[kept.length - 1]!;
|
||||||
|
if (!end.verbatim) end.text = end.text.trimEnd();
|
||||||
|
return kept.map((p) => p.text).join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
function clean(text: string): string {
|
||||||
|
return stripHtml(text)
|
||||||
|
.replace(/[ \t]+\n/g, "\n")
|
||||||
|
.replace(/\n{3,}/g, "\n\n");
|
||||||
|
}
|
||||||
|
|
||||||
|
function stripHtml(input: string): string {
|
||||||
|
// A tag never spans another `<`: each `<` is looked at once, so text full
|
||||||
|
// of unclosed `<` stays linear.
|
||||||
let out = input
|
let out = input
|
||||||
.replace(/<br\s*\/?>/gi, "\n")
|
.replace(/<br\s*\/?>/gi, "\n")
|
||||||
.replace(/<table[^>]*>/gi, "\n")
|
.replace(/<table[^<>]*>/gi, "\n")
|
||||||
.replace(/<\/(p|div|tr|h[1-6]|ul|ol|table|blockquote)>/gi, "\n")
|
.replace(/<\/(p|div|tr|h[1-6]|ul|ol|table|blockquote)>/gi, "\n")
|
||||||
.replace(/<\/t[dh]>/gi, " ")
|
.replace(/<\/t[dh]>/gi, " ")
|
||||||
.replace(/<li[^>]*>/gi, "\n• ")
|
.replace(/<li[^<>]*>/gi, "\n• ")
|
||||||
.replace(/<[^>]+>/g, "");
|
// A prefix such as `<script` is still dangerous when the closing `>` is
|
||||||
|
// absent or is supplied later by a renderer. Remove the opening bracket
|
||||||
|
// itself after known HTML has been converted to text.
|
||||||
|
.replace(/<[^<>]+>/g, "")
|
||||||
|
.replace(/</g, "");
|
||||||
out = out
|
out = out
|
||||||
.replace(/ /gi, " ")
|
.replace(/ /gi, " ")
|
||||||
.replace(/</gi, "<")
|
.replace(/</gi, "<")
|
||||||
.replace(/>/gi, ">")
|
.replace(/>/gi, ">")
|
||||||
.replace(/"/gi, '"')
|
.replace(/"/gi, '"')
|
||||||
.replace(/'/gi, "'")
|
.replace(/'/gi, "'")
|
||||||
.replace(/&#x([0-9a-f]+);/gi, (_m, hex: string) => String.fromCodePoint(parseInt(hex, 16)))
|
.replace(/&#x([0-9a-f]+);/gi, (m, hex: string) => codePoint(parseInt(hex, 16), m))
|
||||||
.replace(/&#(\d+);/g, (_m, dec: string) => String.fromCodePoint(Number(dec)))
|
.replace(/&#(\d+);/g, (m, dec: string) => codePoint(Number(dec), m))
|
||||||
.replace(/&/gi, "&");
|
.replace(/&/gi, "&");
|
||||||
out = out
|
|
||||||
.replace(/[ \t]+\n/g, "\n")
|
|
||||||
.replace(/\n{3,}/g, "\n\n")
|
|
||||||
.trim();
|
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,8 +28,21 @@ export function formatEvent(
|
|||||||
|
|
||||||
const ctx: FormatContext = { payload, repo, repoUrl, author, t, showEmoji };
|
const ctx: FormatContext = { payload, repo, repoUrl, author, t, showEmoji };
|
||||||
|
|
||||||
return (
|
const message =
|
||||||
findFormatter(eventType)?.format(ctx) ??
|
findFormatter(eventType)?.format(ctx) ??
|
||||||
formatGeneric(eventType, payload, repo, author, t, showEmoji)
|
formatGeneric(eventType, payload, repo, author, t, showEmoji);
|
||||||
);
|
// Action buttons (merge / close) call the github.com API with the clicker's
|
||||||
|
// token: on any other forge they would act on a same-named GitHub repository.
|
||||||
|
if (message.actions && !isGitHubDotCom(event.provider, repoUrl)) delete message.actions;
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isGitHubDotCom(provider: string | undefined, repoUrl: string | undefined): boolean {
|
||||||
|
if ((provider ?? "github") !== "github") return false;
|
||||||
|
if (!repoUrl) return true;
|
||||||
|
try {
|
||||||
|
return new URL(repoUrl).hostname.toLowerCase() === "github.com";
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,8 @@ import {
|
|||||||
type T,
|
type T,
|
||||||
buildMessage,
|
buildMessage,
|
||||||
repoBaseUrl,
|
repoBaseUrl,
|
||||||
|
senderProfileUrl,
|
||||||
|
shortRef,
|
||||||
} from "./helpers";
|
} from "./helpers";
|
||||||
|
|
||||||
export function formatPush(
|
export function formatPush(
|
||||||
@@ -20,7 +22,8 @@ export function formatPush(
|
|||||||
): NeutralMessage {
|
): NeutralMessage {
|
||||||
const rawRef = (payload.ref as string) ?? "";
|
const rawRef = (payload.ref as string) ?? "";
|
||||||
const isTagPush = rawRef.startsWith("refs/tags/");
|
const isTagPush = rawRef.startsWith("refs/tags/");
|
||||||
const ref = rawRef.replace("refs/heads/", "").replace("refs/tags/", "tag: ");
|
// One prefix, read once: a branch may itself be named `refs/tags/x`.
|
||||||
|
const ref = rawRef.startsWith("refs/tags/") ? `tag: ${shortRef(rawRef)}` : shortRef(rawRef);
|
||||||
const commits = (payload.commits ?? []) as Array<{
|
const commits = (payload.commits ?? []) as Array<{
|
||||||
id?: string;
|
id?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -52,7 +55,7 @@ export function formatPush(
|
|||||||
type: refType,
|
type: refType,
|
||||||
ref,
|
ref,
|
||||||
}),
|
}),
|
||||||
url: refUrl(baseUrl, rawRef, refType),
|
url: refUrl(baseUrl, shortRef(rawRef), refType),
|
||||||
color: GITHUB_COLORS.delete,
|
color: GITHUB_COLORS.delete,
|
||||||
},
|
},
|
||||||
t,
|
t,
|
||||||
@@ -65,7 +68,7 @@ export function formatPush(
|
|||||||
// instead of a confusing "0 commits pushed".
|
// instead of a confusing "0 commits pushed".
|
||||||
if (created && count === 0) {
|
if (created && count === 0) {
|
||||||
const refType = isTagPush ? "tag" : "branch";
|
const refType = isTagPush ? "tag" : "branch";
|
||||||
const cleanRef = rawRef.replace("refs/heads/", "").replace("refs/tags/", "");
|
const cleanRef = shortRef(rawRef);
|
||||||
return buildMessage(
|
return buildMessage(
|
||||||
{
|
{
|
||||||
author,
|
author,
|
||||||
@@ -75,7 +78,7 @@ export function formatPush(
|
|||||||
type: refType,
|
type: refType,
|
||||||
ref: cleanRef,
|
ref: cleanRef,
|
||||||
}),
|
}),
|
||||||
url: refUrl(baseUrl, cleanRef, refType),
|
url: refUrl(baseUrl, shortRef(rawRef), refType),
|
||||||
color: GITHUB_COLORS.create,
|
color: GITHUB_COLORS.create,
|
||||||
},
|
},
|
||||||
t,
|
t,
|
||||||
@@ -105,7 +108,9 @@ export function formatPush(
|
|||||||
if (commitAuthor === "invalid-email-address") {
|
if (commitAuthor === "invalid-email-address") {
|
||||||
if (commitAuthorName) msg += ` - ${commitAuthorName}`;
|
if (commitAuthorName) msg += ` - ${commitAuthorName}`;
|
||||||
} else {
|
} else {
|
||||||
msg += ` - [${commitAuthor}](https://github.com/${encodeURIComponent(commitAuthor)})`;
|
// On the forge the push came from (a Gitea author is not the
|
||||||
|
// GitHub account of the same name).
|
||||||
|
msg += ` - [${commitAuthor}](${senderProfileUrl(baseUrl ?? undefined, commitAuthor)})`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const url = baseUrl && c.id ? `${baseUrl}/commit/${c.id}` : null;
|
const url = baseUrl && c.id ? `${baseUrl}/commit/${c.id}` : null;
|
||||||
@@ -151,7 +156,9 @@ export function formatPush(
|
|||||||
count,
|
count,
|
||||||
s: count !== 1 ? "s" : "",
|
s: count !== 1 ? "s" : "",
|
||||||
repo: repo ?? t("common.repository"),
|
repo: repo ?? t("common.repository"),
|
||||||
ref: isTagPush ? tagLink(baseUrl, rawRef, ref) : branchLink(baseUrl, rawRef, ref),
|
ref: isTagPush
|
||||||
|
? tagLink(baseUrl, shortRef(rawRef), ref)
|
||||||
|
: branchLink(baseUrl, shortRef(rawRef), ref),
|
||||||
}),
|
}),
|
||||||
url: compareUrl,
|
url: compareUrl,
|
||||||
color: GITHUB_COLORS.push,
|
color: GITHUB_COLORS.push,
|
||||||
|
|||||||
@@ -11,12 +11,19 @@ export function formatCodeScanningAlert(
|
|||||||
): NeutralMessage {
|
): NeutralMessage {
|
||||||
const action = (payload.action as string) ?? "created";
|
const action = (payload.action as string) ?? "created";
|
||||||
const alert = payload.alert as {
|
const alert = payload.alert as {
|
||||||
rule?: { id?: string; severity?: string; description?: string };
|
rule?: {
|
||||||
|
id?: string;
|
||||||
|
severity?: string;
|
||||||
|
security_severity_level?: string;
|
||||||
|
description?: string;
|
||||||
|
};
|
||||||
most_recent_instance?: { location?: { path?: string } };
|
most_recent_instance?: { location?: { path?: string } };
|
||||||
state?: string;
|
state?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const severity = alert.rule?.severity ?? "warning";
|
// The security severity (critical/high/medium/low) where the rule has one;
|
||||||
|
// `severity` is the tool's own level (error/warning/note).
|
||||||
|
const severity = alert.rule?.security_severity_level ?? alert.rule?.severity ?? "warning";
|
||||||
const colorKey =
|
const colorKey =
|
||||||
severity === "critical"
|
severity === "critical"
|
||||||
? "code_scanning_critical"
|
? "code_scanning_critical"
|
||||||
|
|||||||
+72
-40
@@ -1,5 +1,13 @@
|
|||||||
import type { FilterNode } from "./types";
|
import type { FilterNode } from "./types";
|
||||||
import { log } from "./lib/log";
|
import { log } from "./lib/log";
|
||||||
|
import { canUseD1 } from "./storage/d1";
|
||||||
|
import {
|
||||||
|
ConfigConflictError,
|
||||||
|
groupVersion,
|
||||||
|
groupVersionBump,
|
||||||
|
groupVersionGuard,
|
||||||
|
runGuarded,
|
||||||
|
} from "./storage/config-store";
|
||||||
|
|
||||||
export interface NamedFragment {
|
export interface NamedFragment {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -15,59 +23,83 @@ interface D1FragmentRow {
|
|||||||
node: string;
|
node: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadFragments(db: D1Database): Promise<NamedFragment[]> {
|
/**
|
||||||
try {
|
* Named filter fragments, optionally of one group. Without a usable D1
|
||||||
const stmt = db.prepare("SELECT id, group_id, name, node FROM d1_fragments ORDER BY id");
|
* binding there are none; a D1 error propagates, because callers replace a
|
||||||
if (typeof stmt.all !== "function") return [];
|
* group's whole list and must never build that list from a failed read. An
|
||||||
|
* unreadable row is skipped (logged) — or, with `strict`, an error: a write
|
||||||
|
* replacing the group's list must never silently delete a row nobody saw.
|
||||||
|
*/
|
||||||
|
export async function loadFragments(
|
||||||
|
db: D1Database,
|
||||||
|
groupId?: string,
|
||||||
|
strict = false,
|
||||||
|
): Promise<NamedFragment[]> {
|
||||||
|
if (!canUseD1(db)) return [];
|
||||||
|
const stmt =
|
||||||
|
groupId === undefined
|
||||||
|
? db.prepare("SELECT id, group_id, name, node FROM d1_fragments ORDER BY id")
|
||||||
|
: db
|
||||||
|
.prepare(
|
||||||
|
"SELECT id, group_id, name, node FROM d1_fragments WHERE group_id = ? ORDER BY id",
|
||||||
|
)
|
||||||
|
.bind(groupId);
|
||||||
const { results } = await stmt.all<D1FragmentRow>();
|
const { results } = await stmt.all<D1FragmentRow>();
|
||||||
if (!results || results.length === 0) return [];
|
return (results ?? []).flatMap((r) => {
|
||||||
return results.map((r) => ({
|
try {
|
||||||
|
return [
|
||||||
|
{
|
||||||
id: r.id,
|
id: r.id,
|
||||||
groupId: r.group_id || undefined,
|
groupId: r.group_id || undefined,
|
||||||
name: r.name,
|
name: r.name,
|
||||||
node: JSON.parse(r.node) as FilterNode,
|
node: JSON.parse(r.node) as FilterNode,
|
||||||
}));
|
},
|
||||||
|
];
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.warn({ err }, "Failed to load fragments from D1");
|
if (strict) {
|
||||||
|
throw new Error(`filter fragment "${r.id}" is unreadable; repair the row before saving`);
|
||||||
|
}
|
||||||
|
log.warn({ err, id: r.id }, "Ignoring malformed filter fragment");
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function saveFragments(db: D1Database, fragments: NamedFragment[]): Promise<void> {
|
/**
|
||||||
|
* Replace one group's fragments in a single transaction; other groups are
|
||||||
|
* untouched. `expect` sees the stored fragments first and may throw; the write
|
||||||
|
* then commits only if nothing changed the group in between (version guard).
|
||||||
|
*/
|
||||||
|
export async function saveGroupFragments(
|
||||||
|
db: D1Database,
|
||||||
|
groupId: string,
|
||||||
|
fragments: NamedFragment[],
|
||||||
|
opts?: {
|
||||||
|
expect?: (current: NamedFragment[]) => void | Promise<void>;
|
||||||
|
/** Guard statements committed first in the write (see `GuardedWrite.guards`). */
|
||||||
|
guards?: (db: D1Database) => D1PreparedStatement[];
|
||||||
|
},
|
||||||
|
): Promise<NamedFragment[]> {
|
||||||
|
if (!canUseD1(db)) throw new Error("Filter fragments require the D1 binding");
|
||||||
|
const version = await groupVersion(db, groupId);
|
||||||
|
if (version == null) throw new ConfigConflictError(`group "${groupId}" does not exist`);
|
||||||
|
// Loaded strictly even without `expect`: an unreadable row aborts here.
|
||||||
|
const stored = await loadFragments(db, groupId, true);
|
||||||
|
await opts?.expect?.(stored);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
await runGuarded(db, [
|
||||||
// Load existing fragments to determine what to delete
|
groupVersionGuard(db, groupId, version),
|
||||||
const existing = await loadFragments(db);
|
...(opts?.guards?.(db) ?? []),
|
||||||
const existingKeys = new Set(existing.map((f) => `${f.id}:${f.groupId ?? ""}`));
|
groupVersionBump(db, groupId),
|
||||||
const newKeys = new Set(fragments.map((f) => `${f.id}:${f.groupId ?? ""}`));
|
db.prepare("DELETE FROM d1_fragments WHERE group_id = ?").bind(groupId),
|
||||||
|
...fragments.map((f) =>
|
||||||
const statements: D1PreparedStatement[] = [];
|
|
||||||
|
|
||||||
// Delete fragments that are no longer present
|
|
||||||
for (const key of existingKeys) {
|
|
||||||
if (!newKeys.has(key)) {
|
|
||||||
const [id, groupId] = key.split(":");
|
|
||||||
statements.push(
|
|
||||||
db.prepare("DELETE FROM d1_fragments WHERE id = ? AND group_id = ?").bind(id, groupId),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upsert all fragments
|
|
||||||
for (const f of fragments) {
|
|
||||||
statements.push(
|
|
||||||
db
|
db
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT INTO d1_fragments (id, group_id, name, node, version, created_at, updated_at)
|
`INSERT INTO d1_fragments (id, group_id, name, node, version, created_at, updated_at)
|
||||||
VALUES (?, ?, ?, ?, 1, ?, ?)
|
VALUES (?, ?, ?, ?, 1, ?, ?)`,
|
||||||
ON CONFLICT(id, group_id) DO UPDATE SET
|
|
||||||
name = excluded.name,
|
|
||||||
node = excluded.node,
|
|
||||||
updated_at = excluded.updated_at`,
|
|
||||||
)
|
)
|
||||||
.bind(f.id, f.groupId ?? "", f.name, JSON.stringify(f.node), now, now),
|
.bind(f.id, groupId, f.name, JSON.stringify(f.node), now, now),
|
||||||
);
|
),
|
||||||
}
|
]);
|
||||||
|
return loadFragments(db, groupId);
|
||||||
await db.batch(statements);
|
|
||||||
}
|
}
|
||||||
@@ -1,25 +1,89 @@
|
|||||||
import { createAppJwt } from "./oauth";
|
import { createAppJwt } from "./oauth";
|
||||||
|
import { sharedFlight, type Flight } from "../lib/shared-flight";
|
||||||
|
|
||||||
export const GITHUB_API_VERSION = "2022-11-28";
|
export const GITHUB_API_VERSION = "2022-11-28";
|
||||||
|
/**
|
||||||
|
* Longest an optional enrichment call (installation token, jobs, check runs)
|
||||||
|
* may take, its body included: a hanging one must not hold up the delivery.
|
||||||
|
*/
|
||||||
|
export const ENRICH_TIMEOUT_MS = 10_000;
|
||||||
export const GITHUB_USER_AGENT = "WebHooker (https://github.com/Elysola/WebHooker)";
|
export const GITHUB_USER_AGENT = "WebHooker (https://github.com/Elysola/WebHooker)";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A payload-supplied API URL (`jobs_url`, `check_runs_url`) parsed only when
|
||||||
|
* it points at the GitHub REST API's repository endpoints. Anything else — a
|
||||||
|
* forged payload aiming a token at its own server — yields null.
|
||||||
|
*/
|
||||||
|
export function githubApiUrl(value: string | undefined): URL | null {
|
||||||
|
if (!value) return null;
|
||||||
|
try {
|
||||||
|
const url = new URL(value);
|
||||||
|
if (url.protocol !== "https:" || url.host !== "api.github.com") return null;
|
||||||
|
if (!url.pathname.startsWith("/repos/") || url.username || url.password) return null;
|
||||||
|
return url;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mint a short-lived installation access token for a GitHub App installation.
|
* Mint a short-lived installation access token for a GitHub App installation.
|
||||||
* Returns undefined when the App credentials are missing or the exchange
|
* Returns undefined when the App credentials are missing or the exchange
|
||||||
* fails. Best-effort: callers must not depend on it.
|
* fails. Best-effort: callers must not depend on it.
|
||||||
*/
|
*/
|
||||||
|
/**
|
||||||
|
* Installation tokens this isolate holds (until shortly before they expire),
|
||||||
|
* and exchanges in flight: one per installation, not one per event — each is
|
||||||
|
* a subrequest plus a JWT signature.
|
||||||
|
*/
|
||||||
|
const installationTokens = new Map<string, { token: string; until: number }>();
|
||||||
|
const exchanging = new Map<string, Flight<string | undefined>>();
|
||||||
|
/**
|
||||||
|
* Installations whose exchange just failed, until when: enrichment is
|
||||||
|
* optional, so the events right after go without it instead of each signing
|
||||||
|
* a JWT and asking GitHub again.
|
||||||
|
*/
|
||||||
|
const failedExchanges = new Map<string, number>();
|
||||||
|
const FAILED_EXCHANGE_MS = 60_000;
|
||||||
|
|
||||||
export async function getInstallationToken(
|
export async function getInstallationToken(
|
||||||
appId: string | undefined,
|
appId: string | undefined,
|
||||||
privateKey: string | undefined,
|
privateKey: string | undefined,
|
||||||
installationId: number | undefined,
|
installationId: number | undefined,
|
||||||
): Promise<string | undefined> {
|
): Promise<string | undefined> {
|
||||||
if (!appId || !privateKey || !installationId) return undefined;
|
if (!appId || !privateKey || !installationId) return undefined;
|
||||||
|
const key = `${appId}:${installationId}`;
|
||||||
|
const held = installationTokens.get(key);
|
||||||
|
if (held && Date.now() < held.until) return held.token;
|
||||||
|
if ((failedExchanges.get(key) ?? 0) > Date.now()) return undefined;
|
||||||
|
return sharedFlight(
|
||||||
|
exchanging,
|
||||||
|
key,
|
||||||
|
async () => {
|
||||||
|
const token = await exchangeInstallationToken(appId, privateKey, installationId);
|
||||||
|
if (token) failedExchanges.delete(key);
|
||||||
|
else {
|
||||||
|
if (failedExchanges.size >= 1000) failedExchanges.clear();
|
||||||
|
failedExchanges.set(key, Date.now() + FAILED_EXCHANGE_MS);
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
},
|
||||||
|
ENRICH_TIMEOUT_MS + 5_000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exchangeInstallationToken(
|
||||||
|
appId: string,
|
||||||
|
privateKey: string,
|
||||||
|
installationId: number,
|
||||||
|
): Promise<string | undefined> {
|
||||||
try {
|
try {
|
||||||
const jwt = await createAppJwt(appId, privateKey);
|
const jwt = await createAppJwt(appId, privateKey);
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`https://api.github.com/app/installations/${installationId}/access_tokens`,
|
`https://api.github.com/app/installations/${installationId}/access_tokens`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
signal: AbortSignal.timeout(ENRICH_TIMEOUT_MS),
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${jwt}`,
|
Authorization: `Bearer ${jwt}`,
|
||||||
Accept: "application/vnd.github+json",
|
Accept: "application/vnd.github+json",
|
||||||
@@ -29,8 +93,14 @@ export async function getInstallationToken(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (!res.ok) return undefined;
|
if (!res.ok) return undefined;
|
||||||
const { token } = (await res.json()) as { token?: string };
|
const { token, expires_at } = (await res.json()) as { token?: string; expires_at?: string };
|
||||||
return token ?? undefined;
|
if (!token) return undefined;
|
||||||
|
const expires = Date.parse(expires_at ?? "");
|
||||||
|
// Tokens last an hour; given back 5 minutes early (a request in flight
|
||||||
|
// never carries one that just expired).
|
||||||
|
const until = (Number.isFinite(expires) ? expires : Date.now() + 3600_000) - 5 * 60_000;
|
||||||
|
if (until > Date.now()) installationTokens.set(`${appId}:${installationId}`, { token, until });
|
||||||
|
return token;
|
||||||
} catch {
|
} catch {
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
import { getInstallationToken, GITHUB_API_VERSION, GITHUB_USER_AGENT } from "./app-token";
|
import {
|
||||||
|
getInstallationToken,
|
||||||
|
githubApiUrl,
|
||||||
|
ENRICH_TIMEOUT_MS,
|
||||||
|
GITHUB_API_VERSION,
|
||||||
|
GITHUB_USER_AGENT,
|
||||||
|
} from "./app-token";
|
||||||
|
|
||||||
const CLOUDFLARE_SLUG = "cloudflare-workers-and-pages";
|
const CLOUDFLARE_SLUG = "cloudflare-workers-and-pages";
|
||||||
|
|
||||||
@@ -18,12 +24,16 @@ export async function getCheckSuiteBuildLogUrl(
|
|||||||
privateKey: string | undefined,
|
privateKey: string | undefined,
|
||||||
installationId: number | undefined,
|
installationId: number | undefined,
|
||||||
): Promise<string | undefined> {
|
): Promise<string | undefined> {
|
||||||
if (!checkRunsUrl || !appId || !privateKey || !installationId) return undefined;
|
const url = githubApiUrl(checkRunsUrl);
|
||||||
|
if (!url || !appId || !privateKey || !installationId) return undefined;
|
||||||
try {
|
try {
|
||||||
const token = await getInstallationToken(appId, privateKey, installationId);
|
const token = await getInstallationToken(appId, privateKey, installationId);
|
||||||
if (!token) return undefined;
|
if (!token) return undefined;
|
||||||
|
|
||||||
const runsRes = await fetch(checkRunsUrl, {
|
// No redirects: a token must never follow a response to another host.
|
||||||
|
const runsRes = await fetch(url.toString(), {
|
||||||
|
redirect: "manual",
|
||||||
|
signal: AbortSignal.timeout(ENRICH_TIMEOUT_MS),
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
Accept: "application/vnd.github+json",
|
Accept: "application/vnd.github+json",
|
||||||
|
|||||||
+169
-31
@@ -1,8 +1,9 @@
|
|||||||
import { Octokit } from "octokit";
|
import { Octokit } from "octokit";
|
||||||
import { saveToken, getToken } from "./store";
|
import { saveToken, getToken, type TokenSource } from "./store";
|
||||||
|
|
||||||
export function getOAuthURL(clientId: string, state: string): string {
|
export function getOAuthURL(clientId: string, state: string): string {
|
||||||
return `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=repo&state=${state}`;
|
// `read:org` lets the install flow check organization admin rights.
|
||||||
|
return `https://github.com/login/oauth/authorize?client_id=${clientId}&scope=${encodeURIComponent("repo read:org")}&state=${state}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
function b64url(buf: ArrayBuffer | string): string {
|
function b64url(buf: ArrayBuffer | string): string {
|
||||||
@@ -40,31 +41,82 @@ export async function createAppJwt(appId: string, privateKey: string): Promise<s
|
|||||||
return `${data}.${b64url(sig)}`;
|
return `${data}.${b64url(sig)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface InstallationAccount {
|
||||||
|
login: string;
|
||||||
|
id: number;
|
||||||
|
/** "User" or "Organization". */
|
||||||
|
type: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const API_HEADERS = {
|
||||||
|
Accept: "application/vnd.github+json",
|
||||||
|
"X-GitHub-Api-Version": "2022-11-28",
|
||||||
|
"User-Agent": "WebHooker",
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Look up the account (org/user login) that owns a GitHub App installation,
|
* Look up the account (org/user) that owns a GitHub App installation, using
|
||||||
* using an App JWT. Returns null when the App credentials are missing or the
|
* an App JWT. Returns null when the App credentials are missing or the lookup
|
||||||
* lookup fails (the caller falls back to an anonymous installation group).
|
* fails.
|
||||||
*/
|
*/
|
||||||
|
export async function getInstallationDetails(
|
||||||
|
appId: string,
|
||||||
|
privateKey: string,
|
||||||
|
installationId: number,
|
||||||
|
): Promise<InstallationAccount | null> {
|
||||||
|
if (!appId || !privateKey) return null;
|
||||||
|
try {
|
||||||
|
const jwt = await createAppJwt(appId, privateKey);
|
||||||
|
const res = await fetch(`https://api.github.com/app/installations/${installationId}`, {
|
||||||
|
headers: { ...API_HEADERS, Authorization: `Bearer ${jwt}` },
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const data = (await res.json()) as {
|
||||||
|
account?: { login?: string; id?: number; type?: string };
|
||||||
|
};
|
||||||
|
if (!data.account?.login) return null;
|
||||||
|
// An account without an id can still be named, but never matches a user.
|
||||||
|
return { login: data.account.login, id: data.account.id ?? -1, type: data.account.type ?? "" };
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The login of the account owning an installation (null when unknown). */
|
||||||
export async function getInstallationAccount(
|
export async function getInstallationAccount(
|
||||||
appId: string,
|
appId: string,
|
||||||
privateKey: string,
|
privateKey: string,
|
||||||
installationId: number,
|
installationId: number,
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
if (!appId || !privateKey) return null;
|
return (await getInstallationDetails(appId, privateKey, installationId))?.login ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether a GitHub user may administer an App installation. The Setup URL's
|
||||||
|
* `installation_id` is attacker-controlled, so binding it to a group requires
|
||||||
|
* proof from the user's own token: the user is the installation's account, or
|
||||||
|
* an active admin of its organization. Merely having access to it (being
|
||||||
|
* listed in `/user/installations` as a collaborator) is not enough.
|
||||||
|
*/
|
||||||
|
export async function userManagesInstallation(
|
||||||
|
token: string,
|
||||||
|
userId: string,
|
||||||
|
_installationId: number,
|
||||||
|
account: InstallationAccount | null,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const headers = { ...API_HEADERS, Authorization: `Bearer ${token}` };
|
||||||
try {
|
try {
|
||||||
const jwt = await createAppJwt(appId, privateKey);
|
if (!account) return false;
|
||||||
const res = await fetch(`https://api.github.com/app/installations/${installationId}`, {
|
if (account.type === "User") return String(account.id) === userId;
|
||||||
headers: {
|
const res = await fetch(
|
||||||
Authorization: `Bearer ${jwt}`,
|
`https://api.github.com/user/memberships/orgs/${encodeURIComponent(account.login)}`,
|
||||||
Accept: "application/vnd.github+json",
|
{ headers },
|
||||||
"X-GitHub-Api-Version": "2022-11-28",
|
);
|
||||||
},
|
if (!res.ok) return false;
|
||||||
});
|
const membership = (await res.json()) as { state?: string; role?: string };
|
||||||
if (!res.ok) return null;
|
return membership.state === "active" && membership.role === "admin";
|
||||||
const data = (await res.json()) as { account?: { login?: string } };
|
|
||||||
return data.account?.login ?? null;
|
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,6 +126,7 @@ export async function handleOAuthCallback(
|
|||||||
code: string,
|
code: string,
|
||||||
_state: string,
|
_state: string,
|
||||||
kv: KVNamespace,
|
kv: KVNamespace,
|
||||||
|
db?: D1Database,
|
||||||
): Promise<{ userId: string; login: string } | null> {
|
): Promise<{ userId: string; login: string } | null> {
|
||||||
const res = await fetch("https://github.com/login/oauth/access_token", {
|
const res = await fetch("https://github.com/login/oauth/access_token", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -102,15 +155,18 @@ export async function handleOAuthCallback(
|
|||||||
const octokit = new Octokit({ auth: data.access_token });
|
const octokit = new Octokit({ auth: data.access_token });
|
||||||
const { data: user } = await octokit.rest.users.getAuthenticated();
|
const { data: user } = await octokit.rest.users.getAuthenticated();
|
||||||
|
|
||||||
await saveToken(kv, user.id.toString(), data.access_token, 3600 * 10);
|
await saveToken(kv, user.id.toString(), data.access_token, 3600 * 10, db);
|
||||||
|
|
||||||
return { userId: user.id.toString(), login: user.login };
|
return { userId: user.id.toString(), login: user.login };
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUserOctokit(userId: string, kv: KVNamespace): Promise<Octokit | null> {
|
export async function getUserOctokit(userId: string, kv: TokenSource): Promise<Octokit | null> {
|
||||||
const token = await getToken(kv, userId);
|
const token = await getToken(kv, userId);
|
||||||
if (!token) return null;
|
if (!token) return null;
|
||||||
return new Octokit({ auth: token });
|
// No automatic retries: the user's actions (a comment, a merge) are not
|
||||||
|
// idempotent, and a retry after a lost response would act twice. A failure
|
||||||
|
// is reported to the user instead, who can try again knowingly.
|
||||||
|
return new Octokit({ auth: token, retry: { enabled: false }, throttle: { enabled: false } });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -125,8 +181,84 @@ function mapGitHubError(err: unknown): Error {
|
|||||||
return err instanceof Error ? err : new Error(String(err));
|
return err instanceof Error ? err : new Error(String(err));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function requireOctokit(kv: KVNamespace, githubUserId: string): Promise<Octokit> {
|
/**
|
||||||
const octokit = await getUserOctokit(githubUserId, kv);
|
* The immutable user id GitHub has for `login` right now, or null when it is
|
||||||
|
* unknown (no such user, no answer). Looked up with the caller's own token.
|
||||||
|
*/
|
||||||
|
export async function resolveGitHubUserId(token: string, login: string): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const res = await fetch(`https://api.github.com/users/${encodeURIComponent(login)}`, {
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
Accept: "application/vnd.github+json",
|
||||||
|
"User-Agent": "WebHooker",
|
||||||
|
},
|
||||||
|
redirect: "error",
|
||||||
|
signal: AbortSignal.timeout(5000),
|
||||||
|
});
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const data = (await res.json()) as { id?: unknown; login?: unknown };
|
||||||
|
const sameLogin =
|
||||||
|
typeof data.login === "string" && data.login.toLowerCase() === login.toLowerCase();
|
||||||
|
return sameLogin && typeof data.id === "number" ? String(data.id) : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A failure before anything was sent to GitHub (the user's token could not be
|
||||||
|
* read). Bot commands give such a command back for the platform to retry,
|
||||||
|
* instead of consuming it with an error reply.
|
||||||
|
*/
|
||||||
|
export class BeforeGitHubError extends Error {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Another run finished this command meanwhile (this one outlived its claim):
|
||||||
|
* nothing is written, and that run's "done" stays.
|
||||||
|
*/
|
||||||
|
export class CommandTakenError extends BeforeGitHubError {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GitHub refused the request (or none could be made for want of a token):
|
||||||
|
* nothing was done, so running the command again is safe. Anything else (a
|
||||||
|
* network failure, a 5xx) may have acted.
|
||||||
|
*/
|
||||||
|
export function githubRefused(err: unknown): boolean {
|
||||||
|
const message = err instanceof Error ? err.message : "";
|
||||||
|
if (["GITHUB_TOKEN_EXPIRED", "GITHUB_FORBIDDEN", "GITHUB_NOT_FOUND"].includes(message)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const status = (err as { status?: unknown })?.status;
|
||||||
|
return typeof status === "number" && status >= 400 && status < 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `beforeWrite` runs once only the write itself is left (a bot records the
|
||||||
|
* command as done there, so a lost confirmation can never run the write
|
||||||
|
* again); its failure aborts with nothing done.
|
||||||
|
*/
|
||||||
|
export interface WriteHooks {
|
||||||
|
beforeWrite?: () => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function beforeWrite(hooks: WriteHooks | undefined): Promise<void> {
|
||||||
|
if (!hooks?.beforeWrite) return;
|
||||||
|
try {
|
||||||
|
await hooks.beforeWrite();
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof BeforeGitHubError) throw err;
|
||||||
|
throw new BeforeGitHubError(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function requireOctokit(kv: TokenSource, githubUserId: string): Promise<Octokit> {
|
||||||
|
let octokit: Octokit | null;
|
||||||
|
try {
|
||||||
|
octokit = await getUserOctokit(githubUserId, kv);
|
||||||
|
} catch (err) {
|
||||||
|
throw new BeforeGitHubError(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
if (!octokit) throw new Error("GITHUB_TOKEN_EXPIRED");
|
if (!octokit) throw new Error("GITHUB_TOKEN_EXPIRED");
|
||||||
return octokit;
|
return octokit;
|
||||||
}
|
}
|
||||||
@@ -136,23 +268,25 @@ async function requireOctokit(kv: KVNamespace, githubUserId: string): Promise<Oc
|
|||||||
* so the comment shows up under their own identity instead of the bot.
|
* so the comment shows up under their own identity instead of the bot.
|
||||||
*/
|
*/
|
||||||
export async function commentAsUser(
|
export async function commentAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
issueNumber: number,
|
issueNumber: number,
|
||||||
body: string,
|
body: string,
|
||||||
|
hooks?: WriteHooks,
|
||||||
): Promise<{ htmlUrl: string; login: string }> {
|
): Promise<{ htmlUrl: string; login: string }> {
|
||||||
const octokit = await requireOctokit(kv, githubUserId);
|
const octokit = await requireOctokit(kv, githubUserId);
|
||||||
|
await beforeWrite(hooks);
|
||||||
try {
|
try {
|
||||||
const { data: me } = await octokit.rest.users.getAuthenticated();
|
// The author comes with the created comment: no separate `/user` request.
|
||||||
const res = await octokit.rest.issues.createComment({
|
const res = await octokit.rest.issues.createComment({
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
issue_number: issueNumber,
|
issue_number: issueNumber,
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
return { htmlUrl: res.data.html_url, login: me.login };
|
return { htmlUrl: res.data.html_url, login: res.data.user?.login ?? "" };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
throw mapGitHubError(err);
|
throw mapGitHubError(err);
|
||||||
}
|
}
|
||||||
@@ -160,7 +294,7 @@ export async function commentAsUser(
|
|||||||
|
|
||||||
/** Fetch a single issue comment's current body (used to prefill the edit modal). */
|
/** Fetch a single issue comment's current body (used to prefill the edit modal). */
|
||||||
export async function getCommentAsUser(
|
export async function getCommentAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
@@ -177,7 +311,7 @@ export async function getCommentAsUser(
|
|||||||
|
|
||||||
/** Edit an existing issue/PR comment. GitHub enforces permission (403 if not allowed). */
|
/** Edit an existing issue/PR comment. GitHub enforces permission (403 if not allowed). */
|
||||||
export async function editCommentAsUser(
|
export async function editCommentAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
@@ -200,7 +334,7 @@ export async function editCommentAsUser(
|
|||||||
|
|
||||||
/** Delete an existing issue/PR comment. GitHub enforces permission (403 if not allowed). */
|
/** Delete an existing issue/PR comment. GitHub enforces permission (403 if not allowed). */
|
||||||
export async function deleteCommentAsUser(
|
export async function deleteCommentAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
@@ -216,14 +350,16 @@ export async function deleteCommentAsUser(
|
|||||||
|
|
||||||
/** Merge a pull request as the linked GitHub user. GitHub enforces permission (403 if not allowed). */
|
/** Merge a pull request as the linked GitHub user. GitHub enforces permission (403 if not allowed). */
|
||||||
export async function mergePullRequestAsUser(
|
export async function mergePullRequestAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
pullNumber: number,
|
pullNumber: number,
|
||||||
method: "merge" | "squash" | "rebase" = "squash",
|
method: "merge" | "squash" | "rebase" = "squash",
|
||||||
|
hooks?: WriteHooks,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const octokit = await requireOctokit(kv, githubUserId);
|
const octokit = await requireOctokit(kv, githubUserId);
|
||||||
|
await beforeWrite(hooks);
|
||||||
try {
|
try {
|
||||||
await octokit.rest.pulls.merge({
|
await octokit.rest.pulls.merge({
|
||||||
owner,
|
owner,
|
||||||
@@ -238,13 +374,15 @@ export async function mergePullRequestAsUser(
|
|||||||
|
|
||||||
/** Close a pull request as the linked GitHub user. GitHub enforces permission (403 if not allowed). */
|
/** Close a pull request as the linked GitHub user. GitHub enforces permission (403 if not allowed). */
|
||||||
export async function closePullRequestAsUser(
|
export async function closePullRequestAsUser(
|
||||||
kv: KVNamespace,
|
kv: TokenSource,
|
||||||
githubUserId: string,
|
githubUserId: string,
|
||||||
owner: string,
|
owner: string,
|
||||||
repo: string,
|
repo: string,
|
||||||
pullNumber: number,
|
pullNumber: number,
|
||||||
|
hooks?: WriteHooks,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const octokit = await requireOctokit(kv, githubUserId);
|
const octokit = await requireOctokit(kv, githubUserId);
|
||||||
|
await beforeWrite(hooks);
|
||||||
try {
|
try {
|
||||||
await octokit.rest.pulls.update({
|
await octokit.rest.pulls.update({
|
||||||
owner,
|
owner,
|
||||||
|
|||||||
+212
-4
@@ -1,7 +1,16 @@
|
|||||||
|
import { idempotencyStore, recordStatement, unrecordedGuard } from "../lib/idempotency";
|
||||||
|
import { canUseD1, isMissingTable } from "../storage/d1";
|
||||||
|
|
||||||
interface StoredToken {
|
interface StoredToken {
|
||||||
userId: string;
|
userId: string;
|
||||||
accessToken: string;
|
accessToken: string;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
/**
|
||||||
|
* Valid only while D1 records it as the user's live token (see
|
||||||
|
* `markLive`). Unset on tokens saved before that record existed, or
|
||||||
|
* without the D1 table: those follow the revocation records alone.
|
||||||
|
*/
|
||||||
|
live?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function hashToken(token: string): Promise<string> {
|
async function hashToken(token: string): Promise<string> {
|
||||||
@@ -12,11 +21,93 @@ async function hashToken(token: string): Promise<string> {
|
|||||||
.join("");
|
.join("");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tokens are revoked (on removal and rotation) in the idempotency store (D1)
|
||||||
|
* as well as deleted from KV, whose deletes take a while to reach every
|
||||||
|
* location: a revoked token must stop authenticating at once.
|
||||||
|
*/
|
||||||
|
function revokedTokenKey(tokenHash: string): string {
|
||||||
|
return `token-revoked:${tokenHash}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user's live token, in D1. KV can hand a node a stale copy of the user's
|
||||||
|
* token, so a removal or rotation working from that copy would miss the
|
||||||
|
* newer token: dropping every live record of the user covers it whatever
|
||||||
|
* copy was read.
|
||||||
|
*/
|
||||||
|
function liveTokenKey(userId: string, tokenHash: string): string {
|
||||||
|
return `${liveTokenPrefix(userId)}${tokenHash}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function liveTokenPrefix(userId: string): string {
|
||||||
|
return `token-live:${userId}:`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Statement dropping the user's live records (all, or all but `keep`). */
|
||||||
|
function dropLive(db: D1Database, userId: string, keep = ""): D1PreparedStatement {
|
||||||
|
// A range over the prefix (`;` follows `:`), never a LIKE pattern.
|
||||||
|
return db
|
||||||
|
.prepare("DELETE FROM dedup_keys WHERE key >= ? AND key < ? AND key <> ?")
|
||||||
|
.bind(liveTokenPrefix(userId), `token-live:${userId};`, keep);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record `tokenHash` as the user's only live token, in one D1 batch. Returns
|
||||||
|
* false where the D1 table does not exist yet (the token then follows the
|
||||||
|
* revocation records alone).
|
||||||
|
*/
|
||||||
|
async function markLive(
|
||||||
|
db: D1Database,
|
||||||
|
userId: string,
|
||||||
|
tokenHash: string,
|
||||||
|
ttlSeconds: number,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const now = Date.now();
|
||||||
|
const key = liveTokenKey(userId, tokenHash);
|
||||||
|
try {
|
||||||
|
await db.batch([
|
||||||
|
dropLive(db, userId, key),
|
||||||
|
db
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO dedup_keys (key, claimed_at, expires_at) VALUES (?, ?, ?)
|
||||||
|
ON CONFLICT(key) DO UPDATE SET
|
||||||
|
claimed_at = excluded.claimed_at, expires_at = excluded.expires_at`,
|
||||||
|
)
|
||||||
|
.bind(key, now, now + ttlSeconds * 1000),
|
||||||
|
]);
|
||||||
|
return true;
|
||||||
|
} catch (err) {
|
||||||
|
if (isMissingTable(err)) return false;
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a stored token may still be used (expiry aside). */
|
||||||
|
async function usable(
|
||||||
|
db: D1Database | undefined,
|
||||||
|
kv: KVNamespace,
|
||||||
|
t: StoredToken,
|
||||||
|
tokenHash: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (!db) return true;
|
||||||
|
const claims = idempotencyStore(db, kv);
|
||||||
|
if (await claims.has(revokedTokenKey(tokenHash))) return false;
|
||||||
|
if (t.live && !(await claims.has(liveTokenKey(t.userId, tokenHash)))) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revokeToken(db: D1Database, kv: KVNamespace, t: StoredToken): Promise<void> {
|
||||||
|
const ttl = Math.max(60, Math.ceil((t.expiresAt - Date.now()) / 1000));
|
||||||
|
await idempotencyStore(db, kv).claim(revokedTokenKey(await hashToken(t.accessToken)), ttl);
|
||||||
|
}
|
||||||
|
|
||||||
export async function saveToken(
|
export async function saveToken(
|
||||||
kv: KVNamespace,
|
kv: KVNamespace,
|
||||||
userId: string,
|
userId: string,
|
||||||
accessToken: string,
|
accessToken: string,
|
||||||
expiresInSeconds: number,
|
expiresInSeconds: number,
|
||||||
|
db?: D1Database,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const token: StoredToken = {
|
const token: StoredToken = {
|
||||||
userId,
|
userId,
|
||||||
@@ -24,13 +115,36 @@ export async function saveToken(
|
|||||||
expiresAt: Date.now() + expiresInSeconds * 1000,
|
expiresAt: Date.now() + expiresInSeconds * 1000,
|
||||||
};
|
};
|
||||||
const ttl = Math.max(Math.floor(expiresInSeconds * 0.9), 60);
|
const ttl = Math.max(Math.floor(expiresInSeconds * 0.9), 60);
|
||||||
|
const tokenHash = await hashToken(accessToken);
|
||||||
|
// Rotation: the previous token's reverse index must stop resolving to this
|
||||||
|
// user, or the old token would keep acting with the new one.
|
||||||
|
// A failed read aborts the rotation: the old token must be revoked, and
|
||||||
|
// "none" cannot be assumed.
|
||||||
|
const previous = await kv.get<StoredToken>(`token:${userId}`, "json");
|
||||||
|
const rotated = previous?.accessToken && previous.accessToken !== accessToken;
|
||||||
|
// Revoked before it is overwritten: should this fail, the old token is
|
||||||
|
// still on record and a retry revokes it then.
|
||||||
|
if (rotated && db) await revokeToken(db, kv, previous);
|
||||||
|
// The only live token from here on — whichever older one some node's KV
|
||||||
|
// still shows.
|
||||||
|
if (db && canUseD1(db) && (await markLive(db, userId, tokenHash, expiresInSeconds))) {
|
||||||
|
token.live = true;
|
||||||
|
}
|
||||||
await kv.put(`token:${userId}`, JSON.stringify(token), { expirationTtl: ttl });
|
await kv.put(`token:${userId}`, JSON.stringify(token), { expirationTtl: ttl });
|
||||||
|
|
||||||
const tokenHash = await hashToken(accessToken);
|
|
||||||
await kv.put(`token-reverse:${tokenHash}`, userId, { expirationTtl: ttl });
|
await kv.put(`token-reverse:${tokenHash}`, userId, { expirationTtl: ttl });
|
||||||
|
if (rotated) await kv.delete(`token-reverse:${await hashToken(previous.accessToken)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getToken(kv: KVNamespace, userId: string): Promise<string | null> {
|
/** Where tokens are read from: KV alone, or KV with D1 (revocations honored). */
|
||||||
|
export type TokenSource = KVNamespace | { KV: KVNamespace; DB?: D1Database };
|
||||||
|
|
||||||
|
function sourceOf(source: TokenSource): { kv: KVNamespace; db?: D1Database } {
|
||||||
|
return "KV" in source ? { kv: source.KV, db: source.DB } : { kv: source };
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getToken(source: TokenSource, userId: string): Promise<string | null> {
|
||||||
|
const { kv, db } = sourceOf(source);
|
||||||
const raw = await kv.get(`token:${userId}`, "json");
|
const raw = await kv.get(`token:${userId}`, "json");
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
const t = raw as StoredToken;
|
const t = raw as StoredToken;
|
||||||
@@ -38,25 +152,119 @@ export async function getToken(kv: KVNamespace, userId: string): Promise<string
|
|||||||
await kv.delete(`token:${userId}`);
|
await kv.delete(`token:${userId}`);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
// Revoked or no longer live, even where KV still holds it (writes and
|
||||||
|
// deletes take a while to spread).
|
||||||
|
if (!(await usable(db, kv, t, await hashToken(t.accessToken)))) return null;
|
||||||
return t.accessToken;
|
return t.accessToken;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function removeToken(kv: KVNamespace, userId: string): Promise<void> {
|
export async function removeToken(kv: KVNamespace, userId: string, db?: D1Database): Promise<void> {
|
||||||
|
// First, and whatever KV shows here: a newer token than the copy read below
|
||||||
|
// stops too.
|
||||||
|
if (db && canUseD1(db)) {
|
||||||
|
try {
|
||||||
|
await dropLive(db, userId).run();
|
||||||
|
} catch (err) {
|
||||||
|
if (!isMissingTable(err)) throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
const raw = await kv.get(`token:${userId}`, "json");
|
const raw = await kv.get(`token:${userId}`, "json");
|
||||||
if (raw) {
|
if (raw) {
|
||||||
const t = raw as StoredToken;
|
const t = raw as StoredToken;
|
||||||
|
if (db) await revokeToken(db, kv, t);
|
||||||
const tokenHash = await hashToken(t.accessToken);
|
const tokenHash = await hashToken(t.accessToken);
|
||||||
await kv.delete(`token-reverse:${tokenHash}`);
|
await kv.delete(`token-reverse:${tokenHash}`);
|
||||||
}
|
}
|
||||||
await kv.delete(`token:${userId}`);
|
await kv.delete(`token:${userId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The GitHub user whose *current* stored token is `accessToken`. The reverse
|
||||||
|
* index only narrows the lookup; the stored token must match too, so a token
|
||||||
|
* that was rotated, revoked or expired never authenticates (even while a stale
|
||||||
|
* reverse key is still around).
|
||||||
|
*/
|
||||||
export async function findUserIdByToken(
|
export async function findUserIdByToken(
|
||||||
kv: KVNamespace,
|
kv: KVNamespace,
|
||||||
accessToken: string,
|
accessToken: string,
|
||||||
|
db?: D1Database,
|
||||||
): Promise<string | null> {
|
): Promise<string | null> {
|
||||||
const tokenHash = await hashToken(accessToken);
|
const tokenHash = await hashToken(accessToken);
|
||||||
return await kv.get(`token-reverse:${tokenHash}`, "text");
|
if (db && (await idempotencyStore(db, kv).has(revokedTokenKey(tokenHash)))) return null;
|
||||||
|
const userId = await kv.get(`token-reverse:${tokenHash}`, "text");
|
||||||
|
if (!userId) return null;
|
||||||
|
const stored = await kv.get<StoredToken>(`token:${userId}`, "json");
|
||||||
|
if (!stored || Date.now() >= stored.expiresAt) return null;
|
||||||
|
if ((await hashToken(stored.accessToken)) !== tokenHash) return null;
|
||||||
|
if (!(await usable(db, kv, stored, tokenHash))) return null;
|
||||||
|
return userId;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type LinkPlatform = "discord" | "telegram" | "feishu";
|
||||||
|
|
||||||
|
const LINK_TABLES: Record<LinkPlatform, { table: string; column: string }> = {
|
||||||
|
discord: { table: "discord_links", column: "discord_user_id" },
|
||||||
|
telegram: { table: "telegram_links", column: "telegram_user_id" },
|
||||||
|
feishu: { table: "feishu_links", column: "feishu_user_id" },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Statement linking a chat account to a GitHub account (for a batch). */
|
||||||
|
export function linkStatement(
|
||||||
|
db: D1Database,
|
||||||
|
platform: LinkPlatform,
|
||||||
|
chatUserId: string,
|
||||||
|
githubUserId: string,
|
||||||
|
): D1PreparedStatement {
|
||||||
|
const { table, column } = LINK_TABLES[platform];
|
||||||
|
return db
|
||||||
|
.prepare(`INSERT OR REPLACE INTO ${table} (${column}, github_user_id) VALUES (?, ?)`)
|
||||||
|
.bind(chatUserId, githubUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Statement removing a chat account's link (for a batch). */
|
||||||
|
export function unlinkStatement(
|
||||||
|
db: D1Database,
|
||||||
|
platform: LinkPlatform,
|
||||||
|
chatUserId: string,
|
||||||
|
): D1PreparedStatement {
|
||||||
|
const { table, column } = LINK_TABLES[platform];
|
||||||
|
return db.prepare(`DELETE FROM ${table} WHERE ${column} = ?`).bind(chatUserId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlink as a bot command: the command's "done" record (`done`) commits in
|
||||||
|
* the same D1 transaction, so an unlink that went through — even one whose
|
||||||
|
* answer was lost — is never run again by a redelivery (which by then could
|
||||||
|
* remove a link made since).
|
||||||
|
*/
|
||||||
|
export async function unlinkAsCommand(
|
||||||
|
env: { DB: D1Database; KV: KVNamespace },
|
||||||
|
platform: LinkPlatform,
|
||||||
|
chatUserId: string,
|
||||||
|
done?: { key: string; ttl: number },
|
||||||
|
): Promise<void> {
|
||||||
|
if (!done || !canUseD1(env.DB)) {
|
||||||
|
await unlinkStatement(env.DB, platform, chatUserId).run();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await env.DB.batch([
|
||||||
|
// Done already (another run took over this command after ours outlived
|
||||||
|
// its claim): nothing is removed — the link may be a new one by now.
|
||||||
|
unrecordedGuard(env.DB, done.key),
|
||||||
|
unlinkStatement(env.DB, platform, chatUserId),
|
||||||
|
recordStatement(env.DB, done.key, done.ttl),
|
||||||
|
]);
|
||||||
|
} catch (err) {
|
||||||
|
// Recorded — committed here after all (its answer lost), or by another
|
||||||
|
// run before: done either way.
|
||||||
|
if (
|
||||||
|
!(await idempotencyStore(env.DB, env.KV)
|
||||||
|
.has(done.key)
|
||||||
|
.catch(() => false))
|
||||||
|
)
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,10 @@
|
|||||||
import { getInstallationToken, GITHUB_API_VERSION, GITHUB_USER_AGENT } from "./app-token";
|
import {
|
||||||
|
getInstallationToken,
|
||||||
|
githubApiUrl,
|
||||||
|
ENRICH_TIMEOUT_MS,
|
||||||
|
GITHUB_API_VERSION,
|
||||||
|
GITHUB_USER_AGENT,
|
||||||
|
} from "./app-token";
|
||||||
|
|
||||||
export interface WorkflowJob {
|
export interface WorkflowJob {
|
||||||
name?: string;
|
name?: string;
|
||||||
@@ -24,10 +30,10 @@ export async function getWorkflowRunJobs(
|
|||||||
privateKey: string | undefined,
|
privateKey: string | undefined,
|
||||||
installationId: number | undefined,
|
installationId: number | undefined,
|
||||||
): Promise<WorkflowJob[] | undefined> {
|
): Promise<WorkflowJob[] | undefined> {
|
||||||
if (!jobsUrl) return undefined;
|
const url = githubApiUrl(jobsUrl);
|
||||||
|
if (!url) return undefined;
|
||||||
try {
|
try {
|
||||||
const token = await getInstallationToken(appId, privateKey, installationId);
|
const token = await getInstallationToken(appId, privateKey, installationId);
|
||||||
const url = new URL(jobsUrl);
|
|
||||||
url.searchParams.set("per_page", "100");
|
url.searchParams.set("per_page", "100");
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
Accept: "application/vnd.github+json",
|
Accept: "application/vnd.github+json",
|
||||||
@@ -35,7 +41,12 @@ export async function getWorkflowRunJobs(
|
|||||||
"User-Agent": GITHUB_USER_AGENT,
|
"User-Agent": GITHUB_USER_AGENT,
|
||||||
};
|
};
|
||||||
if (token) headers.Authorization = `Bearer ${token}`;
|
if (token) headers.Authorization = `Bearer ${token}`;
|
||||||
const res = await fetch(url.toString(), { headers });
|
// No redirects: a token must never follow a response to another host.
|
||||||
|
const res = await fetch(url.toString(), {
|
||||||
|
headers,
|
||||||
|
redirect: "manual",
|
||||||
|
signal: AbortSignal.timeout(ENRICH_TIMEOUT_MS),
|
||||||
|
});
|
||||||
if (!res.ok) return undefined;
|
if (!res.ok) return undefined;
|
||||||
const data = (await res.json()) as { jobs?: WorkflowJob[] };
|
const data = (await res.json()) as { jobs?: WorkflowJob[] };
|
||||||
return data.jobs?.length ? data.jobs : undefined;
|
return data.jobs?.length ? data.jobs : undefined;
|
||||||
|
|||||||
+50
-17
@@ -1,4 +1,6 @@
|
|||||||
|
import { groupScopeClause, type GroupScope } from "./send-log";
|
||||||
import { log } from "./log";
|
import { log } from "./log";
|
||||||
|
import { isMissingTable } from "../storage/d1";
|
||||||
|
|
||||||
export interface AuditEntry {
|
export interface AuditEntry {
|
||||||
id?: number;
|
id?: number;
|
||||||
@@ -10,6 +12,11 @@ export interface AuditEntry {
|
|||||||
targetType?: string;
|
targetType?: string;
|
||||||
targetId?: string;
|
targetId?: string;
|
||||||
groupId?: string;
|
groupId?: string;
|
||||||
|
/**
|
||||||
|
* Immutable instance of the group (write-only): the entry is filed under
|
||||||
|
* whatever id that instance has when it is written.
|
||||||
|
*/
|
||||||
|
groupInstance?: string;
|
||||||
/** Free-form metadata. Never include secrets or message bodies. */
|
/** Free-form metadata. Never include secrets or message bodies. */
|
||||||
detail?: Record<string, unknown>;
|
detail?: Record<string, unknown>;
|
||||||
ip?: string;
|
ip?: string;
|
||||||
@@ -46,13 +53,20 @@ function toEntry(r: AuditRow): AuditEntry {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Best-effort write; failures never break the business flow. */
|
/**
|
||||||
|
* Best-effort write; failures never break the business flow.
|
||||||
|
*
|
||||||
|
* The group is resolved when the row is written, not when the action was
|
||||||
|
* decided: an entry landing after its group was renamed is filed under the
|
||||||
|
* new id (with the instance known), after a delete or a rename under none —
|
||||||
|
* never under an id another group may take over later.
|
||||||
|
*/
|
||||||
export async function recordAudit(db: D1Database, entry: AuditEntry): Promise<void> {
|
export async function recordAudit(db: D1Database, entry: AuditEntry): Promise<void> {
|
||||||
try {
|
const insert = (groupSql: string, ...groupArgs: Array<string | null>): D1PreparedStatement =>
|
||||||
await db
|
db
|
||||||
.prepare(
|
.prepare(
|
||||||
`INSERT INTO audit_logs (ts, actor_id, actor_login, action, target_type, target_id, group_id, detail, ip)
|
`INSERT INTO audit_logs (ts, actor_id, actor_login, action, target_type, target_id, group_id, detail, ip)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
VALUES (?, ?, ?, ?, ?, ?, ${groupSql}, ?, ?)`,
|
||||||
)
|
)
|
||||||
.bind(
|
.bind(
|
||||||
entry.ts,
|
entry.ts,
|
||||||
@@ -61,11 +75,31 @@ export async function recordAudit(db: D1Database, entry: AuditEntry): Promise<vo
|
|||||||
entry.action,
|
entry.action,
|
||||||
entry.targetType ?? null,
|
entry.targetType ?? null,
|
||||||
entry.targetId ?? null,
|
entry.targetId ?? null,
|
||||||
entry.groupId ?? null,
|
...groupArgs,
|
||||||
entry.detail ? JSON.stringify(entry.detail) : null,
|
entry.detail ? JSON.stringify(entry.detail) : null,
|
||||||
entry.ip ?? null,
|
entry.ip ?? null,
|
||||||
)
|
);
|
||||||
.run();
|
try {
|
||||||
|
try {
|
||||||
|
if (entry.groupInstance) {
|
||||||
|
// The id given is tried first (a primary-key lookup); the groups are
|
||||||
|
// scanned only when it no longer holds that instance (renamed).
|
||||||
|
await insert(
|
||||||
|
"COALESCE((SELECT id FROM d1_groups WHERE id = ? AND json_valid(data) AND json_extract(data, '$.instance') = ?), (SELECT id FROM (SELECT id, CASE WHEN json_valid(data) THEN data ELSE '{}' END AS data FROM d1_groups) WHERE json_extract(data, '$.instance') = ?))",
|
||||||
|
entry.groupId ?? "",
|
||||||
|
entry.groupInstance,
|
||||||
|
entry.groupInstance,
|
||||||
|
).run();
|
||||||
|
} else if (entry.groupId) {
|
||||||
|
await insert("(SELECT id FROM d1_groups WHERE id = ?)", entry.groupId).run();
|
||||||
|
} else {
|
||||||
|
await insert("?", null).run();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
// Groups not in D1 (an unmigrated database): file it as given.
|
||||||
|
if (!isMissingTable(err) || !entry.groupId) throw err;
|
||||||
|
await insert("?", entry.groupId).run();
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
log.warn({ err, action: entry.action }, "Failed to record audit entry");
|
log.warn({ err, action: entry.action }, "Failed to record audit entry");
|
||||||
}
|
}
|
||||||
@@ -73,23 +107,22 @@ export async function recordAudit(db: D1Database, entry: AuditEntry): Promise<vo
|
|||||||
|
|
||||||
export async function getAuditLog(
|
export async function getAuditLog(
|
||||||
db: D1Database,
|
db: D1Database,
|
||||||
opts: { groupId?: string; limit?: number } = {},
|
opts: { groupId?: GroupScope; limit?: number } = {},
|
||||||
): Promise<AuditEntry[]> {
|
): Promise<AuditEntry[]> {
|
||||||
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
|
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
|
||||||
try {
|
try {
|
||||||
if (opts.groupId) {
|
const clause = groupScopeClause(opts.groupId);
|
||||||
const { results } = await db
|
const { results } = await db
|
||||||
.prepare(`SELECT ${COLUMNS} FROM audit_logs WHERE group_id = ? ORDER BY ts DESC LIMIT ?`)
|
.prepare(
|
||||||
.bind(opts.groupId, limit)
|
`SELECT ${COLUMNS} FROM audit_logs${clause ? ` WHERE ${clause.sql}` : ""} ORDER BY ts DESC LIMIT ?`,
|
||||||
.all<AuditRow>();
|
)
|
||||||
return results.map(toEntry);
|
.bind(...(clause?.args ?? []), limit)
|
||||||
}
|
|
||||||
const { results } = await db
|
|
||||||
.prepare(`SELECT ${COLUMNS} FROM audit_logs ORDER BY ts DESC LIMIT ?`)
|
|
||||||
.bind(limit)
|
|
||||||
.all<AuditRow>();
|
.all<AuditRow>();
|
||||||
return results.map(toEntry);
|
return results.map(toEntry);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
// Only a table not created yet means "nothing yet"; any other failure
|
||||||
|
// must reach the caller, not pass for an empty history.
|
||||||
|
if (!isMissingTable(err)) throw err;
|
||||||
log.warn({ err }, "Failed to load audit log");
|
log.warn({ err }, "Failed to load audit log");
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user