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

Migrated from github.com/Trevato/SO-ARM100

workbenchthis machine

Closing the arm locks its owner out: keep sign-in and /admin working while closed, an Open now button on the resting card, and so101 open/close #579

Merged opened this in answer to

Check · Review · Land done · Live — Landed; nothing deploys from this branch, so this is the end of its path.

Merged

vesper/arm:vesper/578-closing-the-arm-locks-its-owner-out-keep → main 3 commits fork

  • Merged. vesper/578-closing-the-arm-locks-its-owner-out-keep was merged into main as fba1312.

Review

Sign in to review this change.
13 files changed +296 −16
Software/so101/README.md +7
@@ -23,6 +23,13 @@ The owner can close the whole app when the shop is dark: on `/admin`, **Open / C
2323
2424 Closed means: every turn ends (the owner's too) and the line is emptied, nobody can join, the cameras are refused and every open camera and `/follow` stream is closed, and nothing reaches the arm but a STOP (anything else is 503). `/` is then a calm card, **The arm is resting**, with the note, when it should be back and when it was last open, a "Get notified when it's back" button (the browser's own notification, while that tab stays open), and links to the story (`/story`) and the code (src/resting-page.ts). A page that was open when it closed reloads into the card, and the card reloads into the arm when it opens. The reopen time is only shown: the arm never reopens by itself.
2525
26 Closing never locks the owner out. Sign-in (the forge's `/__forge/signin`), `/admin` and `/story` keep working while closed; only turns, cameras, `/follow` and commands are refused. The card has a quiet **Owner? Sign in to open** link (sign-in, then `/admin`), and a signed-in owner sees **Open now** right on the card, which opens it and goes back to the arm (a same-origin form post to `/admin`; anyone else gets no button and is refused).
27
28 The switch also works outside the app:
29
30 - **The file.** Writing `{"open": true}` (or `{"open": false, "note": "…"}`) to `so101/open.json` under `FORGE_APP_DATA` counts within a second, no redeploy; this is the hook for the forge's app settings.
31 - **The CLI.** `so101 open` and `so101 close "Back Saturday 10am CT"` type `/open` or `/close <note>` into the app's terminal over your own ssh, so the forge signs you in exactly as for `ssh` by hand. Pass the app's terminal command (the one `FORGE_APP_SSH` names) with `--ssh "…"` or set `SO101_SSH`. The note goes on ssh's stdin and the command runs without a shell (src/app-switch.ts). Not yet tried against the forge's real terminal: if it insists on a pty and the line is lost, add `-tt` to the ssh command (`--ssh "ssh -tt -p …"`); whoever tries it first, say here which it needs.
32
2633 The arm closes itself too: a real arm (ARM_SERVER) that has not answered for more than 2 minutes shows the same card worded **The arm is offline right now**, until the arm answers again. If the owner presses **Open anyway** after it went, the page shows the simulation instead, as before.
2734
2835 `GET /status` says so for everyone: `{"open": false, "reason": "closed"|"offline", "note": "…"|null, "reopenAt": ISO|null, "lastOpenAt": ISO|null, "driver": null, "source": "The arm is resting"}`, answered without asking the arm; while open, the arm's status as before with `"open": true`.
Software/so101/src/admin-routes.ts +3 −1
@@ -167,7 +167,9 @@ export async function handleAdmin(lobby: Lobby, req: IncomingMessage, res: Serve
167167 if (err instanceof AdminError) return show(400, null, err.message);
168168 throw err;
169169 }
170 res.writeHead(303, { location: `/admin?done=${done}`, "cache-control": "no-store" });
170 // The resting card's Open now goes back to the arm itself; every other form comes back here.
171 const home = done === "opened" && form.get("then") === "home";
172 res.writeHead(303, { location: home ? "/" : `/admin?done=${done}`, "cache-control": "no-store" });
171173 res.end();
172174 }
173175
Software/so101/src/app-switch.test.ts added +47
@@ -0,0 +1,47 @@
1 import { expect, test } from "bun:test";
2 import { spawn } from "node:child_process";
3 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { runSwitch, sshArgv, switchLine, SWITCH_NOTE_CHARS } from "./app-switch.ts";
7 import { NOTE_CHARS } from "./opening.ts";
8 import { typed, emptyRoom } from "./terminal.ts";
9
10 test("so101 open and close type the terminal's own /open and /close lines, which the terminal sends as the open frame", () => {
11 expect(switchLine(true)).toBe("/open\n");
12 expect(switchLine(false)).toBe("/close\n");
13 expect(switchLine(false, " Back Saturday 10am CT ")).toBe("/close Back Saturday 10am CT\n");
14 expect(typed(emptyRoom(), switchLine(false, "Back Saturday 10am CT").trimEnd())).toEqual({ send: { type: "open", open: false, note: "Back Saturday 10am CT" } });
15 expect(typed(emptyRoom(), switchLine(true).trimEnd())).toEqual({ send: { type: "open", open: true } });
16 });
17
18 test("a note that is not one line, or too long, is refused before anything runs", () => {
19 expect(SWITCH_NOTE_CHARS).toBe(NOTE_CHARS);
20 expect(() => switchLine(false, "one\n/open")).toThrow(/one line/);
21 expect(() => switchLine(false, "x".repeat(NOTE_CHARS + 1))).toThrow(/at most/);
22 expect(switchLine(false, "x".repeat(NOTE_CHARS))).toBe(`/close ${"x".repeat(NOTE_CHARS)}\n`);
23 expect(() => switchLine(true, "note")).toThrow(/no note/);
24 });
25
26 test("the ssh command is ssh, split into arguments; none says where to find it", () => {
27 expect(sshArgv("ssh -p 2222 [email protected]")).toEqual(["ssh", "-p", "2222", "[email protected]"]);
28 expect(() => sshArgv(undefined)).toThrow(/FORGE_APP_SSH/);
29 expect(() => sshArgv("rm -rf /")).toThrow(/starts with ssh/);
30 });
31
32 test("the line goes on the command's stdin, never its arguments, and its exit code comes back", async () => {
33 const dir = mkdtempSync(join(tmpdir(), "so101-switch-"));
34 try {
35 const out = join(dir, "typed");
36 let argv: readonly string[] = [];
37 const fake = ((cmd: string, args: readonly string[], options: object) => {
38 argv = [cmd, ...args];
39 return spawn("sh", ["-c", 'cat > "$0"', out], options);
40 }) as typeof spawn;
41 expect(await runSwitch(["ssh", "-p", "2222", "arm@host"], "/close Lights; off\n", fake)).toBe(0);
42 expect(readFileSync(out, "utf8")).toBe("/close Lights; off\n");
43 expect(argv).toEqual(["ssh", "-p", "2222", "arm@host"]);
44 } finally {
45 rmSync(dir, { recursive: true, force: true });
46 }
47 });
Software/so101/src/app-switch.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * `so101 open` and `so101 close "note"`: the owner's open/closed switch (src/opening.ts) from a laptop, without a page.
3 *
4 * The CLI does not sign anything itself: it runs the app's own terminal over ssh (the exact command the forge gives as
5 * FORGE_APP_SSH, passed with --ssh or $SO101_SSH) and types one line into it, `/open` or `/close <note>`, which the
6 * terminal sends to the lobby as the person ssh signed in. The server decides whether that person is the owner.
7 * The note goes on ssh's stdin, never on a command line; the ssh command is split on spaces and run without a shell.
8 */
9
10 import { spawn } from "node:child_process";
11
12 /** The longest note (src/opening.ts NOTE_CHARS; not imported, so the CLI never loads the server's modules). */
13 export const SWITCH_NOTE_CHARS = 140;
14
15 export class SwitchError extends Error {}
16
17 /** The one line typed into the terminal: `/open`, or `/close` with the note. Throws SwitchError for a note it can't carry. */
18 export function switchLine(open: boolean, note = ""): string {
19 if (open) {
20 if (note.trim()) throw new SwitchError("so101 open takes no note");
21 return "/open\n";
22 }
23 if (/[\u0000-\u001f\u007f]/.test(note)) throw new SwitchError("the note is one line of text");
24 const text = note.trim();
25 if ([...text].length > SWITCH_NOTE_CHARS) throw new SwitchError(`the note is at most ${SWITCH_NOTE_CHARS} characters`);
26 return text ? `/close ${text}\n` : "/close\n";
27 }
28
29 /** The ssh command as arguments: `ssh -p 2222 arm@host` → ["ssh", "-p", "2222", "arm@host"]. Throws SwitchError. */
30 export function sshArgv(command: string | undefined): string[] {
31 const argv = (command ?? "").trim().split(/\s+/).filter(Boolean);
32 if (argv.length === 0) throw new SwitchError("give the app's ssh command: --ssh \"ssh -p 2222 arm@host\" or SO101_SSH (the app's terminal command, FORGE_APP_SSH)");
33 if (argv[0] !== "ssh") throw new SwitchError(`the ssh command starts with ssh, not ${JSON.stringify(argv[0]!.slice(0, 40))}`);
34 if (argv.some((a) => /[\u0000-\u001f\u007f]/.test(a))) throw new SwitchError("the ssh command is one line");
35 return argv;
36 }
37
38 /** Run the terminal over ssh, type the line, and end input; resolves with ssh's exit code. The terminal prints what the room says. */
39 export function runSwitch(argv: readonly string[], line: string, run: typeof spawn = spawn): Promise<number> {
40 return new Promise((resolve, reject) => {
41 const child = run(argv[0]!, argv.slice(1), { stdio: ["pipe", "inherit", "inherit"] });
42 child.once("error", (err) => reject(new SwitchError(`could not run ${argv[0]}: ${err.message}`)));
43 child.once("close", (code) => resolve(code ?? 1));
44 child.stdin!.end(line);
45 });
46 }
Software/so101/src/cli.ts +16
@@ -52,6 +52,9 @@ usage: so101 <command> [options]
5252 setup [--dry-run] guided: find both arms, reuse calibration, then drive
5353 teleop [--leader P --follower P [--save]] [--hz 60]
5454 the leader arm drives the follower here, space stops it, q quits
55 open [--ssh CMD] open the arm to visitors again, through the app's terminal
56 close ["note"] [--ssh CMD] close it: visitors see the resting card with your note
57 (CMD is the app's terminal command, FORGE_APP_SSH; default $SO101_SSH)
5558
5659 options:
5760 --port <path> serial port (default: $SO101_PORT, else the only USB adapter)
@@ -81,6 +84,7 @@ const OPTIONS = {
8184 follower: { type: "string" },
8285 to: { type: "string" },
8386 model: { type: "string" },
87 ssh: { type: "string" },
8488 } as const;
8589
8690 interface Values {
@@ -106,6 +110,7 @@ interface Values {
106110 follower?: string;
107111 model?: string;
108112 to?: string;
113 ssh?: string;
109114 }
110115
111116 type Command = (values: Values, positionals: string[]) => Promise<void>;
@@ -136,6 +141,14 @@ function message(err: unknown): string {
136141 return (err instanceof Error ? err.message : String(err)).replace(/^Error: /, "");
137142 }
138143
144 /** `so101 open` / `so101 close "note"`: one line typed into the app's terminal over ssh (src/app-switch.ts). */
145 async function flip(values: Values, open: boolean, rest: string[]): Promise<void> {
146 const { runSwitch, sshArgv, switchLine } = await import("./app-switch.ts");
147 const line = switchLine(open, rest.join(" "));
148 const code = await runSwitch(sshArgv(values.ssh ?? process.env.SO101_SSH), line);
149 if (code !== 0) throw new Error(`ssh ended with ${code}`);
150 }
151
139152 const ADAPTER = /usbmodem|usbserial|ttyACM|ttyUSB/i;
140153
141154 const COMMANDS: Record<string, Command> = {
@@ -549,6 +562,9 @@ const COMMANDS: Record<string, Command> = {
549562 await teleop(values.leader, values.follower, bounded(integer(values.hz ?? "60", "--hz"), 1, 120, "--hz"), values.save);
550563 },
551564
565 open: (values, rest) => flip(values, true, rest),
566 close: (values, rest) => flip(values, false, rest),
567
552568 "set-id": (values, [currentArg, nextArg]) => {
553569 if (currentArg === undefined || nextArg === undefined) throw new Error("usage: so101 set-id <current> <new>");
554570 const current = servoId(currentArg, "current id");
Software/so101/src/data-view.test.ts +11 −1
@@ -1,4 +1,4 @@
1 import { afterEach, expect, test } from "bun:test";
1 import { afterEach, expect, setSystemTime, test } from "bun:test";
22 import { mkdtempSync, rmSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
@@ -255,3 +255,13 @@ test("the Pi chart draws under-voltage minutes even with no temperature, and say
255255 expect(neither.all((n) => n.classes.has("mark"))).toHaveLength(0);
256256 expect(neither.all((n) => n.classes.has("none"))[0]!.textContent).toContain("No Pi temperature or under-voltage reading");
257257 });
258
259 test("a sample written in the very millisecond the page asks is in its range (the page's `to` is one ms ahead, like the server's)", async () => {
260 setSystemTime(new Date("2026-10-25T20:00:00.000Z")); // Date stands still: the sample and the page's ask share one ms
261 try {
262 const chart = await piChart({ piUndervolt: true });
263 expect(chart.all((n) => n.classes.has("mark")).length).toBe(1);
264 } finally {
265 setSystemTime();
266 }
267 });
Software/so101/src/lobby.ts +1
@@ -320,6 +320,7 @@ export class Lobby {
320320 /** What the relay knows of the arm, each second and on every change of the link: it may rest the room as offline, or wake it. */
321321 armSeen(arm: ArmSeen): void {
322322 this.arm = arm;
323 this.opening.refresh(); // the switch flipped outside the app (src/opening.ts) counts as soon as it is seen
323324 this.reconsider();
324325 }
325326
Software/so101/src/opening.test.ts +24 −1
@@ -1,5 +1,5 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
2 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { Lobby } from "./lobby.ts";
@@ -98,6 +98,29 @@ describe("the switch is kept", () => {
9898 });
9999 });
100100
101 describe("the switch outside the app", () => {
102 test("a hand-written file is read on refresh: {\"open\": true} alone opens it, stamped now; unchanged is no change", () => {
103 const dir = mkdtempSync(join(tmpdir(), "so101-open-file-"));
104 try {
105 let now = T;
106 const file = join(dir, "open.json");
107 const o = new Opening({ file, now: () => now });
108 o.set({ open: false, note: "Lights off", reopenAt: null });
109 expect(o.refresh()).toBe(false);
110 now = T + 5000;
111 writeFileSync(file, JSON.stringify({ open: true }));
112 expect(o.refresh()).toBe(true);
113 expect(o.state).toEqual({ open: true, note: "", reopenAt: null, changedAt: T + 5000 });
114 expect(o.refresh()).toBe(false);
115 writeFileSync(file, JSON.stringify({ open: false, note: "Back soon", changedAt: T + 6000 }));
116 expect(o.refresh()).toBe(true);
117 expect(o.state).toMatchObject({ open: false, note: "Back soon", changedAt: T + 6000 });
118 } finally {
119 rmSync(dir, { recursive: true, force: true });
120 }
121 });
122 });
123
101124 describe("closed turns", () => {
102125 test("closing ends anyone's turn, the owner's too, and empties the line; nobody may join until it opens", () => {
103126 const turns = new Turns();
Software/so101/src/opening.ts +29 −2
@@ -7,10 +7,12 @@
77 *
88 * Offline (nobody's choice): a real arm the relay has not heard from for more than OFFLINE_AFTER_MS rests the room the
99 * same way, worded "offline", unless the owner switched it open after the arm went (to show the simulation on purpose).
10 * Kept in one JSON file beside the admin settings; plain data in, plain data out.
10 * Kept in one JSON file beside the admin settings; plain data in, plain data out. The file is also the switch outside
11 * the app (the forge's app settings, or a person on the machine): a change to it is picked up within a second, no
12 * redeploy, and `{"open": true}` alone is enough to open it again.
1113 */
1214
13 import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
15 import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
1416 import { dirname } from "node:path";
1517 import { AdminError } from "./admin.ts";
1618 import { cleanText } from "./chat.ts";
@@ -146,7 +148,31 @@ export class Opening {
146148 return true;
147149 }
148150
151 /** Read the file again if something outside the app changed it; returns whether the switch moved. */
152 refresh(): boolean {
153 if (!this.file) return false;
154 const stamp = this.stamp();
155 if (stamp === this.seen) return false;
156 const was = this.state;
157 this.load();
158 // Written by hand without a changedAt: the switch moved now.
159 if (was.open !== this.state.open && this.state.changedAt <= was.changedAt) this.state = { ...this.state, changedAt: this.now() };
160 return JSON.stringify(was) !== JSON.stringify(this.state);
161 }
162
163 /** The file's modification time and size, as last seen ("" while there is none). */
164 private seen = "";
165 private stamp(): string {
166 try {
167 const st = statSync(this.file!);
168 return `${st.mtimeMs}:${st.size}`;
169 } catch {
170 return "";
171 }
172 }
173
149174 private load(): void {
175 this.seen = this.stamp();
150176 try {
151177 const raw = JSON.parse(readFileSync(this.file!, "utf8")) as Record<string, unknown>;
152178 const open = raw.open !== false;
@@ -164,5 +190,6 @@ export class Opening {
164190 mkdirSync(dirname(this.file), { recursive: true });
165191 writeFileSync(`${this.file}.tmp`, JSON.stringify(this.state));
166192 renameSync(`${this.file}.tmp`, this.file);
193 this.seen = this.stamp();
167194 }
168195 }
Software/so101/src/relay.ts +11 −5
@@ -56,7 +56,9 @@
5656 * Resting (the owner closed it, or a real arm unheard for two minutes; src/opening.ts): / is the resting card
5757 * (src/resting-page.ts), /status answers {"open": false, "reason", "note", "reopenAt", "lastOpenAt"} without asking the
5858 * arm, every turn has ended, the cameras and /follow are refused (and those open are closed), and nothing goes to the arm
59 * but a STOP: anything else is 503. Open, /status carries "open": true.
59 * but a STOP: anything else is 503. Sign-in (/__forge/…), /admin and /story keep working, so the owner can always open
60 * it again (#578): the card links an anonymous visitor to sign-in and shows the owner an Open now button. Open, /status
61 * carries "open": true.
6062 *
6163 * GET|PUT|DELETE /leader/calibration the signed-in person's own leader calibration (src/leader-map.js), any time,
6264 * turn or no turn: GET answers it or null, PUT {"joints": {...}} stores it
@@ -202,6 +204,8 @@ const ADMIN_ONLY = new Set(["POST /estop/clear", "PUT /settings", "POST /setting
202204 const OWNER_READS = new Set(["GET /servo-params", "PUT /servo-params", "POST /servo-params/factory", "GET /tuning", "POST /tuning/p"]);
203205 /** The driver's, and any admin's at any time. */
204206 const ADMIN_TOO = new Set(["POST /stop", "POST /resume", "POST /estop"]);
207 /** The forge's own paths (/__forge/signin and the like): the forge answers them in front of the app. */
208 const FORGE_PATH = /^\/__forge(?:\/|$)/;
205209 /** What still goes to the arm server while the link is reconnecting: stopping it. */
206210 const STOPS = new Set(["POST /stop", "POST /estop"]);
207211 const RECONNECTING = "reconnecting to the arm";
@@ -470,9 +474,10 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
470474 /** Why the arm rests right now (src/opening.ts), or null while it is open; never resting without a lobby. */
471475 const restingNow = (): Resting | null => lobby?.resting() ?? null;
472476 /** The resting card, in place of the page. */
473 const restingPage = (res: ServerResponse, rest: Resting) => {
477 const restingPage = (req: IncomingMessage, res: ServerResponse, rest: Resting) => {
478 const who = lobby?.who(req);
474479 res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": RESTING_CSP });
475 res.end(renderResting(rest));
480 res.end(renderResting(rest, who ? (who.owner ? "owner" : "user") : "anonymous"));
476481 };
477482 /**
478483 * The arm's /status, saying which arm it is: from the link while it is live, the last one it had while reconnecting,
@@ -870,11 +875,12 @@ export async function startRelay(options: RelayOptions): Promise<RunningRelay> {
870875 }
871876 }
872877
873 if (req.method === "GET" && PAGE.test(url.pathname) && rest) return restingPage(res, rest);
878 if (req.method === "GET" && PAGE.test(url.pathname) && rest) return restingPage(req, res, rest);
874879 if (req.method === "GET" && PAGE.test(url.pathname)) return await page(req, res, await ask(simulation + path, req, undefined, null, false));
875880 if (req.method === "GET" && STATIC.test(url.pathname) && acceptsGzip(req.headers)) return await packed(res, await ask(simulation + path, req, undefined, null, false), path);
876881 // Resting, nothing reaches an arm but a STOP: not a command, not a read.
877 if (rest && !LOCAL.test(url.pathname) && !STOPS.has(route)) return json(res, 503, { error: `${restingWords(rest)}: nothing goes to it now`, open: false });
882 // The forge's own paths (sign-in among them) are never the arm's: resting never refuses them, so the owner can get back in.
883 if (rest && !LOCAL.test(url.pathname) && !FORGE_PATH.test(url.pathname) && !STOPS.has(route)) return json(res, 503, { error: `${restingWords(rest)}: nothing goes to it now`, open: false });
878884 if (route === "POST /stop" || route === "POST /estop") facts?.event("STOP", lobby ? lobby.who(req)?.id : null);
879885 if (route === "POST /stop") {
880886 // Shut before anything is asked of an arm: a frame already on its way finds the gate closed.
Software/so101/src/resting-page.ts +24 −3
@@ -2,6 +2,9 @@
22 * The page a visitor gets at / while the arm rests (src/opening.ts): one calm card where the camera would be, saying
33 * why (the owner closed it, or the arm is offline), the owner's note, when it should be back and when it was last
44 * open, with a way to be told when it is back, the story and the code. No camera, no controls, no error banner.
5 * The owner is never locked out (#578): an anonymous visitor gets a quiet "Owner? Sign in to open" link to the forge's
6 * sign-in, which comes back to /admin; a signed-in owner gets an Open now button right on the card (a same-origin POST
7 * to /admin, which checks it is the owner again) and a link to /admin.
58 *
69 * Server-rendered from plain data, every value escaped; times go out as UTC text and the script rewrites them in the
710 * visitor's own zone. The script asks GET /status every 20 s: when it says open, it shows the notification the visitor
@@ -39,6 +42,9 @@ button:focus-visible, a:focus-visible { outline: 2px solid var(--accent); outlin
3942 .said { color: var(--dim); font-size: .9rem; min-height: 1.35em; }
4043 nav { display: flex; flex-wrap: wrap; gap: .5rem 1.25rem; border-top: 1px solid var(--line); padding-top: 1rem; }
4144 a { color: var(--accent); display: inline-flex; align-items: center; min-height: 44px; }
45 .owner { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem 1.25rem; }
46 .quiet { color: var(--dim); font-size: .9rem; }
47 form { margin: 0; }
4248 @media (min-width: 720px) {
4349 main { padding: 3rem 2rem; }
4450 .card { max-width: 40rem; padding: 2.5rem 2.75rem; gap: 1.25rem; }
@@ -76,16 +82,30 @@ setTimeout(ask, 20000);
7682 `;
7783
7884 const sha = (text: string) => createHash("sha256").update(text).digest("base64");
79 /** The page's Content-Security-Policy: its style and its script, each pinned by hash; it may only ask /status. */
80 export const RESTING_CSP = `default-src 'none'; style-src 'sha256-${sha(RESTING_STYLE)}'; script-src 'sha256-${sha(RESTING_SCRIPT)}'; connect-src 'self'; img-src 'self'; form-action 'none'; frame-ancestors 'none'; base-uri 'none'`;
85 /** The page's Content-Security-Policy: its style and its script, each pinned by hash; it may only ask /status and post to /admin. */
86 export const RESTING_CSP = `default-src 'none'; style-src 'sha256-${sha(RESTING_STYLE)}'; script-src 'sha256-${sha(RESTING_SCRIPT)}'; connect-src 'self'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`;
8187
8288 const time = (ms: number) => {
8389 const iso = new Date(ms).toISOString();
8490 return `<time datetime="${iso}">${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC</time>`;
8591 };
8692
93 /** The forge's sign-in, back to /admin after: the path the forge answers itself, never the app. */
94 export const OWNER_SIGNIN = "/__forge/signin?to=%2Fadmin";
95
96 /** Who is looking at the card: anonymous, signed in, or the owner. */
97 export type Viewer = "anonymous" | "user" | "owner";
98
99 /** The owner's way back in: sign in (anonymous), nothing (a signed-in visitor who is not the owner), or Open now. */
100 function ownerRow(viewer: Viewer, r: Resting): string {
101 if (viewer === "anonymous") return `<p class="owner quiet">Owner? <a href="${OWNER_SIGNIN}">Sign in to open</a></p>`;
102 if (viewer !== "owner") return "";
103 const label = r.reason === "offline" ? "Open anyway" : "Open now";
104 return `<div class="owner"><form method="post" action="/admin"><input type="hidden" name="action" value="open"><input type="hidden" name="then" value="home"><button>${label}</button></form><a href="/admin">Admin</a></div>`;
105 }
106
87107 /** The resting card as a whole page. */
88 export function renderResting(r: Resting): string {
108 export function renderResting(r: Resting, viewer: Viewer = "anonymous"): string {
89109 const title = restingWords(r);
90110 const description = r.note || (r.reason === "offline" ? "The arm can't be reached from here just now; it comes back by itself." : "The owner has closed the arm for now.");
91111 const when = [
@@ -113,6 +133,7 @@ export function renderResting(r: Resting): string {
113133 ${r.note ? `<p class="note">${esc(r.note)}</p>` : `<p class="note">${esc(description)}</p>`}
114134 ${when ? `<div class="when">${when}</div>` : ""}
115135 <div class="notify"><button type="button" id="notify" hidden>Get notified when it's back</button><p class="said" id="said" role="status"></p></div>
136 ${ownerRow(viewer, r)}
116137 <nav aria-label="While you wait"><a href="${STORY_PATH}">Read the story of the arm</a><a href="${REPO_URL}">See the code</a></nav>
117138 </section>
118139 </main>
Software/so101/src/resting.test.ts +75 −2
@@ -1,5 +1,5 @@
11 import { afterEach, describe, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync } from "node:fs";
2 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import WebSocket from "ws";
@@ -8,7 +8,7 @@ import { FakeBus } from "./fake-bus.ts";
88 import { sign } from "./identity.ts";
99 import { Lobby } from "./lobby.ts";
1010 import { parseRemote, startRelay, type RunningRelay } from "./relay.ts";
11 import { REPO_URL, RESTING_CSP, RESTING_STYLE, STORY_PATH, renderResting } from "./resting-page.ts";
11 import { OWNER_SIGNIN, REPO_URL, RESTING_CSP, RESTING_STYLE, STORY_PATH, renderResting } from "./resting-page.ts";
1212 import { startServer, type RunningServer } from "./server.ts";
1313
1414 const KEY = "k".repeat(64);
@@ -138,6 +138,79 @@ describe("closed by the owner", () => {
138138 });
139139 });
140140
141 describe("closed, the owner is never locked out (#578)", () => {
142 const user = as("bob", "user");
143
144 test("an anonymous visitor's card has a quiet sign-in link back to /admin, and the forge's sign-in path is never refused", async () => {
145 const base = await boot();
146 await fetch(`${base}/admin`, form({ action: "close", note: "Lights off" }));
147 const html = await (await fetch(`${base}/`)).text();
148 expect(html).toContain(`Owner? <a href="${OWNER_SIGNIN}">Sign in to open</a>`);
149 expect(OWNER_SIGNIN).toBe("/__forge/signin?to=%2Fadmin");
150 expect(html).not.toContain("Open now");
151 // Straight to the relay, no forge in front: without its /__forge/ exemption these were the resting 503.
152 for (const path of ["/__forge/signin?to=%2Fadmin", "/__forge/signin"]) {
153 const signin = await fetch(`${base}${path}`, { redirect: "manual" });
154 expect([path, signin.status]).not.toEqual([path, 503]);
155 }
156 // Only the forge's own prefix: a look-alike is still the arm's, and still refused.
157 expect((await fetch(`${base}/__forgery`)).status).toBe(503);
158 expect((await fetch(`${base}/admin`)).status).toBe(404); // anonymous: the page is still nobody's business
159 });
160
161 test("a signed-in owner reaches /admin, and the card shows Open now, which opens it and goes back to the arm", async () => {
162 const base = await boot();
163 await fetch(`${base}/admin`, form({ action: "close", note: "Lights off" }));
164 const admin = await fetch(`${base}/admin`, { headers: owner });
165 expect(admin.status).toBe(200);
166 expect(await admin.text()).toContain("Open the arm");
167
168 const card = await fetch(`${base}/`, { headers: owner });
169 expect(card.headers.get("content-security-policy")).toContain("form-action 'self'");
170 const html = await card.text();
171 expect(html).toContain('<form method="post" action="/admin"><input type="hidden" name="action" value="open"><input type="hidden" name="then" value="home"><button>Open now</button></form>');
172 expect(html).toContain('<a href="/admin">Admin</a>');
173 expect(html).not.toContain("Sign in to open");
174
175 const opened = await fetch(`${base}/admin`, form({ action: "open", then: "home" }));
176 expect(opened.status).toBe(303);
177 expect(opened.headers.get("location")).toBe("/");
178 expect((await (await fetch(`${base}/status`)).json() as any).open).toBe(true);
179 expect(await (await fetch(`${base}/`, { headers: owner })).text()).toContain("urdf-viewer");
180 });
181
182 test("a signed-in visitor who is not the owner sees no Open now and can't open it; nor can another site", async () => {
183 const base = await boot();
184 await fetch(`${base}/admin`, form({ action: "close" }));
185 const html = await (await fetch(`${base}/`, { headers: user })).text();
186 expect(html).not.toContain("Open now");
187 expect(html).not.toContain("Sign in to open");
188 const tried = await fetch(`${base}/admin`, { method: "POST", headers: { ...user, "content-type": "application/x-www-form-urlencoded" }, body: "action=open&then=home", redirect: "manual" });
189 expect(tried.status).toBe(404);
190 const forged = await fetch(`${base}/admin`, { method: "POST", headers: { ...owner, origin: "https://elsewhere.example", "content-type": "application/x-www-form-urlencoded" }, body: "action=open&then=home", redirect: "manual" });
191 expect(forged.status).toBe(403);
192 expect((await (await fetch(`${base}/status`)).json() as any).open).toBe(false);
193 });
194
195 test("the switch flipped outside the app (open.json, the forge's settings) counts within a second or two, no restart", async () => {
196 const base = await boot();
197 await fetch(`${base}/admin`, form({ action: "close", note: "Lights off" }));
198 writeFileSync(join(dir, "open.json"), JSON.stringify({ open: true }));
199 let status: Record<string, unknown> = {};
200 for (let i = 0; i < 30 && status.open !== true; i++) {
201 await sleep(100);
202 status = await (await fetch(`${base}/status`)).json() as any;
203 }
204 expect(status.open).toBe(true);
205 writeFileSync(join(dir, "open.json"), JSON.stringify({ open: false, note: "From the forge" }));
206 for (let i = 0; i < 30 && status.open !== false; i++) {
207 await sleep(100);
208 status = await (await fetch(`${base}/status`)).json() as any;
209 }
210 expect(status).toMatchObject({ open: false, note: "From the forge" });
211 });
212 });
213
141214 describe("offline by itself", () => {
142215 test("a real arm unreachable past the limit shows the offline card, never a broken camera; the owner may open it anyway", async () => {
143216 const base = await boot({ deadArm: true, offlineAfterMs: 300 });
Software/so101/src/ui/data-view.js +2 −1
@@ -379,7 +379,8 @@
379379
380380 async function load() {
381381 const seq = ++state.seq;
382 const now = Date.now();
382 // One ms ahead, as the server's own /data does: the range ends before `to`, and a row written this very ms is in it.
383 const now = Date.now() + 1;
383384 const span = state.custom ? null : RANGES[state.range];
384385 const to = state.custom ? state.custom.to : now;
385386 const from = state.custom ? state.custom.from : now - span;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs