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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Terminal door: tty gating test for mute, end-turn and chat, and tty writes reaching web viewers live #41

Parked opened this
Closed without merging

smith/arm:smith/37-terminal-door-tty-gating-test-for-mute-e → main 5 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +340 −38
Software/README.md +6
@@ -299,6 +299,12 @@ its live pose and the cameras. Driving needs a name and a turn.
299299 the queue, delete messages, mute people and ban them (long-press or
300300 right-click a chat line).
301301 The owner can also press **Stop** during anyone's turn.
302 - The terminal is the same room as the page (`src/tty.ts`): `say <text>`,
303 `join`, `leave`, `who`, and for the owner `end [id]`, `mute <id>`, `ban <id>`,
304 `unmute <id>`, `unban <id>`, `delete <n>`, `pause`, `resume`, `speed <n>`, `announce [text]`. Every line goes through the same Lobby calls as the page,
305 so the gating is identical (a muted person cannot chat, only the owner
306 mutes or ends turns, and the word filter applies) and what is typed there reaches web viewers live.
307 Not yet reachable: no process hosts `run()` for the app terminal (`forge.json` declares no `tty`).
302308 - The red **STOP** button (or Esc) is the emergency stop.
303309 The driver and the owner can press it. Only the owner can clear it, and
304310 only the owner can change the settings.
Software/so101/src/lobby.ts +67 −38
@@ -183,6 +183,68 @@ export class Lobby {
183183 this.broadcastAdmin();
184184 }
185185
186 /** The owner bars someone's account, name and address (or lifts it). Throws AdminError for anyone else or an unknown id. */
187 ban(who: Who, id: string, on: boolean): void {
188 if (!who?.owner) throw new AdminError("only the owner can do that");
189 if (on) {
190 const target = [...this.seats].find((s) => s.who?.id === id);
191 const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null);
192 const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from;
193 const person = known ?? (said ? { id, name: said.name, owner: false } : null);
194 if (!person) throw new AdminError("nobody here by that id");
195 if (person.owner) throw new AdminError("the owner cannot be banned");
196 this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name);
197 this.turns.end(id); // their turn ends, or they leave the line
198 this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) });
199 this.admin.record(who, `banned ${person.name}`);
200 } else {
201 const name = this.accounts.bans().find((b) => b.id === id)?.name;
202 if (!this.accounts.unban(id)) throw new AdminError("not banned");
203 this.admin.record(who, `unbanned ${name ?? id}`);
204 }
205 this.broadcastAdmin();
206 for (const s of this.seats) {
207 if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there
208 if (s.who?.owner) this.send(s, this.bannedList());
209 }
210 }
211
212 /** The owner deletes a chat line; everyone hears it go. */
213 deleteLine(who: Who, id: number): void {
214 if (!who?.owner) throw new AdminError("only the owner can do that");
215 if (this.chat.delete(id)) this.broadcast({ type: "unsaid", id });
216 }
217
218 /** The owner ends that person's turn, or takes them out of the line; both are logged. */
219 removeFromLine(who: Who, id: string): void {
220 if (!who?.owner) throw new AdminError("only the owner can do that");
221 if (this.turns.isDriver(id)) return this.endTurn(who);
222 const waiting = this.turns.queue.find((p) => p.id === id);
223 if (waiting) this.admin.record(who, `took ${waiting.name} out of the line`);
224 this.turns.end(id);
225 }
226
227 /** A signed-in person posts a chat line; everyone hears it and the crew checks it. Throws ChatError when it may not be said. */
228 say(who: Person, text: unknown): void {
229 if (this.barred(who, null)) throw new ChatError("you are banned: you can still watch");
230 if (!who.owner && typeof text === "string" && this.filter.blocks(text)) throw new ChatError("that word is not allowed here");
231 const said = this.chat.post(who, text);
232 this.broadcast({ type: "said", message: said });
233 void this.moderator?.check(said);
234 }
235
236 /** The owner mutes or unmutes someone; they and the other owners are told at once. */
237 mute(who: Who, id: string, on: boolean): void {
238 if (!who?.owner) throw new AdminError("only the owner can do that");
239 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;
240 this.chat.mute(id, name, on);
241 for (const s of this.seats) {
242 if (s.who?.id === id) this.send(s, this.hello(s));
243 if (s.who?.owner) this.send(s, this.mutedList());
244 }
245 this.moderator?.muted(id);
246 }
247
186248 /** Ask to drive; for the owner that is taking control now, and it is logged. */
187249 takeControl(who: Person): "driving" | "queued" | "full" {
188250 if (who.owner && !this.turns.isDriver(who.id)) {
@@ -268,10 +330,7 @@ export class Lobby {
268330 this.turns.leave(who.id);
269331 return;
270332 case "post": {
271 if (!who.owner && typeof m.text === "string" && this.filter.blocks(m.text)) throw new ChatError("that word is not allowed here");
272 const said = this.chat.post(who, m.text);
273 this.broadcast({ type: "said", message: said });
274 void this.moderator?.check(said);
333 this.say(who, m.text);
275334 return;
276335 }
277336 }
@@ -279,9 +338,7 @@ export class Lobby {
279338 switch (m.type) {
280339 case "end":
281340 if (typeof m.id !== "string" || !USER_ID.test(m.id)) return this.send(seat, { type: "error", error: "end whom?" });
282 if (this.turns.isDriver(m.id)) return this.endTurn(who);
283 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`);
284 this.turns.end(m.id);
341 this.removeFromLine(who, m.id);
285342 return;
286343 case "pause":
287344 if (typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "pause on or off?" });
@@ -290,7 +347,7 @@ export class Lobby {
290347 return this.configure(who, m.set);
291348 case "delete":
292349 if (!Number.isSafeInteger(m.id)) return this.send(seat, { type: "error", error: "delete which line?" });
293 if (this.chat.delete(m.id as number)) this.broadcast({ type: "unsaid", id: m.id });
350 this.deleteLine(who, m.id as number);
294351 return;
295352 case "words": {
296353 const words = this.filter.set(m.words);
@@ -301,40 +358,12 @@ export class Lobby {
301358 }
302359 case "mute": {
303360 if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "mute whom?" });
304 const id = m.id;
305 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;
306 this.chat.mute(id, name, m.on);
307 for (const s of this.seats) {
308 if (s.who?.id === id) this.send(s, this.hello(s));
309 if (s.who?.owner) this.send(s, this.mutedList());
310 }
311 this.moderator?.muted(id);
361 this.mute(who, m.id, m.on);
312362 return;
313363 }
314364 case "ban": {
315365 if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "ban whom?" });
316 const id = m.id;
317 if (m.on) {
318 const target = [...this.seats].find((s) => s.who?.id === id);
319 const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null);
320 const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from;
321 const person = known ?? (said ? { id, name: said.name, owner: false } : null);
322 if (!person) return this.send(seat, { type: "error", error: "nobody here by that id" });
323 if (person.owner) return this.send(seat, { type: "error", error: "the owner cannot be banned" });
324 this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name);
325 this.turns.end(id); // their turn ends, or they leave the line
326 this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) });
327 this.admin.record(who, `banned ${person.name}`);
328 } else {
329 const name = this.accounts.bans().find((b) => b.id === id)?.name;
330 if (!this.accounts.unban(id)) return this.send(seat, { type: "error", error: "not banned" });
331 this.admin.record(who, `unbanned ${name ?? id}`);
332 }
333 this.broadcastAdmin();
334 for (const s of this.seats) {
335 if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there
336 if (s.who?.owner) this.send(s, this.bannedList());
337 }
366 this.ban(who, m.id, m.on);
338367 return;
339368 }
340369 case "crew":
Software/so101/src/tty.test.ts added +174
@@ -0,0 +1,174 @@
1 import { afterEach, describe, expect, test } from "bun:test";
2 import { createServer } from "node:http";
3 import WebSocket from "ws";
4 import { Accounts } from "./accounts.ts";
5 import { Admin } from "./admin.ts";
6 import { Chat } from "./chat.ts";
7 import { sign } from "./identity.ts";
8 import { Lobby } from "./lobby.ts";
9 import { Turns } from "./turns.ts";
10 import { run } from "./tty.ts";
11
12 const KEY = "test-identity-key";
13 const OWNER = { id: "u-owner", name: "trevato", owner: true };
14 const ALICE = { id: "u-alice", name: "alice", owner: false };
15 const BOB = { id: "u-bob", name: "bob", owner: false };
16 const as = (id: string, name: string, role = "user") => {
17 const identity = `${id}|${name}|${role}|${Date.now() + 3_600_000}`;
18 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
19 };
20
21 type Msg = Record<string, any>;
22 let lobby: Lobby | undefined;
23 let server: ReturnType<typeof createServer> | undefined;
24 const sockets: WebSocket[] = [];
25 afterEach(() => {
26 for (const s of sockets.splice(0)) s.terminate();
27 server?.close();
28 lobby?.close();
29 lobby = server = undefined;
30 });
31
32 /** A lobby on a real socket with one web viewer connected, so a terminal write has somewhere to arrive. */
33 async function room(who = as("u-bob", "bob")) {
34 lobby = new Lobby({ identityKey: KEY, turns: new Turns(), chat: new Chat({ rateMs: 0 }), admin: new Admin(), accounts: new Accounts() });
35 const l = lobby;
36 server = createServer();
37 server.on("upgrade", (req, socket, head) => l.upgrade(req, socket, head));
38 await new Promise<void>((r) => server!.listen(0, "127.0.0.1", r));
39 const port = (server.address() as { port: number }).port;
40 const ws = new WebSocket(`ws://127.0.0.1:${port}/live`, { headers: who });
41 sockets.push(ws);
42 const heard: Msg[] = [];
43 ws.on("message", (d) => heard.push(JSON.parse(String(d))));
44 await new Promise((r, j) => (ws.once("open", r), ws.once("error", j)));
45 const until = async (match: (m: Msg) => boolean) => {
46 for (let i = 0; i < 100; i++) {
47 const m = heard.find(match);
48 if (m) return m;
49 await new Promise((r) => setTimeout(r, 10));
50 }
51 throw new Error(`nothing matched; heard ${JSON.stringify(heard.slice(-5))}`);
52 };
53 return { l, heard, until };
54 }
55
56 describe("terminal door", () => {
57 test("nobody is signed in: reads work, everything else is refused", async () => {
58 const { l } = await room();
59 expect(run(l, null, "who")).toContain("driving: nobody");
60 expect(run(l, null, "say hi")).toContain("join to take part");
61 expect(run(l, null, "join")).toContain("join to take part");
62 expect(l.chat.messages).toEqual([]);
63 });
64
65 test("mute and end-turn are the owner's alone", async () => {
66 const { l } = await room();
67 run(l, ALICE, "join");
68 expect(l.turns.isDriver(ALICE.id)).toBe(true);
69 expect(run(l, BOB, "mute u-alice")).toBe("error: only the owner can do that");
70 expect(run(l, BOB, "unmute u-alice")).toBe("error: only the owner can do that");
71 expect(run(l, BOB, "end")).toBe("error: only the owner can do that");
72 expect(run(l, ALICE, "end u-alice")).toBe("error: only the owner can do that");
73 expect(l.chat.muted.size).toBe(0);
74 expect(l.turns.isDriver(ALICE.id)).toBe(true);
75
76 expect(run(l, OWNER, "mute u-alice")).toBe("ok");
77 expect(l.chat.muted.has(ALICE.id)).toBe(true);
78 expect(run(l, OWNER, "end")).toBe("ok");
79 expect(l.turns.isDriver(ALICE.id)).toBe(false);
80 expect(run(l, OWNER, "unmute u-alice")).toBe("ok");
81 expect(l.chat.muted.size).toBe(0);
82 });
83
84 test("taking someone out of the line is logged like the page logs it", async () => {
85 const { l } = await room();
86 run(l, ALICE, "join");
87 run(l, BOB, "join");
88 expect(run(l, BOB, "end u-bob")).toBe("error: only the owner can do that");
89 expect(run(l, OWNER, "end u-bob")).toBe("ok");
90 expect(l.turns.queue.some((p) => p.id === BOB.id)).toBe(false);
91 expect(JSON.stringify(l.admin.log)).toContain("took bob out of the line");
92 });
93
94 test("ban, delete, pause, speed and announce are the owner's alone and change what the page sees", async () => {
95 const { l, until } = await room();
96 run(l, ALICE, "say first");
97 const id = l.chat.messages.at(-1)!.id;
98 for (const line of ["ban u-alice", "unban u-alice", `delete ${id}`, "pause", "resume", "speed 20", "announce hello"]) {
99 expect(run(l, BOB, line)).toBe("error: only the owner can do that");
100 }
101 expect(l.chat.messages.some((m) => m.id === id)).toBe(true);
102 expect(l.admin.settings).toMatchObject({ paused: false, maxSpeedPercent: 100, announcement: "" });
103
104 expect(run(l, OWNER, `delete ${id}`)).toBe("ok");
105 expect((await until((m) => m.type === "unsaid")).id).toBe(id);
106 expect(run(l, OWNER, "pause")).toBe("ok");
107 expect(l.admin.settings.paused).toBe(true);
108 expect(run(l, OWNER, "resume")).toBe("ok");
109 expect(run(l, OWNER, "speed 20")).toBe("ok");
110 expect(l.maxSpeedPercent).toBe(20);
111 expect(run(l, OWNER, "speed 1")).toContain("error");
112 expect(run(l, OWNER, "speed fast")).toContain("error");
113 expect(run(l, OWNER, "announce back at noon")).toBe("ok");
114 expect(l.admin.settings.announcement).toBe("back at noon");
115 expect(run(l, OWNER, "announce")).toBe("ok");
116 expect(l.admin.settings.announcement).toBe("");
117
118 run(l, ALICE, "join");
119 expect(run(l, OWNER, "ban u-alice")).toBe("ok");
120 expect(l.turns.isDriver(ALICE.id)).toBe(false);
121 expect(run(l, ALICE, "say hi")).toContain("banned");
122 expect(JSON.stringify(l.admin.log)).toContain("banned alice");
123 run(l, OWNER, "join");
124 expect(run(l, OWNER, "ban u-owner")).toBe("error: the owner cannot be banned");
125 expect(run(l, OWNER, "ban u-nobody")).toBe("error: nobody here by that id");
126 expect(run(l, OWNER, "unban u-alice")).toBe("ok");
127 expect(run(l, OWNER, "unban u-alice")).toBe("error: not banned");
128 expect(run(l, OWNER, "delete x")).toBe("error: delete which line?");
129 });
130
131 test("chat from the terminal: a muted person is refused, input is validated", async () => {
132 const { l } = await room();
133 expect(run(l, ALICE, "say hello there")).toBe("ok");
134 expect(l.chat.messages.at(-1)).toMatchObject({ from: { id: ALICE.id }, text: "hello there" });
135 expect(run(l, ALICE, "say ")).toBe("error: say something");
136 expect(run(l, ALICE, "say " + "x".repeat(501))).toContain("at most");
137 run(l, OWNER, "mute u-alice");
138 expect(run(l, ALICE, "say still here")).toBe("error: you are muted");
139 expect(run(l, OWNER, "mute not/an/id")).toBe("error: mute whom?");
140 expect(run(l, OWNER, "frobnicate")).toContain("unknown command");
141 expect(run(l, ALICE, "x".repeat(5000))).toBe("error: line too long");
142 });
143
144 test("a terminal write reaches a web viewer live", async () => {
145 const { l, heard, until } = await room();
146 run(l, ALICE, "say <b>from the terminal</b>");
147 const said = await until((m) => m.type === "said");
148 expect(said.message).toMatchObject({ from: { name: "alice" }, text: "<b>from the terminal</b>" });
149
150 run(l, ALICE, "join");
151 expect(await until((m) => m.type === "state" && m.driver?.name === "alice")).toBeTruthy();
152 run(l, OWNER, "end");
153 const states = () => heard.filter((m) => m.type === "state");
154 for (let i = 0; i < 100 && states().at(-1)?.driver !== null; i++) await new Promise((r) => setTimeout(r, 10));
155 expect(states().at(-1)?.driver).toBeNull();
156 expect(states().some((m) => m.driver?.name === "alice")).toBe(true);
157 });
158
159 test("a mute set in the terminal reaches the muted person's page", async () => {
160 const { l, until } = await room(as("u-alice", "alice"));
161 run(l, OWNER, "mute u-alice");
162 expect(await until((m) => m.type === "hello" && m.muted === true)).toBeTruthy();
163 });
164 });
165
166 describe("terminal door and the word filter", () => {
167 test("a filtered word is refused for people, not for the owner", async () => {
168 const { l } = await room();
169 l.filter.set(["heck"]);
170 expect(run(l, ALICE, "say what the h3ck")).toBe("error: that word is not allowed here");
171 expect(l.chat.messages).toEqual([]);
172 expect(run(l, OWNER, "say what the heck")).toBe("ok");
173 });
174 });
Software/so101/src/tty.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The terminal door: the same room as the web page, one typed line at a time. The caller (whatever hosts the
3 * app's terminal) says who is typing; every line goes through the Lobby, so the rules are the page's rules and
4 * whatever is said or changed here reaches the web viewers live.
5 *
6 * say <text> post to the chat
7 * join | leave ask to drive / give up the place
8 * end [id] owner: end the current turn, or take someone out of the line
9 * mute <id> | unmute <id> owner
10 * ban <id> | unban <id> owner: bars account, name and address; they still watch
11 * delete <n> owner: remove chat line n
12 * pause | resume owner: maintenance; nobody new gets a turn
13 * speed <5-100> owner: cap on every move, percent of full speed
14 * announce [text] owner: the banner everyone sees; no text clears it
15 * who the driver and the line
16 * help
17 */
18
19 import { AdminError } from "./admin.ts";
20 import { ChatError } from "./chat.ts";
21 import type { Who } from "./identity.ts";
22 import type { Lobby } from "./lobby.ts";
23
24 const USER_ID = /^[A-Za-z0-9_-]{1,64}$/;
25 const MAX_LINE = 4096;
26 const HELP = "say <text> | join | leave | who | end [id] | mute|unmute|ban|unban <id> | delete <n> | pause | resume | speed <n> | announce [text] | help";
27
28 /** Runs one line for `who` and returns what to print back. Never throws for bad input. */
29 export function run(lobby: Lobby, who: Who, line: string): string {

run() has no caller in the app. Wire it to a declared tty in forge.json, with the verified identity passed in as who.

30 if (line.length > MAX_LINE) return "error: line too long";
31 const [word = "", ...rest] = line.trim().split(/\s+/);
32 const command = word.toLowerCase();
33 const arg = rest.join(" ");
34 if (command === "" || command === "help") return HELP;
35 if (command === "who") return describe(lobby);
36 if (!who) return "error: join to take part";
37 try {
38 switch (command) {
39 case "say":
40 lobby.say(who, line.trim().slice(word.length));
41 return "ok";
42 case "join":
43 return lobby.takeControl(who) === "full" ? "error: the line is full" : "ok";
44 case "leave":
45 lobby.turns.leave(who.id);
46 return "ok";
47 case "end":
outdated

The page logs "took X out of the line" before turns.end; this path does not, and does not go through a shared Lobby method. Share one Lobby method and test the log.

48 if (!who.owner) throw new AdminError("only the owner can do that");
49 if (arg === "") lobby.endTurn(who);
50 else if (!USER_ID.test(arg)) return "error: end whom?";
51 else lobby.removeFromLine(who, arg);
52 return "ok";
53 case "mute":
54 case "unmute":
55 if (!who.owner) throw new AdminError("only the owner can do that");
56 if (!USER_ID.test(arg)) return `error: ${command} whom?`;
57 lobby.mute(who, arg, command === "mute");
58 return "ok";
59 case "ban":
60 case "unban":
61 if (!USER_ID.test(arg)) return `error: ${command} whom?`;
62 lobby.ban(who, arg, command === "ban");
63 return "ok";
64 case "delete": {
65 if (!/^\d{1,15}$/.test(arg)) return "error: delete which line?";
66 lobby.deleteLine(who, Number(arg));
67 return "ok";
68 }
69 case "pause":
70 case "resume":
71 lobby.configure(who, { paused: command === "pause" });
72 return "ok";
73 case "speed":
74 if (!/^\d{1,3}$/.test(arg)) return "error: speed is a number from 5 to 100";
75 lobby.configure(who, { maxSpeedPercent: Number(arg) });
76 return "ok";
77 case "announce":
78 lobby.configure(who, { announcement: arg });
79 return "ok";
80 default:
81 return `error: unknown command; ${HELP}`;
82 }
83 } catch (err) {
84 if (err instanceof ChatError || err instanceof AdminError) return `error: ${err.message}`;
85 throw err;
86 }
87 }
88
89 function describe(lobby: Lobby): string {
90 const driver = lobby.turns.driver;
91 const line = lobby.turns.queue.map((p) => p.name).join(", ");
92 return `driving: ${driver ? driver.name : "nobody"}; waiting: ${line || "nobody"}`;
93 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs