Public: anyone can read this; the crew can change it.
Migrated from github.com/Trevato/SO-ARM100
workbenchthis machine
Admin: the owner is the app's admin, can name moderators, and every setting lives on one admin page #102
smith/arm:smith/12-admin-the-owner-is-the-app-s-admin-can-n → main 11 commits fork
7 files
changed +228
−17
.gitignore +14
| @@ -5,3 +5,17 @@ node_modules/ | ||
| 5 | 5 | poses.json |
| 6 | 6 | outputs/ |
| 7 | 7 | __pycache__/ |
| 8 | ||
| 9 | # sandbox home-directory placeholders: never part of the app | |
| 10 | /.bash_profile | |
| 11 | /.bashrc | |
| 12 | /.zshrc | |
| 13 | /.zprofile | |
| 14 | /.profile | |
| 15 | /.gitconfig | |
| 16 | /.gitmodules | |
| 17 | /.mcp.json | |
| 18 | /.ripgreprc | |
| 19 | /.idea | |
| 20 | /.vscode | |
| 21 | /.claude/ |
Software/README.md +11
| @@ -342,6 +342,17 @@ or from the **Admin** tab that only the owner sees: | ||
| 342 | 342 | full. The owner is never turned away. |
| 343 | 343 | - **Announcement**: up to 280 characters, shown to everyone at the top of |
| 344 | 344 | the panel. Leave it empty to remove it. |
| 345 | - **Arm server**: where the arm and its cameras are (`http://host:port`, | |
| 346 | checked as `ARM_SERVER` is). The relay follows it at once for every viewer | |
| 347 | (it shows in `/link`; the camera list is the owner's own); empty uses the | |
| 348 | `ARM_SERVER` environment variable, then the simulation. | |
| 349 | - **Moderators**: usernames the owner names on `/admin`. A moderator can open | |
| 350 | `/admin` and read the settings and the log, and change nothing. A moderator | |
| 351 | is matched on the forge-signed identity (the forge username), never on a | |
| 352 | name a guest typed: a guest who picks a moderator's name still gets a 403. | |
| 353 | Settings are web-only because this app has no terminal (`forge.json` has no | |
| 354 | `tty`); the `so101` command line drives the arm hardware and does not run | |
| 355 | the relay. | |
| 345 | 356 | |
| 346 | 357 | The settings take effect at once and survive a restart: they are stored in |
| 347 | 358 | `$FORGE_APP_DATA/so101/admin.json`. Every change and every owner action |
Software/so101/src/admin-page.ts +19 −11
| @@ -43,8 +43,9 @@ textarea { min-height: 5.5rem; resize: vertical; } | ||
| 43 | 43 | .wide { grid-column: 1 / -1; } |
| 44 | 44 | .save { margin-top: 1.25rem; } |
| 45 | 45 | ol { list-style: none; margin: 0; padding: 0; display: grid; gap: .5rem; font-size: .95rem; } |
| 46 | ol li { display: grid; grid-template-columns: 7.5rem 1fr; gap: 1rem; padding-bottom: .5rem; border-bottom: 1px solid var(--line); } | |
| 46 | ol li { display: grid; grid-template-columns: 7.5rem 1fr; overflow-wrap: anywhere; gap: 1rem; padding-bottom: .5rem; border-bottom: 1px solid var(--line); } | |
| 47 | 47 | time { color: var(--dim); font-variant-numeric: tabular-nums; } |
| 48 | .inline { display: inline; margin: 0; } | |
| 48 | 49 | .empty { color: var(--dim); } |
| 49 | 50 | @media (prefers-reduced-motion: reduce) { * { transition: none !important; } } |
| 50 | 51 | `; |
| @@ -57,6 +58,8 @@ export type Done = keyof typeof DONE; | ||
| 57 | 58 | |
| 58 | 59 | export interface AdminPage { |
| 59 | 60 | who: Who; |
| 61 | /** The owner may change things; a moderator only looks. */ | |
| 62 | canEdit: boolean; | |
| 60 | 63 | settings: AdminSettings; |
| 61 | 64 | snapshot: Snapshot; |
| 62 | 65 | log: readonly LogEntry[]; |
| @@ -94,8 +97,8 @@ const time = (at: number) => { | ||
| 94 | 97 | return `<time datetime="${iso}">${iso.slice(5, 10)} ${iso.slice(11, 16)}</time>`; |
| 95 | 98 | }; |
| 96 | 99 | |
| 97 | const field = (name: keyof AdminSettings, label: string, hint: string, value: number, min: number, max: number) => | |
| 98 | `<label>${label}<small>${hint}</small><input name="${name}" type="number" inputmode="numeric" required min="${min}" max="${max}" step="1" value="${value}"></label>`; | |
| 100 | const field = (name: keyof AdminSettings, label: string, hint: string, value: number, min: number, max: number, off: string) => | |
| 101 | `<label>${label}<small>${hint}</small><input name="${name}" type="number" inputmode="numeric" required min="${min}" max="${max}" step="1" value="${value}"${off}></label>`; | |
| 99 | 102 | |
| 100 | 103 | const action = (name: string, text: string, cls = "", disabled = false) => |
| 101 | 104 | `<form method="post" action="/admin"><input type="hidden" name="action" value="${name}"><button class="${cls}"${disabled ? " disabled" : ""}>${text}</button></form>`; |
| @@ -104,6 +107,9 @@ export function renderAdmin(p: AdminPage): string { | ||
| 104 | 107 | const s = p.settings; |
| 105 | 108 | const d = p.snapshot.driver; |
| 106 | 109 | const mine = d && p.who && d.id === p.who.id; |
| 110 | const off = p.canEdit ? "" : " disabled"; | |
| 111 | const mods = `<ul>${s.moderators.map((m) => `<li>${esc(m)}${p.canEdit ? ` <form method="post" action="/admin" class="inline"><input type="hidden" name="action" value="mod-remove"><input type="hidden" name="name" value="${esc(m)}"><button aria-label="Remove moderator ${esc(m)}">Remove</button></form>` : ""}</li>`).join("") || "<li class=\"empty\">none</li>"}</ul>` + | |
| 112 | (p.canEdit ? `<form method="post" action="/admin"><input type="hidden" name="action" value="mod-add"><label>Add a moderator<small>a username; moderators can look at this page and change nothing</small><input name="name" required maxlength="64"></label><div class="save"><button>Add</button></div></form>` : ""); | |
| 107 | 113 | const flash = p.error ? `<p class="flash bad" role="alert">${esc(p.error)}</p>` : p.done ? `<p class="flash" role="status">${DONE[p.done]}</p>` : ""; |
| 108 | 114 | const log = p.log.length |
| 109 | 115 | ? `<ol>${[...p.log].reverse().map((e) => `<li>${time(e.at)}<span><b>${esc(e.by.name)}</b> ${esc(e.what)}</span></li>`).join("")}</ol>` |
| @@ -117,23 +123,25 @@ export function renderAdmin(p: AdminPage): string { | ||
| 117 | 123 | ${flash} |
| 118 | 124 | <section aria-labelledby="now"><h2 id="now">Right now</h2> |
| 119 | 125 | <div class="actions"> |
| 120 | ${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")} | |
| 126 | ${p.canEdit ? `${s.paused ? action("resume", "Resume the queue", "go") : action("pause", "Pause the queue")} | |
| 121 | 127 | ${action("end", d ? `End ${esc(d.name)}'s turn` : "End current turn", "danger", !d)} |
| 122 | ${action("take", mine ? "You have control" : "Take control now", "go", Boolean(mine))} | |
| 128 | ${action("take", mine ? "You have control" : "Take control now", "go", Boolean(mine))}` : `<p class="empty">${esc(p.who?.name ?? "")} is a moderator: this page is read-only.</p>`} | |
| 123 | 129 | </div> |
| 124 | 130 | </section> |
| 125 | 131 | <section aria-labelledby="set"><h2 id="set">Settings</h2> |
| 126 | 132 | <form method="post" action="/admin"><input type="hidden" name="action" value="save"> |
| 127 | 133 | <div class="grid"> |
| 128 | ${field("turnSeconds", "Turn length", "seconds, 30–3600", s.turnSeconds, 30, 3600)} | |
| 129 | ${field("idleSeconds", "Idle timeout", "seconds without a command, 10–600", s.idleSeconds, 10, 600)} | |
| 130 | ${field("maxSpeedPercent", "Max speed", "percent of full, on top of the safety limits", s.maxSpeedPercent, 5, 100)} | |
| 131 | ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0, 100)} | |
| 132 | <label class="wide">Announcement<small>shown to everyone above the queue; empty for none</small><textarea name="announcement" maxlength="${ANNOUNCEMENT_CHARS}">${esc(s.announcement)}</textarea></label> | |
| 134 | ${field("turnSeconds", "Turn length", "seconds, 30–3600", s.turnSeconds, 30, 3600, off)} | |
| 135 | ${field("idleSeconds", "Idle timeout", "seconds without a command, 10–600", s.idleSeconds, 10, 600, off)} | |
| 136 | ${field("maxSpeedPercent", "Max speed", "percent of full, on top of the safety limits", s.maxSpeedPercent, 5, 100, off)} | |
| 137 | ${field("maxQueue", "Max queue length", "people waiting, 0–100", s.maxQueue, 0, 100, off)} | |
| 138 | <label class="wide">Announcement<small>shown to everyone above the queue; empty for none</small><textarea name="announcement" maxlength="${ANNOUNCEMENT_CHARS}"${off}>${esc(s.announcement)}</textarea></label> | |
| 139 | <label class="wide">Arm server<small>where the arm and its cameras are, http://host:port; empty uses ARM_SERVER from the environment, else the simulation; takes effect at once</small><input name="armServer" maxlength="200" value="${esc(s.armServer)}"${off}></label> | |
| 133 | 140 | </div> |
| 134 | <div class="save"><button class="go">Save settings</button></div> | |
| 141 | ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>` : ""} | |
| 135 | 142 | </form> |
| 136 | 143 | </section> |
| 144 | <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section> | |
| 137 | 145 | <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`, |
| 138 | 146 | ); |
| 139 | 147 | } |
Software/so101/src/admin-relay.test.ts added +103
| @@ -0,0 +1,103 @@ | ||
| 1 | import { afterEach, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { validateChange } from "./admin.ts"; | |
| 6 | import { sign } from "./identity.ts"; | |
| 7 | import { Lobby } from "./lobby.ts"; | |
| 8 | import { startRelay, type RunningRelay } from "./relay.ts"; | |
| 9 | ||
| 10 | const KEY = "k".repeat(64); | |
| 11 | const later = Date.now() + 600_000; | |
| 12 | const as = (name: string, role: "user" | "admin") => { | |
| 13 | const identity = `id-${name}|${name}|${role}|${later}`; | |
| 14 | return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) }; | |
| 15 | }; | |
| 16 | const form = (headers: Record<string, string>, body: Record<string, string>) => ({ method: "POST", headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(body), redirect: "manual" as const }); | |
| 17 | ||
| 18 | let dir = ""; | |
| 19 | let relay: RunningRelay | undefined; | |
| 20 | let lobby: Lobby | undefined; | |
| 21 | afterEach(async () => { | |
| 22 | await relay?.close(); | |
| 23 | lobby?.close(); | |
| 24 | if (dir) rmSync(dir, { recursive: true, force: true }); | |
| 25 | dir = ""; | |
| 26 | relay = lobby = undefined; | |
| 27 | }); | |
| 28 | ||
| 29 | async function boot() { | |
| 30 | dir ||= mkdtempSync(join(tmpdir(), "so101-admin-relay-")); | |
| 31 | lobby = new Lobby({ identityKey: KEY, adminFile: join(dir, "admin.json") }); | |
| 32 | relay = await startRelay({ port: 0, simulation: "http://127.0.0.1:1", lobby }); | |
| 33 | return `http://127.0.0.1:${relay.port}`; | |
| 34 | } | |
| 35 | ||
| 36 | test("the new settings are checked", () => { | |
| 37 | expect(validateChange({ armServer: " http://127.0.0.1:9 " })).toEqual({ armServer: "http://127.0.0.1:9" }); | |
| 38 | expect(validateChange({ armServer: "" })).toEqual({ armServer: "" }); | |
| 39 | expect(() => validateChange({ armServer: "ftp://x" })).toThrow(); | |
| 40 | expect(validateChange({ moderators: ["Bob", "bob", "eve"] })).toEqual({ moderators: ["bob", "eve"] }); | |
| 41 | expect(() => validateChange({ moderators: ["a b"] })).toThrow(); | |
| 42 | expect(() => validateChange({ moderators: "bob" })).toThrow(); | |
| 43 | }); | |
| 44 | ||
| 45 | test("a moderator looks at /admin and changes nothing; the owner names and removes moderators; it persists", async () => { | |
| 46 | dir = mkdtempSync(join(tmpdir(), "so101-admin-relay-")); | |
| 47 | let base = await boot(); | |
| 48 | const owner = as("trevato", "admin"); | |
| 49 | const bob = as("bob", "user"); | |
| 50 | expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(403); | |
| 51 | expect((await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "Bob" }))).status).toBe(303); | |
| 52 | const seen = await fetch(`${base}/admin`, { headers: bob }); | |
| 53 | expect(seen.status).toBe(200); | |
| 54 | expect(await seen.text()).toContain("read-only"); | |
| 55 | expect((await fetch(`${base}/admin`, form(bob, { action: "pause" }))).status).toBe(403); | |
| 56 | expect((await fetch(`${base}/admin`, form(bob, { action: "mod-add", name: "eve" }))).status).toBe(403); | |
| 57 | expect((await fetch(`${base}/admin`, { headers: as("eve", "user") })).status).toBe(403); | |
| 58 | ||
| 59 | await relay!.close(); | |
| 60 | lobby!.close(); | |
| 61 | base = await boot(); | |
| 62 | expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(200); | |
| 63 | const html = await (await fetch(`${base}/admin`, { headers: owner })).text(); | |
| 64 | expect(html).toContain("moderators → bob"); | |
| 65 | await fetch(`${base}/admin`, form(owner, { action: "mod-remove", name: "bob" })); | |
| 66 | expect((await fetch(`${base}/admin`, { headers: bob })).status).toBe(403); | |
| 67 | }); | |
| 68 | ||
| 69 | test("the arm server set on /admin is the one the relay uses, at once; a bad one is refused", async () => { | |
| 70 | dir = mkdtempSync(join(tmpdir(), "so101-admin-relay-")); | |
| 71 | const base = await boot(); | |
| 72 | const owner = as("trevato", "admin"); | |
| 73 | expect(relay!.link().host).toBeNull(); | |
| 74 | const bad = await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "<script>x</script>" })); | |
| 75 | expect(bad.status).toBe(400); | |
| 76 | expect(await bad.text()).not.toContain("<script>x"); | |
| 77 | await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "http://127.0.0.1:1" })); | |
| 78 | expect(relay!.link().host).toBe("127.0.0.1:1"); | |
| 79 | expect(relay!.link().mode).toBe("simulated"); | |
| 80 | await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "" })); | |
| 81 | expect(relay!.link().host).toBeNull(); | |
| 82 | }); | |
| 83 | ||
| 84 | test("a guest who types a moderator's name is not that moderator; the Remove buttons say whom they remove", async () => { | |
| 85 | const base = await boot(); | |
| 86 | const owner = as("trevato", "admin"); | |
| 87 | await fetch(`${base}/admin`, form(owner, { action: "mod-add", name: "bob" })); | |
| 88 | const joined = await fetch(`${base}/join`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "bob" }) }); | |
| 89 | expect(joined.status).toBe(200); | |
| 90 | const cookie = joined.headers.get("set-cookie")!.split(";")[0]!; | |
| 91 | expect((await fetch(`${base}/admin`, { headers: { cookie } })).status).toBe(403); | |
| 92 | expect((await fetch(`${base}/admin`, { headers: as("bob", "user") })).status).toBe(200); | |
| 93 | expect(await (await fetch(`${base}/admin`, { headers: owner })).text()).toContain('aria-label="Remove moderator bob"'); | |
| 94 | }); | |
| 95 | ||
| 96 | test("reading /link never changes anything; the arm server switches when the setting does", async () => { | |
| 97 | const base = await boot(); | |
| 98 | const owner = as("trevato", "admin"); | |
| 99 | await fetch(`${base}/admin`, form(owner, { action: "save", armServer: "http://127.0.0.1:1" })); | |
| 100 | const after = await (await fetch(`${base}/link`)).json(); | |
| 101 | expect(after.host).toBe("127.0.0.1:1"); | |
| 102 | expect(await (await fetch(`${base}/link`)).json()).toEqual(after); | |
| 103 | }); |
Software/so101/src/admin.ts +35 −2
| @@ -8,6 +8,7 @@ import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } fr | ||
| 8 | 8 | import { dirname } from "node:path"; |
| 9 | 9 | import { cleanText } from "./chat.ts"; |
| 10 | 10 | import type { Person } from "./identity.ts"; |
| 11 | import { parseRemote } from "./relay.ts"; | |
| 11 | 12 | |
| 12 | 13 | export interface AdminSettings { |
| 13 | 14 | /** Maintenance: nobody new gets a turn; the owner still may. */ |
| @@ -20,9 +21,16 @@ export interface AdminSettings { | ||
| 20 | 21 | maxQueue: number; |
| 21 | 22 | /** Shown to everyone above the queue; empty for none. */ |
| 22 | 23 | announcement: string; |
| 24 | /** Where the arm and its cameras are (http://host:port); empty uses ARM_SERVER from the environment, else the simulation. */ | |
| 25 | armServer: string; | |
| 26 | /** Usernames (lowercase) who may see /admin but change nothing. */ | |
| 27 | moderators: string[]; | |
| 23 | 28 | } |
| 24 | 29 | |
| 25 | export const DEFAULT_ADMIN: AdminSettings = { paused: false, turnSeconds: 180, idleSeconds: 30, maxSpeedPercent: 100, maxQueue: 20, announcement: "" }; | |
| 30 | export const DEFAULT_ADMIN: AdminSettings = { paused: false, turnSeconds: 180, idleSeconds: 30, maxSpeedPercent: 100, maxQueue: 20, announcement: "", armServer: "", moderators: [] }; | |
| 31 | ||
| 32 | const NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/; | |
| 33 | export const MAX_MODERATORS = 50; | |
| 26 | 34 | |
| 27 | 35 | export const ANNOUNCEMENT_CHARS = 280; |
| 28 | 36 | const RANGES = { |
| @@ -38,6 +46,8 @@ const LABELS: Record<keyof AdminSettings, string> = { | ||
| 38 | 46 | maxSpeedPercent: "max speed (%)", |
| 39 | 47 | maxQueue: "max queue length", |
| 40 | 48 | announcement: "announcement", |
| 49 | armServer: "arm server", | |
| 50 | moderators: "moderators", | |
| 41 | 51 | }; |
| 42 | 52 | const KEEP_LOG = 50; |
| 43 | 53 | |
| @@ -67,6 +77,22 @@ export function validateChange(input: unknown): Partial<AdminSettings> { | ||
| 67 | 77 | /* nothing printable: no announcement */ |
| 68 | 78 | } |
| 69 | 79 | out.announcement = text; |
| 80 | } else if (key === "armServer") { | |
| 81 | if (typeof value !== "string") throw new AdminError("the arm server is an address"); | |
| 82 | const text = value.trim(); | |
| 83 | if (text) { | |
| 84 | try { | |
| 85 | parseRemote({ ARM_SERVER: text }); | |
| 86 | } catch (err) { | |
| 87 | throw new AdminError((err as Error).message); | |
| 88 | } | |
| 89 | } | |
| 90 | out.armServer = text; | |
| 91 | } else if (key === "moderators") { | |
| 92 | if (!Array.isArray(value) || !value.every((m) => typeof m === "string" && NAME.test(m.trim()))) throw new AdminError("a username is letters, digits, _ . -"); | |
| 93 | const names = [...new Set(value.map((m: string) => m.trim().toLowerCase()))]; | |
| 94 | if (names.length > MAX_MODERATORS) throw new AdminError(`at most ${MAX_MODERATORS} moderators`); | |
| 95 | out.moderators = names; | |
| 70 | 96 | } else if (Object.hasOwn(RANGES, key)) { |
| 71 | 97 | const k = key as keyof typeof RANGES; |
| 72 | 98 | const [min, max] = RANGES[k]; |
| @@ -88,6 +114,8 @@ export function changeFromForm(form: URLSearchParams): Partial<AdminSettings> { | ||
| 88 | 114 | } |
| 89 | 115 | const announcement = form.get("announcement"); |
| 90 | 116 | if (announcement !== null) raw.announcement = announcement; |
| 117 | const armServer = form.get("armServer"); | |
| 118 | if (armServer !== null) raw.armServer = armServer; | |
| 91 | 119 | return validateChange(raw); |
| 92 | 120 | } |
| 93 | 121 | |
| @@ -115,7 +143,7 @@ export class Admin { | ||
| 115 | 143 | /** Apply a change as `who`; returns the fields that changed (nothing is written when none did). */ |
| 116 | 144 | set(who: Person, input: unknown): Array<keyof AdminSettings> { |
| 117 | 145 | const change = validateChange(input); |
| 118 | const changed = (Object.keys(change) as Array<keyof AdminSettings>).filter((k) => change[k] !== this.settings[k]); | |
| 146 | const changed = (Object.keys(change) as Array<keyof AdminSettings>).filter((k) => JSON.stringify(change[k]) !== JSON.stringify(this.settings[k])); | |
| 119 | 147 | if (!changed.length) return []; |
| 120 | 148 | this.settings = { ...this.settings, ...change }; |
| 121 | 149 | this.save(); |
| @@ -123,6 +151,11 @@ export class Admin { | ||
| 123 | 151 | return changed; |
| 124 | 152 | } |
| 125 | 153 | |
| 154 | /** Whether this person may look at the admin page without changing anything. */ | |
| 155 | isModerator(name: string): boolean { | |
| 156 | return this.settings.moderators.includes(name.toLowerCase()); | |
| 157 | } | |
| 158 | ||
| 126 | 159 | /** Note an owner action (ending a turn, taking control) in the log. */ |
| 127 | 160 | record(who: Person, what: string): void { |
| 128 | 161 | const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what }; |
Software/so101/src/lobby.ts +13
| @@ -80,6 +80,7 @@ export class Lobby { | ||
| 80 | 80 | private readonly key: string; |
| 81 | 81 | private readonly wss = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME }); |
| 82 | 82 | private readonly seats = new Set<Seat>(); |
| 83 | private readonly changeListeners = new Set<() => void>(); | |
| 83 | 84 | private readonly endListeners = new Set<(who: Person) => void>(); |
| 84 | 85 | private readonly pinger: ReturnType<typeof setInterval>; |
| 85 | 86 | private readonly silentMs: number; |
| @@ -124,6 +125,11 @@ export class Lobby { | ||
| 124 | 125 | return this.accounts.byToken(from.token, from); |
| 125 | 126 | } |
| 126 | 127 | |
| 128 | /** The forge-signed identity behind this request, or null: a guest's chosen name proves nothing, so it never counts here. */ | |
| 129 | verified(req: IncomingMessage): Person | null { | |
| 130 | return this.local ? LOCAL : identify(req.headers, this.key); | |
| 131 | } | |
| 132 | ||
| 127 | 133 | /** Whether this person, or anyone where they are, is banned. The owner never is. */ |
| 128 | 134 | barred(who: Person, from: Visitor | null): boolean { |
| 129 | 135 | return !who.owner && !this.local && this.accounts.banned(who.id, who.name, from?.ip ?? null); |
| @@ -171,6 +177,7 @@ export class Lobby { | ||
| 171 | 177 | } |
| 172 | 178 | this.broadcastState(); |
| 173 | 179 | this.broadcastAdmin(); |
| 180 | if (changed.length) for (const listener of this.changeListeners) listener(); | |
| 174 | 181 | } |
| 175 | 182 | |
| 176 | 183 | /** The owner ends whoever drives now. */ |
| @@ -193,6 +200,12 @@ export class Lobby { | ||
| 193 | 200 | return this.turns.join(who); |
| 194 | 201 | } |
| 195 | 202 | |
| 203 | /** Told once each time the owner's settings change. */ | |
| 204 | onSettingsChange(listener: () => void): () => void { | |
| 205 | this.changeListeners.add(listener); | |
| 206 | return () => this.changeListeners.delete(listener); | |
| 207 | } | |
| 208 | ||
| 196 | 209 | /** Called with whoever's turn just ended, for whatever reason: their streams and moves must stop. */ |
| 197 | 210 | onTurnEnd(listener: (who: Person) => void): () => void { |
| 198 | 211 | this.endListeners.add(listener); |
Software/so101/src/relay.ts +33 −4
| @@ -183,7 +183,10 @@ const reason = (err: unknown) => { | ||
| 183 | 183 | }; |
| 184 | 184 | |
| 185 | 185 | export async function startRelay(options: RelayOptions): Promise<RunningRelay> { |
| 186 | const remote = options.remote ?? null; | |
| 186 | /** The arm server in use: the admin's setting when it names one, else the one the environment gave. */ | |
| 187 | let remote = options.remote ?? null; | |
| 188 | const environment = remote; | |
| 189 | let named = ""; | |
| 187 | 190 | const simulation = options.simulation.replace(/\/+$/, ""); |
| 188 | 191 | const simulationWs = simulation.replace(/^http/, "ws"); |
| 189 | 192 | const probeTimeoutMs = options.probeTimeoutMs ?? 1500; |
| @@ -226,6 +229,18 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 226 | 229 | probing = null; |
| 227 | 230 | } |
| 228 | 231 | })()); |
| 232 | /** Follow the admin's arm server setting: a change cuts what is in flight and probes the new address at once. */ | |
| 233 | const follow = () => { | |
| 234 | if (!lobby) return; | |
| 235 | const address = lobby.admin.settings.armServer; | |
| 236 | if (address === named) return; | |
| 237 | named = address; | |
| 238 | remote = address ? parseRemote({ ARM_SERVER: address }) : environment; | |
| 239 | live = false; | |
| 240 | problem = null; | |
| 241 | for (const c of inFlight) c.abort(new Error("the arm server was changed")); | |
| 242 | if (remote) void probe(); | |
| 243 | }; | |
| 229 | 244 | const link = (): Link => ({ mode: live ? "live" : "simulated", host: remote?.host ?? null, problem }); |
| 230 | 245 | const source = () => (live && remote ? `live ${remote.host}` : `simulated: ${problem ?? "ARM_SERVER is not set"}`); |
| 231 | 246 | |
| @@ -351,14 +366,17 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 351 | 366 | res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": ADMIN_CSP }); |
| 352 | 367 | res.end(text); |
| 353 | 368 | }; |
| 354 | if (!who?.owner) return html(who ? 403 : 401, renderRefusal(who)); | |
| 369 | const canEdit = Boolean(who?.owner); | |
| 370 | // a moderator is named by forge username and must hold that forge identity: a guest who types the same name is not them | |
| 371 | if (!who || !(canEdit || (lobby.verified(req)?.id === who.id && lobby.admin.isModerator(who.name)))) return html(who ? 403 : 401, renderRefusal(who)); | |
| 355 | 372 | const show = (status: number, done: Done | null, error: string | null) => |
| 356 | html(status, renderAdmin({ who, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error })); | |
| 373 | html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error })); | |
| 357 | 374 | if (req.method === "GET" || req.method === "HEAD") { |
| 358 | 375 | const done = url.searchParams.get("done"); |
| 359 | 376 | return show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null); |
| 360 | 377 | } |
| 361 | 378 | if (req.method !== "POST") return json(res, 405, { error: "GET or POST" }); |
| 379 | if (!canEdit) return html(403, renderRefusal(who)); | |
| 362 | 380 | let body: Buffer; |
| 363 | 381 | try { |
| 364 | 382 | body = await readBody(req, MAX_FORM); |
| @@ -374,6 +392,14 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 374 | 392 | lobby.configure(who, changeFromForm(form)); |
| 375 | 393 | done = "saved"; |
| 376 | 394 | break; |
| 395 | case "mod-add": | |
| 396 | case "mod-remove": { | |
| 397 | const name = (form.get("name") ?? "").trim().toLowerCase(); | |
| 398 | const now = lobby.admin.settings.moderators; | |
| 399 | lobby.configure(who, { moderators: form.get("action") === "mod-add" ? [...now, name] : now.filter((m) => m !== name) }); | |
| 400 | done = "saved"; | |
| 401 | break; | |
| 402 | } | |
| 377 | 403 | case "pause": |
| 378 | 404 | case "resume": |
| 379 | 405 | lobby.configure(who, { paused: form.get("action") === "pause" }); |
| @@ -645,6 +671,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 645 | 671 | |
| 646 | 672 | // ------------------------------------------------------------------ a turn that ends |
| 647 | 673 | // Its streams close (the arm server holds the arm when a stream ends) and a move, playback or recording stops. |
| 674 | const settingsChanged = lobby?.onSettingsChange(follow); | |
| 648 | 675 | const turnEnded = lobby?.onTurnEnd((who) => { |
| 649 | 676 | for (const [browser, id] of streams) if (id === who.id) browser.close(1000, "your turn ended"); |
| 650 | 677 | const base = remote && live ? remote.http : simulation; |
| @@ -655,8 +682,9 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 655 | 682 | }); |
| 656 | 683 | |
| 657 | 684 | // ------------------------------------------------------------------ start |
| 685 | follow(); | |
| 658 | 686 | if (remote) await probe(); // bounded by the probe timeout: the first page already knows which arm it has |
| 659 | const timer = remote ? setInterval(() => void probe(), probeEveryMs) : undefined; | |
| 687 | const timer = remote || lobby ? setInterval(() => (follow(), remote && void probe()), probeEveryMs) : undefined; | |
| 660 | 688 | timer?.unref?.(); |
| 661 | 689 | await new Promise<void>((resolve) => http.listen(options.port ?? 8102, options.host ?? "127.0.0.1", resolve)); |
| 662 | 690 | const address = http.address(); |
| @@ -666,6 +694,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> { | ||
| 666 | 694 | close: () => |
| 667 | 695 | new Promise<void>((resolve) => { |
| 668 | 696 | clearInterval(timer); |
| 697 | settingsChanged?.(); | |
| 669 | 698 | turnEnded?.(); |
| 670 | 699 | if (!options.cameras) cameras.close(); |
| 671 | 700 | for (const c of inFlight) c.abort(); |
new above
offline