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 #22

Parked opened this in answer to
Closed without merging

smith/arm:smith/12-admin-the-owner-is-the-app-s-admin-can-n → main 6 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +175 −18
Software/README.md +7
@@ -306,6 +306,13 @@ or from the compact **Admin** bar that only the owner sees beside the queue:
306306 full. The owner is never turned away.
307307 - **Announcement**: up to 280 characters, shown to everyone at the top of
308308 the panel. Leave it empty to remove it.
309 - **Arm server**: where the arm and its cameras are (`http://host:port`,
310 checked as `ARM_SERVER` is). The relay follows it at once for every viewer
311 (it shows in `/link`; the camera list is the owner's own); empty uses the
312 `ARM_SERVER` environment variable, then the simulation.
313 - **Moderators**: usernames the owner names on `/admin`. A moderator can open
314 `/admin` and read the settings and the log, and change nothing. Settings are
315 web-only: the terminal does not expose this page.
309316
310317 The settings take effect at once and survive a restart: they are stored in
311318 `$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; }
4343 .wide { grid-column: 1 / -1; }
4444 .save { margin-top: 1.25rem; }
4545 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); }
4747 time { color: var(--dim); font-variant-numeric: tabular-nums; }
48 .inline { display: inline; margin: 0; }
4849 .empty { color: var(--dim); }
4950 @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
5051 `;
@@ -57,6 +58,8 @@ export type Done = keyof typeof DONE;
5758
5859 export interface AdminPage {
5960 who: Who;
61 /** The owner may change things; a moderator only looks. */
62 canEdit: boolean;
6063 settings: AdminSettings;
6164 snapshot: Snapshot;
6265 log: readonly LogEntry[];
@@ -94,8 +97,8 @@ const time = (at: number) => {
9497 return `<time datetime="${iso}">${iso.slice(5, 10)} ${iso.slice(11, 16)}</time>`;
9598 };
9699
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>`;
99102
100103 const action = (name: string, text: string, cls = "", disabled = false) =>
101104 `<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 {
104107 const s = p.settings;
105108 const d = p.snapshot.driver;
106109 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>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>` : "");
107113 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>` : "";
108114 const log = p.log.length
109115 ? `<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 {
117123 ${flash}
118124 <section aria-labelledby="now"><h2 id="now">Right now</h2>
119125 <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")}
121127 ${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>`}
123129 </div>
124130 </section>
125131 <section aria-labelledby="set"><h2 id="set">Settings</h2>
126132 <form method="post" action="/admin"><input type="hidden" name="action" value="save">
127133 <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>
133140 </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>` : ""}
135142 </form>
136143 </section>
144 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
137145 <section aria-labelledby="log"><h2 id="log">Log</h2>${log}</section>`,
138146 );
139147 }
Software/so101/src/admin-relay.test.ts added +82
@@ -0,0 +1,82 @@
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 });
Software/so101/src/admin.ts +35 −2
@@ -8,6 +8,7 @@ import { appendFileSync, mkdirSync, readFileSync, renameSync, writeFileSync } fr
88 import { dirname } from "node:path";
99 import { cleanText } from "./chat.ts";
1010 import type { Person } from "./identity.ts";
11 import { parseRemote } from "./relay.ts";
1112
1213 export interface AdminSettings {
1314 /** Maintenance: nobody new gets a turn; the owner still may. */
@@ -20,9 +21,16 @@ export interface AdminSettings {
2021 maxQueue: number;
2122 /** Shown to everyone above the queue; empty for none. */
2223 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[];
2328 }
outdated

High: notice is never read anywhere outside this page, so changing it has no effect. Either render it to viewers (with a test), or replace it with the app's real setting, the arm server from parseRemote, so that the issue's "every setting lives on one admin page" holds.

2429
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;
2634
2735 export const ANNOUNCEMENT_CHARS = 280;
2836 const RANGES = {
@@ -38,6 +46,8 @@ const LABELS: Record<keyof AdminSettings, string> = {
3846 maxSpeedPercent: "max speed (%)",
3947 maxQueue: "max queue length",
4048 announcement: "announcement",
49 armServer: "arm server",
50 moderators: "moderators",
4151 };
4252 const KEEP_LOG = 50;
4353
@@ -67,6 +77,22 @@ export function validateChange(input: unknown): Partial<AdminSettings> {
6777 /* nothing printable: no announcement */
6878 }
6979 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;
7096 } else if (Object.hasOwn(RANGES, key)) {
7197 const k = key as keyof typeof RANGES;
7298 const [min, max] = RANGES[k];
@@ -88,6 +114,8 @@ export function changeFromForm(form: URLSearchParams): Partial<AdminSettings> {
88114 }
89115 const announcement = form.get("announcement");
90116 if (announcement !== null) raw.announcement = announcement;
117 const armServer = form.get("armServer");
118 if (armServer !== null) raw.armServer = armServer;
91119 return validateChange(raw);
92120 }
93121
@@ -115,7 +143,7 @@ export class Admin {
115143 /** Apply a change as `who`; returns the fields that changed (nothing is written when none did). */
116144 set(who: Person, input: unknown): Array<keyof AdminSettings> {
117145 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]));
119147 if (!changed.length) return [];
120148 this.settings = { ...this.settings, ...change };
121149 this.save();
@@ -123,6 +151,11 @@ export class Admin {
123151 return changed;
124152 }
125153
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
126159 /** Note an owner action (ending a turn, taking control) in the log. */
127160 record(who: Person, what: string): void {
128161 const entry: LogEntry = { at: this.now(), by: { id: who.id, name: who.name }, what };
Software/so101/src/relay.ts +32 −5
@@ -158,7 +158,10 @@ const reason = (err: unknown) => {
158158 };
159159
160160 export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
161 const remote = options.remote ?? null;
161 /** The arm server in use: the admin's setting when it names one, else the one the environment gave. */
162 let remote = options.remote ?? null;
163 const environment = remote;
164 let named = "";
162165 const simulation = options.simulation.replace(/\/+$/, "");
163166 const simulationWs = simulation.replace(/^http/, "ws");
164167 const probeTimeoutMs = options.probeTimeoutMs ?? 1500;
@@ -199,7 +202,19 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
199202 probing = null;
200203 }
201204 })());
202 const link = (): Link => ({ mode: live ? "live" : "simulated", host: remote?.host ?? null, problem });
205 /** Follow the admin's arm server setting: a change cuts what is in flight and probes the new address at once. */
206 const follow = () => {
207 if (!lobby) return;
208 const address = lobby.admin.settings.armServer;
209 if (address === named) return;
210 named = address;
211 remote = address ? parseRemote({ ARM_SERVER: address }) : environment;
212 live = false;
213 problem = null;
214 for (const c of inFlight) c.abort(new Error("the arm server was changed"));
215 if (remote) void probe();
216 };
217 const link = (): Link => (follow(), { mode: live ? "live" : "simulated", host: remote?.host ?? null, problem });
203218
204219 // ------------------------------------------------------------------ HTTP
205220 const json = (res: ServerResponse, status: number, body: unknown) => {
@@ -290,14 +305,16 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
290305 res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": ADMIN_CSP });
291306 res.end(text);
292307 };
293 if (!who?.owner) return html(who ? 403 : 401, renderRefusal(who));
308 const canEdit = Boolean(who?.owner);
309 if (!who || !(canEdit || lobby.admin.isModerator(who.name))) return html(who ? 403 : 401, renderRefusal(who));
294310 const show = (status: number, done: Done | null, error: string | null) =>
295 html(status, renderAdmin({ who, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
311 html(status, renderAdmin({ who, canEdit, settings: lobby.admin.settings, snapshot: lobby.turns.snapshot(), log: lobby.admin.log, done, error }));
296312 if (req.method === "GET" || req.method === "HEAD") {
297313 const done = url.searchParams.get("done");
298314 return show(200, done && Object.hasOwn(DONE, done) ? (done as Done) : null, null);
299315 }
300316 if (req.method !== "POST") return json(res, 405, { error: "GET or POST" });
317 if (!canEdit) return html(403, renderRefusal(who));
301318 let body: Buffer;
302319 try {
303320 body = await readBody(req, MAX_FORM);
@@ -313,6 +330,14 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
313330 lobby.configure(who, changeFromForm(form));
314331 done = "saved";
315332 break;
333 case "mod-add":
334 case "mod-remove": {
335 const name = (form.get("name") ?? "").trim().toLowerCase();
336 const now = lobby.admin.settings.moderators;
337 lobby.configure(who, { moderators: form.get("action") === "mod-add" ? [...now, name] : now.filter((m) => m !== name) });
338 done = "saved";
339 break;
340 }
316341 case "pause":
317342 case "resume":
318343 lobby.configure(who, { paused: form.get("action") === "pause" });
@@ -371,6 +396,7 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
371396 const url = new URL(req.url ?? "/", "http://x");
372397 const path = url.pathname + url.search;
373398 const reading = req.method === "GET" || req.method === "HEAD";
399 follow();
374400 if (!reading && !sameOrigin(req)) return json(res, 403, { error: "only this page may change the arm" });
375401 if (req.method === "GET" && url.pathname === "/cameras") return json(res, 200, cameras.list().map(({ id, name, online }) => ({ id, name, online })));
376402 if (req.method === "GET" && url.pathname === "/admin/camera-list") {
@@ -543,8 +569,9 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
543569 });
544570
545571 // ------------------------------------------------------------------ start
572 follow();
546573 if (remote) await probe(); // bounded by the probe timeout: the first page already knows which arm it has
547 const timer = remote ? setInterval(() => void probe(), probeEveryMs) : undefined;
574 const timer = remote || lobby ? setInterval(() => (follow(), remote && void probe()), probeEveryMs) : undefined;
548575 timer?.unref?.();
549576 await new Promise<void>((resolve) => http.listen(options.port ?? 8102, options.host ?? "127.0.0.1", resolve));
550577 const address = http.address();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs