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
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
smith/arm:smith/396-each-anonymous-live-viewer-gets-a-stable → main 2 commits fork 2 threads · 2 unresolved
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", () => { | ||
| 74 | 74 | relay = await startRelay({ port: 0, simulation: upstream, lobby }); |
| 75 | 75 | return relay.port; |
| 76 | 76 | }; |
| 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 | ||
| 77 | 111 | const join = async (port: number, headers: Record<string, string> = {}) => { |
| 78 | 112 | const c = await client(port, headers); |
| 79 | 113 | sockets.push(c.ws); |
Software/so101/src/lobby.ts +30 −3
| @@ -27,7 +27,7 @@ | ||
| 27 | 27 | * {"type": "report", …} anyone: the page's own timings (src/viewer-reports.ts), every 5 s (no "id") |
| 28 | 28 | * {"type": "pong"} the answer to {"type": "ping"} |
| 29 | 29 | * {"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), | |
| 31 | 31 | * chat (the last CHAT_FIRST lines of the log, and whether there are more), history (an older page, the same way), |
| 32 | 32 | * said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: |
| 33 | 33 | * settings, hidden lines, mute suggestions), banned (owners and moderators), words (owners only), reports (the owner and verified moderators: the |
| @@ -35,14 +35,17 @@ | ||
| 35 | 35 | * `publish`es to everyone: the arm's status, so a page needs this one socket for the pose, the chat and the queue. |
| 36 | 36 | */ |
| 37 | 37 | |
| 38 | import { randomBytes } from "node:crypto"; | |
| 38 | 39 | import { dirname, join } from "node:path"; |
| 39 | 40 | import type { IncomingMessage } from "node:http"; |
| 40 | 41 | import type { Duplex } from "node:stream"; |
| 41 | 42 | import WebSocket, { WebSocketServer } from "ws"; |
| 42 | 43 | import { Accounts, visitor, type Visitor } from "./accounts.ts"; |
| 44 | import { browserId } from "./browser-id.ts"; | |
| 43 | 45 | import { Admin, AdminError } from "./admin.ts"; |
| 44 | 46 | import { frameBytes, TOO_BIG_CLOSE } from "./frame-limit.ts"; |
| 45 | 47 | import { Chat, ChatError } from "./chat.ts"; |
| 48 | import { nameFor, type GuestName } from "./guest-names.ts"; | |
| 46 | 49 | import { Moderator } from "./moderator.ts"; |
| 47 | 50 | import { ChatRules } from "./chat-rules.ts"; |
| 48 | 51 | import { Reports } from "./reports.ts"; |
| @@ -95,6 +98,8 @@ interface Seat { | ||
| 95 | 98 | /** The forge signed this identity (a guest's chosen name never counts as a moderator). */ |
| 96 | 99 | verified: boolean; |
| 97 | 100 | 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 }; | |
| 98 | 103 | } |
| 99 | 104 | |
| 100 | 105 | const MAX_FRAME = 4096; |
| @@ -129,6 +134,8 @@ export class Lobby { | ||
| 129 | 134 | private readonly presenceMs: number; |
| 130 | 135 | private presenceTimer: ReturnType<typeof setTimeout> | undefined; |
| 131 | 136 | 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 }>(); | |
| 132 | 139 | /** id → when their last line was accepted, for slow mode. */ |
| 133 | 140 | private readonly lastPosted = new Map<string, number>(); |
| 134 | 141 | |
| @@ -288,7 +295,7 @@ export class Lobby { | ||
| 288 | 295 | const who = this.who(req); |
| 289 | 296 | const from = visitor(req); |
| 290 | 297 | 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))); | |
| 292 | 299 | } |
| 293 | 300 | |
| 294 | 301 | close(): void { |
| @@ -301,12 +308,14 @@ export class Lobby { | ||
| 301 | 308 | } |
| 302 | 309 | |
| 303 | 310 | // ------------------------------------------------------------------ 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 { | |
| 305 | 312 | const seat: Seat = { ws, who, from, verified, heard: Date.now() }; |
| 313 | if (!who) seat.guest = this.claim(id); | |
| 306 | 314 | this.seats.add(seat); |
| 307 | 315 | this.presenceChanged(); |
| 308 | 316 | if (who) this.turns.connect(who.id); |
| 309 | 317 | this.send(seat, this.hello(seat)); |
| 318 | if (seat.guest) this.send(seat, { type: "you", guest: seat.guest.name }); | |
| 310 | 319 | this.send(seat, this.state()); |
| 311 | 320 | this.send(seat, this.presence()); |
| 312 | 321 | this.send(seat, this.chatLog()); |
| @@ -342,6 +351,7 @@ export class Lobby { | ||
| 342 | 351 | }); |
| 343 | 352 | ws.on("close", () => { |
| 344 | 353 | this.seats.delete(seat); |
| 354 | if (seat.guest) this.release(seat.guest.id); | |
| 345 | 355 | this.presenceChanged(); |
| 346 | 356 | this.reports.drop(seat); |
| 347 | 357 | if (who) this.turns.disconnect(who.id); |
| @@ -349,6 +359,23 @@ export class Lobby { | ||
| 349 | 359 | ws.on("error", () => ws.terminate()); |
| 350 | 360 | } |
| 351 | 361 | |
| 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 | ||
| 352 | 379 | private handle(seat: Seat, message: unknown): void { |
| 353 | 380 | if (typeof message !== "object" || message === null || Array.isArray(message)) return this.send(seat, { type: "error", error: "frames are JSON objects" }); |
| 354 | 381 | const m = message as Record<string, unknown>; |
Software/so101/src/relay.ts +3
| @@ -63,6 +63,7 @@ import { MachineFeed } from "./machine-feed.ts"; | ||
| 63 | 63 | import { perServo } from "./machine-log.ts"; |
| 64 | 64 | import { parseFrame } from "./safety.ts"; |
| 65 | 65 | import { acceptsGzip, GzipCache, worthCompressing } from "./compress.ts"; |
| 66 | import { browserCookie } from "./browser-id.ts"; | |
| 66 | 67 | import { AccountError, sessionCookie, visitor } from "./accounts.ts"; |
| 67 | 68 | import { CameraSocket } from "./camera-socket.ts"; |
| 68 | 69 | import { OFFLINE_FRAME } from "./offline-frame.ts"; |
| @@ -453,6 +454,8 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 453 | 454 | const boot = JSON.stringify({ link: link(), cameras: cameras.list().map(({ id, name, online }) => ({ id, name, online })) }).replace(/</g, "\\u003c"); |
| 454 | 455 | const body = Buffer.from(response.status === 200 ? html.replace("</head>", `<script type="application/json" id="boot">${boot}</script>\n</head>`) : html); |
| 455 | 456 | 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; | |
| 456 | 459 | if (!acceptsGzip(req.headers)) { |
| 457 | 460 | res.writeHead(response.status, headers); |
| 458 | 461 | return res.end(body); |
new above
offline
This comment and
guestssplit thelastPosteddoc comment above from its field. Put the new field before the/** id → when their last line... */line.