Public: anyone can read this; the crew can change it.
The owner's shell on a game box shows each answer without a reload #17721
Merged 10h 4m ago, live in production
sold/leaf-terminal-1 → main 0 commits 1 thread · 1 unresolved
9 files
changed +401
−30
docs/features/game-box.md +1 −1
| @@ -31,7 +31,7 @@ experiment. | ||
| 31 | 31 | - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand. |
| 32 | 32 | |
| 33 | 33 | Code: `src/games/store.ts` (the `game_box` row and its token, the games store's), `src/games/boot.ts` (the boot config), `src/games/agent.sh`, `gameWant` in `src/actions/infra.ts`, and `bootRow` in `src/actions/pinned.ts`. |
| 34 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 34 | - **Console (owner only):** `/games/<box>` has a Console for the box's owner (forge admins are owners): a command is queued like an rcon (`kind: "shell"`, no service), and the agent runs it with `bash -lc` under `capped`, beside the sync: at most 30 s, no terminal and no input, at most 16 KB of output back at the next sync, streamed into the console over the box's own sync. It runs as root (the agent's unit names no user), and both doors say so. Each command is a block (`src/terminal/blocks.ts`): what was typed, its state in words (waiting, the box has it, done, failed, no answer came back) and what it printed; the page replaces a block in place as its state changes, and up and down in the input walk the commands of the blocks on the page, each once; a block's Edit puts its command in the input, for a phone with no arrows. A program that waits on a person (an editor, a pager, `top`, a bare shell or REPL, a `-f` follow) is refused before it is queued, saying what to run instead. Every command (`game.shell.asked`) and its output (`game.shell.done`) go to the audit, the owner's to read, so a secret a command prints stays there: one line at the input says it. In the terminal, `!` on a box's row opens the same console (`:` runs a command). `src/games/shell.ts`. | |
| 35 | 35 | |
| 36 | 36 | - **Spare while servers sleep (#17576):** `/games/<box>` has two `dl` rows (the `status-rows` of the security page), and the terminal's box screen (`b` on a service) the same two as its first line: "Spare while servers sleep: N core-hours a week, M GB (samples of 7 days). Forge checks, same week: C core-hours." (`src/games/spare.ts`, read by `spare_row.ts`, which keeps the pair a minute per box so a redraw or reload reads nothing). Spare memory = the box's memory − what is awake − a reserve that always fits the largest sleeping server (its highest memory seen awake in the window); spare core-hours = the idle cores (the box's vCPUs − awake servers' CPU, 100 % being a core) of each minute a server sleeps, scaled from the minutes sampled to a week. A box with everything awake has 0. Fewer than 24 hours of samples, or a size or sleeper's memory not known, says "unknown", never 0. The checks' figure is the `cpu_s` of the cost ledger's `check` entries that ended in the last 7 days (read from the end of the month files, stopping at the window's start, at most 4 MiB, not walking the chain; "not measured" when none carried it). A server counts as asleep in a minute that it held no memory. |
| 37 | 37 | - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: it is held in the forge's memory until the box's next sync carries it over, once (see below). |
src/terminal/blocks.ts added +68
| @@ -0,0 +1,68 @@ | ||
| 1 | /** | |
| 2 | * A shell on a box as blocks: each command with its state in words and what it printed. The page | |
| 3 | * (`web/terminal_blocks.ts`) and the terminal (`tui/screens/games.ts`) draw the same ones. It is a | |
| 4 | * list of commands, not a session: `games/shell.ts` queues each, and the box answers when it syncs. | |
| 5 | */ | |
| 6 | ||
| 7 | import type { App } from "../app.ts"; | |
| 8 | import { getUserById } from "../core/users.ts"; | |
| 9 | import { SHELL_SERVICE } from "../games/shell.ts"; | |
| 10 | import { mayDo, NO_ANSWER, recentCommands, roleOn, type GameBox } from "../games/store.ts"; | |
| 11 | ||
| 12 | export interface Block { | |
| 13 | readonly id: string; | |
| 14 | readonly text: string; | |
| 15 | readonly state: "queued" | "sent" | "ok" | "failed" | "unanswered"; | |
| 16 | /** What it printed; empty until it is answered. */ | |
| 17 | readonly output: string; | |
| 18 | } | |
| 19 | ||
| 20 | /** Said beside the input on every door, short enough for the terminal's prompt (50 cells): the audit takes the output whole (`auditShellResults`). */ | |
| 21 | export const AUDIT_SAYS = "The audit keeps commands and output, secrets too."; | |
| 22 | ||
| 23 | /** What the shell is, in one line. */ | |
| 24 | export const shellSays = (box: Pick<GameBox, "name">): string => | |
| 25 | `A shell on ${box.name}, as root: each command runs as bash -lc for at most 30 s, with no terminal, and says back at most 16 KB.`; | |
| 26 | ||
| 27 | /** The box's last shell commands, oldest first. The role is read now, so a lost one ends the list: undefined. */ | |
| 28 | export function shellBlocks(app: App, viewerId: string | undefined, box: GameBox): Block[] | undefined { | |
| 29 | const viewer = viewerId === undefined ? undefined : getUserById(app.db, viewerId); | |
| 30 | if (viewer === undefined || !mayDo(roleOn(app.db, viewer, box.id), "owner")) return undefined; | |
| 31 | return recentCommands(app.db, box.id, SHELL_SERVICE, 10) | |
| 32 | .reverse() | |
| 33 | .map((c) => { | |
| 34 | const state = !c.done ? (c.handed ? "sent" : "queued") : c.ok === null ? "unanswered" : c.ok ? "ok" : "failed"; | |
| 35 | return { id: c.id, text: c.text, state, output: state === "ok" || state === "failed" ? c.output : "" }; | |
| 36 | }); | |
| 37 | } | |
| 38 | ||
| 39 | /** A block's state in words. */ | |
| 40 | export function blockSays(b: Block, box: Pick<GameBox, "name">): string { | |
| 41 | switch (b.state) { | |
| 42 | case "queued": | |
| 43 | return `Waiting for ${box.name}'s next check-in`; | |
| 44 | case "sent": | |
| 45 | return `${box.name} has it`; | |
| 46 | case "unanswered": | |
| 47 | return NO_ANSWER; | |
| 48 | default: | |
| 49 | return `${b.state === "ok" ? "Done" : "Failed"}${b.output === "" ? ", and it printed nothing" : ""}`; | |
| 50 | } | |
| 51 | } | |
| 52 | ||
| 53 | /** | |
| 54 | * For a stream: each call gives the blocks whose state is not the one last told. `known` is what | |
| 55 | * the reader already shows (`id:state`, with commas), so an answer between its page and its stream, | |
| 56 | * or while it was disconnected, is not missed. | |
| 57 | */ | |
| 58 | export function blockChanges(known: string): (blocks: readonly Block[]) => Block[] { | |
| 59 | const told = new Map(known.slice(0, 2_000).split(",").map((k): [string, string] => { | |
| 60 | const [id = "", state = ""] = k.split(":"); | |
| 61 | return [id, state]; | |
| 62 | })); | |
| 63 | return (blocks) => { | |
| 64 | const changed = blocks.filter((b) => told.get(b.id) !== b.state); | |
| 65 | for (const b of changed) told.set(b.id, b.state); | |
| 66 | return changed; | |
| 67 | }; | |
| 68 | } |
src/tui/screens/games.ts +7 −5
| @@ -17,7 +17,8 @@ import { TALK_WORDS, talk } from "../../actions/talk.ts"; | ||
| 17 | 17 | import { emptyText, START_BOX } from "../../core/empty_words.ts"; |
| 18 | 18 | import { consoleText, crashOf } from "../../games/console.ts"; |
| 19 | 19 | import { commitPolicy, policyOf, proxyPort, STILL_BILLED } from "../../games/sleep.ts"; |
| 20 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; | |
| 20 | import { queueShell } from "../../games/shell.ts"; | |
| 21 | import { AUDIT_SAYS, blockSays, shellBlocks, shellSays } from "../../terminal/blocks.ts"; | |
| 21 | 22 | import { watchBox } from "../../games/notify.ts"; |
| 22 | 23 | import { joinAddress, NO_ADDRESS, nowWords, powerNow, PREVIEW_WORDS, privateWords, SAVE_WORDS } from "../../games/gist.ts"; |
| 23 | 24 | import { findingLine, findingsOf as kickFindingsOf } from "../../games/findings.ts"; |
| @@ -652,6 +653,7 @@ export function gameGrantsScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 652 | 653 | */ |
| 653 | 654 | export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { |
| 654 | 655 | let note = ""; |
| 656 | const blocks = () => shellBlocks(f.app, f.user?.id, box) ?? []; | |
| 655 | 657 | const screen: Screen = { |
| 656 | 658 | title: `${box.name} console`, |
| 657 | 659 | keys: [binding([":"], "run a command")], |
| @@ -663,10 +665,8 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 663 | 665 | render(area, s) { |
| 664 | 666 | const c = ctx.theme.c; |
| 665 | 667 | const [head, body] = split(area, "v", [len(1), fill(1)]); |
| 666 | s.text(head!.x, head!.y, truncate(note !== "" ? note : `A shell on ${box.name}: bash -lc, 30 s, no terminal, 16 KB back. : runs one.`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 667 | const lines = recentCommands(f.app.db, box.id, SHELL_SERVICE, 10) | |
| 668 | .reverse() | |
| 669 | .flatMap((cmd) => [`$ ${cmd.text}`, ...(cmd.done ? cmd.output.split("\n") : ["(waiting for the box's next check-in)"])]); | |
| 668 | s.text(head!.x, head!.y, truncate(note !== "" ? note : shellSays(box), head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 669 | const lines = blocks().flatMap((b) => [`$ ${b.text}`, ...(b.output === "" ? [] : b.output.split("\n")), `(${blockSays(b, box)})`]); | |
| 670 | 670 | lines.slice(-body!.h).forEach((l, i) => s.text(body!.x, body!.y + i, truncate(l, body!.w), style(c.fg, c.bg), body!.x + body!.w)); |
| 671 | 671 | }, |
| 672 | 672 | key(e) { |
| @@ -675,6 +675,8 @@ export function gameShellScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 675 | 675 | promptScreen(ctx, screen, { |
| 676 | 676 | title: "Console", |
| 677 | 677 | label: `A command for ${box.name}`, |
| 678 | hint: AUDIT_SAYS, | |
| 679 | history: [...new Set(blocks().map((b) => b.text).reverse())], | |
| 678 | 680 | onSubmit: (text) => { |
| 679 | 681 | const queued = queueShell(f.app, f.user, box, text); |
| 680 | 682 | if (!queued.ok) return queued.error; |
src/web/pages/games.ts +14 −17
| @@ -11,7 +11,9 @@ import { addPluginUrl, commitServiceEnv, composeServices, readCompose, SECRET_KE | ||
| 11 | 11 | import { commitPlan, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf, type Mods, type Plan } from "../../games/mods.ts"; |
| 12 | 12 | import { search, searchPacks, type Hit, type Result } from "../../games/modrinth.ts"; |
| 13 | 13 | import { packCheckLines } from "../../games/pack_check.ts"; |
| 14 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; | |
| 14 | import { queueShell } from "../../games/shell.ts"; | |
| 15 | import { blockChanges, blockSays, shellBlocks, shellSays } from "../../terminal/blocks.ts"; | |
| 16 | import { blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; | |
| 15 | 17 | import { statusRow } from "./security.ts"; |
| 16 | 18 | import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 17 | 19 | import { spareRow } from "../../games/spare_row.ts"; |
| @@ -291,8 +293,8 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 291 | 293 | ctx, |
| 292 | 294 | title: `Games · ${box.name}`, |
| 293 | 295 | styleCss: TOPOLOGY_CSS, |
| 294 | // The owner's console streams its answers over the box's own sync, as a service's does. | |
| 295 | ...(role === "owner" ? { scriptJs: gamesConsoleJs } : {}), | |
| 296 | // The owner's console streams its answers over the box's own sync. | |
| 297 | ...(role === "owner" ? { scriptJs: terminalBlocksJs } : {}), | |
| 296 | 298 | body: html`${pageHead(box.name, { |
| 297 | 299 | sub: `${box.repo}@${box.branch}:${box.path}${box.composeSha === "" ? "" : ` · running ${box.composeSha.slice(0, 10)}`}`, |
| 298 | 300 | })} |
| @@ -336,18 +338,10 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 336 | 338 | * said, newest last, and the answers to come streamed in over the sync. 30 s and 16 KB a command. |
| 337 | 339 | */ |
| 338 | 340 | function shellBlock(ctx: Ctx, box: GameBox): Html { |
| 339 | const done = recentCommands(ctx.app.db, box.id, SHELL_SERVICE, 10).reverse(); | |
| 340 | const lines = done.flatMap((c) => [`$ ${c.text}`, c.done ? c.output : "(waiting for the box's next check-in)"]); | |
| 341 | 341 | return html`<section class="settings-block" id="shell"> |
| 342 | 342 | <h2>Console</h2> |
| 343 | <p class="muted small">A shell on ${box.name}: each command runs as <code>bash -lc</code> for at most 30 s, with no terminal, and says back at most 16 KB. Every command and its output go to the audit.</p> | |
| 344 | <pre id="game-log" class="run-log mono" tabindex="0" aria-label="Console of ${box.name}" data-stream="/games/${box.name}/@shell/stream" data-last="0"> | |
| 345 | ${lines.join("\n")}${lines.length > 0 ? "\n" : ""}</pre | |
| 346 | > | |
| 347 | <form method="post" action="/games/${box.name}/@shell" class="row-fields"> | |
| 348 | <input class="input mono" name="text" aria-label="Command" placeholder="df -h /; docker ps" autocomplete="off" /> | |
| 349 | ${btn("Run", { type: "submit" })} | |
| 350 | </form> | |
| 343 | <p class="muted small">${shellSays(box)}</p> | |
| 344 | ${blocksForm(shellBlocks(ctx.app, ctx.auth.user?.id, box) ?? [], box, `/games/${box.name}/@shell`)} | |
| 351 | 345 | </section>`; |
| 352 | 346 | } |
| 353 | 347 | |
| @@ -366,12 +360,15 @@ export function gameShellStream(ctx: Ctx): Response { | ||
| 366 | 360 | const got = boxOf(ctx, "owner"); |
| 367 | 361 | if (got instanceof Response) return got; |
| 368 | 362 | const { box } = got; |
| 369 | const answers = answersOf(ctx.app.db, box.id, SHELL_SERVICE); | |
| 370 | return eventStream(ctx.app, ctx.request, (emit, _close, ready) => | |
| 363 | const changes = blockChanges(ctx.url.searchParams.get("known") ?? ""); | |
| 364 | return eventStream(ctx.app, ctx.request, (emit, close, ready) => | |
| 371 | 365 | watchBox(ctx.app, box.id, () => { |
| 372 | 366 | if (!ready()) return; |
| 373 | const results = answers(); | |
| 374 | if (results.length > 0) emit("lines", { lines: [], results: results.map((r) => ({ id: r.id, ok: r.ok, output: `$ ${r.text}\n${r.output}`, says: commandSays(r) })) }); | |
| 367 | const blocks = shellBlocks(ctx.app, ctx.auth.user?.id, box); | |
| 368 | // No longer the box's owner: nothing more is said. | |
| 369 | if (blocks === undefined) return close(); | |
| 370 | const changed = changes(blocks); | |
| 371 | if (changed.length > 0) emit("blocks", { blocks: changed.map((b) => ({ id: b.id, says: blockSays(b, box), html: blockHtml(b, box).toString() })) }); | |
| 375 | 372 | }), |
| 376 | 373 | ); |
| 377 | 374 | } |
src/web/terminal_blocks.ts added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | /** | |
| 2 | * A shell's blocks on a page (`terminal/blocks.ts`): drawn by the forge, then each one replaced in | |
| 3 | * place as its state changes. With no script the same page works by reloading. | |
| 4 | */ | |
| 5 | ||
| 6 | import { AUDIT_SAYS, blockSays, type Block } from "../terminal/blocks.ts"; | |
| 7 | import { html, type Html } from "./html.ts"; | |
| 8 | import { btn, field } from "./ui.ts"; | |
| 9 | ||
| 10 | /** One command: what was typed, its state, what it printed. */ | |
| 11 | export function blockHtml(b: Block, box: { readonly name: string }): Html { | |
| 12 | return html`<div id="block-${b.id}" data-block="${b.id}:${b.state}" data-command="${b.text}"><p class="mono break">$ ${b.text} ${btn("Edit", { type: "button", size: "sm", variant: "ghost", extra: "js-only", label: `Edit ${b.text} in the input` })}</p><p class="muted small" data-says>${blockSays(b, box)}</p>${b.output === "" ? null : html`<pre class="run-log mono" tabindex="0" aria-label="What ${b.text} printed"> | |
| 13 | ${b.output}</pre>`}</div>`; | |
| 14 | } | |
| 15 | ||
| 16 | /** The blocks, and the input under them with what the audit keeps. */ | |
| 17 | export function blocksForm(blocks: readonly Block[], box: { readonly name: string }, action: string): Html { | |
| 18 | return html`<div id="shell-blocks" data-stream="${action}/stream">${blocks.map((b) => blockHtml(b, box))}</div> | |
| 19 | <p id="shell-said" class="sr-only" role="status"></p> | |
| 20 | <form method="post" action="${action}"> | |
| 21 | ${field({ id: "shell-command", name: "text", label: "Command", labelHidden: true, mono: true, placeholder: "df -h /; docker ps", autocomplete: "off", autocorrect: false, spellcheck: false, describedby: "shell-audit" })} | |
| 22 | ${btn("Run", { type: "submit" })} | |
| 23 | </form> | |
| 24 | <p id="shell-audit" class="muted small">${AUDIT_SAYS}</p>`; | |
| 25 | } | |
| 26 | ||
| 27 | /** The page's script: blocks over the stream, and up and down through the earlier commands. */ | |
| 28 | export const terminalBlocksJs = /* js */ ` | |
| 29 | (function () { | |
| 30 | var box = document.getElementById('shell-blocks'); | |
| 31 | var said = document.getElementById('shell-said'); | |
| 32 | if (!box) return; | |
| 33 | if (typeof EventSource !== 'undefined') { | |
| 34 | var known = Array.prototype.map.call(box.querySelectorAll('[data-block]'), function (b) { return b.getAttribute('data-block'); }); | |
| 35 | var es = new EventSource(box.getAttribute('data-stream') + '?known=' + encodeURIComponent(known.join(','))); | |
| 36 | es.addEventListener('blocks', function (e) { | |
| 37 | var d; try { d = JSON.parse(e.data); } catch (_) { return; } | |
| 38 | d.blocks.forEach(function (b) { | |
| 39 | // Drawn and escaped by the forge, as the page's own blocks are. | |
| 40 | var old = document.getElementById('block-' + b.id); | |
| 41 | if (old) old.outerHTML = b.html; else box.insertAdjacentHTML('beforeend', b.html); | |
| 42 | if (said) said.textContent = b.says; | |
| 43 | }); | |
| 44 | }); | |
| 45 | } | |
| 46 | var input = document.getElementById('shell-command'); | |
| 47 | if (!input) return; | |
| 48 | // The blocks are the history: newest first, each command once. | |
| 49 | function commands() { | |
| 50 | return Array.prototype.map.call(box.querySelectorAll('[data-command]'), function (c) { return c.getAttribute('data-command'); }) | |
| 51 | .reverse().filter(function (c, i, all) { return all.indexOf(c) === i; }); | |
| 52 | } | |
| 53 | var at = -1, typed = '', past = []; | |
| 54 | input.addEventListener('keydown', function (e) { | |
| 55 | if (e.key !== 'ArrowUp' && e.key !== 'ArrowDown') return; | |
| 56 | // Read as the walk starts, so a block that comes meanwhile moves nothing. | |
| 57 | if (at === -1) { typed = input.value; past = commands(); } | |
| 58 | if (past.length === 0) return; | |
| 59 | e.preventDefault(); | |
| 60 | at = Math.max(-1, Math.min(past.length - 1, at + (e.key === 'ArrowUp' ? 1 : -1))); | |
| 61 | input.value = at === -1 ? typed : past[at]; | |
| 62 | }); | |
| 63 | // A phone has no arrows: a block's button puts its command in the input, and runs nothing. | |
| 64 | box.addEventListener('click', function (e) { | |
| 65 | var again = e.target.closest('button'); | |
| 66 | if (!again) return; | |
| 67 | input.value = again.closest('[data-command]').getAttribute('data-command'); | |
| 68 | at = -1; | |
| 69 | input.focus(); | |
| 70 | }); | |
| 71 | })(); | |
| 72 | `; |
src/web/ui.ts +7 −2
| @@ -1290,6 +1290,10 @@ export interface FieldOptions { | ||
| 1290 | 1290 | mono?: boolean; |
| 1291 | 1291 | /** `false` for names and paths, which a spelling checker only underlines. */ |
| 1292 | 1292 | spellcheck?: boolean; |
| 1293 | /** `false` for a command, which a phone's keyboard must not capitalise or correct. */ | |
| 1294 | autocorrect?: boolean; | |
| 1295 | /** The id of words elsewhere on the page that describe the control, beside its hint and error. */ | |
| 1296 | describedby?: string; | |
| 1293 | 1297 | id?: string; |
| 1294 | 1298 | /** `type: "number"`'s bounds and step. */ |
| 1295 | 1299 | min?: number; |
| @@ -1314,7 +1318,7 @@ export interface FieldOptions { | ||
| 1314 | 1318 | |
| 1315 | 1319 | /** What the control's `aria-describedby` names: the reason's mark or the hint, then the error. */ |
| 1316 | 1320 | function describedBy(o: FieldOptions, id: string): string { |
| 1317 | return [o.why !== undefined ? `why-${o.name}` : o.hint ? `${id}-hint` : "", o.error ? `${id}-err` : ""] | |
| 1321 | return [o.describedby ?? "", o.why !== undefined ? `why-${o.name}` : o.hint ? `${id}-hint` : "", o.error ? `${id}-err` : ""] | |
| 1318 | 1322 | .filter(Boolean) |
| 1319 | 1323 | .join(" "); |
| 1320 | 1324 | } |
| @@ -1345,7 +1349,8 @@ export function field(o: FieldOptions): Html { | ||
| 1345 | 1349 | ${o.autofocus ? raw("autofocus") : null} |
| 1346 | 1350 | ${o.readonly ? raw("readonly") : null} |
| 1347 | 1351 | ${o.placeholder ? html`placeholder="${o.placeholder}"` : null} |
| 1348 | ${o.spellcheck === false ? raw('spellcheck="false"') : null}`; | |
| 1352 | ${o.spellcheck === false ? raw('spellcheck="false"') : null} | |
| 1353 | ${o.autocorrect === false ? raw('autocapitalize="off" autocorrect="off"') : null}`; | |
| 1349 | 1354 | const control = |
| 1350 | 1355 | o.type === "textarea" |
| 1351 | 1356 | ? html`<textarea ${shared} rows="${o.rows ?? 6}" data-grow> |
test/game-answer.test.ts +4 −4
| @@ -52,9 +52,9 @@ test("a command whose answer never comes says so, is not sent again, and a late | ||
| 52 | 52 | } |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | for (const [door, path, service, kind] of [ | |
| 56 | ["a service's page", "/games/mc/hub/stream", "hub", "rcon"], | |
| 57 | ["the owner's console", "/games/mc/@shell/stream", "", "shell"], | |
| 55 | for (const [door, path, service, kind, event] of [ | |
| 56 | ["a service's page", "/games/mc/hub/stream", "hub", "rcon", "lines"], | |
| 57 | ["the owner's console", "/games/mc/@shell/stream", "", "shell", "blocks"], | |
| 58 | 58 | ] as const) |
| 59 | 59 | test(`with no sync at all, ${door} is told that no answer came, and the look ends with the stream`, async () => { |
| 60 | 60 | const dir = mkdtempSync(join(tmpdir(), "forge-game-silent-")); |
| @@ -77,7 +77,7 @@ for (const [door, path, service, kind] of [ | ||
| 77 | 77 | app.db.query("UPDATE game_command SET handed_at = ?2 WHERE id = ?1").run(id, new Date(Date.now() - 121_000).toISOString()); |
| 78 | 78 | jest.advanceTimersByTime(LOOK_MS); |
| 79 | 79 | let text = ""; |
| 80 | while (!text.includes("event: lines")) text += new TextDecoder().decode((await reader.read()).value); | |
| 80 | while (!text.includes(`event: ${event}`)) text += new TextDecoder().decode((await reader.read()).value); | |
| 81 | 81 | expect(text).toContain(`"id":"${id}"`); |
| 82 | 82 | expect(text).toContain(NO_ANSWER); |
| 83 | 83 | expect(jest.getTimerCount()).toBeGreaterThan(before); |
test/terminal-blocks.test.ts added +224
| @@ -0,0 +1,224 @@ | ||
| 1 | /** | |
| 2 | * The owner's shell on /games/<box>: an answer appears in the page as the box gives it, with no | |
| 3 | * reload. The page's own script runs on the page's own HTML, over the forge's real stream. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtempSync } from "node:fs"; | |
| 7 | import { rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { Window } from "happy-dom"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createSession } from "../src/core/sessions.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { synced } from "../src/games/notify.ts"; | |
| 15 | import { queueShell } from "../src/games/shell.ts"; | |
| 16 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; | |
| 17 | import { forgeHttp } from "../src/http/server.ts"; | |
| 18 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 19 | import { gameShellScreen } from "../src/tui/screens/games.ts"; | |
| 20 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | import { pollUntil } from "./helpers/poll.ts"; | |
| 23 | import { settleApp } from "./helpers/tui.ts"; | |
| 24 | ||
| 25 | quietLogs(); | |
| 26 | ||
| 27 | let dir = ""; | |
| 28 | let app: App; | |
| 29 | let http: ReturnType<typeof forgeHttp>; | |
| 30 | let ada: User; | |
| 31 | let bob: User; | |
| 32 | ||
| 33 | beforeAll(async () => { | |
| 34 | dir = mkdtempSync(join(tmpdir(), "forge-terminal-blocks-")); | |
| 35 | app = createApp({ dataDir: dir, port: 0 }); | |
| 36 | http = forgeHttp(app); | |
| 37 | const make = async (username: string, adminIfFirst: boolean): Promise<User> => { | |
| 38 | const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst }); | |
| 39 | if (!made.ok) throw new Error(made.error); | |
| 40 | return made.value; | |
| 41 | }; | |
| 42 | ada = await make("ada", true); | |
| 43 | bob = await make("bob", false); | |
| 44 | createGameBox(app.db, { name: "mc" }); | |
| 45 | }); | |
| 46 | afterAll(async () => { | |
| 47 | app.close(); | |
| 48 | await rm(dir, { recursive: true, force: true }); | |
| 49 | }); | |
| 50 | ||
| 51 | const box = () => boxNamed(app.db, "mc")!; | |
| 52 | const get = async (path: string, who: User): Promise<Response> => | |
| 53 | http.handle(new Request(`http://forge.test${path}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })); | |
| 54 | const ask = (text: string): string => { | |
| 55 | const queued = queueShell(app, ada, box(), text); | |
| 56 | if (!queued.ok) throw new Error(queued.error); | |
| 57 | return queued.value; | |
| 58 | }; | |
| 59 | /** One light sync of the box, with what it answers. */ | |
| 60 | const sync = (results: { id: string; ok: boolean; output: string }[] = []): void => { | |
| 61 | recordSync(app.db, box(), { light: true, results }); | |
| 62 | synced(app, box().id); | |
| 63 | }; | |
| 64 | ||
| 65 | /** The page as a browser has it: its HTML, its own script, and an EventSource over the forge's stream. */ | |
| 66 | async function open(who: User) { | |
| 67 | const page = await (await get("/games/mc", who)).text(); | |
| 68 | const win = new Window({ url: "http://forge.test/games/mc" }); | |
| 69 | win.document.write(page.replace(/<script[\s\S]*?<\/script>/g, "")); | |
| 70 | const readers: { cancel(): Promise<void> }[] = []; | |
| 71 | class Source { | |
| 72 | readonly on = new Map<string, (e: { data: string }) => void>(); | |
| 73 | opened: Promise<void>; | |
| 74 | constructor(url: string) { | |
| 75 | this.opened = this.read(url); | |
| 76 | } | |
| 77 | addEventListener(kind: string, f: (e: { data: string }) => void): void { | |
| 78 | this.on.set(kind, f); | |
| 79 | } | |
| 80 | async read(url: string): Promise<void> { | |
| 81 | const reader = (await get(url, who)).body!.getReader(); | |
| 82 | readers.push(reader); | |
| 83 | let text = ""; | |
| 84 | for (let got = await reader.read(); !got.done; got = await reader.read()) { | |
| 85 | text += new TextDecoder().decode(got.value); | |
| 86 | for (let end = text.indexOf("\n\n"); end >= 0; end = text.indexOf("\n\n")) { | |
| 87 | const [, kind, data] = /^event: (.*)\ndata: (.*)$/m.exec(text.slice(0, end)) ?? []; | |
| 88 | text = text.slice(end + 2); | |
| 89 | if (kind !== undefined) this.on.get(kind)?.({ data: data! }); | |
| 90 | } | |
| 91 | } | |
| 92 | } | |
| 93 | } | |
| 94 | // The page's own script is the one hashed `page-` file; it starts at DOMContentLoaded. | |
| 95 | const src = /<script src="([^"]*\/page-[^"]+)"/.exec(page)?.[1]; | |
| 96 | if (src === undefined) throw new Error("the page ships no script of its own"); | |
| 97 | new Function("document", "EventSource", await (await get(src, who)).text())(win.document, Source); | |
| 98 | win.document.dispatchEvent(new win.Event("DOMContentLoaded")); | |
| 99 | await pollUntil(() => readers.length > 0, "the stream opens"); | |
| 100 | return { | |
| 101 | win, | |
| 102 | shell: () => win.document.getElementById("shell")!.textContent, | |
| 103 | close: async () => { | |
| 104 | for (const r of readers) await r.cancel(); | |
| 105 | await win.happyDOM.close(); | |
| 106 | }, | |
| 107 | }; | |
| 108 | } | |
| 109 | ||
| 110 | test("a shell command's answer appears in the page without a reload, escaped", async () => { | |
| 111 | const id = ask("cat notes"); | |
| 112 | const page = await open(ada); | |
| 113 | try { | |
| 114 | expect(page.shell()).toContain("cat notes"); | |
| 115 | sync(); | |
| 116 | sync([{ id, ok: true, output: "<b>first</b>\nsecond" }]); | |
| 117 | await pollUntil(() => page.shell().includes("<b>first</b>\nsecond"), "the answer in the page", 3_000); | |
| 118 | expect(page.win.document.querySelector("#shell b")).toBeNull(); | |
| 119 | } finally { | |
| 120 | await page.close(); | |
| 121 | } | |
| 122 | }); | |
| 123 | ||
| 124 | test("each state is said, an answer missed between the page and its stream comes, and up walks the history", async () => { | |
| 125 | const id = ask("uptime"); | |
| 126 | const page = await open(ada); | |
| 127 | try { | |
| 128 | const says = () => page.win.document.querySelector(`#block-${id} [data-says]`)?.textContent; | |
| 129 | expect(says()).toBe("Waiting for mc's next check-in"); | |
| 130 | sync(); | |
| 131 | await pollUntil(() => says() === "mc has it", "the box has it"); | |
| 132 | sync([{ id, ok: false, output: "" }]); | |
| 133 | await pollUntil(() => says() === "Failed, and it printed nothing", "it failed"); | |
| 134 | expect(page.win.document.getElementById("shell-said")!.textContent).toBe("Failed, and it printed nothing"); | |
| 135 | const input = page.win.document.getElementById("shell-command") as unknown as { value: string; dispatchEvent(e: unknown): void }; | |
| 136 | const press = (key: string) => input.dispatchEvent(new page.win.KeyboardEvent("keydown", { key })); | |
| 137 | input.value = "half"; | |
| 138 | press("ArrowUp"); | |
| 139 | expect(input.value).toBe("uptime"); | |
| 140 | press("ArrowDown"); | |
| 141 | expect(input.value).toBe("half"); | |
| 142 | } finally { | |
| 143 | await page.close(); | |
| 144 | } | |
| 145 | // A stream told the page still shows it queued says at its first look what came since. | |
| 146 | const res = await get(`/games/mc/@shell/stream?known=${id}:queued`, ada); | |
| 147 | const reader = res.body!.getReader(); | |
| 148 | sync(); | |
| 149 | let text = ""; | |
| 150 | while (!text.includes("event: blocks")) text += new TextDecoder().decode((await reader.read()).value); | |
| 151 | expect(text).toContain("Failed, and it printed nothing"); | |
| 152 | await reader.cancel(); | |
| 153 | }); | |
| 154 | ||
| 155 | test("up and down walk the blocks on the page, one sent since too, each command once; a block's Edit fills the input", async () => { | |
| 156 | ask("first"); | |
| 157 | ask("second"); | |
| 158 | ask("first"); | |
| 159 | const page = await open(ada); | |
| 160 | try { | |
| 161 | const doc = page.win.document; | |
| 162 | expect(doc.querySelectorAll("#shell datalist").length).toBe(0); | |
| 163 | const id = ask("sent since"); | |
| 164 | sync(); | |
| 165 | await pollUntil(() => doc.getElementById(`block-${id}`) !== null, "the new block"); | |
| 166 | const input = doc.getElementById("shell-command") as unknown as { value: string; dispatchEvent(e: unknown): void }; | |
| 167 | const press = (key: string): string => { | |
| 168 | input.dispatchEvent(new page.win.KeyboardEvent("keydown", { key })); | |
| 169 | return input.value; | |
| 170 | }; | |
| 171 | expect([press("ArrowUp"), press("ArrowUp"), press("ArrowUp")]).toEqual(["sent since", "first", "second"]); | |
| 172 | expect([press("ArrowDown"), press("ArrowDown"), press("ArrowDown")]).toEqual(["first", "sent since", ""]); | |
| 173 | (doc.querySelector(`#block-${id} button`) as unknown as { click(): void }).click(); | |
| 174 | expect(input.value).toBe("sent since"); | |
| 175 | expect(press("ArrowUp")).toBe("sent since"); | |
| 176 | expect(press("ArrowDown")).toBe("sent since"); | |
| 177 | } finally { | |
| 178 | await page.close(); | |
| 179 | } | |
| 180 | }); | |
| 181 | ||
| 182 | test("the page says it is root and what the audit keeps, beside the input", async () => { | |
| 183 | const page = await open(ada); | |
| 184 | expect(page.shell()).toContain("A shell on mc, as root"); | |
| 185 | const told = page.win.document.getElementById("shell-command")!.getAttribute("aria-describedby")!; | |
| 186 | expect(page.win.document.getElementById(told)!.textContent).toBe("The audit keeps commands and output, secrets too."); | |
| 187 | await page.close(); | |
| 188 | }); | |
| 189 | ||
| 190 | test("an owner who loses the role is told nothing more", async () => { | |
| 191 | grant(app.db, box().id, bob.id, "owner"); | |
| 192 | const reader = (await get("/games/mc/@shell/stream", bob)).body!.getReader(); | |
| 193 | grant(app.db, box().id, bob.id, "operator"); | |
| 194 | const id = ask("echo private"); | |
| 195 | sync(); | |
| 196 | sync([{ id, ok: true, output: "private words" }]); | |
| 197 | let text = ""; | |
| 198 | for (let got = await reader.read(); !got.done; got = await reader.read()) text += new TextDecoder().decode(got.value); | |
| 199 | expect(text).not.toContain("private"); | |
| 200 | }); | |
| 201 | ||
| 202 | test("the terminal draws the same blocks, and its prompt says what the audit keeps and has the history", async () => { | |
| 203 | ask("free -m"); | |
| 204 | const terminal = headlessTerminal(120, 40); | |
| 205 | const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada }, { terminal, exitHooks: false }); | |
| 206 | tui.start(); | |
| 207 | try { | |
| 208 | tui.ctx.push(gameShellScreen(session, tui.ctx, box())); | |
| 209 | await settleApp(tui); | |
| 210 | const shown = tui.screen.toText(); | |
| 211 | expect(shown).toContain("A shell on mc, as root"); | |
| 212 | expect(shown).toContain("$ free -m"); | |
| 213 | expect(shown).toContain("(Waiting for mc's next check-in)"); | |
| 214 | expect(shown).toContain("(Failed, and it printed nothing)"); | |
| 215 | terminal.feed(":"); | |
| 216 | await settleApp(tui); | |
| 217 | expect(tui.screen.toText()).toContain("The audit keeps commands and output, secrets too."); | |
| 218 | terminal.feed("\x1b[A"); | |
| 219 | await settleApp(tui); | |
| 220 | expect(tui.screen.toText()).toMatch(/[^$] free -m/); | |
| 221 | } finally { | |
| 222 | tui.stop?.(); | |
| 223 | } | |
| 224 | }); |
test/ui-spec/field.test.ts +4 −1
| @@ -1,4 +1,4 @@ | ||
| 1 | import { test } from "bun:test"; | |
| 1 | import { expect, test } from "bun:test"; | |
| 2 | 2 | import { field } from "../../src/web/ui.ts"; |
| 3 | 3 | import { expectAccessible } from "./helper.ts"; |
| 4 | 4 | |
| @@ -11,4 +11,7 @@ test("field: text, textarea, select, checkbox, error, hidden label", () => { | ||
| 11 | 11 | expectAccessible(field({ label: "Kind", name: "kind", type: "select", options: [{ value: "a", label: "A" }] }), SELECT); |
| 12 | 12 | expectAccessible(field({ label: "Public", name: "pub", type: "checkbox", checked: true })); |
| 13 | 13 | expectAccessible(field({ label: "Search", name: "q", labelHidden: true })); |
| 14 | const command = field({ label: "Command", name: "c", labelHidden: true, autocorrect: false, describedby: "says", hint: "One line" }).toString(); | |
| 15 | expect(command).toContain('aria-describedby="says f-c-hint"'); | |
| 16 | expect(command).toContain('autocapitalize="off" autocorrect="off"'); | |
| 14 | 17 | }); |
new above
offline
Principle 7/tokens: hand-rolled input instead of the
input()component. Use the component. Also the datalist on this field and the ArrowUp/ArrowDown handler in the script do the same job two ways; keep one.