Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
TOP: friends and family can join in seconds - pick a username in the app (no forge account), then queue and drive #38
Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.
quill/arm:quill/33-top-friends-and-family-can-join-in-secon → main 3 commits fork
8 files
changed +602
−43
Software/README.md +29 −9
| @@ -247,10 +247,17 @@ modules it imports to the page at `/app/<file>`, with the types stripped | ||
| 247 | 247 | bundled, and no other file is served. |
| 248 | 248 | |
| 249 | 249 | **Watch, take turns, chat.** Anyone with the link can watch: the 3D arm, |
| 250 | its live pose and the cameras. Driving needs a forge account and a turn. | |
| 250 | its live pose and the cameras. Driving needs a name and a turn. | |
| 251 | 251 | |
| 252 | - **Take control** (after **Sign in to take control**) joins the queue in | |
| 253 | the panel beside the arm. When nobody is driving, you drive at once. | |
| 252 | - **Join to take control**: pick a name (3-20 letters, digits, `_` or `-`) | |
| 253 | and press the button. That is the whole account: no email, no password, | |
| 254 | no forge account. The app sets a random session token in an HttpOnly, | |
| 255 | Secure, SameSite=Lax cookie for a year, so the same browser stays the | |
| 256 | same person. Names are unique (ignoring case); reserved names (admin, | |
| 257 | owner, …), offensive words and the names of forge users are refused. One | |
| 258 | address may make at most 3 new names an hour. People who have a forge | |
| 259 | account can sign in there instead (the link under the field). | |
| 260 | - **Take control** then joins the queue in the panel beside the arm. When nobody is driving, you drive at once. | |
| 254 | 261 | - A turn lasts 3 minutes (the owner can change it), with a countdown. It ends |
| 255 | 262 | early when you press **Hand back**, after 30 s with no command (also the |
| 256 | 263 | owner's to change), or 10 s after your connection |
| @@ -262,7 +269,7 @@ its live pose and the cameras. Driving needs a forge account and a turn. | ||
| 262 | 269 | the torque, the settings, the `/follow` stream) from anyone else is |
| 263 | 270 | refused before it reaches the arm. When a turn ends, its stream is closed |
| 264 | 271 | and whatever it started is stopped. |
| 265 | - Chat: everyone reads. Signed-in people post one message every 2 s, up to | |
| 272 | - Chat: everyone reads. Everyone who joined posts one message every 2 s, up to | |
| 266 | 273 | 500 characters. The last 200 messages are kept in |
| 267 | 274 | `$FORGE_APP_DATA/so101/chat.json`. Driver changes appear as grey lines. |
| 268 | 275 | - The crew moderator (`src/moderator.ts`): each posted line is checked in the |
| @@ -276,8 +283,16 @@ its live pose and the cameras. Driving needs a forge account and a turn. | ||
| 276 | 283 | Settings and log: `$FORGE_APP_DATA/so101/crew.json`. |
| 277 | 284 | - The owner (anyone who may write this repository) can take control at |
| 278 | 285 | 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. | |
| 286 | the queue, delete messages, mute people and ban them (hover a chat line). | |
| 287 | The owner can also press **Stop** during anyone's turn. | |
| 288 | - A ban bars the person's account, their name and the address they were | |
| 289 | last seen at: their turn ends, they leave the queue, and they cannot | |
| 290 | chat, queue or make a new name from that address (or from the browser | |
| 291 | still holding their cookie). They can still watch. Everyone else at the | |
| 292 | same address is barred too, so a household shares a ban. The ban list, | |
| 293 | with **unban**, sits under the queue for the owner. A hash of the user | |
| 294 | agent is kept with each ban to read, not to block on: too many people | |
| 295 | share one browser for it to tell them apart. | |
| 281 | 296 | |
| 282 | 297 | **Admin.** The owner runs the room from `/admin` (plain forms, no script), |
| 283 | 298 | or from the compact **Admin** bar that only the owner sees beside the queue: |
| @@ -315,9 +330,14 @@ the latest entries. Changes are accepted only from the owner, and only from | ||
| 315 | 330 | the app's own page. |
| 316 | 331 | |
| 317 | 332 | The queue, the countdown and the chat all come over one WebSocket (`/live`): |
| 318 | no polling. The forge says who someone is with a signed `x-forge-identity` | |
| 333 | no polling. People who joined are kept in | |
| 334 | `$FORGE_APP_DATA/so101/accounts.sqlite` (`src/accounts.ts`, bun's built-in | |
| 335 | sqlite: no new dependency). Only a hash of each session token is stored. The | |
| 336 | address is the last `x-forwarded-for` entry, the one the forge's proxy wrote. | |
| 337 | The forge says who its own users are with a signed `x-forge-identity` | |
| 319 | 338 | header. The app checks that signature with `FORGE_APP_IDENTITY_KEY` and |
| 320 | trusts nothing else (`src/identity.ts`). Run locally (no `FORGE_APP_ENV`, | |
| 339 | trusts nothing else for it (`src/identity.ts`). The owner is the admin that | |
| 340 | way, without joining. Run locally (no `FORGE_APP_ENV`, | |
| 321 | 341 | no key), nobody signs in and every visitor drives, as before. Anonymous |
| 322 | 342 | viewing needs the app set to public on the forge. |
| 323 | 343 | |
| @@ -343,7 +363,7 @@ leader** alike. Without a calibration, it falls back to the leader servos' | ||
| 343 | 363 | stored ranges; a leader that has none still connects, and drives once |
| 344 | 364 | calibrated. The server still clamps every frame to the |
| 345 | 365 | follower's limits. `GET`, `PUT` and `DELETE /leader/calibration` act on the |
| 346 | signed-in person's own calibration. A `PUT` is validated against the same | |
| 366 | person's own calibration. A `PUT` is validated against the same | |
| 347 | 367 | module: whole ticks only, and each end at least 100 ticks from the centre on |
| 348 | 368 | opposite sides. Calibrations are kept in |
| 349 | 369 | `$FORGE_APP_DATA/so101/leader-calibrations.json`. `src/leader-map.js` is |
Software/so101/bench/fake-serve.ts +12 −3
| @@ -6,13 +6,15 @@ | ||
| 6 | 6 | * ARM_SERVER=ws://<host>:8101 puts a real arm's `so101 serve` behind the same page: the relay in src/relay.ts |
| 7 | 7 | * sends the arm API, /follow and the cameras there while it answers, and to the simulation when it does not. |
| 8 | 8 | * The owner lists the cameras on /admin/camera-list (kept in cameras.json under the data dir); the first one comes from ARM_SERVER. |
| 9 | * Anyone may watch; only the signed-in person whose turn it is may drive (src/lobby.ts). The forge signs who that is | |
| 10 | * with FORGE_APP_IDENTITY_KEY. Run on one's own machine, away from the forge and with no key, every visitor is the owner. | |
| 9 | * Anyone may watch; only the person whose turn it is may drive (src/lobby.ts). People join with a name picked here | |
| 10 | * (src/accounts.ts, kept in accounts.sqlite); the forge signs who its own signed-in people are with FORGE_APP_IDENTITY_KEY. | |
| 11 | * Run on one's own machine, away from the forge and with no key, every visitor is the owner. | |
| 11 | 12 | * The owner's settings (pause, turn length, speed cap, announcement) and their log live beside the chat (src/admin.ts). |
| 12 | 13 | */ |
| 13 | 14 | import { mkdirSync, mkdtempSync } from "node:fs"; |
| 14 | 15 | import { tmpdir } from "node:os"; |
| 15 | 16 | import { join } from "node:path"; |
| 17 | import { Accounts } from "../src/accounts.ts"; | |
| 16 | 18 | import { FeetechBus } from "../src/bus.ts"; |
| 17 | 19 | import { FakeBus } from "../src/fake-bus.ts"; |
| 18 | 20 | import { CameraHub } from "../src/cameras.ts"; |
| @@ -44,7 +46,14 @@ try { | ||
| 44 | 46 | } |
| 45 | 47 | const identityKey = process.env.FORGE_APP_IDENTITY_KEY ?? ""; |
| 46 | 48 | 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) }) }); | |
| 49 | const lobby = new Lobby({ | |
| 50 | identityKey, | |
| 51 | local, | |
| 52 | chatFile: join(dir, "chat.json"), | |
| 53 | adminFile: join(dir, "admin.json"), | |
| 54 | accounts: new Accounts({ file: join(dir, "accounts.sqlite") }), | |
| 55 | moderator: new Moderator({ file: join(dir, "crew.json"), model: modelFromEnv(process.env) }), | |
| 56 | }); | |
| 48 | 57 | const cameras = new CameraHub({ file: join(dir, "cameras.json"), seed: remote ? [{ name: "Camera 1", source: remote.cameras[0]! }] : [] }); |
| 49 | 58 | |
| 50 | 59 | const leaders = new LeaderCalibrations({ file: join(dir, "leader-calibrations.json") }); |
Software/so101/src/accounts.test.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, readFileSync } from "node:fs"; | |
| 3 | import type { IncomingMessage } from "node:http"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { AccountError, Accounts, checkName, sessionCookie, sessionToken, visitor, type Visitor } from "./accounts.ts"; | |
| 7 | ||
| 8 | const at = (ip: string, token: string | null = null, ua = "ua"): Visitor => ({ ip, ua, token }); | |
| 9 | const status = (fn: () => unknown) => { | |
| 10 | try { | |
| 11 | fn(); | |
| 12 | } catch (err) { | |
| 13 | if (err instanceof AccountError) return `${err.status} ${err.message}`; | |
| 14 | throw err; | |
| 15 | } | |
| 16 | return "ok"; | |
| 17 | }; | |
| 18 | ||
| 19 | describe("names", () => { | |
| 20 | test("3-20 letters, digits, _ or -, trimmed", () => { | |
| 21 | expect(checkName(" mia_2-b ")).toBe("mia_2-b"); | |
| 22 | for (const bad of ["ab", "a".repeat(21), "has space", "émile", "<b>", "", 42, null]) expect(() => checkName(bad)).toThrow(AccountError); | |
| 23 | }); | |
| 24 | ||
| 25 | test("reserved and offensive names are refused, look-alikes included; ordinary names are not", () => { | |
| 26 | for (const bad of ["admin", "Owner", "m0d", "SYSTEM", "forge", "fuck_it", "sh1tlord", "xXn4z1Xx"]) expect(() => checkName(bad)).toThrow(AccountError); | |
| 27 | for (const good of ["grandma", "Dickens", "peacock", "grape_ape", "spicy", "swanky", "admiral"]) expect(checkName(good)).toBe(good); | |
| 28 | }); | |
| 29 | }); | |
| 30 | ||
| 31 | describe("accounts", () => { | |
| 32 | test("a name makes a person and a token; the token finds them again, and only it does", () => { | |
| 33 | const accounts = new Accounts(); | |
| 34 | const { person, token } = accounts.create("Mia", at("10.0.0.1")); | |
| 35 | expect(person).toMatchObject({ name: "Mia", owner: false }); | |
| 36 | expect(person.id).toMatch(/^a-[A-Za-z0-9_-]+$/); | |
| 37 | expect(accounts.byToken(token)).toEqual(person); | |
| 38 | expect(accounts.byToken(token.slice(0, -1) + (token.endsWith("A") ? "B" : "A"))).toBeNull(); | |
| 39 | expect(accounts.byToken(null)).toBeNull(); | |
| 40 | }); | |
| 41 | ||
| 42 | test("a name is taken whatever its case, and a forge user's name is theirs", () => { | |
| 43 | const accounts = new Accounts(); | |
| 44 | accounts.create("Mia", at("10.0.0.1")); | |
| 45 | expect(status(() => accounts.create("mia", at("10.0.0.2")))).toBe("409 mia is taken"); | |
| 46 | accounts.reserve("trevato"); | |
| 47 | expect(status(() => accounts.create("TREVATO", at("10.0.0.2")))).toBe("409 TREVATO is taken"); | |
| 48 | }); | |
| 49 | ||
| 50 | test("at most 3 new names an hour from one address", () => { | |
| 51 | let now = 1_000_000; | |
| 52 | const accounts = new Accounts({ now: () => now }); | |
| 53 | for (const name of ["one", "two", "three"]) accounts.create(name, at("10.0.0.1")); | |
| 54 | expect(status(() => accounts.create("four", at("10.0.0.1")))).toStartWith("429"); | |
| 55 | expect(status(() => accounts.create("four", at("10.0.0.2")))).toBe("ok"); | |
| 56 | now += 3_600_001; | |
| 57 | expect(status(() => accounts.create("five", at("10.0.0.1")))).toBe("ok"); | |
| 58 | }); | |
| 59 | ||
| 60 | test("a ban bars the account, the name and the address; no new name from there or from that browser; unban lifts it", () => { | |
| 61 | const accounts = new Accounts(); | |
| 62 | const { person, token } = accounts.create("troll", at("10.0.0.9")); | |
| 63 | accounts.ban(person, { ip: "10.0.0.9", ua: "abc" }, "trevato"); | |
| 64 | expect(accounts.banned(person.id, null, null)).toBe(true); | |
| 65 | expect(accounts.banned("someone-else", "TROLL", null)).toBe(true); | |
| 66 | expect(accounts.banned("someone-else", "mia", "10.0.0.9")).toBe(true); | |
| 67 | expect(accounts.banned("someone-else", "mia", "10.0.0.10")).toBe(false); | |
| 68 | expect(status(() => accounts.create("troll2", at("10.0.0.9")))).toStartWith("403"); | |
| 69 | expect(status(() => accounts.create("troll3", at("10.1.1.1", token)))).toStartWith("403"); // a new address, the same browser | |
| 70 | expect(status(() => accounts.create("troll", at("10.1.1.2")))).toStartWith("409"); | |
| 71 | expect(accounts.bans()).toEqual([expect.objectContaining({ id: person.id, name: "troll", ip: "10.0.0.9", ua: "abc", by: "trevato" })]); | |
| 72 | expect(accounts.unban(person.id)).toBe(true); | |
| 73 | expect(accounts.banned(person.id, "troll", "10.0.0.9")).toBe(false); | |
| 74 | expect(status(() => accounts.create("troll2", at("10.0.0.9")))).toBe("ok"); | |
| 75 | }); | |
| 76 | ||
| 77 | test("people and bans survive a restart; the file never holds a token", () => { | |
| 78 | const file = join(mkdtempSync(join(tmpdir(), "so101-accounts-")), "accounts.sqlite"); | |
| 79 | const first = new Accounts({ file }); | |
| 80 | const { person, token } = first.create("Mia", at("10.0.0.1")); | |
| 81 | const troll = first.create("troll", at("10.0.0.2")).person; | |
| 82 | first.ban(troll, null, "trevato"); | |
| 83 | first.close(); | |
| 84 | expect(readFileSync(file).includes(Buffer.from(token))).toBe(false); | |
| 85 | const again = new Accounts({ file }); | |
| 86 | expect(again.byToken(token)).toEqual(person); | |
| 87 | expect(again.banned(troll.id, null, null)).toBe(true); | |
| 88 | again.close(); | |
| 89 | }); | |
| 90 | }); | |
| 91 | ||
| 92 | describe("the request", () => { | |
| 93 | const req = (headers: Record<string, string>, remoteAddress = "::ffff:127.0.0.1") => ({ headers, socket: { remoteAddress } }) as unknown as IncomingMessage; | |
| 94 | ||
| 95 | test("the address is the one the proxy wrote last, not what the client claims", () => { | |
| 96 | expect(visitor(req({})).ip).toBe("127.0.0.1"); | |
| 97 | expect(visitor(req({ "x-forwarded-for": "6.6.6.6, 203.0.113.7" })).ip).toBe("203.0.113.7"); | |
| 98 | expect(visitor(req({ "user-agent": "a" })).ua).not.toBe(visitor(req({ "user-agent": "b" })).ua); | |
| 99 | }); | |
| 100 | ||
| 101 | test("the session cookie: HttpOnly, Secure, SameSite=Lax, a year; only a well-formed token is read back", () => { | |
| 102 | const token = "A".repeat(43); | |
| 103 | expect(sessionCookie(token)).toBe(`arm_session=${token}; Path=/; Max-Age=31536000; HttpOnly; Secure; SameSite=Lax`); | |
| 104 | expect(sessionToken(`x=1; arm_session=${token}`)).toBe(token); | |
| 105 | expect(sessionToken("arm_session=short")).toBeNull(); | |
| 106 | expect(sessionToken(undefined)).toBeNull(); | |
| 107 | }); | |
| 108 | }); |
Software/so101/src/accounts.ts added +193
| @@ -0,0 +1,193 @@ | ||
| 1 | /** | |
| 2 | * People who joined in the app itself: a username and nothing else. No email, no password; the browser keeps a long | |
| 3 | * random session token in an HttpOnly cookie, and the same browser is the same person for a year. Only the token's | |
| 4 | * SHA-256 is stored, so the file alone signs nobody in. | |
| 5 | * | |
| 6 | * Names: 3-20 letters, digits, _ or -; unique ignoring case; no reserved or offensive words; never a name someone | |
| 7 | * signed in through the forge already goes by (so nobody can pass for the owner). At most `perIpPerHour` new names | |
| 8 | * from one address in an hour. | |
| 9 | * | |
| 10 | * Bans: banning someone bars their account, their name, and the address they were last seen at; the ban also keeps a | |
| 11 | * hash of their user agent, for the owner to read (it is too common to block on: half a family shares one browser). | |
| 12 | * A barred visitor still watches. A browser still holding a banned account's cookie cannot make a new name either. | |
| 13 | * | |
| 14 | * Kept with bun:sqlite in one file under FORGE_APP_DATA; ":memory:" (the default) for tests and local runs. | |
| 15 | */ | |
| 16 | ||
| 17 | import { Database } from "bun:sqlite"; | |
| 18 | import { createHash, randomBytes } from "node:crypto"; | |
| 19 | import { mkdirSync } from "node:fs"; | |
| 20 | import type { IncomingMessage } from "node:http"; | |
| 21 | import { dirname } from "node:path"; | |
| 22 | import type { Person } from "./identity.ts"; | |
| 23 | ||
| 24 | export const COOKIE = "arm_session"; | |
| 25 | export const COOKIE_MAX_AGE_S = 365 * 24 * 3600; | |
| 26 | ||
| 27 | export class AccountError extends Error { | |
| 28 | readonly status: number; | |
| 29 | constructor(status: number, message: string) { | |
| 30 | super(message); | |
| 31 | this.status = status; | |
| 32 | } | |
| 33 | } | |
| 34 | ||
| 35 | export interface Visitor { | |
| 36 | /** The client's address, as the forge's proxy saw it. */ | |
| 37 | ip: string; | |
| 38 | /** SHA-256 of the user agent, shortened: a light fingerprint for the ban list. */ | |
| 39 | ua: string; | |
| 40 | /** The session token the browser sent, if any. */ | |
| 41 | token: string | null; | |
| 42 | } | |
| 43 | ||
| 44 | export interface Ban { | |
| 45 | id: string; | |
| 46 | name: string; | |
| 47 | ip: string; | |
| 48 | ua: string; | |
| 49 | at: number; | |
| 50 | by: string; | |
| 51 | } | |
| 52 | ||
| 53 | export interface AccountsOptions { | |
| 54 | /** The sqlite file; ":memory:" (the default) keeps everything in memory. */ | |
| 55 | file?: string; | |
| 56 | perIpPerHour?: number; | |
| 57 | now?: () => number; | |
| 58 | } | |
| 59 | ||
| 60 | const NAME = /^[A-Za-z0-9_-]{3,20}$/; | |
| 61 | const TOKEN = /^[A-Za-z0-9_-]{43}$/; | |
| 62 | /** Names that would claim a role. Matched whole, after folding look-alike digits. */ | |
| 63 | const RESERVED = new Set(["admin", "administrator", "owner", "moderator", "mod", "mods", "system", "forge", "root", "staff", "support", "official", "anonymous", "anon", "nobody", "null", "undefined", "everyone", "local"]); | |
| 64 | /** Never part of a name, wherever they appear. Kept short and unambiguous, so no ordinary name trips over it. */ | |
| 65 | const BLOCKED = ["fuck", "shit", "cunt", "nigger", "nigga", "faggot", "fag", "retard", "whore", "slut", "rapist", "nazi", "hitler", "kike", "chink", "tranny", "pussy", "penis", "vagina", "porn", "bitch", "bastard", "asshole", "wanker", "twat"]; | |
| 66 | const FOLD: Record<string, string> = { "0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "8": "b", "9": "g", "$": "s", "@": "a" }; | |
| 67 | ||
| 68 | /** The canonical form a name is compared in: lower case, look-alike digits folded, separators dropped. */ | |
| 69 | const fold = (name: string) => name.toLowerCase().replace(/[01345789$@]/g, (c) => FOLD[c] ?? c).replace(/[_-]/g, ""); | |
| 70 | ||
| 71 | /** The name as typed, trimmed, or an AccountError saying what is wrong with it. */ | |
| 72 | export function checkName(raw: unknown): string { | |
| 73 | if (typeof raw !== "string") throw new AccountError(400, "a name is text"); | |
| 74 | const name = raw.trim(); | |
| 75 | if (!NAME.test(name)) throw new AccountError(400, "3-20 letters, digits, _ or -"); | |
| 76 | const folded = fold(name); | |
| 77 | if (RESERVED.has(folded) || RESERVED.has(name.toLowerCase())) throw new AccountError(400, "that name is reserved"); | |
| 78 | if (BLOCKED.some((word) => folded.includes(word))) throw new AccountError(400, "pick another name"); | |
| 79 | return name; | |
| 80 | } | |
| 81 | ||
| 82 | const hash = (text: string) => createHash("sha256").update(text).digest("hex"); | |
| 83 | ||
| 84 | /** Who is at the other end of this request. Behind the forge the last x-forwarded-for entry is the one its proxy wrote; earlier ones are the client's say. */ | |
| 85 | export function visitor(req: IncomingMessage): Visitor { | |
| 86 | const forwarded = req.headers["x-forwarded-for"]; | |
| 87 | const hops = (Array.isArray(forwarded) ? forwarded.join(",") : forwarded ?? "").split(",").map((s) => s.trim()).filter(Boolean); | |
| 88 | const ip = (hops.at(-1) ?? req.socket?.remoteAddress ?? "").replace(/^::ffff:/, "").slice(0, 64); | |
| 89 | return { ip, ua: hash(String(req.headers["user-agent"] ?? "")).slice(0, 16), token: sessionToken(req.headers.cookie) }; | |
| 90 | } | |
| 91 | ||
| 92 | /** The session token in a Cookie header, if it is shaped like one. */ | |
| 93 | export function sessionToken(cookie: string | undefined): string | null { | |
| 94 | for (const part of (cookie ?? "").split(";")) { | |
| 95 | const [k, v] = part.trim().split("=", 2); | |
| 96 | if (k === COOKIE && v && TOKEN.test(v)) return v; | |
| 97 | } | |
| 98 | return null; | |
| 99 | } | |
| 100 | ||
| 101 | /** The Set-Cookie header for a session: a year, this site only, never readable by script. */ | |
| 102 | export const sessionCookie = (token: string) => `${COOKIE}=${token}; Path=/; Max-Age=${COOKIE_MAX_AGE_S}; HttpOnly; Secure; SameSite=Lax`; | |
| 103 | ||
| 104 | interface UserRow { | |
| 105 | id: string; | |
| 106 | name: string; | |
| 107 | ip: string; | |
| 108 | ua: string; | |
| 109 | } | |
| 110 | ||
| 111 | export class Accounts { | |
| 112 | private readonly db: Database; | |
| 113 | private readonly perIpPerHour: number; | |
| 114 | private readonly now: () => number; | |
| 115 | ||
| 116 | constructor(options: AccountsOptions = {}) { | |
| 117 | const file = options.file ?? ":memory:"; | |
| 118 | if (file !== ":memory:") mkdirSync(dirname(file), { recursive: true }); | |
| 119 | this.db = new Database(file, { create: true, strict: true }); | |
| 120 | this.perIpPerHour = options.perIpPerHour ?? 3; | |
| 121 | this.now = options.now ?? Date.now; | |
| 122 | this.db.run("PRAGMA journal_mode = WAL"); | |
| 123 | this.db.run(`CREATE TABLE IF NOT EXISTS users ( | |
| 124 | id TEXT PRIMARY KEY, name TEXT NOT NULL, key TEXT NOT NULL UNIQUE, token TEXT NOT NULL UNIQUE, | |
| 125 | ip TEXT NOT NULL, ua TEXT NOT NULL, created INTEGER NOT NULL, seen INTEGER NOT NULL)`); | |
| 126 | this.db.run("CREATE INDEX IF NOT EXISTS users_ip ON users (ip, created)"); | |
| 127 | this.db.run("CREATE TABLE IF NOT EXISTS reserved (key TEXT PRIMARY KEY, name TEXT NOT NULL)"); | |
| 128 | this.db.run(`CREATE TABLE IF NOT EXISTS bans ( | |
| 129 | id TEXT PRIMARY KEY, name TEXT NOT NULL, key TEXT NOT NULL, ip TEXT NOT NULL, ua TEXT NOT NULL, at INTEGER NOT NULL, by TEXT NOT NULL)`); | |
| 130 | this.db.run("CREATE INDEX IF NOT EXISTS bans_key ON bans (key)"); | |
| 131 | this.db.run("CREATE INDEX IF NOT EXISTS bans_ip ON bans (ip)"); | |
| 132 | } | |
| 133 | ||
| 134 | /** Make a new person from a name, or say why not. Returns them and the token their cookie carries. */ | |
| 135 | create(raw: unknown, from: Visitor): { person: Person; token: string } { | |
| 136 | const name = checkName(raw); | |
| 137 | const key = name.toLowerCase(); | |
| 138 | if (from.token) { | |
| 139 | const held = this.db.query<{ id: string }, [string]>("SELECT id FROM users WHERE token = ?").get(hash(from.token)); | |
| 140 | if (held && this.banned(held.id, null, null)) throw new AccountError(403, "you are banned: you can still watch"); | |
| 141 | } | |
| 142 | if (from.ip && this.db.query("SELECT 1 FROM bans WHERE ip = ?").get(from.ip)) throw new AccountError(403, "you are banned: you can still watch"); | |
| 143 | if (this.db.query("SELECT 1 FROM users WHERE key = ?").get(key) || this.db.query("SELECT 1 FROM reserved WHERE key = ?").get(key) || this.db.query("SELECT 1 FROM bans WHERE key = ?").get(key)) { | |
| 144 | throw new AccountError(409, `${name} is taken`); | |
| 145 | } | |
| 146 | const now = this.now(); | |
| 147 | const recent = this.db.query<{ n: number }, [string, number]>("SELECT count(*) AS n FROM users WHERE ip = ? AND created > ?").get(from.ip, now - 3_600_000)!.n; | |
| 148 | if (recent >= this.perIpPerHour) throw new AccountError(429, `at most ${this.perIpPerHour} new names an hour from one place; try again later`); | |
| 149 | const id = `a-${randomBytes(9).toString("base64url")}`; | |
| 150 | const token = randomBytes(32).toString("base64url"); | |
| 151 | this.db.query("INSERT INTO users (id, name, key, token, ip, ua, created, seen) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(id, name, key, hash(token), from.ip, from.ua, now, now); | |
| 152 | return { person: { id, name, owner: false }, token }; | |
| 153 | } | |
| 154 | ||
| 155 | /** The person a session token belongs to, or null. Notes where they were last seen, for a ban. */ | |
| 156 | byToken(token: string | null, from?: Visitor): Person | null { | |
| 157 | if (!token || !TOKEN.test(token)) return null; | |
| 158 | const row = this.db.query<UserRow, [string]>("SELECT id, name, ip, ua FROM users WHERE token = ?").get(hash(token)); | |
| 159 | if (!row) return null; | |
| 160 | if (from && (from.ip !== row.ip || from.ua !== row.ua)) this.db.query("UPDATE users SET ip = ?, ua = ?, seen = ? WHERE id = ?").run(from.ip, from.ua, this.now(), row.id); | |
| 161 | return { id: row.id, name: row.name, owner: false }; | |
| 162 | } | |
| 163 | ||
| 164 | /** A forge user's name is theirs here too: nobody may join under it. */ | |
| 165 | reserve(name: string): void { | |
| 166 | this.db.query("INSERT OR IGNORE INTO reserved (key, name) VALUES (?, ?)").run(name.toLowerCase(), name); | |
| 167 | } | |
| 168 | ||
| 169 | /** Whether this person, or anyone at this address, is barred from taking part. */ | |
| 170 | banned(id: string, name: string | null, ip: string | null): boolean { | |
| 171 | return Boolean(this.db.query("SELECT 1 FROM bans WHERE id = ? OR key = ? OR ip = ? LIMIT 1").get(id, name?.toLowerCase() ?? "\0", ip || "\0")); | |
| 172 | } | |
| 173 | ||
| 174 | /** Bar a person: their account, their name, and the address and browser they were last seen with. */ | |
| 175 | ban(who: Person, seen: Pick<Visitor, "ip" | "ua"> | null, by: string): Ban { | |
| 176 | const row = this.db.query<UserRow, [string]>("SELECT id, name, ip, ua FROM users WHERE id = ?").get(who.id); | |
| 177 | const ban: Ban = { id: who.id, name: who.name, ip: seen?.ip || row?.ip || "", ua: seen?.ua || row?.ua || "", at: this.now(), by }; | |
| 178 | this.db.query("INSERT OR REPLACE INTO bans (id, name, key, ip, ua, at, by) VALUES (?, ?, ?, ?, ?, ?, ?)").run(ban.id, ban.name, ban.name.toLowerCase(), ban.ip, ban.ua, ban.at, ban.by); | |
| 179 | return ban; | |
| 180 | } | |
| 181 | ||
| 182 | unban(id: string): boolean { | |
| 183 | return this.db.query("DELETE FROM bans WHERE id = ?").run(id).changes > 0; | |
| 184 | } | |
| 185 | ||
| 186 | bans(): Ban[] { | |
| 187 | return this.db.query<Ban, []>("SELECT id, name, ip, ua, at, by FROM bans ORDER BY at").all(); | |
| 188 | } | |
| 189 | ||
| 190 | close(): void { | |
| 191 | this.db.close(); | |
| 192 | } | |
| 193 | } |
Software/so101/src/lobby.test.ts +113 −6
| @@ -9,6 +9,7 @@ import { FeetechBus } from "./bus.ts"; | ||
| 9 | 9 | import { Chat } from "./chat.ts"; |
| 10 | 10 | import { FakeBus } from "./fake-bus.ts"; |
| 11 | 11 | import { sign } from "./identity.ts"; |
| 12 | import { Accounts } from "./accounts.ts"; | |
| 12 | 13 | import { Lobby } from "./lobby.ts"; |
| 13 | 14 | import { startRelay, type RunningRelay } from "./relay.ts"; |
| 14 | 15 | import { startServer, type RunningServer } from "./server.ts"; |
| @@ -66,8 +67,8 @@ describe("lobby", () => { | ||
| 66 | 67 | lobby?.close(); |
| 67 | 68 | relay = lobby = undefined; |
| 68 | 69 | }); |
| 69 | const start = async (turns?: Turns, chat = new Chat(), admin = new Admin(), upstream = `http://127.0.0.1:${simulation.port}`) => { | |
| 70 | lobby = new Lobby({ identityKey: KEY, turns: turns ?? new Turns(), chat, admin }); | |
| 70 | const start = async (turns?: Turns, chat = new Chat(), admin = new Admin(), upstream = `http://127.0.0.1:${simulation.port}`, accounts = new Accounts()) => { | |
| 71 | lobby = new Lobby({ identityKey: KEY, turns: turns ?? new Turns(), chat, admin, accounts }); | |
| 71 | 72 | relay = await startRelay({ port: 0, simulation: upstream, lobby }); |
| 72 | 73 | return relay.port; |
| 73 | 74 | }; |
| @@ -96,10 +97,10 @@ describe("lobby", () => { | ||
| 96 | 97 | expect((await fetch(`http://127.0.0.1:${port}/status`)).status).toBe(200); |
| 97 | 98 | const refused = await torque(port); |
| 98 | 99 | expect(refused.status).toBe(401); |
| 99 | expect(((await refused.json()) as { error: string }).error).toContain("sign in"); | |
| 100 | expect(await follow(port)).toBe("4401 sign in to take control"); | |
| 100 | expect(((await refused.json()) as { error: string }).error).toContain("join"); | |
| 101 | expect(await follow(port)).toBe("4401 join to take control"); | |
| 101 | 102 | anon.send({ type: "join" }); |
| 102 | expect((await anon.next((m) => m.type === "error")).error).toContain("sign in"); | |
| 103 | expect((await anon.next((m) => m.type === "error")).error).toContain("join to take part"); | |
| 103 | 104 | }); |
| 104 | 105 | |
| 105 | 106 | test("a forged identity header is nobody", async () => { |
| @@ -221,7 +222,7 @@ describe("lobby", () => { | ||
| 221 | 222 | alice.send({ type: "post", text: "again" }); |
| 222 | 223 | expect((await alice.next((m) => m.type === "error")).error).toContain("one message every 2 s"); |
| 223 | 224 | anon.send({ type: "post", text: "me too" }); |
| 224 | expect((await anon.next((m) => m.type === "error")).error).toContain("sign in"); | |
| 225 | expect((await anon.next((m) => m.type === "error")).error).toContain("join to take part"); | |
| 225 | 226 | |
| 226 | 227 | owner.send({ type: "delete", id: said.message.id }); |
| 227 | 228 | expect((await anon.next((m) => m.type === "unsaid")).id).toBe(said.message.id); |
| @@ -233,6 +234,112 @@ describe("lobby", () => { | ||
| 233 | 234 | expect((await late.first((m) => m.type === "chat")).messages).toEqual([]); |
| 234 | 235 | }); |
| 235 | 236 | |
| 237 | /** A fresh browser picks a name: the headers it sends from then on (its cookie, and the address the proxy saw). */ | |
| 238 | const enter = async (port: number, name: string, ip = "198.51.100.1", headers: Record<string, string> = {}) => { | |
| 239 | const r = await fetch(`http://127.0.0.1:${port}/join`, { method: "POST", headers: { "content-type": "application/json", "x-forwarded-for": ip, ...headers }, body: JSON.stringify({ name }) }); | |
| 240 | const cookie = r.headers.get("set-cookie"); | |
| 241 | return { status: r.status, body: (await r.json()) as Msg, cookie, as: { "x-forwarded-for": ip, cookie: cookie?.split(";")[0] ?? "" } }; | |
| 242 | }; | |
| 243 | ||
| 244 | test("join: a fresh browser picks a name, gets an HttpOnly cookie, and queues and drives with it", async () => { | |
| 245 | const port = await start(); | |
| 246 | const mia = await enter(port, "Mia"); | |
| 247 | expect(mia.status).toBe(200); | |
| 248 | expect(mia.body.you).toMatchObject({ name: "Mia", owner: false }); | |
| 249 | expect(mia.cookie).toMatch(/^arm_session=[A-Za-z0-9_-]{43}; Path=\/; Max-Age=31536000; HttpOnly; Secure; SameSite=Lax$/); | |
| 250 | ||
| 251 | const room = await join(port, mia.as); | |
| 252 | expect((await room.first((m) => m.type === "hello")).you).toEqual(mia.body.you); | |
| 253 | room.send({ type: "join" }); | |
| 254 | await room.next(drivingIs("Mia")); | |
| 255 | expect((await torque(port, mia.as)).status).toBe(200); | |
| 256 | expect((await torque(port, { "x-forwarded-for": "198.51.100.1" })).status).toBe(401); // the address alone is nobody | |
| 257 | room.send({ type: "post", text: "hi from Mia" }); | |
| 258 | expect((await room.next((m) => m.type === "said" && m.message.from)).message.from).toEqual({ id: mia.body.you.id, name: "Mia" }); | |
| 259 | ||
| 260 | const again = await enter(port, "Mia2", "198.51.100.1", { cookie: mia.as.cookie }); | |
| 261 | expect(again.status).toBe(409); // one browser, one person | |
| 262 | expect(again.body.you.name).toBe("Mia"); | |
| 263 | }); | |
| 264 | ||
| 265 | test("join: a duplicate name is refused whatever its case; a bad one says why; only this page may join", async () => { | |
| 266 | const port = await start(); | |
| 267 | expect((await enter(port, "Mia")).status).toBe(200); | |
| 268 | const twin = await enter(port, "mIA", "198.51.100.2"); | |
| 269 | expect(twin.status).toBe(409); | |
| 270 | expect(twin.body.error).toBe("mIA is taken"); | |
| 271 | expect(twin.cookie).toBeNull(); | |
| 272 | expect((await enter(port, "a b", "198.51.100.2")).body.error).toContain("3-20"); | |
| 273 | expect((await enter(port, "admin", "198.51.100.2")).body.error).toContain("reserved"); | |
| 274 | expect((await enter(port, "Zed", "198.51.100.2", { origin: "https://evil.example" })).status).toBe(403); | |
| 275 | expect((await fetch(`http://127.0.0.1:${port}/join`)).status).toBe(405); | |
| 276 | }); | |
| 277 | ||
| 278 | test("join: the owner signed in to the forge is the admin without joining, and their name is reserved", async () => { | |
| 279 | const port = await start(); | |
| 280 | const owner = await join(port, OWNER); | |
| 281 | expect((await owner.first((m) => m.type === "hello")).you).toEqual({ id: "u-owner", name: "trevato", owner: true }); | |
| 282 | expect(await owner.first((m) => m.type === "banned")).toMatchObject({ banned: [] }); | |
| 283 | const already = await enter(port, "x-owner", "198.51.100.3", OWNER); | |
| 284 | expect(already.status).toBe(409); | |
| 285 | expect((await enter(port, "Trevato", "198.51.100.3")).status).toBe(409); | |
| 286 | }); | |
| 287 | ||
| 288 | test("join: a forged forge header beside a real cookie changes nothing", async () => { | |
| 289 | const port = await start(); | |
| 290 | const mia = await enter(port, "Mia"); | |
| 291 | const later = Date.now() + 60_000; | |
| 292 | const forged = { ...mia.as, "x-forge-identity": `u-owner|trevato|admin|${later}`, "x-forge-signature": sign(`u-owner|trevato|admin|${later}`, "not the key") }; | |
| 293 | const room = await join(port, forged); | |
| 294 | expect((await room.first((m) => m.type === "hello")).you).toMatchObject({ name: "Mia", owner: false }); | |
| 295 | expect((await torque(port, forged)).status).toBe(403); | |
| 296 | }); | |
| 297 | ||
| 298 | test("ban: the turn ends, chat and queue are refused, watching goes on, and no new name comes from that address", async () => { | |
| 299 | const port = await start(); | |
| 300 | const troll = await enter(port, "troll", "203.0.113.66"); | |
| 301 | const owner = await join(port, OWNER); | |
| 302 | const room = await join(port, troll.as); | |
| 303 | await room.first((m) => m.type === "hello"); | |
| 304 | room.send({ type: "join" }); | |
| 305 | await owner.next(drivingIs("troll")); | |
| 306 | ||
| 307 | const id = troll.body.you.id; | |
| 308 | room.send({ type: "ban", id: "u-owner", on: true }); | |
| 309 | expect((await room.next((m) => m.type === "error")).error).toContain("only the owner"); | |
| 310 | owner.send({ type: "ban", id, on: true }); | |
| 311 | expect((await room.next((m) => m.type === "hello")).banned).toBe(true); | |
| 312 | await owner.next(drivingIs(null)); | |
| 313 | expect((await owner.next((m) => m.type === "banned")).banned).toEqual([expect.objectContaining({ id, name: "troll", by: "trevato" })]); | |
| 314 | expect((await owner.first((m) => m.type === "admin" && m.log.length > 0)).log.at(-1)).toMatchObject({ what: "banned troll" }); | |
| 315 | ||
| 316 | const refused = await torque(port, troll.as); | |
| 317 | expect(refused.status).toBe(403); | |
| 318 | expect(((await refused.json()) as { error: string }).error).toContain("banned"); | |
| 319 | expect(await follow(port, troll.as)).toStartWith("4403 you are banned"); | |
| 320 | room.send({ type: "join" }); | |
| 321 | expect((await room.next((m) => m.type === "error")).error).toContain("banned"); | |
| 322 | room.send({ type: "post", text: "let me back" }); | |
| 323 | expect((await room.next((m) => m.type === "error")).error).toContain("banned"); | |
| 324 | expect((await fetch(`http://127.0.0.1:${port}/status`, { headers: troll.as })).status).toBe(200); | |
| 325 | ||
| 326 | expect((await enter(port, "nice_person", "203.0.113.66")).status).toBe(403); // the same address | |
| 327 | expect((await enter(port, "nice_person", "192.0.2.5", { cookie: troll.as.cookie })).status).toBe(409); // the same browser is still troll | |
| 328 | expect((await enter(port, "nice_person", "192.0.2.5")).status).toBe(200); | |
| 329 | ||
| 330 | owner.send({ type: "ban", id, on: false }); | |
| 331 | expect((await room.next((m) => m.type === "hello")).banned).toBe(false); | |
| 332 | expect((await enter(port, "another", "203.0.113.66")).status).toBe(200); | |
| 333 | }); | |
| 334 | ||
| 335 | test("join: at most 3 new names an hour from one address", async () => { | |
| 336 | const port = await start(); | |
| 337 | for (const name of ["one", "two", "three"]) expect((await enter(port, name, "198.51.100.9")).status).toBe(200); | |
| 338 | const fourth = await enter(port, "four", "198.51.100.9"); | |
| 339 | expect(fourth.status).toBe(429); | |
| 340 | expect(fourth.body.error).toContain("at most 3"); | |
| 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 +73 −13
| @@ -1,7 +1,8 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * The room around the arm, over one WebSocket (/live): who drives, who waits, and the chat. Everyone may |
| 3 | * watch; a signed-in person may ask to drive and may post; the owner may override. The relay asks the lobby | |
| 4 | * who is behind each request (`who`) and whether they may command the arm (`refusal`). | |
| 3 | * watch; someone who joined (a name picked in the app, src/accounts.ts) or signed in through the forge may ask to | |
| 4 | * drive and may post; the owner may override, mute and ban. A banned visitor still watches. The relay asks the | |
| 5 | * lobby who is behind each request (`who`) and whether they may command the arm (`refusal`). | |
| 5 | 6 | * |
| 6 | 7 | * Client → server, one JSON object per frame: |
| 7 | 8 | * {"type": "join"} ask to drive (the owner takes over at once) |
| @@ -15,15 +16,17 @@ | ||
| 15 | 16 | * {"type": "crew", "settings": {"enabled", "rules", "maxPerMinute"}} owner: the moderator's settings |
| 16 | 17 | * {"type": "restore", "id": 12} owner: put back a line the crew hid |
| 17 | 18 | * {"type": "dismiss", "id": 12} owner: dismiss a mute suggestion |
| 19 | * {"type": "ban", "id": "<user id>", "on": true|false} owner: bars their account, name and address; they still watch | |
| 18 | 20 | * {"type": "pong"} the answer to {"type": "ping"} |
| 19 | 21 | * Server → client: hello (who you are), state (the turn, the line, pause, the announcement and the speed cap), |
| 20 | 22 | * chat (the log), said, unsaid, muted, admin (owners only: the settings and the admin log), crew (owners only: |
| 21 | * settings, hidden lines, mute suggestions), ping, error. | |
| 23 | * settings, hidden lines, mute suggestions), banned (owners only), ping, error. | |
| 22 | 24 | */ |
| 23 | 25 | |
| 24 | 26 | import type { IncomingMessage } from "node:http"; |
| 25 | 27 | import type { Duplex } from "node:stream"; |
| 26 | 28 | import WebSocket, { WebSocketServer } from "ws"; |
| 29 | import { Accounts, visitor, type Visitor } from "./accounts.ts"; | |
| 27 | 30 | import { Admin, AdminError } from "./admin.ts"; |
| 28 | 31 | import { Chat, ChatError } from "./chat.ts"; |
| 29 | 32 | import { Moderator } from "./moderator.ts"; |
| @@ -35,6 +38,8 @@ export interface LobbyOptions { | ||
| 35 | 38 | identityKey?: string; |
| 36 | 39 | /** A forge-less run on one machine: every visitor is the owner and may command the arm (there is no one to sign in as). */ |
| 37 | 40 | local?: boolean; |
| 41 | /** The people who joined in the app, and the bans; none keeps them in memory. */ | |
| 42 | accounts?: Accounts; | |
| 38 | 43 | /** The chat's file; none keeps it in memory. */ |
| 39 | 44 | chatFile?: string; |
| 40 | 45 | /** The admin settings' file; none keeps them in memory. */ |
| @@ -53,6 +58,7 @@ export interface LobbyOptions { | ||
| 53 | 58 | interface Seat { |
| 54 | 59 | ws: WebSocket; |
| 55 | 60 | who: Who; |
| 61 | from: Visitor; | |
| 56 | 62 | heard: number; |
| 57 | 63 | } |
| 58 | 64 | |
| @@ -62,6 +68,7 @@ const USER_ID = /^[A-Za-z0-9_-]{1,64}$/; | ||
| 62 | 68 | export class Lobby { |
| 63 | 69 | readonly turns: Turns; |
| 64 | 70 | readonly chat: Chat; |
| 71 | readonly accounts: Accounts; | |
| 65 | 72 | readonly admin: Admin; |
| 66 | 73 | readonly local: boolean; |
| 67 | 74 | readonly moderator: Moderator | undefined; |
| @@ -81,6 +88,7 @@ export class Lobby { | ||
| 81 | 88 | this.turns = options.turns ?? new Turns({ turnMs: a.turnSeconds * 1000, idleMs: a.idleSeconds * 1000, maxQueue: a.maxQueue }); |
| 82 | 89 | this.turns.setPaused(a.paused); |
| 83 | 90 | this.chat = options.chat ?? new Chat({ file: options.chatFile }); |
| 91 | this.accounts = options.accounts ?? new Accounts(); | |
| 84 | 92 | this.silentMs = options.silentMs ?? 15_000; |
| 85 | 93 | this.moderator = options.moderator; |
| 86 | 94 | if (this.moderator) { |
| @@ -98,16 +106,28 @@ export class Lobby { | ||
| 98 | 106 | this.pinger.unref?.(); |
| 99 | 107 | } |
| 100 | 108 | |
| 101 | /** Who is behind this request: a verified forge identity, the local owner, or nobody. */ | |
| 109 | /** Who is behind this request: a verified forge identity, someone who joined here, the local owner, or nobody. */ | |
| 102 | 110 | who(req: IncomingMessage): Who { |
| 103 | 111 | if (this.local) return LOCAL; |
| 104 | return identify(req.headers, this.key); | |
| 112 | const forge = identify(req.headers, this.key); | |
| 113 | if (forge) { | |
| 114 | this.accounts.reserve(forge.name); | |
| 115 | return forge; | |
| 116 | } | |
| 117 | const from = visitor(req); | |
| 118 | return this.accounts.byToken(from.token, from); | |
| 119 | } | |
| 120 | ||
| 121 | /** Whether this person, or anyone where they are, is banned. The owner never is. */ | |
| 122 | barred(who: Person, from: Visitor | null): boolean { | |
| 123 | return !who.owner && !this.local && this.accounts.banned(who.id, who.name, from?.ip ?? null); | |
| 105 | 124 | } |
| 106 | 125 | |
| 107 | 126 | /** Why this person may not command the arm right now, or null when they may (and then it counts as activity). */ |
| 108 | refusal(who: Who): { status: number; error: string } | null { | |
| 127 | refusal(who: Who, req?: IncomingMessage): { status: number; error: string } | null { | |
| 109 | 128 | if (this.local) return null; |
| 110 | if (!who) return { status: 401, error: "sign in to take control" }; | |
| 129 | if (!who) return { status: 401, error: "join to take control" }; | |
| 130 | if (this.barred(who, req ? visitor(req) : null)) return { status: 403, error: "you are banned: you can still watch" }; | |
| 111 | 131 | if (!this.turns.isDriver(who.id)) { |
| 112 | 132 | const d = this.turns.driver; |
| 113 | 133 | return { status: 403, error: d ? `${d.name} has control; take control to join the queue` : "take control first" }; |
| @@ -175,7 +195,8 @@ export class Lobby { | ||
| 175 | 195 | |
| 176 | 196 | upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void { |
| 177 | 197 | const who = this.who(req); |
| 178 | this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who)); | |
| 198 | const from = visitor(req); | |
| 199 | this.wss.handleUpgrade(req, socket, head, (ws) => this.seat(ws, who, from)); | |
| 179 | 200 | } |
| 180 | 201 | |
| 181 | 202 | close(): void { |
| @@ -183,18 +204,20 @@ export class Lobby { | ||
| 183 | 204 | for (const s of this.seats) s.ws.terminate(); |
| 184 | 205 | this.wss.close(); |
| 185 | 206 | this.turns.dispose(); |
| 207 | this.accounts.close(); | |
| 186 | 208 | } |
| 187 | 209 | |
| 188 | 210 | // ------------------------------------------------------------------ sockets |
| 189 | private seat(ws: WebSocket, who: Who): void { | |
| 190 | const seat: Seat = { ws, who, heard: Date.now() }; | |
| 211 | private seat(ws: WebSocket, who: Who, from: Visitor): void { | |
| 212 | const seat: Seat = { ws, who, from, heard: Date.now() }; | |
| 191 | 213 | this.seats.add(seat); |
| 192 | 214 | 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 }); | |
| 215 | this.send(seat, this.hello(seat)); | |
| 194 | 216 | this.send(seat, this.state()); |
| 195 | 217 | this.send(seat, { type: "chat", messages: this.chat.messages }); |
| 196 | 218 | if (who?.owner) { |
| 197 | 219 | this.send(seat, this.mutedList()); |
| 220 | this.send(seat, this.bannedList()); | |
| 198 | 221 | this.send(seat, this.adminState()); |
| 199 | 222 | this.send(seat, this.crewState()); |
| 200 | 223 | } |
| @@ -227,7 +250,9 @@ export class Lobby { | ||
| 227 | 250 | const m = message as Record<string, unknown>; |
| 228 | 251 | const who = seat.who; |
| 229 | 252 | if (m.type === "pong") return; |
| 230 | if (!who) return this.send(seat, { type: "error", error: "sign in to take part" }); | |
| 253 | if (!who) return this.send(seat, { type: "error", error: "join to take part" }); | |
| 254 | if (m.type === "leave") return void this.turns.leave(who.id); | |
| 255 | if (this.barred(who, seat.from)) return this.send(seat, { type: "error", error: "you are banned: you can still watch" }); | |
| 231 | 256 | switch (m.type) { |
| 232 | 257 | case "join": |
| 233 | 258 | if (this.takeControl(who) === "full") this.send(seat, { type: "error", error: `the line is full (${this.turns.maxQueue}); try again in a little while` }); |
| @@ -265,12 +290,38 @@ export class Lobby { | ||
| 265 | 290 | 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 | 291 | this.chat.mute(id, name, m.on); |
| 267 | 292 | 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 }); | |
| 293 | if (s.who?.id === id) this.send(s, this.hello(s)); | |
| 269 | 294 | if (s.who?.owner) this.send(s, this.mutedList()); |
| 270 | 295 | } |
| 271 | 296 | this.moderator?.muted(id); |
| 272 | 297 | return; |
| 273 | 298 | } |
| 299 | case "ban": { | |
| 300 | if (typeof m.id !== "string" || !USER_ID.test(m.id) || typeof m.on !== "boolean") return this.send(seat, { type: "error", error: "ban whom?" }); | |
| 301 | const id = m.id; | |
| 302 | if (m.on) { | |
| 303 | const target = [...this.seats].find((s) => s.who?.id === id); | |
| 304 | const known = target?.who ?? this.turns.queue.find((p) => p.id === id) ?? (this.turns.driver?.id === id ? this.turns.driver : null); | |
| 305 | const said = [...this.chat.messages].reverse().find((x) => x.from?.id === id)?.from; | |
| 306 | const person = known ?? (said ? { id, name: said.name, owner: false } : null); | |
| 307 | if (!person) return this.send(seat, { type: "error", error: "nobody here by that id" }); | |
| 308 | if (person.owner) return this.send(seat, { type: "error", error: "the owner cannot be banned" }); | |
| 309 | this.accounts.ban({ id: person.id, name: person.name, owner: false }, target?.from ?? null, who.name); | |
| 310 | this.turns.end(id); // their turn ends, or they leave the line | |
| 311 | this.broadcast({ type: "said", message: this.chat.system(`${person.name} was banned`) }); | |
| 312 | this.admin.record(who, `banned ${person.name}`); | |
| 313 | } else { | |
| 314 | const name = this.accounts.bans().find((b) => b.id === id)?.name; | |
| 315 | if (!this.accounts.unban(id)) return this.send(seat, { type: "error", error: "not banned" }); | |
| 316 | this.admin.record(who, `unbanned ${name ?? id}`); | |
| 317 | } | |
| 318 | this.broadcastAdmin(); | |
| 319 | for (const s of this.seats) { | |
| 320 | if (s.who && !s.who.owner) this.send(s, this.hello(s)); // an address ban reaches everyone there | |
| 321 | if (s.who?.owner) this.send(s, this.bannedList()); | |
| 322 | } | |
| 323 | return; | |
| 324 | } | |
| 274 | 325 | case "crew": |
| 275 | 326 | if (!this.moderator) return this.send(seat, { type: "error", error: "no moderator here" }); |
| 276 | 327 | try { |
| @@ -330,6 +381,15 @@ export class Lobby { | ||
| 330 | 381 | for (const s of this.seats) if (s.who?.owner) this.send(s, this.crewState()); |
| 331 | 382 | } |
| 332 | 383 | |
| 384 | private hello(seat: Seat) { | |
| 385 | const who = seat.who; | |
| 386 | return { type: "hello", you: who, signin: !this.local, muted: who ? this.chat.muted.has(who.id) : false, banned: who ? this.barred(who, seat.from) : false }; | |
| 387 | } | |
| 388 | ||
| 389 | private bannedList() { | |
| 390 | return { type: "banned", banned: this.accounts.bans().map(({ id, name, at, by }) => ({ id, name, at, by })) }; | |
| 391 | } | |
| 392 | ||
| 333 | 393 | private mutedList() { |
| 334 | 394 | return { type: "muted", muted: [...this.chat.muted].map(([id, name]) => ({ id, name })) }; |
| 335 | 395 | } |
Software/so101/src/relay.ts +35 −3
| @@ -13,6 +13,8 @@ | ||
| 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 | 15 | * WS /live the lobby: the turn, the queue, the chat |
| 16 | * POST /join {"name": "…"}: become someone here, no forge account needed (src/accounts.ts); the answer | |
| 17 | * sets the HttpOnly session cookie and names you: {"you": {"id", "name", "owner"}} | |
| 16 | 18 | * GET /admin, POST /admin the owner's page: pause, end a turn, take control, the settings, the log |
| 17 | 19 | * GET /link {"mode": "live"|"simulated", "host": "<host:port>"|null, "problem": "…"|null} |
| 18 | 20 | * GET /cameras the listed cameras: [{"id", "name", "online"}] |
| @@ -30,6 +32,7 @@ import type { Duplex } from "node:stream"; | ||
| 30 | 32 | import { Readable } from "node:stream"; |
| 31 | 33 | import { pipeline } from "node:stream/promises"; |
| 32 | 34 | import WebSocket, { WebSocketServer } from "ws"; |
| 35 | import { AccountError, sessionCookie, visitor } from "./accounts.ts"; | |
| 33 | 36 | import { AdminError, changeFromForm } from "./admin.ts"; |
| 34 | 37 | import { ADMIN_CSP, DONE, renderAdmin, renderRefusal, type Done } from "./admin-page.ts"; |
| 35 | 38 | import type { FeedOptions } from "./camera-feed.ts"; |
| @@ -98,6 +101,7 @@ const MAX_FORM = 16_384; | ||
| 98 | 101 | /** Served from this process whichever arm is live: they describe the app, not the arm. */ |
| 99 | 102 | const LOCAL = /^\/(?:index\.html|leader-map\.js)?$|^\/(?:model|vendor|printables|app)(?:\/|$)/; |
| 100 | 103 | const LEADER = "/leader/calibration"; |
| 104 | const MAX_JOIN_BODY = 1024; | |
| 101 | 105 | const FLOOR = { |
| 102 | 106 | "x-content-type-options": "nosniff", |
| 103 | 107 | "referrer-policy": "same-origin", |
| @@ -340,7 +344,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 340 | 344 | /** A person's own calibration: signed in is enough, it never touches the arm. */ |
| 341 | 345 | const leaderCalibration = async (req: IncomingMessage, res: ServerResponse) => { |
| 342 | 346 | const who = lobby ? lobby.who(req) : LOCAL_PERSON; |
| 343 | if (!who) return json(res, 401, { error: "sign in to keep a leader calibration" }); | |
| 347 | if (!who) return json(res, 401, { error: "join to keep a leader calibration" }); | |
| 344 | 348 | switch (req.method) { |
| 345 | 349 | case "GET": |
| 346 | 350 | return json(res, 200, leaders.get(who.id)); |
| @@ -365,6 +369,29 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 365 | 369 | return json(res, 405, { error: "GET, PUT or DELETE" }); |
| 366 | 370 | }; |
| 367 | 371 | |
| 372 | /** Pick a name and become someone here. One browser is one person: a second join from it says who it already is. */ | |
| 373 | const join = async (req: IncomingMessage, res: ServerResponse) => { | |
| 374 | if (!lobby || lobby.local) return json(res, 404, { error: "nobody joins a local run: every visitor drives" }); | |
| 375 | const already = lobby.who(req); | |
| 376 | if (already) return json(res, 409, { error: `you are already ${already.name}`, you: already }); | |
| 377 | let body: unknown; | |
| 378 | try { | |
| 379 | const raw = await readBody(req); | |
| 380 | if (raw.length > MAX_JOIN_BODY) throw new Error(); | |
| 381 | body = JSON.parse(raw.toString("utf8")); | |
| 382 | } catch { | |
| 383 | return json(res, 400, { error: 'send {"name": "…"}' }); | |
| 384 | } | |
| 385 | try { | |
| 386 | const { person, token } = lobby.accounts.create((body as { name?: unknown } | null)?.name, visitor(req)); | |
| 387 | res.setHeader("set-cookie", sessionCookie(token)); | |
| 388 | return json(res, 200, { you: person }); | |
| 389 | } catch (err) { | |
| 390 | if (err instanceof AccountError) return json(res, err.status, { error: err.message }); | |
| 391 | throw err; | |
| 392 | } | |
| 393 | }; | |
| 394 | ||
| 368 | 395 | const http = createServer(async (req, res) => { |
| 369 | 396 | for (const [name, value] of Object.entries(FLOOR)) res.setHeader(name, value); |
| 370 | 397 | try { |
| @@ -381,10 +408,15 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 381 | 408 | if (cameraAdmin) return await administer(req, res, cameraAdmin[1] === undefined ? null : Number(cameraAdmin[1])); |
| 382 | 409 | if (lobby && url.pathname === "/admin") return await admin(lobby, req, res, url); |
| 383 | 410 | if (url.pathname === LEADER) return await leaderCalibration(req, res); |
| 411 | if (url.pathname === "/join") { | |
| 412 | if (req.method === "POST") return await join(req, res); | |
| 413 | res.setHeader("allow", "POST"); | |
| 414 | return json(res, 405, { error: "POST a name" }); | |
| 415 | } | |
| 384 | 416 | if (!reading && lobby) { |
| 385 | 417 | const who = lobby.who(req); |
| 386 | 418 | // Stop is the owner's at any time; everything else is the driver's alone. |
| 387 | const refused = url.pathname === "/stop" && who?.owner ? null : lobby.refusal(who); | |
| 419 | const refused = url.pathname === "/stop" && who?.owner ? null : lobby.refusal(who, req); | |
| 388 | 420 | if (refused) return json(res, refused.status, { error: refused.error }); |
| 389 | 421 | } |
| 390 | 422 | if (req.method === "GET" && url.pathname === "/link") return json(res, 200, link()); |
| @@ -505,7 +537,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 505 | 537 | let driver: string | null = null; |
| 506 | 538 | if (lobby) { |
| 507 | 539 | const who = lobby.who(req); |
| 508 | const refused = lobby.refusal(who); | |
| 540 | const refused = lobby.refusal(who, req); | |
| 509 | 541 | // Accepted and closed at once: a page cannot read a refused handshake's status, but it can read a close reason. |
| 510 | 542 | if (refused) return wss.handleUpgrade(req, socket, head, (browser) => browser.close(4000 + refused.status, refused.error)); |
| 511 | 543 | driver = who!.id; |
Software/so101/src/viewer.html +39 −9
| @@ -93,7 +93,13 @@ | ||
| 93 | 93 | #queue li { display: flex; gap: 8px; align-items: center; padding: 3px 6px; border-radius: 6px; } |
| 94 | 94 | #queue li.me { background: rgba(56,139,253,.18); } #queue .place { color: var(); font-variant-numeric: tabular-nums; min-width: 1.6em; } |
| 95 | 95 | #queue .wait { margin-left: auto; color: var(); font-variant-numeric: tabular-nums; } |
| 96 | #mutedLine { color: var(); font-size: 12px; } #mutedLine:empty { display: none; } | |
| 96 | #mutedLine, #bannedLine { color: var(); font-size: 12px; } #mutedLine:empty, #bannedLine:empty { display: none; } | |
| 97 | #joinForm[hidden], #forgeSignin[hidden] { display: none; } | |
| 98 | #joinForm { display: flex; gap: 6px; width: 100%; } | |
| 99 | #joinForm input { flex: 1; min-width: 0; font: inherit; font-size: 16px; padding: 8px 10px; min-height: 44px; border-radius: 6px; border: 1px solid var(); background: var(); color: var(); } | |
| 100 | #joinForm button { min-height: 44px; white-space: nowrap; } | |
| 101 | #joinErr { color: var(); font-size: 12px; width: 100%; } #joinErr:empty { display: none; } | |
| 102 | #turn .forge { color: var(); font-size: 12px; } | |
| 97 | 103 | #crewLine { color: var(); font-size: 12px; } #crewLine:empty { display: none; } #crewLine textarea { width: 100%; box-sizing: border-box; } #crewLine button.x { min-height: 44px; min-width: 44px; } #crewLine input[type=number] { width: 5em; min-height: 44px; } |
| 98 | 104 | #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 | 105 | #chat .line { line-height: 1.45; } #chat .line b { color: #c9d1d9; font-weight: 600; margin-right: 6px; } #chat .line.me b { color: #58a6ff; } |
| @@ -151,7 +157,7 @@ | ||
| 151 | 157 | <button id="leaderDrive" class="go" hidden title="stream the leader arm's pose to the arm during your turn">Drive with leader</button> |
| 152 | 158 | </span> |
| 153 | 159 | <button id="leaderBtn" title="read a leader arm plugged into this computer or phone (Chrome, Edge)">Connect leader arm</button> |
| 154 | <button id="leaderCal" hidden title="teach this page your own leader arm: once, kept with your sign-in">Calibrate leader</button> | |
| 160 | <button id="leaderCal" hidden title="teach this page your own leader arm: once, kept with your name">Calibrate leader</button> | |
| 155 | 161 | <button id="metricsBtn">Metrics</button> |
| 156 | 162 | <button id="settingsBtn">Settings</button> |
| 157 | 163 | <button id="calib">3D calibration</button> |
| @@ -266,6 +272,9 @@ | ||
| 266 | 272 | <div id="clock"></div> |
| 267 | 273 | <div id="capLine"></div> |
| 268 | 274 | <div class="row" id="turnActions"></div> |
| 275 | <form id="joinForm" hidden><input id="joinName" required minlength="3" maxlength="20" pattern="[A-Za-z0-9_\-]{3,20}" autocomplete="nickname" autocapitalize="off" spellcheck="false" placeholder="Pick a name" aria-label="Your name" title="3-20 letters, digits, _ or -"><button class="go">Join to take control</button></form> | |
| 276 | <div id="joinErr" role="alert"></div> | |
| 277 | <a id="forgeSignin" class="forge" hidden>Have a forge account? Sign in instead</a> | |
| 269 | 278 | <div id="adminBar" hidden aria-label="Admin"> |
| 270 | 279 | <div class="head"><b>Admin</b><button id="pauseBtn"></button><a href="/admin">Admin page</a></div> |
| 271 | 280 | <details><summary>Settings</summary> |
| @@ -282,6 +291,7 @@ | ||
| 282 | 291 | <ol id="queue" aria-label="Queue"></ol> |
| 283 | 292 | <div id="mutedLine"></div> |
| 284 | 293 | <div id="crewLine" aria-live="polite"></div> |
| 294 | <div id="bannedLine"></div> | |
| 285 | 295 | </section> |
| 286 | 296 | <div id="chat" role="log" aria-label="Chat"></div> |
| 287 | 297 | <form id="say" hidden><input id="sayText" maxlength="500" autocomplete="off" placeholder="Say something" aria-label="Message"><button class="go">Send</button></form> |
| @@ -649,7 +659,7 @@ | ||
| 649 | 659 | $("lcNext").textContent = step === "check" ? "Save" : "Capture"; |
| 650 | 660 | $("lcStep").textContent = |
| 651 | 661 | step === "centre" ? "Nothing moves the real arm while you calibrate. Hold the leader in the pose the 3D model shows: every joint in the middle of its travel, the gripper half open. Then press Capture." |
| 652 | : step === "check" ? "Move the leader: the model follows through your calibration. If a joint turns the wrong way, flip it. Save keeps it with your sign-in, for every computer you drive from." | |
| 662 | : step === "check" ? "Move the leader: the model follows through your calibration. If a joint turns the wrong way, flip it. Save keeps it with your name, for every computer you drive from." | |
| 653 | 663 | : `${LABELS[t.id]} (${calib.step} of 12): move it to the ${t.id === 6 ? (t.end === "low" ? "closed" : "open") : "end"} the model shows, as far as it goes, and press Capture.`; |
| 654 | 664 | $("lcRead").replaceChildren(...LEADER_IDS.map((id) => el("span", { className: t?.id === id ? "on" : "", textContent: `${LABELS[id].split(" ")[0]} ${calib.reading.get(id) ?? "–"}` }))); |
| 655 | 665 | if (step === "check") { |
| @@ -665,7 +675,7 @@ | ||
| 665 | 675 | if (!leader) return; |
| 666 | 676 | if (!Object.keys(limits).length) return msg("the arm's limits have not loaded yet", true); |
| 667 | 677 | const mine = await api("/leader/calibration").catch(() => null); |
| 668 | if (mine?.status === 401) return msg("sign in to calibrate your leader: the calibration is kept with your account", true); | |
| 678 | if (mine?.status === 401) return msg("join to calibrate your leader: the calibration is kept with your name", true); | |
| 669 | 679 | if (!leader) return; |
| 670 | 680 | stopLeaderDrive(); |
| 671 | 681 | calib = { step: 0, joints: {}, reading: new Map(leader.pose ?? []), error: null, had: Boolean(mine?.joints) }; |
| @@ -840,7 +850,7 @@ | ||
| 840 | 850 | // ---------------------------------------------------------------- the room: the turn, the queue and the chat over /live |
| 841 | 851 | // Behind the hosted app's relay only the person whose turn it is may drive, and the server refuses everyone else. |
| 842 | 852 | // The page follows suit: the controls are inert until it is your turn. Everything here arrives on one socket. |
| 843 | const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], admin: null }; | |
| 853 | const lobby = { ws: null, hello: null, state: null, offset: 0, retry: 500, mutedList: [], bannedList: [], admin: null }; | |
| 844 | 854 | function mayDrive() { return !relayed || (lobby.hello !== null && (!lobby.hello.signin || (lobby.hello.you !== null && lobby.state?.driver?.id === lobby.hello.you.id))); } |
| 845 | 855 | function isOwner() { return !relayed || Boolean(lobby.hello?.you?.owner); } |
| 846 | 856 | const say = (m) => { if (lobby.ws?.readyState === 1) lobby.ws.send(JSON.stringify(m)); }; |
| @@ -877,12 +887,17 @@ | ||
| 877 | 887 | const queued = me && st.queue.some((q) => q.id === me.id); |
| 878 | 888 | const actions = []; |
| 879 | 889 | if (!lobby.hello.signin) { /* a run on one's own machine: everyone drives, nobody queues */ } |
| 880 | else if (!me) actions.push(el("a", { className: "btn", href: `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`, textContent: "Sign in to take control" })); | |
| 890 | else if (!me) { /* the join form below */ } | |
| 891 | else if (lobby.hello.banned) { /* banned: watching only */ } | |
| 881 | 892 | else if (d?.id === me.id) actions.push(button("Hand back", "", () => say({ type: "leave" }))); |
| 882 | 893 | else if (queued) actions.push(button("Leave the queue", "", () => say({ type: "leave" }))); |
| 883 | 894 | else if (me) actions.push(button(me.owner && d ? "Take control now" : st.paused && !me.owner ? "Join the queue" : "Take control", "go", () => say({ type: "join" }))); |
| 884 | 895 | if (me?.owner && d && d.id !== me.id) actions.push(button(`End ${d.name}'s turn`, "danger", () => say({ type: "end", id: d.id }))); |
| 885 | 896 | $("turnActions").replaceChildren(...actions); |
| 897 | const joining = lobby.hello.signin && !me; | |
| 898 | $("joinForm").hidden = $("forgeSignin").hidden = !joining; | |
| 899 | if (!joining) $("joinErr").textContent = ""; | |
| 900 | $("forgeSignin").href = `/__forge/signin?to=${encodeURIComponent(location.pathname + location.search)}`; | |
| 886 | 901 | $("queue").replaceChildren(...st.queue.map((q) => { |
| 887 | 902 | const mine = me && q.id === me.id; |
| 888 | 903 | const li = el("li", { className: mine ? "me" : "" }, el("span", { className: "place", textContent: `${q.place}.` }), el("span", { textContent: mine ? `${q.name} (you)` : q.name }), el("span", { className: "wait", textContent: `≤ ${Math.max(1, Math.ceil(q.waitMs / 60000))} min` })); |
| @@ -890,6 +905,7 @@ | ||
| 890 | 905 | return li; |
| 891 | 906 | })); |
| 892 | 907 | $("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 }))])] : [])); |
| 908 | $("bannedLine").replaceChildren(...(me?.owner && lobby.bannedList.length ? ["Banned: ", ...lobby.bannedList.flatMap((b) => [el("span", { textContent: `${b.name} ` }), button("unban", "x", () => say({ type: "ban", id: b.id, on: false }))])] : [])); | |
| 893 | 909 | $("adminBar").hidden = !me?.owner; |
| 894 | 910 | if (me?.owner) { |
| 895 | 911 | $("pauseBtn").textContent = st.paused ? "Resume the queue" : "Pause the queue"; |
| @@ -897,8 +913,8 @@ | ||
| 897 | 913 | $("pauseBtn").onclick = () => say({ type: "pause", on: !st.paused }); |
| 898 | 914 | } |
| 899 | 915 | renderCrew(me); |
| 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." : ""; | |
| 916 | $("say").hidden = !me || lobby.hello.muted || lobby.hello.banned; | |
| 917 | $("sayNote").textContent = !lobby.hello.signin ? "" : !me ? "Join to chat." : lobby.hello.banned ? "You are banned: you can still watch." : lobby.hello.muted ? "The owner has muted you." : ""; | |
| 902 | 918 | tickClock(); |
| 903 | 919 | applyLock(); |
| 904 | 920 | } |
| @@ -920,6 +936,19 @@ | ||
| 920 | 936 | ...c.hidden.map((h) => el("div", {}, `Hidden by the crew: ${h.message.from?.name}: ${h.message.text} (${h.reason}) `, button("restore", "x", () => say({ type: "restore", id: h.message.id })))), |
| 921 | 937 | ...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 | 938 | } |
| 939 | /** Join: one field, one button. The answer sets the session cookie; the room is reopened to hear who you are now. */ | |
| 940 | $("joinForm").onsubmit = async (e) => { | |
| 941 | e.preventDefault(); | |
| 942 | const button = $("joinForm").querySelector("button"), err = $("joinErr"); | |
| 943 | button.disabled = true; | |
| 944 | try { | |
| 945 | const r = await fetch("/join", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: $("joinName").value.trim() }) }); | |
| 946 | const body = await r.json().catch(() => ({})); | |
| 947 | err.textContent = r.ok || (r.status === 409 && body.you) ? "" : body.error ?? `could not join (${r.status})`; | |
| 948 | if (!err.textContent) { $("joinName").value = ""; lobby.ws?.close(); } | |
| 949 | } catch { err.textContent = "could not reach the app; try again"; } | |
| 950 | button.disabled = false; | |
| 951 | }; | |
| 923 | 952 | const chatBox = $("chat"); |
| 924 | 953 | function chatLine(m) { |
| 925 | 954 | const me = lobby.hello?.you; |
| @@ -927,7 +956,7 @@ | ||
| 927 | 956 | line.dataset.id = m.id; |
| 928 | 957 | if (m.from) line.append(el("b", { textContent: m.from.name })); |
| 929 | 958 | 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 }) }))); | |
| 959 | 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 }) }), el("button", { textContent: "ban", onclick: () => confirm(`Ban ${m.from.name}? They can still watch, but nobody from their name, browser or address can chat or drive.`) && say({ type: "ban", id: m.from.id, on: true }) }))); | |
| 931 | 960 | return line; |
| 932 | 961 | } |
| 933 | 962 | function addChat(lines, replace = false) { |
| @@ -950,6 +979,7 @@ | ||
| 950 | 979 | else if (m.type === "said") return addChat([m.message]); |
| 951 | 980 | else if (m.type === "unsaid") return chatBox.querySelector(`[data-id="${Number(m.id)}"]`)?.remove(); |
| 952 | 981 | else if (m.type === "muted") lobby.mutedList = m.muted; |
| 982 | else if (m.type === "banned") lobby.bannedList = m.banned; | |
| 953 | 983 | else if (m.type === "admin") { const saved = lobby.admin !== null; lobby.admin = m; fillAdmin(saved); } |
| 954 | 984 | else if (m.type === "crew") lobby.crew = m; |
| 955 | 985 | else if (m.type === "error") return msg(m.error, true); |
new above
offline