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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Each anonymous /live viewer gets a stable guest name from src/guest-names.ts, keyed by an HttpOnly browser-id cookie - lobby and test only #411

Merged opened this

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

smith/arm:smith/396-each-anonymous-live-viewer-gets-a-stable → main 2 commits fork 2 threads · 2 unresolved

  • Merged. smith/396-each-anonymous-live-viewer-gets-a-stable was merged into main as 05e8009.

Review

Sign in to review this change.
4 files changed +87 −3
Software/so101/src/browser-id.ts added +20
@@ -0,0 +1,20 @@
1 /** The anonymous viewer's browser id: 128 random bits in an HttpOnly cookie, set by the page GET, read on the /live upgrade. */
2 import { randomBytes } from "node:crypto";
3
4 export const BROWSER_COOKIE = "arm_browser";
5 const BROWSER_ID = /^[0-9a-f]{32}$/;
6
7 /** The browser id in a Cookie header, if it is shaped like one. */
8 export function browserId(cookie: string | undefined): string | null {
9 for (const part of (cookie ?? "").split(";")) {
10 const [k, v] = part.trim().split("=", 2);
11 if (k === BROWSER_COOKIE && v && BROWSER_ID.test(v)) return v;
12 }
13 return null;
14 }
15
16 /** The Set-Cookie header for a fresh id, or null when the request already carries a good one. */
17 export function browserCookie(cookie: string | undefined): string | null {
18 if (browserId(cookie)) return null;
19 return `${BROWSER_COOKIE}=${randomBytes(16).toString("hex")}; Path=/; Max-Age=${365 * 24 * 3600}; HttpOnly; Secure; SameSite=Lax`;
20 }
Software/so101/src/lobby.test.ts +34
@@ -74,6 +74,40 @@ describe("lobby", () => {
7474 relay = await startRelay({ port: 0, simulation: upstream, lobby });
7575 return relay.port;
7676 };
77 test("anonymous sockets get stable guest names keyed by the browser-id cookie", async () => {
78 const port = await start();
79 const id = (n: string) => ({ cookie: `arm_browser=${n.repeat(32)}` });
80 const a = await join(port, id("a"));
81 const b = await join(port, id("b"));
82 const mine = (await a.first((m) => m.type === "you")).guest;
83 const theirs = (await b.first((m) => m.type === "you")).guest;
84 expect(mine.name).not.toBe(theirs.name);
85 expect(mine.colour).toMatch(/^#[0-9a-f]{6}$/);
86 a.ws.close();
87 await sleep(50);
88 const again = await join(port, id("a"));
89 expect((await again.first((m) => m.type === "you")).guest).toEqual(mine);
90 const tab = await join(port, id("a"));
91 expect((await tab.first((m) => m.type === "you")).guest).toEqual(mine);
92 });
93
94 test("the page sets an HttpOnly browser-id cookie when absent, and not when a good one comes", async () => {
95 const port = await start();
96 const set = (await fetch(`http://127.0.0.1:${port}/`)).headers.get("set-cookie") ?? "";
97 expect(set).toMatch(/^arm_browser=[0-9a-f]{32}; .*HttpOnly; Secure; SameSite=Lax$/);
98 const again = await fetch(`http://127.0.0.1:${port}/`, { headers: { cookie: `arm_browser=${"c".repeat(32)}` } });
99 expect(again.headers.get("set-cookie")).toBeNull();
100 });
101
102 test("a malformed browser-id cookie is treated as absent", async () => {
103 const port = await start();
104 const a = await join(port, { cookie: "arm_browser=nope" });
105 const b = await join(port, { cookie: "arm_browser=nope" });
106 const x = (await a.first((m) => m.type === "you")).guest;
107 const y = (await b.first((m) => m.type === "you")).guest;
108 expect(x.name).not.toBe(y.name);
109 });
110
77111 const join = async (port: number, headers: Record<string, string> = {}) => {
78112 const c = await client(port, headers);
79113 sockets.push(c.ws);
Software/so101/src/lobby.ts +30 −3
@@ -27,7 +27,7 @@
2727 * {"type": "report", …} anyone: the page's own timings (src/viewer-reports.ts), every 5 s (no "id")
2828 * {"type": "pong"} the answer to {"type": "ping"}
2929 * {"type": "history", "before": 12} anyone: up to HISTORY_PAGE lines older than that one
30 * Server → client: hello (who you are, and whether you may moderate: delete a line), state (the turn, the line, pause, the announcement and the speed cap),
30 * Server → client: hello (who you are, and whether you may moderate: delete a line), you (an anonymous socket only: its guest name and colour, once), state (the turn, the line, pause, the announcement and the speed cap),
3131 * chat (the last CHAT_FIRST lines of the log, and whether there are more), history (an older page, the same way),
3232 * said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only:
3333 * settings, hidden lines, mute suggestions), banned (owners and moderators), words (owners only), reports (the owner and verified moderators: the
@@ -35,14 +35,17 @@
3535 * `publish`es to everyone: the arm's status, so a page needs this one socket for the pose, the chat and the queue.
3636 */
3737
38 import { randomBytes } from "node:crypto";
3839 import { dirname, join } from "node:path";
3940 import type { IncomingMessage } from "node:http";
4041 import type { Duplex } from "node:stream";
4142 import WebSocket, { WebSocketServer } from "ws";
4243 import { Accounts, visitor, type Visitor } from "./accounts.ts";
44 import { browserId } from "./browser-id.ts";
4345 import { Admin, AdminError } from "./admin.ts";
4446 import { frameBytes, TOO_BIG_CLOSE } from "./frame-limit.ts";
4547 import { Chat, ChatError } from "./chat.ts";
48 import { nameFor, type GuestName } from "./guest-names.ts";
4649 import { Moderator } from "./moderator.ts";
4750 import { ChatRules } from "./chat-rules.ts";
4851 import { Reports } from "./reports.ts";
@@ -95,6 +98,8 @@ interface Seat {
9598 /** The forge signed this identity (a guest's chosen name never counts as a moderator). */
9699 verified: boolean;
97100 heard: number;
101 /** An anonymous viewer's browser id, and the name it holds while any of its sockets is open. */
102 guest?: { id: string; name: GuestName };
98103 }
99104
100105 const MAX_FRAME = 4096;
@@ -129,6 +134,8 @@ export class Lobby {
129134 private readonly presenceMs: number;
130135 private presenceTimer: ReturnType<typeof setTimeout> | undefined;
131136 private readonly now: () => number;
137 /** browser id → its guest name and how many sockets hold it. */
138 private readonly guests = new Map<string, { name: GuestName; sockets: number }>();
outdated

This comment and guests split the lastPosted doc comment above from its field. Put the new field before the /** id → when their last line... */ line.

132139 /** id → when their last line was accepted, for slow mode. */
133140 private readonly lastPosted = new Map<string, number>();
134141
@@ -288,7 +295,7 @@ export class Lobby {
288295 const who = this.who(req);
289296 const from = visitor(req);
290297 const verified = Boolean(who) && this.verified(req)?.id === who?.id;
291 this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who, from, verified));
298 this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who, from, verified, browserId(req.headers.cookie)));
292299 }
293300
294301 close(): void {
@@ -301,12 +308,14 @@ export class Lobby {
301308 }
302309
303310 // ------------------------------------------------------------------ sockets
304 private seat(ws: WebSocket, who: Who, from: Visitor, verified: boolean): void {
311 private seat(ws: WebSocket, who: Who, from: Visitor, verified: boolean, id: string | null): void {
305312 const seat: Seat = { ws, who, from, verified, heard: Date.now() };
313 if (!who) seat.guest = this.claim(id);
306314 this.seats.add(seat);
307315 this.presenceChanged();
308316 if (who) this.turns.connect(who.id);
309317 this.send(seat, this.hello(seat));
318 if (seat.guest) this.send(seat, { type: "you", guest: seat.guest.name });
310319 this.send(seat, this.state());
311320 this.send(seat, this.presence());
312321 this.send(seat, this.chatLog());
@@ -342,6 +351,7 @@ export class Lobby {
342351 });
343352 ws.on("close", () => {
344353 this.seats.delete(seat);
354 if (seat.guest) this.release(seat.guest.id);
345355 this.presenceChanged();
346356 this.reports.drop(seat);
347357 if (who) this.turns.disconnect(who.id);
@@ -349,6 +359,23 @@ export class Lobby {
349359 ws.on("error", () => ws.terminate());
350360 }
351361
362 /** Take a socket's place under a browser id (a missing or malformed cookie is a fresh random one), naming it if it is new. */
363 private claim(id: string | null): { id: string; name: GuestName } {
364 const key = id ?? randomBytes(16).toString("hex");
365 let held = this.guests.get(key);
366 if (!held) {
367 held = { name: nameFor(key, [...this.guests.values()].map((g) => g.name.name)), sockets: 0 };
368 this.guests.set(key, held);
369 }
370 held.sockets++;
371 return { id: key, name: held.name };
372 }
373
374 private release(id: string): void {
375 const held = this.guests.get(id);
376 if (held && --held.sockets <= 0) this.guests.delete(id);
377 }
378
352379 private handle(seat: Seat, message: unknown): void {
353380 if (typeof message !== "object" || message === null || Array.isArray(message)) return this.send(seat, { type: "error", error: "frames are JSON objects" });
354381 const m = message as Record<string, unknown>;
Software/so101/src/relay.ts +3
@@ -63,6 +63,7 @@ import { MachineFeed } from "./machine-feed.ts";
6363 import { perServo } from "./machine-log.ts";
6464 import { parseFrame } from "./safety.ts";
6565 import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts";
66 import { browserCookie } from "./browser-id.ts";
6667 import { AccountError, sessionCookie, visitor } from "./accounts.ts";
6768 import { CameraSocket } from "./camera-socket.ts";
6869 import { OFFLINE_FRAME } from "./offline-frame.ts";
@@ -453,6 +454,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
453454 const boot = JSON.stringify({ link: link(), cameras: cameras.list().map(({ id, name, online }) => ({ id, name, online })) }).replace(/</g, "\\u003c");
454455 const body = Buffer.from(response.status === 200 ? html.replace("</head>", `<script type="application/json" id="boot">${boot}</script>\n</head>`) : html);
455456 const headers: Record<string, string> = { "content-type": response.headers.get("content-type") ?? "text/html; charset=utf-8", "cache-control": "no-store", vary: "accept-encoding" };
457 const browser = browserCookie(req.headers.cookie);

Minor: this sets the cookie on every page() response, including non-200 ones. Gate it on response.status === 200.

458 if (browser) headers["set-cookie"] = browser;
456459 if (!acceptsGzip(req.headers)) {
457460 res.writeHead(response.status, headers);
458461 return res.end(body);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs