Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Moderation: ban and mute users (for a time or for good), remove messages, slow mode - from the chat itself and the admin page #166
smith/arm:smith/13-moderation-ban-and-mute-users-for-a-time → main 8 commits fork 2 threads · 2 unresolved
14 files
changed +704
−122
Software/README.md +23 −4
| @@ -399,9 +399,29 @@ its live pose and the cameras. Driving needs a name and a turn. | ||
| 399 | 399 | Settings and log: `$FORGE_APP_DATA/so101/crew.json`. |
| 400 | 400 | - The owner (anyone who may write this repository) can take control at |
| 401 | 401 | any time (this skips the queue), end anyone's turn, take people out of |
| 402 | the queue, delete messages, mute people and ban them (long-press or | |
| 403 | right-click a chat line). | |
| 404 | The owner can also press **Stop** during anyone's turn. | |
| 402 | the queue and delete messages. The owner can also press **Stop** during | |
| 403 | anyone's turn. | |
| 404 | - Moderation, owner only (every request is checked on the server against the | |
| 405 | signed identity). Owners see a **Moderation page** link under the queue in | |
| 406 | the viewer; it is `/moderation` on the same address (`/admin` is the arm controls below), and anyone else gets 403. | |
| 407 | - A ⋯ menu on every chat line (always shown, so it works on a phone): | |
| 408 | remove the message, or mute its author for 10 min, 1 h, 24 h or for good, | |
| 409 | or ban them. | |
| 410 | - **Mute**: the person can still watch and drive, but cannot chat. | |
| 411 | - **Ban**: no chat, no queue and no driving (the HTTP controls refuse too); | |
| 412 | a turn in progress ends. They can still watch. The menu bans for good; the | |
| 413 | protocol takes `minutes` for a timed ban, but the UI has no duration yet. A ban for good also bars their name and the address they were last seen at (below); a timed ban is by account. | |
| 414 | - Timed sanctions run from a minute to a year and lift themselves. Owners | |
| 415 | cannot be muted or banned, nor can you sanction yourself; anyone who has | |
| 416 | ever connected as an owner is remembered, online or not. | |
| 417 | - **Slow mode** (on `/moderation`): seconds between one person's messages, 0 to | |
| 418 | 3600; 0 leaves the chat's own 2 s. | |
| 419 | - **Audit log** (on `/moderation`): the last 200 actions with who, whom and when. | |
| 420 | Each can be **undone** once: a lift puts the sanction back with its | |
| 421 | remaining time (nothing if it has run out, or if they are sanctioned | |
| 422 | again); undoing an older mute or ban leaves a newer one alone; a removed | |
| 423 | message comes back; slow mode returns to its old value. | |
| 424 | - Everything is kept in `$FORGE_APP_DATA/so101/moderation.json`. | |
| 405 | 425 | - The red **STOP** button (or Esc) is the emergency stop. |
| 406 | 426 | The driver and the owner can press it. Only the owner can clear it, and |
| 407 | 427 | only the owner can change the settings. |
| @@ -463,7 +483,6 @@ web viewer as it happens. Text from the room is shown with control | ||
| 463 | 483 | characters removed, so a chat line cannot drive your terminal. Locally, |
| 464 | 484 | `PORT=8102 bun run Software/so101/src/tty.ts` beside `fake-serve.ts` |
| 465 | 485 | reaches it as the owner. |
| 466 | ||
| 467 | 486 | **Admin.** The owner runs the room from `/admin` (plain forms, no script), |
| 468 | 487 | or from the **Admin** tab that only the owner sees: |
| 469 | 488 |
Software/so101/bench/fake-serve.ts +1
| @@ -52,6 +52,7 @@ const lobby = new Lobby({ | ||
| 52 | 52 | local, |
| 53 | 53 | chatFile: join(dir, "chat.json"), |
| 54 | 54 | adminFile: join(dir, "admin.json"), |
| 55 | moderationFile: join(dir, "moderation.json"), | |
| 55 | 56 | wordsFile: join(dir, "words.json"), |
| 56 | 57 | accounts: new Accounts({ file: join(dir, "accounts.sqlite") }), |
| 57 | 58 | moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }), |
Software/so101/src/chat.test.ts +12 −8
| @@ -30,27 +30,31 @@ describe("chat", () => { | ||
| 30 | 30 | expect(chat.post(alice, "a\u0000b\nc\u202Ed").text).toBe("ab cd"); |
| 31 | 31 | }); |
| 32 | 32 | |
| 33 | test("the last 200 lines are kept, and survive a restart with the mutes", () => { | |
| 33 | test("the last 200 lines are kept, and survive a restart", () => { | |
| 34 | 34 | const file = join(mkdtempSync(join(tmpdir(), "so101-chat-")), "chat.json"); |
| 35 | 35 | let clock = 0; |
| 36 | 36 | const chat = new Chat({ file, now: () => (clock += 5000) }); |
| 37 | 37 | for (let i = 0; i < KEEP + 5; i++) chat.post(alice, `line ${i}`); |
| 38 | chat.mute("b", "bob", true); | |
| 39 | 38 | expect(chat.messages.length).toBe(KEEP); |
| 40 | 39 | const again = new Chat({ file }); |
| 41 | 40 | expect(again.messages.length).toBe(KEEP); |
| 42 | 41 | expect(again.messages[0]!.text).toBe("line 5"); |
| 43 | expect(again.muted.get("b")).toBe("bob"); | |
| 44 | 42 | expect(again.system("x").id).toBe(chat.messages.at(-1)!.id + 1); |
| 45 | 43 | }); |
| 46 | 44 | |
| 47 | test("a muted person cannot post; a deleted line is gone", () => { | |
| 48 | const chat = new Chat(); | |
| 45 | test("slow mode raises the wait; a deleted line is gone and can be restored in place", () => { | |
| 46 | let clock = 0; | |
| 47 | const chat = new Chat({ now: () => clock }); | |
| 49 | 48 | const line = chat.post(alice, "spam"); |
| 50 | chat.mute("a", "alice", true); | |
| 51 | expect(() => chat.post(alice, "more")).toThrow(/muted/); | |
| 49 | clock += 5000; | |
| 50 | expect(() => chat.post(alice, "more", 10_000)).toThrow(/one message every 10 s/); | |
| 51 | const after = chat.post(bob, "after"); | |
| 52 | expect(chat.delete(line.id)).toBe(true); | |
| 53 | expect(chat.restore(line)).toBe(true); | |
| 54 | expect(chat.restore(line)).toBe(false); | |
| 55 | expect(chat.messages.map((m) => m.id)).toEqual([line.id, after.id]); | |
| 52 | 56 | expect(chat.delete(line.id)).toBe(true); |
| 53 | 57 | expect(chat.delete(line.id)).toBe(false); |
| 54 | expect(chat.messages).toEqual([]); | |
| 58 | expect(chat.messages.map((m) => m.id)).toEqual([after.id]); | |
| 55 | 59 | }); |
| 56 | 60 | }); |
Software/so101/src/chat.ts +12 −19
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | /** |
| 2 | * The chat beside the arm: everyone reads, signed-in people post, the owner deletes lines and mutes people. | |
| 2 | * The chat beside the arm: everyone reads, signed-in people post, the owner deletes lines (moderation.ts decides who may not post). | |
| 3 | 3 | * One line per `rateMs` per person, `MAX_CHARS` characters, the last `KEEP` lines kept; driver changes are |
| 4 | 4 | * system lines. Text is stored as typed (minus control characters) and only ever shown as text. |
| 5 | 5 | * Kept in one JSON file beside the arm's data, rewritten whole on each change (it is a few dozen KB at most). |
| @@ -23,7 +23,7 @@ export interface Message { | ||
| 23 | 23 | export class ChatError extends Error {} |
| 24 | 24 | |
| 25 | 25 | export interface ChatOptions { |
| 26 | /** Where the log and the mutes live; none keeps them in memory. */ | |
| 26 | /** Where the log lives; none keeps it in memory. */ | |
| 27 | 27 | file?: string; |
| 28 | 28 | rateMs?: number; |
| 29 | 29 | now?: () => number; |
| @@ -42,8 +42,6 @@ export function cleanText(text: unknown): string { | ||
| 42 | 42 | |
| 43 | 43 | export class Chat { |
| 44 | 44 | messages: Message[] = []; |
| 45 | /** id → name of everyone muted. */ | |
| 46 | readonly muted = new Map<string, string>(); | |
| 47 | 45 | private next = 1; |
| 48 | 46 | private readonly lastPost = new Map<string, number>(); |
| 49 | 47 | private readonly file: string | undefined; |
| @@ -57,12 +55,13 @@ export class Chat { | ||
| 57 | 55 | if (this.file) this.load(this.file); |
| 58 | 56 | } |
| 59 | 57 | |
| 60 | post(who: Person, text: unknown): Message { | |
| 61 | if (this.muted.has(who.id)) throw new ChatError("you are muted"); | |
| 58 | /** `rateMs` raises the wait between one person's messages (slow mode); it never goes below the chat's own. */ | |
| 59 | post(who: Person, text: unknown, rateMs = 0): Message { | |
| 60 | const wait = Math.max(this.rateMs, rateMs); | |
| 62 | 61 | const clean = cleanText(text); |
| 63 | 62 | const now = this.now(); |
| 64 | 63 | const last = this.lastPost.get(who.id); |
| 65 | if (last !== undefined && now - last < this.rateMs) throw new ChatError(`one message every ${this.rateMs / 1000} s`); | |
| 64 | if (last !== undefined && now - last < wait) throw new ChatError(`one message every ${wait / 1000} s`); | |
| 66 | 65 | this.lastPost.set(who.id, now); |
| 67 | 66 | return this.add({ id: who.id, name: who.name }, clean); |
| 68 | 67 | } |
| @@ -79,19 +78,14 @@ export class Chat { | ||
| 79 | 78 | return true; |
| 80 | 79 | } |
| 81 | 80 | |
| 82 | /** Puts a removed line back where its id puts it. */ | |
| 83 | restore(message: Message): void { | |
| 84 | if (this.messages.some((m) => m.id === message.id)) return; | |
| 81 | /** Put a removed line back where it was (by id); false when it is there already. */ | |
| 82 | restore(message: Message): boolean { | |
| 83 | if (this.messages.some((m) => m.id === message.id)) return false; | |
| 85 | 84 | this.messages.push(message); |
| 86 | 85 | this.messages.sort((a, b) => a.id - b.id); |
| 87 | 86 | if (this.messages.length > KEEP) this.messages.splice(0, this.messages.length - KEEP); |
| 88 | 87 | this.save(); |
| 89 | } | |
| 90 | ||
| 91 | mute(id: string, name: string, on: boolean): void { | |
| 92 | if (on) this.muted.set(id, name); | |
| 93 | else this.muted.delete(id); | |
| 94 | this.save(); | |
| 88 | return true; | |
| 95 | 89 | } |
| 96 | 90 | |
| 97 | 91 | private add(from: Message["from"], text: string): Message { |
| @@ -103,7 +97,7 @@ export class Chat { | ||
| 103 | 97 | } |
| 104 | 98 | |
| 105 | 99 | private load(file: string): void { |
| 106 | let stored: { messages?: unknown; muted?: unknown }; | |
| 100 | let stored: { messages?: unknown }; | |
| 107 | 101 | try { |
| 108 | 102 | stored = JSON.parse(readFileSync(file, "utf8")); |
| 109 | 103 | } catch { |
| @@ -114,14 +108,13 @@ export class Chat { | ||
| 114 | 108 | .filter((m): m is Message => typeof m?.id === "number" && typeof m.at === "number" && typeof m.text === "string" && (m.from === null || (typeof m.from?.id === "string" && typeof m.from?.name === "string"))) |
| 115 | 109 | .slice(-KEEP); |
| 116 | 110 | } |
| 117 | if (stored.muted && typeof stored.muted === "object") for (const [id, name] of Object.entries(stored.muted)) if (typeof name === "string") this.muted.set(id, name); | |
| 118 | 111 | this.next = Math.max(0, ...this.messages.map((m) => m.id)) + 1; |
| 119 | 112 | } |
| 120 | 113 | |
| 121 | 114 | private save(): void { |
| 122 | 115 | if (!this.file) return; |
| 123 | 116 | mkdirSync(dirname(this.file), { recursive: true }); |
| 124 | writeFileSync(`${this.file}.tmp`, JSON.stringify({ messages: this.messages, muted: Object.fromEntries(this.muted) })); | |
| 117 | writeFileSync(`${this.file}.tmp`, JSON.stringify({ messages: this.messages })); | |
| 125 | 118 | renameSync(`${this.file}.tmp`, this.file); |
| 126 | 119 | } |
| 127 | 120 | } |
Software/so101/src/lobby.security.test.ts +1 −1
| @@ -135,7 +135,7 @@ describe("lobby security", () => { | ||
| 135 | 135 | expect((await bob.next((m) => m.type === "error")).error).toContain("only the owner"); |
| 136 | 136 | bob.send({ type: "end", id: "u-alice" }); |
| 137 | 137 | expect((await bob.next((m) => m.type === "error")).error).toContain("only the owner"); |
| 138 | expect(chat.muted.size).toBe(0); | |
| 138 | expect(lobby!.moderation.muted("u-alice")).toBe(false); | |
| 139 | 139 | expect(lobby!.turns.driver?.id).toBe("u-alice"); |
| 140 | 140 | |
| 141 | 141 | const owner = await join(port, OWNER); |
Software/so101/src/lobby.test.ts +109 −2
| @@ -270,9 +270,9 @@ describe("lobby", () => { | ||
| 270 | 270 | |
| 271 | 271 | owner.send({ type: "delete", id: said.message.id }); |
| 272 | 272 | expect((await anon.next((m) => m.type === "unsaid")).id).toBe(said.message.id); |
| 273 | owner.send({ type: "mute", id: "u-alice", on: true }); | |
| 273 | owner.send({ type: "mute", id: "u-alice", minutes: 10 }); | |
| 274 | 274 | expect((await alice.next((m) => m.type === "hello")).muted).toBe(true); |
| 275 | expect((await owner.next((m) => m.type === "muted")).muted).toEqual([{ id: "u-alice", name: "alice" }]); | |
| 275 | expect((await owner.next((m) => m.type === "muted" && m.sanctions.length === 1)).sanctions[0]).toMatchObject({ id: "u-alice", name: "alice", kind: "mute" }); | |
| 276 | 276 | |
| 277 | 277 | const late = await join(port); |
| 278 | 278 | expect((await late.first((m) => m.type === "chat")).messages).toEqual([]); |
| @@ -505,6 +505,113 @@ describe("lobby", () => { | ||
| 505 | 505 | expect(fourth.body.error).toContain("at most 3"); |
| 506 | 506 | }); |
| 507 | 507 | |
| 508 | describe("moderation", () => { | |
| 509 | test("non-moderators cannot do any of it", async () => { | |
| 510 | const port = await start(); | |
| 511 | const alice = await join(port, ALICE); | |
| 512 | const bob = await join(port, BOB); | |
| 513 | bob.send({ type: "post", text: "hi" }); | |
| 514 | const said = await alice.next((m) => m.type === "said"); | |
| 515 | for (const req of [{ type: "delete", id: said.message.id }, { type: "mute", id: "u-bob", minutes: 10 }, { type: "ban", id: "u-bob" }, { type: "slow", seconds: 5 }, { type: "undo", entry: 1 }, { type: "unban", id: "u-bob" }]) { | |
| 516 | alice.send(req); | |
| 517 | expect((await alice.next((m) => m.type === "error")).error).toContain("only the owner"); | |
| 518 | } | |
| 519 | expect(lobby!.moderation.audit).toEqual([]); | |
| 520 | expect(lobby!.chat.messages.length).toBe(1); | |
| 521 | expect((await fetch(`http://127.0.0.1:${port}/moderation`, { headers: ALICE })).status).toBe(403); | |
| 522 | expect((await fetch(`http://127.0.0.1:${port}/moderation`)).status).toBe(403); | |
| 523 | expect((await fetch(`http://127.0.0.1:${port}/moderation`, { headers: OWNER })).status).toBe(200); | |
| 524 | }); | |
| 525 | ||
| 526 | test("a mute blocks posting for the time, then lifts; undo lifts it early", async () => { | |
| 527 | let clock = 1_000_000; | |
| 528 | lobby = undefined; | |
| 529 | const moderation = new (await import("./moderation.ts")).Moderation({ now: () => clock }); | |
| 530 | const turns = new Turns(); | |
| 531 | lobby = new Lobby({ identityKey: KEY, turns, chat: new Chat({ now: () => clock }), moderation }); | |
| 532 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby }); | |
| 533 | const port = relay.port; | |
| 534 | const alice = await join(port, ALICE); | |
| 535 | const owner = await join(port, OWNER); | |
| 536 | owner.send({ type: "mute", id: "u-alice", minutes: 10 }); | |
| 537 | await alice.next((m) => m.type === "hello" && m.muted); | |
| 538 | alice.send({ type: "post", text: "hi" }); | |
| 539 | expect((await alice.next((m) => m.type === "error")).error).toContain("muted"); | |
| 540 | clock += 9 * 60_000; | |
| 541 | alice.send({ type: "post", text: "hi" }); | |
| 542 | expect((await alice.next((m) => m.type === "error" && m.error.includes("muted"), 2000)).error).toContain("muted"); | |
| 543 | clock += 61_000; | |
| 544 | alice.send({ type: "post", text: "hi again" }); | |
| 545 | expect((await alice.next((m) => m.type === "said")).message.text).toBe("hi again"); | |
| 546 | ||
| 547 | owner.send({ type: "mute", id: "u-alice" }); // for good | |
| 548 | await alice.next((m) => m.type === "hello" && m.muted); | |
| 549 | clock += 400 * 86_400_000; | |
| 550 | expect(moderation.muted("u-alice")).toBe(true); | |
| 551 | const entry = moderation.audit.findLast((e) => e.action === "mute" && !e.undone)!; | |
| 552 | owner.send({ type: "undo", entry: entry.id }); | |
| 553 | await alice.next((m) => m.type === "hello" && !m.muted); | |
| 554 | }); | |
| 555 | ||
| 556 | test("a ban blocks chat and the queue, drops the line and ends the turn; the banned can still watch; undo", async () => { | |
| 557 | const port = await start(); | |
| 558 | const alice = await join(port, ALICE); | |
| 559 | const bob = await join(port, BOB); | |
| 560 | const owner = await join(port, OWNER); | |
| 561 | alice.send({ type: "join" }); | |
| 562 | await bob.next(drivingIs("alice")); | |
| 563 | bob.send({ type: "join" }); | |
| 564 | await owner.next((m) => m.type === "state" && m.queue.length === 1); | |
| 565 | expect((await torque(port, ALICE)).status).toBe(200); | |
| 566 | ||
| 567 | owner.send({ type: "ban", id: "u-bob", minutes: 60 }); | |
| 568 | await owner.next((m) => m.type === "state" && m.queue.length === 0); | |
| 569 | bob.send({ type: "join" }); | |
| 570 | expect((await bob.next((m) => m.type === "error")).error).toContain("banned"); | |
| 571 | bob.send({ type: "post", text: "hi" }); | |
| 572 | expect((await bob.next((m) => m.type === "error")).error).toContain("banned"); | |
| 573 | expect(bob.last("state")).toBeTruthy(); // still watching | |
| 574 | ||
| 575 | owner.send({ type: "ban", id: "u-alice" }); | |
| 576 | await bob.next(drivingIs(null)); | |
| 577 | expect(lobby!.moderation.banned("u-alice")).toBe(true); | |
| 578 | expect((await torque(port, ALICE)).status).toBe(403); | |
| 579 | alice.send({ type: "join" }); | |
| 580 | expect((await alice.next((m) => m.type === "error")).error).toContain("banned"); | |
| 581 | ||
| 582 | const entry = lobby!.moderation.audit.find((e) => e.action === "ban" && e.target!.id === "u-alice")!; | |
| 583 | owner.send({ type: "undo", entry: entry.id }); | |
| 584 | await owner.next((m) => m.type === "muted" && m.sanctions.length === 1); | |
| 585 | alice.send({ type: "join" }); | |
| 586 | await bob.next(drivingIs("alice")); | |
| 587 | }); | |
| 588 | ||
| 589 | test("removing a line goes to everyone live, is audited, and undo restores it; slow mode is a setting", async () => { | |
| 590 | const port = await start(); | |
| 591 | const alice = await join(port, ALICE); | |
| 592 | const bob = await join(port, BOB); | |
| 593 | const owner = await join(port, OWNER); | |
| 594 | alice.send({ type: "post", text: "oops" }); | |
| 595 | const said = await bob.next((m) => m.type === "said"); | |
| 596 | owner.send({ type: "delete", id: said.message.id }); | |
| 597 | for (const c of [alice, bob, owner]) expect((await c.next((m) => m.type === "unsaid")).id).toBe(said.message.id); | |
| 598 | const view = await owner.next((m) => m.type === "muted" && m.audit.length === 1); | |
| 599 | expect(view.audit[0]).toMatchObject({ action: "remove", by: { name: "trevato" }, target: { id: "u-alice" } }); | |
| 600 | owner.send({ type: "undo", entry: view.audit[0].id }); | |
| 601 | expect((await bob.next((m) => m.type === "chat" && m.messages.length === 1)).messages[0].text).toBe("oops"); | |
| 602 | ||
| 603 | owner.send({ type: "slow", seconds: 30 }); | |
| 604 | await owner.next((m) => m.type === "muted" && m.slowSeconds === 30); | |
| 605 | bob.send({ type: "post", text: "one" }); | |
| 606 | await bob.next((m) => m.type === "said"); | |
| 607 | await sleep(2100); | |
| 608 | bob.send({ type: "post", text: "two" }); | |
| 609 | expect((await bob.next((m) => m.type === "error")).error).toContain("one message every 30 s"); | |
| 610 | owner.send({ type: "slow", seconds: -1 }); | |
| 611 | expect((await owner.next((m) => m.type === "error")).error).toContain("0 to 3600"); | |
| 612 | }); | |
| 613 | }); | |
| 614 | ||
| 508 | 615 | const form = (port: number, fields: Record<string, string>, headers: Record<string, string> = {}) => |
| 509 | 616 | fetch(`http://127.0.0.1:${port}/admin`, { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded", "sec-fetch-site": "same-origin", ...headers }, body: new URLSearchParams(fields).toString() }); |
| 510 | 617 |
Software/so101/src/lobby.ts +141 −83
| @@ -12,7 +12,10 @@ | ||
| 12 | 12 | * {"type": "post", "text": "…"} say something |
| 13 | 13 | * {"type": "end", "id": "<user id>"} owner: end that turn, or take them out of the line |
| 14 | 14 | * {"type": "delete", "id": 12} owner: delete a chat line |
| 15 | * {"type": "mute", "id": "<user id>", "on": true|false} owner | |
| 15 | * {"type": "mute", "id": "<user id>", "minutes": 10} owner: mute (no minutes: for good); "unmute" lifts it | |
| 16 | * {"type": "ban", "id": "<user id>", "minutes": 60} owner: no chat, no queue, turn ended; "unban" lifts it | |
| 17 | * {"type": "slow", "seconds": 5} owner: seconds between one person's messages | |
| 18 | * {"type": "undo", "entry": 3} owner: undo an audit entry (unmute, unban, restore a line) | |
| 16 | 19 | * {"type": "pause", "on": true|false} owner: maintenance; nobody new gets a turn |
| 17 | 20 | * {"type": "settings", "set": {…}} owner: any of src/admin.ts's settings |
| 18 | 21 | * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings |
| @@ -24,7 +27,7 @@ | ||
| 24 | 27 | * {"type": "history", "before": 12} anyone: up to HISTORY_PAGE lines older than that one |
| 25 | 28 | * Server → client: hello (who you are), state (the turn, the line, pause, the announcement and the speed cap), |
| 26 | 29 | * chat (the last CHAT_FIRST lines of the log, and whether there are more), history (an older page, the same way), |
| 27 | * said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: | |
| 30 | * said, unsaid, muted (owners only: the sanctions, the audit log, slow mode), admin (owners only: the settings and the admin log), crew (owners only: | |
| 28 | 31 | * settings, hidden lines, mute suggestions), banned and words (owners only), ping, error; and whatever the relay |
| 29 | 32 | * `publish`es to everyone: the arm's status, so a page needs this one socket for the pose, the chat and the queue. |
| 30 | 33 | */ |
| @@ -35,6 +38,7 @@ import WebSocket, { WebSocketServer } from "ws"; | ||
| 35 | 38 | import { Accounts, visitor, type Visitor } from "./accounts.ts"; |
| 36 | 39 | import { Admin, AdminError } from "./admin.ts"; |
| 37 | 40 | import { Chat, ChatError } from "./chat.ts"; |
| 41 | import { Moderation, ModerationError } from "./moderation.ts"; | |
| 38 | 42 | import { Moderator } from "./moderator.ts"; |
| 39 | 43 | import { WordFilter } from "./word-filter.ts"; |
| 40 | 44 | import { identify, LOCAL, type Person, type Who } from "./identity.ts"; |
| @@ -49,6 +53,9 @@ export interface LobbyOptions { | ||
| 49 | 53 | accounts?: Accounts; |
| 50 | 54 | /** The chat's file; none keeps it in memory. */ |
| 51 | 55 | chatFile?: string; |
| 56 | /** The mutes, bans, slow mode and audit log's file; none keeps them in memory. */ | |
| 57 | moderationFile?: string; | |
| 58 | moderation?: Moderation; | |
| 52 | 59 | /** The word filter's file; none keeps it in memory. */ |
| 53 | 60 | wordsFile?: string; |
| 54 | 61 | /** The admin settings' file; none keeps them in memory. */ |
| @@ -81,6 +88,7 @@ const USER_ID = /^[A-Za-z0-9_-]{1,64}$/; | ||
| 81 | 88 | export class Lobby { |
| 82 | 89 | readonly turns: Turns; |
| 83 | 90 | readonly chat: Chat; |
| 91 | readonly moderation: Moderation; | |
| 84 | 92 | readonly accounts: Accounts; |
| 85 | 93 | readonly admin: Admin; |
| 86 | 94 | readonly filter: WordFilter; |
| @@ -104,6 +112,7 @@ export class Lobby { | ||
| 104 | 112 | this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue }); |
| 105 | 113 | this.turns.setPaused(a.paused); |
| 106 | 114 | this.chat = options.chat ?? new Chat({ file: options.chatFile }); |
| 115 | this.moderation = options.moderation ?? new Moderation({ file: options.moderationFile }); | |
| 107 | 116 | this.accounts = options.accounts ?? new Accounts(); |
| 108 | 117 | this.filter = new WordFilter(options.wordsFile); |
| 109 | 118 | this.silentMs = options.silentMs ?? 15_000; |
| @@ -142,7 +151,7 @@ export class Lobby { | ||
| 142 | 151 | |
| 143 | 152 | /** Whether this person, or anyone where they are, is banned. The owner never is. */ |
| 144 | 153 | barred(who: Person, from: Visitor | null): boolean { |
| 145 | return !who.owner && !this.local && this.accounts.banned(who.id, who.name, from?.ip ?? null); | |
| 154 | return !who.owner && !this.local && (this.moderation.banned(who.id) || this.accounts.banned(who.id, who.name, from?.ip ?? null)); | |
| 146 | 155 | } |
| 147 | 156 | |
| 148 | 157 | /** Why this person may not command the arm right now, or null when they may (and then it counts as activity). */ |
| @@ -245,13 +254,14 @@ export class Lobby { | ||
| 245 | 254 | // ------------------------------------------------------------------ sockets |
| 246 | 255 | private seat(ws: WebSocket, who: Who, from: Visitor): void { |
| 247 | 256 | const seat: Seat = { ws, who, from, heard: Date.now() }; |
| 257 | if (who?.owner) this.moderation.noteOwner(who.id); | |
| 248 | 258 | this.seats.add(seat); |
| 249 | 259 | if (who) this.turns.connect(who.id); |
| 250 | 260 | this.send(seat, this.hello(seat)); |
| 251 | 261 | this.send(seat, this.state()); |
| 252 | 262 | this.send(seat, this.chatLog()); |
| 253 | 263 | if (who?.owner) { |
| 254 | this.send(seat, this.mutedList()); | |
| 264 | this.send(seat, this.modView()); | |
| 255 | 265 | this.send(seat, this.bannedList()); |
| 256 | 266 | this.send(seat, this.wordsList()); |
| 257 | 267 | this.send(seat, this.adminState()); |
| @@ -306,92 +316,115 @@ export class Lobby { | ||
| 306 | 316 | return; |
| 307 | 317 | case "post": { |
| 308 | 318 | if (!who.owner && typeof m.text === "string" && this.filter.blocks(m.text)) throw new ChatError("that word is not allowed here"); |
| 309 | const said = this.chat.post(who, m.text); | |
| 319 | const s = this.moderation.status(who.id); | |
| 320 | if (s) throw new ChatError("you are muted"); | |
| 321 | const said = this.chat.post(who, m.text, this.moderation.slowSeconds * 1000); | |
| 310 | 322 | this.broadcast({ type: "said", message: said }); |
| 311 | 323 | void this.moderator?.check(said); |
| 312 | 324 | return; |
| 313 | 325 | } |
| 314 | 326 | } |
| 315 | 327 | if (!who.owner) return this.send(seat, { type: "error", error: "only the owner can do that" }); |
| 316 | switch (m.type) { | |
| 317 | case "end": | |
| 318 | if (typeof m.id !== "string" || !USER_ID.test(m.id)) return this.send(seat, { type: "error", error: "end whom?" }); | |
| 319 | if (this.turns.isDriver(m.id)) return this.endTurn(who); | |
| 320 | if (this.turns.queue.some((p) => p.id === m.id)) this.admin.record(who, `took ${this.turns.queue.find((p) => p.id === m.id)!.name} out of the line`); | |
| 321 | this.turns.end(m.id); | |
| 322 | return; | |
| 323 | case "pause": | |
| 324 | if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" }); | |
| 325 | return this.configure(who, { paused: m.on }); | |
| 326 | case "settings": | |
| 327 | return this.configure(who, m.set); | |
| 328 | case "delete": | |
| 329 | if (!Number.isSafeInteger(m.id)) return this.send(seat, { type: "error", error: "delete which line?" }); | |
| 330 | if (this.chat.delete(m.id as number)) this.broadcast({ type: "unsaid", id: m.id }); | |
| 331 | return; | |
| 332 | case "words": { | |
| 333 | const words = this.filter.set(m.words); | |
| 334 | this.admin.record(who, `word filter → ${words.length} word${words.length === 1 ? "" : "s"}`); | |
| 335 | this.broadcastAdmin(); | |
| 336 | for (const s of this.seats) if (s.who?.owner) this.send(s, this.wordsList()); | |
| 337 | return; | |
| 338 | } | |
| 339 | case "mute": { | |
| 340 | if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "mute whom?" }); | |
| 341 | const id = m.id; | |
| 342 | 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; | |
| 343 | this.chat.mute(id, name, m.on); | |
| 344 | for (const s of this.seats) { | |
| 345 | if (s.who?.id === id) this.send(s, this.hello(s)); | |
| 346 | if (s.who?.owner) this.send(s, this.mutedList()); | |
| 328 | const by = { id: who.id, name: who.name }; | |
| 329 | const person = (): { id: string; name: string } => { | |
| 330 | if (typeof m.id !== "string" || !USER_ID.test(m.id)) throw new ChatError("whom?"); | |
| 331 | const id = m.id; | |
| 332 | 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.moderation.status(id)?.name ?? id; | |
| 333 | return { id, name }; | |
| 334 | }; | |
| 335 | const minutes = (): number | null => { | |
| 336 | if (m.minutes === undefined || m.minutes === null) return null; | |
| 337 | if (!Number.isSafeInteger(m.minutes)) throw new ChatError("minutes are a whole number"); | |
| 338 | return (m.minutes as number) * 60_000; | |
| 339 | }; | |
| 340 | try { | |
| 341 | switch (m.type) { | |
| 342 | case "end": { | |
| 343 | const target = person(); | |
| 344 | if (this.turns.isDriver(target.id)) return this.endTurn(who); | |
| 345 | if (this.turns.queue.some((p) => p.id === target.id)) this.admin.record(who, `took ${this.turns.queue.find((p) => p.id === target.id)!.name} out of the line`); | |
| 346 | this.turns.end(target.id); | |
| 347 | return; | |
| 347 | 348 | } |
| 348 | this.moderator?.muted(id); | |
| 349 | return; | |
| 350 | } | |
| 351 | case "ban": { | |
| 352 | if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "ban whom?" }); | |
| 353 | const id = m.id; | |
| 354 | if (m.on) { | |
| 355 | const target = [...this.seats].find((s) => s.who?.id === id); | |
| 356 | const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null); | |
| 357 | const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from; | |
| 358 | const person = known ?? (said ? { id, name: said.name, owner: false } : null); | |
| 359 | if (!person) return this.send(seat, { type: "error", error: "nobody here by that id" }); | |
| 360 | if (person.owner) return this.send(seat, { type: "error", error: "the owner cannot be banned" }); | |
| 361 | this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name); | |
| 362 | this.turns.end(id); // their turn ends, or they leave the line | |
| 363 | this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) }); | |
| 364 | this.admin.record(who, `banned ${person.name}`); | |
| 365 | } else { | |
| 366 | const name = this.accounts.bans().find((b) => b.id === id)?.name; | |
| 367 | if (!this.accounts.unban(id)) return this.send(seat, { type: "error", error: "not banned" }); | |
| 368 | this.admin.record(who, `unbanned ${name ?? id}`); | |
| 349 | case "pause": | |
| 350 | if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" }); | |
| 351 | return this.configure(who, { paused: m.on }); | |
| 352 | case "settings": | |
| 353 | return this.configure(who, m.set); | |
| 354 | case "delete": { | |
| 355 | if (!Number.isSafeInteger(m.id)) throw new ChatError("delete which line?"); | |
| 356 | const line = this.chat.messages.find((x) => x.id === m.id); | |
| 357 | if (line && this.chat.delete(line.id)) { | |
| 358 | this.moderation.removed(by, line); | |
| 359 | this.broadcast({ type: "unsaid", id: line.id }); | |
| 360 | this.tellOwners(); | |
| 361 | } | |
| 362 | return; | |
| 369 | 363 | } |
| 370 | this.broadcastAdmin(); | |
| 371 | for (const s of this.seats) { | |
| 372 | if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there | |
| 373 | if (s.who?.owner) this.send(s, this.bannedList()); | |
| 364 | case "words": { | |
| 365 | const words = this.filter.set(m.words); | |
| 366 | this.admin.record(who, `word filter → ${words.length} word${words.length === 1 ? "" : "s"}`); | |
| 367 | this.broadcastAdmin(); | |
| 368 | for (const s of this.seats) if (s.who?.owner) this.send(s, this.wordsList()); | |
| 369 | return; | |
| 374 | 370 | } |
| 375 | return; | |
| 376 | } | |
| 377 | case "crew": | |
| 378 | if (!this.moderator) return this.send(seat, { type: "error", error: "no moderator here" }); | |
| 379 | try { | |
| 380 | this.moderator.configure(m.settings); | |
| 381 | } catch (err) { | |
| 382 | this.send(seat, { type: "error", error: (err as Error).message }); | |
| 371 | case "mute": | |
| 372 | case "ban": { | |
| 373 | if (m.on === false) return this.lift(who, m.type === "ban" ? "ban" : "mute", person()); | |
| 374 | const target = person(); | |
| 375 | const ms = minutes(); | |
| 376 | this.moderation.sanction(by, m.type, target, ms); | |
| 377 | if (m.type === "ban") { | |
| 378 | // for good, the ban also bars their name and the address they were last seen at | |
| 379 | if (ms === null) this.accounts.ban({ ...target, owner: false }, [...this.seats].find((s) => s.who?.id === target.id)?.from ?? null, by.name); | |
| 380 | this.admin.record(who, `banned ${target.name}`); | |
| 381 | this.broadcast({ type: "said", message: this.chat.system(`${target.name} was banned`) }); | |
| 382 | this.broadcastAdmin(); | |
| 383 | } | |
| 384 | this.moderator?.muted(target.id); | |
| 385 | this.sanctioned(target.id); | |
| 386 | return; | |
| 383 | 387 | } |
| 384 | return; | |
| 385 | case "restore": { | |
| 386 | const back = Number.isSafeInteger(m.id) ? this.moderator?.restore(m.id as number) : null; | |
| 387 | if (!back) return this.send(seat, { type: "error", error: "that line is not in the log" }); | |
| 388 | this.chat.restore(back); | |
| 389 | this.broadcast(this.chatLog()); | |
| 390 | return; | |
| 388 | case "unmute": | |
| 389 | case "unban": | |
| 390 | return this.lift(who, m.type === "unban" ? "ban" : "mute", person()); | |
| 391 | case "slow": | |
| 392 | this.moderation.setSlow(by, m.seconds); | |
| 393 | this.tellOwners(); | |
| 394 | return; | |
| 395 | case "undo": { | |
| 396 | if (!Number.isSafeInteger(m.entry)) throw new ChatError("undo which entry?"); | |
| 397 | const { entry, restore } = this.moderation.undo(by, m.entry as number); | |
| 398 | if (restore && this.chat.restore(restore)) this.broadcast(this.chatLog()); | |
| 399 | if (entry.target) { | |
| 400 | if (!this.moderation.banned(entry.target.id)) this.accounts.unban(entry.target.id); | |
| 401 | this.sanctioned(entry.target.id); | |
| 402 | } | |
| 403 | else this.tellOwners(); | |
| 404 | return; | |
| 405 | } | |
| 406 | case "crew": | |
| 407 | if (!this.moderator) return this.send(seat, { type: "error", error: "no moderator here" }); | |
| 408 | try { | |
| 409 | this.moderator.configure(m.settings); | |
| 410 | } catch (err) { | |
These protocol messages (minutes, slow, undo) have no counterpart in src/tty.ts, so the terminal door cannot do what the page can. |
||
| 411 | this.send(seat, { type: "error", error: (err as Error).message }); | |
| 412 | } | |
| 413 | return; | |
| 414 | case "restore": { | |
| 415 | const back = Number.isSafeInteger(m.id) ? this.moderator?.restore(m.id as number) : null; | |
| 416 | if (!back) return this.send(seat, { type: "error", error: "that line is not in the log" }); | |
| 417 | this.chat.restore(back); | |
| 418 | this.broadcast(this.chatLog()); | |
| 419 | return; | |
| 420 | } | |
| 421 | case "dismiss": | |
| 422 | if (Number.isSafeInteger(m.id)) this.moderator?.dismiss(m.id as number); | |
| 423 | return; | |
| 391 | 424 | } |
| 392 | case "dismiss": | |
| 393 | if (Number.isSafeInteger(m.id)) this.moderator?.dismiss(m.id as number); | |
| 394 | return; | |
| 425 | } catch (err) { | |
| 426 | if (err instanceof ModerationError) throw new ChatError(err.message); | |
| 427 | throw err; | |
| 395 | 428 | } |
| 396 | 429 | this.send(seat, { type: "error", error: "unknown request" }); |
| 397 | 430 | } |
| @@ -423,6 +456,11 @@ export class Lobby { | ||
| 423 | 456 | for (const s of this.seats) if (s.who?.owner && s.ws.readyState === WebSocket.OPEN) s.ws.send(text); |
| 424 | 457 | } |
| 425 | 458 | |
| 459 | private modView() { | |
| 460 | const view = this.moderation.view(); | |
| 461 | return { type: "muted", ...view, muted: view.sanctions.filter((x) => x.kind === "mute").map(({ id, name }) => ({ id, name })) }; | |
| 462 | } | |
| 463 | ||
| 426 | 464 | /** What the crew did, for the owners: its settings, the lines it hid, and who it suggests muting. */ |
| 427 | 465 | private crewState() { |
| 428 | 466 | const m = this.moderator; |
| @@ -430,12 +468,16 @@ export class Lobby { | ||
| 430 | 468 | } |
| 431 | 469 | |
| 432 | 470 | private tellOwners(): void { |
| 433 | for (const s of this.seats) if (s.who?.owner) this.send(s, this.crewState()); | |
| 471 | for (const s of this.seats) { | |
| 472 | if (!s.who?.owner) continue; | |
| 473 | this.send(s, this.modView()); | |
| 474 | this.send(s, this.crewState()); | |
| 475 | } | |
| 434 | 476 | } |
| 435 | 477 | |
| 436 | 478 | private hello(seat: Seat) { |
| 437 | 479 | const who = seat.who; |
| 438 | return { type: "hello", you: who, signin: !this.local, muted: who ? this.chat.muted.has(who.id) : false, banned: who ? this.barred(who, seat.from) : false }; | |
| 480 | return { type: "hello", you: who, signin: !this.local, muted: who ? this.moderation.muted(who.id) : false, banned: who ? this.barred(who, seat.from) : false }; | |
| 439 | 481 | } |
| 440 | 482 | |
| 441 | 483 | private bannedList() { |
| @@ -446,8 +488,24 @@ export class Lobby { | ||
| 446 | 488 | return { type: "words", words: this.filter.words }; |
| 447 | 489 | } |
| 448 | 490 | |
| 449 | private mutedList() { | |
| 450 | return { type: "muted", muted: [...this.chat.muted].map(([id, name]) => ({ id, name })) }; | |
| 491 | private lift(by: Person, kind: "mute" | "ban", target: { id: string; name: string }): void { | |
| 492 | this.moderation.lift(by, kind, target.id); | |
| 493 | if (kind === "ban") { | |
| 494 | this.accounts.unban(target.id); | |
| 495 | this.admin.record(by, `unbanned ${target.name}`); | |
| 496 | this.broadcastAdmin(); | |
| 497 | } | |
| 498 | this.sanctioned(target.id); | |
| 499 | } | |
| 500 | ||
| 501 | /** Someone's standing changed: they hear it, and a ban also takes them out of the queue. */ | |
| 502 | private sanctioned(id: string): void { | |
| 503 | if (this.moderation.banned(id) || this.accounts.bans().some((b) => b.id === id)) this.turns.end(id, "banned"); | |
| 504 | for (const s of this.seats) { | |
| 505 | if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there | |
| 506 | if (s.who?.owner) this.send(s, this.bannedList()); | |
| 507 | } | |
| 508 | this.tellOwners(); | |
| 451 | 509 | } |
| 452 | 510 | |
| 453 | 511 | private ping(): void { |
Software/so101/src/moderation.html added +59
| @@ -0,0 +1,59 @@ | ||
| 1 | ||
| 2 | <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"> | |
| 3 | <title>Moderation</title> | |
| 4 | <style> | |
| 5 | body { font: 14px system-ui, sans-serif; margin: 1.5rem auto; max-width: 52rem; padding: 0 1rem; color: #222; } | |
| 6 | h1 { font-size: 1.2rem; } h2 { font-size: 1rem; margin-top: 1.5rem; } | |
| 7 | table { border-collapse: collapse; width: 100%; } td, th { text-align: left; padding: .25rem .5rem; border-bottom: 1px solid #ddd; } | |
| 8 | .undone { color: #888; text-decoration: line-through; } .note { color: #666; } | |
| 9 | button { cursor: pointer; min-height: 44px; padding: 0 .9rem; font: inherit; } | |
| 10 | input { min-height: 44px; font: inherit; } .scroll { overflow-x: auto; } | |
| 11 | </style></head> | |
| 12 | <body> | |
| 13 | <h1>Moderation</h1> | |
| 14 | <p id="status" class="note">connecting…</p> | |
| 15 | <noscript><p class="note">This page needs JavaScript to show and change anything.</p></noscript> | |
| 16 | <h2>Slow mode</h2> | |
| 17 | <p><label>Seconds between one person's messages (0 is off): <input id="slow" type="number" min="0" max="3600" value="0" style="width:5rem"></label> <button id="setSlow">Set</button></p> | |
| 18 | <h2>Muted and banned</h2> | |
| 19 | <div class="scroll"><table id="sanctions" aria-label="Muted and banned"></table></div> | |
| 20 | <h2>Audit log</h2> | |
| 21 | <div class="scroll"><table id="audit" aria-label="Audit log"></table></div> | |
| 22 | <script> | |
| 23 | const $ = (id) => document.getElementById(id); | |
| 24 | const cell = (text) => { const td = document.createElement("td"); td.textContent = text; return td; }; | |
| 25 | let ws, state = null; | |
| 26 | const say = (m) => ws && ws.readyState === 1 && ws.send(JSON.stringify(m)); | |
| 27 | const button = (label, fn) => { const b = document.createElement("button"); b.textContent = label; b.onclick = fn; return b; }; | |
| 28 | function draw() { | |
| 29 | if (!state) return; | |
| 30 | if (document.activeElement !== $("slow")) $("slow").value = state.slowSeconds; | |
| 31 | $("sanctions").replaceChildren(...state.sanctions.map((s) => { | |
| 32 | const tr = document.createElement("tr"); | |
| 33 | const action = button(s.kind === "ban" ? "unban" : "unmute", () => say({ type: s.kind === "ban" ? "unban" : "unmute", id: s.id })); | |
| 34 | const td = document.createElement("td"); td.append(action); | |
| 35 | tr.append(cell(s.name), cell(s.kind), cell(s.until === null ? "for good" : "until " + new Date(s.until).toLocaleString()), td); | |
| 36 | return tr; | |
| 37 | })); | |
| 38 | if (!state.sanctions.length) $("sanctions").replaceChildren(cell("nobody")); | |
| 39 | $("audit").replaceChildren(...state.audit.map((e) => { | |
| 40 | const tr = document.createElement("tr"); if (e.undone) tr.className = "undone"; | |
| 41 | const td = document.createElement("td"); if (!e.undone) td.append(button("undo", () => say({ type: "undo", entry: e.id }))); | |
| 42 | tr.append(cell(new Date(e.at).toLocaleString()), cell(e.by.name), cell(e.action), cell(e.target ? e.target.name : ""), cell(e.detail), td); | |
| 43 | return tr; | |
| 44 | })); | |
| 45 | } | |
| 46 | $("setSlow").onclick = () => say({ type: "slow", seconds: Number($("slow").value) }); | |
| 47 | function connect() { | |
| 48 | ws = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/live"); | |
| 49 | ws.onmessage = (e) => { | |
| 50 | const m = JSON.parse(e.data); | |
| 51 | if (m.type === "muted") { state = m; $("status").textContent = ""; draw(); } | |
| 52 | else if (m.type === "error") $("status").textContent = m.error; | |
| 53 | else if (m.type === "ping") say({ type: "pong" }); | |
| 54 | }; | |
| 55 | ws.onclose = () => { $("status").textContent = "disconnected; retrying"; setTimeout(connect, 1500); }; | |
| 56 | } | |
| 57 | connect(); | |
| 58 | </script> | |
| 59 | </body></html> |
Software/so101/src/moderation.test.ts added +122
| @@ -0,0 +1,122 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, writeFileSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { Moderation, ModerationError } from "./moderation.ts"; | |
| 6 | ||
| 7 | const boss = { id: "boss", name: "boss" }; | |
| 8 | const ann = { id: "ann", name: "ann" }; | |
| 9 | const MIN = 60_000; | |
| 10 | ||
| 11 | function make(file?: string) { | |
| 12 | const t = { now: 1_000_000 }; | |
| 13 | return { t, m: new Moderation({ file, now: () => t.now }) }; | |
| 14 | } | |
| 15 | ||
| 16 | describe("moderation", () => { | |
| 17 | test("a timed mute runs out", () => { | |
| 18 | const { t, m } = make(); | |
| 19 | m.sanction(boss, "mute", ann, 10 * MIN); | |
| 20 | expect(m.muted("ann")).toBe(true); | |
| 21 | t.now += 10 * MIN; | |
| 22 | expect(m.muted("ann")).toBe(false); | |
| 23 | }); | |
| 24 | ||
| 25 | test("a ban lasts from a minute to a year, or for good", () => { | |
| 26 | const { m } = make(); | |
| 27 | expect(() => m.sanction(boss, "ban", ann, 1000)).toThrow(ModerationError); | |
| 28 | expect(() => m.sanction(boss, "ban", ann, 367 * 86_400_000)).toThrow(ModerationError); | |
| 29 | m.sanction(boss, "ban", ann, 366 * 86_400_000); | |
| 30 | m.sanction(boss, "ban", ann, null); | |
| 31 | expect(m.banned("ann")).toBe(true); | |
| 32 | }); | |
| 33 | ||
| 34 | test("a mute never replaces a ban; you cannot sanction yourself or an owner", () => { | |
| 35 | const { m } = make(); | |
| 36 | m.sanction(boss, "ban", ann, null); | |
| 37 | expect(() => m.sanction(boss, "mute", ann, null)).toThrow("banned already"); | |
| 38 | expect(() => m.sanction(boss, "mute", boss, null)).toThrow("yourself"); | |
| 39 | m.noteOwner("ann2"); | |
| 40 | expect(() => m.sanction(boss, "ban", { id: "ann2", name: "x" }, null)).toThrow("owner"); | |
| 41 | }); | |
| 42 | ||
| 43 | test("undo of an unmute restores the timed mute, not a permanent one", () => { | |
| 44 | const { t, m } = make(); | |
| 45 | m.sanction(boss, "mute", ann, 10 * MIN); | |
| 46 | const lift = m.lift(boss, "mute", "ann"); | |
| 47 | t.now += 2 * MIN; | |
| 48 | m.undo(boss, lift.id); | |
| 49 | expect(m.status("ann")?.until).toBe(1_000_000 + 10 * MIN); | |
| 50 | t.now += 8 * MIN; | |
| 51 | expect(m.muted("ann")).toBe(false); | |
| 52 | }); | |
| 53 | ||
| 54 | test("undo of an unmute after the mute would have run out restores nothing", () => { | |
| 55 | const { t, m } = make(); | |
| 56 | m.sanction(boss, "mute", ann, 10 * MIN); | |
| 57 | const lift = m.lift(boss, "mute", "ann"); | |
| 58 | t.now += 11 * MIN; | |
| 59 | expect(() => m.undo(boss, lift.id)).toThrow("run out"); | |
| 60 | expect(m.muted("ann")).toBe(false); | |
| 61 | }); | |
| 62 | ||
| 63 | test("undo of an unmute does not stack on a newer sanction", () => { | |
| 64 | const { m } = make(); | |
| 65 | m.sanction(boss, "mute", ann, 10 * MIN); | |
| 66 | const lift = m.lift(boss, "mute", "ann"); | |
| 67 | m.sanction(boss, "mute", ann, null); | |
| 68 | expect(() => m.undo(boss, lift.id)).toThrow("again"); | |
| 69 | expect(m.status("ann")?.until).toBeNull(); | |
| 70 | }); | |
| 71 | ||
| 72 | test("undoing an older mute leaves the newer one", () => { | |
| 73 | const { m } = make(); | |
| 74 | const first = m.sanction(boss, "mute", ann, 10 * MIN); | |
| 75 | m.sanction(boss, "mute", ann, null); | |
| 76 | m.undo(boss, first.id); | |
| 77 | expect(m.status("ann")?.until).toBeNull(); | |
| 78 | }); | |
| 79 | ||
| 80 | test("undoing the mute that is current lifts it, once", () => { | |
| 81 | const { m } = make(); | |
| 82 | const e = m.sanction(boss, "mute", ann, null); | |
| 83 | m.undo(boss, e.id); | |
| 84 | expect(m.muted("ann")).toBe(false); | |
| 85 | expect(() => m.undo(boss, e.id)).toThrow("already undone"); | |
| 86 | }); | |
| 87 | ||
| 88 | test("slow mode is bounded and undoable", () => { | |
| 89 | const { m } = make(); | |
| 90 | expect(() => m.setSlow(boss, -1)).toThrow(ModerationError); | |
| 91 | expect(() => m.setSlow(boss, 1.5)).toThrow(ModerationError); | |
| 92 | const e = m.setSlow(boss, 5); | |
| 93 | m.undo(boss, e.id); | |
| 94 | expect(m.slowSeconds).toBe(0); | |
| 95 | }); | |
| 96 | ||
| 97 | test("it survives a restart, and a hand-edited file only loses what is invalid", () => { | |
| 98 | const file = join(mkdtempSync(join(tmpdir(), "mod-")), "moderation.json"); | |
| 99 | const a = make(file); | |
| 100 | a.m.sanction(boss, "ban", ann, null); | |
| 101 | a.m.noteOwner("boss"); | |
| 102 | const b = make(file); | |
| 103 | expect(b.m.banned("ann")).toBe(true); | |
| 104 | expect(b.m.owners.has("boss")).toBe(true); | |
| 105 | ||
| 106 | writeFileSync(file, JSON.stringify({ | |
| 107 | owners: ["ok", 5], | |
| 108 | sanctions: { good: { name: "g", kind: "mute", until: null }, bad: { name: "b", kind: "kick", until: null }, worse: 7, nan: { name: "n", kind: "ban", until: "soon" } }, | |
| 109 | audit: [{ id: 4, at: 1, action: "slow", target: null, detail: "" }, { id: "x" }, null], | |
| 110 | slowSeconds: 1.5, | |
| 111 | })); | |
| 112 | const c = make(file); | |
| 113 | expect([...c.m.sanctions.keys()]).toEqual(["good"]); | |
| 114 | expect([...c.m.owners]).toEqual(["ok"]); | |
| 115 | expect(c.m.audit.length).toBe(1); | |
| 116 | expect(c.m.slowSeconds).toBe(0); | |
| 117 | expect(c.m.setSlow(boss, 3).id).toBe(5); | |
| 118 | ||
| 119 | writeFileSync(file, "{not json"); | |
| 120 | expect(make(file).m.sanctions.size).toBe(0); | |
| 121 | }); | |
| 122 | }); |
Software/so101/src/moderation.ts added +211
| @@ -0,0 +1,211 @@ | ||
| 1 | /** | |
| 2 | * Who may not take part, and the record of it. A mute stops chat for a time or for good; a ban stops chat and the | |
| 3 | * queue (the person can still watch). Removing a chat line is recorded too, with the line, so it can be restored. | |
| 4 | * Every action lands in the audit log (the last `KEEP_AUDIT`), and each one can be undone once. Slow mode, the | |
| 5 | * seconds a person waits between messages, lives here as well. Kept in one JSON file, rewritten whole on change. | |
| 6 | */ | |
| 7 | ||
| 8 | import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 9 | import { dirname } from "node:path"; | |
| 10 | import type { Message } from "./chat.ts"; | |
| 11 | ||
| 12 | export const KEEP_AUDIT = 200; | |
| 13 | export const MAX_SLOW_SECONDS = 3600; | |
| 14 | ||
| 15 | export type Kind = "mute" | "ban"; | |
| 16 | ||
| 17 | export interface Sanction { | |
| 18 | name: string; | |
| 19 | kind: Kind; | |
| 20 | /** Epoch ms it lifts, or null for good. */ | |
| 21 | until: number | null; | |
| 22 | /** The audit entry that set it, so undoing an older entry leaves a newer sanction alone. */ | |
| 23 | entry?: number; | |
| 24 | } | |
| 25 | ||
| 26 | export interface AuditEntry { | |
| 27 | id: number; | |
| 28 | at: number; | |
| 29 | by: { id: string; name: string }; | |
| 30 | action: "mute" | "ban" | "unmute" | "unban" | "remove" | "slow"; | |
| 31 | /** The person, or for `remove` the author of the line. */ | |
| 32 | target: { id: string; name: string } | null; | |
| 33 | /** Human words: "10 min", "for good", "5 s". */ | |
| 34 | detail: string; | |
| 35 | /** For `remove`, the line, to restore. */ | |
| 36 | message?: Message; | |
| 37 | /** Epoch ms of the undo, once undone. */ | |
| 38 | undone?: number; | |
| 39 | /** For `slow`, the value to go back to. */ | |
| 40 | previous?: number; | |
| 41 | /** For `unmute`/`unban`, the sanction that was lifted, to put back as it was. */ | |
| 42 | was?: Sanction; | |
| 43 | } | |
| 44 | ||
| 45 | export class ModerationError extends Error {} | |
| 46 | ||
| 47 | export interface ModerationOptions { | |
| 48 | file?: string; | |
| 49 | now?: () => number; | |
| 50 | } | |
| 51 | ||
| 52 | const describe = (ms: number | null): string => { | |
| 53 | if (ms === null) return "for good"; | |
| 54 | const min = Math.round(ms / 60_000); | |
| 55 | return min % 1440 === 0 ? `${min / 1440} d` : min % 60 === 0 ? `${min / 60} h` : `${min} min`; | |
| 56 | }; | |
| 57 | ||
| 58 | export class Moderation { | |
| 59 | readonly sanctions = new Map<string, Sanction>(); | |
| 60 | audit: AuditEntry[] = []; | |
| 61 | /** Everyone ever seen as an owner: they cannot be muted or banned, connected or not. */ | |
| 62 | readonly owners = new Set<string>(); | |
| 63 | /** Seconds between one person's messages; 0 is the chat's own floor. */ | |
| 64 | slowSeconds = 0; | |
| 65 | private next = 1; | |
| 66 | private readonly file: string | undefined; | |
| 67 | private readonly now: () => number; | |
| 68 | ||
| 69 | constructor(options: ModerationOptions = {}) { | |
| 70 | this.file = options.file; | |
| 71 | this.now = options.now ?? Date.now; | |
| 72 | if (this.file) this.load(this.file); | |
| 73 | } | |
| 74 | ||
| 75 | /** The sanction on this person now, if any; one that has run out is dropped. */ | |
| 76 | status(id: string): Sanction | null { | |
| 77 | const s = this.sanctions.get(id); | |
| 78 | if (!s) return null; | |
| 79 | if (s.until !== null && s.until <= this.now()) { | |
| 80 | this.sanctions.delete(id); | |
| 81 | this.save(); | |
| 82 | return null; | |
| 83 | } | |
| 84 | return s; | |
| 85 | } | |
| 86 | ||
| 87 | noteOwner(id: string): void { | |
| 88 | if (this.owners.has(id)) return; | |
| 89 | this.owners.add(id); | |
| 90 | this.save(); | |
| 91 | } | |
| 92 | ||
| 93 | muted(id: string): boolean { | |
| 94 | return this.status(id) !== null; | |
| 95 | } | |
| 96 | ||
| 97 | banned(id: string): boolean { | |
| 98 | return this.status(id)?.kind === "ban"; | |
| 99 | } | |
| 100 | ||
| 101 | /** Mute or ban for `ms` (null: for good). A ban outranks a mute; a mute never replaces a ban. */ | |
| 102 | sanction(by: AuditEntry["by"], kind: Kind, target: { id: string; name: string }, ms: number | null): AuditEntry { | |
| 103 | if (ms !== null && (!Number.isSafeInteger(ms) || ms < 60_000 || ms > 366 * 86_400_000)) throw new ModerationError("for a minute up to a year, or for good"); | |
| 104 | if (target.id === by.id) throw new ModerationError("not yourself"); | |
| 105 | if (kind === "mute" && this.banned(target.id)) throw new ModerationError(`${target.name} is banned already`); | |
| 106 | if (this.owners.has(target.id)) throw new ModerationError("not the owner"); | |
| 107 | const until = ms === null ? null : this.now() + ms; | |
| 108 | const entry = this.record({ by, action: kind, target, detail: describe(ms) }); | |
| 109 | this.sanctions.set(target.id, { name: target.name, kind, until, entry: entry.id }); | |
| 110 | this.save(); | |
| 111 | return entry; | |
| 112 | } | |
| 113 | ||
| 114 | /** Lift a mute or ban by hand. */ | |
| 115 | lift(by: AuditEntry["by"], kind: Kind, id: string): AuditEntry { | |
| 116 | const s = this.status(id); | |
| 117 | if (!s || s.kind !== kind) throw new ModerationError(`not ${kind === "ban" ? "banned" : "muted"}`); | |
| 118 | this.sanctions.delete(id); | |
| 119 | return this.record({ by, action: kind === "ban" ? "unban" : "unmute", target: { id, name: s.name }, detail: "", was: { ...s } }); | |
| 120 | } | |
| 121 | ||
| 122 | removed(by: AuditEntry["by"], message: Message): AuditEntry { | |
| 123 | return this.record({ by, action: "remove", target: message.from, detail: message.text.slice(0, 80), message }); | |
| 124 | } | |
| 125 | ||
| 126 | setSlow(by: AuditEntry["by"], seconds: unknown): AuditEntry { | |
| 127 | if (!Number.isSafeInteger(seconds) || (seconds as number) < 0 || (seconds as number) > MAX_SLOW_SECONDS) throw new ModerationError(`0 to ${MAX_SLOW_SECONDS} seconds`); | |
| 128 | const previous = this.slowSeconds; | |
| 129 | this.slowSeconds = seconds as number; | |
| 130 | return this.record({ by, action: "slow", target: null, detail: `${seconds} s`, previous }); | |
| 131 | } | |
| 132 | ||
| 133 | /** Undo one entry, once. Returns what to do beyond the bookkeeping: put a line back. */ | |
| 134 | undo(by: AuditEntry["by"], id: number): { entry: AuditEntry; restore?: Message } { | |
| 135 | const entry = this.audit.find((e) => e.id === id); | |
| 136 | if (!entry) throw new ModerationError("no such entry"); | |
| 137 | if (entry.undone) throw new ModerationError("already undone"); | |
| 138 | let restore: Message | undefined; | |
| 139 | switch (entry.action) { | |
| 140 | case "mute": | |
| 141 | case "ban": | |
| 142 | // Only the sanction this entry set; a newer one stays. | |
| 143 | if (this.sanctions.get(entry.target!.id)?.entry === entry.id) this.sanctions.delete(entry.target!.id); | |
| 144 | break; | |
| 145 | case "unmute": | |
| 146 | case "unban": { | |
| 147 | const was = entry.was; | |
| 148 | if (!was || (was.until !== null && was.until <= this.now())) throw new ModerationError("it has run out already"); | |
| 149 | if (this.status(entry.target!.id)) throw new ModerationError("they are sanctioned again; lift that first"); | |
| 150 | this.sanctions.set(entry.target!.id, { ...was }); | |
| 151 | break; | |
| 152 | } | |
| 153 | case "remove": | |
| 154 | restore = entry.message; | |
| 155 | break; | |
| 156 | case "slow": | |
| 157 | this.slowSeconds = entry.previous ?? 0; | |
| 158 | break; | |
| 159 | } | |
| 160 | entry.undone = this.now(); | |
| 161 | this.record({ by, action: entry.action, target: entry.target, detail: `undo #${id}` }, true); | |
| 162 | this.save(); | |
| 163 | return { entry, restore }; | |
| 164 | } | |
| 165 | ||
| 166 | view() { | |
| 167 | for (const id of [...this.sanctions.keys()]) this.status(id); | |
| 168 | return { | |
| 169 | slowSeconds: this.slowSeconds, | |
| 170 | sanctions: [...this.sanctions].map(([id, s]) => ({ id, ...s })), | |
| 171 | audit: this.audit.slice().reverse(), | |
| 172 | }; | |
| 173 | } | |
| 174 | ||
| 175 | private record(entry: Omit<AuditEntry, "id" | "at">, undoing = false): AuditEntry { | |
| 176 | const full: AuditEntry = { id: this.next++, at: this.now(), ...entry }; | |
| 177 | // An undo is itself logged, but only as a note: it has nothing left to undo. | |
| 178 | if (undoing) full.undone = full.at; | |
| 179 | this.audit.push(full); | |
| 180 | if (this.audit.length > KEEP_AUDIT) this.audit.splice(0, this.audit.length - KEEP_AUDIT); | |
| 181 | this.save(); | |
| 182 | return full; | |
| 183 | } | |
| 184 | ||
| 185 | private load(file: string): void { | |
| 186 | let stored: { owners?: unknown; sanctions?: unknown; audit?: unknown; slowSeconds?: unknown }; | |
| 187 | try { | |
| 188 | stored = JSON.parse(readFileSync(file, "utf8")); | |
| 189 | } catch { | |
| 190 | return; | |
| 191 | } | |
| 192 | if (stored.sanctions && typeof stored.sanctions === "object") { | |
| 193 | for (const [id, s] of Object.entries(stored.sanctions as Record<string, Sanction>)) { | |
| 194 | if ((s?.kind === "mute" || s?.kind === "ban") && typeof s.name === "string" && (s.until === null || typeof s.until === "number")) { | |
| 195 | this.sanctions.set(id, { name: s.name, kind: s.kind, until: s.until, ...(Number.isSafeInteger(s.entry) ? { entry: s.entry } : {}) }); | |
| 196 | } | |
| 197 | } | |
| 198 | } | |
| 199 | if (Array.isArray(stored.owners)) for (const id of stored.owners) if (typeof id === "string") this.owners.add(id); | |
| 200 | if (Array.isArray(stored.audit)) this.audit = stored.audit.filter((e): e is AuditEntry => typeof e?.id === "number" && typeof e.at === "number" && typeof e.action === "string").slice(-KEEP_AUDIT); | |
| 201 | if (Number.isSafeInteger(stored.slowSeconds)) this.slowSeconds = stored.slowSeconds as number; | |
| 202 | this.next = Math.max(0, ...this.audit.map((e) => e.id)) + 1; | |
| 203 | } | |
| 204 | ||
| 205 | private save(): void { | |
| 206 | if (!this.file) return; | |
| 207 | mkdirSync(dirname(this.file), { recursive: true }); | |
| 208 | writeFileSync(`${this.file}.tmp`, JSON.stringify({ owners: [...this.owners], sanctions: Object.fromEntries(this.sanctions), audit: this.audit, slowSeconds: this.slowSeconds })); | |
| 209 | renameSync(`${this.file}.tmp`, this.file); | |
| 210 | } | |
| 211 | } |
Software/so101/src/relay.ts +8
| @@ -30,6 +30,7 @@ | ||
| 30 | 30 | * |
| 31 | 31 | * The owner's speed cap (src/speed-cap.ts) is applied here too, to moves, poses, grips, playbacks and every stream frame. |
| 32 | 32 | * |
| 33 | * GET /moderation the moderation page (the owner's; the data itself comes over /live) | |
| 33 | 34 | * WS /live the lobby: the turn, the queue, the chat, and the arm's /status pushed when it changes |
| 34 | 35 | * WS /machine read-only, for anyone: the arm's raw status, the link's round trip and frame rate, and every |
| 35 | 36 | * command in and out with every safety clamp, pushed as it happens (src/machine-feed.ts) |
| @@ -223,6 +224,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 223 | 224 | const followEveryMs = options.followEveryMs ?? 5000; |
| 224 | 225 | const readTimeoutMs = options.readTimeoutMs ?? 2500; |
| 225 | 226 | const lobby = options.lobby ?? null; |
| 227 | const moderationPage = readFileSync(new URL("./moderation.html", import.meta.url), "utf8"); | |
| 226 | 228 | const heartbeatMs = options.heartbeatMs ?? 1000; |
| 227 | 229 | const cameras = options.cameras ?? new CameraHub({ feed: options.camera, seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] }); |
| 228 | 230 | const leaders = options.leaders ?? new LeaderCalibrations(); |
| @@ -616,6 +618,12 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 616 | 618 | if (refused) return json(res, refused.status, { error: refused.error }); |
| 617 | 619 | by = who!.name; |
| 618 | 620 | } |
| 621 | if (lobby && url.pathname === "/moderation") { | |
| 622 | if (req.method !== "GET") return json(res, 405, { error: "read-only" }); | |
| 623 | if (!lobby.who(req)?.owner) return json(res, 403, { error: "only the owner may moderate" }); | |
| 624 | res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); | |
| 625 | return res.end(moderationPage); | |
| 626 | } | |
| 619 | 627 | if (req.method === "GET" && url.pathname === "/link") return json(res, 200, link()); |
| 620 | 628 | if (req.method === "GET" && url.pathname === "/status") return await status(res, path); |
| 621 | 629 |
Software/so101/src/terminal.test.ts +1 −1
| @@ -268,7 +268,7 @@ describe("terminal door", () => { | ||
| 268 | 268 | await bob.printedLine(/^alice: first$/); |
| 269 | 269 | bob.door.input("/mute alice"); |
| 270 | 270 | await bob.printedLine(/^error: only the owner can do that$/); |
| 271 | expect(lobby!.chat.muted.has("u-alice")).toBe(false); | |
| 271 | expect(lobby!.moderation.muted("u-alice")).toBe(false); | |
| 272 | 272 | |
| 273 | 273 | const owner = await terminal(port, ttyEnv("u-owner", "trevato", "admin")); |
| 274 | 274 | expect(owner.door.room.you?.owner).toBe(true); |
Software/so101/src/turns.ts +3 −3
| @@ -21,7 +21,7 @@ export interface Turn extends Person { | ||
| 21 | 21 | bonusMs: number; |
| 22 | 22 | } |
| 23 | 23 | |
| 24 | export type EndReason = "handed back" | "time is up" | "idle" | "not ready" | "disconnected" | "ended by the owner" | "taken over by the owner" | "paused for maintenance"; | |
| 24 | export type EndReason = "handed back" | "time is up" | "idle" | "not ready" | "disconnected" | "ended by the owner" | "banned" | "taken over by the owner" | "paused for maintenance"; | |
| 25 | 25 | |
| 26 | 26 | export type TurnEvent = { kind: "turn"; ended: { who: Person; reason: EndReason } | null; started: Person | null } | { kind: "queue" }; |
| 27 | 27 | |
| @@ -131,8 +131,8 @@ export class Turns { | ||
| 131 | 131 | } |
| 132 | 132 | |
| 133 | 133 | /** The owner ends someone's turn, or takes them out of the line. */ |
| 134 | end(id: string): void { | |
| 135 | if (this.isDriver(id)) return this.handOver("ended by the owner"); | |
| 134 | end(id: string, reason: EndReason = "ended by the owner"): void { | |
| 135 | if (this.isDriver(id)) return this.handOver(reason); | |
| 136 | 136 | if (this.remove(id)) this.emit({ kind: "queue" }); |
| 137 | 137 | } |
| 138 | 138 |
Software/so101/src/viewer.html +1 −1
| @@ -390,7 +390,7 @@ | ||
| 390 | 390 | </div> |
| 391 | 391 | <div class="card" id="adminBar"> |
| 392 | 392 | <h3>Queue and turns</h3> |
| 393 | <div class="row"><button id="pauseBtn"></button><a href="/admin">Admin page</a></div> | |
| 393 | <div class="row"><button id="pauseBtn"></button><a href="/admin">Admin page</a><a href="/moderation">Moderation page</a></div> | |
| 394 | 394 | <form id="adminForm"> |
| 395 | 395 | <label>Turn length, s<input name="turnSeconds" type="number" inputmode="numeric" min="30" max="3600" step="1" required></label> |
| 396 | 396 | <label>Idle timeout, s<input name="idleSeconds" type="number" inputmode="numeric" min="10" max="600" step="1" required></label> |
new above
offline
This menu is not in the viewer (the pull says it was dropped). Document what exists, or restore it.