Manage server tags in Settings: pre-add tags, recolour, rename, delete
New Settings > Tags tab (admin) listing every tag -- ones servers use and ones added ahead of time -- with how many servers carry each: - Add a tag before anything uses it, optionally with a colour. Such tags are offered as one-click "Add:" chips (and datalist suggestions) when tagging a server, so the same word gets spelled the same way everywhere. - Give any tag a colour of your choosing, in use or not, or reset it to the automatic one. Changes are drafted with Save/Cancel rather than saved as the picker drags. Colours show on the Servers page, its tag filter bar, the detail page and the editor, and update everywhere without a reload through one shared cached colour map. - Rename a tag; every server that has it is rewritten. Renaming to a name that already exists merges the two after a confirmation naming what will happen; the target keeps its own colour unless it had none, and a server carrying both ends up with one. - Delete a tag, which removes it from every server that has it, with a confirmation stating how many. Tags still live on the servers (servers.tags); a new tag_definitions table holds only what a server can't: existence before use, and a colour. A defined tag stays listed until an admin deletes it, even with no servers. Rename and delete change the servers and the catalogue in one transaction so they can't disagree. Only servers that actually carry the tag are rewritten and counted -- an earlier draft also counted servers whose tags merely weren't in sorted order, which the tests caught. Reading the list and colours is open to everyone signed in (needed to draw tags anywhere); changing the catalogue is admin-only, while tagging a server stays an operator action. Names go through the same normalisation as before, colours must be #rrggbb, and every change is audit-logged. New table tag_definitions (migration 0013). Verified with 44 backend checks (list/counts, roles, create/adopt/ duplicate/rejects, colour set/reset, rename incl. defined, undefined and unused tags, merge colour rules and both-sides servers, delete, audit, and that normal tagging still works afterwards) and in a browser against the real routers: add with colour, set/reset a colour and see it change on the Servers page live, merge with confirmation, delete, and the error path. Not clicked through: the quick-add chips inside the tag editor on a server's detail page (typechecked; same colour code as the rest). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
72f8c85406
commit
ae64cb345c
15 files changed
+2136
-25
No files matched your search
@@ -0,0 +1,8 @@
|
||||
CREATE TABLE `tag_definitions` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`name` text NOT NULL,
|
||||
`color` text,
|
||||
`created_at` text DEFAULT (current_timestamp) NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX `tag_definitions_name_unique` ON `tag_definitions` (`name`);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -92,6 +92,13 @@
|
||||
"when": 1790388232273,
|
||||
"tag": "0012_cool_harry_osborn",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 13,
|
||||
"version": "6",
|
||||
"when": 1790449897833,
|
||||
"tag": "0013_sturdy_bloodstorm",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -363,3 +363,17 @@ export const consistencyIgnores = sqliteTable("consistency_ignores", {
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
|
||||
// ─── Tag catalogue ──────────────────────────────────────────────────────────
|
||||
|
||||
// Tags themselves live on the servers that carry them (servers.tags). A row here adds two things a server can't: a tag
|
||||
// that exists before anything uses it (so it's offered when tagging), and a chosen colour. A defined tag is kept until an
|
||||
// admin deletes it, even with no server using it; a tag with no row is simply one that's in use and has an automatic colour.
|
||||
export const tagDefinitions = sqliteTable("tag_definitions", {
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
name: text("name").notNull().unique(), // normalised, as in services/serverTags
|
||||
color: text("color"), // "#rrggbb"; null = automatic
|
||||
createdAt: text("created_at")
|
||||
.notNull()
|
||||
.default(sql`(current_timestamp)`),
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import { maintenanceRouter } from "./routes/maintenance.js";
|
||||
import { domainsRouter } from "./routes/domains.js";
|
||||
import { consistencyRouter } from "./routes/consistency.js";
|
||||
import { privacyRouter } from "./routes/privacy.js";
|
||||
import { tagsRouter } from "./routes/tags.js";
|
||||
import { initSecretExpiryScheduler } from "./services/secretExpiryScheduler.js";
|
||||
import { initTailscaleKeyExpiryScheduler } from "./services/tailscaleKeyExpiryScheduler.js";
|
||||
import { initLogRetentionScheduler } from "./services/logRetentionScheduler.js";
|
||||
@@ -98,6 +99,7 @@ app.use("/api/maintenance", maintenanceRouter);
|
||||
app.use("/api/domains", domainsRouter);
|
||||
app.use("/api/consistency", consistencyRouter);
|
||||
app.use("/api/privacy", privacyRouter);
|
||||
app.use("/api/tags", tagsRouter);
|
||||
|
||||
if (existsSync(webDist)) {
|
||||
app.use(express.static(webDist));
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { servers, tagDefinitions } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { InvalidTagError, normalizeColor, normalizeTag, parseTags } from "../services/serverTags.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const tagsRouter = Router();
|
||||
tagsRouter.use(requireAuth);
|
||||
|
||||
interface TagEntry {
|
||||
name: string;
|
||||
/** "#rrggbb", or null for the automatic colour. */
|
||||
color: string | null;
|
||||
/** Servers currently carrying it. */
|
||||
count: number;
|
||||
}
|
||||
|
||||
async function listTags(): Promise<TagEntry[]> {
|
||||
const [defs, rows] = await Promise.all([db.select().from(tagDefinitions), db.select({ tags: servers.tags }).from(servers)]);
|
||||
const counts = new Map<string, number>();
|
||||
for (const r of rows) for (const t of new Set(parseTags(r.tags))) counts.set(t, (counts.get(t) ?? 0) + 1);
|
||||
const defined = new Map(defs.map((d) => [d.name, d.color]));
|
||||
const names = new Set([...defined.keys(), ...counts.keys()]);
|
||||
return [...names]
|
||||
.map((name) => ({ name, color: defined.get(name) ?? null, count: counts.get(name) ?? 0 }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name, "sv"));
|
||||
}
|
||||
|
||||
// Read by everyone signed in: colours are needed to draw tags anywhere, and operators need the list to offer suggestions.
|
||||
tagsRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
res.json({ tags: await listTags() });
|
||||
}));
|
||||
|
||||
// Changing the catalogue is a Settings matter, so admin-only — tagging a server (operator) is separate.
|
||||
const nameField = z.string().min(1).max(100);
|
||||
const colorField = z.string().max(20);
|
||||
|
||||
/** Turns the shared validation failures (bad name, bad colour) into a 400 with a message worth showing. */
|
||||
function handleInvalid(err: unknown, res: import("express").Response) {
|
||||
if (err instanceof InvalidTagError) return res.status(400).json({ error: "invalid_tag", message: err.message });
|
||||
throw err;
|
||||
}
|
||||
|
||||
tagsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = z.object({ name: nameField, color: colorField.nullish() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give the tag a name.", details: parsed.error.flatten() });
|
||||
try {
|
||||
const name = normalizeTag(parsed.data.name);
|
||||
const color = parsed.data.color ? normalizeColor(parsed.data.color) : null;
|
||||
const [existing] = await db.select().from(tagDefinitions).where(eq(tagDefinitions.name, name)).limit(1);
|
||||
if (existing) return res.status(409).json({ error: "exists", message: `"${name}" already exists.` });
|
||||
await db.insert(tagDefinitions).values({ name, color });
|
||||
await recordAudit({ actor: req.currentUser!, category: "tag", action: "create", targetType: "tag", detail: { name, color } });
|
||||
res.status(201).json({ tags: await listTags() });
|
||||
} catch (err) {
|
||||
return handleInvalid(err, res);
|
||||
}
|
||||
}));
|
||||
|
||||
tagsRouter.put("/color", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = z.object({ name: nameField, color: colorField.nullable() }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Choose a tag and a colour.", details: parsed.error.flatten() });
|
||||
try {
|
||||
const name = normalizeTag(parsed.data.name);
|
||||
const color = parsed.data.color === null ? null : normalizeColor(parsed.data.color);
|
||||
const known = (await listTags()).some((t) => t.name === name);
|
||||
if (!known) return res.status(404).json({ error: "not_found", message: `There's no tag "${name}".` });
|
||||
await db
|
||||
.insert(tagDefinitions)
|
||||
.values({ name, color })
|
||||
.onConflictDoUpdate({ target: tagDefinitions.name, set: { color } });
|
||||
await recordAudit({ actor: req.currentUser!, category: "tag", action: "set_color", targetType: "tag", detail: { name, color } });
|
||||
res.json({ tags: await listTags() });
|
||||
} catch (err) {
|
||||
return handleInvalid(err, res);
|
||||
}
|
||||
}));
|
||||
|
||||
/** Rewrites every server's tag list through `change`, saving only the ones that differ. Returns how many servers changed. */
|
||||
async function rewriteServerTags(tx: Pick<typeof db, "select" | "update">, change: (tags: string[]) => string[]): Promise<number> {
|
||||
let changed = 0;
|
||||
for (const row of await tx.select({ id: servers.id, tags: servers.tags }).from(servers)) {
|
||||
const before = parseTags(row.tags);
|
||||
if (before.length === 0) continue;
|
||||
const sorted = (tags: string[]) => [...new Set(tags)].sort((a, b) => a.localeCompare(b, "sv"));
|
||||
const after = sorted(change(before));
|
||||
// Compare against the same tags in the same order, so a server is only rewritten (and counted) when the change really touched it.
|
||||
if (JSON.stringify(after) === JSON.stringify(sorted(before))) continue;
|
||||
await tx.update(servers).set({ tags: after.length > 0 ? JSON.stringify(after) : null }).where(eq(servers.id, row.id));
|
||||
changed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
tagsRouter.post("/rename", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = z.object({ from: nameField, to: nameField }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Give the current and the new name.", details: parsed.error.flatten() });
|
||||
try {
|
||||
const from = normalizeTag(parsed.data.from);
|
||||
const to = normalizeTag(parsed.data.to);
|
||||
const all = await listTags();
|
||||
if (!all.some((t) => t.name === from)) return res.status(404).json({ error: "not_found", message: `There's no tag "${from}".` });
|
||||
if (from === to) return res.status(400).json({ error: "same_name", message: "That's already its name." });
|
||||
const merged = all.some((t) => t.name === to);
|
||||
|
||||
// One transaction: the servers and the catalogue must never disagree about what a tag is called.
|
||||
const updatedServers = await db.transaction(async (tx) => {
|
||||
const n = await rewriteServerTags(tx, (tags) => tags.map((t) => (t === from ? to : t)));
|
||||
const [fromDef] = await tx.select().from(tagDefinitions).where(eq(tagDefinitions.name, from)).limit(1);
|
||||
const [toDef] = await tx.select().from(tagDefinitions).where(eq(tagDefinitions.name, to)).limit(1);
|
||||
if (fromDef && toDef) {
|
||||
// Merging into a tag that already exists: it keeps its own colour, unless it never had one.
|
||||
if (!toDef.color && fromDef.color) await tx.update(tagDefinitions).set({ color: fromDef.color }).where(eq(tagDefinitions.id, toDef.id));
|
||||
await tx.delete(tagDefinitions).where(eq(tagDefinitions.id, fromDef.id));
|
||||
} else if (fromDef) {
|
||||
await tx.update(tagDefinitions).set({ name: to }).where(eq(tagDefinitions.id, fromDef.id));
|
||||
}
|
||||
return n;
|
||||
});
|
||||
|
||||
await recordAudit({ actor: req.currentUser!, category: "tag", action: merged ? "merge" : "rename", targetType: "tag", detail: { from, to, servers: updatedServers } });
|
||||
res.json({ tags: await listTags(), updatedServers, merged });
|
||||
} catch (err) {
|
||||
return handleInvalid(err, res);
|
||||
}
|
||||
}));
|
||||
|
||||
tagsRouter.post("/delete", requireRole("admin"), asyncHandler(async (req, res) => {
|
||||
const parsed = z.object({ name: nameField }).safeParse(req.body);
|
||||
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Choose a tag.", details: parsed.error.flatten() });
|
||||
try {
|
||||
const name = normalizeTag(parsed.data.name);
|
||||
if (!(await listTags()).some((t) => t.name === name)) return res.status(404).json({ error: "not_found", message: `There's no tag "${name}".` });
|
||||
const updatedServers = await db.transaction(async (tx) => {
|
||||
const n = await rewriteServerTags(tx, (tags) => tags.filter((t) => t !== name));
|
||||
await tx.delete(tagDefinitions).where(eq(tagDefinitions.name, name));
|
||||
return n;
|
||||
});
|
||||
await recordAudit({ actor: req.currentUser!, category: "tag", action: "delete", targetType: "tag", detail: { name, servers: updatedServers } });
|
||||
res.json({ tags: await listTags(), updatedServers });
|
||||
} catch (err) {
|
||||
return handleInvalid(err, res);
|
||||
}
|
||||
}));
|
||||
@@ -36,3 +36,17 @@ export function parseTags(stored: string | null | undefined): string[] {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** One tag through the same rules as normalizeTags; throws InvalidTagError (also for an empty one). */
|
||||
export function normalizeTag(input: string): string {
|
||||
const [tag] = normalizeTags([input]);
|
||||
if (!tag) throw new InvalidTagError("A tag needs a name.");
|
||||
return tag;
|
||||
}
|
||||
|
||||
/** "#rrggbb" in lowercase, or throws InvalidTagError. (Reusing the tag error keeps the route's one catch.) */
|
||||
export function normalizeColor(input: string): string {
|
||||
const c = input.trim().toLowerCase();
|
||||
if (!/^#[0-9a-f]{6}$/.test(c)) throw new InvalidTagError(`"${input.trim()}" isn't a colour — use the form #3b82f6.`);
|
||||
return c;
|
||||
}
|
||||
Reference in new issue
Block a user