Commit Graph
72 Commits
Author SHA1 Message Date
w9auto 0c126d4fee feat(storage): Add delivery state store switch (D1 by default or KV) (#12) 2026-11-17 22:46:50 +08:00
RhenCloud fc4495dfb4 fix(security): preserve decoded text entities 2026-10-24 16:49:16 +08:00
github-actions[bot] 110e3ae008 chore: auto-fix lint & formatting [skip ci] 2026-10-24 08:42:49 +00:00
RhenCloud c07741bf54 fix(security): harden URL and HTML sanitization 2026-10-24 16:41:29 +08:00
翅膀喵andRhenCloud 978c53eeb3 fix(security): harden webhook delivery pipeline and group storage (#11)
* fix(log): preserve structured error details

Error objects lose their useful details when serialized as plain JSON.
Keep the message, stack and cause in structured log output.

* fix(runtime): bound shared in-flight waits

A canceled request can leave its shared promise pending forever.
Bound joins and coordinate a single replacement so later requests
make progress without multiplying upstream work.

* fix(bot): reject oversized callback bodies

Reject declared oversized bot callbacks before reading their bodies.
This keeps unauthenticated requests from wasting worker resources.

* test(d1): exercise real sqlite transactions

Exercise real foreign keys, transactions and conditional statements
instead of mocks that cannot reproduce lost updates or cascades.

* fix(storage): preserve claims across kv fallback

Only missing tables justify KV fallback; other failures must surface.
Remember fallback writes so migration to D1 cannot forget claims
and replay completed work. Share marker checks without extra writes.

* fix(filter): use isolated linear-time patterns

Backtracking patterns can exhaust worker CPU on untrusted payloads.
Use linear-time matching and separate bounded cache namespaces so
glob and regex entries cannot corrupt each other.

* fix(filter): read each event branch correctly

Deployment and check branches live in event-specific nested fields.
Read those fields and remove only the actual leading ref prefix.

* fix(filter): read only own payload properties

Inherited object properties are not webhook payload data.
Read own properties only so JSONPath cannot traverse prototypes.

* fix(filter): validate executable condition trees

Malformed trees and unsupported patterns must not silently turn an
exclude rule into a pass. Validate the shape and only the patterns
the evaluator actually executes.

* fix(i18n): bound and cache translation loads

Repeated misses and simultaneous override loads spend KV reads for
the same language. Cache confirmed misses and share bounded loads
without caching read failures as missing translations.

* i18n(bot): explain command and account failures

Explain account linking, command failures and skipped delivery
outcomes consistently in both supported languages.

* fix(github): bound and reuse app token fetches

Repeated token exchanges waste requests and JWT work for every event.
Reuse valid installation tokens, share refreshes and back off briefly
after failures while keeping every shared wait bounded.

* fix(github): restrict enrichment request urls

Webhook-provided URLs must never receive an installation token on
another host. Restrict enrichment to GitHub repository API paths,
reject redirects and bound optional requests.

* fix(formatter): preserve invalid code points

Out-of-range numeric entities can throw while formatting a delivery.
Keep invalid code points verbatim instead of aborting the message.

* fix(formatter): preserve bounded markdown text

Code spans, fences, indentation and autolinks are Markdown content,
not HTML tags to strip. Preserve them while bounding cleanup input
and reusing results across routes for the same event.

* fix(formatter): strip only leading ref prefixes

A short branch or tag may itself contain refs/heads or refs/tags.
Strip one leading full-ref prefix at the caller and keep short names
unchanged when generating labels and links.

* fix(gitea): link push authors to their forge

A Gitea author is not the same-named GitHub account.
Build author profile links from the originating forge.

* fix(formatter): render deployment state values

The deployment status object stringifies as [object Object].
Render its actual state in the status field.

* fix(formatter): read security severity levels

The scanner severity is not the security severity of an alert.
Prefer the security level so critical and high alerts get the right
label and color.

* fix(formatter): hide actions on other forges

Action buttons call the GitHub API as the linked user.
Hide them for other forges to avoid operating on a same-named
GitHub repository.

* fix(check): isolate updates by check suite

Same-named checks from different suites must not edit one message.
Include the suite or app identity and retain the former key for
controlled adoption of existing tracked messages.

* fix(logs): scope queries before limiting results

Filter authorized groups in SQL before LIMIT and aggregate only
visible rows. Preserve current group attribution for late writes,
surface read failures and combine related totals in one scan.

* perf(d1): index pruning and failed send queries

Pruning and failure views should not scan all historical rows.
Index the high-value access paths without adding a write-heavy
index for infrequent delivery-detail lookups.

* fix(discord): bound individual api requests

An unbounded API request can outlive an update-chain lock.
Bound each request so another holder cannot race a late edit.

* fix(discord): defer long rate-limit waits

Long rate-limit sleeps block delivery progress inside a worker.
Return a retryable 429 for the queue when the wait exceeds the bound.

* fix(discord): encode channel path segments

Stored channel and message ids are path segments, not URL paths.
Encode them so aliases cannot address another Discord resource.

* fix(discord): reuse nonces after lost responses

A successful create may lose its response. Reuse a stable nonce
with enforce_nonce so retries recover that message instead of
posting duplicates or accepting an unreadable success.

* fix(discord): constrain embeds and role mentions

Respect combined embed and component limits as well as field caps.
Restrict allowed mentions to validated route roles so payload text
cannot notify everyone.

* fix(discord): resume bounded command syncs

Application changes, command rollbacks and large guild lists can
leave commands stale indefinitely. Track the current hash per app
and resume bounded paginated work without needless KV writes.

* fix(github): verify installation management

An installation id is user-controlled, and repository access is not
installation management. Verify the owning account or an active
organization admin using the user token and read:org scope.

* fix(github): resolve immutable member ids

A login can be renamed and reclaimed before its first sign-in.
Resolve the current immutable user id when membership is granted
so a future holder of the login cannot inherit access.

* fix(auth): revoke stale sessions and tokens

Revoked or rotated credentials must stop working despite stale KV
replicas. Track the live token and revocations in D1 and preserve
immutable identity bindings rather than trusting a recycled login.

* fix(auth): bind sessions and tokens to identity

Automatic retries can repeat non-idempotent user actions.
Disable those retries and expose a write hook so bot handlers can
record completion immediately before the GitHub write.

* fix(discord): defer and deduplicate interactions

Acknowledge slow actions before Discord times out and deduplicate
interaction writes. Preserve comment text and reject edits whose
source changed after the modal opened.

* fix(telegram): always verify webhook secrets

Webhook verification must not silently disable itself when the
optional secret is absent. Derive a stable secret from the bot
token and reject callbacks when verification is unavailable.

* fix(telegram): bound individual api requests

Bound individual platform calls so they cannot outlive the lock
protecting a message update or stall a whole delivery invocation.

* fix(telegram): honor nested rate-limit delays

Telegram places retry_after inside parameters, not at the top level.
Read that value and defer long waits to the delivery queue.

* fix(telegram): report unreadable send results

An unreadable successful response may already have sent the message.
Report an explicit uncertain result instead of retrying a create
without an idempotency key or pretending it succeeded.

* fix(telegram): keep editable messages as text

Guessing photo versus text from message content makes later edits
use the wrong API and a smaller caption budget. Always send text
and use the avatar as a link preview.

* fix(telegram): render hard breaks as newlines

Telegram HTML does not support br tags. Render Markdown hard breaks
as plain newlines so otherwise valid messages are accepted.

* fix(telegram): clamp visible html characters

Telegram counts visible characters, not HTML source bytes.
Truncate without splitting tags, entities or surrogate pairs.

* fix(telegram): honor the author emoji toggle

The author marker must obey the group emoji preference just like
formatter-added decoration.

* fix(telegram): keep completed commands claimed

Redelivery after a completed write must never post another comment.
Keep completion claims despite reply failures, scope updates per bot
and only issue account-login links in private chats.

* fix(feishu): bound individual api requests

Bound individual platform calls so they cannot outlive the lock
protecting a message update or stall a whole delivery invocation.

* fix(feishu): classify retryable api failures

Business error codes can be transient even in HTTP 200 responses.
Classify token and rate-limit errors for retry and defer long waits.

* fix(feishu): retry sends with stable uuids

An unreadable response does not prove a send failed.
Reuse the same uuid for retries so recovering the result cannot
create a second Feishu message.

* fix(feishu): refresh and evict tokens safely

Separate app token caches, stop reusing refused tokens and share
refreshes. Cache failures briefly and keep valid tokens in memory
when a best-effort KV cache write fails.

* fix(feishu): use the card update endpoint

Delayed card updates use the card update endpoint; the config
endpoint cannot update an interaction response.

* fix(feishu): neutralize untrusted mentions

Forge text is untrusted and can contain at-all tags.
Neutralize mentions in card bodies and footers before rendering.

* fix(feishu): authenticate and dedupe callbacks

Authenticate signed or token-verified callbacks before dispatching
commands. Decode encrypted envelopes and handle card actions using
the correct fields without claiming irrelevant chat events.

* fix(target): normalize actual destinations

Different target spellings can name the same actual destination.
Normalize channel, thread and topic identities for ownership checks
and per-route duplicate suppression.

* fix(config): transact per-group configuration

Whole-table writes and cached snapshots can overwrite other groups
or resurrect removed configuration. Use per-group guarded writes,
one-time identity migration and explicit unreadable-row failures.

* fix(group): preserve identity through lifecycle

Group names are mutable and reusable, so they cannot own durable
state. Preserve immutable identities across lifecycle operations and
commit invite use with membership under transaction-time guards.

* fix(oauth): confirm account links and installs

A login link or installation id is not proof of account ownership.
Verify installation management, bind browser state and require an
explicit account-link confirmation before granting chat access.

* fix(queue): fence leases and record target outcomes

Retries must remember completed targets and distinguish active
lease holders. Fence state updates, preserve permanent outcomes and
reject missing parked payloads instead of dispatching empty data.

* fix(dispatch): isolate and resume tenant sends

Check tenant sources before filters and never dispatch orphan routes.
Record each target outcome, isolate update chains by forge and group
identity, and keep stale events from overwriting newer messages.

* fix(queue): bound batches and resume deliveries

A queue invocation has shared query and subrequest limits.
Use a small batch and shared send budget, renew fenced leases and
resume only unfinished work without exhausting unstarted messages.

* fix(admin): guard revisions and tenant targets

Read-time authorization alone cannot protect concurrent edits.
Guard revisions, current roles and destination ownership in the
write transaction, and use per-group endpoints for isolated changes.

* fix(webhook): confirm only accepted deliveries

Acknowledging before queue acceptance permanently loses deliveries.
Confirm only accepted work, release failed claims, scope replay
identities and strip tenant-supplied installation authority.

* fix(storage): prune abandoned parked payloads

Oversized payloads can remain after interrupted enqueue attempts.
Prune objects beyond their retry lifetime without deleting payloads
that a current delivery may still need.

* fix(console): expose api conflict statuses

Callers need the HTTP status to distinguish stale edits from other
failures and reload current data after a conflict.

* refactor(console): model group revisions

Carry server revisions explicitly so console writes can reject
changes based on an outdated group snapshot.

* fix(console): send loaded route revisions

Send the revision actually loaded with the route list and adopt the
server response after a save. Reload on conflict instead of silently
overwriting another editor.

* fix(console): guard fragment saves by revision

Fragments share a group version with other configuration writes.
Submit the loaded revision and reload on conflict to preserve
concurrent edits.

* fix(console): save groups with guarded writes

Whole-list saves can overwrite unrelated groups. Use per-group
revision-aware writes, retain rename results and confirm deletion
on the exact group, routes and version shown to the user.

* fix(console): reject edits of stale routes

A conflict reload can leave an older route editor open.
Compare its original value before saving so it cannot overwrite
the newly loaded route.

* fix(console): show overview loading failures

Failed overview requests must not look like an empty dashboard or
a successful refresh. Show the reason while retaining prior data.

* fix(console): explain rejected install bindings

Explain why an installation binding was refused instead of silently
returning to the console with no visible outcome.

* fix(console): allow selecting a group named all

The all sentinel collides with a valid group id.
Use a value that cannot be a group id so that group stays selectable.

* fix(console): discard stale log detail responses

An older detail request can finish after a newer selection or close.
Discard it so the dialog never shows the previously clicked record.

* fix(console): retain legacy group owners

Groups predating member roles store owners in adminIds.
Load those as owners so adding a member never drops all old owners.

* fix(console): lock member edits during saves

Edits made during a save are overwritten by its result.
Disable member controls and guard handlers until the write settles.

* fix(console): show invite loading failures

Failed invite loads must not look like no pending invites.
Show the error and discard responses from a previously shown group.

* fix(console): retain legacy discord log targets

A stored log target without platform means Discord.
Keep that meaning in the editor instead of clearing the target.

* fix(console): retain undisplayed forge sources

An editor that only displays some providers must preserve the others.
Keep stored custom sources when saving unrelated group settings.

* fix(console): lock the group editor while saving

Prevent edits while a group save is in flight and make super-only
installation settings readonly instead of silently ignoring edits.

* fix(console): lock route edits and show failures

Lock the route editor while saving and show fragment load failures
with a retry action rather than presenting a false empty list.

* fix(config): expose the legal contact override

Declare the public runtime key so the documented environment
override reaches legal pages in deployed Nuxt builds.

* build(deploy): migrate d1 before deployment

Apply pending D1 migrations before deploying code that requires
them. Stop deployment when migration fails instead of running
against an incomplete schema.

* docs(worker): align guides with runtime behavior

Synchronize both language guides, API references and examples with
the implemented authorization, storage and delivery behavior.
Document migration requirements and accepted operational limits.

* fix(storage): repair orphaned KV routes

Repair orphaned KV routes before serving KV-only configuration.

* fix(security): fully escape forge HTML

---------

Co-authored-by: RhenCloud <i@rhen.cloud>
2026-10-24 16:19:06 +08:00
翅膀喵 dbf162bf74 feat(admin-console): improve route and filter management (#10)
* fix(nuxt): pre-bundle the CommonJS deps of the markdown stack

`debug` and `extend` are imported by micromark and unified through
@elysola/ui. Served unbundled by the dev server they have no default
export, so the console page failed with a 500 in `nuxt dev`.

* docs(deployment): list the fragments and feishu link migrations

The manual `d1 execute` fallback stopped at 0008, and AGENTS.md named
0001..0010 although 0011 already exists.

* feat(storage): persist the per-group route order

Routes used to load in id order, so the order saved from the console
was lost on the next read. Migration 0012 adds `d1_routes.position`:
saving writes each route's index within its own group (saving one group
never shifts another), and routes load by `group_id, position, id`.

A database without the column keeps working: only a "no such column" /
"has no column named" error falls back to the legacy statements, and
nothing is cached, so a later migration is picked up on the next call.

* feat(console): add in-app destructive-action confirmation

Deleting a route or a group used `window.confirm`, which blocks the page
and ignores the console theme. A promise-based `useConfirm()` now drives
one <ConfirmDialog /> built on the reka-ui AlertDialog that
@elysola/ui ships; reka-ui is pre-bundled so dev keeps a single copy and
the dialog stacks with the Rc dialogs.

A request never outlives its asker: one made after the asking component
unmounted resolves false, and one still open when it unmounts is
cancelled.

* feat(console): confirm member and webhook removal

Removing a member, revoking an invite link and disabling a group's
webhook endpoint took effect on the first click. They now ask first;
disabling the webhook explains that senders still using the secret will
be rejected, and its button is styled as destructive.

* feat(console): confirm removing filled editor rows

Filter conditions and groups, delivery targets, saved fragments and forge
hosts vanished on a single click, taking whatever had been typed with
them. Rows holding content now ask first, while empty, never-filled
rows (`isBlankNode`: default operator, no path, no values, not negated)
are still removed directly.

* fix(i18n): remove duplicate button glyphs

"New Route", "New Group" and the group cards' "Open" link render a Plus
or ArrowRight icon next to their label, so the "+" and "→" baked into
the strings appeared twice.

* style(console): redesign route cards for narrow screens

The card was one flex row whose badges, filter chips, targets and five
hand-drawn icon buttons squeezed the route name on small screens. It is
now a grid driven by a container query: name and actions share the top
line, the filter summary (clamped to two lines) and targets follow, and
the tags wrap below; from 40rem the tags move up beside the title.

Targets of the same platform collapse into one tag with a count, long
ids truncate instead of widening the page, and the actions use lucide
icons with accessible labels.

* feat(console): reorder a group's routes by drag or keyboard

The per-card up/down arrows saved after every single step, so moving a
route five places took five writes. A Reorder mode on the group page now
swaps each card's switch for a drag handle: pointer drags (mouse and
touch) slide the neighbours out of the way and auto-scroll near the
viewport edges, Arrow Up/Down on a focused handle moves a card by one
and is announced to screen readers, and nothing is written until Save
order. Cancel or Escape (unless a dialog or list owns it) drops the
draft.

The cards move into a new RouteList component that owns the drag state.

* style(members): align member cards and invite actions

* style(group-editor): size forge and log target controls

Keep source hosts, platform selectors and remove actions aligned without stretching short controls across the dialog. Wrap component roots explicitly so their internal markup cannot break the grid.

* style(route-editor): group options and delivery target fields

Give each target labeled fields and a compact platform header, widen the filter workspace, and align fragment controls. Scroll failed validation into view when the footer is far from the affected section.

* feat(filters): add bilingual suggestions and value validation

Catalog forge events, actions, payload paths and known values with searchable English and Chinese descriptions. Match-value validation mirrors the server and only rejects inputs that cannot match.

* feat(filters): add searchable creatable value inputs

Build a theme-aligned combobox on the shared reka-ui primitives. Rank stored keys before bilingual descriptions, allow validated custom values, and preserve unconfirmed multi-value drafts instead of silently committing them.

* feat(filter-editor): integrate searchable condition inputs

Replace chip-only values with context-aware bilingual inputs and a compact condition grid. Preserve drafts across tree changes, block saves and tests until drafts are resolved, and keep keyword filters free of hidden operators.

* feat(filters): split pasted values without breaking regexes

Accept multiple values separated by commas or lines while retaining commas inside wrapped expressions and raw regex patterns. Pasting replaces the selected range and keeps rejected values as an explicit draft.

* fix(filters): adapt suggestions to the selected operator

Offer literal prefixes and suffixes for substring operators, escaped anchored patterns for regex, and numeric suggestions only for comparisons. Suggestion syntax must mean what the selected matcher actually reads.

* fix(filters): preserve regex meaning when changing operators

Swap wrapped and raw regex sources only when both compile identically after saving. Leave literal, glob, multiline and Unicode-sensitive comparisons unchanged rather than inventing non-equivalent conversions.

* a11y(filter-editor): label type and operator controls

Associate each fixed select with a stable per-condition label while keeping the compact visual layout unchanged.

* fix(editors): ignore accidental backdrop dismissal

Do not discard unsaved route or group edits when the user clicks outside the dialog. Preserve Escape, Cancel and explicit close, including popovers and confirmation dialogs stacked above the editor.

* feat(dispatch)!: scope stop and fallback to each group

A match in one group must not suppress delivery in another group. Track regular matches and stopped scopes independently, and document the routing-table boundary.

BREAKING CHANGE: stop and fallback no longer apply globally across
groups. Put mutually exclusive routes in the same group and define
fallback routes in each group that needs its own catch-all.

* fix(dispatch): honor stop on a matching fallback route

Once a fallback matches with stop enabled, skip later routes of the same group without affecting other groups. Cover multiple fallback routes in the group-isolation regression test.

* style(console): pin theme and language controls to the right

Separate utility controls from page actions so narrow screens retain a readable title column and right-aligned actions below. Wrap long headings without letting them push controls out of view.

* style(groups): place creation beside the aligned group count

Keep the new-group action inside the group list at every width and align the label and count on one baseline with a consistent type scale.

* style(groups): align card footers and keep role badges intact

Give long names two lines, show the current role in its own non-wrapping row, and anchor every card footer to the grid-row bottom regardless of optional source metadata.

* style(logs): prevent filter labels and metadata overflow

Keep filter labels on one line and allow long channel, thread and repository identifiers to wrap instead of widening the page.

* style(console): scale the sidebar and hide mobile tab tracks

Narrow the sidebar proportionally while retaining enough room for both locales. Keep mobile navigation swipeable without a visible horizontal scrollbar.

* feat(console): give each group its own routes URL

Resolve the selected group from /admin/groups/{groupId}, validate console paths, and use browser history for back navigation. Keep Groups active and let an active mobile-tab tap return to the list. Scope pending route loads to their group and retain the count beside long headings.

* feat(console): confirm leaving unsaved page work

Guard route changes when an editor or changed order draft is open. Cancel superseded questions and restore the shown history entry when repeated Back or Forward navigation is refused; only completed navigation resets page work.

* feat(console): confirm sign-out from desktop and mobile

Expose sign-out in the mobile topbar when the sidebar is hidden. Both entry points use the in-app confirmation before navigating to the server logout endpoint.

* fix(console): keep topbar tools clear of very narrow headings

Below 360px, place the full-width heading beneath the breadcrumb and utility row so the three top-right buttons cannot overlap it.

* feat(console): prioritize group titles over actions

Place New Route after Reorder in the group bar. Measure available space and remove the reorder label first, then the creation label, before truncating the group title; remeasure on resize, locale and font changes.

* fix(editors): focus the dialog without selecting its name field

Cancel the non-bubbling FocusScope mount event in the capture phase and focus the dialog itself. Keep keyboard navigation working without highlighting the name or opening the touch keyboard automatically.

* perf(console): preserve one instance across admin navigation

Use a fixed page key instead of remounting the whole console for each URL. Refresh each view when shown and isolate overview metrics and logs so page filters cannot leak into the dashboard.

* fix(console-data): discard superseded load responses

Only the latest request may update a list, its error or loading state. Invalidate pending group loads after a save so an older response cannot restore stale configuration during persistent-console navigation.

* fix(routes): serialize writes and reject unloaded route lists

Whole-list saves must start from loaded data and wait for other route writes. Lock switches and actions during saves, recheck deletion after confirmation, and rebuild saved ordering from the newest route objects.

* fix(editors): scope async results and fragment writes to sessions

A completed save or dry run must not close or overwrite a newer editor. Keep fragment state scoped by group, reject writes until the real list is ready, and retain in-flight fragment locks across navigation.

* fix(groups): serialize edits and isolate group detail panels

Prevent overlapping whole-list writes, avoid duplicate ids after rename, and discard delete confirmations prepared on a page that has since been left. Key member and webhook panels by group so local state cannot cross tenants.

* fix(console): omit the empty action row outside overview

Render the refresh-action container only where it has content so narrow layouts do not reserve a blank row after creation controls move into their page bars.

* perf(metrics): send all seven queries in one D1 batch

Avoid seven sequential network round trips and read totals, breakdowns and recent failures in one consistent transaction. Reuse the failed-send statement and row mapping while retaining group scoping.

* fix(admin-api): bypass browser cache locks for live requests

Use no-store on both client requests and admin responses. Personalized live data must not be reused, and one stalled same-URL cache entry must not block later log requests behind the browser cache lock.

* docs(routes): Clarify fallback hints and document group-scoped stop and fallback upgrade behavior
2026-10-17 21:13:20 +08:00
github-actions[bot] 29b15f4933 chore: auto-fix lint & formatting [skip ci] 2026-10-17 03:37:45 +00:00
RhenCloud 2281c19939 refactor: rebrand WebHooker as Elysola 2026-10-17 11:37:02 +08:00
github-actions[bot] 37d2eb3636 chore: auto-fix lint & formatting [skip ci] 2026-10-03 14:55:16 +00:00
RhenCloud fbbff669a3 feat(ui): migrate to @recloudstudio/ui, add theme toggle and polish console UX 2026-10-03 22:54:32 +08:00
github-actions[bot] 0e2e30ae1a chore: auto-fix lint & formatting [skip ci] 2026-10-02 21:18:20 +08:00
RhenCloud 3567c6d321 fix(formatter): link branch and tag titles 2026-10-01 18:40:02 +08:00
RhenCloud b7fd31a665 fix(push): handle unresolved bot authors 2026-10-01 18:33:17 +08:00
RhenCloud 1057a60de7 fix(push): show differing commit author 2026-09-30 18:52:07 +08:00
RhenCloud 2891e1f33c fix(github): send User-Agent header on GitHub API requests
GitHub rejects API requests without a User-Agent (403), and Workers'
fetch does not set one by default, so workflow job enrichment and
check-suite build-log lookups silently failed in production.
2026-09-26 16:02:27 +08:00
RhenCloud 027ca2bcca fix(dispatch): hoist workflow jobs memoization above route loop
The workflow_jobsPromise declaration sat after the route dispatch loop,
so processRoute hit a temporal dead zone ReferenceError for
workflow_run events; Promise.allSettled swallowed it and no message was
sent. Move the memoized enrichment above the loop and add a regression
test that dispatches a workflow_run event with jobs enrichment.
2026-09-26 15:52:32 +08:00
github-actions[bot] e8d7455a2b chore: auto-fix lint & formatting [skip ci] 2026-09-26 07:33:49 +00:00
RhenCloud 04352c3a19 feat(github): fetch workflow_run jobs via jobs_url enrichment
The workflow_run webhook payload carries no jobs array, only jobs_url,
so the Jobs field never populated for real GitHub events. Fetch the job
list from the GitHub API once per delivery (lazy, memoized across
routes) and inject it into the payload before formatting.

- app-token.ts: shared getInstallationToken (App JWT -> installation
  token) + GITHUB_API_VERSION; check-run.ts now reuses it
- workflow-jobs.ts: getWorkflowRunJobs, App token when configured else
  unauthenticated (public repos), per_page=100, best-effort
- docs: GitHub App needs Actions: read; note API enrichment in the
  message-format and supported-events guides (en + zh)
2026-09-26 15:33:06 +08:00
github-actions[bot] ae36c22fda chore: auto-fix lint & formatting [skip ci] 2026-09-26 06:58:56 +00:00
RhenCloud e607d41432 feat(workflow): render workflow_run jobs as colored diff block
List each job on its own line with a status emoji and, for completed
jobs, the duration. Discord colors the diff fence: '+' green for
success, '-' red for other finished conclusions, plain for
running/queued/pending. Telegram/Feishu collapse it to inline code.

Sync AGENTS.md, README(s), docs guide and supported-events tables.
2026-09-26 14:58:00 +08:00
RhenCloud 2e89c79e9c fix(telegram): render rich header title as plain text 2026-09-13 13:13:09 +08:00
github-actions[bot] 1348873847 chore: auto-fix lint & formatting [skip ci] 2026-09-10 14:36:24 +00:00
RhenCloud 1a0500b812 fix: prevent data loss in routes, fragments, and group operations
Found and fixed multiple critical bugs with similar patterns:

1. routeStatements() used DELETE FROM d1_routes before re-inserting
   - Could cause data loss if interrupted or if logic changes
   - Now uses DELETE with WHERE clause + INSERT...ON CONFLICT (upsert)

2. saveFragments() used DELETE FROM d1_fragments before re-inserting
   - Same pattern as routes, fixed with targeted deletes + upsert
   - Added loadFragments() call to determine what to delete

3. adminGroupRename() didn't update fragment groupId
   - When renaming a group, fragments were left pointing to old groupId
   - Now updates fragments alongside routes, secrets, and invites

All changes follow the same safe pattern:
- Load existing data to identify what needs deletion
- Delete only removed items with WHERE clauses
- Use INSERT...ON CONFLICT DO UPDATE for upserts
- Never use bare DELETE FROM table

Testing: All 339 tests pass.
2026-09-10 22:35:43 +08:00
github-actions[bot] 6c6c67fd73 chore: auto-fix lint & formatting [skip ci] 2026-09-10 14:30:55 +00:00
RhenCloud b313cdc2fe fix: prevent cascade deletion of routes when updating groups
Previously, saveGroups() used DELETE FROM d1_groups followed by re-insertion,
which triggered ON DELETE CASCADE and wiped all routes whenever any group was updated.

Changes:
- Use INSERT...ON CONFLICT DO UPDATE (upsert) instead of delete-then-insert
- Only delete groups that are actually being removed
- Delete routes first, then delete groups (proper cascade order)
- Load existing group IDs before saving to detect deletions

This fixes the critical bug where updating one group's metadata would
delete all routes across all groups.

Data recovery: Used D1 Time Travel to restore from bookmark
000018f9-00000002-000050de-f23b7bfe5ccdc00e9c9dec3a4de8bc81 (before
the problematic group update), recovering 18 routes.
2026-09-10 22:29:47 +08:00
RhenCloud fd6ccda411 fix(check): key check_run in-place edits on check name + head_sha
Providers that emit a fresh check run id per phase (e.g. Cloudflare Pages)
no longer post a new message for each status change; same name + commit
SHA now edits the existing message. Falls back to the run id when name or
head_sha is absent. Docs updated in sync.
2026-08-31 01:17:13 +08:00
RhenCloud cc8bb4182f fix(push): render created tags/branches as create events instead of 0 commits 2026-08-29 16:47:00 +08:00
github-actions[bot] 5c31b573d3 chore: auto-fix lint & formatting [skip ci] 2026-08-27 14:00:26 +00:00
RhenCloud 449739ee97 feat(check): resolve build log url for failed check suites via GitHub API
check_suite payloads carry no details_url; the build log lives on the
underlying check_run. For failed suites, fetch the suite's check runs with
an installation token and inject the first run's details_url (preferring
the Cloudflare run) as a Build Log field.
2026-08-27 21:59:48 +08:00
RhenCloud b2db616865 fix(check): show build log link for failed check suites too
The Build Log field was only added to check_run messages; failed
check_suite messages now also link check_suite.details_url.
2026-08-27 21:43:32 +08:00
RhenCloud 8681723f2a feat(check): add build log link for failed Cloudflare checks
Failed check_run messages now include a Build Log field linking to
check_run.details_url (the Cloudflare build log page).
2026-08-27 21:43:26 +08:00
github-actions[bot] 1375db9a20 chore: auto-fix lint & formatting [skip ci] 2026-08-26 16:39:02 +00:00
RhenCloud 4b99f6d33d feat(feishu): add Feishu inbound webhook, /gh commands and card actions
- add feishu_links D1 table and link store helpers
- implement X-Lark-Signature verification, url_verification, /gh login|logout|comment|merge|close and card.action.trigger Merge/Close
- render interactive cards with clickable title link, inline links and callback buttons (no whole-card card_link)
- bind Feishu account in OAuth callback
- document event subscription and required scopes
2026-08-27 00:07:05 +08:00
github-actions[bot] df16dc94f7 chore: auto-fix lint & formatting [skip ci] 2026-08-24 14:52:59 +00:00
RhenCloud 9899cd01bf fix(telegram): render HTML with markdown-it and strip HTML from Discord bodies 2026-08-24 22:51:26 +08:00
RhenCloud c090281cb2 feat(filters): JSONPath field filters, operators, AST groups, fragments, and test-match
Add a field filter type reading any payload value by JSONPath with array expansion, 12 comparison operators (eq/ne/contains/startsWith/endsWith/regex/gt/gte/lt/lte/in/exists), a visual AST builder (all/any/not) in the route editor, chip-based multi-value input, a stateless POST /admin/api/test-match dry-run, and named filter fragments stored in D1 (d1_fragments, migration 0010) inlined into route ASTs on insert.
2026-08-24 22:51:20 +08:00
RhenCloud c955db03c3 feat(logs): populate send log detail and fix dedup re-claim condition
- dispatch: attach per-send detail (title/url/description/match/provider)
  so the admin log view shows message context, not just a bare ok flag
- idempotency: compare dedup expiry against claimed_at instead of the new
  expires_at so non-expired duplicates are rejected and expired keys re-claim
2026-08-24 22:51:11 +08:00
github-actions[bot] 7c37f5d8b6 chore: auto-fix lint & formatting [skip ci] 2026-08-17 07:51:36 +00:00
RhenCloud 25ebae4ae5 feat(storage): migrate config, dedup and delivery state to D1
- Move oversized queue payloads from KV to R2 (PAYLOAD binding, webhooks/YYYY/MM/DD/*.json, KV queue:payload:* fallback)
- Persist routes/groups to D1 (d1_routes/d1_groups) with memory -> KV -> D1 three-tier cache, seeded from legacy KV config keys
- Move webhook dedup (dedup_keys), delivery state (delivery_state) and message tracking (message_tracking) to D1 via canUseD1 probe with automatic KV fallback
- Batch send_logs inserts (recordSendBatch) and add group_id/ts index
- Add storage-prune scheduled task for expired dedup/state/tracking rows
- Add TTL to invite:group:{id} index and audit all ephemeral KV keys
- Add D1 indexes for the new tables
- Sync AGENTS.md, README.md/zh and docs/ (en/zh) with the new storage layout
2026-08-17 15:01:20 +08:00
RhenCloud 2975087262 fix(push): link branch ref in title as inline code 2026-08-17 00:01:32 +08:00
github-actions[bot] 3bcc98efc8 chore: auto-fix lint & formatting [skip ci] 2026-08-16 14:47:01 +00:00
RhenCloud df0edbb581 refactor(push): move commits to description, comparison to changes field 2026-08-16 22:46:11 +08:00
RhenCloud 47d7c9105b feat(ui): update ui style 2026-08-16 22:46:07 +08:00
github-actions[bot] ca6dfd3f64 chore: auto-fix lint & formatting [skip ci] 2026-08-15 11:24:23 +00:00
RhenCloud af2b22d65c chore(types): drop dead Env fields (DISCORD_CHANNEL_ID, DOCS_URL, GITHUB_REPO_URL, LEGAL_CONTACT) 2026-08-15 18:43:38 +08:00
RhenCloud 7ac7bb7958 fix(render): link title head to the event object URL 2026-08-15 18:25:23 +08:00
RhenCloud 2f8a87048e feat(formatters): add updateKey for suite/deployment/comment edit-in-place 2026-08-15 18:18:52 +08:00
RhenCloud 3af50496a7 fix(formatters): strip HTML from comment bodies so bot notifications render cleanly 2026-08-15 17:55:38 +08:00
RhenCloud 1e9ba3c5dd feat(observability): delivery metrics, admin metrics/delivery endpoints, admin API route wiring 2026-08-15 17:03:45 +08:00
RhenCloud 2470bd786d feat(config): valibot schemas, schema version, migrations, filter AST 2026-08-15 17:03:42 +08:00