Public: anyone can read this; the crew can change it.

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

/admin lists every moderation action with who and when, and offers Unmute and Unban beside each #203

Parked opened this
Closed without merging

smith/arm:smith/196-admin-lists-every-moderation-action-with → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +149 −39
Software/so101/src/admin-page.ts +27 −2
@@ -5,7 +5,7 @@
55 */
66
77 import { createHash } from "node:crypto";
8 import { ANNOUNCEMENT_CHARS, type AdminSettings, type LogEntry } from "./admin.ts";
8 import { ANNOUNCEMENT_CHARS, type AdminSettings, type LogEntry, type ModerationAction } from "./admin.ts";
99 import type { Person, Who } from "./identity.ts";
1010 import type { Snapshot } from "./turns.ts";
1111
@@ -53,7 +53,7 @@ time { color: var(--dim); font-variant-numeric: tabular-nums; }
5353 export const ADMIN_CSP = `default-src 'none'; style-src 'sha256-${createHash("sha256").update(STYLE).digest("base64")}'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
5454
5555 /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */
56 export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control." } as const;
56 export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control.", unmuted: "Unmuted.", unbanned: "Unbanned." } as const;
5757 export type Done = keyof typeof DONE;
5858
5959 export interface AdminPage {
@@ -63,6 +63,9 @@ export interface AdminPage {
6363 settings: AdminSettings;
6464 snapshot: Snapshot;
6565 log: readonly LogEntry[];
66 /** Ids muted or banned right now: only those get a button to lift it. */
67 muted?: ReadonlySet<string>;
68 banned?: ReadonlySet<string>;
6669 done?: Done | null;
6770 error?: string | null;
6871 }
@@ -101,6 +104,27 @@ const field = (name: keyof AdminSettings, label: string, hint: string, value: nu
101104 const action = (name: string, text: string, cls = "", disabled = false) =>
102105 `<form method="post" action="/admin"><input type="hidden" name="action" value="${name}"><button class="${cls}"${disabled ? " disabled" : ""}>${text}</button></form>`;
103106
107 const VERB: Record<ModerationAction["kind"], string> = { removed: "removed a line by", muted: "muted", unmuted: "unmuted", banned: "banned", unbanned: "unbanned" };
108
109 /** The moderation entries of the log, newest first, each with a button to lift a mute or ban that is still live. */
110 function moderation(log: readonly LogEntry[], muted: ReadonlySet<string>, banned: ReadonlySet<string>): string {
111 const seen = new Set<string>();
112 const items = [...log].reverse().filter((e) => e.action).map((e) => {
113 const a = e.action!;
114 // only the newest entry about a person offers the button, and only while the mute or ban still stands
115 const key = `${a.kind}:${a.id}`;
116 const first = !seen.has(key);
117 seen.add(key);
118 const live = first && ((a.kind === "muted" && muted.has(a.id)) || (a.kind === "banned" && banned.has(a.id)));
119 const lift = live
120 ? ` <form method="post" action="/admin" class="inline"><input type="hidden" name="action" value="${a.kind === "muted" ? "unmute" : "unban"}"><input type="hidden" name="id" value="${esc(a.id)}"><button aria-label="${a.kind === "muted" ? "Unmute" : "Unban"} ${esc(a.name)}">${a.kind === "muted" ? "Unmute" : "Unban"}</button></form>`
121 : "";
122 const length = a.kind === "muted" ? " (until unmuted)" : "";
123 return `<li>${time(e.at)}<span><b>${esc(e.by.name)}</b> ${VERB[a.kind]} ${esc(a.name)}${length}${lift}</span></li>`;
124 });
125 return items.length ? `<ol>${items.join("")}</ol>` : `<p class="empty">Nothing yet.</p>`;
126 }
127
104128 export function renderAdmin(p: AdminPage): string {
105129 const s = p.settings;
106130 const d = p.snapshot.driver;
@@ -139,6 +163,7 @@ ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0
139163 ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>` : ""}
140164 </form>
141165 </section>
166 <section aria-labelledby="mod"><h2 id="mod">Moderation</h2>${moderation(p.log, p.muted ?? new Set(), p.banned ?? new Set())}</section>
142167 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
143168 <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`,
144169 );
Software/so101/src/admin-relay.test.ts +33
@@ -123,3 +123,36 @@ test("/status names who is driving: null, then alice, then the owner after a tak
123123 sim.stop(true);
124124 }
125125 });
126
127 test("/admin lists moderation actions newest first, escaped; a moderator lifts a ban and a mute; a plain user is refused", async () => {
128 const base = await boot();
129 const owner = as("trevato", "admin");
130 const bob = as("bob", "user");
131 const trevato = { id: "id-trevato", name: "trevato", owner: true };
132 await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" }));
133 lobby!.turns.join({ id: "id-evil", name: "<img src=x>", owner: false });
134 lobby!.ban(trevato, "id-evil");
135 lobby!.setMute(trevato, "id-quiet", true);
136
137 const html = await (await fetch(`${base}/admin`, { headers: bob })).text();
138 expect(html).not.toContain("<img src=x>");
139 expect(html).toContain("banned &#60;img src=x&#62;");
140 expect(html.indexOf("muted id-quiet")).toBeLessThan(html.indexOf("banned &#60;img"));
141 expect(html).toContain("(until unmuted)");
142 expect(html).toContain('aria-label="Unban &#60;img src=x&#62;"');
143
144 expect((await fetch(`${base}/admin`, form(as("eve", "user"), { action: "unban", id: "id-evil" }))).status).toBe(404);
145 expect(lobby!.accounts.bans().some((b) => b.id === "id-evil")).toBe(true);
146
147 expect((await fetch(`${base}/admin`, form(bob, { action: "unban", id: "id-evil" }))).status).toBe(303);
148 expect((await fetch(`${base}/admin`, form(bob, { action: "unmute", id: "id-quiet" }))).status).toBe(303);
149 expect(lobby!.accounts.bans()).toEqual([]);
150 expect(lobby!.chat.muted.has("id-quiet")).toBe(false);
151 expect((await fetch(`${base}/admin`, form(bob, { action: "unban", id: "id-evil" }))).status).toBe(400);
152 expect((await fetch(`${base}/admin`, form(bob, { action: "unban", id: "<x>" }))).status).toBe(400);
153
154 const after = await (await fetch(`${base}/admin`, { headers: bob })).text();
155 expect(after).toContain("<b>bob</b> unbanned &#60;img src=x&#62;");
156 expect(after).toContain("<b>bob</b> unmuted id-quiet");
157 expect(after).not.toContain("Unban &#60;");
158 });
Software/so101/src/admin-routes.ts +14 −3
@@ -34,7 +34,7 @@ export function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerRe
3434 return null;
3535 }
3636 const show = (status: number, done: Done | null, error: string | null) =>
37 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
37 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, muted: new Set(lobby.chat.muted.keys()), banned: new Set(lobby.accounts.bans().map((b) => b.id)), done, error }));
3838 if (req.method === "GET" || req.method === "HEAD") {
3939 const done = url.searchParams.get("done");
4040 show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
@@ -59,7 +59,6 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve
5959 res.end(JSON.stringify({ error: "GET or POST" }));
6060 return;
6161 }
62 if (!canEdit) return session.refuse(403);
6362 let body: Buffer;
6463 try {
6564 body = await readBody(req, MAX_FORM);
@@ -68,9 +67,21 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve
6867 return show(413, null, "that form is too large");
6968 }
7069 const form = new URLSearchParams(body.toString("utf8"));
70 const act = form.get("action");
71 // a moderator may lift a mute or a ban and nothing else
72 if (!canEdit && act !== "unmute" && act !== "unban") return session.refuse(403);
7173 let done: Done;
7274 try {
73 switch (form.get("action")) {
75 switch (act) {
76 case "unmute":
77 case "unban": {
78 const id = form.get("id") ?? "";
79 if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new AdminError("whom?");
80 if (act === "unmute") lobby.setMute(who, id, false);
81 else lobby.unban(who, id);
82 done = act === "unmute" ? "unmuted" : "unbanned";
83 break;
84 }
7485 case "save":
7586 lobby.configure(who, changeFromForm(form));
7687 done = "saved";
Software/so101/src/admin.ts +16 −4
@@ -49,14 +49,23 @@ const LABELS: Record<keyof AdminSettings, string> = {
4949 armServer: "arm server",
5050 moderators: "moderators",
5151 };
52 const KEEP_LOG = 50;
52 const KEEP_LOG = 200;
5353
5454 export class AdminError extends Error {}
5555
56 /** What a moderation entry did and to whom; entries without one are ordinary settings changes. */
57 export const MODERATION_KINDS = ["removed", "muted", "unmuted", "banned", "unbanned"] as const;
58 export interface ModerationAction {
59 kind: (typeof MODERATION_KINDS)[number];
60 id: string;
61 name: string;
62 }
63
5664 export interface LogEntry {
5765 at: number;
5866 by: { id: string; name: string };
5967 what: string;
68 action?: ModerationAction;
6069 }
6170
6271 /** Check a partial change; throws AdminError naming the first bad field. Unknown fields are refused, not ignored. */
@@ -157,8 +166,8 @@ export class Admin {
157166 }
158167
159168 /** Note an owner action (ending a turn, taking control) in the log. */
160 record(who: Person, what: string): void {
161 const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what };
169 record(who: Person, what: string, action?: ModerationAction): void {
170 const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what, ...(action ? { action } : {}) };
162171 this.log.push(entry);
163172 if (this.log.length > KEEP_LOG) this.log.splice(0, this.log.length - KEEP_LOG);
164173 console.log(`admin: ${who.name}: ${what}`);
@@ -190,7 +199,10 @@ export class Admin {
190199 for (const line of lines) {
191200 try {
192201 const e = JSON.parse(line) as LogEntry;
193 if (typeof e.at === "number" && typeof e.what === "string" && typeof e.by?.id === "string" && typeof e.by?.name === "string") this.log.push(e);
202 if (typeof e.at === "number" && typeof e.what === "string" && typeof e.by?.id === "string" && typeof e.by?.name === "string") {
203 const ok = e.action && (MODERATION_KINDS as readonly string[]).includes(e.action.kind) && typeof e.action.id === "string" && typeof e.action.name === "string";
204 this.log.push(ok ? e : { at: e.at, by: e.by, what: e.what });
205 }
194206 } catch {
195207 /* skip a torn line */
196208 }
Software/so101/src/lobby.ts +59 −30
@@ -191,6 +191,51 @@ export class Lobby {
191191 if (changed.length) for (const listener of this.changeListeners) listener();
192192 }
193193
194 /** Mute or unmute by id, logged. */
195 setMute(who: Person, id: string, on: boolean): void {
196 const name = [...this.seats].find((s) => s.who?.id === id)?.who?.name ?? [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from?.name ?? this.chat.muted.get(id) ?? id;
197 if (this.chat.muted.has(id) === on) return;
198 this.chat.mute(id, name, on);
199 this.admin.record(who, `${on ? "muted" : "unmuted"} ${name}`, { kind: on ? "muted" : "unmuted", id, name });
200 for (const s of this.seats) {
201 if (s.who?.id === id) this.send(s, this.hello(s));
202 if (s.who?.owner) this.send(s, this.mutedList());
203 }
204 this.moderator?.muted(id);
205 this.broadcastAdmin();
206 }
207
208 /** Ban by id (owner only: it needs the person to be known here). */
209 ban(who: Person, id: string): void {
210 const target = [...this.seats].find((s) => s.who?.id === id);
211 const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null);
212 const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from;
213 const person = known ?? (said ? { id, name: said.name, owner: false } : null);
214 if (!person) throw new AdminError("nobody here by that id");
215 if (person.owner) throw new AdminError("the owner cannot be banned");
216 this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name);
217 this.turns.end(id); // their turn ends, or they leave the line
218 this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) });
219 this.admin.record(who, `banned ${person.name}`, { kind: "banned", id, name: person.name });
220 this.afterBanChange();
221 }
222
223 /** Lift a ban by id, logged; throws when there was none. */
224 unban(who: Person, id: string): void {
225 const name = this.accounts.bans().find((b) => b.id === id)?.name;
226 if (!this.accounts.unban(id)) throw new AdminError("not banned");
227 this.admin.record(who, `unbanned ${name ?? id}`, { kind: "unbanned", id, name: name ?? id });
228 this.afterBanChange();
229 }
230
231 private afterBanChange(): void {
232 this.broadcastAdmin();
233 for (const s of this.seats) {
234 if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there
235 if (s.who?.owner) this.send(s, this.bannedList());
236 }
237 }
238
194239 /** The owner ends whoever drives now. */
195240 endTurn(who: Who): void {
196241 if (!who?.owner) throw new AdminError("only the owner can do that");
@@ -329,7 +374,13 @@ export class Lobby {
329374 return this.configure(who, m.set);
330375 case "delete":
331376 if (!Number.isSafeInteger(m.id)) return this.send(seat, { type: "error", error: "delete which line?" });
332 if (this.chat.delete(m.id as number)) this.broadcast({ type: "unsaid", id: m.id });
377 {
378 const line = this.chat.messages.find((x) => x.id === m.id);
379 if (this.chat.delete(m.id as number)) {
380 this.broadcast({ type: "unsaid", id: m.id });
381 if (line?.from) this.admin.record(who, `removed a line by ${line.from.name}`, { kind: "removed", id: line.from.id, name: line.from.name });
382 }
383 }
333384 return;
334385 case "words": {
335386 const words = this.filter.set(m.words);
@@ -340,39 +391,17 @@ export class Lobby {
340391 }
341392 case "mute": {
342393 if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "mute whom?" });
343 const id = m.id;
344 const name = [...this.seats].find((s) => s.who?.id === id)?.who?.name ?? [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from?.name ?? this.chat.muted.get(id) ?? id;
345 this.chat.mute(id, name, m.on);
346 for (const s of this.seats) {
347 if (s.who?.id === id) this.send(s, this.hello(s));
348 if (s.who?.owner) this.send(s, this.mutedList());
349 }
350 this.moderator?.muted(id);
394 this.setMute(who, m.id, m.on);
351395 return;
352396 }
353397 case "ban": {
354398 if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "ban whom?" });
355 const id = m.id;
356 if (m.on) {
357 const target = [...this.seats].find((s) => s.who?.id === id);
358 const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null);
359 const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from;
360 const person = known ?? (said ? { id, name: said.name, owner: false } : null);
361 if (!person) return this.send(seat, { type: "error", error: "nobody here by that id" });
362 if (person.owner) return this.send(seat, { type: "error", error: "the owner cannot be banned" });
363 this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name);
364 this.turns.end(id); // their turn ends, or they leave the line
365 this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) });
366 this.admin.record(who, `banned ${person.name}`);
367 } else {
368 const name = this.accounts.bans().find((b) => b.id === id)?.name;
369 if (!this.accounts.unban(id)) return this.send(seat, { type: "error", error: "not banned" });
370 this.admin.record(who, `unbanned ${name ?? id}`);
371 }
372 this.broadcastAdmin();
373 for (const s of this.seats) {
374 if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there
375 if (s.who?.owner) this.send(s, this.bannedList());
399 try {
400 if (m.on) this.ban(who, m.id);
401 else this.unban(who, m.id);
402 } catch (err) {
403 if (!(err instanceof AdminError)) throw err;
404 this.send(seat, { type: "error", error: err.message });
376405 }
377406 return;
378407 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs