mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-20 17:13:49 +00:00
fix(security): harden webhook delivery pipeline and group storage (#11)
* fix(log): preserve structured error details Error objects lose their useful details when serialized as plain JSON. Keep the message, stack and cause in structured log output. * fix(runtime): bound shared in-flight waits A canceled request can leave its shared promise pending forever. Bound joins and coordinate a single replacement so later requests make progress without multiplying upstream work. * fix(bot): reject oversized callback bodies Reject declared oversized bot callbacks before reading their bodies. This keeps unauthenticated requests from wasting worker resources. * test(d1): exercise real sqlite transactions Exercise real foreign keys, transactions and conditional statements instead of mocks that cannot reproduce lost updates or cascades. * fix(storage): preserve claims across kv fallback Only missing tables justify KV fallback; other failures must surface. Remember fallback writes so migration to D1 cannot forget claims and replay completed work. Share marker checks without extra writes. * fix(filter): use isolated linear-time patterns Backtracking patterns can exhaust worker CPU on untrusted payloads. Use linear-time matching and separate bounded cache namespaces so glob and regex entries cannot corrupt each other. * fix(filter): read each event branch correctly Deployment and check branches live in event-specific nested fields. Read those fields and remove only the actual leading ref prefix. * fix(filter): read only own payload properties Inherited object properties are not webhook payload data. Read own properties only so JSONPath cannot traverse prototypes. * fix(filter): validate executable condition trees Malformed trees and unsupported patterns must not silently turn an exclude rule into a pass. Validate the shape and only the patterns the evaluator actually executes. * fix(i18n): bound and cache translation loads Repeated misses and simultaneous override loads spend KV reads for the same language. Cache confirmed misses and share bounded loads without caching read failures as missing translations. * i18n(bot): explain command and account failures Explain account linking, command failures and skipped delivery outcomes consistently in both supported languages. * fix(github): bound and reuse app token fetches Repeated token exchanges waste requests and JWT work for every event. Reuse valid installation tokens, share refreshes and back off briefly after failures while keeping every shared wait bounded. * fix(github): restrict enrichment request urls Webhook-provided URLs must never receive an installation token on another host. Restrict enrichment to GitHub repository API paths, reject redirects and bound optional requests. * fix(formatter): preserve invalid code points Out-of-range numeric entities can throw while formatting a delivery. Keep invalid code points verbatim instead of aborting the message. * fix(formatter): preserve bounded markdown text Code spans, fences, indentation and autolinks are Markdown content, not HTML tags to strip. Preserve them while bounding cleanup input and reusing results across routes for the same event. * fix(formatter): strip only leading ref prefixes A short branch or tag may itself contain refs/heads or refs/tags. Strip one leading full-ref prefix at the caller and keep short names unchanged when generating labels and links. * fix(gitea): link push authors to their forge A Gitea author is not the same-named GitHub account. Build author profile links from the originating forge. * fix(formatter): render deployment state values The deployment status object stringifies as [object Object]. Render its actual state in the status field. * fix(formatter): read security severity levels The scanner severity is not the security severity of an alert. Prefer the security level so critical and high alerts get the right label and color. * fix(formatter): hide actions on other forges Action buttons call the GitHub API as the linked user. Hide them for other forges to avoid operating on a same-named GitHub repository. * fix(check): isolate updates by check suite Same-named checks from different suites must not edit one message. Include the suite or app identity and retain the former key for controlled adoption of existing tracked messages. * fix(logs): scope queries before limiting results Filter authorized groups in SQL before LIMIT and aggregate only visible rows. Preserve current group attribution for late writes, surface read failures and combine related totals in one scan. * perf(d1): index pruning and failed send queries Pruning and failure views should not scan all historical rows. Index the high-value access paths without adding a write-heavy index for infrequent delivery-detail lookups. * fix(discord): bound individual api requests An unbounded API request can outlive an update-chain lock. Bound each request so another holder cannot race a late edit. * fix(discord): defer long rate-limit waits Long rate-limit sleeps block delivery progress inside a worker. Return a retryable 429 for the queue when the wait exceeds the bound. * fix(discord): encode channel path segments Stored channel and message ids are path segments, not URL paths. Encode them so aliases cannot address another Discord resource. * fix(discord): reuse nonces after lost responses A successful create may lose its response. Reuse a stable nonce with enforce_nonce so retries recover that message instead of posting duplicates or accepting an unreadable success. * fix(discord): constrain embeds and role mentions Respect combined embed and component limits as well as field caps. Restrict allowed mentions to validated route roles so payload text cannot notify everyone. * fix(discord): resume bounded command syncs Application changes, command rollbacks and large guild lists can leave commands stale indefinitely. Track the current hash per app and resume bounded paginated work without needless KV writes. * fix(github): verify installation management An installation id is user-controlled, and repository access is not installation management. Verify the owning account or an active organization admin using the user token and read:org scope. * fix(github): resolve immutable member ids A login can be renamed and reclaimed before its first sign-in. Resolve the current immutable user id when membership is granted so a future holder of the login cannot inherit access. * fix(auth): revoke stale sessions and tokens Revoked or rotated credentials must stop working despite stale KV replicas. Track the live token and revocations in D1 and preserve immutable identity bindings rather than trusting a recycled login. * fix(auth): bind sessions and tokens to identity Automatic retries can repeat non-idempotent user actions. Disable those retries and expose a write hook so bot handlers can record completion immediately before the GitHub write. * fix(discord): defer and deduplicate interactions Acknowledge slow actions before Discord times out and deduplicate interaction writes. Preserve comment text and reject edits whose source changed after the modal opened. * fix(telegram): always verify webhook secrets Webhook verification must not silently disable itself when the optional secret is absent. Derive a stable secret from the bot token and reject callbacks when verification is unavailable. * fix(telegram): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(telegram): honor nested rate-limit delays Telegram places retry_after inside parameters, not at the top level. Read that value and defer long waits to the delivery queue. * fix(telegram): report unreadable send results An unreadable successful response may already have sent the message. Report an explicit uncertain result instead of retrying a create without an idempotency key or pretending it succeeded. * fix(telegram): keep editable messages as text Guessing photo versus text from message content makes later edits use the wrong API and a smaller caption budget. Always send text and use the avatar as a link preview. * fix(telegram): render hard breaks as newlines Telegram HTML does not support br tags. Render Markdown hard breaks as plain newlines so otherwise valid messages are accepted. * fix(telegram): clamp visible html characters Telegram counts visible characters, not HTML source bytes. Truncate without splitting tags, entities or surrogate pairs. * fix(telegram): honor the author emoji toggle The author marker must obey the group emoji preference just like formatter-added decoration. * fix(telegram): keep completed commands claimed Redelivery after a completed write must never post another comment. Keep completion claims despite reply failures, scope updates per bot and only issue account-login links in private chats. * fix(feishu): bound individual api requests Bound individual platform calls so they cannot outlive the lock protecting a message update or stall a whole delivery invocation. * fix(feishu): classify retryable api failures Business error codes can be transient even in HTTP 200 responses. Classify token and rate-limit errors for retry and defer long waits. * fix(feishu): retry sends with stable uuids An unreadable response does not prove a send failed. Reuse the same uuid for retries so recovering the result cannot create a second Feishu message. * fix(feishu): refresh and evict tokens safely Separate app token caches, stop reusing refused tokens and share refreshes. Cache failures briefly and keep valid tokens in memory when a best-effort KV cache write fails. * fix(feishu): use the card update endpoint Delayed card updates use the card update endpoint; the config endpoint cannot update an interaction response. * fix(feishu): neutralize untrusted mentions Forge text is untrusted and can contain at-all tags. Neutralize mentions in card bodies and footers before rendering. * fix(feishu): authenticate and dedupe callbacks Authenticate signed or token-verified callbacks before dispatching commands. Decode encrypted envelopes and handle card actions using the correct fields without claiming irrelevant chat events. * fix(target): normalize actual destinations Different target spellings can name the same actual destination. Normalize channel, thread and topic identities for ownership checks and per-route duplicate suppression. * fix(config): transact per-group configuration Whole-table writes and cached snapshots can overwrite other groups or resurrect removed configuration. Use per-group guarded writes, one-time identity migration and explicit unreadable-row failures. * fix(group): preserve identity through lifecycle Group names are mutable and reusable, so they cannot own durable state. Preserve immutable identities across lifecycle operations and commit invite use with membership under transaction-time guards. * fix(oauth): confirm account links and installs A login link or installation id is not proof of account ownership. Verify installation management, bind browser state and require an explicit account-link confirmation before granting chat access. * fix(queue): fence leases and record target outcomes Retries must remember completed targets and distinguish active lease holders. Fence state updates, preserve permanent outcomes and reject missing parked payloads instead of dispatching empty data. * fix(dispatch): isolate and resume tenant sends Check tenant sources before filters and never dispatch orphan routes. Record each target outcome, isolate update chains by forge and group identity, and keep stale events from overwriting newer messages. * fix(queue): bound batches and resume deliveries A queue invocation has shared query and subrequest limits. Use a small batch and shared send budget, renew fenced leases and resume only unfinished work without exhausting unstarted messages. * fix(admin): guard revisions and tenant targets Read-time authorization alone cannot protect concurrent edits. Guard revisions, current roles and destination ownership in the write transaction, and use per-group endpoints for isolated changes. * fix(webhook): confirm only accepted deliveries Acknowledging before queue acceptance permanently loses deliveries. Confirm only accepted work, release failed claims, scope replay identities and strip tenant-supplied installation authority. * fix(storage): prune abandoned parked payloads Oversized payloads can remain after interrupted enqueue attempts. Prune objects beyond their retry lifetime without deleting payloads that a current delivery may still need. * fix(console): expose api conflict statuses Callers need the HTTP status to distinguish stale edits from other failures and reload current data after a conflict. * refactor(console): model group revisions Carry server revisions explicitly so console writes can reject changes based on an outdated group snapshot. * fix(console): send loaded route revisions Send the revision actually loaded with the route list and adopt the server response after a save. Reload on conflict instead of silently overwriting another editor. * fix(console): guard fragment saves by revision Fragments share a group version with other configuration writes. Submit the loaded revision and reload on conflict to preserve concurrent edits. * fix(console): save groups with guarded writes Whole-list saves can overwrite unrelated groups. Use per-group revision-aware writes, retain rename results and confirm deletion on the exact group, routes and version shown to the user. * fix(console): reject edits of stale routes A conflict reload can leave an older route editor open. Compare its original value before saving so it cannot overwrite the newly loaded route. * fix(console): show overview loading failures Failed overview requests must not look like an empty dashboard or a successful refresh. Show the reason while retaining prior data. * fix(console): explain rejected install bindings Explain why an installation binding was refused instead of silently returning to the console with no visible outcome. * fix(console): allow selecting a group named all The all sentinel collides with a valid group id. Use a value that cannot be a group id so that group stays selectable. * fix(console): discard stale log detail responses An older detail request can finish after a newer selection or close. Discard it so the dialog never shows the previously clicked record. * fix(console): retain legacy group owners Groups predating member roles store owners in adminIds. Load those as owners so adding a member never drops all old owners. * fix(console): lock member edits during saves Edits made during a save are overwritten by its result. Disable member controls and guard handlers until the write settles. * fix(console): show invite loading failures Failed invite loads must not look like no pending invites. Show the error and discard responses from a previously shown group. * fix(console): retain legacy discord log targets A stored log target without platform means Discord. Keep that meaning in the editor instead of clearing the target. * fix(console): retain undisplayed forge sources An editor that only displays some providers must preserve the others. Keep stored custom sources when saving unrelated group settings. * fix(console): lock the group editor while saving Prevent edits while a group save is in flight and make super-only installation settings readonly instead of silently ignoring edits. * fix(console): lock route edits and show failures Lock the route editor while saving and show fragment load failures with a retry action rather than presenting a false empty list. * fix(config): expose the legal contact override Declare the public runtime key so the documented environment override reaches legal pages in deployed Nuxt builds. * build(deploy): migrate d1 before deployment Apply pending D1 migrations before deploying code that requires them. Stop deployment when migration fails instead of running against an incomplete schema. * docs(worker): align guides with runtime behavior Synchronize both language guides, API references and examples with the implemented authorization, storage and delivery behavior. Document migration requirements and accepted operational limits. * fix(storage): repair orphaned KV routes Repair orphaned KV routes before serving KV-only configuration. * fix(security): fully escape forge HTML --------- Co-authored-by: RhenCloud <i@rhen.cloud>
This commit is contained in:
1 parent
dbf162bf74
commit
978c53eeb3
163 files changed
+18459
-3607
No files matched your search
@@ -8,6 +8,8 @@ const props = defineProps<{
|
||||
groupsLoading: boolean;
|
||||
logsLoading: boolean;
|
||||
metricsLoading: boolean;
|
||||
/** Why the latest load failed (what is shown may be empty or older). */
|
||||
error?: string;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -72,6 +74,7 @@ function fmtTime(ts: number): string {
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<p v-if="error" class="err">{{ t("overview.loadFailed", { error }) }}</p>
|
||||
<!-- KPI cards -->
|
||||
<section class="grid grid-cols-2 gap-4 xl:grid-cols-4">
|
||||
<RcCard v-for="k in kpis" :key="k.label" variant="outline" padding="md" class="p-5">
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<label class="filter-label">{{ t("audit.filterGroup") }}</label>
|
||||
<RcSelect
|
||||
class="filter-select"
|
||||
:model-value="selectedGroupId || 'all'"
|
||||
:model-value="selectedGroupId || '*'"
|
||||
:options="groupOptions"
|
||||
:disabled="loading"
|
||||
@update:model-value="onGroupFilter"
|
||||
@@ -75,12 +75,12 @@ function refresh(): void {
|
||||
}
|
||||
|
||||
const groupOptions = computed(() => [
|
||||
{ label: t("audit.allGroups"), value: "all" },
|
||||
{ label: t("audit.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||
]);
|
||||
|
||||
function onGroupFilter(value: string): void {
|
||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
||||
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||
emit("filter");
|
||||
}
|
||||
</script>
|
||||
@@ -96,6 +96,7 @@
|
||||
:groups-loading="groupsLoading"
|
||||
:logs-loading="overviewLogsLoading"
|
||||
:metrics-loading="overviewMetricsLoading"
|
||||
:error="overviewError"
|
||||
/>
|
||||
|
||||
<template v-else-if="selectedGroup">
|
||||
@@ -543,12 +544,22 @@ const { logs, loading: logsLoading, error: logsError, load: loadLogs } = useSend
|
||||
// Overview shows every group's latest sends and totals, apart from the Send
|
||||
// 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, load: loadOverviewLogs } = useSendLogs();
|
||||
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,
|
||||
@@ -568,7 +579,9 @@ const {
|
||||
needLogin,
|
||||
error: groupsError,
|
||||
load: loadGroups,
|
||||
save: saveGroups,
|
||||
update: updateGroup,
|
||||
create: createGroup,
|
||||
remove: removeGroup,
|
||||
rename: groupsRename,
|
||||
} = useGroupsApi();
|
||||
const {
|
||||
@@ -733,6 +746,7 @@ onMounted(() => {
|
||||
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();
|
||||
});
|
||||
@@ -868,7 +882,8 @@ watch(
|
||||
async function refreshOverview(): Promise<void> {
|
||||
refreshKey.value++;
|
||||
await Promise.all([loadGroups(), loadOverviewLogs(50), loadOverviewMetrics()]);
|
||||
push(t("overview.refreshed"));
|
||||
if (overviewError.value) push(t("overview.refreshFailed"), "bad");
|
||||
else push(t("overview.refreshed"));
|
||||
}
|
||||
|
||||
function enterGroup(group: Group): void {
|
||||
@@ -966,6 +981,13 @@ async function onSave(route: Route): Promise<void> {
|
||||
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)) {
|
||||
@@ -1036,8 +1058,8 @@ function openEditGroup(group: Group): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Group writes replace the whole group list, so they run one at a time, each
|
||||
* built from the list the previous one saved; true when one may start.
|
||||
* 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;
|
||||
@@ -1049,8 +1071,7 @@ async function onSaveGroupFromPanel(group: Group): Promise<void> {
|
||||
if (!canWriteGroups()) return;
|
||||
savingGroup.value = true;
|
||||
try {
|
||||
const next = groups.value.map((g) => (g.id === group.id ? group : g));
|
||||
await saveGroups(next);
|
||||
await updateGroup(group);
|
||||
push(t("toast.groupSaved"));
|
||||
} catch (err) {
|
||||
push(t("toast.saveFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
||||
@@ -1066,25 +1087,34 @@ async function onSaveGroup(group: Group): Promise<void> {
|
||||
savingGroup.value = true;
|
||||
try {
|
||||
const editing = editingGroup.value;
|
||||
let next: Group[];
|
||||
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,
|
||||
// then persist the remaining edits under the new id.
|
||||
await groupsRename(editing.id, group.id);
|
||||
// A list loaded meanwhile may already hold the new id as well.
|
||||
next = [...groups.value.filter((g) => g.id !== editing.id && g.id !== group.id), group];
|
||||
// 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 {
|
||||
next = groups.value.map((g) => (g.id === editing.id ? group : g));
|
||||
await updateGroup(edited);
|
||||
}
|
||||
} else {
|
||||
if (groups.value.some((g) => g.id === group.id)) {
|
||||
push(t("toast.groupIdExists"), "bad");
|
||||
return;
|
||||
}
|
||||
next = [...groups.value, group];
|
||||
await createGroup(group);
|
||||
}
|
||||
await saveGroups(next);
|
||||
if (session === groupEditorSession) groupEditorOpen.value = false;
|
||||
push(t("toast.groupSaved"));
|
||||
await loadGroups();
|
||||
@@ -1101,13 +1131,25 @@ async function onDeleteGroup(group: Group): Promise<void> {
|
||||
// Fetch the real route count for this group instead of relying on the
|
||||
// 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[] }>(
|
||||
const data = await apiFetch<{ routes?: Route[]; revision?: string; version?: number | null }>(
|
||||
`/admin/api/groups/${encodeURIComponent(group.id)}/routes`,
|
||||
);
|
||||
used = (data.routes ?? []).length;
|
||||
} catch {
|
||||
// Count is best-effort; proceed without the warning.
|
||||
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;
|
||||
@@ -1118,7 +1160,8 @@ async function onDeleteGroup(group: Group): Promise<void> {
|
||||
if (!confirmed || visit !== pageVisit || !canWriteGroups()) return;
|
||||
savingGroup.value = true;
|
||||
try {
|
||||
await saveGroups(groups.value.filter((g) => g.id !== group.id));
|
||||
// Deletes the group as confirmed: a route added meanwhile makes it fail.
|
||||
await removeGroup(group.id, group.revision, routesRevision, version);
|
||||
push(t("toast.groupDeleted"));
|
||||
} catch (err) {
|
||||
push(t("toast.deleteFailed", { msg: err instanceof Error ? err.message : String(err) }), "bad");
|
||||
|
||||
+219
-205
@@ -14,225 +14,233 @@
|
||||
</div>
|
||||
</template>
|
||||
<form class="editor-body" @submit.prevent="save">
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionBasic") }}</h3>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.name") }}</label>
|
||||
<RcInput
|
||||
v-model="form.name"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.namePlaceholder')"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.id") }}</label>
|
||||
<RcInput
|
||||
v-model="form.id"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.idPlaceholder')"
|
||||
required
|
||||
/>
|
||||
<div class="hint">
|
||||
{{ isEdit ? t("groupEditor.renameHint") : t("groupEditor.idHint") }}
|
||||
<!-- Locked while saving: an edit made meanwhile would be lost when the
|
||||
save closes the editor. -->
|
||||
<fieldset :disabled="saving" class="contents">
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionBasic") }}</h3>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.name") }}</label>
|
||||
<RcInput
|
||||
v-model="form.name"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.namePlaceholder')"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.id") }}</label>
|
||||
<RcInput
|
||||
v-model="form.id"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.idPlaceholder')"
|
||||
required
|
||||
/>
|
||||
<div class="hint">
|
||||
{{ isEdit ? t("groupEditor.renameHint") : t("groupEditor.idHint") }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionPreferences") }}</h3>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.language") }}</label>
|
||||
<RcInput
|
||||
v-model="form.lang"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.langPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("groupEditor.langHint") }}</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionPreferences") }}</h3>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("groupEditor.language") }}</label>
|
||||
<RcInput
|
||||
v-model="form.lang"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.langPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("groupEditor.langHint") }}</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.emoji") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.emojiNote") }}</span></label
|
||||
>
|
||||
<RcSwitch v-model="form.emoji" :label="t('groupEditor.emojiLabel')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.emoji") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.emojiNote") }}</span></label
|
||||
>{{ t("groupEditor.forgeSources") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.forgeSourcesNote") }}</span></label
|
||||
>
|
||||
<RcSwitch v-model="form.emoji" :label="t('groupEditor.emojiLabel')" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.forgeSources") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.forgeSourcesNote") }}</span></label
|
||||
>
|
||||
<div v-for="(s, i) in form.forgeSources" :key="i" class="forge-source-row">
|
||||
<div class="f-host">
|
||||
<RcInput
|
||||
v-model="s.host"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesHost')"
|
||||
/>
|
||||
<div v-for="(s, i) in form.forgeSources" :key="i" class="forge-source-row">
|
||||
<div class="f-host">
|
||||
<RcInput
|
||||
v-model="s.host"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesHost')"
|
||||
/>
|
||||
</div>
|
||||
<div class="f-type">
|
||||
<RcSelect
|
||||
v-model="s.type"
|
||||
:options="[
|
||||
{ label: 'GitHub', value: 'github' },
|
||||
{ label: 'Gitea', value: 'gitea' },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="f-del h-9 w-9 text-muted hover:text-bad"
|
||||
:title="t('groupEditor.forgeSourcesRemove')"
|
||||
:aria-label="t('groupEditor.forgeSourcesRemove')"
|
||||
@click="removeForgeSource(s)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
<div class="f-name">
|
||||
<RcInput
|
||||
v-model="s.name"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesName')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="f-type">
|
||||
<RcSelect
|
||||
v-model="s.type"
|
||||
:options="[
|
||||
{ label: 'GitHub', value: 'github' },
|
||||
{ label: 'Gitea', value: 'gitea' },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="f-del h-9 w-9 text-muted hover:text-bad"
|
||||
:title="t('groupEditor.forgeSourcesRemove')"
|
||||
:aria-label="t('groupEditor.forgeSourcesRemove')"
|
||||
@click="removeForgeSource(s)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addForgeSource">
|
||||
{{ t("groupEditor.forgeSourcesAdd") }}
|
||||
</RcButton>
|
||||
<div class="f-name">
|
||||
<RcInput
|
||||
v-model="s.name"
|
||||
type="text"
|
||||
:placeholder="t('groupEditor.forgeSourcesName')"
|
||||
<div class="hint">{{ t("groupEditor.forgeSourcesHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionAccess") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.membersNote") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.membersHint") }}</span></label
|
||||
>
|
||||
<p class="hint">
|
||||
{{ t("groupEditor.membersGoPanel") }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="superAdmin" class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.owners") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.ownersNote") }}</span></label
|
||||
>
|
||||
<RcTagInput
|
||||
v-model="owners"
|
||||
separator=","
|
||||
:placeholder="t('groupEditor.ownersPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("groupEditor.ownersHint") }}</div>
|
||||
</div>
|
||||
<div v-else class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.owners") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.ownersSuperOnly") }}</span></label
|
||||
>
|
||||
<RcInput v-model="ownersReadonly" type="text" class="opacity-60" disabled />
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionProviders") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.providers") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.providersNote") }}</span></label
|
||||
>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<RcCheckbox
|
||||
:model-value="form.providers.includes('github')"
|
||||
label="GitHub"
|
||||
@update:model-value="toggleProvider('github', $event)"
|
||||
/>
|
||||
<RcCheckbox
|
||||
:model-value="form.providers.includes('gitea')"
|
||||
label="Gitea"
|
||||
@update:model-value="toggleProvider('gitea', $event)"
|
||||
/>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.providersHint") }}</div>
|
||||
</div>
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addForgeSource">
|
||||
{{ t("groupEditor.forgeSourcesAdd") }}
|
||||
</RcButton>
|
||||
<div class="hint">{{ t("groupEditor.forgeSourcesHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionAccess") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.membersNote") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.membersHint") }}</span></label
|
||||
>
|
||||
<p class="hint">
|
||||
{{ t("groupEditor.membersGoPanel") }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="superAdmin" class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.owners") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.ownersNote") }}</span></label
|
||||
>
|
||||
<RcTagInput
|
||||
v-model="owners"
|
||||
separator=","
|
||||
:placeholder="t('groupEditor.ownersPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("groupEditor.ownersHint") }}</div>
|
||||
</div>
|
||||
<div v-else class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.owners") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.ownersSuperOnly") }}</span></label
|
||||
>
|
||||
<RcInput v-model="ownersReadonly" type="text" class="opacity-60" disabled />
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionProviders") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.providers") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.providersNote") }}</span></label
|
||||
>
|
||||
<div class="flex flex-wrap gap-4">
|
||||
<RcCheckbox
|
||||
:model-value="form.providers.includes('github')"
|
||||
label="GitHub"
|
||||
@update:model-value="toggleProvider('github', $event)"
|
||||
/>
|
||||
<RcCheckbox
|
||||
:model-value="form.providers.includes('gitea')"
|
||||
label="Gitea"
|
||||
@update:model-value="toggleProvider('gitea', $event)"
|
||||
/>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.providersHint") }}</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.installationId") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.installationIdNote") }}</span></label
|
||||
>
|
||||
<div class="ctl-md">
|
||||
<RcInput
|
||||
v-model="form.installationId"
|
||||
type="text"
|
||||
inputmode="numeric"
|
||||
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.installationIdHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionLog") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.logTarget") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.logTargetNote") }}</span></label
|
||||
>
|
||||
<div class="ctl-md">
|
||||
<RcSelect
|
||||
:model-value="form.logPlatform || 'none'"
|
||||
:options="[
|
||||
{ label: t('groupEditor.logDisabled'), value: 'none' },
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('groupEditor.logFeishu'), value: 'feishu' },
|
||||
]"
|
||||
@update:model-value="
|
||||
form.logPlatform = ($event === 'none' ? '' : $event) as
|
||||
'' | 'discord' | 'telegram' | 'feishu'
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="form.logPlatform" class="ctl-stack">
|
||||
<template v-if="form.logPlatform === 'discord'">
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.installationId") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.installationIdNote") }}</span></label
|
||||
>
|
||||
<div class="ctl-md">
|
||||
<!-- Only super admins bind installations here (the server keeps
|
||||
the stored value for anyone else); owners use the install flow. -->
|
||||
<RcInput
|
||||
v-model="form.logChannelId"
|
||||
v-model="form.installationId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
inputmode="numeric"
|
||||
:class="superAdmin ? '' : 'opacity-60'"
|
||||
:disabled="!superAdmin"
|
||||
:placeholder="t('groupEditor.installationIdPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="form.logThreadId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<RcInput
|
||||
v-model="form.logChatId"
|
||||
type="text"
|
||||
:placeholder="
|
||||
form.logPlatform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.installationIdHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("groupEditor.sectionLog") }}</h3>
|
||||
<div class="field">
|
||||
<label
|
||||
>{{ t("groupEditor.logTarget") }}
|
||||
<span class="lbl-note">{{ t("groupEditor.logTargetNote") }}</span></label
|
||||
>
|
||||
<div class="ctl-md">
|
||||
<RcSelect
|
||||
:model-value="form.logPlatform || 'none'"
|
||||
:options="[
|
||||
{ label: t('groupEditor.logDisabled'), value: 'none' },
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('groupEditor.logFeishu'), value: 'feishu' },
|
||||
]"
|
||||
@update:model-value="
|
||||
form.logPlatform = ($event === 'none' ? '' : $event) as
|
||||
'' | 'discord' | 'telegram' | 'feishu'
|
||||
"
|
||||
/>
|
||||
<RcInput
|
||||
v-if="form.logPlatform === 'telegram'"
|
||||
v-model="form.logTopicId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div v-if="form.logPlatform" class="ctl-stack">
|
||||
<template v-if="form.logPlatform === 'discord'">
|
||||
<RcInput
|
||||
v-model="form.logChannelId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
<RcInput
|
||||
v-model="form.logThreadId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else>
|
||||
<RcInput
|
||||
v-model="form.logChatId"
|
||||
type="text"
|
||||
:placeholder="
|
||||
form.logPlatform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
"
|
||||
/>
|
||||
<RcInput
|
||||
v-if="form.logPlatform === 'telegram'"
|
||||
v-model="form.logTopicId"
|
||||
type="text"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.logTargetHint") }}</div>
|
||||
</div>
|
||||
<div class="hint">{{ t("groupEditor.logTargetHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
<div class="err">{{ formError }}</div>
|
||||
</section>
|
||||
<div class="err">{{ formError }}</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
<template #footer>
|
||||
<div class="editor-foot">
|
||||
@@ -330,7 +338,8 @@ watch(
|
||||
form.emoji = g?.emoji ?? true;
|
||||
form.forgeSources = (g?.forgeSources ?? []).map((s) => ({ ...s }));
|
||||
form.lang = g?.lang ?? "";
|
||||
form.logPlatform = lt?.platform ?? "";
|
||||
// A stored target without a platform is a Discord one (as the server reads it).
|
||||
form.logPlatform = lt ? (lt.platform ?? "discord") : "";
|
||||
form.logChannelId = lt?.channelId ?? "";
|
||||
form.logThreadId = lt?.threadId ?? "";
|
||||
form.logChatId = lt?.chatId ?? "";
|
||||
@@ -417,8 +426,13 @@ function save(): void {
|
||||
members,
|
||||
adminIds: members.filter((m) => m.role === "owner").map((m) => m.login),
|
||||
owners: props.superAdmin ? (owners.length ? owners : undefined) : props.group?.owners,
|
||||
providers: form.providers.length ? form.providers : undefined,
|
||||
installationId,
|
||||
// Sources the form does not offer (e.g. "custom") are kept as they were.
|
||||
providers: (() => {
|
||||
const kept = (props.group?.providers ?? []).filter((p) => p !== "github" && p !== "gitea");
|
||||
const all = [...form.providers, ...kept];
|
||||
return all.length ? all : undefined;
|
||||
})(),
|
||||
installationId: props.superAdmin ? installationId : props.group?.installationId,
|
||||
emoji: form.emoji,
|
||||
forgeSources: form.forgeSources.length
|
||||
? form.forgeSources.map((s) => ({
|
||||
|
||||
@@ -46,11 +46,12 @@
|
||||
type="text"
|
||||
size="sm"
|
||||
:placeholder="t('members.addPlaceholder')"
|
||||
:disabled="saving"
|
||||
@keydown.enter.prevent="addMember"
|
||||
/>
|
||||
</div>
|
||||
<div class="member-role">
|
||||
<RcSelect v-model="newRole" :options="roleOptions" />
|
||||
<RcSelect v-model="newRole" :options="roleOptions" :disabled="saving" />
|
||||
</div>
|
||||
<RcButton type="button" size="sm" class="h-9" :disabled="saving" @click="addMember">
|
||||
{{ t("members.addBtn") }}
|
||||
@@ -76,6 +77,9 @@
|
||||
{{ t("members.createInvite") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<p v-if="invitesError" class="err">
|
||||
{{ t("members.invitesFailed", { error: invitesError }) }}
|
||||
</p>
|
||||
<ul v-if="invites.length" class="invite-list">
|
||||
<li v-for="inv in invites" :key="inv.token" class="invite-row">
|
||||
<code class="invite-token">{{ shortToken(inv.token) }}</code>
|
||||
@@ -93,7 +97,7 @@
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-else class="empty-log">{{ t("members.noInvites") }}</p>
|
||||
<p v-else-if="!invitesError" class="empty-log">{{ t("members.noInvites") }}</p>
|
||||
</div>
|
||||
|
||||
<div class="err">{{ formError }}</div>
|
||||
@@ -115,6 +119,8 @@ const emit = defineEmits<{ (e: "save", group: Group): void }>();
|
||||
const invitesApi = useInvitesApi();
|
||||
const members = ref<GroupMember[]>([]);
|
||||
const invites = ref<GroupInvite[]>([]);
|
||||
/** The last list load failed (the list shown, if any, is the one before). */
|
||||
const invitesError = ref("");
|
||||
const newLogin = ref("");
|
||||
const newRole = ref<GroupRole>("admin");
|
||||
const inviteRole = ref<"admin" | "viewer">("admin");
|
||||
@@ -132,16 +138,34 @@ const inviteRoleOptions = computed(() =>
|
||||
|
||||
watch(
|
||||
() => props.group,
|
||||
(g) => {
|
||||
members.value = (g.members ?? []).map((m) => ({ ...m }));
|
||||
(g, prev) => {
|
||||
// A group from before member roles lists its owners in `adminIds` only:
|
||||
// read as owners (as the server does), so a save never drops them.
|
||||
members.value = g.members?.length
|
||||
? g.members.map((m) => ({ ...m }))
|
||||
: (g.adminIds ?? []).map((login) => ({ login, role: "owner" as const }));
|
||||
formError.value = "";
|
||||
// Another group's invites are never shown, not even while loading.
|
||||
if (g.id !== prev?.id) {
|
||||
invites.value = [];
|
||||
invitesError.value = "";
|
||||
}
|
||||
if (props.canEdit) loadInvites();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
async function loadInvites(): Promise<void> {
|
||||
invites.value = await invitesApi.list(props.group.id);
|
||||
const groupId = props.group.id;
|
||||
try {
|
||||
const list = await invitesApi.list(groupId);
|
||||
if (props.group.id !== groupId) return;
|
||||
invites.value = list;
|
||||
invitesError.value = "";
|
||||
} catch (err) {
|
||||
if (props.group.id !== groupId) return;
|
||||
invitesError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
}
|
||||
|
||||
function ownerCount(): number {
|
||||
@@ -149,6 +173,9 @@ function ownerCount(): number {
|
||||
}
|
||||
|
||||
function onRoleChange(m: GroupMember, role: string): void {
|
||||
// One save at a time: a change made meanwhile would be overwritten by the
|
||||
// first save's result (and the second save refused).
|
||||
if (props.saving) return;
|
||||
const nextRole = role as GroupRole;
|
||||
if (nextRole === "viewer" && m.role === "owner" && ownerCount() === 1) {
|
||||
formError.value = t("members.errLastOwner");
|
||||
@@ -159,6 +186,7 @@ function onRoleChange(m: GroupMember, role: string): void {
|
||||
}
|
||||
|
||||
function addMember(): void {
|
||||
if (props.saving) return;
|
||||
const login = newLogin.value.trim();
|
||||
if (!login) return;
|
||||
if (members.value.some((m) => m.login.toLowerCase() === login.toLowerCase())) {
|
||||
@@ -180,7 +208,7 @@ async function removeMember(m: GroupMember): Promise<void> {
|
||||
title: t("confirm.removeMember", { name: m.login }),
|
||||
confirmText: t("members.remove"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
if (!confirmed || props.saving) return;
|
||||
members.value = members.value.filter((x) => x !== m);
|
||||
emitSave();
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ const emit = defineEmits<{
|
||||
const sortBy = ref<"total" | "failed" | "rate">("total");
|
||||
|
||||
const groupOptions = computed(() => [
|
||||
{ label: t("metrics.allGroups"), value: "all" },
|
||||
{ label: t("metrics.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||
]);
|
||||
|
||||
@@ -34,7 +34,7 @@ function pctOf(count: number, total: number): string {
|
||||
}
|
||||
|
||||
function onGroupFilter(value: string): void {
|
||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
||||
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||
emit("filter");
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ function cycleSort(): void {
|
||||
<label class="filter-label">{{ t("metrics.filterGroup") }}</label>
|
||||
<RcSelect
|
||||
class="filter-select"
|
||||
:model-value="selectedGroupId || 'all'"
|
||||
:model-value="selectedGroupId || '*'"
|
||||
:options="groupOptions"
|
||||
:disabled="loading"
|
||||
@update:model-value="onGroupFilter"
|
||||
|
||||
+248
-224
@@ -77,6 +77,8 @@ const eventSuggestions = computed(() => eventOptions(locale.value));
|
||||
|
||||
const {
|
||||
fragments,
|
||||
loading: fragmentsLoading,
|
||||
error: fragmentsLoadError,
|
||||
readyFor: fragmentsReadyFor,
|
||||
load: loadFragments,
|
||||
save: saveFragments,
|
||||
@@ -459,250 +461,272 @@ watch(
|
||||
</template>
|
||||
|
||||
<form ref="bodyEl" class="editor-body" @submit.prevent="save">
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionBasic") }}</h3>
|
||||
<div v-if="!isEdit" class="templates">
|
||||
<RcButton
|
||||
v-for="tmpl in ROUTE_TEMPLATES"
|
||||
:key="tmpl.id"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
:class="form.id === tmpl.id ? 'template-chip active' : 'template-chip'"
|
||||
@click="applyTemplate(tmpl)"
|
||||
>
|
||||
{{ t(tmpl.nameKey) }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.name") }}</label>
|
||||
<RcInput v-model="form.name" :placeholder="t('routeEditor.namePlaceholder')" required />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.id") }}</label>
|
||||
<RcInput v-model="form.id" placeholder="my-route" required />
|
||||
<div class="hint">{{ t("routeEditor.idHint") }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionOptions") }}</h3>
|
||||
<div class="option-list">
|
||||
<div class="option-row">
|
||||
<RcSwitch v-model="form.enabled" :label="t('routeEditor.enabled')" />
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.fallback" :label="t('routeEditor.fallback')" />
|
||||
<p class="option-hint">{{ t("routeEditor.fallbackHint") }}</p>
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.stop" :label="t('routeEditor.stop')" />
|
||||
<p class="option-hint">{{ t("routeEditor.stopHint") }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.discordRoles") }}</label>
|
||||
<RcTagInput
|
||||
v-model="discordRoles"
|
||||
separator=","
|
||||
:placeholder="t('routeEditor.discordRolesPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("routeEditor.discordRolesHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionFilters") }}</h3>
|
||||
<FilterNodeEditor :node="root" />
|
||||
<div v-if="filterError" class="err" data-save-error>{{ filterError }}</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.testMatch") }}</h3>
|
||||
<div class="field test-event">
|
||||
<FilterCombobox
|
||||
ref="testEventInput"
|
||||
:model-value="testEvent"
|
||||
:options="eventSuggestions"
|
||||
creatable
|
||||
:validate="validateEventName"
|
||||
:placeholder="t('routeEditor.testEvent')"
|
||||
:label="t('routeEditor.testEvent')"
|
||||
@update:model-value="testEvent = typeof $event === 'string' ? $event : ''"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<RcTextarea
|
||||
v-model="testPayload"
|
||||
class="test-payload"
|
||||
:rows="6"
|
||||
:placeholder="t('routeEditor.testPayloadPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<RcButton type="button" variant="ghost" :loading="testing" @click="runTest">
|
||||
{{ testing ? "…" : t("routeEditor.testRun") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div v-if="testResult" class="test-result" :class="{ ok: testResult.matched }">
|
||||
<span class="test-badge">
|
||||
{{
|
||||
testResult.matched ? t("routeEditor.testMatched") : t("routeEditor.testNotMatched")
|
||||
}}
|
||||
</span>
|
||||
<span class="test-explanation">{{ testResult.explanation }}</span>
|
||||
</div>
|
||||
<div v-if="testError" class="err">{{ testError }}</div>
|
||||
</section>
|
||||
|
||||
<section v-if="groupId" class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.fragments") }}</h3>
|
||||
<div class="fragments-presets">
|
||||
<span class="hint">{{ t("routeEditor.fragmentsPresets") }}</span>
|
||||
<div v-for="preset in FRAGMENT_PRESETS" :key="preset.id" class="fragment-row">
|
||||
<span class="fragment-name">{{ t(preset.nameKey) }}</span>
|
||||
<!-- Locked while saving: an edit made meanwhile would be lost when the
|
||||
save closes the editor. -->
|
||||
<fieldset :disabled="saving" class="contents">
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionBasic") }}</h3>
|
||||
<div v-if="!isEdit" class="templates">
|
||||
<RcButton
|
||||
v-for="tmpl in ROUTE_TEMPLATES"
|
||||
:key="tmpl.id"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="fragment-action"
|
||||
@click="insertNode(preset.node)"
|
||||
:class="form.id === tmpl.id ? 'template-chip active' : 'template-chip'"
|
||||
@click="applyTemplate(tmpl)"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsInsert") }}
|
||||
{{ t(tmpl.nameKey) }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="fragments-list">
|
||||
<div v-if="!fragments.length" class="hint">{{ t("routeEditor.fragmentsEmpty") }}</div>
|
||||
<div v-for="frag in fragments" :key="frag.id" class="fragment-row">
|
||||
<span class="fragment-name">{{ frag.name }}</span>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="fragment-action"
|
||||
@click="insertFragment(frag)"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsInsert") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:disabled="!fragmentsWritable"
|
||||
:title="t('routeEditor.fragmentsDelete')"
|
||||
:aria-label="t('routeEditor.fragmentsDelete')"
|
||||
@click="deleteFragment(frag)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
<div class="row2">
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.name") }}</label>
|
||||
<RcInput
|
||||
v-model="form.name"
|
||||
:placeholder="t('routeEditor.namePlaceholder')"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.id") }}</label>
|
||||
<RcInput v-model="form.id" placeholder="my-route" required />
|
||||
<div class="hint">{{ t("routeEditor.idHint") }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="fragment-save">
|
||||
<div class="fragment-save-input">
|
||||
<RcInput
|
||||
v-model="fragmentName"
|
||||
:placeholder="t('routeEditor.fragmentsNamePlaceholder')"
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionOptions") }}</h3>
|
||||
<div class="option-list">
|
||||
<div class="option-row">
|
||||
<RcSwitch v-model="form.enabled" :label="t('routeEditor.enabled')" />
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.fallback" :label="t('routeEditor.fallback')" />
|
||||
<p class="option-hint">{{ t("routeEditor.fallbackHint") }}</p>
|
||||
</div>
|
||||
<div class="option-row">
|
||||
<RcCheckbox v-model="form.stop" :label="t('routeEditor.stop')" />
|
||||
<p class="option-hint">{{ t("routeEditor.stopHint") }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>{{ t("routeEditor.discordRoles") }}</label>
|
||||
<RcTagInput
|
||||
v-model="discordRoles"
|
||||
separator=","
|
||||
:placeholder="t('routeEditor.discordRolesPlaceholder')"
|
||||
/>
|
||||
<div class="hint">{{ t("routeEditor.discordRolesHint") }}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionFilters") }}</h3>
|
||||
<FilterNodeEditor :node="root" />
|
||||
<div v-if="filterError" class="err" data-save-error>{{ filterError }}</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.testMatch") }}</h3>
|
||||
<div class="field test-event">
|
||||
<FilterCombobox
|
||||
ref="testEventInput"
|
||||
:model-value="testEvent"
|
||||
:options="eventSuggestions"
|
||||
creatable
|
||||
:validate="validateEventName"
|
||||
:placeholder="t('routeEditor.testEvent')"
|
||||
:label="t('routeEditor.testEvent')"
|
||||
@update:model-value="testEvent = typeof $event === 'string' ? $event : ''"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
class="shrink-0 whitespace-nowrap"
|
||||
:disabled="!fragmentsWritable"
|
||||
@click="saveAsFragment"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsSave") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div v-if="fragmentError" class="err">{{ fragmentError }}</div>
|
||||
</section>
|
||||
<div class="field">
|
||||
<RcTextarea
|
||||
v-model="testPayload"
|
||||
class="test-payload"
|
||||
:rows="6"
|
||||
:placeholder="t('routeEditor.testPayloadPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<RcButton type="button" variant="ghost" :loading="testing" @click="runTest">
|
||||
{{ testing ? "…" : t("routeEditor.testRun") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div v-if="testResult" class="test-result" :class="{ ok: testResult.matched }">
|
||||
<span class="test-badge">
|
||||
{{
|
||||
testResult.matched ? t("routeEditor.testMatched") : t("routeEditor.testNotMatched")
|
||||
}}
|
||||
</span>
|
||||
<span class="test-explanation">{{ testResult.explanation }}</span>
|
||||
</div>
|
||||
<div v-if="testError" class="err">{{ testError }}</div>
|
||||
</section>
|
||||
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionTargets") }}</h3>
|
||||
<div v-for="(tg, i) in form.targets" :key="i" class="target-card">
|
||||
<div class="target-card-head">
|
||||
<div class="target-platform">
|
||||
<RcSelect
|
||||
v-model="tg.platform"
|
||||
:options="[
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('routeEditor.platformFeishu'), value: 'feishu' },
|
||||
]"
|
||||
<section v-if="groupId" class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.fragments") }}</h3>
|
||||
<div class="fragments-presets">
|
||||
<span class="hint">{{ t("routeEditor.fragmentsPresets") }}</span>
|
||||
<div v-for="preset in FRAGMENT_PRESETS" :key="preset.id" class="fragment-row">
|
||||
<span class="fragment-name">{{ t(preset.nameKey) }}</span>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="fragment-action"
|
||||
@click="insertNode(preset.node)"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsInsert") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="fragments-list">
|
||||
<!-- A failed load is said so (never shown as "no fragments"). -->
|
||||
<div v-if="fragmentsLoadError" class="err">
|
||||
{{ t("routeEditor.fragmentsLoadFailed", { error: fragmentsLoadError }) }}
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
@click="groupId && loadFragments(groupId)"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsRetry") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<div v-else-if="!fragments.length && !fragmentsLoading" class="hint">
|
||||
{{ t("routeEditor.fragmentsEmpty") }}
|
||||
</div>
|
||||
<div v-for="frag in fragments" :key="frag.id" class="fragment-row">
|
||||
<span class="fragment-name">{{ frag.name }}</span>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="fragment-action"
|
||||
@click="insertFragment(frag)"
|
||||
>
|
||||
{{ t("routeEditor.fragmentsInsert") }}
|
||||
</RcButton>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:disabled="!fragmentsWritable"
|
||||
:title="t('routeEditor.fragmentsDelete')"
|
||||
:aria-label="t('routeEditor.fragmentsDelete')"
|
||||
@click="deleteFragment(frag)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="fragment-save">
|
||||
<div class="fragment-save-input">
|
||||
<RcInput
|
||||
v-model="fragmentName"
|
||||
:placeholder="t('routeEditor.fragmentsNamePlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeTarget')"
|
||||
:aria-label="t('routeEditor.removeTarget')"
|
||||
@click="removeTarget(tg)"
|
||||
class="shrink-0 whitespace-nowrap"
|
||||
:disabled="!fragmentsWritable"
|
||||
@click="saveAsFragment"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
{{ t("routeEditor.fragmentsSave") }}
|
||||
</RcButton>
|
||||
</div>
|
||||
<template v-if="tg.platform === 'discord'">
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-channel`">{{ t("routeEditor.channel") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-channel`"
|
||||
v-model="tg.channelId"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-thread`"
|
||||
>{{ t("routeEditor.thread") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.threadNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-thread`"
|
||||
v-model="tg.threadId"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-chat`">{{ t("routeEditor.chat") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-chat`"
|
||||
v-model="tg.chatId"
|
||||
:placeholder="
|
||||
tg.platform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="tg.platform === 'telegram'" class="target-field">
|
||||
<label :for="`target-${i}-topic`"
|
||||
>{{ t("routeEditor.topic") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.topicNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-topic`"
|
||||
v-model="tg.topicId"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addTarget">
|
||||
{{ t("routeEditor.addTarget") }}
|
||||
</RcButton>
|
||||
<div v-if="targetError" class="err" data-save-error>{{ targetError }}</div>
|
||||
</section>
|
||||
<div v-if="fragmentError" class="err">{{ fragmentError }}</div>
|
||||
</section>
|
||||
|
||||
<div v-if="formError" class="err" data-save-error>{{ formError }}</div>
|
||||
<section class="editor-section">
|
||||
<h3 class="editor-section-title">{{ t("routeEditor.sectionTargets") }}</h3>
|
||||
<div v-for="(tg, i) in form.targets" :key="i" class="target-card">
|
||||
<div class="target-card-head">
|
||||
<div class="target-platform">
|
||||
<RcSelect
|
||||
v-model="tg.platform"
|
||||
:options="[
|
||||
{ label: 'Discord', value: 'discord' },
|
||||
{ label: 'Telegram', value: 'telegram' },
|
||||
{ label: t('routeEditor.platformFeishu'), value: 'feishu' },
|
||||
]"
|
||||
/>
|
||||
</div>
|
||||
<RcButton
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
size="icon"
|
||||
class="h-8 w-8 text-muted hover:text-bad"
|
||||
:title="t('routeEditor.removeTarget')"
|
||||
:aria-label="t('routeEditor.removeTarget')"
|
||||
@click="removeTarget(tg)"
|
||||
>
|
||||
<Trash2 :size="15" />
|
||||
</RcButton>
|
||||
</div>
|
||||
<template v-if="tg.platform === 'discord'">
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-channel`">{{ t("routeEditor.channel") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-channel`"
|
||||
v-model="tg.channelId"
|
||||
:placeholder="t('routeEditor.channelPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-thread`"
|
||||
>{{ t("routeEditor.thread") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.threadNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-thread`"
|
||||
v-model="tg.threadId"
|
||||
:placeholder="t('routeEditor.threadPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="target-field">
|
||||
<label :for="`target-${i}-chat`">{{ t("routeEditor.chat") }}</label>
|
||||
<RcInput
|
||||
:id="`target-${i}-chat`"
|
||||
v-model="tg.chatId"
|
||||
:placeholder="
|
||||
tg.platform === 'telegram'
|
||||
? t('routeEditor.chatPlaceholder')
|
||||
: t('routeEditor.feishuChatPlaceholder')
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="tg.platform === 'telegram'" class="target-field">
|
||||
<label :for="`target-${i}-topic`"
|
||||
>{{ t("routeEditor.topic") }}
|
||||
<span class="lbl-note">{{ t("routeEditor.topicNote") }}</span></label
|
||||
>
|
||||
<RcInput
|
||||
:id="`target-${i}-topic`"
|
||||
v-model="tg.topicId"
|
||||
:placeholder="t('routeEditor.topicPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<RcButton type="button" variant="ghost" class="add-filter" @click="addTarget">
|
||||
{{ t("routeEditor.addTarget") }}
|
||||
</RcButton>
|
||||
<div v-if="targetError" class="err" data-save-error>{{ targetError }}</div>
|
||||
</section>
|
||||
|
||||
<div v-if="formError" class="err" data-save-error>{{ formError }}</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
|
||||
<template #footer>
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<label class="filter-label">{{ t("logs.filterGroup") }}</label>
|
||||
<RcSelect
|
||||
class="filter-select"
|
||||
:model-value="selectedGroupId || 'all'"
|
||||
:model-value="selectedGroupId || '*'"
|
||||
:options="groupOptions"
|
||||
:disabled="loading"
|
||||
@update:model-value="onGroupFilter"
|
||||
@@ -101,7 +101,7 @@ const detailLoading = ref(false);
|
||||
const detailError = ref("");
|
||||
|
||||
const groupOptions = computed(() => [
|
||||
{ label: t("logs.allGroups"), value: "all" },
|
||||
{ label: t("logs.allGroups"), value: "*" }, // "*" is no group id: one named "all" stays selectable
|
||||
...props.groups.map((g) => ({ label: g.name || g.id, value: g.id })),
|
||||
]);
|
||||
|
||||
@@ -142,28 +142,37 @@ function refresh(): void {
|
||||
}
|
||||
|
||||
function onGroupFilter(value: string): void {
|
||||
emit("update:selectedGroupId", value === "all" ? "" : value);
|
||||
emit("update:selectedGroupId", value === "*" ? "" : value);
|
||||
emit("filter");
|
||||
}
|
||||
|
||||
/** Bumped by every open/close: only the latest detail request may land. */
|
||||
let detailRequest = 0;
|
||||
|
||||
async function openDetail(l: SendRecord): Promise<void> {
|
||||
if (l.id == null) return;
|
||||
const mine = ++detailRequest;
|
||||
detailOpen.value = true;
|
||||
detail.value = null;
|
||||
detailError.value = "";
|
||||
detailLoading.value = true;
|
||||
try {
|
||||
detail.value = await loadById(l.id);
|
||||
const entry = await loadById(l.id);
|
||||
if (mine === detailRequest) detail.value = entry;
|
||||
} catch (err) {
|
||||
detailError.value = err instanceof Error ? err.message : String(err);
|
||||
if (mine === detailRequest) {
|
||||
detailError.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
} finally {
|
||||
detailLoading.value = false;
|
||||
if (mine === detailRequest) detailLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function closeDetail(): void {
|
||||
detailRequest++;
|
||||
detailOpen.value = false;
|
||||
detail.value = null;
|
||||
detailLoading.value = false;
|
||||
}
|
||||
|
||||
function onDetailOpenChange(open: boolean): void {
|
||||
|
||||
@@ -7,10 +7,26 @@ export function useAuthState() {
|
||||
return { needLogin };
|
||||
}
|
||||
|
||||
/** A failed admin API call, with its HTTP status (409: changed meanwhile). */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly status: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
}
|
||||
}
|
||||
|
||||
/** The write lost against a concurrent change: the shown data is stale. */
|
||||
export function isConflict(err: unknown): boolean {
|
||||
return err instanceof ApiError && err.status === 409;
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON fetch for same-origin admin API calls: sends credentials, treats 401
|
||||
* as "not logged in" (flips the shared flag and throws), and surfaces the
|
||||
* server's `{ error }` message on failure.
|
||||
* server's `{ error }` message (as an ApiError with the status) on failure.
|
||||
*/
|
||||
export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
@@ -32,11 +48,11 @@ export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T>
|
||||
});
|
||||
if (res.status === 401) {
|
||||
useAuthState().needLogin.value = true;
|
||||
throw new Error("unauthorized");
|
||||
throw new ApiError("unauthorized", 401);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
throw new Error(data.error ?? `HTTP ${res.status}`);
|
||||
throw new ApiError(data.error ?? `HTTP ${res.status}`, res.status);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
@@ -10,6 +10,8 @@ export function useFragmentsApi() {
|
||||
const shownGroupId = ref<string | null>(null);
|
||||
/** Group whose fragments were last loaded (or saved) successfully. */
|
||||
const loadedGroupId = ref<string | null>(null);
|
||||
/** Server revision of the shown fragments, sent back to detect concurrent edits. */
|
||||
let revision: string | undefined;
|
||||
// Bumped by every load/save, so only the latest request may land.
|
||||
let request = 0;
|
||||
|
||||
@@ -33,17 +35,19 @@ export function useFragmentsApi() {
|
||||
if (shownGroupId.value !== groupId) {
|
||||
fragments.value = [];
|
||||
loadedGroupId.value = null;
|
||||
revision = undefined;
|
||||
}
|
||||
shownGroupId.value = groupId;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
try {
|
||||
const data = await apiFetch<{ fragments?: NamedFragment[] }>(
|
||||
const data = await apiFetch<{ fragments?: NamedFragment[]; revision?: string }>(
|
||||
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
||||
);
|
||||
if (mine !== request) return;
|
||||
fragments.value = data.fragments ?? [];
|
||||
revision = data.revision;
|
||||
loadedGroupId.value = groupId;
|
||||
} catch (err) {
|
||||
if (mine === request && !needLogin.value)
|
||||
@@ -55,11 +59,25 @@ export function useFragmentsApi() {
|
||||
|
||||
async function save(groupId: string, next: NamedFragment[]): Promise<void> {
|
||||
saving.value = true;
|
||||
let data: { fragments?: NamedFragment[]; revision?: string };
|
||||
try {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ fragments: next }),
|
||||
});
|
||||
data = await apiFetch<{ fragments?: NamedFragment[]; revision?: string }>(
|
||||
`/admin/api/groups/${encodeURIComponent(groupId)}/fragments`,
|
||||
{
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
fragments: next,
|
||||
revision: loadedGroupId.value === groupId ? revision : undefined,
|
||||
}),
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
// Changed elsewhere meanwhile: reload so the next write builds on it.
|
||||
if (isConflict(err) && shownGroupId.value === groupId) {
|
||||
saving.value = false;
|
||||
void load(groupId);
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
@@ -67,7 +85,8 @@ export function useFragmentsApi() {
|
||||
request++;
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
fragments.value = next;
|
||||
fragments.value = data.fragments ?? next;
|
||||
revision = data.revision;
|
||||
loadedGroupId.value = groupId;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,12 @@ export function useGroupRoutesApi() {
|
||||
const groupId = ref<string | null>(null);
|
||||
/** Group whose routes were last loaded (or saved) successfully. */
|
||||
const loadedId = ref<string | null>(null);
|
||||
/**
|
||||
* Server revision of the shown routes. Every save sends it back, so a save
|
||||
* built on a list someone else has changed meanwhile is refused (409)
|
||||
* instead of overwriting their change.
|
||||
*/
|
||||
let revision: string | undefined;
|
||||
// Bumped by every load/clear, so only the latest request may land.
|
||||
let request = 0;
|
||||
|
||||
@@ -24,17 +30,19 @@ export function useGroupRoutesApi() {
|
||||
if (groupId.value !== id) {
|
||||
routes.value = [];
|
||||
loadedId.value = null;
|
||||
revision = undefined;
|
||||
}
|
||||
groupId.value = id;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
needLogin.value = false;
|
||||
try {
|
||||
const data = await apiFetch<{ routes?: Route[] }>(
|
||||
const data = await apiFetch<{ routes?: Route[]; revision?: string }>(
|
||||
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
||||
);
|
||||
if (mine !== request) return;
|
||||
routes.value = data.routes ?? [];
|
||||
revision = data.revision;
|
||||
loadedId.value = id;
|
||||
} catch (err) {
|
||||
if (mine === request && !needLogin.value)
|
||||
@@ -50,15 +58,29 @@ export function useGroupRoutesApi() {
|
||||
groupId.value = null;
|
||||
loadedId.value = null;
|
||||
routes.value = [];
|
||||
revision = undefined;
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
}
|
||||
|
||||
async function save(id: string, next: Route[]): Promise<void> {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(id)}/routes`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ routes: next }),
|
||||
});
|
||||
let data: { routes?: Route[]; revision?: string };
|
||||
try {
|
||||
data = await apiFetch<{ routes?: Route[]; revision?: string }>(
|
||||
`/admin/api/groups/${encodeURIComponent(id)}/routes`,
|
||||
{
|
||||
method: "PUT",
|
||||
body: JSON.stringify({
|
||||
routes: next,
|
||||
revision: groupId.value === id ? revision : undefined,
|
||||
}),
|
||||
},
|
||||
);
|
||||
} catch (err) {
|
||||
// Someone changed the routes meanwhile: show theirs, nothing was written.
|
||||
if (isConflict(err) && groupId.value === id) void load(id);
|
||||
throw err;
|
||||
}
|
||||
// The page may have moved on to another group while the request ran.
|
||||
if (groupId.value !== id) return;
|
||||
// What was just written is the newest state: a load of this group that
|
||||
@@ -66,7 +88,8 @@ export function useGroupRoutesApi() {
|
||||
request++;
|
||||
loading.value = false;
|
||||
error.value = "";
|
||||
routes.value = next;
|
||||
routes.value = data.routes ?? next;
|
||||
revision = data.revision;
|
||||
loadedId.value = id;
|
||||
}
|
||||
|
||||
|
||||
@@ -52,22 +52,87 @@ export function useGroupsApi() {
|
||||
}
|
||||
}
|
||||
|
||||
async function save(next: Group[]): Promise<void> {
|
||||
await apiFetch("/admin/api/groups", {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ groups: next }),
|
||||
});
|
||||
/** Apply a write's result locally; a load that started earlier must not land. */
|
||||
function settle(next: Group[]): void {
|
||||
request++;
|
||||
loading.value = false;
|
||||
groups.value = next;
|
||||
}
|
||||
|
||||
/** Rename a group; routes, webhook secret and invites follow automatically. */
|
||||
async function rename(oldId: string, newId: string): Promise<void> {
|
||||
await apiFetch(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ newId }),
|
||||
/** Reload after a refused write (409): someone changed the group meanwhile. */
|
||||
async function guard<T>(write: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await write();
|
||||
} catch (err) {
|
||||
if (isConflict(err)) void load();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update one group. Its `revision` (from the last load) travels along, so an
|
||||
* edit made from a stale copy is refused instead of reverting newer changes.
|
||||
*/
|
||||
async function update(group: Group): Promise<Group> {
|
||||
const data = await guard(() =>
|
||||
apiFetch<{ group: Group }>(`/admin/api/groups/${encodeURIComponent(group.id)}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ group }),
|
||||
}),
|
||||
);
|
||||
settle(groups.value.map((g) => (g.id === data.group.id ? data.group : g)));
|
||||
return data.group;
|
||||
}
|
||||
|
||||
/** Create one group (super admins). */
|
||||
async function create(group: Group): Promise<Group> {
|
||||
const data = await apiFetch<{ group: Group }>("/admin/api/groups", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ group }),
|
||||
});
|
||||
settle([...groups.value.filter((g) => g.id !== data.group.id), data.group]);
|
||||
return data.group;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete one group with its routes. `revision` (the group) and
|
||||
* `routesRevision` (its routes) are what the deletion was confirmed on: if
|
||||
* either changed meanwhile, the server refuses (409) instead of deleting
|
||||
* something nobody saw.
|
||||
*/
|
||||
async function remove(
|
||||
id: string,
|
||||
revision?: string,
|
||||
routesRevision?: string,
|
||||
version?: number | null,
|
||||
): Promise<void> {
|
||||
const query = new URLSearchParams();
|
||||
if (revision) query.set("revision", revision);
|
||||
if (routesRevision) query.set("routesRevision", routesRevision);
|
||||
if (version != null) query.set("version", String(version));
|
||||
const qs = query.toString();
|
||||
await guard(() =>
|
||||
apiFetch(`/admin/api/groups/${encodeURIComponent(id)}${qs ? `?${qs}` : ""}`, {
|
||||
method: "DELETE",
|
||||
}),
|
||||
);
|
||||
settle(groups.value.filter((g) => g.id !== id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Rename a group; routes, webhook secret and invites follow automatically.
|
||||
* `revision` is the group's revision the rename was decided on.
|
||||
*/
|
||||
async function rename(oldId: string, newId: string, revision?: string): Promise<Group> {
|
||||
const data = await guard(() =>
|
||||
apiFetch<{ group: Group }>(`/admin/api/groups/${encodeURIComponent(oldId)}/rename`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify({ newId, revision }),
|
||||
}),
|
||||
);
|
||||
// Show the group under its new id right away (a later step may still fail).
|
||||
settle(groups.value.map((g) => (g.id === oldId ? data.group : g)));
|
||||
return data.group;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -82,7 +147,9 @@ export function useGroupsApi() {
|
||||
needLogin,
|
||||
error,
|
||||
load,
|
||||
save,
|
||||
update,
|
||||
create,
|
||||
remove,
|
||||
rename,
|
||||
};
|
||||
}
|
||||
@@ -25,6 +25,9 @@ const en: Dict = {
|
||||
"overview.recent": "Recent deliveries",
|
||||
"overview.viewAll": "View all",
|
||||
"overview.refreshed": "Refreshed",
|
||||
"overview.refreshFailed": "Refresh failed",
|
||||
"overview.loadFailed":
|
||||
"Some data could not be loaded; what is shown may be incomplete or out of date: {error}",
|
||||
"overview.thRoute": "Route",
|
||||
"overview.thGroup": "Group",
|
||||
"overview.thEvents": "Events",
|
||||
@@ -104,6 +107,7 @@ const en: Dict = {
|
||||
"members.copied": "Copied!",
|
||||
"members.revoke": "Revoke",
|
||||
"members.noInvites": "No pending invites.",
|
||||
"members.invitesFailed": "Could not load invites: {error}",
|
||||
"members.errSelfOwner": "You must remain an owner of this group.",
|
||||
"members.errOwner": "A group needs at least one owner.",
|
||||
"members.errLastOwner": "Cannot remove the last owner.",
|
||||
@@ -111,6 +115,8 @@ const en: Dict = {
|
||||
"members.inviteBad": "This invite is invalid or expired.",
|
||||
"install.ok":
|
||||
"GitHub App installation registered — the group has been created and bound to this installation.",
|
||||
"install.forbidden":
|
||||
"Your GitHub account cannot manage this installation, so it was not bound. Sign in with an account that administers it.",
|
||||
"webhook.title": "Webhook endpoint",
|
||||
"webhook.note": "(per-group URL + secret)",
|
||||
"webhook.empty": "Not configured. Generate a secret to enable the group's own webhook endpoint.",
|
||||
@@ -289,6 +295,8 @@ const en: Dict = {
|
||||
"routeEditor.fragments": "Fragments",
|
||||
"routeEditor.fragmentsPresets": "Presets",
|
||||
"routeEditor.fragmentsEmpty": "No fragments yet",
|
||||
"routeEditor.fragmentsLoadFailed": "Fragments could not be loaded: {error}",
|
||||
"routeEditor.fragmentsRetry": "Retry",
|
||||
"routeEditor.fragmentsInsert": "Insert",
|
||||
"routeEditor.fragmentsDelete": "Delete",
|
||||
"routeEditor.fragmentsSave": "Save as fragment",
|
||||
@@ -428,6 +436,8 @@ const en: Dict = {
|
||||
"toast.groupSaved": "Groups saved",
|
||||
"toast.groupDeleted": "Group deleted",
|
||||
"toast.routeIdExists": "Route ID already exists",
|
||||
"toast.routeChanged":
|
||||
"This route was changed by someone else since you opened it. Close the editor and open it again.",
|
||||
"toast.groupIdExists": "Group ID already exists",
|
||||
"toast.saveFailed": "Save failed: {msg}",
|
||||
"toast.deleteFailed": "Delete failed: {msg}",
|
||||
@@ -473,6 +483,8 @@ const zh: Dict = {
|
||||
"overview.recent": "最近投递",
|
||||
"overview.viewAll": "查看全部",
|
||||
"overview.refreshed": "已刷新",
|
||||
"overview.refreshFailed": "刷新失败",
|
||||
"overview.loadFailed": "部分数据加载失败,当前显示的内容可能不完整或已过期:{error}",
|
||||
"overview.thRoute": "路由",
|
||||
"overview.thGroup": "分组",
|
||||
"overview.thEvents": "事件",
|
||||
@@ -552,12 +564,14 @@ const zh: Dict = {
|
||||
"members.copied": "已复制!",
|
||||
"members.revoke": "撤销",
|
||||
"members.noInvites": "暂无待接受的邀请。",
|
||||
"members.invitesFailed": "邀请列表加载失败:{error}",
|
||||
"members.errSelfOwner": "你必须保留本组的 owner 身份。",
|
||||
"members.errOwner": "分组至少需要一位 owner。",
|
||||
"members.errLastOwner": "不能移除最后一位 owner。",
|
||||
"members.inviteOk": "邀请已接受 —— 欢迎!",
|
||||
"members.inviteBad": "该邀请无效或已过期。",
|
||||
"install.ok": "GitHub App 安装已注册 —— 分组已创建并绑定到该安装。",
|
||||
"install.forbidden": "你的 GitHub 账号无权管理该安装,未进行绑定。请使用该安装的管理员账号登录。",
|
||||
"webhook.title": "Webhook 入口",
|
||||
"webhook.note": "(分组独立的 URL + secret)",
|
||||
"webhook.empty": "未配置。生成 secret 即可启用该分组的独立 webhook 入口。",
|
||||
@@ -733,6 +747,8 @@ const zh: Dict = {
|
||||
"routeEditor.fragments": "过滤器片段",
|
||||
"routeEditor.fragmentsPresets": "预设",
|
||||
"routeEditor.fragmentsEmpty": "暂无片段",
|
||||
"routeEditor.fragmentsLoadFailed": "片段加载失败:{error}",
|
||||
"routeEditor.fragmentsRetry": "重试",
|
||||
"routeEditor.fragmentsInsert": "插入",
|
||||
"routeEditor.fragmentsDelete": "删除",
|
||||
"routeEditor.fragmentsSave": "存为片段",
|
||||
@@ -870,6 +886,7 @@ const zh: Dict = {
|
||||
"toast.groupSaved": "分组已保存",
|
||||
"toast.groupDeleted": "分组已删除",
|
||||
"toast.routeIdExists": "路由 ID 已存在",
|
||||
"toast.routeChanged": "该路由在你打开后已被他人修改。请关闭编辑器后重新打开。",
|
||||
"toast.groupIdExists": "分组 ID 已存在",
|
||||
"toast.saveFailed": "保存失败:{msg}",
|
||||
"toast.deleteFailed": "删除失败:{msg}",
|
||||
|
||||
@@ -21,6 +21,7 @@ export function useInvitesApi() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Throws when the list cannot be read: never shown as "no invites". */
|
||||
async function list(groupId: string): Promise<GroupInvite[]> {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
@@ -31,7 +32,7 @@ export function useInvitesApi() {
|
||||
return data.invites ?? [];
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
return [];
|
||||
throw err;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
@@ -85,6 +85,12 @@ export interface Group {
|
||||
owners?: string[];
|
||||
providers?: ("github" | "gitea" | "gitlab")[];
|
||||
installationId?: number;
|
||||
/** Self-service group: only its own webhook ingress dispatches to it (super-only). */
|
||||
isolated?: boolean;
|
||||
/** Immutable server-assigned group identity (kept across renames). */
|
||||
instance?: string;
|
||||
/** Server revision of the stored group; sent back on update to detect stale edits. */
|
||||
revision?: string;
|
||||
emoji?: boolean;
|
||||
forgeSources?: ForgeSource[];
|
||||
lang?: string;
|
||||
|
||||
Reference in new issue
Block a user