Files
WebHooker/app/components/ConsolePage.vue
T
翅膀喵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

1578 lines
50 KiB
Vue

<template>
<div class="console-shell">
<aside class="console-sidebar">
<NuxtLink class="console-brand" to="/">
<AppLogo :size="32" />
<span
><strong>WebHooker</strong><small>{{ t("app.tagline") }}</small></span
>
</NuxtLink>
<p class="console-nav-label">{{ t("app.tagline") }}</p>
<nav class="console-nav">
<button
v-for="n in nav"
:key="n.id"
class="console-nav-item"
:class="{ active: n.id === activeNav }"
@click="switchView(n.id)"
>
<component :is="navIcon(n.id)" :size="17" :stroke-width="1.8" />
{{ n.label }}
</button>
</nav>
<div class="console-sidebar-footer">
<button type="button" @click="signOut"><LogOut :size="16" />{{ t("app.signOut") }}</button>
</div>
</aside>
<div class="console-main">
<header class="console-topbar">
<div class="console-heading">
<p class="console-kicker">WebHooker / {{ activeNav }}</p>
<h1 :title="pageTitle">{{ pageTitle }}</h1>
</div>
<div class="console-utilities">
<RcBadge
v-if="!needLogin && loadingAny"
variant="soft"
size="sm"
dot
class="console-status"
>
{{ t("status.loading") }}
</RcBadge>
<ThemeToggle />
<RcButton variant="ghost" size="sm" @click="toggle"
><Languages :size="15" class="console-lang-icon" />{{ t("app.langToggle") }}</RcButton
>
<!-- The sidebar (with its sign-out) is hidden on narrow screens. -->
<RcButton
v-if="!needLogin"
variant="ghost"
size="sm"
class="console-topbar-signout"
:title="t('app.signOut')"
:aria-label="t('app.signOut')"
@click="signOut"
><LogOut :size="15" /><span class="console-signout-label">{{
t("app.signOut")
}}</span></RcButton
>
</div>
<div v-if="view === 'overview'" class="console-actions">
<RcButton variant="ghost" size="sm" @click="refreshOverview"
><RefreshCw :size="15" />{{ t("metrics.refresh") }}</RcButton
>
</div>
</header>
<div class="console-mobile-nav" @click="onMobileNavClick">
<RcTabs
:model-value="activeNav"
:items="mobileNav"
@update:model-value="switchView($event as View)"
/>
</div>
<main class="console-content">
<div v-if="needLogin" class="console-login">
<RcCard variant="outline" padding="lg" class="console-login-card">
<template #header><LockKeyhole :size="24" /></template>
<h2>{{ t("login.title") }}</h2>
<p>{{ forbidden ? t("login.forbidden") : t("login.prompt") }}</p>
<a href="/admin/login"
><RcButton size="lg"><LogIn :size="17" />{{ t("login.button") }}</RcButton></a
>
</RcCard>
</div>
<template v-else>
<AdminHome
v-if="view === 'overview'"
:key="refreshKey"
:groups="groups"
:logs="overviewLogs"
:metrics="overviewMetrics"
:groups-loading="groupsLoading"
:logs-loading="overviewLogsLoading"
:metrics-loading="overviewMetricsLoading"
:error="overviewError"
/>
<template v-else-if="selectedGroup">
<section
ref="groupBarEl"
class="console-context-bar console-group-bar"
:class="`labels-${barLabels}`"
>
<div class="console-group-heading">
<h2 ref="groupNameEl" :title="selectedGroup.name">{{ selectedGroup.name }}</h2>
<RcBadge
:variant="groupRoutesLoading ? 'soft' : 'success'"
size="sm"
dot
class="shrink-0"
:title="t('group.routeCount', { count: groupRoutes.length })"
>{{ groupRoutes.length }}</RcBadge
>
</div>
<div class="console-context-actions">
<template v-if="reordering">
<RcButton
variant="outline"
color="neutral"
size="sm"
:disabled="savingOrder"
@click="cancelReorder"
>{{ t("routes.reorderCancel") }}</RcButton
>
<RcButton
size="sm"
:loading="savingOrder"
:disabled="!orderChanged || reorderBusy"
@click="saveOrder"
><Check :size="15" />{{ t("routes.reorderSave") }}</RcButton
>
</template>
<template v-else>
<RcButton
v-if="canReorder"
variant="outline"
color="neutral"
size="sm"
class="console-reorder-btn"
:disabled="routesBusy"
:title="t('routes.reorder')"
:aria-label="t('routes.reorder')"
@click="startReorder"
><ArrowUpDown :size="15" /><span class="console-reorder-label">{{
t("routes.reorder")
}}</span></RcButton
>
<RcButton
v-if="canCreateRoute"
size="sm"
class="console-new-route-btn"
:disabled="!routesWritable"
:title="t('app.newRoute')"
:aria-label="t('app.newRoute')"
@click="openNew"
><Plus :size="15" /><span class="console-new-route-label">{{
t("app.newRoute")
}}</span></RcButton
>
</template>
</div>
<p v-if="reordering" class="console-reorder-hint">{{ t("routes.reorderHint") }}</p>
<!-- Unseen full-width copies of the buttons: how much room their labels need. -->
<div
v-if="!reordering"
ref="barSizerEl"
class="console-bar-sizer"
aria-hidden="true"
inert
>
<RcButton
v-if="canReorder"
data-size="reorder"
variant="outline"
color="neutral"
size="sm"
tabindex="-1"
><ArrowUpDown :size="15" />{{ t("routes.reorder") }}</RcButton
>
<RcButton v-if="canCreateRoute" data-size="new" size="sm" tabindex="-1"
><Plus :size="15" />{{ t("app.newRoute") }}</RcButton
>
</div>
</section>
<p v-if="groupRoutesError" class="err">{{ groupRoutesError }}</p>
<RouteList
:routes="reordering ? orderDraft : groupRoutes"
:reordering="reordering"
:locked="routesLocked"
:readonly="!canEditRoutes(selectedGroup.id)"
@update:routes="orderDraft = $event"
@update:busy="reorderBusy = $event"
@toggle="onToggle"
@edit="openEdit"
@delete="onDelete"
/>
<section v-if="groupRoutesReady && !groupRoutes.length" class="console-empty">
<RcEmptyState :title="t('routes.emptyGroup')">
<RcButton v-if="canCreateRoute" :disabled="!routesWritable" @click="openNew"
><Plus :size="16" />{{ t("routes.createFirst") }}</RcButton
>
</RcEmptyState>
</section>
<MembersPanel
:key="selectedGroup.id"
:group="selectedGroup"
:can-edit="canEditGroup(selectedGroup.id)"
:saving="savingGroup"
@save="onSaveGroupFromPanel"
/>
<WebhookPanel
v-if="canEditGroup(selectedGroup.id)"
:key="selectedGroup.id"
:group-id="selectedGroup.id"
:can-edit="canEditGroup(selectedGroup.id)"
/>
</template>
<section v-else-if="groupMissing" class="console-empty">
<RcEmptyState :title="t('group.notFound')">
<NuxtLink to="/admin/groups"
><RcButton variant="outline" color="neutral">{{
t("group.allGroups")
}}</RcButton></NuxtLink
>
</RcEmptyState>
</section>
<section v-else-if="routeGroupId" class="console-context-bar">
<p v-if="groupsError" class="err">{{ groupsError }}</p>
<RcBadge v-else variant="soft" size="sm" dot>{{ t("status.loading") }}</RcBadge>
</section>
<template v-else-if="view === 'groups'">
<section class="console-context-bar">
<div class="console-count">
<p>{{ t("tab.groups") }}</p>
<strong>{{ groups.length }}</strong>
</div>
<div class="console-context-actions">
<RcBadge v-if="groupsLoading" variant="soft" size="sm" dot>{{
t("status.loading")
}}</RcBadge>
<RcButton
v-if="canCreateGroup"
size="sm"
:disabled="savingGroup"
@click="openNewGroup"
><Plus :size="15" />{{ t("app.newGroup") }}</RcButton
>
</div>
</section>
<p v-if="groupsError" class="err">{{ groupsError }}</p>
<section class="grid grid-cols-1 gap-3.5 sm:grid-cols-2 lg:grid-cols-3">
<RcCard
v-for="(g, i) in groups"
:key="g.id"
variant="outline"
:hoverable="true"
padding="none"
class="console-group-card transition-all hover:border-border-strong hover:shadow-xs"
:style="{ animationDelay: i * 35 + 'ms' }"
@click="enterGroup(g)"
>
<div class="flex flex-1 flex-col gap-3 p-4">
<div class="flex items-start justify-between gap-2.5">
<div class="min-w-0 flex-1">
<div
class="line-clamp-2 text-[15px] leading-snug font-semibold text-text [overflow-wrap:anywhere]"
:title="g.name || t('route.untitled')"
>
{{ g.name || t("route.untitled") }}
</div>
<div class="mt-0.5 font-mono text-[11px] text-faint truncate" :title="g.id">
{{ g.id }}
</div>
</div>
<div
v-if="canEditGroup(g.id)"
class="flex shrink-0 items-center gap-1"
@click.stop
>
<RcButton
variant="ghost"
size="icon"
class="h-7 w-7 text-muted hover:text-text"
:disabled="savingGroup"
:title="t('groupEditor.editTitle')"
@click="openEditGroup(g)"
>
<Pencil :size="13.5" />
</RcButton>
<RcButton
variant="ghost"
color="error"
size="icon"
class="h-7 w-7 text-muted hover:text-bad"
:disabled="savingGroup"
:title="t('groups.delete')"
:aria-label="t('groups.delete')"
@click="onDeleteGroup(g)"
>
<Trash2 :size="13.5" />
</RcButton>
</div>
</div>
<div class="space-y-1.5 text-xs">
<div
v-if="roleOf(g.id)"
class="flex items-center justify-between text-[11.5px]"
>
<span class="text-faint font-semibold">{{ t("groups.myRole") }}</span>
<RcBadge variant="brand" size="xs" class="whitespace-nowrap">
{{ t("roles." + roleOf(g.id)) }}
</RcBadge>
</div>
<div class="flex items-center justify-between text-[11.5px]">
<span class="text-faint font-semibold">{{ t("groups.members") }}</span>
<span class="rounded bg-surface-2 px-1.5 py-0.5 font-mono text-text">
{{ (g.members ?? []).length || (g.adminIds || []).length || 0 }}
</span>
</div>
<div
v-if="g.owners?.length"
class="flex items-center justify-between text-[11.5px]"
>
<span class="text-faint font-semibold">{{ t("groups.owners") }}</span>
<span
class="truncate max-w-[170px] text-muted text-right font-mono text-[11px]"
>
{{ g.owners.join(", ") }}
</span>
</div>
</div>
<div
class="mt-auto flex items-center justify-between pt-2 border-t border-border/70 text-xs"
>
<span class="text-faint text-[11px]">{{ t("overview.routes") }}</span>
<NuxtLink
:to="groupPath(g.id)"
class="inline-flex items-center gap-1 font-semibold text-accent hover:underline"
@click.stop
>
{{ t("groups.open") }}
<ArrowRight :size="12" />
</NuxtLink>
</div>
</div>
</RcCard>
</section>
<section v-if="!groupsLoading && !groups.length" class="console-empty">
<RcEmptyState :title="t('groups.empty')"
><RcButton v-if="isSuper" :disabled="savingGroup" @click="openNewGroup"
><Plus :size="16" />{{ t("groups.createFirst") }}</RcButton
></RcEmptyState
>
</section>
</template>
<template v-else-if="view === 'logs'">
<section v-if="logsLoading" class="console-context-bar">
<RcBadge variant="soft" size="sm" dot>{{ t("status.loading") }}</RcBadge>
</section>
<SendLogs
:logs="logs"
:loading="logsLoading"
:error="logsError"
:groups="groups"
:selected-group-id="logFilterGroup"
@refresh="loadLogs(50, logFilterGroup || undefined)"
@filter="loadLogs(50, logFilterGroup || undefined)"
@update:selected-group-id="logFilterGroup = $event"
/>
</template>
<template v-else-if="view === 'audit'">
<AuditLog
:entries="auditEntries"
:loading="auditLoading"
:error="auditError"
:groups="groups"
:selected-group-id="auditFilterGroup"
@refresh="loadAudit(50, auditFilterGroup || undefined)"
@filter="loadAudit(50, auditFilterGroup || undefined)"
@update:selected-group-id="auditFilterGroup = $event"
/>
</template>
<template v-else-if="view === 'metrics'">
<MetricsPanel
:metrics="metrics"
:loading="metricsLoading"
:error="metricsError"
:groups="groups"
:selected-group-id="metricsFilterGroup"
@refresh="loadMetrics(metricsFilterGroup || undefined)"
@filter="loadMetrics(metricsFilterGroup || undefined)"
@update:selected-group-id="metricsFilterGroup = $event"
/>
</template>
</template>
</main>
</div>
<!-- One editor for every group (not keyed): its fragment store, scoped
per group, keeps a pending fragment write's lock across navigation. -->
<RouteEditor
:open="editorOpen"
:route="editing"
:saving="routesLocked"
:group-id="selectedGroup?.id ?? null"
@close="editorOpen = false"
@save="onSave"
/>
<GroupEditor
:open="groupEditorOpen"
:group="editingGroup"
:saving="savingGroup"
:super-admin="isSuper"
@close="groupEditorOpen = false"
@save="onSaveGroup"
/>
<ConfirmDialog />
</div>
</template>
<script setup lang="ts">
import {
Activity,
ArrowRight,
ArrowUpDown,
Check,
ClipboardList,
Gauge,
Languages,
Layers3,
LockKeyhole,
LogIn,
LogOut,
Pencil,
Plus,
RefreshCw,
ShieldCheck,
Trash2,
} from "lucide-vue-next";
import type { Group, Route } from "~/types";
import type { AdminView } from "~/utils/admin-path";
import { adminGroupPath, parseAdminPath } from "~/utils/admin-path";
import { useAuditApi } from "~/composables/useAudit";
import WebhookPanel from "~/components/WebhookPanel.vue";
import AdminHome from "~/components/AdminHome.vue";
const { t, toggle, locale } = useI18n();
const { push } = useToasts();
const { confirm, settle: dismissConfirm } = useConfirm();
const route = useRoute();
const router = useRouter();
/**
* The console view mirrors the URL path so navigation is deep-linkable:
* /admin (overview) · /admin/groups · /admin/groups/{groupId} (a group's
* routes) · /admin/logs · /admin/audit · /admin/metrics. The page validates
* the path, so unknown slugs 404 before the console renders.
*/
type View = AdminView;
const adminPath = computed(() => parseAdminPath(route.params.slug));
const view = computed<View | null>(() => adminPath.value?.view ?? null);
/** Group whose routes page the URL opens (/admin/groups/{groupId}). */
const routeGroupId = computed(() => adminPath.value?.groupId ?? null);
const groupPath = adminGroupPath;
const nav = computed(() => [
{ id: "overview" as View, label: t("tab.overview"), path: "/admin" },
{ id: "groups" as View, label: t("tab.groups"), path: "/admin/groups" },
{ id: "logs" as View, label: t("tab.logs"), path: "/admin/logs" },
{ id: "audit" as View, label: t("tab.audit"), path: "/admin/audit" },
{ id: "metrics" as View, label: t("tab.metrics"), path: "/admin/metrics" },
]);
const mobileNav = computed(() =>
nav.value.map(({ id, label }) => ({ value: id, label, icon: navIcon(id) })),
);
function navIcon(id: View) {
const icons = {
overview: Gauge,
groups: Layers3,
logs: Activity,
audit: ClipboardList,
metrics: ShieldCheck,
} satisfies Record<View, typeof Gauge>;
return icons[id];
}
const activeNav = computed<View>(() => view.value ?? "overview");
const pageTitle = computed(() => {
if (selectedGroup.value) return t("group.routesIn", { name: selectedGroup.value.name });
if (routeGroupId.value) return t("tab.groups");
switch (view.value) {
case "overview":
return t("tab.overview");
case "groups":
return t("tab.groups");
case "logs":
return t("tab.logs");
case "audit":
return t("tab.audit");
case "metrics":
return t("tab.metrics");
default:
return "";
}
});
const loadingAny = computed(
() =>
groupsLoading.value ||
logsLoading.value ||
metricsLoading.value ||
overviewLogsLoading.value ||
overviewMetricsLoading.value ||
groupRoutesLoading.value ||
auditLoading.value,
);
const { logs, loading: logsLoading, error: logsError, load: loadLogs } = useSendLogs();
// 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
// shared state would carry one page's filter into the other).
const {
logs: overviewLogs,
loading: overviewLogsLoading,
error: overviewLogsError,
load: loadOverviewLogs,
} = useSendLogs();
const {
metrics: overviewMetrics,
loading: overviewMetricsLoading,
error: overviewMetricsError,
load: loadOverviewMetrics,
} = useMetrics();
/** A failed overview load: shown, never passed off as "no data". */
const overviewError = computed(
() => groupsError.value || overviewLogsError.value || overviewMetricsError.value,
);
const {
entries: auditEntries,
loading: auditLoading,
error: auditError,
load: loadAudit,
} = useAuditApi();
const { metrics, loading: metricsLoading, error: metricsError, load: loadMetrics } = useMetrics();
const {
groups,
isSuper,
roles,
roleOf,
canEditGroup,
canEditRoutes,
loading: groupsLoading,
loaded: groupsLoaded,
needLogin,
error: groupsError,
load: loadGroups,
update: updateGroup,
create: createGroup,
remove: removeGroup,
rename: groupsRename,
} = useGroupsApi();
const {
routes: groupRoutes,
loading: groupRoutesLoading,
error: groupRoutesError,
load: loadGroupRoutes,
clear: clearGroupRoutes,
ready: groupRoutesReady,
save: saveGroupRoutes,
} = useGroupRoutesApi();
const editorOpen = ref(false);
const editing = ref<Route | null>(null);
const saving = ref(false);
const forbidden = ref(false);
/** The group the URL opens, once the group list knows it. */
const selectedGroup = computed<Group | null>(() =>
routeGroupId.value ? (groups.value.find((g) => g.id === routeGroupId.value) ?? null) : null,
);
/** The URL names a group the signed-in user cannot see (or that does not exist). */
const groupMissing = computed(
() => !!routeGroupId.value && groupsLoaded.value && !groupsError.value && !selectedGroup.value,
);
const groupEditorOpen = ref(false);
const editingGroup = ref<Group | null>(null);
const savingGroup = ref(false);
/** Reorder mode: the draft order the user drags until it is saved or cancelled. */
const reordering = ref(false);
const orderDraft = ref<Route[]>([]);
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;
}
// Bumped whenever an editor opens: a save may only close the editor it was
// made from, never one opened since (on another page, for another route).
let routeEditorSession = 0;
let groupEditorSession = 0;
/** A dropped card is still settling; its new position is not in the draft yet. */
const reorderBusy = ref(false);
const orderChanged = computed(
() =>
orderDraft.value.length !== groupRoutes.value.length ||
orderDraft.value.some((r, i) => r.id !== groupRoutes.value[i]?.id),
);
const canCreateRoute = computed(
() =>
!needLogin.value &&
!!selectedGroup.value &&
canEditRoutes(selectedGroup.value.id) &&
!reordering.value,
);
const canReorder = computed(
() =>
!!selectedGroup.value && canEditRoutes(selectedGroup.value.id) && groupRoutes.value.length > 1,
);
/**
* Labels of the group bar's buttons, given up so the group name stays whole:
* first Reorder turns into an icon, then New route; only with both on icons
* may a long name be cut short.
*/
const barLabels = ref<"all" | "new" | "none">("all");
const groupBarEl = ref<HTMLElement | null>(null);
const groupNameEl = ref<HTMLElement | null>(null);
const barSizerEl = ref<HTMLElement | null>(null);
function fitBarLabels(): void {
const bar = groupBarEl.value;
const name = groupNameEl.value;
const sizer = barSizerEl.value;
if (!bar || !name || !sizer) return;
// Fractional widths throughout: a rounded pixel decides whether a name fits.
const px = (value: string): number => parseFloat(value) || 0;
const gap = (el: Element | null): number => (el ? px(getComputedStyle(el).columnGap) : 0);
const width = (el: Element | Range | null | undefined): number =>
el?.getBoundingClientRect().width ?? 0;
const barStyle = getComputedStyle(bar);
const room =
width(bar) -
px(barStyle.paddingLeft) -
px(barStyle.paddingRight) -
px(barStyle.borderLeftWidth) -
px(barStyle.borderRightWidth) -
1;
// The whole name (its text, not the ellipsis box) plus the count after it.
const text = document.createRange();
text.selectNodeContents(name);
const count = name.nextElementSibling;
const heading = width(text) + (count ? gap(name.parentElement) + width(count) : 0);
const full = (key: string): number => width(sizer.querySelector(`[data-size="${key}"]`));
// An icon-only button is a 2rem square (see `.labels-*` below).
const icon = 2 * px(getComputedStyle(document.documentElement).fontSize);
const reorder = full("reorder");
const create = full("new");
const actionsGap = gap(bar.querySelector(".console-context-actions"));
const fits = (widths: number[]): boolean => {
const shown = widths.filter((w) => w > 0);
const actions = shown.reduce((sum, w) => sum + w, 0) + (shown.length - 1) * actionsGap;
return heading + px(barStyle.columnGap) + actions <= room;
};
if (fits([reorder, create])) barLabels.value = "all";
else if (fits([reorder && icon, create])) barLabels.value = "new";
else barLabels.value = "none";
}
let barObserver: ResizeObserver | undefined;
watch(groupBarEl, (bar) => {
barObserver?.disconnect();
if (!bar || typeof ResizeObserver === "undefined") return;
barObserver = new ResizeObserver(() => fitBarLabels());
barObserver.observe(bar);
});
watch(
() => [
selectedGroup.value?.name,
groupRoutes.value.length,
locale.value,
canReorder.value,
canCreateRoute.value,
reordering.value,
],
() => nextTick(fitBarLabels),
);
onMounted(() => document.fonts?.ready.then(fitBarLabels));
onBeforeUnmount(() => barObserver?.disconnect());
const canCreateGroup = computed(
() => !needLogin.value && !routeGroupId.value && view.value === "groups" && isSuper.value,
);
const logFilterGroup = ref("");
const auditFilterGroup = ref("");
const metricsFilterGroup = ref("");
const refreshKey = ref(0);
onMounted(() => {
if (typeof window !== "undefined") {
const params = new URLSearchParams(window.location.search);
forbidden.value = params.get("error") === "forbidden";
const invite = params.get("invite");
if (invite === "ok") push(t("members.inviteOk"));
else if (invite != null && invite !== "ok") push(t("members.inviteBad"), "bad");
if (params.get("install") === "ok") push(t("install.ok"));
if (params.get("error") === "install-forbidden") push(t("install.forbidden"), "bad");
}
loadGroups();
});
// The console stays mounted across its pages (the admin page has a fixed
// key), so a page refreshes what it shows whenever it becomes active —
// direct deep links included.
watch(
view,
(v, previous) => {
if (v === "overview") {
loadOverviewLogs(50);
loadOverviewMetrics();
}
if (v === "logs") loadLogs(50, logFilterGroup.value || undefined);
if (v === "audit") loadAudit(50, auditFilterGroup.value || undefined);
if (v === "metrics") loadMetrics(metricsFilterGroup.value || undefined);
// The first load runs on mount; later visits pick up changes made since.
if (previous && (v === "overview" || v === "groups")) loadGroups();
},
{ immediate: true },
);
// Every page is a history entry: the browser's (or device's) back button
// returns from a group's routes to the group list.
function switchView(next: View): void {
const path = next === "overview" ? "/admin" : `/admin/${next}`;
if (route.path !== path) router.push(path);
}
/**
* The active mobile tab emits no change, so a tap on "Groups" while a group's
* routes are open leads back to the list here (the sidebar link does so itself).
*/
function onMobileNavClick(event: MouseEvent): void {
const tab = event.target instanceof Element ? event.target.closest('[role="tab"]') : null;
if (tab?.getAttribute("aria-selected") === "true" && routeGroupId.value) switchView("groups");
}
/** Work on the current page that leaving it would throw away. */
function hasUnsavedWork(): boolean {
return editorOpen.value || groupEditorOpen.value || (reordering.value && orderChanged.value);
}
/** Counts navigations reaching the guards; a newer one supersedes the question. */
let navigationAttempt = 0;
/** Ask before a navigation throws work away; the page resets once it happened. */
async function confirmLeave(): Promise<boolean> {
if (!hasUnsavedWork()) return true;
const attempt = navigationAttempt;
const leave = await confirm({
title: t("confirm.leaveUnsaved"),
description: t("confirm.leaveUnsavedDesc"),
confirmText: t("confirm.leave"),
kind: "leave",
});
// Superseded while asking: let the router cancel this navigation itself.
// Refusing it would read as "stay" and step the browser history back again,
// on top of the newer navigation that already moved it.
if (attempt !== navigationAttempt) return true;
// Staying after Back/Forward: the browser has already moved. The router
// steps back its own move; earlier, superseded moves are undone after it.
if (!leave && historyPosition() !== shownPosition) {
window.addEventListener("popstate", restoreShownEntry, { once: true });
}
return leave;
}
/** vue-router's position (in `history.state`) of the current history entry. */
function historyPosition(): number | null {
const position = (window.history.state as { position?: unknown } | null)?.position;
return typeof position === "number" ? position : null;
}
/** History position of the page on screen, as of the last completed navigation. */
let shownPosition = typeof window === "undefined" ? null : historyPosition();
const stopTrackingPosition = router.afterEach((_to, _from, failure) => {
if (!failure) shownPosition = historyPosition();
});
onBeforeUnmount(stopTrackingPosition);
/** Move the browser back to the entry on screen without starting a navigation. */
function restoreShownEntry(): void {
const position = historyPosition();
if (position !== null && shownPosition !== null && position !== shownPosition) {
router.options.history.go(shownPosition - position, false);
}
}
async function signOut(): Promise<void> {
const confirmed = await confirm({
title: t("confirm.signOut"),
confirmText: t("app.signOut"),
kind: "signOut",
});
// A full page load: the server clears the session and redirects.
if (confirmed) window.location.assign("/admin/logout");
}
// A newer navigation supersedes one still waiting for an answer: that
// question (like any other confirmation of this page) is cancelled first.
function supersedePending(): void {
navigationAttempt++;
dismissConfirm(false);
}
onBeforeRouteUpdate((to, from) => {
supersedePending();
return to.path === from.path || confirmLeave();
});
onBeforeRouteLeave(() => {
supersedePending();
return confirmLeave();
});
/** Bumped by every page change: work begun on one page must not act on the next. */
let pageVisit = 0;
// Only a navigation that actually happened resets the page it left: its
// editors, a reorder draft and any confirmation still open.
watch(
() => route.path,
() => {
pageVisit++;
dismissConfirm(false);
editorOpen.value = false;
groupEditorOpen.value = false;
cancelReorder();
},
);
async function refreshOverview(): Promise<void> {
refreshKey.value++;
await Promise.all([loadGroups(), loadOverviewLogs(50), loadOverviewMetrics()]);
if (overviewError.value) push(t("overview.refreshFailed"), "bad");
else push(t("overview.refreshed"));
}
function enterGroup(group: Group): void {
router.push(groupPath(group.id));
}
// The URL decides which group's routes are shown — on a deep link, a click
// on a group, or the browser's back/forward buttons alike.
watch(
routeGroupId,
(id, previous) => {
cancelReorder();
if (id) loadGroupRoutes(id);
else clearGroupRoutes();
// Back on the list: members or sources may have changed meanwhile.
if (!id && previous && view.value === "groups") loadGroups();
},
{ immediate: true },
);
function startReorder(): void {
if (!routesWritable.value) return;
orderDraft.value = [...groupRoutes.value];
reorderBusy.value = false;
reordering.value = true;
}
function cancelReorder(): void {
reordering.value = false;
reorderBusy.value = false;
orderDraft.value = [];
}
async function saveOrder(): Promise<void> {
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 {
// 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) {
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
} finally {
savingOrder.value = false;
}
}
function onReorderKey(event: KeyboardEvent): void {
if (event.key !== "Escape" || savingOrder.value || event.defaultPrevented) return;
// Escape closes an open dialog or list first (e.g. a member-removal
// confirmation); it must not also throw away the unsaved order.
const target = event.target instanceof Element ? event.target : null;
if (
target?.closest('[role="dialog"], [role="alertdialog"], [role="listbox"], [role="menu"]') ||
document.querySelector('[role="dialog"], [role="alertdialog"]')
)
return;
cancelReorder();
}
watch(reordering, (on) => {
if (on) window.addEventListener("keydown", onReorderKey);
else window.removeEventListener("keydown", onReorderKey);
});
onBeforeUnmount(() => window.removeEventListener("keydown", onReorderKey));
function openNew(): void {
routeEditorSession++;
editing.value = null;
editorOpen.value = true;
}
function openEdit(route: Route): void {
routeEditorSession++;
editing.value = route;
editorOpen.value = true;
}
async function onSave(route: Route): Promise<void> {
const group = selectedGroup.value;
if (!group || !canWriteRoutes()) return;
const session = routeEditorSession;
saving.value = true;
try {
let next: Route[];
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));
} else {
if (groupRoutes.value.some((r) => r.id === route.id)) {
push(t("toast.routeIdExists"), "bad");
return;
}
next = [...groupRoutes.value, route];
}
await saveGroupRoutes(group.id, next);
if (session === routeEditorSession) editorOpen.value = false;
push(t("toast.routesSaved"));
} catch (err) {
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
} finally {
saving.value = false;
}
}
async function onToggle(route: Route): Promise<void> {
const group = selectedGroup.value;
if (!group || !canWriteRoutes()) return;
routeMutations.value++;
try {
await saveGroupRoutes(
group.id,
groupRoutes.value.map((r) => (r.id === route.id ? route : r)),
);
} catch (err) {
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
// 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<void> {
const group = selectedGroup.value;
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,
groupRoutes.value.filter((r) => r.id !== route.id),
);
push(t("toast.routeDeleted"));
} catch (err) {
push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
} finally {
routeMutations.value--;
}
}
function openNewGroup(): void {
groupEditorSession++;
editingGroup.value = null;
groupEditorOpen.value = true;
}
function openEditGroup(group: Group): void {
groupEditorSession++;
editingGroup.value = group;
groupEditorOpen.value = true;
}
/**
* Group writes run one at a time, each built on what the previous one saved;
* true when one may start.
*/
function canWriteGroups(): boolean {
if (!savingGroup.value) return true;
push(t("toast.groupsBusy"), "bad");
return false;
}
async function onSaveGroupFromPanel(group: Group): Promise<void> {
if (!canWriteGroups()) return;
savingGroup.value = true;
try {
await updateGroup(group);
push(t("toast.groupSaved"));
} catch (err) {
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
loadGroups();
} finally {
savingGroup.value = false;
}
}
async function onSaveGroup(group: Group): Promise<void> {
if (!canWriteGroups()) return;
const session = groupEditorSession;
savingGroup.value = true;
try {
const editing = editingGroup.value;
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) {
// Id changed: rename first so routes/webhook secret/invites follow
// (refused if the group changed since the editor opened), then
// persist the remaining edits under the new id, on top of exactly the
// renamed group. If that second step fails, the editor already points
// 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 {
await updateGroup(edited);
}
} else {
if (groups.value.some((g) => g.id === group.id)) {
push(t("toast.groupIdExists"), "bad");
return;
}
await createGroup(group);
}
if (session === groupEditorSession) groupEditorOpen.value = false;
push(t("toast.groupSaved"));
await loadGroups();
} catch (err) {
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
} finally {
savingGroup.value = false;
}
}
async function onDeleteGroup(group: Group): Promise<void> {
if (!canWriteGroups()) return;
const visit = pageVisit;
// 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.
let used = 0;
let routesRevision: string | undefined;
let version: number | null = null;
try {
const data = await apiFetch<{ routes?: Route[]; revision?: string; version?: number | null }>(
`/admin/api/groups/${encodeURIComponent(group.id)}/routes`,
);
used = (data.routes ?? []).length;
routesRevision = data.revision;
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.
if (visit !== pageVisit) return;
const confirmed = await confirm({
title: t("confirm.deleteGroup", { name: group.name || group.id }),
description: used ? t("confirm.deleteGroupWarn", { n: used }).trim() : undefined,
});
if (!confirmed || visit !== pageVisit || !canWriteGroups()) return;
savingGroup.value = true;
try {
// Deletes the group as confirmed: a route added meanwhile makes it fail.
await removeGroup(group.id, group.revision, routesRevision, version);
push(t("toast.groupDeleted"));
} catch (err) {
push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
} finally {
savingGroup.value = false;
}
}
</script>
<style scoped>
.console-shell {
display: grid;
/* The sidebar narrows with the window (264px from ~1260px down to 208px),
wide enough for every label in either language. */
grid-template-columns: clamp(208px, 21vw, 264px) minmax(0, 1fr);
min-height: 100vh;
background: rgb(var(--wh-bg));
color: rgb(var(--wh-text));
}
.console-sidebar {
position: sticky;
top: 0;
display: flex;
height: 100vh;
flex-direction: column;
border-right: 1px solid rgb(var(--wh-border));
background: linear-gradient(165deg, rgb(var(--wh-surface)), rgb(var(--wh-surface-2)));
padding: 1.25rem 0.85rem;
}
.console-brand {
display: flex;
align-items: center;
gap: 0.7rem;
padding: 0.45rem 0.55rem 1.75rem;
color: rgb(var(--wh-text));
text-decoration: none;
}
.console-brand :deep(svg) {
color: rgb(var(--wh-accent));
}
.console-brand span {
display: grid;
gap: 0.1rem;
}
.console-brand strong {
font-size: 1rem;
letter-spacing: -0.04em;
}
.console-brand small,
.console-nav-label,
.console-kicker {
color: rgb(var(--wh-faint));
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.console-nav-label {
margin: 0 0.65rem 0.45rem;
}
.console-nav {
display: grid;
gap: 0.2rem;
}
.console-nav-item {
display: flex;
align-items: center;
gap: 0.7rem;
width: 100%;
border: 0;
border-radius: 0.65rem;
background: transparent;
padding: 0.7rem;
color: rgb(var(--wh-muted));
font: inherit;
font-size: 0.82rem;
font-weight: 700;
text-align: left;
transition:
background-color 150ms ease,
color 150ms ease;
cursor: pointer;
}
.console-nav-item:hover {
background: rgb(var(--wh-surface-2));
color: rgb(var(--wh-text));
}
.console-nav-item.active {
background: rgb(var(--wh-accent));
color: white;
box-shadow: 0 8px 18px rgb(var(--wh-accent) / 0.2);
}
.console-sidebar-footer {
display: grid;
gap: 0.9rem;
margin-top: auto;
padding: 0.9rem 0.55rem 0.25rem;
border-top: 1px solid rgb(var(--wh-border));
}
.console-sidebar-footer button {
display: inline-flex;
align-items: center;
gap: 0.55rem;
border: 0;
background: transparent;
padding: 0;
color: rgb(var(--wh-muted));
font: inherit;
font-size: 0.8rem;
font-weight: 700;
cursor: pointer;
}
.console-sidebar-footer button:hover {
color: rgb(var(--wh-bad));
}
.console-main {
min-width: 0;
}
.console-topbar {
position: sticky;
top: 0;
z-index: 20;
display: flex;
min-height: 76px;
align-items: center;
gap: 0.45rem;
border-bottom: 1px solid rgb(var(--wh-border));
background: color-mix(in srgb, rgb(var(--wh-bg)) 87%, transparent);
padding: 0.8rem clamp(1rem, 3vw, 2.5rem);
backdrop-filter: blur(18px);
}
.console-heading {
flex: 1 1 auto;
min-width: 0;
padding-right: 0.55rem;
}
.console-topbar h1 {
display: -webkit-box;
overflow: hidden;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
margin: 0.1rem 0 0;
font-size: 1.15rem;
letter-spacing: -0.035em;
overflow-wrap: anywhere;
}
.console-kicker {
margin: 0;
}
.console-heading .console-kicker {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.console-utilities,
.console-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 0.45rem;
}
.console-status {
white-space: nowrap;
}
.console-topbar-signout {
display: none;
}
.console-mobile-nav {
display: none;
}
.console-content {
width: min(100% - 2rem, 1240px);
margin: 0 auto;
padding: clamp(1.25rem, 3vw, 2.5rem) 0 5rem;
}
.console-login {
display: grid;
min-height: 62vh;
place-items: center;
}
.console-login-card {
width: min(100%, 430px);
text-align: center;
}
.console-login-card :deep(.rc-card-header) {
justify-content: center;
color: rgb(var(--wh-accent));
}
.console-login-card h2 {
margin: 0.35rem 0 0.65rem;
font-size: 1.35rem;
letter-spacing: -0.035em;
}
.console-login-card p {
margin: 0 0 1.4rem;
color: rgb(var(--wh-muted));
}
.console-context-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem 1rem;
margin-bottom: 1rem;
padding: 0.8rem 1rem;
border: 1px solid rgb(var(--wh-border));
border-radius: 0.85rem;
background: rgb(var(--wh-surface) / 0.6);
}
.console-context-bar > div {
display: flex;
align-items: center;
gap: 0.8rem;
}
.console-context-bar p {
margin: 0;
color: rgb(var(--wh-muted));
font-size: 0.8rem;
font-weight: 700;
}
.console-context-bar strong {
font-size: 1.25rem;
letter-spacing: -0.04em;
}
/* A heading with its count: one size, aligned on the text baseline. */
.console-context-bar > .console-count {
align-items: baseline;
gap: 0.5rem;
}
.console-count p {
color: rgb(var(--wh-text));
font-size: 1rem;
font-weight: 600;
}
.console-count strong {
color: rgb(var(--wh-muted));
font-size: 1rem;
font-variant-numeric: tabular-nums;
letter-spacing: 0;
}
.console-context-actions {
display: flex;
align-items: center;
gap: 0.5rem;
margin-left: auto;
}
/* A group's routes: its name with the route count right after it. The name
gives way (ellipsis) so the count and the actions keep their line. */
.console-group-bar {
position: relative;
}
.console-context-bar > .console-group-heading {
flex: 1 1 0;
min-width: 0;
gap: 0.5rem;
}
.console-group-heading h2 {
min-width: 0;
overflow: hidden;
margin: 0;
font-size: 1rem;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.console-group-bar .console-context-actions {
flex: none;
}
/* Labels given up for the name (see fitBarLabels): an icon-only button
turns into a 2rem square. */
.labels-new .console-reorder-label,
.labels-none .console-reorder-label,
.labels-none .console-new-route-label {
display: none;
}
.labels-new .console-reorder-btn,
.labels-none .console-reorder-btn,
.labels-none .console-new-route-btn {
width: 2rem;
padding-inline: 0;
}
/* Measures the buttons with their labels without showing or overflowing. */
.console-bar-sizer {
position: absolute;
top: 0;
left: 0;
display: flex;
width: 100%;
overflow: hidden;
visibility: hidden;
pointer-events: none;
}
.console-bar-sizer > * {
flex: none;
}
.console-context-bar .console-reorder-hint {
flex-basis: 100%;
font-size: 0.78rem;
font-weight: 500;
}
.console-empty {
padding: 4rem 1rem;
}
.console-group-card {
cursor: pointer;
}
/* Cards stretch to their grid row; the footer sits at the bottom so the
dividers of one row line up whatever each card lists above them. */
.console-group-card,
.console-group-card > :deep(div) {
display: flex;
flex-direction: column;
}
.console-group-card > :deep(div) {
flex: 1 1 auto;
}
.console-open {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: rgb(var(--wh-accent));
font-size: 0.75rem;
font-weight: 800;
}
@media (max-width: 900px) {
.console-shell {
display: block;
}
.console-sidebar {
display: none;
}
.console-topbar-signout {
display: inline-flex;
}
.console-mobile-nav {
display: block;
border-bottom: 1px solid rgb(var(--wh-border));
padding: 0.5rem 1rem;
overflow-x: auto;
/* Still swipeable, without a scrollbar under the tabs. */
scrollbar-width: none;
}
.console-mobile-nav::-webkit-scrollbar {
display: none;
}
.console-mobile-nav :deep(.rc-tabs) {
min-width: max-content;
}
}
@media (max-width: 620px) {
/* Title left with theme/language pinned top-right; page actions below, right-aligned. */
.console-topbar {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: start;
gap: 0.75rem 0.25rem;
}
.console-heading {
padding-right: 0;
}
.console-utilities {
gap: 0.25rem;
}
.console-actions {
grid-column: 1 / -1;
justify-self: end;
max-width: 100%;
overflow-x: auto;
padding-bottom: 0.05rem;
}
/* Keep the top-right tools compact so the title column stays readable. */
.console-status,
.console-signout-label,
.console-lang-icon {
display: none;
}
.console-topbar-signout {
width: 2rem;
padding-inline: 0;
}
.console-content {
width: min(100% - 1.25rem, 1240px);
}
}
@media (max-width: 360px) {
/* Too narrow to share a row with the tools: the breadcrumb sits beside
them and the title takes the full width below. */
.console-topbar {
row-gap: 0.3rem;
}
.console-heading {
display: contents;
}
.console-kicker {
grid-column: 1;
grid-row: 1;
align-self: center;
}
.console-topbar h1 {
grid-column: 1 / -1;
grid-row: 2;
margin: 0;
}
.console-utilities {
grid-column: 2;
grid-row: 1;
}
.console-actions {
grid-row: 3;
margin-top: 0.45rem;
}
}
</style>