From 8f5f7bb07ecbc0b9c851e4cf4ba62124f150bd8e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 20:33:37 +0200 Subject: [PATCH 1/3] feat(ui,http,cli,docs): the daemon serves a web console at / with operator sign-in Implements ADR 0011: a React and Vite app in ui/, built into dist/ui and served in front of app.fetch with the CSP and cache headers; sign-in with an operator token kept per tab; the shell with its navigation; status.get's daemon.consoleUrl, printed by simlock status and daemon start; a Playwright browser lane in Chromium, Firefox and WebKit; CONSOLE.md and DESIGN.md. Closes #271 --- .fallowrc.json | 19 +- .github/workflows/ci.yml | 24 ++ .gitignore | 2 + AGENTS.md | 3 + README.md | 1 + docs/ABOUT.md | 9 +- docs/CLI.md | 8 +- docs/CONFIGURATION.md | 2 +- docs/CONSOLE.md | 100 +++++++ docs/HTTP-API.md | 20 +- docs/internal/ARCHITECTURE.md | 12 +- docs/internal/DESIGN.md | 127 ++++++++ e2e/console-serving.test.ts | 83 ++++++ e2e/console/fixtures.ts | 128 +++++++++ e2e/console/shell.spec.ts | 128 +++++++++ e2e/console/sign-in.spec.ts | 144 ++++++++++ e2e/helpers/env.ts | 23 +- e2e/helpers/index.ts | 3 +- e2e/helpers/port.ts | 24 ++ e2e/tsconfig.typecheck.json | 2 +- package.json | 20 +- playwright.config.ts | 22 ++ pnpm-lock.yaml | 477 +++++++++++++++++++------------ src/cli/index.test.ts | 38 +++ src/cli/index.ts | 14 +- src/contract/console-url.test.ts | 20 ++ src/contract/console-url.ts | 33 +++ src/contract/index.ts | 1 + src/contract/operations.ts | 10 +- src/daemon/dispatcher.test.ts | 46 ++- src/daemon/dispatcher.ts | 7 +- src/gateway/dispatcher.test.ts | 26 +- src/gateway/dispatcher.ts | 11 +- src/http/server.test.ts | 237 +++++++++++++++ src/http/server.ts | 102 ++++++- ui/index.html | 14 + ui/public/favicon.svg | 1 + ui/src/api.test.ts | 79 +++++ ui/src/api.ts | 118 ++++++++ ui/src/app.tsx | 22 ++ ui/src/console-context.tsx | 32 +++ ui/src/main.tsx | 30 ++ ui/src/router.tsx | 49 ++++ ui/src/session.ts | 52 ++++ ui/src/shell.tsx | 53 ++++ ui/src/sign-in-check.test.ts | 78 +++++ ui/src/sign-in-check.ts | 50 ++++ ui/src/sign-in.tsx | 75 +++++ ui/src/styles.css | 361 +++++++++++++++++++++++ ui/src/views/coming-soon.tsx | 9 + ui/src/views/index.tsx | 27 ++ ui/src/views/not-found.tsx | 18 ++ ui/tsconfig.json | 16 ++ ui/vite.config.ts | 23 ++ vitest.config.ts | 4 +- 55 files changed, 2791 insertions(+), 246 deletions(-) create mode 100644 docs/CONSOLE.md create mode 100644 docs/internal/DESIGN.md create mode 100644 e2e/console-serving.test.ts create mode 100644 e2e/console/fixtures.ts create mode 100644 e2e/console/shell.spec.ts create mode 100644 e2e/console/sign-in.spec.ts create mode 100644 e2e/helpers/port.ts create mode 100644 playwright.config.ts create mode 100644 src/contract/console-url.test.ts create mode 100644 src/contract/console-url.ts create mode 100644 src/http/server.test.ts create mode 100644 ui/index.html create mode 100644 ui/public/favicon.svg create mode 100644 ui/src/api.test.ts create mode 100644 ui/src/api.ts create mode 100644 ui/src/app.tsx create mode 100644 ui/src/console-context.tsx create mode 100644 ui/src/main.tsx create mode 100644 ui/src/router.tsx create mode 100644 ui/src/session.ts create mode 100644 ui/src/shell.tsx create mode 100644 ui/src/sign-in-check.test.ts create mode 100644 ui/src/sign-in-check.ts create mode 100644 ui/src/sign-in.tsx create mode 100644 ui/src/styles.css create mode 100644 ui/src/views/coming-soon.tsx create mode 100644 ui/src/views/index.tsx create mode 100644 ui/src/views/not-found.tsx create mode 100644 ui/tsconfig.json create mode 100644 ui/vite.config.ts diff --git a/.fallowrc.json b/.fallowrc.json index 990e0c3c2..acf63c6cf 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -5,8 +5,25 @@ // other source file), and e2e/fake-driver/index.ts is loaded dynamically by the // daemon via SIMLOCK_DRIVERS_MODULE (see docs/CLI.md) -- neither is visible to // fallow's static reachability graph without being declared explicitly. - "entry": ["src/index.ts", "src/cli/main.ts", "src/daemon/main.ts", "e2e/**/*.test.ts"], + // The web console is its own entry: Vite loads ui/index.html, which loads ui/src/main.tsx. The + // browser lane's specs are Playwright entry points, as the e2e tests are vitest's. + "entry": [ + "src/index.ts", + "src/cli/main.ts", + "src/daemon/main.ts", + "e2e/**/*.test.ts", + "ui/src/main.tsx", + "e2e/console/*.spec.ts" + ], "dynamicallyLoaded": ["e2e/fake-driver/index.ts"], + // The web console's libraries are bundled into dist/ui at build time and ship as files, so + // they are dev dependencies on purpose: the package gains no runtime dependency for them. + "ignoreDependencies": [ + "react", + "react-dom", + "@fontsource-variable/geist", + "@fontsource-variable/geist-mono" + ], "ignoreDependencyOverrides": [ // MCP SDK 1.29 transitively requires vulnerable node-server 1.x; lockfile/audit verify this patched override. { "package": "@hono/node-server", "source": "pnpm-workspace.yaml" }, diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index db22681d6..43c3e3950 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -38,6 +38,30 @@ jobs: - name: Quality checks run: pnpm check + console: + name: Console + runs-on: ubuntu-24.04 + permissions: + contents: read + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 22 + - name: Enable Corepack + run: | + corepack enable + corepack prepare pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621 --activate + - name: Install dependencies + run: pnpm install --frozen-lockfile --ignore-scripts + - name: Install Playwright browsers + run: pnpm exec playwright install --with-deps chromium firefox webkit + - name: Browser lane + run: pnpm test:console + fallow: name: Fallow runs-on: ubuntu-24.04 diff --git a/.gitignore b/.gitignore index 74d98ad21..8c4db42f5 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,5 @@ dist/ .fallow/ .claude/settings.local.json .claude/worktrees/ +test-results/ +playwright-report/ diff --git a/AGENTS.md b/AGENTS.md index 526f1fdd4..e4487efc4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,11 +53,14 @@ End-user docs live directly under [docs/](docs/) and must stay self-contained - [CLIENT.md](docs/CLIENT.md) — the programmatic client (`simlock/client`, `simlock/admin`) - [CONFIGURATION.md](docs/CONFIGURATION.md) — every config key, its default, and how limits interact - [HTTP-API.md](docs/HTTP-API.md) — the network-facing HTTP API +- [CONSOLE.md](docs/CONSOLE.md) — the web console: turning it on, opening it, signing in - [EVENTS.md](docs/EVENTS.md) — catalog of business events, end-user cut Maintainer/agent docs live under [docs/internal/](docs/internal/): - [ARCHITECTURE.md](docs/internal/ARCHITECTURE.md) — high-level architecture overview +- [DESIGN.md](docs/internal/DESIGN.md) — the design guide for the web console + (and the landing page): type, colour, status colours, spacing, voice - [DELIVERY.md](docs/internal/DELIVERY.md) — how work flows through GitHub Issues: the three walkthroughs, handoffs, what is automated, where ADRs fit - [templates/](docs/internal/templates/) — the feature and task spec bodies a diff --git a/README.md b/README.md index 374b5e367..515afeac5 100644 --- a/README.md +++ b/README.md @@ -212,6 +212,7 @@ lease-loss notifications are documented in - [docs/CLIENT.md](docs/CLIENT.md) — the programmatic client (`simlock/client`, `simlock/admin`) - [docs/CONFIGURATION.md](docs/CONFIGURATION.md) — every config key, its default, and how limits interact - [docs/HTTP-API.md](docs/HTTP-API.md) — the network-facing HTTP API +- [docs/CONSOLE.md](docs/CONSOLE.md) — the web console the daemon serves for operators - [docs/EVENTS.md](docs/EVENTS.md) — catalog of business events on `simlock events` ## Made with ❤️ at Callstack diff --git a/docs/ABOUT.md b/docs/ABOUT.md index 56efaa382..96909fd45 100644 --- a/docs/ABOUT.md +++ b/docs/ABOUT.md @@ -22,7 +22,9 @@ devices from a self-hosted simlock host over the network (see without spawning a `simlock` command at all — agent-device, for example — can instead depend on `simlock/client`/`simlock/admin`, the typed programmatic client the CLI and MCP frontends are themselves built on (see -[CLIENT.md](CLIENT.md)). +[CLIENT.md](CLIENT.md)). With HTTP on, the daemon also serves a web console +for operators, signed in with an operator token (see +[CONSOLE.md](CONSOLE.md)). - `simlock lease` returns a *ready* device — booted and health-checked — that no other agent will touch for the duration of the lease. @@ -73,5 +75,6 @@ registry, and every safety invariant stay on the worker. optional MCP server reserves stdout for MCP JSON-RPC. See [CLI.md](CLI.md) for the command surface, -[CLIENT.md](CLIENT.md) for the programmatic client, and -[HTTP-API.md](HTTP-API.md) for the network API. +[CLIENT.md](CLIENT.md) for the programmatic client, +[HTTP-API.md](HTTP-API.md) for the network API, and +[CONSOLE.md](CONSOLE.md) for the web console. diff --git a/docs/CLI.md b/docs/CLI.md index 0e5f09886..e82c6192f 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -1063,7 +1063,9 @@ A device currently `provisioning` or `reclaiming` carries a derived and `list --devices` well before it crosses the threshold that would make `doctor` flag it as stalled. -Human-oriented overview: daemon health *and mode*, the host it runs on +Human-oriented overview: daemon health *and mode*, the web console's address +when HTTP is enabled (`Console: http://127.0.0.1:4700/`, see +[CONSOLE.md](CONSOLE.md); `daemon.consoleUrl` in `--json`), the host it runs on (`Host: macOS 15.5 arm64; xcode 16.4 (16F6), emulator 35.4.9`), managed capacity (used/limit per platform), running and reserved capacity (globally and per platform), the RAM budget (`RAM budget: 4.50 GiB/12.00 GiB used`), every @@ -1642,7 +1644,9 @@ Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` exists for operators and debugging. `start` starts whichever mode `config.mode` selects — a worker (the default) or a gateway — and `status` reports it, both in the human line (`Daemon: running (gateway)`) and -as `daemon.mode` under `--json`. `stop` does not touch leases: they persist, +as `daemon.mode` under `--json`. With HTTP enabled, `start` and `status` also +print the web console's address on a `Console:` line (see +[CONSOLE.md](CONSOLE.md)). `stop` does not touch leases: they persist, and the next daemon restores each one's TTL timer from its deadline. What a stop does end is the connections to it — a running `simlock lease` cannot reconnect, so it exits `1` with a `DAEMON_CONNECTION_LOST` line naming a lease diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index e1e25a4f9..49927d1cf 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -34,7 +34,7 @@ edit yourself keeps the mode you give it until the next `config set`; run | `gateway.disconnectedRetentionMs` | **Gateway side.** How long a disconnected worker is kept (greyed, never dispatched to) before the gateway forgets it. The clock is held while the gateway still knows of gateway-issued leases on that worker, and that hold ends when the last of those leases passes its deadline. | `24 hours` | | `gateway.execTimeoutMs` | **Gateway side.** How long the gateway waits on a proxied `device.exec` before giving up. A backstop for a worker that never answers at all — deliberately longer than the worker's own `exec.timeoutMs`, which is authoritative because that side owns the process and can kill it, so an ordinary timeout surfaces as the worker's `EXEC_TIMEOUT` rather than racing this one. | `11 minutes` | | `gateway.leaseRequestTimeoutMs` | **Gateway side.** How long the gateway waits on a forwarded `lease.request` before giving up on that worker for this request, answering `WORKER_UNREACHABLE`. Bounds the one uplink call that otherwise had no timeout of its own, so a wedged worker cannot park a request where neither a deadline nor `lease.cancel` could ever reach it again. Generous against a cold device provision-plus-boot; well below `gateway.execTimeoutMs`, since granting a lease should never take as long as a command run against the device afterward. | `5 minutes` | -| `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | +| `http.enabled` | Master switch for the network-facing HTTP API (see [HTTP-API.md](HTTP-API.md)) and the web console served beside it (see [CONSOLE.md](CONSOLE.md)). Off by default; the daemon binds nothing until this is `true`. A gateway is the fleet's contact point, so it must be `true` there — see [Modes](#modes-gateway-and-worker). | `false` | | `http.host` | Address the HTTP listener binds. `127.0.0.1` keeps it loopback-only; reaching it remotely is the operator's own tunnel (Tailscale, cloudflared, reverse proxy) — Simlock does no TLS termination in v1. | `127.0.0.1` | | `http.port` | Port the HTTP listener binds. Must be an integer `1`-`65535`. | `4700` | | `exec.timeoutMs` | How long a single `device.exec` command (the remote half of `simlock simctl` / `simlock adb` — see [CLI.md](CLI.md#reaching-a-leased-device)) may run before Simlock kills it and fails the call with `EXEC_TIMEOUT`. Output is streamed, never buffered, so there is no size limit to go with it. | `10 minutes` | diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md new file mode 100644 index 000000000..25055f80a --- /dev/null +++ b/docs/CONSOLE.md @@ -0,0 +1,100 @@ +# Web console + +Part of the user manual: the web console is a page in your browser that shows +what a Simlock host, or a gateway and its workers, is doing. The daemon serves +it itself. There is nothing to install and nothing is fetched from the +internet. + +The console is for people who operate Simlock. It needs an operator token. +Coding agents keep using the CLI, the MCP server, the client and the HTTP API. + +This version has sign-in and the console's navigation: Workers, Leases, +Waiting, Attention and Events. Each page says "Coming soon" until its view is +built. + +## Turn it on + +The console comes with the HTTP API. It is on whenever `http.enabled` is +`true`, and there is no separate switch for it. A gateway always has HTTP on. + +On a single host, turn HTTP on and restart the daemon: + +```sh +simlock config set http.enabled true +simlock daemon stop && simlock daemon start +``` + +`http.host` and `http.port` decide where it listens, `127.0.0.1:4700` by +default (see [CONFIGURATION.md](CONFIGURATION.md)). + +## Open it + +`simlock daemon start` and `simlock status` print the address: + +``` +Daemon running +Console: http://127.0.0.1:4700/ +``` + +Open that address in a browser. `simlock status --json` has it as +`daemon.consoleUrl`. When HTTP is off there is no `Console:` line and no +`consoleUrl`. + +When `http.host` is `0.0.0.0` or `::`, the daemon listens on every interface +and the address says `localhost`. From another machine, use this host's name +or address instead. An IPv6 host is shown in brackets, as a browser expects: +`http://[::1]:4700/`. + +The console uses the HTTP listener and nothing else. To reach it from another +machine, use the same tunnel you use for the HTTP API (Tailscale, cloudflared, +a reverse proxy). Simlock does not do TLS. + +Every page has its own address, such as `/workers`, so you can bookmark a page +or reload it. + +## Sign in + +Paste an operator token and press **Sign in**. To make one, run this on the +host or the gateway: + +```sh +simlock token create --role operator +``` + +The secret is printed once. A token works only on the daemon that minted it: +a gateway's token does not sign in to a worker, and the other way round. + +If the console does not accept the token, it says why: + +| Message | What it means | +| --- | --- | +| This daemon does not know that token. | The token is mistyped, revoked, or from another daemon. | +| That token is real, but the console needs an operator token. | It is an agent token or a worker join token. | +| The daemon is starting. Try again in a moment. | The daemon answers, but has not finished starting. | +| The daemon cannot be reached. | Nothing answers at this address. | +| The daemon answered with an error (HTTP *n*). | Anything else; the daemon's log says more. | + +## Staying signed in + +The console keeps the token in this browser tab only. + +- **Reload** the page and you stay signed in. +- **Open a new tab** and it asks for a token again. +- **Close the tab** and you are signed out. +- **Sign out** forgets the token at once. +- If the token is **revoked**, the console signs you out the next time it asks + the daemon for anything. + +Some browsers copy a tab's storage into a duplicated or reopened tab, so such a +tab may still be signed in. + +## What the page loads + +Everything the console needs comes from the daemon: the page, its script, its +styles and its fonts. The page tells the browser not to send anything to any +other host, so it works without internet access and your token stays with the +daemon. + +The console's own files need no token, because they hold no data. Anyone who +reaches the HTTP listener can load the sign-in page and nothing more. Every +piece of data comes from the HTTP API, with your token. diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index 506aaf4ee..b161c304e 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -6,7 +6,8 @@ uses instead of the CLI/MCP frontends' unix socket. It is off by default enabled, binds `127.0.0.1` unless configured otherwise. Reaching it from another machine is the operator's own tunnel (Tailscale, cloudflared, a reverse proxy) — Simlock does no TLS termination in v1, and `Authorization` -is required on every route regardless of how it's reached, loopback included. +is required on every API route regardless of how it's reached, loopback +included (see [Authentication](#authentication) for the two exceptions). This frontend calls the exact same in-process `Dispatcher` the unix socket calls — not a second copy of role/ownership logic, and not a @@ -43,8 +44,11 @@ terminal state. No route blocks on device work in flight. ## Authentication -Every route requires `Authorization: Bearer slk_` except `GET -/v1/healthz`. Missing or unrecognized tokens are `401 UNAUTHENTICATED`. +Every route requires `Authorization: Bearer slk_` except two: `GET +/v1/healthz`, and the web console's own files, which the daemon serves at +every path outside `/v1` (see [CONSOLE.md](CONSOLE.md)). They hold no data; +the console reads everything it shows from the routes below, with the +operator's token. Missing or unrecognized tokens are `401 UNAUTHENTICATED`. Tokens are minted and managed with `simlock token` (see [CLI.md](CLI.md)). Since 0.3.0 `token.create|list|revoke` are daemon operations (admin role) and @@ -139,9 +143,15 @@ The daemon block carries `health` (`starting`/`running`) and **`mode`** daemon answered: ```json -{ "daemon": { "health": "running", "mode": "worker" } } +{ "daemon": { "health": "running", "mode": "worker", "consoleUrl": "http://127.0.0.1:4700/" } } ``` +**`consoleUrl`** is the web console's address (see [CONSOLE.md](CONSOLE.md)): +`http://:/`, with `localhost` for a host of `0.0.0.0` or +`::` and an IPv6 host in brackets. Since HTTP has to be on to reach this route, +an HTTP answer always carries it; over the unix socket it is absent while HTTP +is off. An older daemon sends none. + Beside it, **`host`** says what machine the daemon runs on: the operating system, its version, the CPU architecture, and the version of each platform tool its drivers use: @@ -203,7 +213,7 @@ on, and an additive **`workers`** array carries one [worker view](#worker-routes) per worker: ```json -{ "daemon": { "health": "running", "mode": "gateway" }, +{ "daemon": { "health": "running", "mode": "gateway", "consoleUrl": "http://127.0.0.1:4700/" }, "host": { "os": "Linux", "osVersion": "6.8.0", "arch": "x64", "tools": [] }, "workers": [ { "id": "3f81a2c4", "label": "mac-studio-2", "connection": "connected", "drained": false } ] } ``` diff --git a/docs/internal/ARCHITECTURE.md b/docs/internal/ARCHITECTURE.md index 6d137a657..71f210e7a 100644 --- a/docs/internal/ARCHITECTURE.md +++ b/docs/internal/ARCHITECTURE.md @@ -43,7 +43,7 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. kind, not just transport: it is the one frontend meant to be reached over a real network, so it calls the daemon's dispatcher **in-process** — the exact same one the socket path calls — rather than going through the unix socket at - all, and requires a bearer token on every route but `GET /v1/healthz`. It + all, and requires a bearer token on every `/v1` route but `GET /v1/healthz`. It grants exactly the same TTL-renewed lease every other frontend does (ADR 0004) — being reachable over a real network is no longer a reason for a different lease model, because there is only one. Its listener now starts @@ -55,6 +55,16 @@ modes](#gateway-and-worker-modes-adr-0005) below for that topology. before convergence completes now waits on the shared dispatcher's readiness gate exactly like a socket request, instead of being refused. See [HTTP-API.md](../HTTP-API.md) for the full route reference. +- **Web console** (ADR 0011): a React app in `ui/`, built by Vite into + `dist/ui` and served by the same HTTP listener at every path outside `/v1`. + `src/http/server.ts` puts it in front of `app.fetch`, so `app.ts` stays a + pure request-to-response function and the console never touches the API's + auth or request log. The console is a client of the HTTP API like any other: + it reads only `/v1`, with the operator's token, through one fetch helper + (`ui/src/api.ts`). Its views are listed once, in `ui/src/views/index.tsx`, + which is both the navigation and the router's table. See + [CONSOLE.md](../CONSOLE.md) for the user's side and + [DESIGN.md](DESIGN.md) for the style. - **CLI**: by default it acquires a lease, prints one JSON result line on stdout, then stays alive — renewing the lease at one third of the lease's TTL and releasing it on exit, parent death, or `SIGINT`/`SIGTERM`. That is the diff --git a/docs/internal/DESIGN.md b/docs/internal/DESIGN.md new file mode 100644 index 000000000..9015f7b7a --- /dev/null +++ b/docs/internal/DESIGN.md @@ -0,0 +1,127 @@ +# Design guide + +How Simlock looks. The web console follows it today, and the landing page will +follow it when it is built. The tokens live in `ui/src/styles.css`; change this +guide and that file together. + +The style is Callstack's incubator style: plain, dense, square, quiet. Orange is +Simlock's accent. + +## Type + +- **Geist** for everything people read. **Geist Mono** for what people copy or + compare: ids, tokens, commands, versions, timestamps, numbers in tables. +- Both are bundled with the console (`@fontsource-variable/geist`, + `@fontsource-variable/geist-mono`, OFL-1.1). Nothing is loaded from a font + service. +- One scale, in `rem`, from a 16px base: + + | Token | Size | Use | + | --- | --- | --- | + | `--text-xs` | 12px | badges, table footnotes | + | `--text-sm` | 14px | navigation, labels, hints, table cells | + | `--text-md` | 16px | body text | + | `--text-lg` | 20px | the wordmark | + | `--text-xl` | 24px | a page's heading (`h1`) | + | `--text-2xl` | 32px | the landing page's headings only | + +- Weights: 400 for text, 500 for labels and controls, 600 for headings. +- Headings get a small negative tracking (`-0.01em`). Body text has none. +- Line height 1.5 for text, 1.25 for headings. + +## Colour + +Every colour is a CSS custom property on `:root`. The light values apply by +default; the dark values replace them under `prefers-color-scheme: dark`. The +console has no theme switch of its own: it follows the system. + +| Token | Light | Dark | Use | +| --- | --- | --- | --- | +| `--bg` | `#ffffff` | `#0e0e0f` | the page | +| `--surface` | `#f5f5f4` | `#18181b` | panels, hovered rows | +| `--border` | `#d9d9d6` | `#2e2e33` | dividers, panel edges | +| `--text` | `#0e0e0f` | `#f2f2f0` | text | +| `--text-muted` | `#55555a` | `#a1a1a8` | secondary text, inactive nav | +| `--accent` | `#c2410c` | `#ff7a1a` | brand and interaction | +| `--accent-hover` | `#9a3412` | `#ff9442` | a hovered accent control | +| `--on-accent` | `#ffffff` | `#0e0e0f` | text on an accent fill | +| `--selection` | `#fed7aa` | `#7c2d12` | selected text | + +The accent is a darker orange in the light theme so that it passes WCAG AA as +text and as a focus ring on white. + +### Orange is for brand and interaction only + +Use the accent for the wordmark's square, buttons, links, the focus ring, the +current page in the navigation, and selection. Never use it to say something +about state: not for "busy", not for "warning", not for "new". A reader who +sees orange should think "I can act here", nothing else. + +### Status colours + +| Token | Light | Dark | Means | +| --- | --- | --- | --- | +| `--status-ok` | `#15803d` | `#4ade80` | healthy, connected, ready | +| `--status-warn` | `#a16207` | `#facc15` | needs a look soon: drained, stalled, over a limit | +| `--status-error` | `#b91c1c` | `#f87171` | broken: disconnected, incompatible, quarantined, a refused sign-in | +| `--status-idle` | `#57534e` | `#a8a29e` | neither: shut down, waiting, unknown | + +**A status always shows a word.** The colour is a second signal, never the only +one: `● connected`, not a green dot. Use the daemon's own word for the state +(`leased`, `quarantined`, `drained`), so the console and the CLI agree. + +Every pair of text and background colour in both themes meets WCAG AA: 4.5:1 +for text, and 3:1 for the focus ring and an input's border. The browser lane +checks text contrast with axe in both themes; a new token must pass it too. + +## Shape + +- **Square corners** everywhere: `--radius` is `0`. No rounded buttons, panels + or inputs. +- Borders are 1px `--border`. Panels are `--surface` with a border, no shadow. +- No gradients, no illustrations. The one decoration is the wordmark's orange + square. + +## Spacing + +A 4px grid: `--space-1` 4px, `--space-2` 8px, `--space-3` 12px, `--space-4` +16px, `--space-6` 24px, `--space-8` 32px, `--space-12` 48px. Pick from the +scale; never a value between. + +- Controls are at least 40px tall, so they are easy to hit on a phone. +- A page has 16px side padding on a phone and 32px from 768px up. + +## Layout + +- Phone first. Every page works at 360px wide with no sideways scrolling of the + page. A wide table scrolls inside its own box, never the page. +- Under 768px: the header, then the navigation as a wrapping row, then the + page. From 768px: the header across the top, the navigation as a 200px + column on the left, the page beside it. +- The navigation lists every view in a fixed order. The current one has an + accent bar and `aria-current="page"`. + +## Focus and keyboard + +- Everything clickable is a real `` or ` + + +
+ {view === undefined ? path === "/" ? null : : } +
+ + ); +} diff --git a/ui/src/sign-in-check.test.ts b/ui/src/sign-in-check.test.ts new file mode 100644 index 000000000..a6c1db6cc --- /dev/null +++ b/ui/src/sign-in-check.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { Fetch } from "./api"; +import { checkToken, refusalMessage } from "./sign-in-check"; + +type Answer = number | "network-error" | "hang"; + +/** A daemon that answers `/v1/healthz` and `/v1/workers` as scripted. */ +function daemon(healthz: Answer, workers: Answer): Fetch { + return (input, init) => { + const answer = input === "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/v1/healthz" ? healthz : workers; + if (answer === "network-error") return Promise.reject(new TypeError("Failed to fetch")); + if (answer === "hang") { + return new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(new DOMException("aborted"))); + }); + } + return Promise.resolve(new Response("{}", { status: answer })); + }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("checkToken", () => { + it("signs in on a 200 from /v1/workers", async () => { + expect(await checkToken("slk_op", daemon(200, 200))).toEqual({ kind: "signed-in" }); + }); + + it("calls an unknown token unknown on a 401", async () => { + const outcome = await checkToken("slk_nope", daemon(200, 401)); + + expect(outcome).toEqual({ kind: "unknown-token" }); + expect(refusalMessage({ kind: "unknown-token" })).toBe("This daemon does not know that token."); + }); + + it("says the console needs an operator token on a 403", async () => { + const outcome = await checkToken("slk_agent", daemon(200, 403)); + + expect(outcome).toEqual({ kind: "not-operator" }); + expect(refusalMessage({ kind: "not-operator" })).toBe( + "That token is real, but the console needs an operator token.", + ); + }); + + it("says the daemon is starting when /v1/workers gives no answer in 10 seconds while /v1/healthz answers", async () => { + vi.useFakeTimers(); + const outcome = checkToken("slk_op", daemon(200, "hang")); + await vi.advanceTimersByTimeAsync(10_000); + + expect(await outcome).toEqual({ kind: "starting" }); + expect(refusalMessage({ kind: "starting" })).toBe( + "The daemon is starting. Try again in a moment.", + ); + }); + + it("says the daemon cannot be reached when /v1/healthz does not answer", async () => { + vi.useFakeTimers(); + const hung = checkToken("slk_op", daemon("hang", 200)); + await vi.advanceTimersByTimeAsync(10_000); + + expect(await checkToken("slk_op", daemon("network-error", 200))).toEqual({ + kind: "unreachable", + }); + expect(await hung).toEqual({ kind: "unreachable" }); + expect(refusalMessage({ kind: "unreachable" })).toBe("The daemon cannot be reached."); + }); + + it("reports any other answer from /v1/workers with its status", async () => { + const outcome = await checkToken("slk_op", daemon(200, 500)); + + expect(outcome).toEqual({ kind: "failed", status: 500 }); + expect(refusalMessage({ kind: "failed", status: 500 })).toBe( + "The daemon answered with an error (HTTP 500).", + ); + }); +}); diff --git a/ui/src/sign-in-check.ts b/ui/src/sign-in-check.ts new file mode 100644 index 000000000..a87aa320a --- /dev/null +++ b/ui/src/sign-in-check.ts @@ -0,0 +1,50 @@ +import { type Fetch, RequestTimeoutError, send } from "./api"; + +/** What checking a pasted token found (ADR 0011 §6). */ +export type SignInOutcome = + | { readonly kind: "signed-in" } + | { readonly kind: "unknown-token" } + | { readonly kind: "not-operator" } + | { readonly kind: "starting" } + | { readonly kind: "unreachable" } + | { readonly kind: "failed"; readonly status: number }; + +/** + * First `GET /v1/healthz`, to learn whether the daemon is up at all; then `GET /v1/workers`, a + * read only an operator token may make, in both modes. A timeout on the second while the first + * answered means the daemon is still starting: its reads wait until it is ready. + */ +export async function checkToken(token: string, fetch: Fetch): Promise { + try { + const up = await send("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/v1/healthz", { fetch }, async (response) => response.ok); + if (!up) return { kind: "unreachable" }; + } catch { + return { kind: "unreachable" }; + } + let status: number; + try { + status = await send("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/v1/workers", { fetch, token }, async (response) => response.status); + } catch (error: unknown) { + return { kind: error instanceof RequestTimeoutError ? "starting" : "unreachable" }; + } + if (status === 200) return { kind: "signed-in" }; + if (status === 401) return { kind: "unknown-token" }; + if (status === 403) return { kind: "not-operator" }; + return { kind: "failed", status }; +} + +/** What the sign-in screen says for each refusal. */ +export function refusalMessage(outcome: Exclude): string { + switch (outcome.kind) { + case "unknown-token": + return "This daemon does not know that token."; + case "not-operator": + return "That token is real, but the console needs an operator token."; + case "starting": + return "The daemon is starting. Try again in a moment."; + case "unreachable": + return "The daemon cannot be reached."; + case "failed": + return `The daemon answered with an error (HTTP ${outcome.status}).`; + } +} diff --git a/ui/src/sign-in.tsx b/ui/src/sign-in.tsx new file mode 100644 index 000000000..ec887a3b3 --- /dev/null +++ b/ui/src/sign-in.tsx @@ -0,0 +1,75 @@ +import { type FormEvent, useState } from "react"; + +import type { Fetch } from "./api"; +import { useSession } from "./console-context"; +import { checkToken, refusalMessage } from "./sign-in-check"; + +/** Checks a pasted token and signs in with it, or keeps the reason it was refused. */ +function useSignIn(fetch: Fetch) { + const session = useSession(); + const [checking, setChecking] = useState(false); + const [refusal, setRefusal] = useState(undefined); + const submit = async (token: string) => { + if (token === "" || checking) return; + setChecking(true); + setRefusal(undefined); + const outcome = await checkToken(token, fetch); + setChecking(false); + if (outcome.kind === "signed-in") session.signIn(token); + else setRefusal(refusalMessage(outcome)); + }; + return { checking, refusal, submit }; +} + +/** The screen a tab without a token sees (ADR 0011 §6). */ +export function SignIn({ fetch }: { readonly fetch: Fetch }) { + const [token, setToken] = useState(""); + const { checking, refusal, submit } = useSignIn(fetch); + const onSubmit = (event: FormEvent) => { + event.preventDefault(); + void submit(token.trim()); + }; + const refused = refusal !== undefined; + + return ( +
+
+

+

+

Sign in

+
+ + setToken(event.target.value)} + aria-describedby={refused ? "token-hint token-refusal" : "token-hint"} + aria-invalid={refused || undefined} + /> +

+ Create one with simlock token create --role operator. +

+ + + +
+
+ ); +} + +function Refusal({ message }: { readonly message: string | undefined }) { + if (message === undefined) return null; + return ( + + ); +} diff --git a/ui/src/styles.css b/ui/src/styles.css new file mode 100644 index 000000000..ee898f601 --- /dev/null +++ b/ui/src/styles.css @@ -0,0 +1,361 @@ +/* + * The console's design tokens and base styles. docs/internal/DESIGN.md is the guide these + * follow; change both together. + */ + +:root { + color-scheme: light dark; + + --font-sans: "Geist Variable", ui-sans-serif, system-ui, sans-serif; + --font-mono: "Geist Mono Variable", ui-monospace, "SF Mono", Menlo, monospace; + + --text-xs: 0.75rem; + --text-sm: 0.875rem; + --text-md: 1rem; + --text-lg: 1.25rem; + --text-xl: 1.5rem; + --text-2xl: 2rem; + + --space-1: 4px; + --space-2: 8px; + --space-3: 12px; + --space-4: 16px; + --space-6: 24px; + --space-8: 32px; + --space-12: 48px; + + --radius: 0; + --focus-width: 2px; + --duration: 120ms; + + /* Light theme. */ + --bg: #ffffff; + --surface: #f5f5f4; + --border: #d9d9d6; + --text: #0e0e0f; + --text-muted: #55555a; + --accent: #c2410c; + --accent-hover: #9a3412; + --on-accent: #ffffff; + --selection: #fed7aa; + + --status-ok: #15803d; + --status-warn: #a16207; + --status-error: #b91c1c; + --status-idle: #57534e; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #0e0e0f; + --surface: #18181b; + --border: #2e2e33; + --text: #f2f2f0; + --text-muted: #a1a1a8; + --accent: #ff7a1a; + --accent-hover: #ff9442; + --on-accent: #0e0e0f; + --selection: #7c2d12; + + --status-ok: #4ade80; + --status-warn: #facc15; + --status-error: #f87171; + --status-idle: #a8a29e; + } +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html, +body { + margin: 0; +} + +body { + background: var(--bg); + color: var(--text); + font-family: var(--font-sans); + font-size: var(--text-md); + line-height: 1.5; + -webkit-font-smoothing: antialiased; +} + +::selection { + background: var(--selection); + color: var(--text); +} + +h1 { + margin: 0 0 var(--space-2); + font-size: var(--text-xl); + font-weight: 600; + letter-spacing: -0.01em; + line-height: 1.25; +} + +p { + margin: 0 0 var(--space-3); +} + +code { + font-family: var(--font-mono); + overflow-wrap: anywhere; +} + +a { + color: var(--accent); +} + +a:hover { + color: var(--accent-hover); +} + +:focus-visible { + outline: var(--focus-width) solid var(--accent); + outline-offset: 2px; +} + +.muted { + color: var(--text-muted); +} + +/* Buttons. Orange marks interaction; a quiet button is the same control without the fill. */ + +.button { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 40px; + padding: 0 var(--space-4); + border: 1px solid var(--accent); + border-radius: var(--radius); + background: var(--accent); + color: var(--on-accent); + font: inherit; + font-weight: 500; + cursor: pointer; + transition: + background-color var(--duration), + border-color var(--duration); +} + +.button:hover { + background: var(--accent-hover); + border-color: var(--accent-hover); +} + +.button:disabled { + cursor: progress; + opacity: 0.75; +} + +.button-quiet { + background: transparent; + border-color: var(--border); + color: var(--text); +} + +.button-quiet:hover { + background: var(--surface); + border-color: var(--text-muted); +} + +/* The brand mark: a square of the accent, the one decoration the console has. */ + +.brand { + display: inline-flex; + align-items: center; + gap: var(--space-2); + margin: 0; + font-weight: 600; + font-size: var(--text-lg); + letter-spacing: -0.01em; +} + +.brand-mark { + width: 14px; + height: 14px; + background: var(--accent); +} + +.skip-link { + position: absolute; + left: var(--space-2); + top: -100px; + padding: var(--space-2) var(--space-3); + background: var(--bg); + border: 1px solid var(--accent); + z-index: 10; +} + +.skip-link:focus { + top: var(--space-2); +} + +/* Sign-in. */ + +.sign-in { + display: grid; + min-height: 100vh; + place-items: center; + padding: var(--space-4); +} + +.sign-in-panel { + width: 100%; + max-width: 400px; + padding: var(--space-8) var(--space-6); + border: 1px solid var(--border); + background: var(--surface); +} + +.sign-in-panel .brand { + margin-bottom: var(--space-6); +} + +.sign-in form { + display: grid; + gap: var(--space-2); +} + +label { + font-size: var(--text-sm); + font-weight: 500; +} + +input { + min-height: 40px; + width: 100%; + padding: 0 var(--space-3); + border: 1px solid var(--text-muted); + border-radius: var(--radius); + background: var(--bg); + color: var(--text); + font-family: var(--font-mono); + font-size: var(--text-sm); +} + +input[aria-invalid="true"] { + border-color: var(--status-error); +} + +.hint { + margin: 0 0 var(--space-2); + color: var(--text-muted); + font-size: var(--text-sm); +} + +.refusal { + margin: 0 0 var(--space-2); + color: var(--status-error); + font-size: var(--text-sm); + font-weight: 500; +} + +/* The shell: header and nav on top on a phone, nav beside the view from 768px. */ + +.shell { + display: grid; + grid-template-columns: minmax(0, 1fr); + grid-template-areas: + "topbar" + "nav" + "main"; + min-height: 100vh; +} + +.topbar { + grid-area: topbar; + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-4); + padding: var(--space-3) var(--space-4); + border-bottom: 1px solid var(--border); +} + +.nav { + grid-area: nav; + border-bottom: 1px solid var(--border); +} + +.nav ul { + display: flex; + flex-wrap: wrap; + margin: 0; + padding: 0 var(--space-2); + list-style: none; +} + +.nav a { + display: block; + padding: var(--space-3) var(--space-2); + border-bottom: 2px solid transparent; + color: var(--text-muted); + font-size: var(--text-sm); + font-weight: 500; + text-decoration: none; +} + +.nav a:hover { + color: var(--text); +} + +.nav a[aria-current="page"] { + border-bottom-color: var(--accent); + color: var(--text); +} + +.main { + grid-area: main; + min-width: 0; + padding: var(--space-6) var(--space-4); +} + +.main:focus { + outline: none; +} + +@media (min-width: 768px) { + .shell { + grid-template-columns: 200px minmax(0, 1fr); + grid-template-rows: auto 1fr; + grid-template-areas: + "topbar topbar" + "nav main"; + } + + .nav { + border-bottom: 0; + border-right: 1px solid var(--border); + } + + .nav ul { + flex-direction: column; + padding: var(--space-4) 0; + } + + .nav a { + padding: var(--space-2) var(--space-4); + border-bottom: 0; + border-left: 2px solid transparent; + } + + .nav a[aria-current="page"] { + border-left-color: var(--accent); + } + + .main { + padding: var(--space-8); + } +} + +@media (prefers-reduced-motion: reduce) { + :root { + --duration: 0ms; + } +} diff --git a/ui/src/views/coming-soon.tsx b/ui/src/views/coming-soon.tsx new file mode 100644 index 000000000..b6c508e52 --- /dev/null +++ b/ui/src/views/coming-soon.tsx @@ -0,0 +1,9 @@ +/** A view whose data has not been built yet. */ +export function ComingSoon({ title }: { readonly title: string }) { + return ( +
+

{title}

+

Coming soon.

+
+ ); +} diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx new file mode 100644 index 000000000..ecd4546c6 --- /dev/null +++ b/ui/src/views/index.tsx @@ -0,0 +1,27 @@ +import type { ComponentType } from "react"; + +import { ComingSoon } from "./coming-soon"; + +/** + * Every view the console has, in navigation order. An entry is one nav link and one page: its + * `path` is the page's URL, `label` names it in the nav and the page title, and `Component` + * renders the page inside the shell. Adding a view is adding an entry here. + */ +export interface View { + readonly path: `/${string}`; + readonly label: string; + readonly Component: ComponentType; +} + +export const VIEWS: readonly View[] = [ + { path: "/workers", label: "Workers", Component: () => }, + { path: "/leases", label: "Leases", Component: () => }, + { path: "/waiting", label: "Waiting", Component: () => }, + { path: "/attention", label: "Attention", Component: () => }, + { path: "/events", label: "Events", Component: () => }, +]; + +/** The view a path shows, or `undefined` for a path the console has no view for. */ +export function viewFor(path: string): View | undefined { + return VIEWS.find((view) => path === view.path || path.startsWith(`${view.path}/`)); +} diff --git a/ui/src/views/not-found.tsx b/ui/src/views/not-found.tsx new file mode 100644 index 000000000..173304d7d --- /dev/null +++ b/ui/src/views/not-found.tsx @@ -0,0 +1,18 @@ +import { Link } from "../router"; +import { VIEWS } from "./index"; + +/** A path the console has no view for, such as an old or mistyped link. */ +export function NotFound() { + const home = VIEWS[0]; + return ( +
+

Page not found

+

The console has no page at this address.

+ {home === undefined ? null : ( +

+ Go to {home.label} +

+ )} +
+ ); +} diff --git a/ui/tsconfig.json b/ui/tsconfig.json new file mode 100644 index 000000000..c00a5fb40 --- /dev/null +++ b/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "isolatedModules": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["**/*.ts", "**/*.tsx"] +} diff --git a/ui/vite.config.ts b/ui/vite.config.ts new file mode 100644 index 000000000..1dc718978 --- /dev/null +++ b/ui/vite.config.ts @@ -0,0 +1,23 @@ +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +/** + * The web console's build (ADR 0011 §1, §2, §7). Run with `ui` as Vite's root (`vite build ui`), + * so every path below is relative to this directory. + */ +export default defineConfig({ + plugins: [react()], + build: { + // `dist/ui`, beside the daemon's own build: the package already publishes `dist`. + outDir: "../dist/ui", + emptyOutDir: true, + // No font or image becomes a `data:` URI: the CSP allows fonts and images from `'self'` only. + assetsInlineLimit: 0, + // Nothing to polyfill in the browsers the console supports, and nothing inline either. + modulePreload: { polyfill: false }, + }, + server: { + // Development only: a local daemon with `http.enabled` answers `/v1` on its default port. + proxy: { "/v1": "http://127.0.0.1:4700" }, + }, +}); diff --git a/vitest.config.ts b/vitest.config.ts index 9cee5bb05..8f2f57071 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -9,7 +9,9 @@ export default defineConfig({ { test: { name: "unit", - include: ["src/**/*.test.ts"], + // `ui/` holds the console's own unit tests: plain functions, no browser. The browser + // lane is Playwright's (`pnpm test:console`). + include: ["src/**/*.test.ts", "ui/**/*.test.ts"], }, }, { From 88cbe05a9395a9bdf499cb2c3b2ee71ca596d827 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 20:48:41 +0200 Subject: [PATCH 2/3] fix(ui,http,contract,docs): answer review findings on the console --- docs/CONSOLE.md | 2 +- docs/internal/DESIGN.md | 2 +- docs/internal/agent-rules/documentation.md | 2 +- e2e/console/fixtures.ts | 6 ++-- e2e/console/sign-in.spec.ts | 37 ++++++++++++++++++++++ src/contract/console-url.test.ts | 24 +++++++++++++- src/contract/console-url.ts | 11 +++++-- src/contract/operations.ts | 4 ++- src/http/server.test.ts | 31 ++++++++++++++++-- src/http/server.ts | 17 ++++++---- ui/src/api.test.ts | 2 ++ ui/src/console-context.tsx | 1 - ui/src/router.test.ts | 16 ++++++++++ ui/src/router.tsx | 4 ++- ui/src/shell.tsx | 16 +++++++--- ui/src/sign-in-check.test.ts | 12 +++++++ ui/src/sign-in.tsx | 4 ++- ui/src/views/index.test.ts | 23 ++++++++++++++ ui/src/views/index.tsx | 6 +++- 19 files changed, 194 insertions(+), 26 deletions(-) create mode 100644 ui/src/router.test.ts create mode 100644 ui/src/views/index.test.ts diff --git a/docs/CONSOLE.md b/docs/CONSOLE.md index 25055f80a..533722cf2 100644 --- a/docs/CONSOLE.md +++ b/docs/CONSOLE.md @@ -83,7 +83,7 @@ The console keeps the token in this browser tab only. - **Close the tab** and you are signed out. - **Sign out** forgets the token at once. - If the token is **revoked**, the console signs you out the next time it asks - the daemon for anything. + the daemon for anything, and at the latest when you reload. Some browsers copy a tab's storage into a duplicated or reopened tab, so such a tab may still be signed in. diff --git a/docs/internal/DESIGN.md b/docs/internal/DESIGN.md index 9015f7b7a..42eb9cc97 100644 --- a/docs/internal/DESIGN.md +++ b/docs/internal/DESIGN.md @@ -88,7 +88,7 @@ A 4px grid: `--space-1` 4px, `--space-2` 8px, `--space-3` 12px, `--space-4` 16px, `--space-6` 24px, `--space-8` 32px, `--space-12` 48px. Pick from the scale; never a value between. -- Controls are at least 40px tall, so they are easy to hit on a phone. +- Buttons and inputs are at least 40px tall, so they are easy to hit on a phone. - A page has 16px side padding on a phone and 32px from 768px up. ## Layout diff --git a/docs/internal/agent-rules/documentation.md b/docs/internal/agent-rules/documentation.md index 1f6fcae5a..968f9064b 100644 --- a/docs/internal/agent-rules/documentation.md +++ b/docs/internal/agent-rules/documentation.md @@ -19,7 +19,7 @@ grounds for rejecting a change even if the prose reads well. sentence — never leave a dangling reference to an internal doc standing in for an explanation. This applies to `docs/ABOUT.md`, `docs/CLI.md`, `docs/CLIENT.md`, `docs/CONFIGURATION.md`, `docs/HTTP-API.md`, - `docs/EVENTS.md`, and `README.md`. + `docs/CONSOLE.md`, `docs/EVENTS.md`, and `README.md`. 3. **Nothing the running tool prints or returns ever names a file path in this repository.** `--help` text, usage banners, error messages, and HTTP error bodies must not tell a user to go read a specific markdown file — diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 2710a131d..47323e123 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { test as base, expect, type Page } from "@playwright/test"; -import { cli } from "../helpers/cli.js"; +import { cli, type CliResult } from "../helpers/cli.js"; import { freeLoopbackPort } from "../helpers/port.js"; import { REPO_ROOT } from "../helpers/repo-root.js"; import { waitFor } from "../helpers/wait.js"; @@ -19,6 +19,8 @@ import { waitFor } from "../helpers/wait.js"; export interface ConsoleDaemon { /** The console's address, exactly as `simlock status --json` reports it. */ readonly url: string; + /** Runs `simlock` against this daemon, for a test that changes its state (a revoked token). */ + readonly cli: (args: readonly string[]) => Promise; readonly tokens: { readonly operator: string; readonly agent: string; @@ -81,7 +83,7 @@ async function startDaemon(mode: "worker" | "gateway"): Promise<{ }, { label: "HTTP listener accepting connections" }, ); - return { daemon: { tokens, url: url ?? "" }, stop }; + return { daemon: { cli: (args) => cli(args, env), tokens, url: url ?? "" }, stop }; } catch (error: unknown) { await stop(); throw error; diff --git a/e2e/console/sign-in.spec.ts b/e2e/console/sign-in.spec.ts index ee06d820c..8812028fc 100644 --- a/e2e/console/sign-in.spec.ts +++ b/e2e/console/sign-in.spec.ts @@ -16,6 +16,43 @@ test.describe("sign-in", () => { await expect(page.getByLabel("Operator token")).toHaveCount(0); }); + test("the navigation marks the current page, and the tab's title names it", async ({ + daemon, + page, + }) => { + await page.goto("/"); + await signIn(page, daemon.tokens.operator); + const nav = page.getByRole("navigation", { name: "Console" }); + + await expect(nav.locator("[aria-current='page']")).toHaveText("Workers"); + await expect(page).toHaveTitle("Workers · Simlock"); + await nav.getByRole("link", { name: "Events" }).click(); + + await expect(nav.locator("[aria-current='page']")).toHaveText("Events"); + await expect(page).toHaveTitle("Events · Simlock"); + }); + + test("a token pasted with spaces around it signs in", async ({ daemon, page }) => { + await page.goto("/"); + await signIn(page, ` ${daemon.tokens.operator}\n`); + + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); + }); + + test("a revoked token is signed out on the next reload", async ({ daemon, page }) => { + const minted = await daemon.cli(["token", "create", "--role", "operator"]); + const { secret, token } = minted.json as { secret: string; token: { id: string } }; + await page.goto("/"); + await signIn(page, secret); + await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible(); + + expect((await daemon.cli(["token", "revoke", token.id])).code).toBe(0); + await page.reload(); + + await expect(page.getByLabel("Operator token")).toBeVisible(); + await expect(page.getByRole("button", { name: "Sign out" })).toHaveCount(0); + }); + test("an agent token is refused with a message that the console needs an operator token", async ({ daemon, page, diff --git a/src/contract/console-url.test.ts b/src/contract/console-url.test.ts index 855db9b7e..89e788ebb 100644 --- a/src/contract/console-url.test.ts +++ b/src/contract/console-url.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; -import { consoleUrl } from "./console-url.js"; +import { CONSOLE_URL_MAX_LENGTH, consoleUrl, consoleUrlField } from "./console-url.js"; +import { OPERATIONS } from "./operations.js"; describe("consoleUrl", () => { it("consoleUrl shows localhost for an unspecified host and brackets an IPv6 host", () => { @@ -10,6 +11,8 @@ describe("consoleUrl", () => { expect(at("::")).toBe("http://localhost:4700/"); expect(at("::1")).toBe("http://[::1]:4700/"); expect(at("fd7a:115c:a1e0::1")).toBe("http://[fd7a:115c:a1e0::1]:4700/"); + // Written already bracketed, it is not bracketed twice. + expect(at("[::1]")).toBe("http://[::1]:4700/"); expect(at("127.0.0.1")).toBe("http://127.0.0.1:4700/"); expect(at("mac-mini.tailnet.ts.net")).toBe("http://mac-mini.tailnet.ts.net:4700/"); }); @@ -18,3 +21,22 @@ describe("consoleUrl", () => { expect(consoleUrl({ enabled: false, host: "127.0.0.1", port: 4700 })).toBeUndefined(); }); }); + +describe("consoleUrlField", () => { + it("leaves out an address over status.get's bound, which the wire refuses", () => { + const longest = "a".repeat(CONSOLE_URL_MAX_LENGTH - "http://:4700/".length); + const fits = consoleUrlField({ enabled: true, host: longest, port: 4700 }); + const over = consoleUrlField({ enabled: true, host: `${longest}a`, port: 4700 }); + const daemonBlock = OPERATIONS["status.get"].output.shape.daemon; + + expect(fits.consoleUrl).toHaveLength(CONSOLE_URL_MAX_LENGTH); + expect(over).toEqual({}); + expect( + daemonBlock.safeParse({ + health: "running", + mode: "worker", + consoleUrl: `${fits.consoleUrl}x`, + }).success, + ).toBe(false); + }); +}); diff --git a/src/contract/console-url.ts b/src/contract/console-url.ts index cdc6f0af5..5387faf34 100644 --- a/src/contract/console-url.ts +++ b/src/contract/console-url.ts @@ -5,6 +5,12 @@ export interface ConsoleHttpConfig { readonly port: number; } +/** + * `status.get`'s bound on `daemon.consoleUrl`. Far above any real address: a DNS name is at most + * 253 characters. + */ +export const CONSOLE_URL_MAX_LENGTH = 512; + /** Hosts that mean "every interface": a browser cannot open them, so the address names this machine. */ const UNSPECIFIED_HOSTS = new Set(["0.0.0.0", "::"]); @@ -25,9 +31,10 @@ export function consoleUrl(http: ConsoleHttpConfig): string | undefined { /** * `status.get`'s `daemon.consoleUrl`, ready to spread into the `daemon` block: absent rather * than `undefined` when HTTP is off. A worker's and a gateway's dispatcher both call this, so - * the two cannot report the address differently. + * the two cannot report the address differently. An address over the bound is left out rather + * than failing the daemon's own `status.get`. */ export function consoleUrlField(http: ConsoleHttpConfig): { readonly consoleUrl?: string } { const url = consoleUrl(http); - return url === undefined ? {} : { consoleUrl: url }; + return url === undefined || url.length > CONSOLE_URL_MAX_LENGTH ? {} : { consoleUrl: url }; } diff --git a/src/contract/operations.ts b/src/contract/operations.ts index 7ac689b40..77d9ffa91 100644 --- a/src/contract/operations.ts +++ b/src/contract/operations.ts @@ -9,6 +9,7 @@ */ import { z } from "zod"; +import { CONSOLE_URL_MAX_LENGTH } from "./console-url.js"; import { ownsLease, type AuthorizeContext, type Role } from "./roles.js"; import { cleanupRuleSummarySchema, @@ -108,7 +109,8 @@ export const statusGet = defineOperation({ daemon: z.object({ health: daemonHealthSchema, mode: daemonModeSchema, - consoleUrl: z.string().optional(), + // Bounded: a gateway parses every worker's answer (safety rule 10). + consoleUrl: z.string().max(CONSOLE_URL_MAX_LENGTH).optional(), }), /** * ADR 0008 §5: the machine, beside `daemon`, the process. Served from memory, so reading it diff --git a/src/http/server.test.ts b/src/http/server.test.ts index 6941970b7..c0b28cc7b 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -92,6 +92,28 @@ describe("withConsole", () => { expect(await response.text()).not.toContain(PAGE); }); + it("a path under /assets/ with no file extension answers 404, never the page", async () => { + const { get } = harness(await builtConsole()); + + for (const path of ["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/assets/chunk", "/assets/"]) { + const response = await get(path); + expect(response.status, path).toBe(404); + expect(response.headers.get("cache-control"), path).toBe("no-cache"); + expect(await response.text(), path).not.toContain(PAGE); + } + }); + + it("GET /v1 itself goes to the API, not the page", async () => { + const { app, get } = harness(await builtConsole()); + + const response = await get("/v1"); + const direct = await app.request("/v1"); + + expect(response.status).toBe(direct.status); + expect(await response.text()).toBe(await direct.text()); + expect(response.headers.get("content-security-policy")).toBeNull(); + }); + it("GET /v1/unknown answers the API's 404, not the page", async () => { const { app, get } = harness(await builtConsole()); @@ -184,11 +206,16 @@ describe("withConsole", () => { expect(logged).toEqual(["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/v1/status"]); }); - it("answers 404 on every console path when the console is not built", async () => { - const { get } = harness(await emptyRoot()); + it("answers 404 on the page and on files when the console is not built", async () => { + const root = await emptyRoot(); + // A stray file in an unbuilt root is still not served: without index.html there is no console. + await writeFile(join(root, "favicon.svg"), ""); + const { get } = harness(root); expect((await get("/")).status).toBe(404); expect((await get("/workers")).status).toBe(404); + expect((await get("/favicon.svg")).status).toBe(404); + expect((await get("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/assets/index-3f2a9c.js")).status).toBe(404); expect((await get("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/v1/healthz")).status).toBe(200); }); }); diff --git a/src/http/server.ts b/src/http/server.ts index 21031f805..e030f3afd 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -68,8 +68,8 @@ export interface FetchApp { * other path is the console's: * * - a `GET`/`HEAD` for a file in `root` serves that file; - * - a `GET`/`HEAD` for a path with no file extension serves `index.html`, so a page URL - * survives a reload; + * - a `GET`/`HEAD` for a path with no file extension, outside `/assets/`, serves + * `index.html`, so a page URL survives a reload; * - anything else is `404`, so a missing asset is never answered with the page. * * Console files need no token -- they hold no data -- and never reach the app, so they are @@ -82,7 +82,7 @@ export function withConsole(app: FetchApp, options: { root: string; logger: Logg if (existsSync(join(options.root, "index.html"))) { const page = serveStatic({ root: options.root, path: "index.html" }); files.on(["GET", "HEAD"], "*", serveStatic({ root: options.root }), (c, next) => - hasFileExtension(c.req.path) ? next() : page(c, next), + isPagePath(c.req.path) ? page(c, next) : next(), ); } else { options.logger.warn("The web console is not built; console paths answer 404", { @@ -100,9 +100,14 @@ export function withConsole(app: FetchApp, options: { root: string; logger: Logg }; } -/** Whether the path's last segment names a file (`/assets/index-3f2a.js`), not a page (`/workers`). */ -function hasFileExtension(path: string): boolean { - return path.slice(path.lastIndexOf("/") + 1).includes("."); +/** + * Whether a path names a page (`/workers`) rather than a file (`/favicon.svg`). Nothing under + * `/assets/` is a page: that directory holds only built files, which are cached for good, so + * the page must never be answered there. + */ +function isPagePath(path: string): boolean { + if (path.startsWith("/assets/")) return false; + return !path.slice(path.lastIndexOf("/") + 1).includes("."); } /** diff --git a/ui/src/api.test.ts b/ui/src/api.test.ts index 0e1c21017..9d034b00b 100644 --- a/ui/src/api.test.ts +++ b/ui/src/api.test.ts @@ -71,6 +71,8 @@ describe("createApiClient", () => { expect(calls[0]?.input).toBe("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/v1/workers"); expect(calls[0]?.init.headers).toEqual({ Authorization: "Bearer slk_op" }); expect(calls[0]?.init.credentials).toBe("omit"); + // Never answered from the browser's cache: what the daemon holds now is the answer. + expect(calls[0]?.init.cache).toBe("no-store"); await expect(api.getJson("//elsewhere.example/v1/workers" as ApiPath)).rejects.toThrow( "Not an API path", ); diff --git a/ui/src/console-context.tsx b/ui/src/console-context.tsx index 65ed23512..3f4bea6e8 100644 --- a/ui/src/console-context.tsx +++ b/ui/src/console-context.tsx @@ -22,7 +22,6 @@ function useServices(): ConsoleServices { } /** The daemon's API for the signed-in operator. Every view reads its data through this. */ -// fallow-ignore-next-line unused-export -- the read path every data view uses; the shell itself shows none yet. export function useApi(): ApiClient { return useServices().api; } diff --git a/ui/src/router.test.ts b/ui/src/router.test.ts new file mode 100644 index 000000000..030c4648b --- /dev/null +++ b/ui/src/router.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; + +import { opensInThisTab } from "./router"; + +const plain = { altKey: false, button: 0, ctrlKey: false, metaKey: false, shiftKey: false }; + +describe("opensInThisTab", () => { + it("handles a plain primary click in the console, and leaves every other click to the browser", () => { + expect(opensInThisTab(plain)).toBe(true); + // A middle click, or a click with a modifier, opens a new tab or window as it always does. + expect(opensInThisTab({ ...plain, button: 1 })).toBe(false); + for (const key of ["altKey", "ctrlKey", "metaKey", "shiftKey"] as const) { + expect(opensInThisTab({ ...plain, [key]: true }), key).toBe(false); + } + }); +}); diff --git a/ui/src/router.tsx b/ui/src/router.tsx index 91e954ab2..34e9b43c5 100644 --- a/ui/src/router.tsx +++ b/ui/src/router.tsx @@ -33,8 +33,10 @@ interface LinkProps extends Omit, "href" const MODIFIER_KEYS = ["altKey", "ctrlKey", "metaKey", "shiftKey"] as const; +type ClickKeys = Pick; + /** A primary click with no modifier key: the browser would open the link in this tab. */ -function opensInThisTab(event: MouseEvent): boolean { +export function opensInThisTab(event: ClickKeys): boolean { return event.button === 0 && !MODIFIER_KEYS.some((key) => event[key]); } diff --git a/ui/src/shell.tsx b/ui/src/shell.tsx index facf6a383..09ee29f59 100644 --- a/ui/src/shell.tsx +++ b/ui/src/shell.tsx @@ -1,20 +1,26 @@ import { useEffect } from "react"; -import { useSession } from "./console-context"; +import { useApi, useSession } from "./console-context"; import { Link, navigate, usePath } from "./router"; import { VIEWS, viewFor } from "./views/index"; import { NotFound } from "./views/not-found"; /** The signed-in console: the header, the navigation from `VIEWS`, and the current view. */ export function Shell() { + const api = useApi(); const session = useSession(); const path = usePath(); const view = viewFor(path); - const home = VIEWS[0]; + // ADR 0011 §6: a 401 at any time signs the operator out. A tab reloaded with a token that has + // since been revoked finds out here, before any view asks for data. useEffect(() => { - if (path === "/" && home !== undefined) navigate(home.path, { replace: true }); - }, [path, home]); + api.getJson("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/v1/workers").catch(() => undefined); + }, [api]); + + useEffect(() => { + if (path === "/" && view !== undefined) navigate(view.path, { replace: true }); + }, [path, view]); useEffect(() => { document.title = view === undefined ? "Simlock" : `${view.label} · Simlock`; @@ -46,7 +52,7 @@ export function Shell() {
- {view === undefined ? path === "/" ? null : : } + {view === undefined ? : }
); diff --git a/ui/src/sign-in-check.test.ts b/ui/src/sign-in-check.test.ts index a6c1db6cc..a5bbb2cc0 100644 --- a/ui/src/sign-in-check.test.ts +++ b/ui/src/sign-in-check.test.ts @@ -67,6 +67,18 @@ describe("checkToken", () => { expect(refusalMessage({ kind: "unreachable" })).toBe("The daemon cannot be reached."); }); + it("says the daemon cannot be reached when something else answers /v1/healthz", async () => { + // A daemon always answers its liveness route with 200; a proxy with no daemon behind it + // answers 502. + expect(await checkToken("slk_op", daemon(502, 200))).toEqual({ kind: "unreachable" }); + }); + + it("says the daemon cannot be reached when /v1/workers fails at the network level", async () => { + expect(await checkToken("slk_op", daemon(200, "network-error"))).toEqual({ + kind: "unreachable", + }); + }); + it("reports any other answer from /v1/workers with its status", async () => { const outcome = await checkToken("slk_op", daemon(200, 500)); diff --git a/ui/src/sign-in.tsx b/ui/src/sign-in.tsx index ec887a3b3..552cc8308 100644 --- a/ui/src/sign-in.tsx +++ b/ui/src/sign-in.tsx @@ -9,8 +9,10 @@ function useSignIn(fetch: Fetch) { const session = useSession(); const [checking, setChecking] = useState(false); const [refusal, setRefusal] = useState(undefined); + // No guard against a second submit while checking: the disabled button blocks it, the Enter + // key included, since a form with a disabled submit button does not submit implicitly. const submit = async (token: string) => { - if (token === "" || checking) return; + if (token === "") return; setChecking(true); setRefusal(undefined); const outcome = await checkToken(token, fetch); diff --git a/ui/src/views/index.test.ts b/ui/src/views/index.test.ts new file mode 100644 index 000000000..1e30513d4 --- /dev/null +++ b/ui/src/views/index.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from "vitest"; + +import { VIEWS, viewFor } from "./index"; + +describe("viewFor", () => { + it("finds each view by its path, and the first view at /", () => { + expect(VIEWS.map((view) => view.label)).toEqual([ + "Workers", + "Leases", + "Waiting", + "Attention", + "Events", + ]); + for (const view of VIEWS) expect(viewFor(view.path)).toBe(view); + expect(viewFor("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/leases/lease_1")?.label).toBe("Leases"); + expect(viewFor("/")).toBe(VIEWS[0]); + }); + + it("finds no view for a path the console does not have", () => { + expect(viewFor("/no-such-page")).toBeUndefined(); + expect(viewFor("/workersx")).toBeUndefined(); + }); +}); diff --git a/ui/src/views/index.tsx b/ui/src/views/index.tsx index ecd4546c6..2c38f8649 100644 --- a/ui/src/views/index.tsx +++ b/ui/src/views/index.tsx @@ -21,7 +21,11 @@ export const VIEWS: readonly View[] = [ { path: "/events", label: "Events", Component: () => }, ]; -/** The view a path shows, or `undefined` for a path the console has no view for. */ +/** + * The view a path shows, or `undefined` for a path the console has no view for. `/` shows the + * first view; the shell then rewrites the address to that view's own path. + */ export function viewFor(path: string): View | undefined { + if (path === "/") return VIEWS[0]; return VIEWS.find((view) => path === view.path || path.startsWith(`${view.path}/`)); } From 8d8a051d859eabd52e4b662e7e421e78703b3798 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Fri, 2 Oct 2026 21:05:26 +0200 Subject: [PATCH 3/3] fix(ui,http,docs): answer the second round of review findings --- docs/HTTP-API.md | 7 +++-- e2e/console/shell.spec.ts | 20 ++++++------ e2e/console/sign-in.spec.ts | 23 ++++++++++++++ src/http/server.test.ts | 5 ++- ui/src/api.test.ts | 26 +++++++++++++++ ui/src/main.tsx | 10 +----- ui/src/session.test.ts | 61 ++++++++++++++++++++++++++++++++++++ ui/src/session.ts | 23 +++++++------- ui/src/sign-in-check.test.ts | 12 +++++++ ui/src/sign-in-check.ts | 6 ++++ 10 files changed, 160 insertions(+), 33 deletions(-) create mode 100644 ui/src/session.test.ts diff --git a/docs/HTTP-API.md b/docs/HTTP-API.md index b161c304e..d34a4f77c 100644 --- a/docs/HTTP-API.md +++ b/docs/HTTP-API.md @@ -148,9 +148,10 @@ daemon answered: **`consoleUrl`** is the web console's address (see [CONSOLE.md](CONSOLE.md)): `http://:/`, with `localhost` for a host of `0.0.0.0` or -`::` and an IPv6 host in brackets. Since HTTP has to be on to reach this route, -an HTTP answer always carries it; over the unix socket it is absent while HTTP -is off. An older daemon sends none. +`::` and an IPv6 host in brackets. It is present whenever HTTP is on, so an +HTTP answer carries it; over the unix socket it is absent while HTTP is off. +It is also left out if the address would be longer than 512 characters, which +no real host name is. An older daemon sends none. Beside it, **`host`** says what machine the daemon runs on: the operating system, its version, the CPU architecture, and the version of each platform diff --git a/e2e/console/shell.spec.ts b/e2e/console/shell.spec.ts index b9bbd9fcd..d874ef032 100644 --- a/e2e/console/shell.spec.ts +++ b/e2e/console/shell.spec.ts @@ -60,16 +60,18 @@ test.describe("the shell", () => { expect(controls).toEqual(["Skip to content", "Sign out", ...NAV_LABELS]); expect(visited).toEqual(controls); - // Each control does its job from the keyboard. Focus is on the last nav link, Events. - await page.keyboard.press(back); - await expect(page.getByRole("link", { name: "Attention" })).toBeFocused(); - await page.keyboard.press("Enter"); - await expect(page).toHaveURL(/\/attention$/); - await expect(page.getByRole("heading", { level: 1, name: "Attention" })).toBeVisible(); + // Each control does its job from the keyboard. Focus is on the last nav link, Events; walk + // back through every nav link and open each one with Enter. + for (const [index, label] of [...NAV_LABELS].reverse().entries()) { + if (index > 0) await page.keyboard.press(back); + await expect(page.getByRole("link", { name: label })).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(new RegExp(`/${label.toLowerCase()}$`)); + await expect(page.getByRole("heading", { level: 1, name: label })).toBeVisible(); + } - // Back past Waiting, Leases, Workers and Sign out to the skip link, which moves focus to - // the view. - await pressTimes(back, 5); + // Back past Sign out to the skip link, which moves focus to the view. + await pressTimes(back, 2); await expect(page.getByRole("link", { name: "Skip to content" })).toBeFocused(); await page.keyboard.press("Enter"); await expect(page.locator("#main")).toBeFocused(); diff --git a/e2e/console/sign-in.spec.ts b/e2e/console/sign-in.spec.ts index 8812028fc..32cfbf83f 100644 --- a/e2e/console/sign-in.spec.ts +++ b/e2e/console/sign-in.spec.ts @@ -30,6 +30,29 @@ test.describe("sign-in", () => { await expect(nav.locator("[aria-current='page']")).toHaveText("Events"); await expect(page).toHaveTitle("Events · Simlock"); + + // The browser's back and forward move between the console's pages too. + await page.goBack(); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + await expect(nav.locator("[aria-current='page']")).toHaveText("Workers"); + await page.goForward(); + await expect(page.getByRole("heading", { level: 1, name: "Events" })).toBeVisible(); + }); + + test("signing in with an empty field asks the daemon nothing", async ({ page }) => { + await page.goto("/"); + const asked: string[] = []; + page.on("request", (request) => { + if (new URL(request.url()).pathname.startsWith("/v1/")) asked.push(request.url()); + }); + + await page.getByRole("button", { name: "Sign in" }).click(); + await page.getByLabel("Operator token").fill(" "); + await page.getByRole("button", { name: "Sign in" }).click(); + + await expect(page.getByLabel("Operator token")).toBeVisible(); + await expect(page.getByRole("alert")).toHaveCount(0); + expect(asked).toEqual([]); }); test("a token pasted with spaces around it signs in", async ({ daemon, page }) => { diff --git a/src/http/server.test.ts b/src/http/server.test.ts index c0b28cc7b..ae2b9de03 100644 --- a/src/http/server.test.ts +++ b/src/http/server.test.ts @@ -237,11 +237,14 @@ describe("HttpGateway", () => { it("the daemon warns once at start when the console is not built", async () => { const { gateway, port, warnings } = await started(await emptyRoot()); try { + // Already logged once the listener is up, before any request arrives. + const atStart = warnings(); const page = await fetch(`http://127.0.0.1:${port}/`); await fetch(`http://127.0.0.1:${port}/workers`); + expect(atStart).toEqual(["The web console is not built; console paths answer 404"]); expect(page.status).toBe(404); - expect(warnings()).toEqual(["The web console is not built; console paths answer 404"]); + expect(warnings()).toEqual(atStart); } finally { await gateway.stop(); } diff --git a/ui/src/api.test.ts b/ui/src/api.test.ts index 9d034b00b..62189e1bd 100644 --- a/ui/src/api.test.ts +++ b/ui/src/api.test.ts @@ -62,6 +62,32 @@ describe("createApiClient", () => { expect(await outcome).toBeInstanceOf(RequestTimeoutError); }); + it("the 10 seconds cover reading the body, not only the headers", async () => { + vi.useFakeTimers(); + // Headers at once, then a body that never ends, as a real fetch's body does until its + // request is aborted. + const stalledBody: Fetch = async (_input, init) => + new Response( + new ReadableStream({ + start(controller) { + init.signal?.addEventListener("abort", () => controller.error(init.signal?.reason)); + }, + }), + { status: 200 }, + ); + const api = createApiClient({ fetch: stalledBody, signOut: () => {}, token: () => "slk_op" }); + + const outcome = api.getJson("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/v1/workers").then( + () => "answered", + (error: unknown) => error, + ); + await vi.advanceTimersByTimeAsync(10_000); + + expect(await Promise.race([outcome, Promise.resolve("pending")])).toBeInstanceOf( + RequestTimeoutError, + ); + }); + it("sends the token only as a bearer header, to a relative /v1 path", async () => { const { calls, fetch } = answering(200, { workers: [] }); const api = createApiClient({ fetch, signOut: () => {}, token: () => "slk_op" }); diff --git a/ui/src/main.tsx b/ui/src/main.tsx index 188c9d417..d09569969 100644 --- a/ui/src/main.tsx +++ b/ui/src/main.tsx @@ -9,16 +9,8 @@ import { createApiClient, type Fetch } from "./api"; import { App } from "./app"; import { createSession } from "./session"; -function sessionStorageOrNone(): Storage | undefined { - try { - return window.sessionStorage; - } catch { - return undefined; - } -} - const fetch: Fetch = (input, init) => window.fetch(input, init); -const session = createSession(sessionStorageOrNone()); +const session = createSession(() => window.sessionStorage); const api = createApiClient({ fetch, signOut: session.signOut, token: session.token }); const root = document.getElementById("root"); diff --git a/ui/src/session.test.ts b/ui/src/session.test.ts new file mode 100644 index 000000000..9cf8034a1 --- /dev/null +++ b/ui/src/session.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from "vitest"; + +import { createSession } from "./session"; + +/** A `sessionStorage` stand-in that keeps what it is given. */ +function memoryStorage() { + const items = new Map(); + return { + items, + getItem: (key: string) => items.get(key) ?? null, + removeItem: (key: string) => void items.delete(key), + setItem: (key: string, value: string) => void items.set(key, value), + }; +} + +const refusing = { + getItem: (): string | null => { + throw new DOMException("blocked", "SecurityError"); + }, + removeItem: (): void => { + throw new DOMException("blocked", "SecurityError"); + }, + setItem: (): void => { + throw new DOMException("blocked", "SecurityError"); + }, +}; + +describe("createSession", () => { + it("keeps the token in storage, so a reloaded page starts signed in", () => { + const storage = memoryStorage(); + const first = createSession(() => storage); + const changes: (string | undefined)[] = []; + first.subscribe(() => changes.push(first.token())); + + first.signIn("slk_op"); + const reloaded = createSession(() => storage); + first.signOut(); + const afterSignOut = createSession(() => storage); + + expect(reloaded.token()).toBe("slk_op"); + expect(afterSignOut.token()).toBeUndefined(); + expect(storage.items.size).toBe(0); + expect(changes).toEqual(["slk_op", undefined]); + }); + + it("still signs in and out when the browser refuses storage, keeping the token in the page", () => { + // Either each call is refused, or reading `window.sessionStorage` itself throws. + const unreachable = (): typeof refusing => { + throw new DOMException("blocked", "SecurityError"); + }; + for (const storage of [() => refusing, unreachable]) { + const session = createSession(storage); + + expect(session.token()).toBeUndefined(); + session.signIn("slk_op"); + expect(session.token()).toBe("slk_op"); + session.signOut(); + expect(session.token()).toBeUndefined(); + } + }); +}); diff --git a/ui/src/session.ts b/ui/src/session.ts index a7a9e606c..3e0b8301a 100644 --- a/ui/src/session.ts +++ b/ui/src/session.ts @@ -16,20 +16,20 @@ export interface Session { } /** - * `storage` may be missing or refuse writes (a browser with site data blocked). The console then + * `storage` is asked for lazily, because a browser with site data blocked throws on merely + * reading `window.sessionStorage`; it may also refuse each read and write. The console then * still signs in, and the token lives only as long as the page. */ -export function createSession(storage: Storage | undefined): Session { +export function createSession(storage: () => Storage): Session { const listeners = new Set<() => void>(); - let current = read(storage); + let current = attempt(() => storage().getItem(STORAGE_KEY) ?? undefined); const update = (token: string | undefined) => { current = token; - try { - if (token === undefined) storage?.removeItem(STORAGE_KEY); - else storage?.setItem(STORAGE_KEY, token); - } catch { - // Kept in memory only; see above. - } + attempt(() => + token === undefined + ? storage().removeItem(STORAGE_KEY) + : storage().setItem(STORAGE_KEY, token), + ); for (const listener of listeners) listener(); }; return { @@ -43,9 +43,10 @@ export function createSession(storage: Storage | undefined): Session { }; } -function read(storage: Storage | undefined): string | undefined { +/** Runs a storage call, treating a refusal as "nothing stored". */ +function attempt(call: () => T): T | undefined { try { - return storage?.getItem(STORAGE_KEY) ?? undefined; + return call(); } catch { return undefined; } diff --git a/ui/src/sign-in-check.test.ts b/ui/src/sign-in-check.test.ts index a5bbb2cc0..648c327fe 100644 --- a/ui/src/sign-in-check.test.ts +++ b/ui/src/sign-in-check.test.ts @@ -67,6 +67,18 @@ describe("checkToken", () => { expect(refusalMessage({ kind: "unreachable" })).toBe("The daemon cannot be reached."); }); + it("calls a token with a character no token has unknown, without asking the daemon", async () => { + const asked: string[] = []; + const recording: Fetch = (input, init) => { + asked.push(input); + return daemon(200, 200)(input, init); + }; + + expect(await checkToken("slk_abc…", recording)).toEqual({ kind: "unknown-token" }); + expect(await checkToken("slk_a b", recording)).toEqual({ kind: "unknown-token" }); + expect(asked).toEqual([]); + }); + it("says the daemon cannot be reached when something else answers /v1/healthz", async () => { // A daemon always answers its liveness route with 200; a proxy with no daemon behind it // answers 502. diff --git a/ui/src/sign-in-check.ts b/ui/src/sign-in-check.ts index a87aa320a..1b0ff5582 100644 --- a/ui/src/sign-in-check.ts +++ b/ui/src/sign-in-check.ts @@ -9,12 +9,18 @@ export type SignInOutcome = | { readonly kind: "unreachable" } | { readonly kind: "failed"; readonly status: number }; +const TOKEN_SHAPE = /^[\x21-\x7e]+$/; + /** * First `GET /v1/healthz`, to learn whether the daemon is up at all; then `GET /v1/workers`, a * read only an operator token may make, in both modes. A timeout on the second while the first * answered means the daemon is still starting: its reads wait until it is ready. */ export async function checkToken(token: string, fetch: Fetch): Promise { + // A token is printable ASCII. Anything else, such as a "…" copied from a document, cannot be + // one the daemon issued, and cannot go in a header either: `fetch` would refuse it with the + // same error as a network failure, and the screen would wrongly say the daemon is down. + if (!TOKEN_SHAPE.test(token)) return { kind: "unknown-token" }; try { const up = await send("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/v1/healthz", { fetch }, async (response) => response.ok); if (!up) return { kind: "unreachable" };