From 5dfd0426aa282ba53ef65f368ba21e3af81a75a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=85=E8=86=80?= Date: Sat, 17 Oct 2026 15:06:34 +0800 Subject: [PATCH] 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. --- AGENTS.md | 2 +- app/components/ConsolePage.vue | 59 ++++++++++++++++++++++++++++------ app/components/RouteCard.vue | 8 ++++- app/composables/useI18n.ts | 2 ++ 4 files changed, 59 insertions(+), 12 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 09fa226..f02d1d8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,7 +18,7 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord - Per-group webhook ingress: optional `POST /webhook/{groupId}` with a per-group secret in KV (`tenant:{groupId}`) — Gitea/classic-GitHub/custom webhooks are verified against the group's secret instead of the operator's global ones; only that group's routes fire. The legacy `POST /webhook` (global secrets, all routes) stays untouched - GitHub App tenant isolation: `Group.installationId` binds a group to one GitHub App installation; events whose `payload.installation.id` differs are rejected at dispatch (hard isolation on top of the optional `owners` list). The App's Setup URL points at `GET /auth/github/install`, which renders a choice page (create `inst-{installationId}` or bind to a group the signed-in user owns, verified by role); `POST /auth/github/install/bind` performs the provisioning. `installation.created` webhook events auto-provision as a fallback (create `inst-{installationId}` or bind existing groups whose `owners` match the installing account) - 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; 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 - 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) - 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) diff --git a/app/components/ConsolePage.vue b/app/components/ConsolePage.vue index fda303a..462d6e0 100644 --- a/app/components/ConsolePage.vue +++ b/app/components/ConsolePage.vue @@ -140,7 +140,7 @@ color="neutral" size="sm" class="console-reorder-btn" - :disabled="groupRoutesLoading || saving" + :disabled="routesBusy" :title="t('routes.reorder')" :aria-label="t('routes.reorder')" @click="startReorder" @@ -152,6 +152,7 @@ v-if="canCreateRoute" size="sm" class="console-new-route-btn" + :disabled="!routesWritable" :title="t('app.newRoute')" :aria-label="t('app.newRoute')" @click="openNew" @@ -190,7 +191,7 @@ - {{ t("routes.createFirst") }} @@ -412,7 +413,7 @@ ([]); const savingOrder = ref(false); +/** Route saves (toggle/delete) still in flight; reordering waits for them. */ +const routeMutations = ref(0); +const routesBusy = computed( + () => groupRoutesLoading.value || saving.value || routeMutations.value > 0, +); +/** Route controls wait while the routes load or a write is in flight. */ +const routesLocked = computed(() => routesBusy.value || savingOrder.value); +/** + * A route write may start: the group's routes are loaded (a save replaces the + * whole list, so writing from a still-empty or failed list would wipe it) + * and no other load or write is running. + */ +const routesWritable = computed(() => groupRoutesReady.value && !routesLocked.value); + +/** Refuse a route write the page is not ready for; true when it may go ahead. */ +function canWriteRoutes(): boolean { + if (routesWritable.value) return true; + push(t("toast.routesNotReady"), "bad"); + return false; +} /** A dropped card is still settling; its new position is not in the draft yet. */ const reorderBusy = ref(false); const orderChanged = computed( @@ -856,7 +877,7 @@ watch( ); function startReorder(): void { - if (groupRoutesLoading.value || saving.value) return; + if (!routesWritable.value) return; orderDraft.value = [...groupRoutes.value]; reorderBusy.value = false; reordering.value = true; @@ -871,9 +892,18 @@ function cancelReorder(): void { async function saveOrder(): Promise { const group = selectedGroup.value; if (!group || !orderChanged.value || reorderBusy.value || savingOrder.value) return; + if (!groupRoutesReady.value || routesBusy.value) { + push(t("toast.routesNotReady"), "bad"); + return; + } savingOrder.value = true; try { - await saveGroupRoutes(group.id, orderDraft.value); + // Persist the latest copy of each route in the draft order, so the save + // can never resurrect or roll back a route changed since reordering began. + const latest = new Map(groupRoutes.value.map((r) => [r.id, r])); + const ordered = orderDraft.value.flatMap((r) => latest.get(r.id) ?? []); + const added = groupRoutes.value.filter((r) => !orderDraft.value.some((d) => d.id === r.id)); + await saveGroupRoutes(group.id, [...ordered, ...added]); cancelReorder(); push(t("toast.orderSaved")); } catch (err) { @@ -915,7 +945,7 @@ function openEdit(route: Route): void { async function onSave(route: Route): Promise { const group = selectedGroup.value; - if (!group) return; + if (!group || !canWriteRoutes()) return; saving.value = true; try { let next: Route[]; @@ -940,7 +970,8 @@ async function onSave(route: Route): Promise { async function onToggle(route: Route): Promise { const group = selectedGroup.value; - if (!group) return; + if (!group || !canWriteRoutes()) return; + routeMutations.value++; try { await saveGroupRoutes( group.id, @@ -948,15 +979,21 @@ async function onToggle(route: Route): Promise { ); } catch (err) { push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad"); - loadGroupRoutes(group.id); + // Restore the switch from the server, unless another group is open by now. + if (routeGroupId.value === group.id) loadGroupRoutes(group.id); + } finally { + routeMutations.value--; } } async function onDelete(route: Route): Promise { const group = selectedGroup.value; - if (!group) return; + if (!group || !canWriteRoutes()) return; if (!(await confirm({ title: t("confirm.deleteRoute", { name: route.name || route.id }) }))) return; + // The page may have changed while the question was open. + if (selectedGroup.value?.id !== group.id || !canWriteRoutes()) return; + routeMutations.value++; try { await saveGroupRoutes( group.id, @@ -965,6 +1002,8 @@ async function onDelete(route: Route): Promise { push(t("toast.routeDeleted")); } catch (err) { push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad"); + } finally { + routeMutations.value--; } } diff --git a/app/components/RouteCard.vue b/app/components/RouteCard.vue index 4c2cf2c..b22ddca 100644 --- a/app/components/RouteCard.vue +++ b/app/components/RouteCard.vue @@ -19,6 +19,7 @@ v-else-if="!readonly" :model-value="route.enabled" size="sm" + :disabled="locked" @update:model-value="onToggle" /> @@ -62,6 +63,7 @@ variant="ghost" size="icon" class="h-8 w-8 text-muted hover:text-text" + :disabled="locked" :title="t('routeEditor.editTitle')" :aria-label="t('routeEditor.editTitle')" @click="emit('edit', route)" @@ -74,6 +76,7 @@ color="error" size="icon" class="h-8 w-8 text-muted hover:text-bad" + :disabled="locked" :title="t('routes.delete')" :aria-label="t('routes.delete')" @click="emit('delete', route)" @@ -123,7 +126,10 @@ const props = defineProps<{ readonly?: boolean; /** Reorder mode: a drag handle replaces the switch and the actions hide. */ reordering?: boolean; - /** The new order is being saved: the handle waits until it is written. */ + /** + * The routes are being written (an order, a switch, a delete): every control + * waits, so the next change builds on what was saved. + */ locked?: boolean; /** 1-based position shown while reordering. */ position?: number; diff --git a/app/composables/useI18n.ts b/app/composables/useI18n.ts index dcda787..200d1ce 100644 --- a/app/composables/useI18n.ts +++ b/app/composables/useI18n.ts @@ -421,6 +421,7 @@ const en: Dict = { "audit.allGroups": "All groups", "audit.refresh": "⟳ Refresh", "toast.routesSaved": "Routes saved", + "toast.routesNotReady": "The routes are still loading or saving; try again in a moment", "toast.routeDeleted": "Route deleted", "toast.groupSaved": "Groups saved", "toast.groupDeleted": "Group deleted", @@ -859,6 +860,7 @@ const zh: Dict = { "audit.allGroups": "全部分组", "audit.refresh": "⟳ 刷新", "toast.routesSaved": "路由已保存", + "toast.routesNotReady": "路由仍在加载或保存中,请稍后再试", "toast.routeDeleted": "路由已删除", "toast.groupSaved": "分组已保存", "toast.groupDeleted": "分组已删除",