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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

/admin shows the table height (tableOffsetMm) as a number the owner can edit and save #315

Parked opened this
Closed without merging

smith/arm:smith/279-admin-shows-the-table-height-tableoffset → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +144 −6
Software/README.md +10 −2
@@ -547,8 +547,16 @@ characters removed, so a chat line cannot drive your terminal. Locally,
547547 `PORT=8102 bun run Software/so101/src/tty.ts` beside `fake-serve.ts`
548548 reaches it as the owner.
549549
550 **Admin.** The owner runs the room from `/admin` (plain forms, no script),
551 or from the **Admin** tab that only the owner sees:
550 **Admin.** The owner runs the room from `/admin` (plain forms), or from the
551 **Admin** tab that only the owner sees. Besides the Health table's refresh, the only scripted control on `/admin` is
552 the **Table height** field (mm from the model's floor, -100 to 100, whole
553 numbers): it must read the arm server's `GET /settings` and save with
554 `PUT /settings`, which the page's forms cannot do. The field starts disabled
555 and the section hidden; both come alive only once the read succeeds, so it
556 never shows or saves a guessed 0, and with script off it is not there. The
557 page's Content-Security-Policy allows exactly those two scripts, each by its sha256 hash,
558 and `connect-src 'self'`; nothing else. Moderators get neither the field nor
559 the script. In the terminal the same is `/table <mm>`, or `/table here`.
552560
553561 - **Pause the queue** for maintenance. The driver's turn ends (unless it is
554562 the owner's), nobody new gets a turn, and everyone sees "Paused for
Software/so101/src/admin-page.test.ts added +103
@@ -0,0 +1,103 @@
1 import { describe, expect, test } from "bun:test";
2 import { createHash } from "node:crypto";
3 import { DEFAULT_ADMIN } from "./admin.ts";
4 import { ADMIN_CSP, renderAdmin } from "./admin-page.ts";
5
6 /** The table height's script: the one that names its form. */
7 const tableScript = (html: string) => [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]!).find((t) => t.includes("table-form"))!;
8 const snapshot = { driver: null, queue: [] } as never;
9 const page = (canEdit: boolean) => renderAdmin({ who: { id: "u", name: "trevato", owner: canEdit }, canEdit, settings: { ...DEFAULT_ADMIN }, snapshot, log: [] });
10
11 describe("the table height on /admin", () => {
12 test("the owner gets a -100..100 number field that saves through PUT /settings", () => {
13 const html = page(true);
14 expect(html).toContain('name="tableOffsetMm" type="number" inputmode="numeric" required min="-100" max="100" step="1"');
15 expect(html).toContain('method: "PUT"');
16 expect(html).toContain('fetch("/settings"');
17 });
18
19 test("a moderator sees neither the field nor the script", () => {
20 const html = page(false);
21 expect(html).not.toContain("tableOffsetMm");
22 expect(html).not.toContain('id="table-form"');
23 expect(html).not.toContain("table-msg");
24 });
25
26 test("the inline script is the one the policy pins, and it may only reach its own origin", () => {
27 const script = tableScript(page(true));
28 expect(ADMIN_CSP).toContain(`'sha256-${createHash("sha256").update(script).digest("base64")}'`);
29 expect(ADMIN_CSP).toContain("connect-src 'self'");
30 });
31
32 test("the section starts hidden and the field and button disabled, so without the script it is not there to use", () => {
33 const html = page(true);
34 expect(html).toMatch(/<section id="table"[^>]* hidden>/);
35 expect(html).toMatch(/<input name="tableOffsetMm"[^>]* disabled>/);
36 expect(html).toMatch(/<button class="go" disabled>Save table height/);
37 });
38 });
39
40 /** Run the page's script against a stand-in document and fetch. */
41 function run(fetcher: (path: string, init?: any) => Promise<any>) {
42 const script = tableScript(page(true));
43 const input: any = { value: "0", disabled: true };
44 const button: any = { disabled: true };
45 const msg: any = { textContent: "", className: "empty" };
46 const section: any = { hidden: true };
47 const form: any = { elements: { tableOffsetMm: input }, querySelector: () => button };
48 const ids: Record<string, any> = { table: section, "table-form": form, "table-msg": msg };
49 new Function("document", "fetch", script)({ getElementById: (id: string) => ids[id] }, fetcher);
50 const submit = () => form.onsubmit({ preventDefault() {} });
51 return { input, button, msg, section, submit };
52 }
53 const reply = (ok: boolean, body: unknown) => Promise.resolve({ ok, json: () => Promise.resolve(body) });
54 const settle = () => new Promise((r) => setTimeout(r, 0));
55
56 describe("the table height script", () => {
57 test("a good read fills the field and enables it", async () => {
58 const t = run(() => reply(true, { tableOffsetMm: -7 }));
59 expect(t.section.hidden).toBe(false);
60 await settle();
61 expect(t.input).toMatchObject({ value: -7, disabled: false });
62 expect(t.button.disabled).toBe(false);
63 });
64
65 test("a failed or odd read leaves the field disabled and says so", async () => {
66 for (const f of [() => Promise.reject(new Error("down")), () => reply(true, {}), () => reply(true, { tableOffsetMm: 1.5 })]) {
67 const t = run(f);
68 await settle();
69 expect(t.input.disabled).toBe(true);
70 expect(t.button.disabled).toBe(true);
71 expect(t.msg.textContent).toBe("could not read the table height");
72 }
73 });
74
75 test("a save PUTs the number as JSON; a refusal shows the server's words", async () => {
76 const calls: any[] = [];
77 let ok = true;
78 const t = run((path, init) => {
79 calls.push([path, init?.method, init?.headers?.["content-type"], init?.body]);
80 return init?.method === "PUT" ? (ok ? reply(true, {}) : reply(false, { error: "tableOffsetMm must be -100 to 100" })) : reply(true, { tableOffsetMm: 0 });
81 });
82 await settle();
83 t.input.value = "25";
84 await t.submit();
85 expect(calls.at(-1)).toEqual(["/settings", "PUT", "application/json", '{"tableOffsetMm":25}']);
86 expect(t.msg.textContent).toBe("Saved.");
87 ok = false;
88 await t.submit();
89 expect(t.msg).toMatchObject({ textContent: "tableOffsetMm must be -100 to 100", className: "flash bad" });
90 });
91
92 test("a value out of range or not whole is refused before any request", async () => {
93 const calls: unknown[] = [];
94 const t = run((path, init) => (calls.push(init?.method), reply(true, { tableOffsetMm: 0 })));
95 await settle();
96 for (const v of ["101", "-101", "1.5", "", "abc"]) {
97 t.input.value = v;
98 await t.submit();
99 expect(t.msg.className).toBe("flash bad");
100 }
101 expect(calls).toEqual([undefined]); // only the read
102 });
103 });
Software/so101/src/admin-page.ts +29 −2
@@ -57,6 +57,28 @@ th { color: var(--dim); font-weight: 600; }
5757 @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }
5858 `;
5959
60 /** The table height field: reads the arm server's settings and saves tableOffsetMm with PUT /settings, same-origin. Owner only. */
61 const TABLE_SCRIPT = `
62 const sec = document.getElementById("table"), f = document.getElementById("table-form"), i = f.elements.tableOffsetMm, b = f.querySelector("button"), m = document.getElementById("table-msg");
63 const say = (t, bad) => { m.textContent = t; m.className = bad ? "flash bad" : "empty"; };
64 sec.hidden = false;
65 fetch("/settings", { cache: "no-store" }).then((r) => r.json()).then((s) => {
66 if (!Number.isInteger(s.tableOffsetMm)) throw 0;
67 i.value = s.tableOffsetMm; i.disabled = b.disabled = false;
68 }).catch(() => say("could not read the table height", true));
69 f.onsubmit = async (e) => {
70 e.preventDefault();
71 const mm = Number(i.value);
72 if (i.value.trim() === "" || !Number.isInteger(mm) || mm < -100 || mm > 100) return say("table height must be a whole number of mm from -100 to 100", true);
73 try {
74 const r = await fetch("/settings", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ tableOffsetMm: mm }), cache: "no-store" });
75 const j = await r.json().catch(() => ({}));
76 r.ok ? say("Saved.") : say(j.error || "could not save the table height", true);
77 } catch { say("could not save the table height", true); }
78 };
79 `;
80 const hash = (text: string) => `'sha256-${createHash("sha256").update(text).digest("base64")}'`;
81
6082 /** The Health table's columns: the row key and its heading. */
6183 const HEALTH_COLUMNS: readonly (readonly [keyof ViewerRow, string])[] = [
6284 ["name", "Viewer"], ["rttP50", "RTT p50 ms"], ["rttP95", "RTT p95 ms"], ["sentPerS", "Sent/s"], ["droppedPerS", "Dropped/s"],
@@ -83,7 +105,7 @@ async function tick() {
83105 setInterval(tick, 2000);
84106 `;
85107
86 export const ADMIN_CSP = `default-src 'none'; style-src 'sha256-${createHash("sha256").update(STYLE).digest("base64")}'; script-src 'sha256-${createHash("sha256").update(HEALTH_SCRIPT).digest("base64")}'; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
108 export const ADMIN_CSP = `default-src 'none'; style-src ${hash(STYLE)}; script-src ${hash(HEALTH_SCRIPT)} ${hash(TABLE_SCRIPT)}; connect-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
87109
88110 /** The fixed lines a redirect back may ask for; nothing from the request is echoed. */
89111 export const DONE = { saved: "Saved.", paused: "Paused: nobody new gets a turn.", resumed: "Open again: the next in line has control.", ended: "Turn ended.", taken: "You have control.", restored: "Line restored." } as const;
@@ -140,7 +162,7 @@ const entries = (list: readonly LogEntry[], none: string): string =>
140162 const health = (rows: readonly ViewerRow[]): string =>
141163 `<div class="scroll"><table aria-label="Viewer health"><caption>Each open page's link, as it last reported; refreshed every 2 seconds.</caption><thead><tr>${HEALTH_COLUMNS.map(([, h]) => `<th scope="col">${h}</th>`).join("")}</tr></thead><tbody id="health-rows">${rows.map((r) => `<tr>${HEALTH_COLUMNS.map(([k]) => `<td>${esc(String(r[k]))}</td>`).join("")}</tr>`).join("")}</tbody></table></div><p class="empty" id="health-none"${rows.length ? " hidden" : ""}>No viewer has reported yet.</p>`;
142164
143 const field = (name: keyof AdminSettings, label: string, hint: string, value: number, min: number, max: number, off: string) =>
165 const field = (name: keyof AdminSettings | "tableOffsetMm", label: string, hint: string, value: number, min: number, max: number, off: string) =>
144166 `<label>${label}<small>${hint}</small><input name="${name}" type="number" inputmode="numeric" required min="${min}" max="${max}" step="1" value="${value}"${off}></label>`;
145167
146168 const action = (name: string, text: string, cls = "", disabled = false) =>
@@ -193,6 +215,11 @@ ${field("slowModeSeconds", "Slow mode", "seconds between a person's chat message
193215 ${p.canEdit ? `<div class="save"><button class="go">Save settings</button></div>` : ""}
194216 </form>
195217 </section>
218 ${p.canEdit ? `<section id="table" aria-labelledby="table-h" hidden><h2 id="table-h">Table height</h2>
219 <form id="table-form">${field("tableOffsetMm", "Table height", "mm from the model's floor, -100–100", 0, -100, 100, " disabled")}
220 <div class="save"><button class="go" disabled>Save table height</button></div><p id="table-msg" class="empty" role="status"></p></form>
221 <script>${TABLE_SCRIPT}</script>
222 </section>` : ""}
196223 <section aria-labelledby="health"><h2 id="health">Health</h2>${health(p.health ?? [])}</section>
197224 <section aria-labelledby="mods"><h2 id="mods">Moderators</h2>${mods}</section>
198225 <section aria-labelledby="moderation"><h2 id="moderation">Moderation</h2>${actions}</section>
Software/so101/src/lobby.test.ts +2 −2
@@ -775,9 +775,9 @@ describe("lobby", () => {
775775
776776 const ok = await page(OWNER);
777777 expect(ok.status).toBe(200);
778 expect(ok.headers.get("content-security-policy")).toMatch(/^default-src 'none'; style-src 'sha256-[A-Za-z0-9+/=]+'/);
778 expect(ok.headers.get("content-security-policy")).toMatch(/^default-src 'none'; style-src 'sha256-[A-Za-z0-9+/=]+'; script-src 'sha256-[A-Za-z0-9+/=]+' 'sha256-[A-Za-z0-9+/=]+'; connect-src 'self'/);
779779 const html = await ok.text();
780 expect(html.match(/<script/g)).toHaveLength(1); // the Health refresh, pinned by hash in the CSP; the announcement's is escaped
780 expect(html.match(/<script/g)).toHaveLength(2); // the Health refresh and the table height, each pinned by hash in the CSP; the announcement's is escaped
781781 expect(html).not.toContain("<script>alert");
782782 expect(html).toContain("&#60;script&#62;alert(&#34;x&#34;)&#60;/script&#62;");
783783 expect(html).toContain('name="maxSpeedPercent" type="number" inputmode="numeric" required min="5" max="100" step="1" value="40"');

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs