diff --git a/README.md b/README.md index c0309ba28..3dd77c12f 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ You should not have to run `git status` in every worktree to find out what your Not everyone lives in a terminal. `/gentle:tower` opens a local web view where each project is a painted building and each open Gentle Shell session is a floor of it. The orchestrator and its named helpers (`worker`, `explore`, `verify`, or `worker-tests` when a role repeats) stand in the room of what they are doing: the map while exploring, the workshop while building, the lab while testing, the lounge when done. A `?` means a floor needs you. -To open it without a session, run `gentle-shell tower` from any terminal: it prints the local URL, opens your browser and keeps serving until Ctrl+C (`--no-open` only prints the URL; `--port ` fixes the port, still `127.0.0.1` only; `--json` prints the URL as one JSON line for programs). +To open it without a session, run `gentle-shell tower` from any terminal: it prints the local URL, opens your browser and keeps serving until Ctrl+C (`--no-open` only prints the URL; `--port ` fixes the port, still `127.0.0.1` only; `--json` prints the URL as one JSON line for programs). Add `--lan` to also serve the machine's network addresses, so a phone on the same network can open the view: it prints one URL per address, a QR code of the first for the phone to scan, and the warning below. - **Tasks at a glance**: each floor shows its todo progress (`2/4 · blocked: …`); click it for the full list. The map's corkboard notes are the same tasks. - **Talk to a floor** (`T`): read the orchestrator's latest words and send a message; it arrives as a new turn, or as a follow-up while the agent works. Questions asked in the terminal show as waiting; answer them there or tell the floor. @@ -228,7 +228,9 @@ To open it without a session, run `gentle-shell tower` from any terminal: it pri - **Engram library and your tab**: a read-only window on the project's memories and on what the open sessions spent, by model and by project. - **Controls**: stop a helper, change a floor's permissions, and switch review mode. -The web never has more power than the terminal: it listens on `127.0.0.1` only, with a fresh token in the path on every launch, refuses other origins. Lowering a floor's permissions applies at once; raising them asks for confirmation in that session's terminal. Each session runs the requests itself, with its own rules. +On a phone (or any touch screen) the same view adapts: the building scales to the viewport width, the floor cards become a tappable list under it with at least 44px targets, the helpers on a floor get their own tappable chips, and the panels — Talk, tasks, artifacts, the Engram library, your tab, permissions — dock into a bottom sheet. `/gentle:tower-mobile` (or `/gentle:tower --lan`) serves the view on your network for the phone; `gentle-shell tower --lan` from a terminal prints a QR code to scan. + +The web never has more power than the terminal: it listens on `127.0.0.1` only (`--lan` additionally serves the machine's own addresses), with a fresh token in the path on every launch, refuses other origins. Lowering a floor's permissions applies at once; raising them asks for confirmation in that session's terminal. Each session runs the requests itself, with its own rules. `--lan` is for a trusted home network: anyone on it who opens the URL can read and drive your sessions, and the traffic is not encrypted — the launch prints this warning. **[Docs →](docs/gentle-shell.md#gentle-tower)** diff --git a/bin/gentle-shell.mjs b/bin/gentle-shell.mjs index 792978686..e970531a2 100755 --- a/bin/gentle-shell.mjs +++ b/bin/gentle-shell.mjs @@ -2176,7 +2176,7 @@ async function main() { const tower = parseTowerArgs(args.commandArgs); if (tower.error !== undefined) fail(`gentle-shell tower: ${tower.error}\nRun 'gentle-shell --help' for usage.`, 2); const { runTower } = await import("../runtime/tower-open.mjs"); - process.exitCode = await runTower({ env: process.env, open: tower.open, port: tower.port, json: tower.json === true, + process.exitCode = await runTower({ env: process.env, open: tower.open, port: tower.port, json: tower.json === true, lan: tower.lan === true, stdout: (text) => process.stdout.write(text), stderr: (text) => process.stderr.write(text) }); return; } diff --git a/docs/gentle-shell.md b/docs/gentle-shell.md index f9c5a56b0..ce1bc9f72 100644 --- a/docs/gentle-shell.md +++ b/docs/gentle-shell.md @@ -530,7 +530,7 @@ The canvas server binds `127.0.0.1` on a random port and needs a random per-serv ### Gentle Tower -Gentle Tower is a web view of every open Gentle Shell session, for people who prefer a picture to a terminal. Each project is a painted building and each session is a floor of it. Open it with `/gentle:tower` inside a session, or with `gentle-shell tower` from any terminal (`--no-open` prints the URL only, `--port ` fixes the port, `--json` prints one JSON line `{"schema":"gentle-shell.tower/v1","url":…,"host":"127.0.0.1","port":…}` instead of the text, for programs such as the desktop app). It serves until Ctrl+C or until the session that opened it ends. Hovering anything clickable outlines it and names what a click does; a short tour on the first visit points at the floors, people, rooms, door and top bar, and the `?` button (or the `?` key) shows it again. +Gentle Tower is a web view of every open Gentle Shell session, for people who prefer a picture to a terminal. Each project is a painted building and each session is a floor of it. Open it with `/gentle:tower` inside a session, or with `gentle-shell tower` from any terminal (`--no-open` prints the URL only, `--port ` fixes the port, `--json` prints one JSON line `{"schema":"gentle-shell.tower/v1","url":…,"host":"127.0.0.1","port":…}` instead of the text, for programs such as the desktop app; with `--lan` the line also carries `lan`, `urls` and `warning`). `/gentle:tower-mobile` is the one-word way to open the same-network mode from a session (equivalent to `/gentle:tower --lan`); asking for a different mode replaces the running tower with one in that mode. It serves until Ctrl+C or until the session that opened it ends. Hovering anything clickable outlines it and names what a click does; a short tour on the first visit points at the floors, people, rooms, door and top bar, and the `?` button (or the `?` key) shows it again. `/gentle:tower --lan` turns on the same-network mode from a session: the report lists one URL per LAN address and the warning, and the QR code is left to the terminal command, whose text mode prints it under the URLs. Gentle Tower with two floors of the gentle-pi building, their todo bars on the left and the selection strip with Talk, Tasks, Artifacts and Permissions at the bottom @@ -566,9 +566,9 @@ node bin/gentle-shell.mjs --link --package-root "$PWD" `--link` alone may use the `gentle-pi` already installed in that home, rather than the checkout; `--package-root` explicitly selects the checkout for this linked launch. -The server listens on `127.0.0.1` only, on a random port unless you pick one, with a fresh token as the first path segment on every launch; it refuses other origins. A request from the page is checked and queued to that session's private inbox, and the session runs it itself with its own rules; the web never has more power than the terminal. Set `GENTLE_TOWER=off` to stop a session from publishing. +The server listens on `127.0.0.1` only, on a random port unless you pick one, with a fresh token as the first path segment on every launch; it refuses other origins. With `--lan` it binds every interface instead and serves one URL per LAN address, still token-gated, and an origin is accepted only when it names the exact address the page was served on — a host the launch does not serve is refused, which blocks DNS rebinding. The mode prints a warning because anyone on the network holding the URL can read and drive the sessions over unencrypted HTTP; it is meant for a trusted home network. A request from the page is checked and queued to that session's private inbox, and the session runs it itself with its own rules; the web never has more power than the terminal. Set `GENTLE_TOWER=off` to stop a session from publishing. -The web app is built with Vite, TypeScript and PixiJS into `web/tower/dist`, which ships with the package (`pnpm build:tower` rebuilds it). +The web app is built with Vite, TypeScript and PixiJS into `web/tower/dist`, which ships with the package (`pnpm build:tower` rebuilds it). On a phone or any touch screen the layout adapts: the building scales to the viewport width, the floor cards become a tappable list under it (44px minimum targets, one chip per helper), and the panels dock into a bottom sheet; the transport is SSE, so a dropped Wi-Fi reconnects on its own and the next event re-renders the full snapshot. ### Gentle Music diff --git a/extensions/gentle-tower.ts b/extensions/gentle-tower.ts index 166eebc53..53ecbb26d 100644 --- a/extensions/gentle-tower.ts +++ b/extensions/gentle-tower.ts @@ -4,9 +4,10 @@ // the desktop agents adapter; it owns no state of its own beyond the file. import { execFile } from "node:child_process"; +import { type NetworkInterfaceInfo } from "node:os"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; import type { TowerServer } from "../lib/tower-server.ts"; -import { openInBrowser, openTowerServer, TOWER_WEB_DIR, TowerNotBuiltError } from "../lib/tower-open.ts"; +import { openInBrowser, openTowerServer, TOWER_LAN_WARNING, TOWER_WEB_DIR, TowerNotBuiltError } from "../lib/tower-open.ts"; import { discoverDesktopAgentsService } from "../lib/desktop-agents-service.ts"; import { oddPhaseRegistry } from "../lib/odd-phase.ts"; import { collectSessionStats } from "../lib/shell-stats.ts"; @@ -24,6 +25,8 @@ export interface TowerPublisherOptions { now?: () => number; /** Built web app folder (defaults to the package's web/tower/dist). */ webDir?: string; + /** Network interfaces to enumerate the LAN addresses from (defaults to the OS's). */ + interfaces?: NodeJS.Dict; /** Opens the tower URL; defaults to the system browser. */ openUrl?: (url: string) => void; /** How often the session checks its action inbox. */ @@ -64,6 +67,8 @@ export function createTowerPublisher(pi: ExtensionAPI, options: TowerPublisherOp const webDir = options.webDir ?? TOWER_WEB_DIR; const openUrl = options.openUrl ?? openInBrowser; let server: Promise | undefined; + /** The mode the current server promise runs in, so a mode change replaces it. */ + let serverLan: boolean | undefined; const debounceMs = options.debounceMs ?? 300; const now = options.now ?? Date.now; let ctx: ExtensionContext | undefined; @@ -93,6 +98,10 @@ export function createTowerPublisher(pi: ExtensionAPI, options: TowerPublisherOp const stats = collectSessionStats(branch); const usage = ctx.getContextUsage?.(); // The agents service keeps finished tasks as history; only live helpers are on the floor. + // SAFETY: the agents service's record shape is not exported, but every field the + // tower reads from it is an optional member of TowerAgentInput consumed defensively + // (String() coercion for status, optional chains elsewhere), so a field it lacks + // degrades to "unknown" instead of breaking the snapshot. const listed = ((agents?.read().agents ?? []) as unknown as TowerAgentInput[]).filter((a) => LIVE_HELPER.has(String(a.status))); writeTowerSnapshot(dir, { pid: process.pid, ...buildTowerSnapshot({ sessionId, @@ -275,28 +284,58 @@ export function createTowerPublisher(pi: ExtensionAPI, options: TowerPublisherOp // The tower this session opened ends with it. const opened = server; server = undefined; + serverLan = undefined; void opened?.then((s) => s.close()).catch(() => undefined); }); + // Same startup as `gentle-shell tower`: hub, web app, token, presence, new floors. + // The server is reused while the requested mode matches; a different mode + // closes the running one and starts its replacement. + const ensureTower = (lan: boolean): Promise => { + if (server !== undefined && serverLan === lan) return server; + const previous = server; + serverLan = lan; + server = openTowerServer(env, { webDir, ...(lan ? { lan: true } : {}), ...(options.interfaces === undefined ? {} : { interfaces: options.interfaces }) }); + if (previous !== undefined) void previous.then((s) => s.close()).catch(() => undefined); + return server; + }; + + const reportTower = async (lan: boolean, notify: (text: string, level: "info" | "warning" | "error") => void): Promise => { + let pending: Promise | undefined; + try { + pending = ensureTower(lan); + const s = await pending; + // The TUI notify box cannot carry QR art; the terminal command prints it. + const lines = [`Gentle Tower: ${s.url}`, ...s.urls.slice(1).map((u) => ` ${u}`), ...(s.lan ? [TOWER_LAN_WARNING] : [])]; + notify(lines.join("\n"), "info"); + openUrl(s.url); + } catch (error) { + // Clear only the startup this report owns; a newer command may have replaced it. + if (pending === undefined || server === pending) { + server = undefined; + serverLan = undefined; + } + if (error instanceof TowerNotBuiltError) return notify(error.message, "warning"); + notify(`Gentle Tower could not start: ${error instanceof Error ? error.message : String(error)}`, "error"); + } + }; + pi.registerCommand("gentle:tower", { description: "Open the Gentle Tower: every Gentle Shell session as a floor, in your browser", + handler: async (args, c) => { + // One flag only: --lan turns on the same-network mode. + await reportTower((args ?? "").trim() === "--lan", (text, level) => c.ui.notify(text, level)); + }, + }); + pi.registerCommand("gentle:tower-mobile", { + description: "Open the Gentle Tower for your phone: the same view served on your network, with a URL to open from the phone", handler: async (_args, c) => { - // Same startup as `gentle-shell tower`: hub, web app, token, presence, new floors. - server ??= openTowerServer(env, { webDir }); - try { - const s = await server; - c.ui.notify(`Gentle Tower: ${s.url}`, "info"); - openUrl(s.url); - } catch (error) { - server = undefined; - if (error instanceof TowerNotBuiltError) return c.ui.notify(error.message, "warning"); - c.ui.notify(`Gentle Tower could not start: ${error instanceof Error ? error.message : String(error)}`, "error"); - } + await reportTower(true, (text, level) => c.ui.notify(text, level)); }, }); return { - close: async () => { const s = server; server = undefined; if (s) await (await s).close(); }, + close: async () => { const s = server; server = undefined; serverLan = undefined; if (s) await (await s).close(); }, }; } diff --git a/lib/gentle-shell-launcher.ts b/lib/gentle-shell-launcher.ts index a73081335..8db42f5e6 100644 --- a/lib/gentle-shell-launcher.ts +++ b/lib/gentle-shell-launcher.ts @@ -185,16 +185,19 @@ export interface TowerArgs { port?: number; /** Print one JSON line (`gentle-shell.tower/v1`) instead of the text lines. */ json?: true; + /** Bind every network interface and serve one URL per LAN address (opt-in). */ + lan?: true; error?: string; } -// `gentle-shell tower [--no-open] [--port ] [--json]`: the server always -// binds 127.0.0.1; --port only fixes which local port; --json is for programs -// (the desktop app) that read the URL instead of a person. +// `gentle-shell tower [--no-open] [--port ] [--json] [--lan]`: the server +// binds 127.0.0.1 unless --lan; --port only fixes which local port; --json is +// for programs (the desktop app) that read the URL instead of a person. export function parseTowerArgs(args: string[]): TowerArgs { let open = true; let port: number | undefined; let json = false; + let lan = false; for (let i = 0; i < args.length; i += 1) { const arg = args[i]; if (arg === "--no-open") { @@ -205,6 +208,10 @@ export function parseTowerArgs(args: string[]): TowerArgs { json = true; continue; } + if (arg === "--lan") { + lan = true; + continue; + } if (arg === "--port" || arg.startsWith("--port=")) { const value = arg === "--port" ? args[(i += 1)] : arg.slice("--port=".length); if (value === undefined) return { open, error: "--port needs a whole number from 1 to 65535" }; @@ -215,7 +222,7 @@ export function parseTowerArgs(args: string[]): TowerArgs { } return { open, error: `unknown tower argument "${arg}"` }; } - return { open, ...(port === undefined ? {} : { port }), ...(json ? { json: true as const } : {}) }; + return { open, ...(port === undefined ? {} : { port }), ...(json ? { json: true as const } : {}), ...(lan ? { lan: true as const } : {}) }; } // --- home resolution ------------------------------------------------------- @@ -1380,7 +1387,7 @@ export function helpText(): string { " gentle-shell memory migrate --confirm-quiescent", " gentle-shell self-uninstall [--dry-run] [--yes] [--include-shared]", " gentle-shell desktop [--yes] [--no-open] | --status | --uninstall", - " gentle-shell tower [--no-open] [--port ] [--json]", + " gentle-shell tower [--no-open] [--port ] [--json] [--lan]", "", "Opens pi with the Gentle Shell package loaded, without touching your", "vanilla pi installation.", @@ -1431,8 +1438,11 @@ export function helpText(): string { " question); --status and --uninstall; 'gentle-shell desktop --help'.", " tower Open the Gentle Tower outside any session: every open Gentle Shell session", " as a floor, in your browser. Prints the local URL and serves until Ctrl+C.", - " --no-open only prints the URL; --port fixes the port (127.0.0.1 only);", - " --json prints one JSON line with the URL instead, for programs.", + " --no-open only prints the URL; --port fixes the port (127.0.0.1 only,", + " unless --lan); --json prints one JSON line with the URL instead, for programs.", + " --lan also binds every network interface, to open the view from a", + " phone on the same network: it prints one URL per address, a QR code and a warning;", + " --port then fixes the port on every interface.", "", "Managing packages:", " gentle-shell install npm: Run pi's own 'install' against the resolved home.", diff --git a/lib/tower-open.ts b/lib/tower-open.ts index 6b2bb7837..80af22ec1 100644 --- a/lib/tower-open.ts +++ b/lib/tower-open.ts @@ -5,11 +5,13 @@ import { randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; +import { type NetworkInterfaceInfo } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { towerHubDir } from "./tower-hub.ts"; import { launchInTerminal } from "./tower-launch.ts"; import { defaultPresenceDirs } from "./tower-presence.ts"; +import { encodeQr, renderQrTerminal } from "./tower-qr.ts"; import { startTowerServer, type TowerServer } from "./tower-server.ts"; // lib/ and its generated runtime/ copy both sit one level under the package root. @@ -31,8 +33,15 @@ export interface OpenTowerOptions { port?: number; /** Peer presence registries (defaults to the user's). */ presenceDirs?: readonly string[]; + /** Opt-in LAN mode: bind every IPv4 interface and serve one URL per LAN address. */ + lan?: boolean; + /** Network interfaces to enumerate the LAN addresses from (defaults to the OS's). */ + interfaces?: NodeJS.Dict; } +/** The warning every LAN-mode report prints, exactly. */ +export const TOWER_LAN_WARNING = "LAN mode: anyone on this network who opens the URL can read and drive your sessions; traffic is not encrypted. Use it only on a trusted home network."; + export function openTowerServer(env: NodeJS.ProcessEnv, options: OpenTowerOptions = {}): Promise { const webDir = options.webDir ?? TOWER_WEB_DIR; if (!existsSync(join(webDir, "index.html"))) return Promise.reject(new TowerNotBuiltError(webDir)); @@ -43,6 +52,8 @@ export function openTowerServer(env: NodeJS.ProcessEnv, options: OpenTowerOption engramUrl: env.ENGRAM_URL || "http://127.0.0.1:7437", presenceDirs: options.presenceDirs ?? defaultPresenceDirs(), ...(options.port === undefined ? {} : { port: options.port }), + ...(options.lan ? { lan: true } : {}), + ...(options.interfaces === undefined ? {} : { interfaces: options.interfaces }), onNewFloor: (cwd, prompt) => launchInTerminal({ cwd, node: process.execPath, launcher: LAUNCHER, ...(prompt ? { prompt } : {}) }), }); } @@ -94,9 +105,19 @@ export async function runTower(options: RunTowerOptions): Promise { return 1; } try { - options.stdout(options.json - ? `${JSON.stringify({ schema: TOWER_JSON_SCHEMA, url: server.url, host: server.host, port: server.port })}\n` - : `Gentle Tower: ${server.url}\nPress Ctrl+C to stop.\n`); + if (options.json) { + // One line, no QR art; LAN mode adds its own fields at the end. + options.stdout(`${JSON.stringify({ schema: TOWER_JSON_SCHEMA, url: server.url, host: server.host, port: server.port, + ...(server.lan ? { lan: server.lan, urls: server.urls, warning: TOWER_LAN_WARNING } : {}) })}\n`); + } else if (server.lan) { + const lines = [`Gentle Tower: ${server.url}`, ...server.urls.slice(1).map((u) => ` ${u}`)]; + // The QR carries the first LAN address: the phone's way in. + if (server.urls.length > 1) for (const line of renderQrTerminal(encodeQr(server.urls[1]))) lines.push(` ${line}`); + lines.push(TOWER_LAN_WARNING, "Press Ctrl+C to stop."); + options.stdout(`${lines.join("\n")}\n`); + } else { + options.stdout(`Gentle Tower: ${server.url}\nPress Ctrl+C to stop.\n`); + } if (options.open) (options.openUrl ?? openInBrowser)(server.url); await (options.untilStopped ?? untilSignal)(server); } finally { diff --git a/lib/tower-qr.ts b/lib/tower-qr.ts new file mode 100644 index 000000000..50795c68b --- /dev/null +++ b/lib/tower-qr.ts @@ -0,0 +1,1089 @@ +// Gentle Tower: QR codes for terminal URLs, so a phone on the same network can +// open the tower without typing a token. Self-contained on purpose: the launcher +// runtime module inlines it without import rewrites. + +// The encoder below is vendored from Project Nayuki's "QR Code generator library +// (TypeScript)" (MIT License), https://www.nayuki.io/page/qr-code-generator-library , +// fetched from +// https://raw.githubusercontent.com/nayuki/QR-Code-generator/master/typescript-javascript/qrcodegen.ts +// on 2026-11-24. The algorithm is unmodified. Only mechanical, behavior-preserving +// syntax adaptations were applied, required because this repository runs lib/ +// sources through node --experimental-strip-types (mode "strip"), which rejects +// namespaces and constructor parameter properties: +// - the `namespace qrcodegen`, `namespace qrcodegen.QrCode` and +// `namespace qrcodegen.QrSegment` wrappers were removed: QrCode, QrSegment, Ecc +// and Mode are exported directly, the `type bit/byte/int` aliases moved to module +// scope, and internal `qrcodegen.` qualifiers were dropped; +// - `QrCode.Ecc` became `Ecc` and `QrSegment.Mode` became `Mode` everywhere; +// - constructor parameter properties were expanded into declared fields plus +// constructor assignments (QrCode.version, QrCode.errorCorrectionLevel, +// QrSegment.mode, QrSegment.numChars, QrSegment.bitData, Ecc.ordinal, +// Ecc.formatBits, Mode.modeBits, Mode.numBitsCharCount); +// - three side-effecting callbacks were rewritten from single-expression bodies +// returning the assignment value into block bodies returning nothing, one +// unused callback parameter was dropped (`map(_ => 0)` became `map(() => 0)`), +// and the upstream `==`/`!=` comparisons were tightened to `===`/`!==` with one +// single-assigned `let` becoming `const`, to satisfy the repository's lint +// blockers; every one of these is semantics-preserving for the number and +// boolean comparisons involved. The upstream naming is kept verbatim. +// Everything between the "Vendored" markers below stays reviewable against the +// upstream file (only the adaptations listed above differ). +// +// The original MIT license notice, kept as required: +// +// Copyright (c) Project Nayuki. (MIT License) +// https://www.nayuki.io/page/qr-code-generator-library +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// - The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// - The Software is provided "as is", without warranty of any kind, express or +// implied, including but not limited to the warranties of merchantability, +// fitness for a particular purpose and noninfringement. In no event shall the +// authors or copyright holders be liable for any claim, damages or other +// liability, whether in an action of contract, tort or otherwise, arising from, +// out of or in connection with the Software or the use or other dealings in the +// Software. + +"use strict"; + +// ---- Vendored from Nayuki qrcodegen.ts (mechanically adapted; see header) ---- + +type bit = number; +type byte = number; +type int = number; + + +/*---- QR Code symbol class ----*/ + +/* + * A QR Code symbol, which is a type of two-dimensional barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * Instances of this class represent an immutable square grid of dark and light cells. + * The class provides static factory functions to create a QR Code from text or binary data. + * The class covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary(). + * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments(). + * - Low level: Custom-make the array of data codeword bytes (including + * segment headers and final padding, excluding error correction codewords), + * supply the appropriate version number, and call the QrCode() constructor. + * (Note that all ways require supplying the desired error correction level.) + */ +export class QrCode { + + /*-- Static factory functions (high level) --*/ + + // Returns a QR Code representing the given Unicode text string at the given error correction level. + // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer + // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible + // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than + // the ecl argument if it can be done without increasing the version. + public static encodeText(text: string, ecl: Ecc): QrCode { + const segs: Array = QrSegment.makeSegments(text); + return QrCode.encodeSegments(segs, ecl); + } + + + // Returns a QR Code representing the given binary data at the given error correction level. + // This function always encodes using the binary segment mode, not any text mode. The maximum number of + // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. + // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. + public static encodeBinary(data: Readonly>, ecl: Ecc): QrCode { + const seg: QrSegment = QrSegment.makeBytes(data); + return QrCode.encodeSegments([seg], ecl); + } + + + /*-- Static factory functions (mid level) --*/ + + // Returns a QR Code representing the given segments with the given encoding parameters. + // The smallest possible QR Code version within the given range is automatically + // chosen for the output. Iff boostEcl is true, then the ECC level of the result + // may be higher than the ecl argument if it can be done without increasing the + // version. The mask number is either between 0 to 7 (inclusive) to force that + // mask, or -1 to automatically choose an appropriate mask (which may be slow). + // This function allows the user to create a custom sequence of segments that switches + // between modes (such as alphanumeric and byte) to encode text in less space. + // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). + public static encodeSegments(segs: Readonly>, ecl: Ecc, + minVersion: int = 1, maxVersion: int = 40, + mask: int = -1, boostEcl: boolean = true): QrCode { + + if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) + || mask < -1 || mask > 7) + throw new RangeError("Invalid value"); + + // Find the minimal version number to use + let version: int; + let dataUsedBits: int; + for (version = minVersion; ; version++) { + const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available + const usedBits: number = QrSegment.getTotalBits(segs, version); + if (usedBits <= dataCapacityBits) { + dataUsedBits = usedBits; + break; // This version number is found to be suitable + } + if (version >= maxVersion) // All versions in the range could not fit the given data + throw new RangeError("Data too long"); + } + + // Increase the error correction level while the data still fits in the current version number + for (const newEcl of [Ecc.MEDIUM, Ecc.QUARTILE, Ecc.HIGH]) { // From low to high + if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) + ecl = newEcl; + } + + // Concatenate all segments to create the data bit string + let bb: Array = [] + for (const seg of segs) { + appendBits(seg.mode.modeBits, 4, bb); + appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb); + for (const b of seg.getData()) + bb.push(b); + } + assert(bb.length === dataUsedBits); + + // Add terminator and pad up to a byte if applicable + const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; + assert(bb.length <= dataCapacityBits); + appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); + appendBits(0, (8 - bb.length % 8) % 8, bb); + assert(bb.length % 8 === 0); + + // Pad with alternating bytes until data capacity is reached + for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + appendBits(padByte, 8, bb); + + // Pack bits into bytes in big endian + let dataCodewords: Array = []; + while (dataCodewords.length * 8 < bb.length) + dataCodewords.push(0); + bb.forEach((b: bit, i: int): void => { + dataCodewords[i >>> 3] |= b << (7 - (i & 7)); + }); + + // Create the QR Code object + return new QrCode(version, ecl, dataCodewords, mask); + } + + + /*-- Fields --*/ + + // The width and height of this QR Code, measured in modules, between + // 21 and 177 (inclusive). This is equal to version * 4 + 17. + public readonly size: int; + + // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). + // Even if a QR Code is created with automatic masking requested (mask = -1), + // the resulting object still has a mask value between 0 and 7. + public readonly mask: int; + + // The modules of this QR Code (false = light, true = dark). + // Immutable after constructor finishes. Accessed through getModule(). + private readonly modules : Array> = []; + + // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. + private readonly isFunction: Array> = []; + + + /*-- Constructor (low level) and fields --*/ + + // Creates a new QR Code with the given version number, + // error correction level, data codeword bytes, and mask number. + // This is a low-level API that most users should not use directly. + // A mid-level API is the encodeSegments() function. + public readonly version: int; + public readonly errorCorrectionLevel: Ecc; + + public constructor( + // The version number of this QR Code, which is between 1 and 40 (inclusive). + // This determines the size of this barcode. + version: int, + + // The error correction level used in this QR Code. + errorCorrectionLevel: Ecc, + + dataCodewords: Readonly>, + + msk: int) { + this.version = version; + this.errorCorrectionLevel = errorCorrectionLevel; + + // Check scalar arguments + if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) + throw new RangeError("Version value out of range"); + if (msk < -1 || msk > 7) + throw new RangeError("Mask value out of range"); + this.size = version * 4 + 17; + + // Initialize both grids to be size*size arrays of Boolean false + let row: Array = []; + for (let i = 0; i < this.size; i++) + row.push(false); + for (let i = 0; i < this.size; i++) { + this.modules .push(row.slice()); // Initially all light + this.isFunction.push(row.slice()); + } + + // Compute ECC, draw modules + this.drawFunctionPatterns(); + const allCodewords: Array = this.addEccAndInterleave(dataCodewords); + this.drawCodewords(allCodewords); + + // Do masking + if (msk === -1) { // Automatically choose best mask + let minPenalty: int = 1000000000; + for (let i = 0; i < 8; i++) { + this.applyMask(i); + this.drawFormatBits(i); + const penalty: int = this.getPenaltyScore(); + if (penalty < minPenalty) { + msk = i; + minPenalty = penalty; + } + this.applyMask(i); // Undoes the mask due to XOR + } + } + assert(0 <= msk && msk <= 7); + this.mask = msk; + this.applyMask(msk); // Apply the final choice of mask + this.drawFormatBits(msk); // Overwrite old format bits + + this.isFunction = []; + } + + + /*-- Accessor methods --*/ + + // Returns the color of the module (pixel) at the given coordinates, which is false + // for light or true for dark. The top left corner has the coordinates (x=0, y=0). + // If the given coordinates are out of bounds, then false (light) is returned. + public getModule(x: int, y: int): boolean { + return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; + } + + + /*-- Private helper methods for constructor: Drawing function modules --*/ + + // Reads this object's version field, and draws and marks all function modules. + private drawFunctionPatterns(): void { + // Draw horizontal and vertical timing patterns + for (let i = 0; i < this.size; i++) { + this.setFunctionModule(6, i, i % 2 === 0); + this.setFunctionModule(i, 6, i % 2 === 0); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + this.drawFinderPattern(3, 3); + this.drawFinderPattern(this.size - 4, 3); + this.drawFinderPattern(3, this.size - 4); + + // Draw numerous alignment patterns + const alignPatPos: Array = this.getAlignmentPatternPositions(); + alignPatPos.forEach((x: int, i: int): void => { + alignPatPos.forEach((y: int, j: int): void => { + // Don't draw on the three finder corners + if (!(i === 0 && j === 0 || i === 0 && j === alignPatPos.length - 1 || i === alignPatPos.length - 1 && j === 0)) + this.drawAlignmentPattern(x, y); + }); + }); + + // Draw configuration data + this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor + this.drawVersion(); + } + + + // Draws two copies of the format bits (with its own error correction code) + // based on the given mask and this object's error correction level field. + private drawFormatBits(mask: int): void { + // Calculate error correction code and pack bits + const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3 + let rem: int = data; + for (let i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >>> 9) * 0x537); + const bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >>> 15 === 0); + + // Draw first copy + for (let i = 0; i <= 5; i++) + this.setFunctionModule(8, i, getBit(bits, i)); + this.setFunctionModule(8, 7, getBit(bits, 6)); + this.setFunctionModule(8, 8, getBit(bits, 7)); + this.setFunctionModule(7, 8, getBit(bits, 8)); + for (let i = 9; i < 15; i++) + this.setFunctionModule(14 - i, 8, getBit(bits, i)); + + // Draw second copy + for (let i = 0; i < 8; i++) + this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); + for (let i = 8; i < 15; i++) + this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); + this.setFunctionModule(8, this.size - 8, true); // Always dark + } + + + // Draws two copies of the version bits (with its own error correction code), + // based on this object's version field, iff 7 <= version <= 40. + private drawVersion(): void { + if (this.version < 7) + return; + + // Calculate error correction code and pack bits + let rem: int = this.version; // version is uint6, in the range [7, 40] + for (let i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); + const bits: int = this.version << 12 | rem; // uint18 + assert(bits >>> 18 === 0); + + // Draw two copies + for (let i = 0; i < 18; i++) { + const color: boolean = getBit(bits, i); + const a: int = this.size - 11 + i % 3; + const b: int = Math.floor(i / 3); + this.setFunctionModule(a, b, color); + this.setFunctionModule(b, a, color); + } + } + + + // Draws a 9*9 finder pattern including the border separator, + // with the center module at (x, y). Modules can be out of bounds. + private drawFinderPattern(x: int, y: int): void { + for (let dy = -4; dy <= 4; dy++) { + for (let dx = -4; dx <= 4; dx++) { + const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm + const xx: int = x + dx; + const yy: int = y + dy; + if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) + this.setFunctionModule(xx, yy, dist !== 2 && dist !== 4); + } + } + } + + + // Draws a 5*5 alignment pattern, with the center module + // at (x, y). All modules must be in bounds. + private drawAlignmentPattern(x: int, y: int): void { + for (let dy = -2; dy <= 2; dy++) { + for (let dx = -2; dx <= 2; dx++) + this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); + } + } + + + // Sets the color of a module and marks it as a function module. + // Only used by the constructor. Coordinates must be in bounds. + private setFunctionModule(x: int, y: int, isDark: boolean): void { + this.modules[y][x] = isDark; + this.isFunction[y][x] = true; + } + + + /*-- Private helper methods for constructor: Codewords and masking --*/ + + // Returns a new byte string representing the given data with the appropriate error correction + // codewords appended to it, based on this object's version and error correction level. + private addEccAndInterleave(data: Readonly>): Array { + const ver: int = this.version; + const ecl: Ecc = this.errorCorrectionLevel; + if (data.length !== QrCode.getNumDataCodewords(ver, ecl)) + throw new RangeError("Invalid argument"); + + // Calculate parameter numbers + const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver]; + const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8); + const numShortBlocks: int = numBlocks - rawCodewords % numBlocks; + const shortBlockLen: int = Math.floor(rawCodewords / numBlocks); + + // Split data into blocks and append ECC to each block + let blocks: Array> = []; + const rsDiv: Array = QrCode.reedSolomonComputeDivisor(blockEccLen); + for (let i = 0, k = 0; i < numBlocks; i++) { + let dat: Array = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); + k += dat.length; + const ecc: Array = QrCode.reedSolomonComputeRemainder(dat, rsDiv); + if (i < numShortBlocks) + dat.push(0); + blocks.push(dat.concat(ecc)); + } + + // Interleave (not concatenate) the bytes from every block into a single sequence + let result: Array = []; + for (let i = 0; i < blocks[0].length; i++) { + blocks.forEach((block: Array, j: int): void => { + // Skip the padding byte in short blocks + if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) + result.push(block[i]); + }); + } + assert(result.length === rawCodewords); + return result; + } + + + // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire + // data area of this QR Code. Function modules need to be marked off before this is called. + private drawCodewords(data: Readonly>): void { + if (data.length !== Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) + throw new RangeError("Invalid argument"); + let i: int = 0; // Bit index into the data + // Do the funny zigzag scan + for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right === 6) + right = 5; + for (let vert = 0; vert < this.size; vert++) { // Vertical counter + for (let j = 0; j < 2; j++) { + const x: int = right - j; // Actual x coordinate + const upward: boolean = ((right + 1) & 2) === 0; + const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate + if (!this.isFunction[y][x] && i < data.length * 8) { + this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i === data.length * 8); + } + + + // XORs the codeword modules in this QR Code with the given mask pattern. + // The function modules must be marked and the codeword bits must be drawn + // before masking. Due to the arithmetic of XOR, calling applyMask() with the + // same mask value a second time will undo the mask. A final well-formed + // QR Code needs exactly one (not zero, two, etc.) mask applied. + private applyMask(mask: int): void { + if (mask < 0 || mask > 7) + throw new RangeError("Mask value out of range"); + for (let y = 0; y < this.size; y++) { + for (let x = 0; x < this.size; x++) { + let invert: boolean; + switch (mask) { + case 0: invert = (x + y) % 2 === 0; break; + case 1: invert = y % 2 === 0; break; + case 2: invert = x % 3 === 0; break; + case 3: invert = (x + y) % 3 === 0; break; + case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; break; + case 5: invert = x * y % 2 + x * y % 3 === 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 === 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 === 0; break; + default: throw new Error("Unreachable"); + } + if (!this.isFunction[y][x] && invert) + this.modules[y][x] = !this.modules[y][x]; + } + } + } + + + // Calculates and returns the penalty score based on state of this QR Code's current modules. + // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. + private getPenaltyScore(): int { + let result: int = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (let y = 0; y < this.size; y++) { + let runColor: boolean = false; + let runX: int = 0; + let runHistory: Array = [0,0,0,0,0,0,0]; + for (let x = 0; x < this.size; x++) { + if (this.modules[y][x] === runColor) { + runX++; + if (runX === 5) + result += QrCode.PENALTY_N1; + else if (runX > 5) + result++; + } else { + this.finderPenaltyAddHistory(runX, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; + runColor = this.modules[y][x]; + runX = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (let x = 0; x < this.size; x++) { + let runColor: boolean = false; + let runY: int = 0; + let runHistory: Array = [0,0,0,0,0,0,0]; + for (let y = 0; y < this.size; y++) { + if (this.modules[y][x] === runColor) { + runY++; + if (runY === 5) + result += QrCode.PENALTY_N1; + else if (runY > 5) + result++; + } else { + this.finderPenaltyAddHistory(runY, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; + runColor = this.modules[y][x]; + runY = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (let y = 0; y < this.size - 1; y++) { + for (let x = 0; x < this.size - 1; x++) { + const color: boolean = this.modules[y][x]; + if ( color === this.modules[y][x + 1] && + color === this.modules[y + 1][x] && + color === this.modules[y + 1][x + 1]) + result += QrCode.PENALTY_N2; + } + } + + // Balance of dark and light modules + let dark: int = 0; + for (const row of this.modules) + dark = row.reduce((sum: int, color: boolean): int => sum + (color ? 1 : 0), dark); + const total: int = this.size * this.size; // Note that size is odd, so dark/total !== 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; + assert(0 <= k && k <= 9); + result += k * QrCode.PENALTY_N4; + assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; + } + + + /*-- Private helper functions --*/ + + // Returns an ascending list of positions of alignment patterns for this version number. + // Each position is in the range [0,177), and are used on both the x and y axes. + // This could be implemented as lookup table of 40 variable-length lists of integers. + private getAlignmentPatternPositions(): Array { + if (this.version === 1) + return []; + else { + const numAlign: int = Math.floor(this.version / 7) + 2; + const step: int = Math.floor((this.version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4)) * 2; + const result: Array = [6]; + for (let pos = this.size - 7; result.length < numAlign; pos -= step) + result.splice(1, 0, pos); + return result; + } + } + + + // Returns the number of data bits that can be stored in a QR Code of the given version number, after + // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. + // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. + private static getNumRawDataModules(ver: int): int { + if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) + throw new RangeError("Version number out of range"); + let result: int = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + const numAlign: int = Math.floor(ver / 7) + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; + } + + + // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any + // QR Code of the given version number and error correction level, with remainder bits discarded. + // This stateless pure function could be implemented as a (40*4)-cell lookup table. + private static getNumDataCodewords(ver: int, ecl: Ecc): int { + return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - + QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] * + QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + } + + + // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be + // implemented as a lookup table over all possible parameter values, instead of as an algorithm. + private static reedSolomonComputeDivisor(degree: int): Array { + if (degree < 1 || degree > 255) + throw new RangeError("Degree out of range"); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. + let result: Array = []; + for (let i = 0; i < degree - 1; i++) + result.push(0); + result.push(1); // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // and drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + let root: byte = 1; + for (let i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (let j = 0; j < result.length; j++) { + result[j] = QrCode.reedSolomonMultiply(result[j], root); + if (j + 1 < result.length) + result[j] ^= result[j + 1]; + } + root = QrCode.reedSolomonMultiply(root, 0x02); + } + return result; + } + + + // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. + private static reedSolomonComputeRemainder(data: Readonly>, divisor: Readonly>): Array { + let result: Array = divisor.map((): byte => 0); + for (const b of data) { // Polynomial division + const factor: byte = b ^ (result.shift() as byte); + result.push(0); + divisor.forEach((coef: byte, i: int): void => { + result[i] ^= QrCode.reedSolomonMultiply(coef, factor); + }); + } + return result; + } + + + // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result + // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. + private static reedSolomonMultiply(x: byte, y: byte): byte { + if (x >>> 8 !== 0 || y >>> 8 !== 0) + throw new RangeError("Byte out of range"); + // Russian peasant multiplication + let z: int = 0; + for (let i = 7; i >= 0; i--) { + z = (z << 1) ^ ((z >>> 7) * 0x11D); + z ^= ((y >>> i) & 1) * x; + } + assert(z >>> 8 === 0); + return z as byte; + } + + + // Can only be called immediately after a light run is added, and + // returns either 0, 1, or 2. A helper function for getPenaltyScore(). + private finderPenaltyCountPatterns(runHistory: Readonly>): int { + const n: int = runHistory[1]; + assert(n <= this.size * 3); + const core: boolean = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n; + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); + } + + + // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). + private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array): int { + if (currentRunColor) { // Terminate dark run + this.finderPenaltyAddHistory(currentRunLength, runHistory); + currentRunLength = 0; + } + currentRunLength += this.size; // Add light border to final run + this.finderPenaltyAddHistory(currentRunLength, runHistory); + return this.finderPenaltyCountPatterns(runHistory); + } + + + // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). + private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array): void { + if (runHistory[0] === 0) + currentRunLength += this.size; // Add light border to initial run + runHistory.pop(); + runHistory.unshift(currentRunLength); + } + + + /*-- Constants and tables --*/ + + // The minimum version number supported in the QR Code Model 2 standard. + public static readonly MIN_VERSION: int = 1; + // The maximum version number supported in the QR Code Model 2 standard. + public static readonly MAX_VERSION: int = 40; + + // For use in getPenaltyScore(), when evaluating which mask is best. + private static readonly PENALTY_N1: int = 3; + private static readonly PENALTY_N2: int = 3; + private static readonly PENALTY_N3: int = 40; + private static readonly PENALTY_N4: int = 10; + + private static readonly ECC_CODEWORDS_PER_BLOCK: Array> = [ + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low + [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium + [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile + [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High + ]; + + private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array> = [ + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low + [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium + [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile + [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High + ]; + +} + + +// Appends the given number of low-order bits of the given value +// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. +function appendBits(val: int, len: int, bb: Array): void { + if (len < 0 || len > 31 || val >>> len !== 0) + throw new RangeError("Value out of range"); + for (let i = len - 1; i >= 0; i--) // Append bit by bit + bb.push((val >>> i) & 1); +} + + +// Returns true iff the i'th bit of x is set to 1. +function getBit(x: int, i: int): boolean { + return ((x >>> i) & 1) !== 0; +} + + +// Throws an exception if the given condition is false. +function assert(cond: boolean): void { + if (!cond) + throw new Error("Assertion error"); +} + + + +/*---- Data segment class ----*/ + +/* + * A segment of character/binary/control data in a QR Code symbol. + * Instances of this class are immutable. + * The mid-level way to create a segment is to take the payload data + * and call a static factory function such as QrSegment.makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and call the QrSegment() constructor with appropriate values. + * This segment class imposes no length restrictions, but QR Codes have restrictions. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + */ +export class QrSegment { + + /*-- Static factory functions (mid level) --*/ + + // Returns a segment representing the given binary data encoded in + // byte mode. All input byte arrays are acceptable. Any text string + // can be converted to UTF-8 bytes and encoded as a byte mode segment. + public static makeBytes(data: Readonly>): QrSegment { + let bb: Array = [] + for (const b of data) + appendBits(b, 8, bb); + return new QrSegment(Mode.BYTE, data.length, bb); + } + + + // Returns a segment representing the given string of decimal digits encoded in numeric mode. + public static makeNumeric(digits: string): QrSegment { + if (!QrSegment.isNumeric(digits)) + throw new RangeError("String contains non-numeric characters"); + let bb: Array = [] + for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration + const n: int = Math.min(digits.length - i, 3); + appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); + i += n; + } + return new QrSegment(Mode.NUMERIC, digits.length, bb); + } + + + // Returns a segment representing the given text string encoded in alphanumeric mode. + // The characters allowed are: 0 to 9, A to Z (uppercase only), space, + // dollar, percent, asterisk, plus, hyphen, period, slash, colon. + public static makeAlphanumeric(text: string): QrSegment { + if (!QrSegment.isAlphanumeric(text)) + throw new RangeError("String contains unencodable characters in alphanumeric mode"); + let bb: Array = [] + let i: int; + for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2 + let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; + temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); + appendBits(temp, 11, bb); + } + if (i < text.length) // 1 character remaining + appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); + return new QrSegment(Mode.ALPHANUMERIC, text.length, bb); + } + + + // Returns a new mutable list of zero or more segments to represent the given Unicode text string. + // The result may use various segment modes and switch modes to optimize the length of the bit stream. + public static makeSegments(text: string): Array { + // Select the most efficient segment encoding automatically + if (text === "") + return []; + else if (QrSegment.isNumeric(text)) + return [QrSegment.makeNumeric(text)]; + else if (QrSegment.isAlphanumeric(text)) + return [QrSegment.makeAlphanumeric(text)]; + else + return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))]; + } + + + // Returns a segment representing an Extended Channel Interpretation + // (ECI) designator with the given assignment value. + public static makeEci(assignVal: int): QrSegment { + let bb: Array = [] + if (assignVal < 0) + throw new RangeError("ECI assignment value out of range"); + else if (assignVal < (1 << 7)) + appendBits(assignVal, 8, bb); + else if (assignVal < (1 << 14)) { + appendBits(0b10, 2, bb); + appendBits(assignVal, 14, bb); + } else if (assignVal < 1000000) { + appendBits(0b110, 3, bb); + appendBits(assignVal, 21, bb); + } else + throw new RangeError("ECI assignment value out of range"); + return new QrSegment(Mode.ECI, 0, bb); + } + + + // Tests whether the given string can be encoded as a segment in numeric mode. + // A string is encodable iff each character is in the range 0 to 9. + public static isNumeric(text: string): boolean { + return QrSegment.NUMERIC_REGEX.test(text); + } + + + // Tests whether the given string can be encoded as a segment in alphanumeric mode. + // A string is encodable iff each character is in the following set: 0 to 9, A to Z + // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + public static isAlphanumeric(text: string): boolean { + return QrSegment.ALPHANUMERIC_REGEX.test(text); + } + + + /*-- Constructor (low level) and fields --*/ + + // Creates a new QR Code segment with the given attributes and data. + // The character count (numChars) must agree with the mode and the bit buffer length, + // but the constraint isn't checked. The given bit buffer is cloned and stored. + public readonly mode: Mode; + public readonly numChars: int; + private readonly bitData: Array; + + public constructor( + // The mode indicator of this segment. + mode: Mode, + + // The length of this segment's unencoded data. Measured in characters for + // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + // Always zero or positive. Not the same as the data's bit length. + numChars: int, + + // The data bits of this segment. Accessed through getData(). + bitData: Array) { + this.mode = mode; + this.numChars = numChars; + if (numChars < 0) + throw new RangeError("Invalid argument"); + this.bitData = bitData.slice(); // Make defensive copy + } + + + /*-- Methods --*/ + + // Returns a new copy of the data bits of this segment. + public getData(): Array { + return this.bitData.slice(); // Make defensive copy + } + + + // (Package-private) Calculates and returns the number of bits needed to encode the given segments at + // the given version. The result is infinity if a segment has too many characters to fit its length field. + public static getTotalBits(segs: Readonly>, version: int): number { + let result: number = 0; + for (const seg of segs) { + const ccbits: int = seg.mode.numCharCountBits(version); + if (seg.numChars >= (1 << ccbits)) + return Infinity; // The segment's length doesn't fit the field's bit width + result += 4 + ccbits + seg.bitData.length; + } + return result; + } + + + // Returns a new array of bytes representing the given string encoded in UTF-8. + private static toUtf8ByteArray(str: string): Array { + str = encodeURI(str); + let result: Array = []; + for (let i = 0; i < str.length; i++) { + if (str.charAt(i) !== "%") + result.push(str.charCodeAt(i)); + else { + result.push(parseInt(str.substring(i + 1, i + 3), 16)); + i += 2; + } + } + return result; + } + + + /*-- Constants --*/ + + // Describes precisely all strings that are encodable in numeric mode. + private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/; + + // Describes precisely all strings that are encodable in alphanumeric mode. + private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/; + + // The set of all legal characters in alphanumeric mode, + // where each character value maps to the index in the string. + private static readonly ALPHANUMERIC_CHARSET: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +} + + +/*---- Public helper enumeration ----*/ + +/* + * The error correction level in a QR Code symbol. Immutable. + */ +export class Ecc { + + /*-- Constants --*/ + + public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords + public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords + public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords + public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords + + + /*-- Constructor and fields --*/ + + public readonly ordinal: int; + // (Package-private) In the range 0 to 3 (unsigned 2-bit integer). + public readonly formatBits: int; + + private constructor( + // In the range 0 to 3 (unsigned 2-bit integer). + ordinal: int, + formatBits: int) { + this.ordinal = ordinal; + this.formatBits = formatBits; + } + +} + + +/*---- Public helper enumeration ----*/ + +/* + * Describes how a segment's data bits are interpreted. Immutable. + */ +export class Mode { + + /*-- Constants --*/ + + public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]); + public static readonly ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]); + public static readonly BYTE = new Mode(0x4, [ 8, 16, 16]); + public static readonly KANJI = new Mode(0x8, [ 8, 10, 12]); + public static readonly ECI = new Mode(0x7, [ 0, 0, 0]); + + + /*-- Constructor and fields --*/ + + // The mode indicator bits, which is a uint4 value (range 0 to 15). + public readonly modeBits: int; + // Number of character count bits for three different version ranges. + private readonly numBitsCharCount: [int,int,int]; + + private constructor( + modeBits: int, + numBitsCharCount: [int,int,int]) { + this.modeBits = modeBits; + this.numBitsCharCount = numBitsCharCount; + } + + + /*-- Method --*/ + + // (Package-private) Returns the bit width of the character count field for a segment in + // this mode in a QR Code at the given version number. The result is in the range [0, 16]. + public numCharCountBits(ver: int): int { + return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; + } + +} + +// ---- End of vendored code ---- + + +/*---- Gentle Tower terminal QR API ----*/ + +/** A rendered QR Code: `modules` is the row-major bitmap, dark = true, `size * size` entries. */ +export interface QrMatrix { + size: number; + version: number; + ecl: "L" | "M" | "Q" | "H"; + mask: number; + modules: boolean[]; +} + +const ECL_NAMES: Record = { 0: "L", 1: "M", 2: "Q", 3: "H" }; + +/** + * Encodes text at error correction level M, without boosting the level, so the + * printed matrix is stable for a given text. Throws RangeError when no QR Code + * can carry the text (the same error the vendored encoder raises). + */ +export function encodeQr(text: string): QrMatrix { + const qr = QrCode.encodeSegments(QrSegment.makeSegments(text), Ecc.MEDIUM, 1, 40, -1, false); + const modules: boolean[] = []; + for (let y = 0; y < qr.size; y++) + for (let x = 0; x < qr.size; x++) + modules.push(qr.getModule(x, y)); + return { size: qr.size, version: qr.version, ecl: ECL_NAMES[qr.errorCorrectionLevel.ordinal], mask: qr.mask, modules }; +} + +export interface QrTerminalOptions { + /** Quiet zone width in modules on every side. Default 4, the QR Code Model 2 spec's margin. */ + quiet?: number; +} + +/** + * Renders a matrix as terminal lines of half blocks (" ", "▀", "▄", "█"): two + * module rows per line, one character per module column, quiet zone included. + * Dark-on-light as terminals draw; every line has the same width. + */ +export function renderQrTerminal(qr: QrMatrix, options: QrTerminalOptions = {}): string[] { + const quiet = options.quiet ?? 4; + const width = qr.size + quiet * 2; + const dark = (x: number, y: number): boolean => { + const mx = x - quiet, my = y - quiet; + return mx >= 0 && mx < qr.size && my >= 0 && my < qr.size && qr.modules[my * qr.size + mx]; + }; + const lines: string[] = []; + for (let y = 0; y < width; y += 2) { + let line = ""; + for (let x = 0; x < width; x++) { + const top = dark(x, y), bottom = dark(x, y + 1); + let glyph: string; + if (top && bottom) glyph = "█"; + else if (top) glyph = "▀"; + else if (bottom) glyph = "▄"; + else glyph = " "; + line += glyph; + } + lines.push(line); + } + return lines; +} diff --git a/lib/tower-server.ts b/lib/tower-server.ts index d2e102576..11eca31e8 100644 --- a/lib/tower-server.ts +++ b/lib/tower-server.ts @@ -1,10 +1,13 @@ // Gentle Tower web server: serves the built web app and the hub's floors. // Closed by default: 127.0.0.1 only, a random port, a per-launch token on every -// request, and any Origin other than its own is refused. Read-only for now: -// actions come later and reuse Gentle Shell's own authority. +// request, and any Origin other than its own is refused. The opt-in lan mode +// additionally serves the machine's LAN addresses, accepting only the origins +// of the hosts it launched with. Read-only for now: actions come later and +// reuse Gentle Shell's own authority. import { readFileSync, realpathSync, statSync } from "node:fs"; import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; +import { type NetworkInterfaceInfo, networkInterfaces } from "node:os"; import { basename, dirname, extname, resolve, sep } from "node:path"; import { timingSafeEqual } from "node:crypto"; import { readLiveTowerSnapshots as readTowerSnapshots } from "./tower-hub.ts"; @@ -25,6 +28,10 @@ export interface TowerServerOptions { now?: () => number; /** Opens a new Gentle Shell session (a floor) in a project already in the tower. */ onNewFloor?: (cwd: string, prompt?: string) => Promise; + /** Opt-in LAN mode: bind every IPv4 interface and serve one URL per LAN address. */ + lan?: boolean; + /** Network interfaces to enumerate the LAN addresses from (defaults to the OS's). */ + interfaces?: NodeJS.Dict; } const ARTIFACT_TYPES: Record = { ".md": "text/plain; charset=utf-8", ".markdown": "text/plain; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".mmd": "text/plain; charset=utf-8", ".mermaid": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" }; @@ -32,9 +39,16 @@ const ARTIFACT_MAX_BYTES = 2 * 1024 * 1024; const MEMORY_MAX_BYTES = 512 * 1024; export interface TowerServer { - host: "127.0.0.1"; + /** The bind address: "127.0.0.1", or "0.0.0.0" in lan mode. */ + host: string; port: number; url: string; + /** Whether the server also serves the machine's LAN addresses. */ + lan: boolean; + /** Every launch URL: the loopback one first, then one per LAN address. */ + urls: string[]; + /** The LAN addresses lan mode serves (empty otherwise). */ + lanIps: string[]; close(): Promise; } @@ -55,11 +69,48 @@ function sameToken(given: string | null | undefined, token: string): boolean { return a.length === b.length && timingSafeEqual(a, b); } +function isPrivateIpv4(ip: string): boolean { + const o = ip.split(".").map(Number); + return o.length === 4 && (o[0] === 10 || (o[0] === 192 && o[1] === 168) || (o[0] === 172 && o[1] >= 16 && o[1] <= 31)); +} + +/** Private ranges first, then numeric order, so the first URL is the most likely home LAN address. */ +function compareLanIpv4(a: string, b: string): number { + const rank = (ip: string) => (isPrivateIpv4(ip) ? 0 : 1); + if (rank(a) !== rank(b)) return rank(a) - rank(b); + const as = a.split(".").map(Number), bs = b.split(".").map(Number); + for (let i = 0; i < 4; i += 1) if (as[i] !== bs[i]) return (as[i] ?? 0) - (bs[i] ?? 0); + return a.localeCompare(b); +} + +/** The machine's non-internal IPv4 addresses, link-local 169.254.0.0/16 aside, private ranges first. */ +export function lanIpv4Addresses(interfaces: NodeJS.Dict): string[] { + const ips = new Set(); + for (const nics of Object.values(interfaces)) + for (const nic of nics ?? []) + if (nic.family === "IPv4" && !nic.internal && !nic.address.startsWith("169.254.")) ips.add(nic.address); + return [...ips].sort(compareLanIpv4); +} + +/** The `host` or `host:port` authorities a lan launch answers to, canonical for HTTP: on port 80 both the bare host and the explicit `:80` are approved (WHATWG URL serialization drops the default port); on any other port the authority always carries it. */ +export function lanAllowedHosts(lanIps: readonly string[], port: number): Set { + const hosts = new Set(); + for (const host of ["127.0.0.1", "localhost", ...lanIps]) { + if (port === 80) { hosts.add(host); hosts.add(`${host}:80`); } + else hosts.add(`${host}:${port}`); + } + return hosts; +} + export function startTowerServer(options: TowerServerOptions): Promise { const webRoot = realpathSync(options.webDir); const clients = new Set(); let lastBody = ""; const now = options.now ?? Date.now; + const lan = options.lan === true; + const lanIps = lan ? lanIpv4Addresses(options.interfaces ?? networkInterfaces()) : []; + /** The `host:port` values an Origin may name in lan mode; filled once the port is known. */ + let allowedHosts = new Set(); // Detailed floors (tower extension) win; every other live session joins as a basic floor. const LIVE = new Set(["queued", "running", "waiting"]); /** A snapshot this much older than the heartbeat has stopped updating. */ @@ -166,7 +217,15 @@ export function startTowerServer(options: TowerServerOptions): Promise { if (req.method !== "GET" && req.method !== "POST") return deny(res, 405); const origin = req.headers.origin; - if (origin && origin !== `http://127.0.0.1:${port}`) return deny(res); + if (lan) { + // Every request names the host it wants, even a navigation GET without an + // Origin: it must be one this launch answers to, so a rebinding Host is + // refused before the token or the page is even considered. The Origin, + // when a browser sends one, must name that same host. + const host = req.headers.host ?? ""; + if (!allowedHosts.has(host)) return deny(res); + if (origin && origin !== `http://${host}`) return deny(res); + } else if (origin && origin !== `http://127.0.0.1:${port}`) return deny(res); // A browser always sends Origin on POST; a missing one is not our page. if (req.method === "POST" && !origin) return deny(res); // The token is the first path segment, so every relative request the app @@ -212,14 +271,19 @@ export function startTowerServer(options: TowerServerOptions): Promise { server.once("error", reject); - server.listen(options.port ?? 0, "127.0.0.1", () => { + server.listen(options.port ?? 0, lan ? "0.0.0.0" : "127.0.0.1", () => { const addr = server.address(); port = typeof addr === "object" && addr ? addr.port : 0; + if (lan) allowedHosts = lanAllowedHosts(lanIps, port); + const url = `http://127.0.0.1:${port}/${options.token}/`; lastBody = sessionsBody(); resolveStart({ - host: "127.0.0.1", + host: lan ? "0.0.0.0" : "127.0.0.1", port, - url: `http://127.0.0.1:${port}/${options.token}/`, + url, + lan, + urls: [url, ...lanIps.map((ip) => `http://${ip}:${port}/${options.token}/`)], + lanIps, close: () => new Promise((done) => { clearInterval(poll); for (const c of clients) c.end(); diff --git a/odd/tasks/tower-lan-mobile.md b/odd/tasks/tower-lan-mobile.md new file mode 100644 index 000000000..27fe5f9b3 --- /dev/null +++ b/odd/tasks/tower-lan-mobile.md @@ -0,0 +1,57 @@ +# tower-lan-mobile — Gentle Tower: opt-in LAN URL with QR, and a mobile layout +Objective: open Gentle Tower from a phone on the same network through a generated URL, and make the tower web view usable on that phone. +Branch: `feat/tower-lan-mobile` from `main` @ `0d181e872` · Delivery: `ask-on-risk` · Tests: focused `node --experimental-strip-types --test tests/.test.ts`; full `node scripts/run-test-suite.mjs`; types `node scripts/check-types.mjs`; runtime modules `node scripts/build-runtime-modules.mjs --write` then `--check`; web `cd web/tower && npx -y pnpm@11.1.1 install --frozen-lockfile && npx -y pnpm@11.1.1 run build`. + +## Specs +User strings are quoted verbatim (Spanish, as written). Evidence baseline: `lib/tower-server.ts:35,168-178,215-222`, `lib/gentle-shell-launcher.ts:181-216,1383,1432`, `README.md:221-231`, `docs/gentle-shell.md:533-569`, `web/tower/src/*` (Pixi scene plus DOM panels; `style.css` has no responsive rules). + +S1 — Opt-in LAN URL. `gentle-shell tower --lan` binds the server on all IPv4 interfaces (`0.0.0.0`) instead of `127.0.0.1`, and the text output prints one URL `http://://` for each non-internal IPv4 address of the machine (excluding link-local `169.254.0.0/16`), after the loopback URL. The first LAN address (private ranges first) is the primary URL. The `--json` output keeps every existing field with the same names and values and adds `lan: boolean` and `urls: string[]` (loopback first). Request: "lo ideal seria es que si estoy en la misma red pudiese verlo desde el telefono yendo a una url generada". Checks: launcher test with `--lan --json` (every non-internal IPv4 address from `os.networkInterfaces()` appears in `urls`; with no such address, `urls` holds only the loopback entry); a request over the LAN address with the token is served. + +S2 — QR in the terminal. In `--lan` mode the text output includes an ASCII QR code of the primary LAN URL (none in `--json` mode, which stays one line). The encoder is vendored under `lib/` with no new runtime dependency, keeping its MIT license notice. The terminal rendering uses a four-module quiet zone, the QR Code Model 2 spec's margin (review finding; was two). Decision: "Opt-in --lan, token en URL + QR (recomendado)". Checks: `tests/tower-qr.test.ts` pins the module matrix for three URLs (loopback, LAN IP, and a URL with a 63-character path) against fixtures in `tests/fixtures/tower-qr/`; the fixture matrices were decoded back to their URLs by an independent decoder (`jsqr`) in a scratch script outside the repository, recorded in the Log; a launcher test asserts the QR block appears in text output and not in JSON output. + +S3 — Token unchanged in LAN mode. The per-launch token is still the first path segment, still required on every HTTP request and on the WebSocket upgrade, and still compared in constant time through the existing `sameToken`. Checks: without token and with a wrong token the request is denied (same denial as today); with the right token through the LAN address it is served. + +S4 — Origin and Host in LAN mode. Every request's `` must be in the allowlist built at launch — `127.0.0.1`, `localhost` and each enumerated LAN address, with canonical HTTP authorities so port 80 approves both the bare host and the explicit `:80` — even an Origin-less navigation GET (review finding: the Host rule now applies before the optional Origin comparison). A request carrying `Origin` is additionally accepted only when `Origin === "http://" + `. `POST` without `Origin` is denied. Every other case gets the existing `deny` response. Checks: accepted (LAN IP host with the same origin); denied (foreign origin `http://evil.example`); denied (Host `evil.example:` with a matching Origin, the DNS-rebinding case); denied (Host `evil.example:` with a valid token and no Origin); denied (loopback Origin with a LAN Host); denied (`POST` without `Origin`); `lanAllowedHosts` pinned for port 80 and a non-default port. + +S5 — Default unchanged. Without `--lan` the server binds `127.0.0.1` only, keeps the current origin rule (`Origin` must be exactly `http://127.0.0.1:`; `localhost` is not added to the default allowlist) and the current token rule. Checks: `tests/tower-actions.test.ts` and the existing tower tests pass unmodified; in default mode `urls` is `[]` and `lan` is `false`. + +S6 — In-session command. `/gentle:tower --lan` starts the same LAN mode from a session and surfaces the LAN URLs and the warning where `/gentle:tower` surfaces the loopback URL today; `/gentle:tower` without the flag is unchanged. `/gentle:tower-mobile` is the one-word form of the same-network mode (user request, review finding: the server is reused while the mode matches and replaced, closing the running one, when it changes). Checks: `tests/gentle-tower.test.ts` covers both forms, the mobile command, both mode-change orders and same-mode reuse. + +S7 — Warning. In `--lan` mode the text output and the in-session report print a warning stating that anyone on the network who opens the URL can read and drive the sessions, that the traffic is not encrypted, and that it is meant for a trusted home network. Request: "gestionar pi y las sesiones desde el telefono mientras estoy en la casa (osea la misma red". Checks: the warning line is present in `--lan` text output (launcher test) and in the extension's report (extension test); JSON output may carry the same text in a `warning` field and still prints one line. + +S8 — Help and docs. Update the launcher help (`lib/gentle-shell-launcher.ts`, the `tower` usage and description lines), `README.md` (tower section, today "it listens on `127.0.0.1` only"), `docs/gentle-shell.md` (tower section) and any other doc line stating the loopback-only model for the tower, to describe `--lan`, the QR, the warning, the trust model (home network, HTTP without encryption), and that `--port` with `--lan` binds every interface. Checks: `grep -n '127.0.0.1` only' README.md docs/*.md` returns no tower statement contradicting the new behavior; any test pinning the help text is updated. + +S9 — Mobile layout. At a viewport width of 720 CSS px or less, or with a coarse pointer, the tower web app lays out for a phone: the Pixi building fits the viewport width with a minimum floor height of 44 CSS px (the scene scrolls vertically when the floors do not fit), and the panels — Talk, Todo, Artifacts, Library/usage and the floor controls — become tabs in a bottom sheet; Talk gets a visible button, not only the `T` key. Decision: "Responsive con hoja inferior (recomendado)"; request: "que esta vista de tower tuviese una vista mobile". Checks: `tests/tower-responsive.test.ts` covers the pure layout functions (`fitBuilding`, the sheet decision) at 390x844, 768x1024, 1440x900 and with many floors; `tsc --noEmit && vite build` pass; the built CSS contains the narrow-width media query. + +S10 — Touch and viewport. Floors and sheet tabs are at least 44x44 CSS px tap targets; the scene hit-testing uses pointer events; `touch-action: manipulation`; the app height uses `100dvh` and honours `env(safe-area-inset-*)`. Checks: `tsc --noEmit && vite build`; a structural probe of the built `dist` (media query, `100dvh`, `touch-action` present). + +S11 — Reconnection (assumption: a phone loses Wi-Fi more often than a desktop; if the client already reconnects and refetches the snapshot, this task only records the proof). When the WebSocket drops, the client reconnects with capped exponential backoff and fetches a fresh snapshot, so the view resumes without a manual reload. Checks: a test of the backoff schedule if a new one is written; otherwise the evidence recorded in the Log. + +S12 — Desktop unchanged. At desktop widths with a fine pointer the layout and interactions stay as today: no bottom sheet, keyboard `T` still opens Talk. Checks: the existing tower tests pass; the structural probe shows the desktop rules untouched (additive CSS only). + +## Tasks +T1 — S1, S3, S4, S5 — LAN server mode in `lib/tower-server.ts` (`lib/tower-launch.ts` if the address enumeration belongs there), runtime module rebuilt; tests `tests/tower-lan.test.ts` (new) and `tests/tower-actions.test.ts` (unchanged) — route: writer A2 + parent inline (A2 timed out; its server diff and tests kept, finished and verified by the parent) — done (C2). +T2 — S2 — vendored encoder `lib/tower-qr.ts`, `tests/tower-qr.test.ts`, `tests/fixtures/tower-qr/` — route: parent inline (writer A lost to a provider rate limit; recovered serially) — done (commit `687fca1a6`; tests 6/6 GREEN, jsQR decoded all three fixture matrices back to their exact URLs in scratch, `check-types` 0 regressions, runtime module generated and smoke-tested). +T3 — S1, S6, S7, S8 — `--lan` in the launcher (`lib/gentle-shell-launcher.ts`, runtime module rebuilt), `/gentle:tower --lan` in `extensions/gentle-tower.ts`, warning, docs and help; tests in `tests/gentle-shell-launcher-tower.test.ts` and `tests/gentle-tower.test.ts` — route: writer A3 + parent inline (A3 timed out after writing the RED tests; parent implemented to them) — done (C2). +T4 — S9, S10 — mobile layout in `web/tower/src` (`layout.ts` new, `style.css`, `panels.ts`, `main.ts`, `scene.ts`), `tests/tower-responsive.test.ts` (new) — route: parent inline (three writer timeouts; test written RED first, then implemented) — done (C3). +T5 — S11 — reconnection in `web/tower/src` — route: parent inline — done by proof (no new code needed: the transport is SSE, the server writes the full snapshot on every connection at `lib/tower-server.ts:242` and pushes changes every 700ms, and `EventSource` reconnects by itself — `web/tower/src/main.ts` `connect()`; `onmessage` re-renders the whole snapshot, so a dropped Wi-Fi resumes without a manual reload). +T6 — S1-S12 — seam check (full suite), independent verification of the high-risk units, work-unit commits — route: parent — done (commits `687fca1a6`, `f4ba7644e`, `e112a59fd`, `75b5be970`; full-suite seam check run three times with a pnpm shim; `gentle-ai-verify` returned VERIFIED for S1-S8 with 14/14 security probes and 17/17 CLI probes, no discrepancies; S9-S12 via their own passing test). +T7 — S2, S4 — review fixes: Host allowlist on every LAN request (including Origin-less GETs), canonical port-80 authorities (`lanAllowedHosts`), `interfaces` injection for deterministic tests, four-module QR quiet zone — route: parent inline — done. +T8 — S6 — mode-aware tower reuse in the extension plus `/gentle:tower-mobile` — route: parent inline — done. +T9 — S9, S10 — helper chips as the accessible touch route, Talk closes Tasks on phones, docs for the mobile command, verification and PR push — route: parent inline — done. + +Commit plan: C1 `feat(tower): vendored QR encoder for terminal URLs` (T2); C2 `feat(tower): opt-in --lan mode with host-bound origin checks` (T1, T3; Risk: items 2 and 3); C3 `feat(tower-web): mobile layout with bottom-sheet tabs` (T4, T5). Forecast: about 750 authored lines excluding the vendored encoder; slices follow the commits above. + +## Log +L1 (2026-11-24) — User request, verbatim: "analiza el repo y ayudame a aportar algo" followed by the README tower paragraph (`README.md:221-231`) and: "en esta parte dice que se abre en un navegador, lo ideal seria es que si estoy en la misma red pudiese verlo desde el telefono yendo a una url generada y tambien que esta vista de tower tuviese una vista mobile para ello asi gestionar pi y las sesiones desde el telefono mientras estoy en la casa (osea la misma red". +L2 (2026-11-24) — User decisions, verbatim: "Implementar LAN + vista móvil ahora"; "Opt-in --lan, token en URL + QR (recomendado)"; "Responsive con hoja inferior (recomendado)". +L3 (2026-11-24) — Evidence: the server binds `127.0.0.1` at `lib/tower-server.ts:215` with a literal `host` type (`:35`, `:220`); Origin must equal `http://127.0.0.1:${port}` and a `POST` without Origin is denied (`:168-171`); the token is the first path segment, compared in constant time (`:52`, `:172-178`); `runtime/*.mjs` is generated by `scripts/build-runtime-modules.mjs`; launcher flags are parsed at `lib/gentle-shell-launcher.ts:181-216`, help at `:1383` and `:1432`; `web/tower` is Vite plus TypeScript with a Pixi scene (`src/scene.ts`) and DOM panels (`src/panels.ts`), and `src/style.css` has no responsive rules; there is no LAN or QR precedent in the repository (`design-canvas-server` and `installer-server` are loopback only). +L4 (2026-11-24) — Decisions: exposure is opt-in (`--lan`) and the default stays behaviorally unchanged; the QR encoder is vendored (the package ships one runtime dependency through an installer and a tap, so no new runtime dependency); LAN binds `0.0.0.0` only under the flag; Origin must match the served Host and Host must be in the launch allowlist (blocks DNS rebinding); no HTTPS (self-signed certificates on phones are a wall), documented as a home-network trust model; the mobile layout stays additive so the user's uncommitted "DMG" skin in the sibling worktree `gentle-shell-tower-pokedex` remains mergeable. +L5 (2026-11-24) — Incident: both parallel writers (zai/glm-5.4, high effort) died on a provider rate limit — unit A after 60 turns having written only `tests/tower-qr.test.ts` (its RED test), unit B after 9 turns with no writes. Recovery (plan changed, not a blind retry): serial writer launches, and T2 moved inline to the parent because the vendoring is mechanical token-heavy transcription. Unit A's scope shrinks accordingly. +L6 (2026-11-24) — T2 evidence: vendored Nayuki qrcodegen.ts (MIT, master 2026-11-24) into `lib/tower-qr.ts` with documented strip-types adaptations (namespace removal, parameter-property expansion, three callback-body lint fixes, comment trailing-whitespace strip; algorithm untouched). Fixed two authoring bugs in the RED test left by writer A (`path.join(URL)` crash; impossible fixture order `loopback` < `long-path`) without weakening any assertion. `tests/tower-qr.test.ts` 6/6 pass; fixtures generated in scratch and independently decoded by jsQR (all three OK, exact URL match); `build-runtime-modules --write`/`--check` clean (27 modules); `check-types` 0 regressions after installing devDependencies with `pnpm@11.1.1` (the checkout had no node_modules); runtime smoke of `runtime/tower-qr.mjs` OK (v3, size 29, invariants hold). +L7 (2026-11-24) — T1+T3 evidence and incidents: writer A2 timed out at the 20-minute cap after implementing the server half and writing `tests/tower-lan.test.ts`; writer A3 (relaunched with a precise, smaller handoff) timed out the same way after writing the two RED test extensions. The parent finished both inline against those tests. Third authoring bug fixed in A2's test (expected `172.32.0.1` dropped; S1 keeps every non-internal IPv4 — private ranges only sort first). The foreground native-subagent relaunch also failed on tooling (a foreground child cannot load the `todo` extension the agent requires). Verification: 304 tests across the six tower/launcher files, 303 pass, 0 fail, 1 pre-existing skip; runtime modules regenerated and matching; `check-types` 0 regressions; the remaining `127.0.0.1\` only\`` doc statements are all correctly scoped for the default mode. Real CLI smoke: `gentle-shell tower --no-open --lan --port n --json` prints one JSON line with `lan`, `urls` (loopback + the machine's real 192.168.1.3 address) and the exact warning; text mode prints the loopback line, the LAN URL line, a 19-line indented QR block, the warning and `Press Ctrl+C to stop.` +L8 (2026-11-24) — T4+T5 evidence: `tests/tower-responsive.test.ts` written first and observed RED (`ERR_MODULE_NOT_FOUND`), then `web/tower/src/layout.ts` implemented — one formula bug caught by the test itself (an inner `max(1, …)` forced desktop scale on phones) and fixed; 5/5 GREEN. `main.ts` now takes its scale from `fitBuilding` and reserves the collapsed sheet for the sky; `style.css` gained one additive media block (`(max-width: 720px), (pointer: coarse)`): floor cards flow as a static list under the scaled building (44px targets), `.sel` docks as the bottom sheet with safe-area padding, todo/intercom/modals/library reflow, `touch-action: manipulation`, `100dvh`. Desktop rules untouched (S12: the fit test pins `max(1, width/720)` for widths >= 720). `vite build` passes; the built CSS contains `media(max-width:720px),(pointer:coarse)`, `min-height:44px`, `100dvh`, `touch-action` and `safe-area-inset-bottom`; a serve probe returned the built index.html (viewport meta) over the token URL. Docs gained the mobile paragraph in README.md and docs/gentle-shell.md. +L9 (2026-11-25) — T6 evidence and close: the full suite (`node scripts/run-test-suite.mjs`, run through a `npx pnpm@11.1.1` shim because pnpm is not on PATH here) failed unit-tests; every failure was classified by running the same files on the baseline `0d181e872` (worktrees with and without spaces in the path, with devDependencies installed): `package-files:15`/`verify-package-files:19` was this feature's one real seam defect — `runtime/tower-qr.mjs` missing from `requiredPaths` — fixed in `75b5be970` and now passing; `tower-pack:32/42` and `gentle-shell:4388` fail on the baseline too when the checkout path contains spaces (latent percent-encoded-URL bugs, pre-existing); `gentle-agents:9112`, `review-relay-transport-agent:336`, `shell-git-runner-stall:26/37/45`, `shell-git-worker-fallback:34` fail on the baseline identically; `desktop-rpc-config-watch:697`, `skill-registry:963` and `gentle-shell-desktop:694` are timing-flaky under full-suite load and pass in isolation on both trees. Zero failures remain attributable to this feature's diff. `gentle-ai-verify` independently verified the LAN unit (final verdict VERIFIED): 31/31 and 278/278 on the focused files, runtime and types clean, 14/14 security probes against a scratch server with controlled Host headers (foreign Origin, rebinding Host, POST without Origin, token rules, default-mode origin rule including the localhost refusal), 17/17 CLI shape probes (one-line JSON with exactly schema,url,host,port,lan,urls,warning; the QR block and the verbatim warning in text mode; the default JSON line unchanged with host 127.0.0.1), and a full read of the diff against S4 with no discrepancy. Feature closed: four commits on `feat/tower-lan-mobile`, not pushed (push and PR are the user's decisions). +L10 (2026-11-25) — Delivered as upstream PR Gentleman-Programming/gentle-shell#3569 (fork `vigbe/gentle-shell`, remote `fork`). CodeRabbit reviewed it with seven actionable findings; all verified against the code before acting: (1, Major) the extension reused the first tower regardless of the requested mode — fixed with mode tracking and replace-on-change, tests for both orders and same-mode reuse; (2) quiet zone 2 → 4 modules (QR Model 2 margin) — fixed, default-rendering test updated, matrix fixtures unchanged and still passing; (3) the LAN Host allowlist was skipped for Origin-less GETs — fixed, now checked on every LAN request before the optional Origin comparison, new test with a valid token and an unlisted Host; (4) port 80 canonical authorities — fixed with the pure `lanAllowedHosts` (both spellings approved on 80, exact matching elsewhere), pinned by test; (5) the tests re-read `networkInterfaces()` after startup — fixed with an `interfaces` option injected from a fixed fixture in the server, launcher and TUI tests (the real-LAN serve test keeps using real addresses); (6) helper touch targets too small on phones — fixed via the accessible-control route: one chip per helper on the floor card (desktop keeps the textual crew, hidden on touch); (7) `.todo` and `.intercom` overlapped on phones — Talk now closes Tasks when the bottom sheet is active. The user also asked, verbatim: "tambien haz mas sensillo el comando puede ser /gentle:tower-mobile y que eso lo active" — added `/gentle:tower-mobile` as the one-word same-network command. One hang during T8 was my own test assertion (reuse still re-opens the browser: `opened.length` is 2 with equal URLs); the failed assertion skipped `tower.close()`, leaving a server listening — fixed by correcting the assertion. Verification after the review fixes: 313/313 across the seven tower/launcher/responsive files, runtime modules matching, types 0 regressions, web build with the structural probe (media query, 44px, `100dvh`, `touch-action`, `crew-row`, safe-area). The vendored QR file keeps upstream `let`/parameter-reassignment idioms verbatim (53 `==`/`!=` were tightened to strict equality, semantics-preserving and proven by the unchanged fixture matrices); the web app's established `innerHTML`+`esc()` rendering pattern is kept, with the new interpolations escaped. +L11 (2026-11-26) — CodeRabbit re-reviewed 26d0276f0 (verdict: pass) with two follow-up Minor findings, both applied: the extension's failure path now clears `server` only when the failed startup still owns the reference (a newer command may have replaced it), and a shared `openTasks()` helper now closes the intercom when Tasks opens on a bottom sheet (the three entry points: the floor-card toggle, the Tasks button and the map room). Verification: web build clean, 60/60 on the focused tower files, runtime modules matching, types 0 regressions. +L12 (2026-11-26) — CodeRabbit's last follow-up (resize into bottom-sheet mode could leave Talk and Tasks both open in the shared area) — valid, applied: render() now reconciles the two panels when the sheet is active (the panel opened last keeps the area; the winner when nothing was tracked is Talk, made explicit in the pure `sheetWinner()` and pinned by a test). Session-lint style blockers on web/tower/src/main.ts (forEach wiring, nested ternaries, negation test) were mechanically cleaned with identical semantics; the file's established `innerHTML`+`esc()` rendering pattern and the vendored encoder's upstream idioms remain deliberate documented exceptions. Verification: build clean, 61/61 on the focused tower files, runtime modules matching, types 0 regressions. diff --git a/runtime/gentle-shell-launcher.mjs b/runtime/gentle-shell-launcher.mjs index 401812b3c..0342afed5 100644 --- a/runtime/gentle-shell-launcher.mjs +++ b/runtime/gentle-shell-launcher.mjs @@ -189,13 +189,16 @@ export function parseLauncherArgs(argv ) { -// `gentle-shell tower [--no-open] [--port ] [--json]`: the server always -// binds 127.0.0.1; --port only fixes which local port; --json is for programs -// (the desktop app) that read the URL instead of a person. + + +// `gentle-shell tower [--no-open] [--port ] [--json] [--lan]`: the server +// binds 127.0.0.1 unless --lan; --port only fixes which local port; --json is +// for programs (the desktop app) that read the URL instead of a person. export function parseTowerArgs(args ) { let open = true; let port ; let json = false; + let lan = false; for (let i = 0; i < args.length; i += 1) { const arg = args[i]; if (arg === "--no-open") { @@ -206,6 +209,10 @@ export function parseTowerArgs(args ) { json = true; continue; } + if (arg === "--lan") { + lan = true; + continue; + } if (arg === "--port" || arg.startsWith("--port=")) { const value = arg === "--port" ? args[(i += 1)] : arg.slice("--port=".length); if (value === undefined) return { open, error: "--port needs a whole number from 1 to 65535" }; @@ -216,7 +223,7 @@ export function parseTowerArgs(args ) { } return { open, error: `unknown tower argument "${arg}"` }; } - return { open, ...(port === undefined ? {} : { port }), ...(json ? { json: true } : {}) }; + return { open, ...(port === undefined ? {} : { port }), ...(json ? { json: true } : {}), ...(lan ? { lan: true } : {}) }; } // --- home resolution ------------------------------------------------------- @@ -1381,7 +1388,7 @@ export function helpText() { " gentle-shell memory migrate --confirm-quiescent", " gentle-shell self-uninstall [--dry-run] [--yes] [--include-shared]", " gentle-shell desktop [--yes] [--no-open] | --status | --uninstall", - " gentle-shell tower [--no-open] [--port ] [--json]", + " gentle-shell tower [--no-open] [--port ] [--json] [--lan]", "", "Opens pi with the Gentle Shell package loaded, without touching your", "vanilla pi installation.", @@ -1432,8 +1439,11 @@ export function helpText() { " question); --status and --uninstall; 'gentle-shell desktop --help'.", " tower Open the Gentle Tower outside any session: every open Gentle Shell session", " as a floor, in your browser. Prints the local URL and serves until Ctrl+C.", - " --no-open only prints the URL; --port fixes the port (127.0.0.1 only);", - " --json prints one JSON line with the URL instead, for programs.", + " --no-open only prints the URL; --port fixes the port (127.0.0.1 only,", + " unless --lan); --json prints one JSON line with the URL instead, for programs.", + " --lan also binds every network interface, to open the view from a", + " phone on the same network: it prints one URL per address, a QR code and a warning;", + " --port then fixes the port on every interface.", "", "Managing packages:", " gentle-shell install npm: Run pi's own 'install' against the resolved home.", diff --git a/runtime/tower-open.mjs b/runtime/tower-open.mjs index dd4acd4d5..d497c9d11 100644 --- a/runtime/tower-open.mjs +++ b/runtime/tower-open.mjs @@ -6,11 +6,13 @@ import { randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; +import { } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { towerHubDir } from "./tower-hub.mjs"; import { launchInTerminal } from "./tower-launch.mjs"; import { defaultPresenceDirs } from "./tower-presence.mjs"; +import { encodeQr, renderQrTerminal } from "./tower-qr.mjs"; import { startTowerServer, } from "./tower-server.mjs"; // lib/ and its generated runtime/ copy both sit one level under the package root. @@ -34,6 +36,13 @@ export class TowerNotBuiltError extends Error { + + + + +/** The warning every LAN-mode report prints, exactly. */ +export const TOWER_LAN_WARNING = "LAN mode: anyone on this network who opens the URL can read and drive your sessions; traffic is not encrypted. Use it only on a trusted home network."; + export function openTowerServer(env , options = {}) { const webDir = options.webDir ?? TOWER_WEB_DIR; if (!existsSync(join(webDir, "index.html"))) return Promise.reject(new TowerNotBuiltError(webDir)); @@ -44,6 +53,8 @@ export function openTowerServer(env , options engramUrl: env.ENGRAM_URL || "http://127.0.0.1:7437", presenceDirs: options.presenceDirs ?? defaultPresenceDirs(), ...(options.port === undefined ? {} : { port: options.port }), + ...(options.lan ? { lan: true } : {}), + ...(options.interfaces === undefined ? {} : { interfaces: options.interfaces }), onNewFloor: (cwd, prompt) => launchInTerminal({ cwd, node: process.execPath, launcher: LAUNCHER, ...(prompt ? { prompt } : {}) }), }); } @@ -95,9 +106,19 @@ export async function runTower(options ) { return 1; } try { - options.stdout(options.json - ? `${JSON.stringify({ schema: TOWER_JSON_SCHEMA, url: server.url, host: server.host, port: server.port })}\n` - : `Gentle Tower: ${server.url}\nPress Ctrl+C to stop.\n`); + if (options.json) { + // One line, no QR art; LAN mode adds its own fields at the end. + options.stdout(`${JSON.stringify({ schema: TOWER_JSON_SCHEMA, url: server.url, host: server.host, port: server.port, + ...(server.lan ? { lan: server.lan, urls: server.urls, warning: TOWER_LAN_WARNING } : {}) })}\n`); + } else if (server.lan) { + const lines = [`Gentle Tower: ${server.url}`, ...server.urls.slice(1).map((u) => ` ${u}`)]; + // The QR carries the first LAN address: the phone's way in. + if (server.urls.length > 1) for (const line of renderQrTerminal(encodeQr(server.urls[1]))) lines.push(` ${line}`); + lines.push(TOWER_LAN_WARNING, "Press Ctrl+C to stop."); + options.stdout(`${lines.join("\n")}\n`); + } else { + options.stdout(`Gentle Tower: ${server.url}\nPress Ctrl+C to stop.\n`); + } if (options.open) (options.openUrl ?? openInBrowser)(server.url); await (options.untilStopped ?? untilSignal)(server); } finally { diff --git a/runtime/tower-qr.mjs b/runtime/tower-qr.mjs new file mode 100644 index 000000000..6006c301f --- /dev/null +++ b/runtime/tower-qr.mjs @@ -0,0 +1,1090 @@ +// Generated by scripts/build-runtime-modules.mjs. Do not edit. +// Gentle Tower: QR codes for terminal URLs, so a phone on the same network can +// open the tower without typing a token. Self-contained on purpose: the launcher +// runtime module inlines it without import rewrites. + +// The encoder below is vendored from Project Nayuki's "QR Code generator library +// (TypeScript)" (MIT License), https://www.nayuki.io/page/qr-code-generator-library , +// fetched from +// https://raw.githubusercontent.com/nayuki/QR-Code-generator/master/typescript-javascript/qrcodegen.ts +// on 2026-11-24. The algorithm is unmodified. Only mechanical, behavior-preserving +// syntax adaptations were applied, required because this repository runs lib/ +// sources through node --experimental-strip-types (mode "strip"), which rejects +// namespaces and constructor parameter properties: +// - the `namespace qrcodegen`, `namespace qrcodegen.QrCode` and +// `namespace qrcodegen.QrSegment` wrappers were removed: QrCode, QrSegment, Ecc +// and Mode are exported directly, the `type bit/byte/int` aliases moved to module +// scope, and internal `qrcodegen.` qualifiers were dropped; +// - `QrCode.Ecc` became `Ecc` and `QrSegment.Mode` became `Mode` everywhere; +// - constructor parameter properties were expanded into declared fields plus +// constructor assignments (QrCode.version, QrCode.errorCorrectionLevel, +// QrSegment.mode, QrSegment.numChars, QrSegment.bitData, Ecc.ordinal, +// Ecc.formatBits, Mode.modeBits, Mode.numBitsCharCount); +// - three side-effecting callbacks were rewritten from single-expression bodies +// returning the assignment value into block bodies returning nothing, one +// unused callback parameter was dropped (`map(_ => 0)` became `map(() => 0)`), +// and the upstream `==`/`!=` comparisons were tightened to `===`/`!==` with one +// single-assigned `let` becoming `const`, to satisfy the repository's lint +// blockers; every one of these is semantics-preserving for the number and +// boolean comparisons involved. The upstream naming is kept verbatim. +// Everything between the "Vendored" markers below stays reviewable against the +// upstream file (only the adaptations listed above differ). +// +// The original MIT license notice, kept as required: +// +// Copyright (c) Project Nayuki. (MIT License) +// https://www.nayuki.io/page/qr-code-generator-library +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// - The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// - The Software is provided "as is", without warranty of any kind, express or +// implied, including but not limited to the warranties of merchantability, +// fitness for a particular purpose and noninfringement. In no event shall the +// authors or copyright holders be liable for any claim, damages or other +// liability, whether in an action of contract, tort or otherwise, arising from, +// out of or in connection with the Software or the use or other dealings in the +// Software. + +"use strict"; + +// ---- Vendored from Nayuki qrcodegen.ts (mechanically adapted; see header) ---- + + + + + + +/*---- QR Code symbol class ----*/ + +/* + * A QR Code symbol, which is a type of two-dimensional barcode. + * Invented by Denso Wave and described in the ISO/IEC 18004 standard. + * Instances of this class represent an immutable square grid of dark and light cells. + * The class provides static factory functions to create a QR Code from text or binary data. + * The class covers the QR Code Model 2 specification, supporting all versions (sizes) + * from 1 to 40, all 4 error correction levels, and 4 character encoding modes. + * + * Ways to create a QR Code object: + * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary(). + * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments(). + * - Low level: Custom-make the array of data codeword bytes (including + * segment headers and final padding, excluding error correction codewords), + * supply the appropriate version number, and call the QrCode() constructor. + * (Note that all ways require supplying the desired error correction level.) + */ +export class QrCode { + + /*-- Static factory functions (high level) --*/ + + // Returns a QR Code representing the given Unicode text string at the given error correction level. + // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer + // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible + // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than + // the ecl argument if it can be done without increasing the version. + static encodeText(text , ecl ) { + const segs = QrSegment.makeSegments(text); + return QrCode.encodeSegments(segs, ecl); + } + + + // Returns a QR Code representing the given binary data at the given error correction level. + // This function always encodes using the binary segment mode, not any text mode. The maximum number of + // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. + // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. + static encodeBinary(data , ecl ) { + const seg = QrSegment.makeBytes(data); + return QrCode.encodeSegments([seg], ecl); + } + + + /*-- Static factory functions (mid level) --*/ + + // Returns a QR Code representing the given segments with the given encoding parameters. + // The smallest possible QR Code version within the given range is automatically + // chosen for the output. Iff boostEcl is true, then the ECC level of the result + // may be higher than the ecl argument if it can be done without increasing the + // version. The mask number is either between 0 to 7 (inclusive) to force that + // mask, or -1 to automatically choose an appropriate mask (which may be slow). + // This function allows the user to create a custom sequence of segments that switches + // between modes (such as alphanumeric and byte) to encode text in less space. + // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). + static encodeSegments(segs , ecl , + minVersion = 1, maxVersion = 40, + mask = -1, boostEcl = true) { + + if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) + || mask < -1 || mask > 7) + throw new RangeError("Invalid value"); + + // Find the minimal version number to use + let version ; + let dataUsedBits ; + for (version = minVersion; ; version++) { + const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available + const usedBits = QrSegment.getTotalBits(segs, version); + if (usedBits <= dataCapacityBits) { + dataUsedBits = usedBits; + break; // This version number is found to be suitable + } + if (version >= maxVersion) // All versions in the range could not fit the given data + throw new RangeError("Data too long"); + } + + // Increase the error correction level while the data still fits in the current version number + for (const newEcl of [Ecc.MEDIUM, Ecc.QUARTILE, Ecc.HIGH]) { // From low to high + if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) + ecl = newEcl; + } + + // Concatenate all segments to create the data bit string + let bb = [] + for (const seg of segs) { + appendBits(seg.mode.modeBits, 4, bb); + appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb); + for (const b of seg.getData()) + bb.push(b); + } + assert(bb.length === dataUsedBits); + + // Add terminator and pad up to a byte if applicable + const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; + assert(bb.length <= dataCapacityBits); + appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb); + appendBits(0, (8 - bb.length % 8) % 8, bb); + assert(bb.length % 8 === 0); + + // Pad with alternating bytes until data capacity is reached + for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11) + appendBits(padByte, 8, bb); + + // Pack bits into bytes in big endian + let dataCodewords = []; + while (dataCodewords.length * 8 < bb.length) + dataCodewords.push(0); + bb.forEach((b , i ) => { + dataCodewords[i >>> 3] |= b << (7 - (i & 7)); + }); + + // Create the QR Code object + return new QrCode(version, ecl, dataCodewords, mask); + } + + + /*-- Fields --*/ + + // The width and height of this QR Code, measured in modules, between + // 21 and 177 (inclusive). This is equal to version * 4 + 17. + size ; + + // The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive). + // Even if a QR Code is created with automatic masking requested (mask = -1), + // the resulting object still has a mask value between 0 and 7. + mask ; + + // The modules of this QR Code (false = light, true = dark). + // Immutable after constructor finishes. Accessed through getModule(). + modules = []; + + // Indicates function modules that are not subjected to masking. Discarded when constructor finishes. + isFunction = []; + + + /*-- Constructor (low level) and fields --*/ + + // Creates a new QR Code with the given version number, + // error correction level, data codeword bytes, and mask number. + // This is a low-level API that most users should not use directly. + // A mid-level API is the encodeSegments() function. + version ; + errorCorrectionLevel ; + + constructor( + // The version number of this QR Code, which is between 1 and 40 (inclusive). + // This determines the size of this barcode. + version , + + // The error correction level used in this QR Code. + errorCorrectionLevel , + + dataCodewords , + + msk ) { + this.version = version; + this.errorCorrectionLevel = errorCorrectionLevel; + + // Check scalar arguments + if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) + throw new RangeError("Version value out of range"); + if (msk < -1 || msk > 7) + throw new RangeError("Mask value out of range"); + this.size = version * 4 + 17; + + // Initialize both grids to be size*size arrays of Boolean false + let row = []; + for (let i = 0; i < this.size; i++) + row.push(false); + for (let i = 0; i < this.size; i++) { + this.modules .push(row.slice()); // Initially all light + this.isFunction.push(row.slice()); + } + + // Compute ECC, draw modules + this.drawFunctionPatterns(); + const allCodewords = this.addEccAndInterleave(dataCodewords); + this.drawCodewords(allCodewords); + + // Do masking + if (msk === -1) { // Automatically choose best mask + let minPenalty = 1000000000; + for (let i = 0; i < 8; i++) { + this.applyMask(i); + this.drawFormatBits(i); + const penalty = this.getPenaltyScore(); + if (penalty < minPenalty) { + msk = i; + minPenalty = penalty; + } + this.applyMask(i); // Undoes the mask due to XOR + } + } + assert(0 <= msk && msk <= 7); + this.mask = msk; + this.applyMask(msk); // Apply the final choice of mask + this.drawFormatBits(msk); // Overwrite old format bits + + this.isFunction = []; + } + + + /*-- Accessor methods --*/ + + // Returns the color of the module (pixel) at the given coordinates, which is false + // for light or true for dark. The top left corner has the coordinates (x=0, y=0). + // If the given coordinates are out of bounds, then false (light) is returned. + getModule(x , y ) { + return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x]; + } + + + /*-- Private helper methods for constructor: Drawing function modules --*/ + + // Reads this object's version field, and draws and marks all function modules. + drawFunctionPatterns() { + // Draw horizontal and vertical timing patterns + for (let i = 0; i < this.size; i++) { + this.setFunctionModule(6, i, i % 2 === 0); + this.setFunctionModule(i, 6, i % 2 === 0); + } + + // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules) + this.drawFinderPattern(3, 3); + this.drawFinderPattern(this.size - 4, 3); + this.drawFinderPattern(3, this.size - 4); + + // Draw numerous alignment patterns + const alignPatPos = this.getAlignmentPatternPositions(); + alignPatPos.forEach((x , i ) => { + alignPatPos.forEach((y , j ) => { + // Don't draw on the three finder corners + if (!(i === 0 && j === 0 || i === 0 && j === alignPatPos.length - 1 || i === alignPatPos.length - 1 && j === 0)) + this.drawAlignmentPattern(x, y); + }); + }); + + // Draw configuration data + this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor + this.drawVersion(); + } + + + // Draws two copies of the format bits (with its own error correction code) + // based on the given mask and this object's error correction level field. + drawFormatBits(mask ) { + // Calculate error correction code and pack bits + const data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3 + let rem = data; + for (let i = 0; i < 10; i++) + rem = (rem << 1) ^ ((rem >>> 9) * 0x537); + const bits = (data << 10 | rem) ^ 0x5412; // uint15 + assert(bits >>> 15 === 0); + + // Draw first copy + for (let i = 0; i <= 5; i++) + this.setFunctionModule(8, i, getBit(bits, i)); + this.setFunctionModule(8, 7, getBit(bits, 6)); + this.setFunctionModule(8, 8, getBit(bits, 7)); + this.setFunctionModule(7, 8, getBit(bits, 8)); + for (let i = 9; i < 15; i++) + this.setFunctionModule(14 - i, 8, getBit(bits, i)); + + // Draw second copy + for (let i = 0; i < 8; i++) + this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i)); + for (let i = 8; i < 15; i++) + this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i)); + this.setFunctionModule(8, this.size - 8, true); // Always dark + } + + + // Draws two copies of the version bits (with its own error correction code), + // based on this object's version field, iff 7 <= version <= 40. + drawVersion() { + if (this.version < 7) + return; + + // Calculate error correction code and pack bits + let rem = this.version; // version is uint6, in the range [7, 40] + for (let i = 0; i < 12; i++) + rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25); + const bits = this.version << 12 | rem; // uint18 + assert(bits >>> 18 === 0); + + // Draw two copies + for (let i = 0; i < 18; i++) { + const color = getBit(bits, i); + const a = this.size - 11 + i % 3; + const b = Math.floor(i / 3); + this.setFunctionModule(a, b, color); + this.setFunctionModule(b, a, color); + } + } + + + // Draws a 9*9 finder pattern including the border separator, + // with the center module at (x, y). Modules can be out of bounds. + drawFinderPattern(x , y ) { + for (let dy = -4; dy <= 4; dy++) { + for (let dx = -4; dx <= 4; dx++) { + const dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm + const xx = x + dx; + const yy = y + dy; + if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) + this.setFunctionModule(xx, yy, dist !== 2 && dist !== 4); + } + } + } + + + // Draws a 5*5 alignment pattern, with the center module + // at (x, y). All modules must be in bounds. + drawAlignmentPattern(x , y ) { + for (let dy = -2; dy <= 2; dy++) { + for (let dx = -2; dx <= 2; dx++) + this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1); + } + } + + + // Sets the color of a module and marks it as a function module. + // Only used by the constructor. Coordinates must be in bounds. + setFunctionModule(x , y , isDark ) { + this.modules[y][x] = isDark; + this.isFunction[y][x] = true; + } + + + /*-- Private helper methods for constructor: Codewords and masking --*/ + + // Returns a new byte string representing the given data with the appropriate error correction + // codewords appended to it, based on this object's version and error correction level. + addEccAndInterleave(data ) { + const ver = this.version; + const ecl = this.errorCorrectionLevel; + if (data.length !== QrCode.getNumDataCodewords(ver, ecl)) + throw new RangeError("Invalid argument"); + + // Calculate parameter numbers + const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver]; + const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8); + const numShortBlocks = numBlocks - rawCodewords % numBlocks; + const shortBlockLen = Math.floor(rawCodewords / numBlocks); + + // Split data into blocks and append ECC to each block + let blocks = []; + const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen); + for (let i = 0, k = 0; i < numBlocks; i++) { + let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1)); + k += dat.length; + const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv); + if (i < numShortBlocks) + dat.push(0); + blocks.push(dat.concat(ecc)); + } + + // Interleave (not concatenate) the bytes from every block into a single sequence + let result = []; + for (let i = 0; i < blocks[0].length; i++) { + blocks.forEach((block , j ) => { + // Skip the padding byte in short blocks + if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) + result.push(block[i]); + }); + } + assert(result.length === rawCodewords); + return result; + } + + + // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire + // data area of this QR Code. Function modules need to be marked off before this is called. + drawCodewords(data ) { + if (data.length !== Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) + throw new RangeError("Invalid argument"); + let i = 0; // Bit index into the data + // Do the funny zigzag scan + for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair + if (right === 6) + right = 5; + for (let vert = 0; vert < this.size; vert++) { // Vertical counter + for (let j = 0; j < 2; j++) { + const x = right - j; // Actual x coordinate + const upward = ((right + 1) & 2) === 0; + const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate + if (!this.isFunction[y][x] && i < data.length * 8) { + this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7)); + i++; + } + // If this QR Code has any remainder bits (0 to 7), they were assigned as + // 0/false/light by the constructor and are left unchanged by this method + } + } + } + assert(i === data.length * 8); + } + + + // XORs the codeword modules in this QR Code with the given mask pattern. + // The function modules must be marked and the codeword bits must be drawn + // before masking. Due to the arithmetic of XOR, calling applyMask() with the + // same mask value a second time will undo the mask. A final well-formed + // QR Code needs exactly one (not zero, two, etc.) mask applied. + applyMask(mask ) { + if (mask < 0 || mask > 7) + throw new RangeError("Mask value out of range"); + for (let y = 0; y < this.size; y++) { + for (let x = 0; x < this.size; x++) { + let invert ; + switch (mask) { + case 0: invert = (x + y) % 2 === 0; break; + case 1: invert = y % 2 === 0; break; + case 2: invert = x % 3 === 0; break; + case 3: invert = (x + y) % 3 === 0; break; + case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0; break; + case 5: invert = x * y % 2 + x * y % 3 === 0; break; + case 6: invert = (x * y % 2 + x * y % 3) % 2 === 0; break; + case 7: invert = ((x + y) % 2 + x * y % 3) % 2 === 0; break; + default: throw new Error("Unreachable"); + } + if (!this.isFunction[y][x] && invert) + this.modules[y][x] = !this.modules[y][x]; + } + } + } + + + // Calculates and returns the penalty score based on state of this QR Code's current modules. + // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. + getPenaltyScore() { + let result = 0; + + // Adjacent modules in row having same color, and finder-like patterns + for (let y = 0; y < this.size; y++) { + let runColor = false; + let runX = 0; + let runHistory = [0,0,0,0,0,0,0]; + for (let x = 0; x < this.size; x++) { + if (this.modules[y][x] === runColor) { + runX++; + if (runX === 5) + result += QrCode.PENALTY_N1; + else if (runX > 5) + result++; + } else { + this.finderPenaltyAddHistory(runX, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; + runColor = this.modules[y][x]; + runX = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3; + } + // Adjacent modules in column having same color, and finder-like patterns + for (let x = 0; x < this.size; x++) { + let runColor = false; + let runY = 0; + let runHistory = [0,0,0,0,0,0,0]; + for (let y = 0; y < this.size; y++) { + if (this.modules[y][x] === runColor) { + runY++; + if (runY === 5) + result += QrCode.PENALTY_N1; + else if (runY > 5) + result++; + } else { + this.finderPenaltyAddHistory(runY, runHistory); + if (!runColor) + result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3; + runColor = this.modules[y][x]; + runY = 1; + } + } + result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3; + } + + // 2*2 blocks of modules having same color + for (let y = 0; y < this.size - 1; y++) { + for (let x = 0; x < this.size - 1; x++) { + const color = this.modules[y][x]; + if ( color === this.modules[y][x + 1] && + color === this.modules[y + 1][x] && + color === this.modules[y + 1][x + 1]) + result += QrCode.PENALTY_N2; + } + } + + // Balance of dark and light modules + let dark = 0; + for (const row of this.modules) + dark = row.reduce((sum , color ) => sum + (color ? 1 : 0), dark); + const total = this.size * this.size; // Note that size is odd, so dark/total !== 1/2 + // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)% + const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1; + assert(0 <= k && k <= 9); + result += k * QrCode.PENALTY_N4; + assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4 + return result; + } + + + /*-- Private helper functions --*/ + + // Returns an ascending list of positions of alignment patterns for this version number. + // Each position is in the range [0,177), and are used on both the x and y axes. + // This could be implemented as lookup table of 40 variable-length lists of integers. + getAlignmentPatternPositions() { + if (this.version === 1) + return []; + else { + const numAlign = Math.floor(this.version / 7) + 2; + const step = Math.floor((this.version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4)) * 2; + const result = [6]; + for (let pos = this.size - 7; result.length < numAlign; pos -= step) + result.splice(1, 0, pos); + return result; + } + } + + + // Returns the number of data bits that can be stored in a QR Code of the given version number, after + // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. + // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. + static getNumRawDataModules(ver ) { + if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) + throw new RangeError("Version number out of range"); + let result = (16 * ver + 128) * ver + 64; + if (ver >= 2) { + const numAlign = Math.floor(ver / 7) + 2; + result -= (25 * numAlign - 10) * numAlign - 55; + if (ver >= 7) + result -= 36; + } + assert(208 <= result && result <= 29648); + return result; + } + + + // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any + // QR Code of the given version number and error correction level, with remainder bits discarded. + // This stateless pure function could be implemented as a (40*4)-cell lookup table. + static getNumDataCodewords(ver , ecl ) { + return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - + QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] * + QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]; + } + + + // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be + // implemented as a lookup table over all possible parameter values, instead of as an algorithm. + static reedSolomonComputeDivisor(degree ) { + if (degree < 1 || degree > 255) + throw new RangeError("Degree out of range"); + // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1. + // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93]. + let result = []; + for (let i = 0; i < degree - 1; i++) + result.push(0); + result.push(1); // Start off with the monomial x^0 + + // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}), + // and drop the highest monomial term which is always 1x^degree. + // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D). + let root = 1; + for (let i = 0; i < degree; i++) { + // Multiply the current product by (x - r^i) + for (let j = 0; j < result.length; j++) { + result[j] = QrCode.reedSolomonMultiply(result[j], root); + if (j + 1 < result.length) + result[j] ^= result[j + 1]; + } + root = QrCode.reedSolomonMultiply(root, 0x02); + } + return result; + } + + + // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. + static reedSolomonComputeRemainder(data , divisor ) { + let result = divisor.map(() => 0); + for (const b of data) { // Polynomial division + const factor = b ^ (result.shift() ); + result.push(0); + divisor.forEach((coef , i ) => { + result[i] ^= QrCode.reedSolomonMultiply(coef, factor); + }); + } + return result; + } + + + // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result + // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. + static reedSolomonMultiply(x , y ) { + if (x >>> 8 !== 0 || y >>> 8 !== 0) + throw new RangeError("Byte out of range"); + // Russian peasant multiplication + let z = 0; + for (let i = 7; i >= 0; i--) { + z = (z << 1) ^ ((z >>> 7) * 0x11D); + z ^= ((y >>> i) & 1) * x; + } + assert(z >>> 8 === 0); + return z ; + } + + + // Can only be called immediately after a light run is added, and + // returns either 0, 1, or 2. A helper function for getPenaltyScore(). + finderPenaltyCountPatterns(runHistory ) { + const n = runHistory[1]; + assert(n <= this.size * 3); + const core = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n; + return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) + + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0); + } + + + // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). + finderPenaltyTerminateAndCount(currentRunColor , currentRunLength , runHistory ) { + if (currentRunColor) { // Terminate dark run + this.finderPenaltyAddHistory(currentRunLength, runHistory); + currentRunLength = 0; + } + currentRunLength += this.size; // Add light border to final run + this.finderPenaltyAddHistory(currentRunLength, runHistory); + return this.finderPenaltyCountPatterns(runHistory); + } + + + // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). + finderPenaltyAddHistory(currentRunLength , runHistory ) { + if (runHistory[0] === 0) + currentRunLength += this.size; // Add light border to initial run + runHistory.pop(); + runHistory.unshift(currentRunLength); + } + + + /*-- Constants and tables --*/ + + // The minimum version number supported in the QR Code Model 2 standard. + static MIN_VERSION = 1; + // The maximum version number supported in the QR Code Model 2 standard. + static MAX_VERSION = 40; + + // For use in getPenaltyScore(), when evaluating which mask is best. + static PENALTY_N1 = 3; + static PENALTY_N2 = 3; + static PENALTY_N3 = 40; + static PENALTY_N4 = 10; + + static ECC_CODEWORDS_PER_BLOCK = [ + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low + [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium + [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile + [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High + ]; + + static NUM_ERROR_CORRECTION_BLOCKS = [ + // Version: (note that index 0 is for padding, and is set to an illegal value) + //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level + [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low + [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium + [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile + [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High + ]; + +} + + +// Appends the given number of low-order bits of the given value +// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len. +function appendBits(val , len , bb ) { + if (len < 0 || len > 31 || val >>> len !== 0) + throw new RangeError("Value out of range"); + for (let i = len - 1; i >= 0; i--) // Append bit by bit + bb.push((val >>> i) & 1); +} + + +// Returns true iff the i'th bit of x is set to 1. +function getBit(x , i ) { + return ((x >>> i) & 1) !== 0; +} + + +// Throws an exception if the given condition is false. +function assert(cond ) { + if (!cond) + throw new Error("Assertion error"); +} + + + +/*---- Data segment class ----*/ + +/* + * A segment of character/binary/control data in a QR Code symbol. + * Instances of this class are immutable. + * The mid-level way to create a segment is to take the payload data + * and call a static factory function such as QrSegment.makeNumeric(). + * The low-level way to create a segment is to custom-make the bit buffer + * and call the QrSegment() constructor with appropriate values. + * This segment class imposes no length restrictions, but QR Codes have restrictions. + * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data. + * Any segment longer than this is meaningless for the purpose of generating QR Codes. + */ +export class QrSegment { + + /*-- Static factory functions (mid level) --*/ + + // Returns a segment representing the given binary data encoded in + // byte mode. All input byte arrays are acceptable. Any text string + // can be converted to UTF-8 bytes and encoded as a byte mode segment. + static makeBytes(data ) { + let bb = [] + for (const b of data) + appendBits(b, 8, bb); + return new QrSegment(Mode.BYTE, data.length, bb); + } + + + // Returns a segment representing the given string of decimal digits encoded in numeric mode. + static makeNumeric(digits ) { + if (!QrSegment.isNumeric(digits)) + throw new RangeError("String contains non-numeric characters"); + let bb = [] + for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration + const n = Math.min(digits.length - i, 3); + appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb); + i += n; + } + return new QrSegment(Mode.NUMERIC, digits.length, bb); + } + + + // Returns a segment representing the given text string encoded in alphanumeric mode. + // The characters allowed are: 0 to 9, A to Z (uppercase only), space, + // dollar, percent, asterisk, plus, hyphen, period, slash, colon. + static makeAlphanumeric(text ) { + if (!QrSegment.isAlphanumeric(text)) + throw new RangeError("String contains unencodable characters in alphanumeric mode"); + let bb = [] + let i ; + for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2 + let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45; + temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1)); + appendBits(temp, 11, bb); + } + if (i < text.length) // 1 character remaining + appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb); + return new QrSegment(Mode.ALPHANUMERIC, text.length, bb); + } + + + // Returns a new mutable list of zero or more segments to represent the given Unicode text string. + // The result may use various segment modes and switch modes to optimize the length of the bit stream. + static makeSegments(text ) { + // Select the most efficient segment encoding automatically + if (text === "") + return []; + else if (QrSegment.isNumeric(text)) + return [QrSegment.makeNumeric(text)]; + else if (QrSegment.isAlphanumeric(text)) + return [QrSegment.makeAlphanumeric(text)]; + else + return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))]; + } + + + // Returns a segment representing an Extended Channel Interpretation + // (ECI) designator with the given assignment value. + static makeEci(assignVal ) { + let bb = [] + if (assignVal < 0) + throw new RangeError("ECI assignment value out of range"); + else if (assignVal < (1 << 7)) + appendBits(assignVal, 8, bb); + else if (assignVal < (1 << 14)) { + appendBits(0b10, 2, bb); + appendBits(assignVal, 14, bb); + } else if (assignVal < 1000000) { + appendBits(0b110, 3, bb); + appendBits(assignVal, 21, bb); + } else + throw new RangeError("ECI assignment value out of range"); + return new QrSegment(Mode.ECI, 0, bb); + } + + + // Tests whether the given string can be encoded as a segment in numeric mode. + // A string is encodable iff each character is in the range 0 to 9. + static isNumeric(text ) { + return QrSegment.NUMERIC_REGEX.test(text); + } + + + // Tests whether the given string can be encoded as a segment in alphanumeric mode. + // A string is encodable iff each character is in the following set: 0 to 9, A to Z + // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. + static isAlphanumeric(text ) { + return QrSegment.ALPHANUMERIC_REGEX.test(text); + } + + + /*-- Constructor (low level) and fields --*/ + + // Creates a new QR Code segment with the given attributes and data. + // The character count (numChars) must agree with the mode and the bit buffer length, + // but the constraint isn't checked. The given bit buffer is cloned and stored. + mode ; + numChars ; + bitData ; + + constructor( + // The mode indicator of this segment. + mode , + + // The length of this segment's unencoded data. Measured in characters for + // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode. + // Always zero or positive. Not the same as the data's bit length. + numChars , + + // The data bits of this segment. Accessed through getData(). + bitData ) { + this.mode = mode; + this.numChars = numChars; + if (numChars < 0) + throw new RangeError("Invalid argument"); + this.bitData = bitData.slice(); // Make defensive copy + } + + + /*-- Methods --*/ + + // Returns a new copy of the data bits of this segment. + getData() { + return this.bitData.slice(); // Make defensive copy + } + + + // (Package-private) Calculates and returns the number of bits needed to encode the given segments at + // the given version. The result is infinity if a segment has too many characters to fit its length field. + static getTotalBits(segs , version ) { + let result = 0; + for (const seg of segs) { + const ccbits = seg.mode.numCharCountBits(version); + if (seg.numChars >= (1 << ccbits)) + return Infinity; // The segment's length doesn't fit the field's bit width + result += 4 + ccbits + seg.bitData.length; + } + return result; + } + + + // Returns a new array of bytes representing the given string encoded in UTF-8. + static toUtf8ByteArray(str ) { + str = encodeURI(str); + let result = []; + for (let i = 0; i < str.length; i++) { + if (str.charAt(i) !== "%") + result.push(str.charCodeAt(i)); + else { + result.push(parseInt(str.substring(i + 1, i + 3), 16)); + i += 2; + } + } + return result; + } + + + /*-- Constants --*/ + + // Describes precisely all strings that are encodable in numeric mode. + static NUMERIC_REGEX = /^[0-9]*$/; + + // Describes precisely all strings that are encodable in alphanumeric mode. + static ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/; + + // The set of all legal characters in alphanumeric mode, + // where each character value maps to the index in the string. + static ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; + +} + + +/*---- Public helper enumeration ----*/ + +/* + * The error correction level in a QR Code symbol. Immutable. + */ +export class Ecc { + + /*-- Constants --*/ + + static LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords + static MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords + static QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords + static HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords + + + /*-- Constructor and fields --*/ + + ordinal ; + // (Package-private) In the range 0 to 3 (unsigned 2-bit integer). + formatBits ; + + constructor( + // In the range 0 to 3 (unsigned 2-bit integer). + ordinal , + formatBits ) { + this.ordinal = ordinal; + this.formatBits = formatBits; + } + +} + + +/*---- Public helper enumeration ----*/ + +/* + * Describes how a segment's data bits are interpreted. Immutable. + */ +export class Mode { + + /*-- Constants --*/ + + static NUMERIC = new Mode(0x1, [10, 12, 14]); + static ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]); + static BYTE = new Mode(0x4, [ 8, 16, 16]); + static KANJI = new Mode(0x8, [ 8, 10, 12]); + static ECI = new Mode(0x7, [ 0, 0, 0]); + + + /*-- Constructor and fields --*/ + + // The mode indicator bits, which is a uint4 value (range 0 to 15). + modeBits ; + // Number of character count bits for three different version ranges. + numBitsCharCount ; + + constructor( + modeBits , + numBitsCharCount ) { + this.modeBits = modeBits; + this.numBitsCharCount = numBitsCharCount; + } + + + /*-- Method --*/ + + // (Package-private) Returns the bit width of the character count field for a segment in + // this mode in a QR Code at the given version number. The result is in the range [0, 16]. + numCharCountBits(ver ) { + return this.numBitsCharCount[Math.floor((ver + 7) / 17)]; + } + +} + +// ---- End of vendored code ---- + + +/*---- Gentle Tower terminal QR API ----*/ + +/** A rendered QR Code: `modules` is the row-major bitmap, dark = true, `size * size` entries. */ + + + + + + + + +const ECL_NAMES = { 0: "L", 1: "M", 2: "Q", 3: "H" }; + +/** + * Encodes text at error correction level M, without boosting the level, so the + * printed matrix is stable for a given text. Throws RangeError when no QR Code + * can carry the text (the same error the vendored encoder raises). + */ +export function encodeQr(text ) { + const qr = QrCode.encodeSegments(QrSegment.makeSegments(text), Ecc.MEDIUM, 1, 40, -1, false); + const modules = []; + for (let y = 0; y < qr.size; y++) + for (let x = 0; x < qr.size; x++) + modules.push(qr.getModule(x, y)); + return { size: qr.size, version: qr.version, ecl: ECL_NAMES[qr.errorCorrectionLevel.ordinal], mask: qr.mask, modules }; +} + + + + + + +/** + * Renders a matrix as terminal lines of half blocks (" ", "▀", "▄", "█"): two + * module rows per line, one character per module column, quiet zone included. + * Dark-on-light as terminals draw; every line has the same width. + */ +export function renderQrTerminal(qr , options = {}) { + const quiet = options.quiet ?? 4; + const width = qr.size + quiet * 2; + const dark = (x , y ) => { + const mx = x - quiet, my = y - quiet; + return mx >= 0 && mx < qr.size && my >= 0 && my < qr.size && qr.modules[my * qr.size + mx]; + }; + const lines = []; + for (let y = 0; y < width; y += 2) { + let line = ""; + for (let x = 0; x < width; x++) { + const top = dark(x, y), bottom = dark(x, y + 1); + let glyph ; + if (top && bottom) glyph = "█"; + else if (top) glyph = "▀"; + else if (bottom) glyph = "▄"; + else glyph = " "; + line += glyph; + } + lines.push(line); + } + return lines; +} diff --git a/runtime/tower-server.mjs b/runtime/tower-server.mjs index 16ed42134..525ff1fca 100644 --- a/runtime/tower-server.mjs +++ b/runtime/tower-server.mjs @@ -1,11 +1,14 @@ // Generated by scripts/build-runtime-modules.mjs. Do not edit. // Gentle Tower web server: serves the built web app and the hub's floors. // Closed by default: 127.0.0.1 only, a random port, a per-launch token on every -// request, and any Origin other than its own is refused. Read-only for now: -// actions come later and reuse Gentle Shell's own authority. +// request, and any Origin other than its own is refused. The opt-in lan mode +// additionally serves the machine's LAN addresses, accepting only the origins +// of the hosts it launched with. Read-only for now: actions come later and +// reuse Gentle Shell's own authority. import { readFileSync, realpathSync, statSync } from "node:fs"; import { createServer, } from "node:http"; +import { networkInterfaces } from "node:os"; import { basename, dirname, extname, resolve, sep } from "node:path"; import { timingSafeEqual } from "node:crypto"; import { readLiveTowerSnapshots as readTowerSnapshots } from "./tower-hub.mjs"; @@ -28,6 +31,10 @@ import { parseTowerAction, TOWER_ACTION_MAX_BYTES, writeTowerAction } from "./to + + + + const ARTIFACT_TYPES = { ".md": "text/plain; charset=utf-8", ".markdown": "text/plain; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".mmd": "text/plain; charset=utf-8", ".mermaid": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif" }; const ARTIFACT_MAX_BYTES = 2 * 1024 * 1024; const MEMORY_MAX_BYTES = 512 * 1024; @@ -39,6 +46,13 @@ const MEMORY_MAX_BYTES = 512 * 1024; + + + + + + + const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".png": "image/png", ".svg": "image/svg+xml", ".woff2": "font/woff2", ".ico": "image/x-icon", @@ -56,11 +70,48 @@ function sameToken(given , token ) { return a.length === b.length && timingSafeEqual(a, b); } +function isPrivateIpv4(ip ) { + const o = ip.split(".").map(Number); + return o.length === 4 && (o[0] === 10 || (o[0] === 192 && o[1] === 168) || (o[0] === 172 && o[1] >= 16 && o[1] <= 31)); +} + +/** Private ranges first, then numeric order, so the first URL is the most likely home LAN address. */ +function compareLanIpv4(a , b ) { + const rank = (ip ) => (isPrivateIpv4(ip) ? 0 : 1); + if (rank(a) !== rank(b)) return rank(a) - rank(b); + const as = a.split(".").map(Number), bs = b.split(".").map(Number); + for (let i = 0; i < 4; i += 1) if (as[i] !== bs[i]) return (as[i] ?? 0) - (bs[i] ?? 0); + return a.localeCompare(b); +} + +/** The machine's non-internal IPv4 addresses, link-local 169.254.0.0/16 aside, private ranges first. */ +export function lanIpv4Addresses(interfaces ) { + const ips = new Set (); + for (const nics of Object.values(interfaces)) + for (const nic of nics ?? []) + if (nic.family === "IPv4" && !nic.internal && !nic.address.startsWith("169.254.")) ips.add(nic.address); + return [...ips].sort(compareLanIpv4); +} + +/** The `host` or `host:port` authorities a lan launch answers to, canonical for HTTP: on port 80 both the bare host and the explicit `:80` are approved (WHATWG URL serialization drops the default port); on any other port the authority always carries it. */ +export function lanAllowedHosts(lanIps , port ) { + const hosts = new Set (); + for (const host of ["127.0.0.1", "localhost", ...lanIps]) { + if (port === 80) { hosts.add(host); hosts.add(`${host}:80`); } + else hosts.add(`${host}:${port}`); + } + return hosts; +} + export function startTowerServer(options ) { const webRoot = realpathSync(options.webDir); const clients = new Set (); let lastBody = ""; const now = options.now ?? Date.now; + const lan = options.lan === true; + const lanIps = lan ? lanIpv4Addresses(options.interfaces ?? networkInterfaces()) : []; + /** The `host:port` values an Origin may name in lan mode; filled once the port is known. */ + let allowedHosts = new Set (); // Detailed floors (tower extension) win; every other live session joins as a basic floor. const LIVE = new Set(["queued", "running", "waiting"]); /** A snapshot this much older than the heartbeat has stopped updating. */ @@ -167,7 +218,15 @@ export function startTowerServer(options ) const handler = (req , res ) => { if (req.method !== "GET" && req.method !== "POST") return deny(res, 405); const origin = req.headers.origin; - if (origin && origin !== `http://127.0.0.1:${port}`) return deny(res); + if (lan) { + // Every request names the host it wants, even a navigation GET without an + // Origin: it must be one this launch answers to, so a rebinding Host is + // refused before the token or the page is even considered. The Origin, + // when a browser sends one, must name that same host. + const host = req.headers.host ?? ""; + if (!allowedHosts.has(host)) return deny(res); + if (origin && origin !== `http://${host}`) return deny(res); + } else if (origin && origin !== `http://127.0.0.1:${port}`) return deny(res); // A browser always sends Origin on POST; a missing one is not our page. if (req.method === "POST" && !origin) return deny(res); // The token is the first path segment, so every relative request the app @@ -213,14 +272,19 @@ export function startTowerServer(options ) return new Promise((resolveStart, reject) => { server.once("error", reject); - server.listen(options.port ?? 0, "127.0.0.1", () => { + server.listen(options.port ?? 0, lan ? "0.0.0.0" : "127.0.0.1", () => { const addr = server.address(); port = typeof addr === "object" && addr ? addr.port : 0; + if (lan) allowedHosts = lanAllowedHosts(lanIps, port); + const url = `http://127.0.0.1:${port}/${options.token}/`; lastBody = sessionsBody(); resolveStart({ - host: "127.0.0.1", + host: lan ? "0.0.0.0" : "127.0.0.1", port, - url: `http://127.0.0.1:${port}/${options.token}/`, + url, + lan, + urls: [url, ...lanIps.map((ip) => `http://${ip}:${port}/${options.token}/`)], + lanIps, close: () => new Promise ((done) => { clearInterval(poll); for (const c of clients) c.end(); diff --git a/scripts/build-runtime-modules.mjs b/scripts/build-runtime-modules.mjs index 1042b25dc..5c31e94f2 100644 --- a/scripts/build-runtime-modules.mjs +++ b/scripts/build-runtime-modules.mjs @@ -27,6 +27,7 @@ const sources = [ "design-canvas-assets", // `gentle-shell tower` runs the Gentle Tower server without Pi. "tower-snapshot", + "tower-qr", "tower-hub", "tower-presence", "tower-actions", diff --git a/scripts/verify-package-files.mjs b/scripts/verify-package-files.mjs index 5f702de84..fbd633c76 100644 --- a/scripts/verify-package-files.mjs +++ b/scripts/verify-package-files.mjs @@ -162,6 +162,7 @@ export const requiredPaths = [ "runtime/review-relay-contract.mjs", "runtime/telemetry-trigger.mjs", "runtime/tower-open.mjs", + "runtime/tower-qr.mjs", "runtime/sensitive-paths.mjs", "runtime/tower-server.mjs", "runtime/tower-hub.mjs", diff --git a/tests/fixtures/tower-qr/lan.json b/tests/fixtures/tower-qr/lan.json new file mode 100644 index 000000000..80f376b3c --- /dev/null +++ b/tests/fixtures/tower-qr/lan.json @@ -0,0 +1,43 @@ +{ + "name": "lan", + "text": "http://192.168.1.42:51730/kMp3xV7qR9tW2zB5nC8yH4jF6dS1gU/", + "version": 4, + "ecl": "M", + "mask": 2, + "size": 33, + "rows": [ + "#######..#..#.#....#..###.#######", + "#.....#.....#..#.##.##..#.#.....#", + "#.###.#.#..##.##....##.#..#.###.#", + "#.###.#.#...#..#.##.#.#...#.###.#", + "#.###.#.##..#.###...#.###.#.###.#", + "#.....#.#...##....#..#....#.....#", + "#######.#.#.#.#.#.#.#.#.#.#######", + "........##..#.#.#...##.##........", + "#.#####...##.##.###.#.....#####..", + ".....#.#.######.#..#...#####.####", + "#.#...###.#.#####.#..#......#.##.", + "#.##.#.#..#.##.##..#.##.#.#.#####", + ".##.#####..#..#.##.#.##.##..##.#.", + ".#.###.#..##.#.#..###....###..###", + "#..#########.#####....#.#...####.", + "##..#....##..#.#...###.#.#...##..", + "..##.##..#..####.##.#..#...####.#", + ".##.#...##....###..#..######.####", + "......###.####.###...#..#.#.#.#..", + "#..........##......#.#.#..#.###.#", + "###...#.#.###.#.....#..###...#.#.", + "#.#.........#..##..#.###......#.#", + "#.#...##.#..#.#..##..#....##...#.", + "#.#.##...##.###.#..####..#....##.", + "#..#..###..#.#...##.#...######..#", + "........#..#.#..#..#.#..#...#.##.", + "#######...##.#.##....####.#.#.##.", + "#.....#.#....##.#...##..#...#.#..", + "#.###.#.###.#.#..##...#.######..#", + "#.###.#.#..#.###..#.#......##..##", + "#.###.#.##..#..##.#...#.####.##..", + "#.....#..##.##..#.##.#.#...####..", + "#######.##.##....####...#.####.#." + ] +} diff --git a/tests/fixtures/tower-qr/long-path.json b/tests/fixtures/tower-qr/long-path.json new file mode 100644 index 000000000..c3bd61e76 --- /dev/null +++ b/tests/fixtures/tower-qr/long-path.json @@ -0,0 +1,51 @@ +{ + "name": "long-path", + "text": "http://192.168.1.42:51730/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678/", + "version": 6, + "ecl": "M", + "mask": 2, + "size": 41, + "rows": [ + "#######....###.##..##.##..#.#####.#######", + "#.....#.....#.##..#.#.#.#..###....#.....#", + "#.###.#.#####...#.........#.####..#.###.#", + "#.###.#.#.##.#....#####........#..#.###.#", + "#.###.#.#..#..#.....##...######.#.#.###.#", + "#.....#.#.###.#####........#..#.#.#.....#", + "#######.#.#.#.#.#.#.#.#.#.#.#.#.#.#######", + "........#.##.#.......#.##...#............", + "#.#####...#..########....#..#####.#####..", + "###.#...#####..#.#.#.#####...#.#.####.#.#", + ".#..###.#####.###.#.###.####.##.#......#.", + ".#.#....#.##.......###....#.#.#..#####.##", + "...##.#..#.#.##.#....##...##.....#..####.", + ".##.#...###..#.###..###.#.#####...###..##", + ".#.#########.##..###.##......##.#####.#..", + "#...#....##...##..#####.#...#..#######.##", + "#..#.##...#....######.#..##..#.#.#.#...#.", + "#.#.##.#.#.#.#.###.#####.##.#.#####.#..#.", + ".#.#..######.#..##...#...###..#.#...###..", + "#.#.#...#.#....####..#####..#....##.##...", + "...#..#.#....#.....###....#...##...#..##.", + "######...#.#####..#.#.#..#.##...##..#..##", + "##....#.#..#.#..#.#.#...#######....####..", + "...#.#.#....#.#...####.##..##.#...###..#.", + "##....#.#..#..##.##.#....#..#####....####", + "#.#.....#####.#..###.####.#..###.#####..#", + "#..#.##.#.######.##.###.#..####.#..##..#.", + "###.....###.#.###.#..###...#...##.####...", + "#..######..#.#.###..#####.###..#.#..####.", + "##..#..####.####..#..##...##.###..###..##", + "#...#.###...#...#.#.#.###..##.....#.###..", + "#.#.##.#.##...#...#..#.#..##..#...####...", + "#...####..#...##.##.#.##.###.#.######..#.", + "........##.#####...##.##..#.###.#...##.#.", + "#######...##.#.#..#.#.#.#..###.##.#.#....", + "#.....#.#.#.#####..##..##.#######...##..#", + "#.###.#.#..####.#.#.###.........#####.#.#", + "#.###.#.#....###.#..##....#####..#.#.#...", + "#.###.#.##...#....#..##....#.#..#####....", + "#.....#....#.#.....####.#.###.#.....#..#.", + "#######.#####.##.#..#...##..####..#####.." + ] +} diff --git a/tests/fixtures/tower-qr/loopback.json b/tests/fixtures/tower-qr/loopback.json new file mode 100644 index 000000000..153185117 --- /dev/null +++ b/tests/fixtures/tower-qr/loopback.json @@ -0,0 +1,43 @@ +{ + "name": "loopback", + "text": "http://127.0.0.1:51730/kMp3xV7qR9tW2zB5nC8yH4jF6dS1gU/", + "version": 4, + "ecl": "M", + "mask": 4, + "size": 33, + "rows": [ + "#######.##.##..#....#.###.#######", + "#.....#...#.#......#..#.#.#.....#", + "#.###.#....#.#...###.##.#.#.###.#", + "#.###.#.###.#.##....#...#.#.###.#", + "#.###.#.#.#..##...##...##.#.###.#", + "#.....#.#####...#.##....#.#.....#", + "#######.#.#.#.#.#.#.#.#.#.#######", + "........##....####.#####.........", + "#...#.####..#...####.#.#######..#", + "..####.#.#...#..###.##.##....##..", + ".#...####.#.#..##.#.#.##.#...#.#.", + "..##.....#.##.##########.#.....#.", + "...#####...#.###..###.#.#.####.#.", + "#...#..##..#....###..#...#...##..", + "#.##.##..#.#.##.#.#.#..##..#.#.#.", + "######.##.#####..##..###.#.##....", + "#.###.##..#..#.###.#.#.#.##.####.", + ".###....#.#.#.#####.#.###....##..", + ".#..####..##.###..#.#..#.##..#...", + "######.###..#.#.#....##.#.#.....#", + "####.##.#######.#..#.#.#..#..#.##", + "#.#..#.##...##...##.#.##.###.###.", + "..#.#####......#....####...#..##.", + "...#.#..###.#..#####.#.#..##.#..#", + "###.#.##.#.#..#.#..#.#.#######..#", + "........#..##..#..#.#.#.#...#.#.#", + "#######.#......###..#...#.#.##.#.", + "#.....#..####.#####.#####...##.#.", + "#.###.#.#.#.#.#...##.##.######.##", + "#.###.#....##.#.##.#.#.#.##.#.#..", + "#.###.#....#.##.###...#..######..", + "#.....#..###..#..##.###.#..#.....", + "#######.###.#.####.#.#..#...##..#" + ] +} diff --git a/tests/gentle-shell-launcher-tower.test.ts b/tests/gentle-shell-launcher-tower.test.ts index 988bbfb2d..41133dac8 100644 --- a/tests/gentle-shell-launcher-tower.test.ts +++ b/tests/gentle-shell-launcher-tower.test.ts @@ -1,11 +1,14 @@ import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { type NetworkInterfaceInfo, tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import test, { after } from "node:test"; import { helpText, parseLauncherArgs, parseTowerArgs } from "../lib/gentle-shell-launcher.ts"; +import { runTower } from "../lib/tower-open.ts"; +import { encodeQr, renderQrTerminal } from "../lib/tower-qr.ts"; +import { type TowerServer } from "../lib/tower-server.ts"; const binPath = fileURLToPath(new URL("../bin/gentle-shell.mjs", import.meta.url)); const packageRoot = dirname(dirname(binPath)); @@ -53,10 +56,20 @@ test("parseTowerArgs reads --json alone and with the other options", () => { assert.deepEqual(parseTowerArgs(["--json=yes"]), { open: true, error: 'unknown tower argument "--json=yes"' }); }); +test("parseTowerArgs reads --lan alone and with the other options", () => { + assert.deepEqual(parseTowerArgs(["--lan"]), { open: true, lan: true }); + assert.deepEqual(parseTowerArgs(["--no-open", "--lan", "--port=4242", "--json"]), { open: false, port: 4242, json: true, lan: true }); + assert.deepEqual(parseTowerArgs(["--lan=yes"]), { open: true, error: 'unknown tower argument "--lan=yes"' }); +}); + test("help text lists gentle-shell tower and its options", () => { const text = helpText(); - assert.ok(text.includes(" gentle-shell tower [--no-open] [--port ] [--json]")); + assert.ok(text.includes(" gentle-shell tower [--no-open] [--port ] [--json] [--lan]")); assert.match(text, /\n tower +Open the Gentle Tower/); + assert.match(text, /--port fixes the port \(127\.0\.0\.1 only,\n\s+unless --lan\)/); + assert.match(text, /--lan also binds every network interface, to open the view from a\n\s+phone on the same network/); + assert.ok(text.includes("one URL per address, a QR code and a warning")); + assert.ok(text.includes("--port then fixes the port on every interface")); }); test("existing subcommands still parse as before", () => { @@ -81,6 +94,78 @@ test("gentle-shell tower --port with a bad value fails with exit 2 and the error assert.equal(result.stderr, `gentle-shell tower: --port needs a whole number from 1 to 65535 (got "abc")\nRun 'gentle-shell --help' for usage.\n`); }); +// S7: the exact warning line every --lan report prints. +const LAN_WARNING = "LAN mode: anyone on this network who opens the URL can read and drive your sessions; traffic is not encrypted. Use it only on a trusted home network."; +const QR_BLOCKS = /[\u2580\u2584\u2588]/; + +function builtWeb(root: string): string { + const web = join(root, "web"); + mkdirSync(web, { recursive: true }); + writeFileSync(join(web, "index.html"), "Gentle Tower"); + return web; +} + +function towerEnv(root: string): NodeJS.ProcessEnv { + return { GENTLE_TOWER_HOME: join(root, "hub"), GENTLE_SHELL_NO_AUTO_SETUP: "1" }; +} + +// A fixed interface list, given before the tower starts: the report must name +// exactly these addresses, whatever the OS says by the time it is asserted. +const LAN_NIC: NetworkInterfaceInfo = { address: "192.168.0.2", netmask: "255.255.255.0", mac: "00:00:00:00:00:00", internal: false, cidr: null, family: "IPv4" }; +const LAN_INTERFACES: NodeJS.Dict = { en0: [LAN_NIC] }; + +const lanUrl = (server: TowerServer) => `http://192.168.0.2:${server.port}/${new URL(server.url).pathname.replaceAll("/", "")}/`; + +test("runTower --lan --json prints one line adding lan, urls and the warning", async () => { + const root = scratch(); + const out: string[] = [], err: string[] = [], opened: string[] = []; + let server: TowerServer | undefined; + const code = await runTower({ env: towerEnv(root), open: false, lan: true, json: true, webDir: builtWeb(root), presenceDirs: [], interfaces: LAN_INTERFACES, + stdout: (s) => out.push(s), stderr: (s) => err.push(s), openUrl: (u) => opened.push(u), + untilStopped: async (s) => { server = s; } }); + assert.equal(code, 0); + assert.ok(server); + assert.deepEqual(err, []); + assert.deepEqual(opened, []); + const text = out.join(""); + assert.ok(text.endsWith("\n") && !text.slice(0, -1).includes("\n"), "exactly one JSON line"); + assert.ok(!QR_BLOCKS.test(text), "no QR in JSON mode"); + const parsed = JSON.parse(text) as Record; + assert.deepEqual(Object.keys(parsed), ["schema", "url", "host", "port", "lan", "urls", "warning"]); + assert.equal(parsed.schema, "gentle-shell.tower/v1"); + assert.equal(parsed.url, server.url); + assert.equal(parsed.host, "0.0.0.0"); + assert.equal(parsed.port, server.port); + assert.equal(parsed.lan, true); + assert.equal(parsed.warning, LAN_WARNING); + assert.deepEqual(parsed.urls, [server.url, lanUrl(server)]); +}); + +test("runTower --lan prints every LAN URL, the QR of the first and the warning", async () => { + const root = scratch(); + const out: string[] = [], err: string[] = [], opened: string[] = []; + let server: TowerServer | undefined; + const code = await runTower({ env: towerEnv(root), open: true, lan: true, webDir: builtWeb(root), presenceDirs: [], interfaces: LAN_INTERFACES, + stdout: (s) => out.push(s), stderr: (s) => err.push(s), openUrl: (u) => opened.push(u), + untilStopped: async (s) => { + server = s; + assert.equal(s.host, "0.0.0.0"); + assert.equal(s.lan, true); + } }); + assert.equal(code, 0); + assert.ok(server); + assert.deepEqual(err, []); + // The browser still opens the loopback URL, exactly as today. + assert.deepEqual(opened, [server.url]); + const lanUrls = [lanUrl(server)]; + assert.deepEqual(server.urls, [server.url, ...lanUrls]); + const lines = [`Gentle Tower: ${server.url}`, ...lanUrls.map((u) => ` ${u}`)]; + for (const line of renderQrTerminal(encodeQr(lanUrls[0]))) lines.push(` ${line}`); + lines.push(LAN_WARNING, "Press Ctrl+C to stop."); + assert.equal(out.join(""), `${lines.join("\n")}\n`); + assert.ok(QR_BLOCKS.test(out.join("")), "the QR of the first LAN address is printed"); +}); + const built = existsSync(join(packageRoot, "web", "tower", "dist", "index.html")); test("gentle-shell tower --no-open serves until SIGINT, then exits 0", { skip: built ? false : "web/tower/dist is not built" }, async (t) => { const child = spawn(process.execPath, [binPath, "tower", "--no-open"], { env: isolatedEnv(scratch()), stdio: ["ignore", "pipe", "pipe"] }); diff --git a/tests/gentle-tower.test.ts b/tests/gentle-tower.test.ts index 49fb5aa5d..12e6aad99 100644 --- a/tests/gentle-tower.test.ts +++ b/tests/gentle-tower.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; +import { type NetworkInterfaceInfo, tmpdir } from "node:os"; import { join } from "node:path"; import test, { after } from "node:test"; import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; @@ -121,6 +121,11 @@ function uiCtx(messages: string[]): ExtensionContext { return { ...fakeCtx([]), ui: { notify: (m: string) => messages.push(m) } } as unknown as ExtensionContext; } +// A fixed interface list for the LAN reports: the assertions must name exactly +// these addresses, whatever the OS says by the time they run. +const TUI_LAN_NIC: NetworkInterfaceInfo = { address: "192.168.0.2", netmask: "255.255.255.0", mac: "00:00:00:00:00:00", internal: false, cidr: null, family: "IPv4" }; +const TUI_LAN_INTERFACES: NodeJS.Dict = { en0: [TUI_LAN_NIC] }; + test("/gentle:tower opens the local tower once and reuses it", async () => { const dir = hub(); const web = join(dir, "..", "web"); @@ -139,6 +144,9 @@ test("/gentle:tower opens the local tower once and reuses it", async () => { assert.equal(opened[0], opened[1]); assert.match(opened[0], /^http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_-]{32,}\/$/); assert.match(messages[0], /Gentle Tower: http:\/\/127\.0\.0\.1/); + // Without the flag the report stays byte-identical: one line, the loopback URL. + assert.equal(messages[0], `Gentle Tower: ${opened[0]}`); + assert.equal(messages[1], messages[0]); await tower?.close(); }); @@ -153,6 +161,83 @@ test("/gentle:tower explains when the web app is not built", async () => { assert.match(messages[0], /web app is not built/); }); +test("/gentle:tower --lan reports the LAN URLs and the warning, without QR art", async () => { + const dir = hub(); + const web = join(dir, "..", "web"); + (await import("node:fs")).mkdirSync(web, { recursive: true }); + (await import("node:fs")).writeFileSync(join(web, "index.html"), "Gentle Tower"); + const { pi, commands } = commandPi(); + const opened: string[] = []; + // A fixed interface list, given before the tower starts: the report must + // name exactly these addresses, whatever the OS says by now. + const tower = createTowerPublisher(pi, { env: { GENTLE_TOWER_HOME: dir }, debounceMs: 0, webDir: web, interfaces: TUI_LAN_INTERFACES, openUrl: (u) => opened.push(u) }); + const messages: string[] = []; + await commands.get("gentle:tower")!.handler("--lan", uiCtx(messages)); + const lines = messages[0].split("\n"); + assert.match(lines[0], /^Gentle Tower: http:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9_-]{32,}\/$/); + // The browser still opens the loopback URL, and the report carries every LAN URL. + assert.deepEqual(opened, [lines[0].slice("Gentle Tower: ".length)]); + assert.deepEqual(lines.slice(1, 2), [` http://192.168.0.2:${new URL(lines[0].slice("Gentle Tower: ".length)).port}/${new URL(lines[0].slice("Gentle Tower: ".length)).pathname.replaceAll("/", "")}/`]); + // One loopback line, one per LAN address, the warning last; the TUI notify box cannot carry QR art. + assert.equal(lines.length, 3); + assert.equal(lines[lines.length - 1], "LAN mode: anyone on this network who opens the URL can read and drive your sessions; traffic is not encrypted. Use it only on a trusted home network."); + assert.ok(!/[\u2580\u2584\u2588]/.test(messages[0]), "no QR blocks in the TUI notify"); + await tower?.close(); +}); + +test("/gentle:tower replaces the tower when the mode changes, in both orders", async () => { + const dir = hub(); + const web = join(dir, "..", "web"); + (await import("node:fs")).mkdirSync(web, { recursive: true }); + (await import("node:fs")).writeFileSync(join(web, "index.html"), "Gentle Tower"); + const { pi, commands } = commandPi(); + const opened: string[] = []; + const tower = createTowerPublisher(pi, { env: { GENTLE_TOWER_HOME: dir }, debounceMs: 0, webDir: web, interfaces: TUI_LAN_INTERFACES, openUrl: (u) => opened.push(u) }); + const messages: string[] = []; + // Loopback first: one line, the loopback URL. + await commands.get("gentle:tower")!.handler("", uiCtx(messages)); + assert.equal(messages[0], `Gentle Tower: ${opened[0]}`); + // Same mode reuses the server: the same URL, the same one-line report. + await commands.get("gentle:tower")!.handler("", uiCtx(messages)); + assert.equal(messages[1], messages[0]); + assert.equal(opened.length, 2); + // Asking for the network mode replaces the tower: a new URL, LAN lines and the warning. + await commands.get("gentle:tower")!.handler("--lan", uiCtx(messages)); + assert.notEqual(opened[2], opened[0], "a mode change starts a new server"); + assert.equal(messages[2].split("\n").length, 3); + assert.match(messages[2], /http:\/\/192\.168\.0\.2:/); + assert.match(messages[2], /LAN mode: anyone on this network/); + // And back to loopback: replaced again, one line, no LAN, no warning. + await commands.get("gentle:tower")!.handler("", uiCtx(messages)); + assert.notEqual(opened[3], opened[2], "a mode change starts a new server"); + assert.equal(messages[3], `Gentle Tower: ${opened[3]}`); + await tower?.close(); +}); + +test("/gentle:tower-mobile serves the network mode and reuses it on repeat", async () => { + const dir = hub(); + const web = join(dir, "..", "web"); + (await import("node:fs")).mkdirSync(web, { recursive: true }); + (await import("node:fs")).writeFileSync(join(web, "index.html"), "Gentle Tower"); + const { pi, commands } = commandPi(); + const opened: string[] = []; + const tower = createTowerPublisher(pi, { env: { GENTLE_TOWER_HOME: dir }, debounceMs: 0, webDir: web, interfaces: TUI_LAN_INTERFACES, openUrl: (u) => opened.push(u) }); + const mobile = commands.get("gentle:tower-mobile"); + assert.ok(mobile, "command registered"); + assert.match(mobile.description ?? "", /phone/i); + const messages: string[] = []; + await mobile.handler("", uiCtx(messages)); + assert.equal(messages[0].split("\n").length, 3); + assert.match(messages[0], /http:\/\/192\.168\.0\.2:/); + assert.match(messages[0], /LAN mode: anyone on this network/); + // Same mode as /gentle:tower --lan: the same server is reused (the browser still opens it again). + await commands.get("gentle:tower")!.handler("--lan", uiCtx(messages)); + assert.equal(messages[1], messages[0]); + assert.equal(opened.length, 2); + assert.equal(opened[1], opened[0], "the same server is reused"); + await tower?.close(); +}); + // ---------- T5: actions requested from the web view ---------- import { writeTowerAction } from "../lib/tower-actions.ts"; import { DESKTOP_AGENTS_SERVICE_SCHEMA } from "../lib/desktop-rpc-agents.ts"; diff --git a/tests/tower-lan.test.ts b/tests/tower-lan.test.ts new file mode 100644 index 000000000..4afa1105a --- /dev/null +++ b/tests/tower-lan.test.ts @@ -0,0 +1,169 @@ +// LAN mode of the Gentle Tower server (`gentle-shell tower --lan`): the +// opt-in contract on top of the default loopback-only server, pinned through +// the public interface the other tower tests use (startTowerServer + HTTP). + +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { request } from "node:http"; +import { type NetworkInterfaceInfo, tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; +import { lanAllowedHosts, lanIpv4Addresses, startTowerServer, type TowerServer } from "../lib/tower-server.ts"; + +const roots: string[] = []; +const servers: TowerServer[] = []; +after(async () => { + for (const s of servers) await s.close(); + for (const r of roots) rmSync(r, { recursive: true, force: true }); +}); + +function scratch() { + const root = mkdtempSync(join(tmpdir(), "gentle-tower-lan-")); + roots.push(root); + const hub = join(root, "sessions"); + const web = join(root, "web"); + mkdirSync(web); + writeFileSync(join(web, "index.html"), "Gentle Tower"); + return { root, hub, web }; +} + +/** One HTTP call with full control of the Host header (fetch forbids setting it). */ +function call(host: string, port: number, path: string, method: "GET" | "POST" = "GET", headers: Record = {}, body?: string): Promise<{ status: number; body: string }> { + return new Promise((resolve, reject) => { + const req = request({ host, port, path, method, headers }, (res) => { + let b = ""; + res.on("data", (c) => (b += c)); + res.on("end", () => resolve({ status: res.statusCode ?? 0, body: b })); + }); + req.on("error", reject); + req.end(body); + }); +} + +async function start(hub: string, web: string, lan = false, interfaces?: NodeJS.Dict) { + const s = await startTowerServer({ hubDir: hub, webDir: web, token: "tok-123", ...(lan ? { lan: true } : {}), ...(interfaces ? { interfaces } : {}) }); + servers.push(s); + return s; +} + +const nic = (address: string, internal = false): NetworkInterfaceInfo => ({ address, netmask: "255.255.255.0", mac: "00:00:00:00:00:00", internal, cidr: null, family: "IPv4" }); +const nic6 = (address: string): NetworkInterfaceInfo => ({ address, netmask: "ffff:ffff:ffff:ffff::", mac: "00:00:00:00:00:00", internal: false, cidr: null, family: "IPv6", scopeid: 1 }); + +test("the LAN enumeration keeps private ranges first and drops internal, link-local and IPv6 addresses", () => { + assert.deepEqual(lanIpv4Addresses({ + lo0: [nic("127.0.0.1", true)], + en0: [nic("203.0.113.7"), nic("192.168.1.5"), nic("192.168.1.5")], + en1: [nic("169.254.4.2"), nic("10.0.0.9"), nic("172.20.1.3"), nic("172.32.0.1")], + en2: [nic6("fe80::1"), nic6("2001:db8::3")], + }), ["10.0.0.9", "172.20.1.3", "192.168.1.5", "172.32.0.1", "203.0.113.7"]); + assert.deepEqual(lanIpv4Addresses({}), []); +}); + +test("without lan the server stays loopback-only and urls holds just the loopback URL", async () => { + const { hub, web } = scratch(); + const s = await start(hub, web); + assert.equal(s.lan, false); + assert.equal(s.host, "127.0.0.1"); + assert.deepEqual(s.lanIps, []); + assert.deepEqual(s.urls, [`http://127.0.0.1:${s.port}/tok-123/`]); + assert.equal(s.url, s.urls[0]); + // The default origin rule is unchanged: localhost is not added to it. + assert.equal((await call("127.0.0.1", s.port, "/tok-123/api/sessions", "GET", { Origin: `http://localhost:${s.port}` })).status, 403); + assert.equal((await call("127.0.0.1", s.port, "/tok-123/api/sessions", "GET", { Origin: `http://127.0.0.1:${s.port}` })).status, 200); +}); + +test("the LAN host allowlist uses canonical HTTP authorities", () => { + // On port 80 a browser serializes http:// without the default port, so + // both spellings are approved; anywhere else the authority carries the port. + const port80 = lanAllowedHosts(["192.168.1.3"], 80); + assert.ok(port80.has("192.168.1.3") && port80.has("192.168.1.3:80")); + assert.ok(port80.has("127.0.0.1") && port80.has("localhost") && port80.has("localhost:80")); + assert.ok(!port80.has("evil.example") && !port80.has("192.168.1.3:8080")); + const lanPort = lanAllowedHosts(["192.168.1.3"], 51730); + assert.ok(lanPort.has("192.168.1.3:51730")); + assert.ok(!lanPort.has("192.168.1.3") && !lanPort.has("192.168.1.3:80")); +}); + +test("with lan the server reports one URL per LAN address after the loopback URL", async () => { + const { hub, web } = scratch(); + // A fixed interface list, given before the server starts: the report must + // come from exactly these addresses, whatever the OS says by now. + const s = await start(hub, web, true, { en0: [nic("192.168.0.2")], lo0: [nic("127.0.0.1", true)] }); + assert.equal(s.lan, true); + assert.equal(s.host, "0.0.0.0"); + assert.deepEqual(s.lanIps, ["192.168.0.2"]); + assert.deepEqual(s.urls, ["http://127.0.0.1:" + s.port + "/tok-123/", `http://192.168.0.2:${s.port}/tok-123/`]); + // Loopback keeps working as before. + assert.equal((await call("127.0.0.1", s.port, "/tok-123/")).status, 200); +}); + +test("with lan an Origin-less GET names a host this launch must answer to", async () => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + // A navigation GET can omit Origin: the Host allowlist still applies, so a + // rebinding host cannot fetch the app even with a valid token. + const denied = await call("127.0.0.1", s.port, "/tok-123/", "GET", { Host: `evil.example:${s.port}` }); + assert.deepEqual([denied.status, denied.body], [403, "Forbidden"]); + // An approved host without an Origin still serves the app. + assert.equal((await call("127.0.0.1", s.port, "/tok-123/", "GET", { Host: `127.0.0.1:${s.port}` })).status, 200); + assert.equal((await call("127.0.0.1", s.port, "/tok-123/", "GET", { Host: `localhost:${s.port}` })).status, 200); +}); + +test("with lan the token still gates every request as before", async () => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + assert.equal((await call("127.0.0.1", s.port, "/tok-123/")).status, 200); + for (const path of ["/", "/wrong/"]) { + const denied = await call("127.0.0.1", s.port, path); + assert.deepEqual([path, denied.status, denied.body], [path, 403, "Forbidden"]); + } +}); + +test("with lan the token-gated app is served through a LAN address", async (t) => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + const ip = s.lanIps[0]; + if (ip === undefined) return t.skip("this machine has no non-internal IPv4 address"); + assert.equal((await call(ip, s.port, "/tok-123/")).status, 200); + const denied = await call(ip, s.port, "/wrong/"); + assert.deepEqual([denied.status, denied.body], [403, "Forbidden"]); +}); + +test("with lan an Origin is accepted only on a host this launch serves", async () => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + const p = s.port; + const path = "/tok-123/api/sessions"; + // The loopback and localhost hosts carry their own origin. + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `127.0.0.1:${p}`, Origin: `http://127.0.0.1:${p}` })).status, 200); + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `localhost:${p}`, Origin: `http://localhost:${p}` })).status, 200); + // A foreign origin never passes. + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `127.0.0.1:${p}`, Origin: "http://evil.example" })).status, 403); + // DNS rebinding: the Host spells a matching origin but is not one this launch serves. + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `evil.example:${p}`, Origin: `http://evil.example:${p}` })).status, 403); + // The origin must match the host it arrives on. + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `localhost:${p}`, Origin: `http://127.0.0.1:${p}` })).status, 403); +}); + +test("with lan a LAN host serves its own origin and refuses a loopback origin", async (t) => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + const ip = s.lanIps[0]; + if (ip === undefined) return t.skip("this machine has no non-internal IPv4 address"); + const p = s.port; + const path = "/tok-123/api/sessions"; + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `${ip}:${p}`, Origin: `http://${ip}:${p}` })).status, 200); + assert.equal((await call("127.0.0.1", p, path, "GET", { Host: `${ip}:${p}`, Origin: `http://127.0.0.1:${p}` })).status, 403); +}); + +test("with lan POST keeps the browser rules: own origin in, missing origin out", async () => { + const { hub, web } = scratch(); + const s = await start(hub, web, true); + const p = s.port; + const denied = await call("127.0.0.1", p, "/tok-123/api/action", "POST", { "Content-Type": "application/json" }, "{}"); + assert.deepEqual([denied.status, denied.body], [403, "Forbidden"]); + // With the page's own origin the request reaches the action parser, which + // refuses this body with 400 — proof the origin gate let it through. + const parsed = await call("127.0.0.1", p, "/tok-123/api/action", "POST", { Host: `127.0.0.1:${p}`, Origin: `http://127.0.0.1:${p}`, "Content-Type": "application/json" }, "{nope"); + assert.deepEqual([parsed.status, parsed.body], [400, "Bad request"]); +}); diff --git a/tests/tower-qr.test.ts b/tests/tower-qr.test.ts new file mode 100644 index 000000000..658d9f8c6 --- /dev/null +++ b/tests/tower-qr.test.ts @@ -0,0 +1,103 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import test from "node:test"; +import { encodeQr, renderQrTerminal, type QrMatrix } from "../lib/tower-qr.ts"; + +// The fixtures in tests/fixtures/tower-qr/ pin the module matrix encodeQr() +// returns for the three Gentle Tower URL shapes (loopback, LAN address, and a +// 63-character path). Each fixture was decoded back to its URL by an +// independent decoder (jsQR) in a scratch directory outside the repository, +// with the module matrix scaled to raw RGBA pixels; the observation is +// recorded in the task log. `#` is a dark module, `.` a light one. + +const fixturesDir = new URL("../tests/fixtures/tower-qr/", import.meta.url); +interface Fixture { name: string; text: string; version: number; ecl: string; mask: number; size: number; rows: string[] } +const fixtures: Fixture[] = readdirSync(fixturesDir).filter((f) => f.endsWith(".json")).sort().map((f) => JSON.parse(readFileSync(new URL(f, fixturesDir), "utf8")) as Fixture); + +const HALF_BLOCKS = new Set([" ", "▀", "▄", "█"]); + +/** Reads the half-block terminal lines back into module rows (dark = true), quiet zone removed. */ +function modulesFromLines(lines: string[], quiet: number): boolean[][] { + const width = lines[0].length - 2 * quiet; + const rows: boolean[][] = []; + for (let y = 0; y < lines.length * 2; y++) { + const line = lines[Math.floor(y / 2)]; + const top = y % 2 === 0; + const row: boolean[] = []; + for (let x = 0; x < width; x++) { + const glyph = line[x + quiet]; + row.push(glyph === "█" || (top ? glyph === "▀" : glyph === "▄")); + } + rows.push(row); + } + return rows.slice(quiet, quiet + width); +} + +test("the three URL fixtures are present and are tower URLs", () => { + assert.deepEqual(fixtures.map((f) => f.name), ["lan", "long-path", "loopback"]); + for (const f of fixtures) { + assert.match(f.text, /^http:\/\/[0-9.]+:[0-9]+\/[A-Za-z0-9_-]+\/$/); + assert.equal(f.ecl, "M"); + assert.equal(f.size, f.version * 4 + 17); + assert.equal(f.rows.length, f.size); + assert.ok(f.rows.every((r) => r.length === f.size && /^[#.]+$/.test(r))); + } + assert.match(fixtures.find((f) => f.name === "loopback")!.text, /^http:\/\/127\.0\.0\.1:/); + assert.match(fixtures.find((f) => f.name === "lan")!.text, /^http:\/\/192\.168\./); + const long = fixtures.find((f) => f.name === "long-path")!; + assert.equal(new URL(long.text).pathname.length, 63, "the path (with both slashes) is 63 characters"); +}); + +test("encodeQr pins the module matrix of every fixture at error correction level M", () => { + for (const f of fixtures) { + const qr = encodeQr(f.text); + assert.deepEqual([qr.size, qr.version, qr.ecl, qr.mask], [f.size, f.version, f.ecl, f.mask], f.name); + assert.equal(qr.modules.length, f.size * f.size); + const rows = Array.from({ length: f.size }, (_, y) => Array.from({ length: f.size }, (_, x) => (qr.modules[y * f.size + x] ? "#" : ".")).join("")); + assert.deepEqual(rows, f.rows, f.name); + } +}); + +test("the longest possible tower URL still fits at level M under version 10", () => { + // 7 + "255.255.255.255:65535" (21) + a 63-character path = 91 characters. + const text = `http://255.255.255.255:65535/${"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".slice(0, 61)}/`; + assert.equal(text.length, 91); + const qr = encodeQr(text); + assert.equal(qr.ecl, "M"); + assert.ok(qr.version <= 10, `version ${qr.version}`); + assert.equal(qr.size, qr.version * 4 + 17); +}); + +test("encodeQr refuses text that no QR Code can carry", () => { + assert.throws(() => encodeQr("x".repeat(4000)), RangeError); +}); + +test("renderQrTerminal draws half blocks with a four-module quiet zone and the fixture's modules", () => { + for (const f of fixtures) { + const qr: QrMatrix = { ...encodeQr(f.text) }; + const lines = renderQrTerminal(qr); + const width = f.size + 8; + assert.equal(lines.length, Math.ceil((f.size + 8) / 2), f.name); + for (const line of lines) { + assert.equal(line.length, width, f.name); + assert.ok([...line].every((g) => HALF_BLOCKS.has(g)), `${f.name}: only space, ▀, ▄, █`); + } + // The quiet zone: four light module rows on every side. + assert.equal(lines[0].trim(), "", `${f.name}: top quiet rows`); + assert.equal(lines[1].trim(), "", `${f.name}: top quiet rows`); + assert.equal(lines[lines.length - 1].trim(), "", `${f.name}: bottom quiet row`); + assert.ok(lines.every((l) => l.startsWith(" ") && l.endsWith(" ")), `${f.name}: side quiet columns`); + // The symbol itself: the finder pattern's dark ring starts at module (4, 4) of the padded grid. + assert.equal(lines[2][4], "█", `${f.name}: the top-left finder's corner is dark`); + assert.deepEqual(modulesFromLines(lines, 4), f.rows.map((r) => [...r].map((c) => c === "#")), f.name); + } +}); + +test("a rendered QR keeps its modules when the quiet zone width changes", () => { + const f = fixtures.find((x) => x.name === "loopback")!; + const qr = encodeQr(f.text); + const lines = renderQrTerminal(qr, { quiet: 6 }); + assert.equal(lines.length, Math.ceil((f.size + 12) / 2)); + assert.ok(lines.every((l) => l.length === f.size + 12 && l.startsWith(" ") && l.endsWith(" "))); + assert.deepEqual(modulesFromLines(lines, 6), f.rows.map((r) => [...r].map((c) => c === "#")), f.name); +}); diff --git a/tests/tower-responsive.test.ts b/tests/tower-responsive.test.ts new file mode 100644 index 000000000..3d39513b5 --- /dev/null +++ b/tests/tower-responsive.test.ts @@ -0,0 +1,58 @@ +// Pins the mobile layout rules of the Gentle Tower web app through the pure +// functions web/tower/src/layout.ts exports (no browser needed). + +import assert from "node:assert/strict"; +import test from "node:test"; +import { FH, fitBuilding, SCENE_W, sheetWinner, SHEET_MAX_WIDTH, useBottomSheet } from "../web/tower/src/layout.ts"; + +test("useBottomSheet is on at or below 720 CSS px and for coarse pointers", () => { + assert.equal(useBottomSheet(390, false), true); + assert.equal(useBottomSheet(720, false), true); + assert.equal(useBottomSheet(721, false), false); + assert.equal(useBottomSheet(768, false), false); + assert.equal(useBottomSheet(768, true), true, "an iPad-width coarse pointer still gets the sheet"); + assert.equal(useBottomSheet(1440, true), true, "a coarse pointer on a big screen is still touch"); + assert.equal(useBottomSheet(1440, false), false); + assert.equal(SHEET_MAX_WIDTH, 720); +}); + +test("fitBuilding scales the building to the phone width and keeps floors tappable", () => { + const phone = fitBuilding(390, 844, 4); + assert.ok(Math.abs(phone.scale - 390 / SCENE_W) < 1e-9, "the building fits the viewport width"); + assert.ok(phone.floorHeight >= 44, `floor height ${phone.floorHeight} is a large enough tap target`); + assert.ok(Number.isFinite(phone.contentHeight) && phone.contentHeight > 0); + assert.ok(phone.contentHeight >= phone.floorHeight * 4); +}); + +test("fitBuilding never shrinks a floor below 44 CSS px, whatever the width", () => { + for (const width of [200, 280, 320, 360, 390, 414, 480, 540, 720]) { + const f = fitBuilding(width, 844, 2); + assert.ok(f.floorHeight >= 44, `${width}px: floor height ${f.floorHeight}`); + assert.ok(Number.isFinite(f.scale) && f.scale > 0); + } +}); + +test("sheetWinner gives the shared bottom area to the panel opened last, Talk when unknown", () => { + assert.equal(sheetWinner("tasks"), "tasks"); + assert.equal(sheetWinner("talk"), "talk"); + // The explicit fallback for a resize into sheet mode before anything was tracked. + assert.equal(sheetWinner(undefined), "talk"); +}); + +test("fitBuilding keeps the desktop behavior unchanged at 720px and up", () => { + // Today: scale = max(1, width / 720); the mobile path must not change it. + for (const [width, height] of [[720, 900], [768, 1024], [1024, 768], [1440, 900], [2560, 1440]] as const) { + const f = fitBuilding(width, height, 3); + assert.ok(Math.abs(f.scale - Math.max(1, width / SCENE_W)) < 1e-9, `${width}px keeps the desktop scale`); + assert.ok(f.floorHeight === FH * f.scale); + } +}); + +test("fitBuilding grows the content height with the floors and the viewport", () => { + const few = fitBuilding(390, 844, 2), many = fitBuilding(390, 844, 30); + assert.ok(many.contentHeight > few.contentHeight, "thirty floors need more height than two"); + assert.ok(many.contentHeight >= 30 * 44, "every floor keeps its tap height in the content"); + const short = fitBuilding(390, 400, 4), tall = fitBuilding(390, 1200, 4); + assert.ok(tall.contentHeight > short.contentHeight, "a taller viewport grows the sky"); + for (const f of [few, many, short, tall]) assert.ok(Number.isFinite(f.contentHeight) && f.contentHeight > 0); +}); diff --git a/web/tower/src/layout.ts b/web/tower/src/layout.ts new file mode 100644 index 000000000..97966be0a --- /dev/null +++ b/web/tower/src/layout.ts @@ -0,0 +1,64 @@ +// Mobile layout rules of the Gentle Tower web app, as pure functions so a +// node test can pin them without a browser (tests/tower-responsive.test.ts). +// The scene constants mirror web/tower/src/art.ts, which cannot be imported +// here because it touches `document` at module load; keep them in sync. + +/** The scene's width in scene units; the building spans x 172..688 inside it. */ +export const SCENE_W = 720; +/** One floor's height in scene units (art.ts FH). */ +export const FH = 100; +/** The lobby strip under the floors (art.ts LOBBY_H). */ +export const LOBBY_H = 66; +/** At or below this CSS width, or with a coarse pointer, panels become a bottom sheet. */ +export const SHEET_MAX_WIDTH = 720; +/** The smallest floor tap target we accept, in CSS pixels. */ +export const MIN_FLOOR_CSS = 44; +/** The collapsed bottom sheet (its tab row) reserve, in CSS pixels. */ +export const SHEET_RESERVE = 72; + +export interface BuildingFit { + /** CSS pixels per scene unit; the canvas is displayed at SCENE_W * scale. */ + scale: number; + /** One floor's height in CSS pixels; never below MIN_FLOOR_CSS. */ + floorHeight: number; + /** The scene's full height in CSS pixels at this scale. */ + contentHeight: number; +} + +/** + * Fits the building to a viewport. At 720px and up this is exactly today's + * desktop rule (scale never below 1); below it the building shrinks to the + * width, with the floor height's 44px minimum taking precedence over fitting + * (a sub-320px viewport crops the sky rather than the tap targets). The + * content height follows the scene's own stacking: the lobby grows with the + * floors and the sky fills the height it is given, so the page scrolls when + * the floors do not fit the viewport. + */ +export function fitBuilding(width: number, height: number, floorCount: number): BuildingFit { + const scale = width >= SCENE_W ? Math.max(1, width / SCENE_W) : Math.max(width / SCENE_W, MIN_FLOOR_CSS / FH); + const floorHeight = FH * scale; + const sceneUnits = Math.max(height / scale - 32 - LOBBY_H, 60 + floorCount * FH); + return { scale, floorHeight, contentHeight: (sceneUnits + LOBBY_H + 32) * scale }; +} + +/** Whether the panels render as a bottom sheet: a narrow viewport or a touch screen. */ +export function useBottomSheet(width: number, coarsePointer: boolean): boolean { + return width <= SHEET_MAX_WIDTH || coarsePointer; +} + +/** The height reserve for the collapsed sheet, for callers sizing the scene. */ +export function sheetReserve(width: number, coarsePointer: boolean): number { + return useBottomSheet(width, coarsePointer) ? SHEET_RESERVE : 0; +} + +/** The two panels that share the bottom sheet's area: the task list and the intercom. */ +export type SheetPanel = "tasks" | "talk"; + +/** + * Which of the two shared panels keeps the bottom sheet: the one the user opened + * last, and Talk when nothing was tracked (an explicit choice, so a resize into + * sheet mode always leaves exactly one panel in the shared area). + */ +export function sheetWinner(last: SheetPanel | undefined): SheetPanel { + return last ?? "talk"; +} diff --git a/web/tower/src/main.ts b/web/tower/src/main.ts index 84e8ed24b..c7d71eb6b 100644 --- a/web/tower/src/main.ts +++ b/web/tower/src/main.ts @@ -2,6 +2,7 @@ import "pixi.js/unsafe-eval"; import "./style.css"; import { floorTop } from "./art"; +import { fitBuilding, sheetReserve, sheetWinner, useBottomSheet, type SheetPanel } from "./layout"; import { FLOOR_COLORS, floorState, groupProjects, money, todoProgress } from "./model"; import { TowerScene, type Pick } from "./scene"; import { closeIntercom, closeModals, intercomSession, openArtifact, openArtifacts, openLibrary, openNewFloor, openTab, postAction, renderIntercom } from "./panels"; @@ -15,6 +16,8 @@ let current = ""; // Panels follow a session, not a floor number: floors reorder and sessions come and go. let selected: Pick | undefined; let todoSession: string | undefined; +/** The bottom sheet's shared area belongs to the panel opened last (Talk and Tasks cannot share it). */ +let lastPanel: SheetPanel | undefined; let scale = 2; const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!); @@ -34,7 +37,7 @@ function renderProjects() { const need = p.sessions.filter((s) => floorState(s) === "need").length; return ``; }).join(""); - el.querySelectorAll("button").forEach((b) => b.addEventListener("click", () => { current = b.dataset.cwd!; selected = undefined; todoSession = undefined; render(); })); + for (const b of el.querySelectorAll("button")) b.addEventListener("click", () => { current = b.dataset.cwd!; selected = undefined; todoSession = undefined; render(); }); } function renderFloors(p: Project) { @@ -43,19 +46,39 @@ function renderFloors(p: Project) { el.innerHTML = p.sessions.map((s, i) => { const st = floorState(s), col = FLOOR_COLORS[i % FLOOR_COLORS.length], prog = todoProgress(s.todos); const crew = s.subagents.map((a) => a.name).join(", ") || "no helpers"; + // On touch the scene's helpers are too small and too close to tap; these chips + // are the accessible way to select one (details and stop live in the selection panel). + const crewChips = s.subagents.map((a) => ``).join(""); const segs = s.todos.filter((t) => t.status !== "dropped").map((t) => ``).join(""); - const now = prog.now ? `${prog.now.status === "blocked" ? 'blocked:' : "now:"} ${esc(prog.now.title)}` : prog.total ? "all done" : "no task list yet"; + let now: string; + if (prog.now) now = `${prog.now.status === "blocked" ? 'blocked:' : "now:"} ${esc(prog.now.title)}`; + else if (prog.total) now = "all done"; + else now = "no task list yet"; return `
- + + ${s.basic || !crewChips ? "" : `
${crewChips}
`} ${s.basic ? `
Details need the tower in this session
` : ``}
`; }).join(""); - el.querySelectorAll(".fl").forEach((b) => b.addEventListener("click", () => { const i = +b.dataset.i!; select({ kind: "orchestrator", floor: i, session: p.sessions[i] }); })); - el.querySelectorAll("button.prog").forEach((b) => b.addEventListener("click", () => { const id = p.sessions[+b.dataset.i!]?.sessionId; todoSession = todoSession === id ? undefined : id; render(); })); + for (const b of el.querySelectorAll(".fl")) b.addEventListener("click", () => { const i = +b.dataset.i!; select({ kind: "orchestrator", floor: i, session: p.sessions[i] }); }); + for (const b of el.querySelectorAll(".crew")) b.addEventListener("click", () => { + const i = Number(b.dataset.i); + const session = p.sessions[i]; + const helper = session?.subagents.find((a) => a.id === b.dataset.id); + if (session && helper) select({ kind: "helper", floor: i, session, helper }); + }); + for (const b of el.querySelectorAll("button.prog")) b.addEventListener("click", () => { const id = p.sessions[+b.dataset.i!]?.sessionId; openTasks(todoSession === id ? undefined : id); }); } +/** The glyph a task status shows in the todo list. */ +const todoGlyph = (status: TowerTodo["status"]): string => { + if (status === "done") return "✓"; + if (status === "blocked") return "!"; + return ""; +}; + function renderTodo(p: Project) { const el = $("todo"); const floor = p.sessions.findIndex((x) => x.sessionId === todoSession); @@ -63,7 +86,7 @@ function renderTodo(p: Project) { const s = p.sessions[floor], prog = todoProgress(s.todos); el.hidden = false; el.innerHTML = `

${esc(s.name)}${prog.done} of ${prog.total} done

` - + (s.todos.length ? `
    ${s.todos.map((t, k) => `
  1. ${t.status === "done" ? "✓" : t.status === "blocked" ? "!" : ""}${k + 1}. ${esc(t.title)}${t.status.replace("_", " ")}${t.note ? `${esc(t.note)}` : ""}
  2. `).join("")}
` : `

This session has no task list yet.

`); + + (s.todos.length ? `
    ${s.todos.map((t, k) => `
  1. ${todoGlyph(t.status)}${k + 1}. ${esc(t.title)}${t.status.replace("_", " ")}${t.note ? `${esc(t.note)}` : ""}
  2. `).join("")}
` : `

This session has no task list yet.

`); } /** Strictness order. Lowering applies at once; raising is confirmed in that session's terminal. */ @@ -102,7 +125,7 @@ function renderSelection() { ${s.permission ? `` : ""}`; el.querySelector("#talk")!.addEventListener("click", () => openIntercom(s.sessionId)); - el.querySelector("#tasks")!.addEventListener("click", () => { todoSession = s.sessionId; render(); }); + el.querySelector("#tasks")!.addEventListener("click", () => openTasks(s.sessionId)); el.querySelector("#arts")!.addEventListener("click", () => openArtifacts(s)); el.querySelector("#door")?.addEventListener("change", async (e) => { const mode = (e.target as HTMLSelectElement).value; @@ -113,9 +136,20 @@ function renderSelection() { function openIntercom(sessionId: string | undefined) { const p = project(); const floor = p ? p.sessions.findIndex((x) => x.sessionId === sessionId) : -1; if (!p || floor < 0 || p.sessions[floor].basic) return; + lastPanel = "talk"; + // On a phone the intercom and the task list share the bottom area: Talk wins, Tasks closes. + if (todoSession !== undefined && useBottomSheet(innerWidth, matchMedia("(pointer: coarse)").matches)) { todoSession = undefined; render(); } renderIntercom(p.sessions[floor], floor); } +/** Opens (or closes) the task list; on a bottom sheet it wins the shared area over the intercom. */ +function openTasks(sessionId: string | undefined) { + todoSession = sessionId; + if (todoSession !== undefined) lastPanel = "tasks"; + if (todoSession !== undefined && useBottomSheet(innerWidth, matchMedia("(pointer: coarse)").matches) && !$("intercom").hidden) closeIntercom(); + render(); +} + function renderLobby(p: Project) { const L = scene.layout; if (!L) return; const review = p.sessions.find((s) => s.review)?.review; @@ -128,6 +162,12 @@ function renderLobby(p: Project) { function select(p: Pick | undefined) { selected = p; renderSelection(); const pr = project(); if (pr) renderFloors(pr); } function render() { + // Entering bottom-sheet mode (a resize or rotation) must leave one panel in the shared + // area: the one opened last keeps it, and Talk wins when nothing was tracked. + if (todoSession !== undefined && !$("intercom").hidden && useBottomSheet(innerWidth, matchMedia("(pointer: coarse)").matches)) { + if (sheetWinner(lastPanel) === "talk") todoSession = undefined; + else closeIntercom(); + } const p = project(); $("empty").hidden = !!p; $("stage").hidden = !p; @@ -135,7 +175,9 @@ function render() { if (!p) return; current = p.cwd; fit(); - scene.show(p, p.sessions.map((_, i) => FLOOR_COLORS[i % FLOOR_COLORS.length]), p.sessions.some((s) => s.review === "on") || !p.sessions.some((s) => s.review), innerHeight / scale); + // On touch or a narrow viewport the bottom sheet reserves the lower strip, so the sky stops above it. + const reserve = sheetReserve(innerWidth, matchMedia("(pointer: coarse)").matches); + scene.show(p, p.sessions.map((_, i) => FLOOR_COLORS[i % FLOOR_COLORS.length]), p.sessions.some((s) => s.review === "on") || !p.sessions.some((s) => s.review), (innerHeight - reserve) / scale); sizeCanvas(); renderFloors(p); renderTodo(p); @@ -157,7 +199,8 @@ function render() { } // The scene fills the window's width; its sky grows to fill the height, with the building on the ground. -function fit() { scale = Math.max(1, innerWidth / 720); } +// Below 720px the building itself shrinks to the width (layout.ts keeps every floor tappable). +function fit() { scale = fitBuilding(innerWidth, innerHeight, project()?.sessions.length ?? 0).scale; } function sizeCanvas() { const c = scene.app.canvas; c.style.width = `${c.width * scale}px`; @@ -201,7 +244,12 @@ addEventListener("keydown", (e) => { if (e.target instanceof HTMLTextAreaElement || e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement) return; if (tour.isOpen) return; if (e.key === "?" && !e.metaKey && !e.ctrlKey) { e.preventDefault(); tour.open(); return; } - if (e.key === "Escape") { if (closeModals()) return; if (!$("intercom").hidden) { closeIntercom(); return; } if (todoSession !== undefined) { todoSession = undefined; render(); } else select(undefined); } + if (e.key === "Escape") { + if (closeModals()) return; + const intercomOpen = !$("intercom").hidden; + if (intercomOpen) { closeIntercom(); return; } + if (todoSession !== undefined) { todoSession = undefined; render(); } else select(undefined); + } if ((e.key === "t" || e.key === "T") && !e.metaKey && !e.ctrlKey) { e.preventDefault(); openIntercom(selected?.session.sessionId ?? project()?.sessions[0]?.sessionId); } if ((e.key === "n" || e.key === "N") && !e.metaKey && !e.ctrlKey) { const p = project(); if (p) { e.preventDefault(); openNewFloor(p); } } if (e.altKey && /^[1-9]$/.test(e.key) && projects[+e.key - 1]) { current = projects[+e.key - 1].cwd; selected = undefined; render(); } @@ -218,7 +266,7 @@ scene.onRoom = (roomId, floor) => { const p = project(); if (!p) return; if (roomId === "engram") return openLibrary(p); if (roomId === "lounge" || roomId === "engine") return openTab(projects); - if (roomId === "map") { todoSession = p.sessions[floor]?.sessionId; render(); return; } + if (roomId === "map") { openTasks(p.sessions[floor]?.sessionId); return; } select({ kind: "orchestrator", floor, session: p.sessions[floor] }); }; scene.onDoor = (floor) => { const p = project(); if (!p) return; select({ kind: "orchestrator", floor, session: p.sessions[floor] }); (document.getElementById("door") as HTMLSelectElement | null)?.focus(); }; diff --git a/web/tower/src/style.css b/web/tower/src/style.css index 2bb3b71c8..6513b635d 100644 --- a/web/tower/src/style.css +++ b/web/tower/src/style.css @@ -31,6 +31,9 @@ button { font: inherit; color: inherit; cursor: pointer; background: none; borde .fl .nm { font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .fl .sub { grid-column: 2; font-size: 11px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .fl .st { grid-row: span 2; font-weight: 800; } +/* Helper chips: hidden on desktop, where the scene and the crew text select helpers; on touch they are the tappable route. */ +.crew-row { display: none; } +.crew { font: inherit; color: var(--muted); border: 1px solid #5a3a6e; background: #0d0816e6; border-radius: 2px; } .st.need { color: var(--warn); } .st.done { color: var(--ok); } .st.work { color: var(--teal); } .prog { display: grid; gap: 3px; padding: 6px 9px; text-align: left; } .prog:hover, .prog[aria-expanded="true"] { border-color: var(--accent); } @@ -162,4 +165,35 @@ kbd { font: 700 10px var(--mono); border: 1px solid currentColor; border-radius: .tour footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 0 12px; } .tour footer label { color: var(--muted); font-size: 12px; display: flex; gap: 6px; align-items: center; cursor: pointer; } .tour footer span { display: flex; gap: 6px; } -@media (prefers-reduced-motion: reduce) { .tour-spot { transition: none; } } +@media (prefers-reduced-motion: reduce) { .tour-spot { transition: none; } +} + +/* Phones and touch screens: the building scales to the viewport width, the floor cards + become a tappable list below it, and every panel docks into a bottom sheet. Desktop + rules above stay untouched; this block only adds. */ +@media (max-width: 720px), (pointer: coarse) { + html { height: 100dvh; } + body { min-height: 100dvh; } + button, select, textarea { touch-action: manipulation; } + .btn, .door select { min-height: 44px; } + .top { flex-wrap: wrap; gap: 8px 10px; padding: 8px 10px; padding-top: max(8px, env(safe-area-inset-top)); } + .brand { font-size: 13px; } + .lobby { flex-wrap: wrap; } + .top .projects { order: 3; width: 100%; margin: 0; overflow-x: auto; } + .projects button { min-height: 44px; flex: 0 0 auto; } + .canvas canvas { touch-action: manipulation; } + .floors { position: static; width: 100%; display: grid; gap: 8px; padding: 8px 10px 96px; } + .floor { position: static; left: auto; transform: none; width: auto; } + .fl, button.prog { min-height: 44px; } + .fl .sub .crew-txt { display: none; } + .crew-row { display: flex; flex-wrap: wrap; gap: 4px; } + .crew { min-height: 44px; padding: 4px 10px; color: var(--text); } + .sel { left: 0; right: 0; bottom: 0; transform: none; width: auto; border-radius: 6px 6px 0 0; padding: 8px 10px max(8px, env(safe-area-inset-bottom)); } + .todo { left: 10px; right: 10px; top: auto; bottom: calc(84px + env(safe-area-inset-bottom)); width: auto; max-height: min(48dvh, 420px); } + .intercom { left: 10px; right: 10px; top: max(56px, env(safe-area-inset-top)); bottom: calc(84px + env(safe-area-inset-bottom)); width: auto; } + .modal.wide { width: calc(100% - 20px); height: min(620px, 80dvh); } + .lib { grid-template-columns: 1fr; } + .lib .shelves { max-height: 38dvh; border-right: 0; border-bottom: 1px solid #3a2a4a; } + .offline { right: 10px; bottom: calc(84px + env(safe-area-inset-bottom)); } + .empty-state { margin-top: 20dvh; } +}