Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
Moderation: ban and mute users (for a time or for good), remove messages, slow mode - from the chat itself and the admin page #23
smith/arm:smith/13-moderation-ban-and-mute-users-for-a-time → main 6 commits fork 7 threads · 7 unresolved
Software/README.md +23 −2
| @@ -276,8 +276,29 @@ its live pose and the cameras. Driving needs a forge account and a turn. | ||
| 276 | 276 | Settings and log: `$FORGE_APP_DATA/so101/crew.json`. |
| 277 | 277 | - The owner (anyone who may write this repository) can take control at |
| 278 | 278 | any time (this skips the queue), end anyone's turn, take people out of |
| 279 | the queue, delete messages and mute people. The owner can also press | |
| 280 | **Stop** during anyone's turn. | |
| 279 | the queue and delete messages. The owner can also press **Stop** during | |
| 280 | anyone's turn. | |
| 281 | - Moderation, owner only (every request is checked on the server against the | |
| 282 | signed identity). Owners see a **Moderation page** link under the queue in | |
| 283 | the viewer; it is `/moderation` on the same address (`/admin` is the arm controls below), and anyone else gets 403. | |
| 284 | - A ⋯ menu on every chat line (always shown, so it works on a phone): | |
| 285 | remove the message, or mute its author for 10 min, 1 h, 24 h or for good, | |
| 286 | or ban them. | |
| 287 | - **Mute**: the person can still watch and drive, but cannot chat. | |
| 288 | - **Ban**: no chat, no queue and no driving (the HTTP controls refuse too); | |
| 289 | a turn in progress ends. They can still watch. The menu bans for good; the | |
| 290 | protocol takes `minutes` for a timed ban, but the UI has no duration yet. | |
| 291 | - Timed sanctions run from a minute to a year and lift themselves. Owners | |
| 292 | cannot be muted or banned, nor can you sanction yourself; anyone who has | |
| 293 | ever connected as an owner is remembered, online or not. | |
| 294 | - **Slow mode** (on `/moderation`): seconds between one person's messages, 0 to | |
| 295 | 3600; 0 leaves the chat's own 2 s. | |
| 296 | - **Audit log** (on `/moderation`): the last 200 actions with who, whom and when. | |
| 297 | Each can be **undone** once: a lift puts the sanction back with its | |
| 298 | remaining time (nothing if it has run out, or if they are sanctioned | |
| 299 | again); undoing an older mute or ban leaves a newer one alone; a removed | |
| 300 | message comes back; slow mode returns to its old value. | |
| 301 | - Everything is kept in `$FORGE_APP_DATA/so101/moderation.json`. | |
| 281 | 302 | |
| 282 | 303 | **Admin.** The owner runs the room from `/admin` (plain forms, no script), |
| 283 | 304 | or from the compact **Admin** bar that only the owner sees beside the queue: |
Software/so101/bench/fake-serve.ts +1 −1
| @@ -44,7 +44,7 @@ try { | ||
| 44 | 44 | } |
| 45 | 45 | const identityKey = process.env.FORGE_APP_IDENTITY_KEY ?? ""; |
| 46 | 46 | const local = !identityKey && !process.env.FORGE_APP_ENV; |
| 47 | const lobby = new Lobby({ identityKey, local, chatFile: join(dir, "chat.json"), adminFile: join(dir, "admin.json"), moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }) }); | |
| 47 | const lobby = new Lobby({ identityKey, local, chatFile: join(dir, "chat.json"), moderationFile: join(dir, "moderation.json"), adminFile: join(dir, "admin.json"), moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }) }); | |
| 48 | 48 | const cameras = new CameraHub({ file: join(dir, "cameras.json"), seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] }); |
| 49 | 49 | |
| 50 | 50 | const leaders = new LeaderCalibrations({ file: join(dir, "leader-calibrations.json") }); |
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.test.ts +109 −2
| @@ -225,14 +225,121 @@ describe("lobby", () => { | ||
| 225 | 225 | |
| 226 | 226 | owner.send({ type: "delete", id: said.message.id }); |
| 227 | 227 | expect((await anon.next((m) => m.type === "unsaid")).id).toBe(said.message.id); |
| 228 | owner.send({ type: "mute", id: "u-alice", on: true }); | |
| 228 | owner.send({ type: "mute", id: "u-alice", minutes: 10 }); | |
| 229 | 229 | expect((await alice.next((m) => m.type === "hello")).muted).toBe(true); |
| 230 | expect((await owner.next((m) => m.type === "muted")).muted).toEqual([{ id: "u-alice", name: "alice" }]); | |
| 230 | expect((await owner.next((m) => m.type === "muted" && m.sanctions.length === 1)).sanctions[0]).toMatchObject({ id: "u-alice", name: "alice", kind: "mute" }); | |
| 231 | 231 | |
| 232 | 232 | const late = await join(port); |
| 233 | 233 | expect((await late.first((m) => m.type === "chat")).messages).toEqual([]); |
| 234 | 234 | }); |
| 235 | 235 | |
| 236 | describe("moderation", () => { | |
| 237 | test("non-moderators cannot do any of it", async () => { | |
| 238 | const port = await start(); | |
| 239 | const alice = await join(port, ALICE); | |
| 240 | const bob = await join(port, BOB); | |
| 241 | bob.send({ type: "post", text: "hi" }); | |
| 242 | const said = await alice.next((m) => m.type === "said"); | |
| 243 | 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" }]) { | |
| 244 | alice.send(req); | |
| 245 | expect((await alice.next((m) => m.type === "error")).error).toContain("only the owner"); | |
| 246 | } | |
| 247 | expect(lobby!.moderation.audit).toEqual([]); | |
| 248 | expect(lobby!.chat.messages.length).toBe(1); | |
| 249 | expect((await fetch(`http://127.0.0.1:${port}/moderation`, { headers: ALICE })).status).toBe(403); | |
| 250 | expect((await fetch(`http://127.0.0.1:${port}/moderation`)).status).toBe(403); | |
| 251 | expect((await fetch(`http://127.0.0.1:${port}/moderation`, { headers: OWNER })).status).toBe(200); | |
| 252 | }); | |
| 253 | ||
| 254 | test("a mute blocks posting for the time, then lifts; undo lifts it early", async () => { | |
| 255 | let clock = 1_000_000; | |
| 256 | lobby = undefined; | |
| 257 | const moderation = new (await import("./moderation.ts")).Moderation({ now: () => clock }); | |
| 258 | const turns = new Turns(); | |
| 259 | lobby = new Lobby({ identityKey: KEY, turns, chat: new Chat({ now: () => clock }), moderation }); | |
| 260 | relay = await startRelay({ port: 0, simulation: `http://127.0.0.1:${simulation.port}`, lobby }); | |
| 261 | const port = relay.port; | |
| 262 | const alice = await join(port, ALICE); | |
| 263 | const owner = await join(port, OWNER); | |
| 264 | owner.send({ type: "mute", id: "u-alice", minutes: 10 }); | |
| 265 | await alice.next((m) => m.type === "hello" && m.muted); | |
| 266 | alice.send({ type: "post", text: "hi" }); | |
| 267 | expect((await alice.next((m) => m.type === "error")).error).toContain("muted"); | |
| 268 | clock += 9 * 60_000; | |
| 269 | alice.send({ type: "post", text: "hi" }); | |
| 270 | expect((await alice.next((m) => m.type === "error" && m.error.includes("muted"), 2000)).error).toContain("muted"); | |
| 271 | clock += 61_000; | |
| 272 | alice.send({ type: "post", text: "hi again" }); | |
| 273 | expect((await alice.next((m) => m.type === "said")).message.text).toBe("hi again"); | |
| 274 | ||
| 275 | owner.send({ type: "mute", id: "u-alice" }); // for good | |
| 276 | await alice.next((m) => m.type === "hello" && m.muted); | |
| 277 | clock += 400 * 86_400_000; | |
| 278 | expect(moderation.muted("u-alice")).toBe(true); | |
| 279 | const entry = moderation.audit.findLast((e) => e.action === "mute" && !e.undone)!; | |
| 280 | owner.send({ type: "undo", entry: entry.id }); | |
| 281 | await alice.next((m) => m.type === "hello" && !m.muted); | |
| 282 | }); | |
| 283 | ||
| 284 | test("a ban blocks chat and the queue, drops the line and ends the turn; the banned can still watch; undo", async () => { | |
| 285 | const port = await start(); | |
| 286 | const alice = await join(port, ALICE); | |
| 287 | const bob = await join(port, BOB); | |
| 288 | const owner = await join(port, OWNER); | |
| 289 | alice.send({ type: "join" }); | |
| 290 | await bob.next(drivingIs("alice")); | |
| 291 | bob.send({ type: "join" }); | |
| 292 | await owner.next((m) => m.type === "state" && m.queue.length === 1); | |
| 293 | expect((await torque(port, ALICE)).status).toBe(200); | |
| 294 | ||
| 295 | owner.send({ type: "ban", id: "u-bob", minutes: 60 }); | |
| 296 | await owner.next((m) => m.type === "state" && m.queue.length === 0); | |
| 297 | bob.send({ type: "join" }); | |
| 298 | expect((await bob.next((m) => m.type === "error")).error).toContain("banned"); | |
| 299 | bob.send({ type: "post", text: "hi" }); | |
| 300 | expect((await bob.next((m) => m.type === "error")).error).toContain("banned"); | |
| 301 | expect(bob.last("state")).toBeTruthy(); // still watching | |
| 302 | ||
| 303 | owner.send({ type: "ban", id: "u-alice" }); | |
| 304 | await bob.next(drivingIs(null)); | |
| 305 | expect(lobby!.moderation.banned("u-alice")).toBe(true); | |
| 306 | expect((await torque(port, ALICE)).status).toBe(403); | |
| 307 | alice.send({ type: "join" }); | |
| 308 | expect((await alice.next((m) => m.type === "error")).error).toContain("banned"); | |
| 309 | ||
| 310 | const entry = lobby!.moderation.audit.find((e) => e.action === "ban" && e.target!.id === "u-alice")!; | |
| 311 | owner.send({ type: "undo", entry: entry.id }); | |
| 312 | await owner.next((m) => m.type === "muted" && m.sanctions.length === 1); | |
| 313 | alice.send({ type: "join" }); | |
| 314 | await bob.next(drivingIs("alice")); | |
| 315 | }); | |
| 316 | ||
| 317 | test("removing a line goes to everyone live, is audited, and undo restores it; slow mode is a setting", async () => { | |
| 318 | const port = await start(); | |
| 319 | const alice = await join(port, ALICE); | |
| 320 | const bob = await join(port, BOB); | |
| 321 | const owner = await join(port, OWNER); | |
| 322 | alice.send({ type: "post", text: "oops" }); | |
| 323 | const said = await bob.next((m) => m.type === "said"); | |
| 324 | owner.send({ type: "delete", id: said.message.id }); | |
| 325 | for (const c of [alice, bob, owner]) expect((await c.next((m) => m.type === "unsaid")).id).toBe(said.message.id); | |
| 326 | const view = await owner.next((m) => m.type === "muted" && m.audit.length === 1); | |
| 327 | expect(view.audit[0]).toMatchObject({ action: "remove", by: { name: "trevato" }, target: { id: "u-alice" } }); | |
| 328 | owner.send({ type: "undo", entry: view.audit[0].id }); | |
| 329 | expect((await bob.next((m) => m.type === "chat" && m.messages.length === 1)).messages[0].text).toBe("oops"); | |
| 330 | ||
| 331 | owner.send({ type: "slow", seconds: 30 }); | |
| 332 | await owner.next((m) => m.type === "muted" && m.slowSeconds === 30); | |
| 333 | bob.send({ type: "post", text: "one" }); | |
| 334 | await bob.next((m) => m.type === "said"); | |
| 335 | await sleep(2100); | |
| 336 | bob.send({ type: "post", text: "two" }); | |
| 337 | expect((await bob.next((m) => m.type === "error")).error).toContain("one message every 30 s"); | |
| 338 | owner.send({ type: "slow", seconds: -1 }); | |
| 339 | expect((await owner.next((m) => m.type === "error")).error).toContain("0 to 3600"); | |
| 340 | }); | |
| 341 | }); | |
| 342 | ||
| 236 | 343 | const form = (port: number, fields: Record<string, string>, headers: Record<string, string> = {}) => |
| 237 | 344 | 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() }); |
| 238 | 345 |
Software/so101/src/lobby.ts +115 −51
| @@ -9,7 +9,10 @@ | ||
| 9 | 9 | * {"type": "post", "text": "…"} say something |
| 10 | 10 | * {"type": "end", "id": "<user id>"} owner: end that turn, or take them out of the line |
| 11 | 11 | * {"type": "delete", "id": 12} owner: delete a chat line |
| 12 | * {"type": "mute", "id": "<user id>", "on": true|false} owner | |
| 12 | * {"type": "mute", "id": "<user id>", "minutes": 10} owner: mute (no minutes: for good); "unmute" lifts it | |
| 13 | * {"type": "ban", "id": "<user id>", "minutes": 60} owner: no chat, no queue, turn ended; "unban" lifts it | |
| 14 | * {"type": "slow", "seconds": 5} owner: seconds between one person's messages | |
| 15 | * {"type": "undo", "entry": 3} owner: undo an audit entry (unmute, unban, restore a line) | |
| 13 | 16 | * {"type": "pause", "on": true|false} owner: maintenance; nobody new gets a turn |
| 14 | 17 | * {"type": "settings", "set": {…}} owner: any of src/admin.ts's settings |
| 15 | 18 | * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings |
| @@ -17,7 +20,7 @@ | ||
| 17 | 20 | * {"type": "dismiss", "id": 12} owner: dismiss a mute suggestion |
| 18 | 21 | * {"type": "pong"} the answer to {"type": "ping"} |
| 19 | 22 | * Server → client: hello (who you are), state (the turn, the line, pause, the announcement and the speed cap), |
| 20 | * chat (the log), said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: | |
| 23 | * chat (the log), said, unsaid, muted (owners only: the sanctions, the audit log, slow mode), admin (owners only: the settings and the admin log), crew (owners only: | |
| 21 | 24 | * settings, hidden lines, mute suggestions), ping, error. |
| 22 | 25 | */ |
| 23 | 26 | |
| @@ -26,6 +29,7 @@ import type { Duplex } from "node:stream"; | ||
| 26 | 29 | import WebSocket, { WebSocketServer } from "ws"; |
| 27 | 30 | import { Admin, AdminError } from "./admin.ts"; |
| 28 | 31 | import { Chat, ChatError } from "./chat.ts"; |
| 32 | import { Moderation, ModerationError } from "./moderation.ts"; | |
| 29 | 33 | import { Moderator } from "./moderator.ts"; |
| 30 | 34 | import { identify, LOCAL, type Person, type Who } from "./identity.ts"; |
| 31 | 35 | import { Turns, type TurnEvent } from "./turns.ts"; |
| @@ -37,6 +41,9 @@ export interface LobbyOptions { | ||
| 37 | 41 | local?: boolean; |
| 38 | 42 | /** The chat's file; none keeps it in memory. */ |
| 39 | 43 | chatFile?: string; |
| 44 | /** The mutes, bans, slow mode and audit log's file; none keeps them in memory. */ | |
| 45 | moderationFile?: string; | |
| 46 | moderation?: Moderation; | |
| 40 | 47 | /** The admin settings' file; none keeps them in memory. */ |
| 41 | 48 | adminFile?: string; |
| 42 | 49 | /** Given turns keep their own limits until the owner changes one; made here, they start from the admin settings. */ |
| @@ -62,6 +69,7 @@ const USER_ID = /^[A-Za-z0-9_-]{1,64}$/; | ||
| 62 | 69 | export class Lobby { |
| 63 | 70 | readonly turns: Turns; |
| 64 | 71 | readonly chat: Chat; |
| 72 | readonly moderation: Moderation; | |
| 65 | 73 | readonly admin: Admin; |
| 66 | 74 | readonly local: boolean; |
| 67 | 75 | readonly moderator: Moderator | undefined; |
| @@ -81,6 +89,7 @@ export class Lobby { | ||
| 81 | 89 | this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue }); |
| 82 | 90 | this.turns.setPaused(a.paused); |
| 83 | 91 | this.chat = options.chat ?? new Chat({ file: options.chatFile }); |
| 92 | this.moderation = options.moderation ?? new Moderation({ file: options.moderationFile }); | |
| 84 | 93 | this.silentMs = options.silentMs ?? 15_000; |
| 85 | 94 | this.moderator = options.moderator; |
| 86 | 95 | if (this.moderator) { |
| @@ -108,6 +117,7 @@ export class Lobby { | ||
| 108 | 117 | refusal(who: Who): { status: number; error: string } | null { |
| 109 | 118 | if (this.local) return null; |
| 110 | 119 | if (!who) return { status: 401, error: "sign in to take control" }; |
| 120 | if (this.moderation.banned(who.id)) return { status: 403, error: "you are banned from driving" }; | |
| 111 | 121 | if (!this.turns.isDriver(who.id)) { |
| 112 | 122 | const d = this.turns.driver; |
| 113 | 123 | return { status: 403, error: d ? `${d.name} has control; take control to join the queue` : "take control first" }; |
| @@ -188,13 +198,14 @@ export class Lobby { | ||
| 188 | 198 | // ------------------------------------------------------------------ sockets |
| 189 | 199 | private seat(ws: WebSocket, who: Who): void { |
| 190 | 200 | const seat: Seat = { ws, who, heard: Date.now() }; |
| 201 | if (who?.owner) this.moderation.noteOwner(who.id); | |
| 191 | 202 | this.seats.add(seat); |
| 192 | 203 | if (who) this.turns.connect(who.id); |
| 193 | this.send(seat, { type: "hello", you: who, signin: !this.local, muted: who ? this.chat.muted.has(who.id) : false }); | |
| 204 | this.send(seat, { type: "hello", you: who, signin: !this.local, muted: who ? this.moderation.muted(who.id) : false }); | |
| 194 | 205 | this.send(seat, this.state()); |
| 195 | 206 | this.send(seat, { type: "chat", messages: this.chat.messages }); |
| 196 | 207 | if (who?.owner) { |
| 197 | this.send(seat, this.mutedList()); | |
| 208 | this.send(seat, this.modView()); | |
| 198 | 209 | this.send(seat, this.adminState()); |
| 199 | 210 | this.send(seat, this.crewState()); |
| 200 | 211 | } |
| @@ -230,65 +241,107 @@ export class Lobby { | ||
| 230 | 241 | if (!who) return this.send(seat, { type: "error", error: "sign in to take part" }); |
| 231 | 242 | switch (m.type) { |
| 232 | 243 | case "join": |
| 244 | if (this.moderation.banned(who.id)) throw new ChatError("you are banned from driving"); | |
| 233 | 245 | if (this.takeControl(who) === "full") this.send(seat, { type: "error", error: `the line is full (${this.turns.maxQueue}); try again in a little while` }); |
| 234 | 246 | return; |
| 235 | 247 | case "leave": |
| 236 | 248 | this.turns.leave(who.id); |
| 237 | 249 | return; |
| 238 | 250 | case "post": { |
| 239 | const said = this.chat.post(who, m.text); | |
| 251 | const s = this.moderation.status(who.id); | |
| 252 | if (s) throw new ChatError(s.kind === "ban" ? "you are banned" : "you are muted"); | |
| 253 | const said = this.chat.post(who, m.text, this.moderation.slowSeconds * 1000); | |
| 240 | 254 | this.broadcast({ type: "said", message: said }); |
| 241 | 255 | void this.moderator?.check(said); |
| 242 | 256 | return; |
| 243 | 257 | } |
| 244 | 258 | } |
| 245 | 259 | if (!who.owner) return this.send(seat, { type: "error", error: "only the owner can do that" }); |
| 246 | switch (m.type) { | |
| 247 | case "end": | |
| 248 | if (typeof m.id !== "string" || !USER_ID.test(m.id)) return this.send(seat, { type: "error", error: "end whom?" }); | |
| 249 | if (this.turns.isDriver(m.id)) return this.endTurn(who); | |
| 250 | 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`); | |
| 251 | this.turns.end(m.id); | |
| 252 | return; | |
| 253 | case "pause": | |
| 254 | if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" }); | |
| 255 | return this.configure(who, { paused: m.on }); | |
| 256 | case "settings": | |
| 257 | return this.configure(who, m.set); | |
| 258 | case "delete": | |
| 259 | if (!Number.isSafeInteger(m.id)) return this.send(seat, { type: "error", error: "delete which line?" }); | |
| 260 | if (this.chat.delete(m.id as number)) this.broadcast({ type: "unsaid", id: m.id }); | |
| 261 | return; | |
| 262 | case "mute": { | |
| 263 | if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "mute whom?" }); | |
| 264 | const id = m.id; | |
| 265 | 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; | |
| 266 | this.chat.mute(id, name, m.on); | |
| 267 | for (const s of this.seats) { | |
| 268 | if (s.who?.id === id) this.send(s, { type: "hello", you: s.who, signin: !this.local, muted: m.on }); | |
| 269 | if (s.who?.owner) this.send(s, this.mutedList()); | |
| 260 | const by = { id: who.id, name: who.name }; | |
| 261 | const person = (): { id: string; name: string } => { | |
| 262 | if (typeof m.id !== "string" || !USER_ID.test(m.id)) throw new ChatError("whom?"); | |
| 263 | const id = m.id; | |
| 264 | 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; | |
| 265 | return { id, name }; | |
| 266 | }; | |
| 267 | const minutes = (): number | null => { | |
| 268 | if (m.minutes === undefined || m.minutes === null) return null; | |
| 269 | if (!Number.isSafeInteger(m.minutes)) throw new ChatError("minutes are a whole number"); | |
| 270 | return (m.minutes as number) * 60_000; | |
| 271 | }; | |
| 272 | try { | |
| 273 | switch (m.type) { | |
| 274 | case "end": { | |
| 275 | const target = person(); | |
| 276 | if (this.turns.isDriver(target.id)) return this.endTurn(who); | |
| 277 | 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`); | |
| 278 | this.turns.end(target.id); | |
| 279 | return; | |
| 270 | 280 | } |
| 271 | this.moderator?.muted(id); | |
| 272 | return; | |
| 273 | } | |
| 274 | case "crew": | |
| 275 | if (!this.moderator) return this.send(seat, { type: "error", error: "no moderator here" }); | |
| 276 | try { | |
| 277 | this.moderator.configure(m.settings); | |
| 278 | } catch (err) { | |
| 279 | this.send(seat, { type: "error", error: (err as Error).message }); | |
| 281 | case "pause": | |
| 282 | if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" }); | |
| 283 | return this.configure(who, { paused: m.on }); | |
| 284 | case "settings": | |
| 285 | return this.configure(who, m.set); | |
| 286 | case "delete": { | |
| 287 | if (!Number.isSafeInteger(m.id)) throw new ChatError("delete which line?"); | |
| 288 | const line = this.chat.messages.find((x) => x.id === m.id); | |
| 289 | if (line && this.chat.delete(line.id)) { | |
| 290 | this.moderation.removed(by, line); | |
| 291 | this.broadcast({ type: "unsaid", id: line.id }); | |
| 292 | this.tellOwners(); | |
| 293 | } | |
| 294 | return; | |
| 280 | 295 | } |
| 281 | return; | |
| 282 | case "restore": { | |
| 283 | const back = Number.isSafeInteger(m.id) ? this.moderator?.restore(m.id as number) : null; | |
| 284 | if (!back) return this.send(seat, { type: "error", error: "that line is not in the log" }); | |
| 285 | this.chat.restore(back); | |
| 286 | this.broadcast({ type: "chat", messages: this.chat.messages }); | |
| 287 | return; | |
| 296 | case "mute": | |
| 297 | case "ban": { | |
| 298 | const target = person(); | |
| 299 | this.moderation.sanction(by, m.type, target, minutes()); | |
| 300 | this.moderator?.muted(target.id); | |
| 301 | this.sanctioned(target.id); | |
| 302 | return; | |
| 303 | } | |
| 304 | case "unmute": | |
| 305 | case "unban": { | |
| 306 | const target = person(); | |
| 307 | this.moderation.lift(by, m.type === "unban" ? "ban" : "mute", target.id); | |
| 308 | this.sanctioned(target.id); | |
| 309 | return; | |
| 310 | } | |
| 311 | case "slow": | |
| 312 | this.moderation.setSlow(by, m.seconds); | |
| 313 | this.tellOwners(); | |
| 314 | return; | |
| 315 | case "undo": { | |
| 316 | if (!Number.isSafeInteger(m.entry)) throw new ChatError("undo which entry?"); | |
| 317 | const { entry, restore } = this.moderation.undo(by, m.entry as number); | |
| 318 | if (restore && this.chat.restore(restore)) this.broadcast({ type: "chat", messages: this.chat.messages }); | |
| 319 | if (entry.target) this.sanctioned(entry.target.id); | |
| 320 | else this.tellOwners(); | |
| 321 | return; | |
| 322 | } | |
| 323 | case "crew": | |
| 324 | if (!this.moderator) return this.send(seat, { type: "error", error: "no moderator here" }); | |
| 325 | try { | |
| 326 | this.moderator.configure(m.settings); | |
| 327 | } catch (err) { | |
| 328 | this.send(seat, { type: "error", error: (err as Error).message }); | |
| 329 | } | |
| 330 | return; | |
| 331 | case "restore": { | |
| 332 | const back = Number.isSafeInteger(m.id) ? this.moderator?.restore(m.id as number) : null; | |
| 333 | if (!back) return this.send(seat, { type: "error", error: "that line is not in the log" }); | |
| 334 | this.chat.restore(back); | |
| 335 | this.broadcast({ type: "chat", messages: this.chat.messages }); | |
| 336 | return; | |
| 337 | } | |
| 338 | case "dismiss": | |
| 339 | if (Number.isSafeInteger(m.id)) this.moderator?.dismiss(m.id as number); | |
| 340 | return; | |
| 288 | 341 | } |
| 289 | case "dismiss": | |
| 290 | if (Number.isSafeInteger(m.id)) this.moderator?.dismiss(m.id as number); | |
| 291 | return; | |
| 342 | } catch (err) { | |
| 343 | if (err instanceof ModerationError) throw new ChatError(err.message); | |
| 344 | throw err; | |
| 292 | 345 | } |
| 293 | 346 | this.send(seat, { type: "error", error: "unknown request" }); |
| 294 | 347 | } |
| @@ -320,6 +373,10 @@ export class Lobby { | ||
| 320 | 373 | for (const s of this.seats) if (s.who?.owner && s.ws.readyState === WebSocket.OPEN) s.ws.send(text); |
| 321 | 374 | } |
| 322 | 375 | |
| 376 | private modView() { | |
| 377 | return { type: "muted", ...this.moderation.view() }; | |
| 378 | } | |
| 379 | ||
| 323 | 380 | /** What the crew did, for the owners: its settings, the lines it hid, and who it suggests muting. */ |
| 324 | 381 | private crewState() { |
| 325 | 382 | const m = this.moderator; |
| @@ -327,11 +384,18 @@ export class Lobby { | ||
| 327 | 384 | } |
| 328 | 385 | |
| 329 | 386 | private tellOwners(): void { |
| 330 | for (const s of this.seats) if (s.who?.owner) this.send(s, this.crewState()); | |
| 387 | for (const s of this.seats) { | |
| 388 | if (!s.who?.owner) continue; | |
| 389 | this.send(s, this.modView()); | |
| 390 | this.send(s, this.crewState()); | |
| 391 | } | |
| 331 | 392 | } |
| 332 | 393 | |
| 333 | private mutedList() { | |
| 334 | return { type: "muted", muted: [...this.chat.muted].map(([id, name]) => ({ id, name })) }; | |
| 394 | /** Someone's standing changed: they hear it, and a ban also takes them out of the queue. */ | |
| 395 | private sanctioned(id: string): void { | |
| 396 | if (this.moderation.banned(id)) this.turns.end(id, "banned"); | |
| 397 | for (const s of this.seats) if (s.who?.id === id) this.send(s, { type: "hello", you: s.who, signin: !this.local, muted: this.moderation.muted(id) }); | |
| 398 | this.tellOwners(); | |
| 335 | 399 | } |
| 336 | 400 | |
| 337 | 401 | 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. */ | |
outdated
Deletes the current sanction of this kind even if a newer entry made it. Only lift if it is the one this entry created. |
||
| 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 | ||
outdated
Restores as until:null; a timed mute becomes permanent on undo. Keep the previous sanction on the entry and restore it. |
||
| 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 { | |
outdated
Undoing an old |
||
| 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 | } | |
outdated
Undoing an |
||
| 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
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | * |
| 13 | 13 | * The owner's speed cap (src/speed-cap.ts) is applied here too, to moves, poses, grips, playbacks and every stream frame. |
| 14 | 14 | * |
| 15 | * GET /moderation the moderation page (the owner's; the data itself comes over /live) | |
| 15 | 16 | * WS /live the lobby: the turn, the queue, the chat |
| 16 | 17 | * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log |
| 17 | 18 | * GET /link {"mode": "live"|"simulated", "host": "<host:port>"|null, "problem": "…"|null} |
| @@ -165,6 +166,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 165 | 166 | const probeEveryMs = options.probeEveryMs ?? 5000; |
| 166 | 167 | const readTimeoutMs = options.readTimeoutMs ?? 2500; |
| 167 | 168 | const lobby = options.lobby ?? null; |
| 169 | const moderationPage = readFileSync(new URL("./moderation.html", import.meta.url), "utf8"); | |
| 168 | 170 | const cameras = options.cameras ?? new CameraHub({ feed: options.camera, seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] }); |
| 169 | 171 | const leaders = options.leaders ?? new LeaderCalibrations(); |
| 170 | 172 | |
| @@ -387,6 +389,12 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 387 | 389 | const refused = url.pathname === "/stop" && who?.owner ? null : lobby.refusal(who); |
| 388 | 390 | if (refused) return json(res, refused.status, { error: refused.error }); |
| 389 | 391 | } |
| 392 | if (lobby && url.pathname === "/moderation") { | |
| 393 | if (req.method !== "GET") return json(res, 405, { error: "read-only" }); | |
| 394 | if (!lobby.who(req)?.owner) return json(res, 403, { error: "only the owner may moderate" }); | |
| 395 | res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }); | |
| 396 | return res.end(moderationPage); | |
| 397 | } | |
| 390 | 398 | if (req.method === "GET" && url.pathname === "/link") return json(res, 200, link()); |
| 391 | 399 | |
| 392 | 400 | const camera = CAMERA.exec(url.pathname); |
Software/so101/src/turns.ts +3 −3
| @@ -17,7 +17,7 @@ export interface Turn extends Person { | ||
| 17 | 17 | lastActive: number; |
| 18 | 18 | } |
| 19 | 19 | |
| 20 | export type EndReason = "handed back" | "time is up" | "idle" | "disconnected" | "ended by the owner" | "taken over by the owner" | "paused for maintenance"; | |
| 20 | export type EndReason = "handed back" | "time is up" | "idle" | "disconnected" | "ended by the owner" | "banned" | "taken over by the owner" | "paused for maintenance"; | |
| 21 | 21 | |
| 22 | 22 | export type TurnEvent = { kind: "turn"; ended: { who: Person; reason: EndReason } | null; started: Person | null } | { kind: "queue" }; |
| 23 | 23 | |
| @@ -123,8 +123,8 @@ export class Turns { | ||
| 123 | 123 | } |
| 124 | 124 | |
| 125 | 125 | /** The owner ends someone's turn, or takes them out of the line. */ |
| 126 | end(id: string): void { | |
| 127 | if (this.isDriver(id)) return this.handOver("ended by the owner"); | |
| 126 | end(id: string, reason: EndReason = "ended by the owner"): void { | |
| 127 | if (this.isDriver(id)) return this.handOver(reason); | |
| 128 | 128 | if (this.remove(id)) this.emit({ kind: "queue" }); |
| 129 | 129 | } |
| 130 | 130 |
Software/so101/src/viewer.html +18 −6
| @@ -98,8 +98,8 @@ | ||
| 98 | 98 | #chat { flex: 1; min-height: 0; overflow: auto; padding: 8px 12px; display: flex; flex-direction: column; gap: 3px; font-size: 13px; overflow-wrap: anywhere; } |
| 99 | 99 | #chat .line { line-height: 1.45; } #chat .line b { color: #c9d1d9; font-weight: 600; margin-right: 6px; } #chat .line.me b { color: #58a6ff; } |
| 100 | 100 | #chat .sys { color: var(); font-style: italic; } |
| 101 | #chat .mod { display: none; margin-left: 6px; } #chat .line:hover .mod, #chat .line:focus-within .mod { display: inline-flex; gap: 4px; } | |
| 102 | #chat .mod button { min-height: 22px; padding: 0 6px; font-size: 11px; } | |
| 101 | #chat .mod { margin-left: 6px; font-size: 13px; min-height: 44px; min-width: 44px; vertical-align: middle; } | |
| 102 | #mutedLine a { color: var(); display: inline-block; padding: 12px 6px; } | |
| 103 | 103 | #say { display: flex; gap: 6px; padding: 8px 12px calc(8px + env(safe-area-inset-bottom)); border-top: 1px solid var(); } |
| 104 | 104 | #say input { flex: 1; min-width: 0; font: inherit; padding: 6px 10px; border-radius: 6px; border: 1px solid var(); background: var(); color: var(); } |
| 105 | 105 | #sayNote { color: var(); font-size: 12px; padding: 0 12px 8px; } #sayNote:empty { display: none; } |
| @@ -889,7 +889,7 @@ | ||
| 889 | 889 | if (me?.owner) li.append(button("×", "x", () => say({ type: "end", id: q.id }))); |
| 890 | 890 | return li; |
| 891 | 891 | })); |
| 892 | $("mutedLine").replaceChildren(...(me?.owner && lobby.mutedList.length ? ["Muted: ", ...lobby.mutedList.flatMap((m) => [el("span", { textContent: `${m.name} ` }), button("unmute", "x", () => say({ type: "mute", id: m.id, on: false }))])] : [])); | |
| 892 | $("mutedLine").replaceChildren(...(me?.owner ? [el("a", { href: "/moderation", textContent: "Moderation page" })] : []), ...(me?.owner && lobby.mutedList.length ? ["Muted or banned: ", ...lobby.mutedList.flatMap((m) => [el("span", { textContent: `${m.name} (${m.kind}) ` }), button(m.kind === "ban" ? "unban" : "unmute", "x", () => say({ type: m.kind === "ban" ? "unban" : "unmute", id: m.id }))])] : [])); | |
| 893 | 893 | $("adminBar").hidden = !me?.owner; |
| 894 | 894 | if (me?.owner) { |
| 895 | 895 | $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue"; |
| @@ -898,7 +898,7 @@ | ||
| 898 | 898 | } |
| 899 | 899 | renderCrew(me); |
| 900 | 900 | $("say").hidden = !me || lobby.hello.muted; |
| 901 | $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Sign in to chat." : lobby.hello.muted ? "The owner has muted you." : ""; | |
| 901 | $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Sign in to chat." : lobby.hello.muted ? "A moderator has muted you." : ""; | |
| 902 | 902 | tickClock(); |
| 903 | 903 | applyLock(); |
| 904 | 904 | } |
| @@ -921,13 +921,25 @@ | ||
| 921 | 921 | ...c.suggestions.map((x) => el("div", {}, `Crew suggests muting ${x.message.from?.name}: ${x.message.text} (${x.reason}) `, button("mute", "x", () => say({ type: "mute", id: x.message.from.id, on: true })), button("dismiss", "x", () => say({ type: "dismiss", id: x.message.id }))))); |
| 922 | 922 | } |
| 923 | 923 | const chatBox = $("chat"); |
| 924 | // The owner's menu on a line: remove it, mute or ban its author for a time or for good. | |
| 925 | function modMenu(m) { | |
| 926 | const menu = el("select", { className: "mod", title: "moderate" }); | |
| 927 | menu.setAttribute("aria-label", `Moderate ${m.from.name}'s message`); | |
| 928 | menu.append(new Option("⋯", "")); | |
| 929 | const items = [["Remove message", { type: "delete", id: m.id }]]; | |
| 930 | for (const [label, minutes] of [["10 min", 10], ["1 h", 60], ["24 h", 1440], ["permanent", null]]) items.push([`Mute ${m.from.name}, ${label}`, { type: "mute", id: m.from.id, minutes }]); | |
| 931 | items.push([`Ban ${m.from.name}`, { type: "ban", id: m.from.id }]); | |
| 932 | items.forEach(([label], i) => menu.append(new Option(label, String(i)))); | |
| 933 | menu.onchange = () => { const item = items[Number(menu.value)]; menu.value = ""; if (item) say(item[1]); }; | |
| 934 | return menu; | |
| 935 | } | |
| 924 | 936 | function chatLine(m) { |
| 925 | 937 | const me = lobby.hello?.you; |
| 926 | 938 | const line = el("div", { className: m.from ? `line${me && m.from.id === me.id ? " me" : ""}` : "line sys", title: new Date(m.at).toLocaleTimeString() }); |
| 927 | 939 | line.dataset.id = m.id; |
| 928 | 940 | if (m.from) line.append(el("b", { textContent: m.from.name })); |
| 929 | 941 | line.append(el("span", { textContent: m.text })); |
| 930 | if (m.from && me?.owner) line.append(el("span", { className: "mod" }, el("button", { textContent: "delete", onclick: () => say({ type: "delete", id: m.id }) }), el("button", { textContent: "mute", onclick: () => say({ type: "mute", id: m.from.id, on: true }) }))); | |
| 942 | if (m.from && me?.owner && m.from.id !== me.id) line.append(modMenu(m)); | |
| 931 | 943 | return line; |
| 932 | 944 | } |
| 933 | 945 | function addChat(lines, replace = false) { |
| @@ -949,7 +961,7 @@ | ||
| 949 | 961 | else if (m.type === "chat") return addChat(m.messages, true); |
| 950 | 962 | else if (m.type === "said") return addChat([m.message]); |
| 951 | 963 | else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove(); |
| 952 | else if (m.type === "muted") lobby.mutedList = m.muted; | |
| 964 | else if (m.type === "muted") lobby.mutedList = m.sanctions; | |
| 953 | 965 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; fillAdmin(saved); } |
| 954 | 966 | else if (m.type === "crew") lobby.crew = m; |
| 955 | 967 | else if (m.type === "error") return msg(m.error, true); |
This only protects owners who have a socket open right now. An offline admin can be muted or banned by another admin. Once banned, they cannot post, but they keep every moderation power, unban included, because the owner check comes after the ban check in
handle. Decide on the rule, enforce it whatever the connection state, and test it.