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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Beside a live mute or ban on /admin, an Unmute or Unban button lifts it, same-origin, and the lift is logged #322

Parked opened this
Closed without merging

smith/arm:smith/221-beside-a-live-mute-or-ban-on-admin-an-un → main 3 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +99 −16
Software/README.md +4 −1
@@ -579,7 +579,10 @@ or from the **Admin** tab that only the owner sees:
579579 (it shows in `/link`; the camera list is the owner's own); empty uses the
580580 `ARM_SERVER` environment variable, then the simulation.
581581 - **Moderators**: usernames the owner names on `/admin`. A moderator can open
582 `/admin` and read the settings and the log, and change nothing. A moderator
582 `/admin`, read the settings and the log, and lift a mute or a ban from the
583 Moderation list (never another moderator's mute); the lift is logged under
584 their name. They change nothing else. The lift is web-only, like the rest of
585 `/admin`: the terminal has no mute or ban door. A moderator
583586 is matched on the forge-signed identity (the forge username), never on a
584587 name a guest typed: a guest who picks a moderator's name still gets a 403.
585588 Settings are web-only because this app has no terminal (`forge.json` has no
Software/so101/src/admin-page.ts +18 −2
@@ -53,6 +53,7 @@ th:first-child, td:first-child { text-align: left; }
5353 th { color: var(--dim); font-weight: 600; }
5454 .scroll { overflow-x: auto; }
5555 .inline { display: inline; margin: 0; }
56 .lift { display: block; margin: .5rem 0 0; }
5657 .empty { color: var(--dim); }
5758 @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
5859 `;
@@ -86,7 +87,7 @@ setInterval(tick, 2000);
8687 export const ADMIN_CSP = `default-src 'none'; style-src 'sha256-${createHash("sha256").update(STYLE).digest("base64")}'; script-src 'sha256-${createHash("sha256").update(HEALTH_SCRIPT).digest("base64")}'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
8788
8889 /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */
89 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.", restored: "Line restored." } as const;
90 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.", restored: "Line restored.", unmuted: "Mute lifted.", unbanned: "Ban lifted." } as const;
9091 export type Done = keyof typeof DONE;
9192
9293 export interface AdminPage {
@@ -100,6 +101,9 @@ export interface AdminPage {
100101 log: readonly LogEntry[];
101102 /** Chat lines a person removed, newest first. */
102103 removed?: readonly Removed[];
104 /** Mutes and bans in force now. */
105 muted?: readonly { id: string; name: string; until: number | null }[];
106 bans?: readonly { id: string; name: string; at: number; by: string }[];
103107 done?: Done | null;
104108 error?: string | null;
105109 }
@@ -149,6 +153,18 @@ const action = (name: string, text: string, cls = "", disabled = false) =>
149153 /** The log lines that are moderation: chat-line deletions, removals from the line, mutes, bans and their reversals. */
150154 export const isModeration = (e: LogEntry): boolean => /^(banned|unbanned|muted|unmuted|deleted chat line|restored chat line|took .+ out of the line)/.test(e.what);
151155
156 /** Mutes and bans in force, each with a button that lifts it; the owner and a moderator both see them. */
157 const inForce = (muted: NonNullable<AdminPage["muted"]>, bans: NonNullable<AdminPage["bans"]>): string => {
158 const lift = (act: string, id: string, label: string, name: string) =>
159 `<form method="post" action="/admin" class="lift"><input type="hidden" name="action" value="${act}"><input type="hidden" name="id" value="${esc(id)}"><button aria-label="${label} ${esc(name)}">${label}</button></form>`;
160 const until = (at: number) => esc(new Date(at).toLocaleString("en-GB", { timeZone: "UTC", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) + " UTC");
161 const rows = [
outdated

Raw ISO timestamp and an inline button after running text: hard on a 360px phone. Put the form on its own line/with padding and word the time for a person.

162 ...muted.map((m) => `<li><span>Muted</span><span><b>${esc(m.name)}</b>, ${m.until === null ? "for good" : `until ${until(m.until)}`}${lift("unmute", m.id, "Unmute", m.name)}</span></li>`),
163 ...bans.map((b) => `<li><span>Banned</span><span><b>${esc(b.name)}</b>, by ${esc(b.by)}${lift("unban", b.id, "Unban", b.name)}</span></li>`),
164 ];
165 return rows.length ? `<ol>${rows.join("")}</ol>` : `<p class="empty">No mutes or bans in force.</p>`;
166 };
167
152168 /** Removed chat lines, each with who took it down and, for the owner, a Restore button. */
153169 const removedLines = (list: readonly Removed[], canEdit: boolean): string =>
154170 list.length
@@ -195,7 +211,7 @@ ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>
195211 </section>
196212 <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section>
197213 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
198 <section aria-labelledby="moderation"><h2 id="moderation">Moderation</h2>${actions}</section>
214 <section aria-labelledby="moderation"><h2 id="moderation">Moderation</h2>${inForce(p.muted ?? [], p.bans ?? [])}${actions}</section>
199215 <section aria-labelledby="removed"><h2 id="removed">Removed lines</h2>${removedLines(p.removed ?? [], p.canEdit)}</section>
200216 <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`,
201217 );
Software/so101/src/admin-relay.test.ts +28
@@ -123,3 +123,31 @@ test("/status names who is driving: null, then alice, then the owner after a tak
123123 sim.stop(true);
124124 }
125125 });
126
127 test("a moderator lifts a ban and a mute from /admin and the log says who; a plain user or another origin cannot", async () => {
128 dir = mkdtempSync(join(tmpdir(), "so101-admin-relay-"));
129 const base = await boot();
130 const owner = as("trevato", "admin");
131 const bob = as("bob", "user");
132 await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" }));
133 lobby!.accounts.ban({ id: "u-eve", name: "eve", owner: false }, null, "trevato");
134 lobby!.chat.mute("u-mal", "mal", null);
135 const page = await (await fetch(`${base}/admin`, { headers: bob })).text();
136 expect(page).toContain('aria-label="Unban eve"');
137 expect(page).toContain('aria-label="Unmute mal"');
138
139 expect((await fetch(`${base}/admin`, form(as("zed", "user"), { action: "unban", id: "u-eve" }))).status).toBe(404);
140 const cross = await fetch(`${base}/admin`, form({ ...bob, "sec-fetch-site": "cross-site" }, { action: "unban", id: "u-eve" }));
141 expect(cross.status).toBe(403);
142 expect(lobby!.accounts.bans()).toHaveLength(1);
143 expect((await fetch(`${base}/admin`, form(bob, { action: "pause" }))).status).toBe(403);
144
145 expect((await fetch(`${base}/admin`, form(bob, { action: "unban", id: "u-eve" }))).status).toBe(303);
146 expect((await fetch(`${base}/admin`, form(bob, { action: "unmute", id: "u-mal" }))).status).toBe(303);
147 expect(lobby!.accounts.bans()).toHaveLength(0);
148 expect(lobby!.chat.muted.size).toBe(0);
149 expect((await fetch(`${base}/admin`, form(bob, { action: "unban", id: "u-eve" }))).status).toBe(400);
150 const log = lobby!.admin.log.map((e) => `${e.by.name} ${e.what}`);
151 expect(log.some((l) => l.includes("bob") && l.includes("unbanned eve"))).toBe(true);
152 expect(log.some((l) => l.includes("bob") && l.includes("unmuted mal"))).toBe(true);
153 });
Software/so101/src/admin-routes.ts +14 −3
@@ -44,7 +44,7 @@ export function serveAdminPage(lobby: Lobby, req: IncomingMessage, res: ServerRe
4444 return null;
4545 }
4646 const show = (status: number, done: Done | null, error: string | null) =>
47 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, health: lobby.reports.rows(), done, error }));
47 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, removed: lobby.chat.removed, muted: lobby.chat.mutedList(), bans: lobby.accounts.bans(), health: lobby.reports.rows(), done, error }));
4848 if (req.method === "GET" || req.method === "HEAD") {
4949 const done = url.searchParams.get("done");
5050 show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
@@ -69,7 +69,6 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve
6969 res.end(JSON.stringify({ error: "GET or POST" }));
7070 return;
7171 }
72 if (!canEdit) return session.refuse(403);
7372 let body: Buffer;
7473 try {
7574 body = await readBody(req, MAX_FORM);
@@ -78,9 +77,21 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve
7877 return show(413, null, "that form is too large");
7978 }
8079 const form = new URLSearchParams(body.toString("utf8"));
80 const act = form.get("action");
81 // a moderator may lift a mute or a ban and nothing else
82 if (!canEdit && act !== "unmute" && act !== "unban") return session.refuse(403);

Correct gate. Document it in Software/README.md (moderators currently documented as read-only).

8183 let done: Done;
8284 try {
83 switch (form.get("action")) {
85 switch (act) {
86 case "unmute":
87 if (!lobby.liftMute(who, form.get("id"))) throw new AdminError("that mute is not in force");
88 done = "unmuted";
89 break;
90 case "unban":
91 if (!lobby.liftBan(who, form.get("id"))) throw new AdminError("that ban is not in force");
92 lobby.afterBanChange();
93 done = "unbanned";
94 break;
8495 case "save":
8596 lobby.configure(who, changeFromForm(form));
8697 done = "saved";
Software/so101/src/lobby.ts +35 −10
@@ -382,16 +382,8 @@ export class Lobby {
382382 this.turns.end(id); // their turn ends, or they leave the line
383383 this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) });
384384 this.admin.record(who, `banned ${person.name}`);
385 } else {
386 const name = this.accounts.bans().find((b) => b.id === id)?.name;
387 if (!this.accounts.unban(id)) return this.send(seat, { type: "error", error: "not banned" });
388 this.admin.record(who, `unbanned ${name ?? id}`);
389 }
390 this.broadcastAdmin();
391 for (const s of this.seats) {
392 if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there
393 if (s.who?.owner) this.send(s, this.bannedList());
394 }
385 } else if (!this.liftBan(who, id)) return this.send(seat, { type: "error", error: "not banned" });
386 this.afterBanChange();
395387 return;
396388 }
397389 case "crew":
@@ -431,6 +423,10 @@ export class Lobby {
431423 if (m.on) this.chat.mute(id, name, span === null ? null : this.now() + span);
432424 else this.chat.unmute(id);
433425 this.admin.record(who, `${m.on ? "muted" : "unmuted"} ${name}`);
426 this.afterMuteChange(id);
427 }
428
429 private afterMuteChange(id: string): void {
434430 this.broadcastAdmin();
435431 for (const s of this.seats) {
436432 if (s.who?.id === id) this.send(s, this.hello(s));
@@ -439,6 +435,35 @@ export class Lobby {
439435 this.moderator?.muted(id);
440436 }
441437
438 /** Lifts a mute that is in force, for the admin page: the owner any, a moderator any but a moderator's. False when there is none. */
439 liftMute(who: Person, id: unknown): boolean {
440 if (typeof id !== "string" || !USER_ID.test(id)) return false;
441 const name = this.chat.muted.get(id);
442 if (name === undefined || (!who.owner && this.admin.isModerator(name))) return false;
443 this.chat.unmute(id);
444 this.admin.record(who, `unmuted ${name}`);
445 this.afterMuteChange(id);
446 return true;
447 }
448
449 /** Lifts a ban that is in force, for the owner or a moderator; the admin log says who. False when there is none. */
450 liftBan(who: Person, id: unknown): boolean {
451 if (typeof id !== "string" || !USER_ID.test(id)) return false;
452 const name = this.accounts.bans().find((b) => b.id === id)?.name;
453 if (!this.accounts.unban(id)) return false;
454 this.admin.record(who, `unbanned ${name ?? id}`);
455 return true;
456 }
457
458 /** Tells everyone a ban was made or lifted: an address ban reaches everyone there. */
459 afterBanChange(): void {
460 this.broadcastAdmin();
461 for (const s of this.seats) {
462 if (s.who && !s.who.owner) this.send(s, this.hello(s));
463 if (s.who?.owner) this.send(s, this.bannedList());
464 }
465 }
466
442467 /** The owner and a verified moderator are sent the muted list. */
443468 private mayHearMuted(s: Seat): boolean {
444469 return Boolean(s.who && (s.who.owner || (s.verified && this.admin.isModerator(s.who.name))));

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs