feat(daemon)!: phone-first binding and a two-step pairing flow

Implements ADR 0001 (docs/adr/0001-phone-first-pairing.md): the console is
meant to be opened from a phone, so reachability stops being a mode and the
pairing link becomes the only access control that matters.

Binding / CORS
- `PI2_HOST` defaults to `0.0.0.0`; `PI2_ACCESS_MODE` (local|lan|tailscale) is
  deleted, together with its parser, `AccessMode` type and LAN probe.
- `src/core/network.ts` is the single source of truth for reachable addresses:
  kind classification, ordering (public → lan → other → tailscale → loopback,
  physical NICs first, link-local skipped), bind-aware `networkBases()`,
  `primaryBase()` and `localOrigins()`. Config, the pairing route, doctor and
  the CLI all consume it, so the CORS allowlist always matches the pairing URL.
- `/api/v1/info` and `daemon.json` report `host` instead of `access`; doctor's
  `access` check becomes `bind` (loopback ok, wildcard warns unless an `https:`
  public URL is configured).

Pairing
- `POST /api/v1/pair` only mints, requires a token, and returns the code, the
  chosen URL, the expiry, the nonce, the QR matrix and every usable base.
  `base` may pin one of those bases; anything else is a 400.
- `POST /api/v1/pair/redeem` is the public half, rate limited per client
  (5/min) and globally (50/h) → 429 `E_RATE_LIMITED` with `retry-after`.
- `GET /pair/:code` answers 302 to `/connect?code=…&auto=1`, so a scanned link
  needs no JavaScript to reach the console.
- `src/core/qr.ts` (moved out of the CLI) is the one encoder: byte mode, EC
  level M, versions 1–10, rows without a quiet zone, shared by the HTTP mint
  response and the terminal renderer.
- `pi2 pairing` prints a human report plus a half-block terminal QR and keeps
  `--base`; `--json` and `--public-url` are gone (the Neovim client calls the
  HTTP mint directly).

Device scopes
- `Scope`, `SCOPES`, `DEFAULT_SCOPES`, `DeviceRecord.scopes` and the `scopes`
  field in device/hello payloads are removed: nothing enforced them, and a
  paired device now holds the same rights as the local browser. A permission
  model, if wanted, gets its own ADR.

Breaking: `PI2_ACCESS_MODE`, `info.access`, `pi2 status --json`'s `access`,
`pi2 pairing --json`/`--public-url`, `POST /api/v1/pair {code}`, and the
`scopes` field. All in-repo callers and the e2e drivers are updated; the plugin
side (`:PiWebAccess`, `env.PI2_ACCESS_MODE`, text-format parsing) follows in
pi2.nvim.

Verification: root typecheck clean; 369/370 tests (the one failure is the
pre-existing supervisor timing flake, 24/24 in isolation ×3); `smoke.sh` green;
web suite 299/299; visual matrix 24/24.
This commit is contained in:
yuez committed 2026-10-27 10:44:08 +08:00
1 parent 3789394c85
commit a57c874095
34 files changed
+2148 -479

No files matched your search

+4 -2
View File
@@ -30,7 +30,9 @@ Adding bulk to this file is a mistake, not a contribution.
| `src/instances/` | discovery, lazy spawn, one-instance-per-workspace, crash handling |
| `src/workspaces/` | registry, disk discovery, aliases/trust, visibility policy |
| `src/cli/` | `pi2` — `daemon`, `open`, `attach`, `status`, `doctor`, `pairing`, `install-service` |
| `src/config.ts` | env-only configuration (`PI2_*`, `PI2_ACCESS_MODE`, `PI2_WORKSPACE_*`) |
| `src/config.ts` | env-only configuration (`PI2_*`, `PI2_HOST`, `PI2_WORKSPACE_*`) |
| `src/core/network.ts` | reachable addresses: kind classification, `bases[]` order, CORS origins |
| `src/core/qr.ts` | zero-dependency QR encoder (pairing links; rows, no quiet zone) |
| `web/` | React console (own lockfile + workspace); built into `web/dist` and served by the daemon |
| `fixtures/` | golden event streams + expected state, shared with pi2.nvim conformance tests |
| `test/` | vitest, hermetic, injectable I/O |
@@ -68,7 +70,7 @@ owner/repo/workflow filename, not the npm name).
| `docs/deployment.md` | env vars, runtime files, ports, auth, services, troubleshooting |
| `docs/e2e.md` | scenario ids, isolation, skip conditions, report paths |
| `docs/releasing.md` | npm Trusted Publishing, the bootstrap phases, verification |
| `README.md` | install paths, `:PiWeb`, access modes |
| `README.md` | install paths, `:PiWeb`, binding & pairing |
| `.agents/skills/release/` | how to cut and verify a release |
## Before you say "done"
+16 -10
View File
@@ -79,23 +79,29 @@ The plugin looks for the daemon in this order, and `:PiWebStatus` reports which
## Remote access (phone, LAN, Tailscale)
The daemon binds `127.0.0.1` by default and never exposes itself to the network on its own.
`:PiWeb` asks once which access mode you want and remembers the answer; `web.access = "lan"`
(or `"tailscale"`, or `"local"`) skips the prompt.
The daemon binds `0.0.0.0` by default, so a phone on the same network can open the console;
access is gated by pairing codes and per-device tokens, never by the bind address. Set
`web.host = "127.0.0.1"` (or `PI2_HOST=127.0.0.1`) for a loopback-only daemon, and
`web.public_url` when a `tailscale serve` portal is in front.
| Mode | Bind | Browser access | Login |
|---|---|---|---|
| `local` | `127.0.0.1` | same machine | automatic (one-time token handed to the browser) |
| `lan` | `0.0.0.0` | `http://<lan-ip>:7676` | pairing code / QR, **never** automatic |
| `tailscale` | `127.0.0.1` + `tailscale serve` | `https://<host>.<tailnet>.ts.net` | pairing code / QR, **never** automatic |
| Bind (`PI2_HOST`) | Browser access | Login |
|---|---|---|
| unset → `0.0.0.0` | `http://127.0.0.1:7676` on the desktop, `http://<lan-ip>:7676` from a phone, or a `tailscale serve` URL | desktop: automatic one-time token; other devices: pairing code / QR |
| `127.0.0.1` | this machine only (put `tailscale serve` in front if you need remote access) | automatic one-time token |
Pair a device from the CLI:
```bash
pi2 pairing # loopback URL + code + QR payload
pi2 pairing --public-url https://myhost.tail1234.ts.net
pi2 pairing # phone-reachable URL + code + terminal QR
pi2 pairing --base https://myhost.tail1234.ts.net # pin the interface to advertise
```
The link is built on the primary LAN address by default, so scanning it from a phone
actually works — the link carries host, port and code, so opening it pairs the device with
no further input; the mint response additionally carries the QR module matrix (`qr.rows`) and every
selectable base (`bases`), which is what `:PiWebPair` in Neovim uses: pick an interface
(name + IP), then draw the code.
Or from the web console's device page. Tokens are per-device, revocable, and stored
hashed; `pi2 doctor` reports the active mode and warns when a non-loopback bind has no TLS.
+108
View File
@@ -0,0 +1,108 @@
# ADR 0001 — Phone-first binding and zero-input pairing
- Status: accepted (implementing)
- Date: 2026-10-26
- Supersedes: `PI2_ACCESS_MODE` (`local` / `lan` / `tailscale`)
## Context
The console has to be usable from a phone: open the link, done. Two things blocked
that:
1. **Reachability was an opt-in mode.** `PI2_ACCESS_MODE` picked the bind address
(`local` → loopback), and CORS only allowed the single detected LAN address in
`lan` mode. A phone that typed `http://192.168.2.10:7676` was refused by the
origin check, and the default pairing URL was `http://127.0.0.1:7676/pair/…`,
which is unscannable from another device.
2. **Pairing was a form, not a link.** The QR on the status page was a *fake*
pattern (`web/src/features/status/qr.ts` derived it from a seed), so scanning
it did nothing. The redemption endpoint and the mint endpoint shared one path
(`POST /api/v1/pair`), distinguished by whether `body.code` was present — the
authorization rule was implied by a field, not by the route.
Access control is already carried by the device token that a pairing code mints.
The bind address is not a security boundary we want to maintain.
## Decision
### 1. Bind every interface by default
- `PI2_HOST` defaults to `0.0.0.0`; setting it (e.g. `127.0.0.1`) narrows the bind.
- CORS derives from the addresses the daemon is actually reachable on: loopback plus
every non-internal IPv4 at the bound port, plus `PI2_PUBLIC_URL`'s origin, plus
`PI2_ORIGINS`. `PI2_ACCESS_MODE` and its three modes are deleted outright (the
repo is pre-1.0 and the plugin that set the env var ships from the same project).
- `/api/v1/info` and `daemon.json` report `host` instead of `access`.
### 2. One network source of truth
`src/core/network.ts` owns address classification and ordering:
| kind | rule |
|---|---|
| `public` | the configured `PI2_PUBLIC_URL` (never a NIC) |
| `lan` | private IPv4 (10/8, 172.16/12, 192.168/16) |
| `other` | any other routed IPv4 |
| `tailscale` | `tailscale*` interface or 100.64/10 address |
| `loopback` | 127/8 |
Ordering: `public` → `lan` → `other` → `tailscale` → `loopback`, physical interface
names before virtual ones (`docker*`, `veth*`, `br-*`, `virbr*`, `tun*`, `wg*`, …),
link-local (169.254/16) never advertised. `networkBases()` respects `bindHost`:
a loopback bind advertises only loopback, a specific address advertises that
address plus loopback, `0.0.0.0`/`::` advertises everything reachable.
Config (CORS), the pairing route (URL + `bases[]`) and `pi2 doctor` all consume it.
### 3. Pairing is mint → link → redeem
```
POST /api/v1/pair (authenticated) → {code,url,expiresAt,nonce,qr,bases[]}
POST /api/v1/pair/redeem (public, rate limited) → {token,device}
GET /pair/:code (public) → 302 /connect?code=…&auto=1
```
- The mint picks the URL server-side (`base` may be supplied, but only a value
present in `bases[]` is accepted) and returns the QR matrix, so no client
re-derives either.
- `qr` is byte-mode, EC level M, versions 1–10, `rows` without a quiet zone;
renderers own margin and colours. One encoder in `src/core/qr.ts`.
- Redeem is unauthenticated by design (the code *is* the capability) and now
rate limited: 5 attempts/minute/IP and 50/hour globally, over the limit → 429.
- Codes stay 8 characters from a 32-symbol alphabet, single use, 10 minutes.
### 4. Devices carry no scope list
Scopes were declared (`read`/`steer`/`control`/`admin`, plus a bogus `apply` in the
web client) but never enforced anywhere — HTTP and WS only checked that the token
was valid. Rather than invent an enforcement matrix, this ADR drops the concept:
a paired device and the local browser hold the same rights as `local-cli`, and any
fine-grained permission model is a separate feature with its own ADR.
Removed with it: `Scope`, `SCOPES`, `DEFAULT_SCOPES`, `DeviceRecord.scopes`,
`CreateDeviceInput.scopes`, `web`'s `PAIR_SCOPES`/`DEFAULT_DEVICE_SCOPES`, and the
`scopes` field in `/api/v1/devices` responses and the stored pair metadata.
### 5. Zero-input web flow
`/pair/<CODE>` (both the daemon's 302 and the SPA `/#/pair/CODE` route) lands on
`/connect?code=<CODE>&auto=1`, which redeems against its own origin with the
localized default device name and redirects to `next`/`/workspaces`. The code and
`auto` flag are stripped from the URL afterwards. A rejected or expired code falls
back to the manual form with host, port and code prefilled.
The in-console camera scanner (`web/src/features/connect/scan-dialog.tsx`) is
deleted: phones scan with the system camera, desktops type the code.
## Consequences
- A daemon started without configuration is reachable from the LAN. `pi2 doctor`
reports the bind, and warns (not fails) when a non-loopback bind has no `https:`
public URL.
- `pi2 pairing` prints a human-readable report and a terminal QR; it no longer
emits `--json`. The Neovim client calls `POST /api/v1/pair` directly.
- Breaking for anyone parsing `info.access`, `pi2 status --json`'s `access`,
`pi2 pairing --json`, or `POST /api/v1/pair {code}`; all in-repo callers are
updated in the same change.
- `docs/protocol.md` no longer claims `E_FORBIDDEN` covers scopes; it covers
origins and `PI2_WORKSPACE_ROOTS` only.
+67 -30
View File
@@ -111,8 +111,7 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
| Variable | Default | Meaning |
|---|---|---|
| `PI2_PORT` | `7676` | HTTP/WS port, `0` = ephemeral |
| `PI2_HOST` | `127.0.0.1` (`0.0.0.0` in `lan` mode) | bind address; wins over the mode default |
| `PI2_ACCESS_MODE` | `local` | `local` / `lan` / `tailscale` (see below) |
| `PI2_HOST` | `0.0.0.0` | bind address (all interfaces); set `127.0.0.1` for a loopback-only daemon |
| `PI2_PUBLIC_URL` | – | external base URL, e.g. `https://myhost.tail1234.ts.net` (no trailing slash) |
| `PI2_ORIGINS` | – | **extra** CORS/Origin allowlist entries (comma separated), added to the derived origins |
| `PI2_STATIC_DIR` | `<repo>/web/dist` | built web UI |
@@ -158,21 +157,35 @@ page lists `default` rows only behind a persisted “Show N hidden” toggle
secondary rows dimmed with a reason badge; any workspace picker offers
`default` rows only, while lookups by id ignore `visibility` entirely.
### Access modes
### Binding and reachability
| `PI2_ACCESS_MODE` | bind (unless `PI2_HOST`) | derived `corsOrigins` |
The daemon listens on **all interfaces** (`0.0.0.0`) by default: the console is meant to
be opened from a phone as well as from the desktop, and it is the **pairing code** — not
the bind address — that grants access (each device then holds its own revocable token).
`PI2_HOST` narrows the bind:
| `PI2_HOST` | Reachable from | Use when |
|---|---|---|
| `local` (default) | `127.0.0.1` | `http://127.0.0.1:<port>`, `http://localhost:<port>`, `http://[::1]:<port>` |
| `lan` | `0.0.0.0` | loopback three **plus** `http://<detected-lan-ip>:<port>` |
| `tailscale` | `127.0.0.1` | loopback three **plus** the origin of `PI2_PUBLIC_URL` |
| unset (default `0.0.0.0`) | this machine, the LAN, a tailnet | the normal homelab setup |
| `127.0.0.1` | this machine only | you always put `tailscale serve` (or another proxy) in front, or you want the console strictly local |
Origins are normalized (trailing `/` stripped, empties dropped) and
`PI2_ORIGINS` is appended — never a replacement. LAN detection is best effort:
when the address is unknown that extra origin is simply skipped. `tailscale`
assumes `tailscale serve` terminates TLS in front of the loopback daemon; the
daemon never does TLS itself. An unknown mode fails startup with one line:
`pi2: PI2_ACCESS_MODE must be local, lan or tailscale`. Changing the mode
requires restarting `pi2 daemon`.
`corsOrigins` are *derived*, not configured: loopback plus **every IPv4 address of this
host** at the bound port, plus the origin of `PI2_PUBLIC_URL`, plus anything in
`PI2_ORIGINS`. A browser that loaded the console from `http://192.168.11.7:7676` sends an
`Origin` header that is not loopback, so the allowlist has to cover the address the user
actually typed. Origins are normalized (trailing `/` stripped, empties dropped) and
deduped; `PI2_ORIGINS` never replaces the derived list.
The daemon never terminates TLS. For a tailnet, point `PI2_PUBLIC_URL` at the
`tailscale serve` URL (`https://host.tail1234.ts.net`): the origin is then allowed,
`pi2 pairing` advertises that base, and `pi2 doctor` reports the bind as `ok` instead of
warning about the missing TLS.
The pairing link follows the same preference (public URL → LAN address → loopback) and
is chosen by the **daemon**, not the client: `POST /api/v1/pair` returns the URL together
with the QR matrix and every base a browser could use, and accepts `base` to pin a
different entry. `:PiWebPair` renders that list as the "pick the interface" menu; the
reasoning is in [ADR 0001](adr/0001-phone-first-pairing.md).
## 5. Runtime files
@@ -182,7 +195,7 @@ All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|---|---|---|
| `d.sock` | `0600` | plugin ↔ daemon JSONL socket (nvim dials it) |
| `d.sock.token` | `0600` | handshake token for `hello`; rotated per daemon start |
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion, access?, publicUrl?}` |
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion, host?, publicUrl?}` |
| `daemon.json` | `0600` | same payload, written **after** `listen()` so tools learn the real port |
| `cli.token` | `0600` | 32-byte hex local admin token, rotated per daemon start |
@@ -216,7 +229,7 @@ Two token kinds:
`PI2_DATA_DIR/devices.json`.
2. **Local CLI token**: `PI2_RUNTIME_DIR/cli.token`, minted by `pi2 daemon` on
each start. Any request carrying it authenticates as the synthetic device
`{id:"local-cli", name:"local CLI", scopes:["read","steer","control","admin"]}`
`{id:"local-cli", name:"local CLI", kind:"laptop"}`
(constant-time compare, never persisted, not revocable, not listed by
`GET /api/v1/devices`). Rotating the file invalidates the old value
immediately.
@@ -230,7 +243,7 @@ authenticated (auth runs before routing).
`pi2 open` calls this endpoint (loopback **and** local CLI token required) to
sign the browser in without a pairing code: it rotates the single
`local browser` device (`kind:"laptop"`, all four scopes) and answers
`local browser` device (`kind:"laptop"`) and answers
`{token, device, url}` with
`url = http://127.0.0.1:<actual bound port>/#t=<token>`. The token lives in the
fragment, so it never reaches a request line, a `Referer` header or a proxy
@@ -303,7 +316,7 @@ object `{daemon, instances, resources, health}`.
| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers |
| `daemon` | `/api/v1/info` unreachable | – |
| `port` | – (reports bound/free) | – |
| `access` | `lan`/`tailscale` with a non-loopback bind and no `PI2_PUBLIC_URL` | `lan`/`tailscale` (adds `— no TLS, prefer \`tailscale serve\`` without an `https:` public URL) |
| `bind` | – | non-loopback bind without an `https:` `PI2_PUBLIC_URL` (`all interfaces/7676 — no TLS; pairing codes gate access, set PI2_HOST=127.0.0.1 to restrict`) |
| `service-manager` | – | systemd/launchd not found |
| `linger` (Linux) | – | `Linger=no` |
| `web-dist` | – | missing |
@@ -327,23 +340,47 @@ the command: if it is missing or fails, `pi2 open` prints the URL and still
exits `0`. This is a local-only shortcut; use `pi2 pairing` for LAN/Tailscale
browsers.
### 8.5 `pi2 pairing [--public-url <url>]`
### 8.5 `pi2 pairing [--base <url>]`
`POST /api/v1/pair` with the local token and prints:
`POST /api/v1/pair` with the local token, then prints a scannable report:
```
url http://127.0.0.1:7676/pair/ABCD2345
url http://192.168.2.10:7676/pair/ABCD2345
code ABCD2345
expires 2026-10-21T04:30:15.085Z (600s)
qr {"v":1,"code":"ABCD2345","url":"…","expiresAt":…,"nonce":"…"}
expires in 600s (2026-10-21T04:30:15.085Z)
▄▄▄▄▄▄▄ ▄▄ ▄▄▄▄▄▄▄
█ ▄▄▄ █ ▀█▄▀█ ▄▄▄ █
█ ███ █ ▄▀▄ █ ███ █
…
```
The URL is rebuilt from the *actual* daemon base URL because the daemon's own
`url` field is derived from the configured port (stale after a retry or
`--port 0`). `--public-url <url>` rebuilds both the printed `url` and the QR
payload's `url` on that base (e.g. `https://host.ts.net/pair/ABCD2345`); it
defaults to `daemon.json`'s `publicUrl`, then `PI2_PUBLIC_URL`. The code, expiry
and nonce are unchanged.
The daemon owns the URL, the QR matrix and the base list (see
[ADR 0001](adr/0001-phone-first-pairing.md) §3); the CLI only renders them. The base is
chosen for reachability, first non-empty wins:
| # | Base (`kind`) | When |
|---|---|---|
| 1 | `PI2_PUBLIC_URL` (`public`) | behind `tailscale serve` or another proxy |
| 2 | primary LAN address (`lan`) | the default — the daemon binds `0.0.0.0` |
| 3 | other routed / tailnet address (`other`, `tailscale`) | multi-homed hosts |
| 4 | `http://127.0.0.1:<port>` (`loopback`) | `PI2_HOST=127.0.0.1`, or a host with no LAN address |
`--base <url>` pins a different address; the daemon validates it against the list it
just returned and answers `400` for anything else, so a link can never point at an
address nothing listens on.
`GET /pair/<code>` answers `302` to `/connect?code=<code>&auto=1`, which is what makes a
scanned link zero-input: the console redeems the code against its own origin and lands on
`/workspaces` without a form.
`qr` is byte mode, EC level M, versions 1–10, and lives in `src/core/qr.ts`; `rows` is the
raw module matrix without a quiet zone (`size` strings of `size` `1`/`0` characters). The
HTTP mint response carries the same matrix, so the console and a terminal draw the same
symbol. A URL too long for version 10 is printed without a QR, with a note.
Machines call `POST /api/v1/pair` directly — that is what `:PiWebPair` does — so the CLI
keeps only this human report; there is no `--json`.
### 8.6 `pi2 install-service` / `pi2 uninstall-service`
@@ -455,7 +492,7 @@ debugging.
| `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) |
| `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) |
| `pi2 open` → `403 console login is loopback-only` | the request came from a non-loopback address; pair the device instead |
| `pi2 doctor` → `access FAIL` | `PI2_ACCESS_MODE=lan/tailscale` binds a non-loopback address without `PI2_PUBLIC_URL`; set it or use `tailscale serve` |
| `pi2 doctor` → `bind warn` | the daemon listens on a non-loopback address without TLS; that is the default posture — pair each device, or set `PI2_HOST=127.0.0.1` / `PI2_PUBLIC_URL=https://…` |
| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` |
| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project |
| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout |
+21 -11
View File
@@ -139,7 +139,7 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
- `GET /api/v1/health` → `ok=true`, `static` item ok (web/dist served).
- `GET /` → 200 HTML containing the app root.
- unauthenticated `GET /api/v1/workspaces` → 401 `E_UNAUTHORIZED`; bogus bearer → 401.
- `POST /api/v1/pair` redeem: valid code → `{token, device}`; same code again → 401;
- `POST /api/v1/pair/redeem`: valid code → `{token, device}`; same code again → 401;
the token authorizes the API; `DELETE /api/v1/devices/:id` revokes it (next call 401).
**A1 Workspaces**
@@ -222,7 +222,7 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
**A13 Console login handoff**
- `POST /api/v1/console/session` with the CLI token → 200, one `local browser`/`laptop`
device with every scope, and a `http://127.0.0.1:<port>/#t=<token>` URL (fragment only,
device, and a `http://127.0.0.1:<port>/#t=<token>` URL (fragment only,
never `?t=`).
- the handed-off token authenticates; a second login returns the **same** token so a second
`:PiWeb` does not log the open tab out.
@@ -244,8 +244,8 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
allow-listed `next`.
**B2 Pairing (manual)**
- enter host/port/pairing code/device name → `POST /api/v1/pair` succeeds; the summary
shows server/endpoint/device/scopes; localStorage keys are written; redirect to `next`.
- enter host/port/pairing code/device name → `POST /api/v1/pair/redeem` succeeds; the summary
shows server/endpoint/device; localStorage keys are written; redirect to `next`.
- wrong code → inline localized error, still unpaired, form stays usable.
- while paired, `/connect` shows the summary, not the form; disconnect asks for
confirmation and clears the connection (returns to `/connect`).
@@ -254,6 +254,12 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
- paste a `pi2://pair?host=…&port=…&code=…` link in the scan fallback → confirmation
modal shows the masked token → confirm pairs; cancel changes nothing.
- the daemon's own `http://host:port/pair/<code>` URL is accepted by the parser.
- opening that URL directly is **zero-input**: `/pair/<code>` redirects to
`/connect?code=<code>&auto=1`, which redeems against its own origin with the
localized default device name and lands on `/workspaces` (or `next`) without the
form ever being shown; the device then appears on the status page.
- a rejected/expired code falls back to the manual form with host, port and code
prefilled from the link, plus the inline pairing error.
**B4 Workspaces**
- seeded W1/W2 render as `[data-workspace-id]` rows, pinned/last-active order, context
@@ -284,11 +290,14 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
- change the thinking select to `low` → API command sent, state/toast update, value
survives a reload; change the model select → the same, and the tree subtitle updates.
**B9 Chat: panels (Subagents / Todo / Tasks)**
- panel tabs switch; each renders either real data or its empty state; no mock copy.
- Dispatch modal creates a real batch (`items[]`), the subagent row/batch appears, and
the preview modal opens (real tail or an explicit empty state); “Back to parent” works.
- Tasks tab shows real tasks or the empty state; the task output modal shows the real
**B9 Chat: session tray (Todo / Tasks) + subagent child view**
- the stream-head chips (`计划` / `任务`) open the session tray; the two tabs switch and
each renders either real data or its empty state; no mock copy; the right panel is gone
(`.panel-pane` count is 0) and Esc returns focus to the chip.
- the row `…` popover dispatches a subagent: a real batch (`items[]`) appears, the row
shows the child in the tree, and the in-place child view renders the synthesized
timeline (`sub-timeline`) or an explicit empty state; `← 父级` / Esc works.
- the Tasks tab shows real tasks or the empty state; the task output modal shows the real
output tail or an explicit unsupported state (no fake pid).
**B10 Attention**
@@ -296,8 +305,9 @@ The plan's original intent below is unchanged; the legend **P0**/**P1**/**P2** s
title/options; Accept writes the file; the dialog closes; a second client cannot answer.
**B11 Status**
- `/status` renders info/health/resources/models/tasks/devices/connection cards from the
API; no server/workspace selector; resources refresh; health items show pass/fail.
- `/status` renders the four metric tiles + info/health/models/tasks/devices/connection
cards from the API; no server/workspace selector; metrics refresh; health items show
pass/fail. The page has zero primary actions.
- paired devices come from the API and can be revoked with confirmation; a revoked
device token stops working.
- disconnect clears connection and returns to `/connect`.
+6 -2
View File
@@ -85,7 +85,10 @@ Plugin obligations:
| `GET /api/v1/workspaces/:id/sessions` | relayed `workspace.query{kind:"sessions"}` (row fields below) |
| `GET /api/v1/sessions/:sid/entries?before=&limit=` | relayed; plugin paginates |
| `GET /api/v1/attention?workspaceId=` | pending attention for one workspace |
| `GET /api/v1/devices` | paired devices (daemon-owned) |
| `GET /api/v1/devices` | paired devices (daemon-owned; `{id, name, kind, createdAt, lastSeenAt, revokedAt}`) |
| `POST /api/v1/pair` | **authenticated**; mints `{code, url, expiresAt, nonce, qr, bases}` |
| `POST /api/v1/pair/redeem` | public + rate limited (`E_RATE_LIMITED`); `{code, kind, deviceName}` → `{token, device}` |
| `GET /pair/:code` | public; `302 /connect?code=<code>&auto=1` (scanned links) |
| `GET /api/v1/models?workspaceId=` | relayed to the instance |
| `GET /api/v1/resources` | instances, sessions, RSS totals for the soft-limit notice |
| `GET /api/v1/diagnostics` | connections, event rates, slow queries, instance table |
@@ -276,7 +279,8 @@ browser cmd(sessionId=s1)
|---|---|---|
| `E_BAD_REQUEST` | 400 | malformed JSON / missing field |
| `E_UNAUTHORIZED` | 401 | missing/invalid device token |
| `E_FORBIDDEN` | 403 | bad `Origin`, insufficient scope, cwd outside `PI2_WORKSPACE_ROOTS` |
| `E_FORBIDDEN` | 403 | bad `Origin`, cwd outside `PI2_WORKSPACE_ROOTS` |
| `E_RATE_LIMITED` | 429 | too many pairing attempts (per client and globally) |
| `E_NOT_FOUND` | 404 | unknown workspace/session/instance |
| `E_PROTOCOL_VERSION` | 426 | `v` unsupported |
| `E_PAYLOAD_TOO_LARGE` | 413 | body/frame > limits |
+108 -23
View File
@@ -140,6 +140,8 @@ async function http(method, path, opts = {}) {
method,
headers,
body,
// `redirect: "manual"` keeps 30x responses inspectable (e.g. /pair/<code>).
redirect: opts.redirect ?? "follow",
signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
});
} catch (error) {
@@ -152,7 +154,14 @@ async function http(method, path, opts = {}) {
} catch {
json = undefined;
}
return { status: response.status, ok: response.ok, text, json, contentType: response.headers.get("content-type") ?? "" };
return {
status: response.status,
ok: response.ok,
text,
json,
contentType: response.headers.get("content-type") ?? "",
location: response.headers.get("location"),
};
}
/** `POST /api/v1/cmd` with the CLI token by default. */
@@ -965,20 +974,89 @@ scenario("A0", "Bootstrap & auth", async (ctx) => {
observed: health.text.slice(0, 120),
});
// Pairing: a fresh code, treat it as single-use, then revoke the device.
const created = await cmd({ method: "pair.create", params: { ttlSec: 600 } });
ctx.eq("pair.create → 202", created.status, 202);
const code = created.json?.code;
ctx.check("pair.create returns an 8-char code", typeof code === "string" && /^[A-Z0-9]{8}$/.test(code), {
// Pairing (ADR 0001): `POST /api/v1/pair` only *mints* a code (authenticated,
// QR matrix + reachable bases included), the public
// `POST /api/v1/pair/redeem` exchanges it for a device token, and
// `GET /pair/<code>` is the scanned link that bounces into the SPA.
const minted = await http("POST", "/api/v1/pair", { token: CLI_TOKEN, body: { ttlSec: 600 } });
ctx.eq("POST /api/v1/pair (mint) → 200", minted.status, 200);
ctx.eq("mint reports accepted", minted.json?.accepted, true);
const code = minted.json?.code;
ctx.check("mint returns an 8-char code", typeof code === "string" && /^[A-Z0-9]{8}$/.test(code), {
expected: "8 uppercase alphanumerics",
observed: code,
});
if (typeof code !== "string") return;
const redeemed = await http("POST", "/api/v1/pair", {
const mintedUrl = minted.json?.url;
ctx.check("mint returns the /pair/<code> url", typeof mintedUrl === "string" && mintedUrl.endsWith(`/pair/${code}`), {
expected: `…/pair/${code}`,
observed: mintedUrl,
});
ctx.check(
"mint returns expiresAt + nonce",
typeof minted.json?.expiresAt === "number" &&
minted.json.expiresAt > Date.now() &&
/^[0-9a-f]{32}$/.test(String(minted.json?.nonce ?? "")),
{
expected: { expiresAt: "future epoch ms", nonce: "32 hex chars" },
observed: { expiresAt: minted.json?.expiresAt, nonce: minted.json?.nonce },
},
);
const qr = minted.json?.qr;
const qrRows = Array.isArray(qr?.rows) ? qr.rows : [];
ctx.check(
"mint carries the QR matrix (version/ecc/mask/size/rows)",
qr !== null &&
typeof qr === "object" &&
typeof qr.version === "number" &&
qr.ecc === "M" &&
typeof qr.mask === "number" &&
typeof qr.size === "number" &&
qrRows.length === qr.size &&
qrRows.every((row) => typeof row === "string" && row.length === qr.size),
{
expected: "{version, ecc:'M', mask, size, rows: size strings of size modules}",
observed:
qr === null
? null
: { version: qr?.version, ecc: qr?.ecc, mask: qr?.mask, size: qr?.size, rowCount: qrRows.length },
},
);
const bases = Array.isArray(minted.json?.bases) ? minted.json.bases : [];
ctx.check(
"mint lists the reachable bases",
bases.length > 0 &&
bases.every(
(base) =>
typeof base?.kind === "string" &&
typeof base?.name === "string" &&
typeof base?.address === "string" &&
typeof base?.url === "string",
),
{ expected: "non-empty [{kind, name, address, url}]", observed: bases },
);
ctx.check("the minted url is built from the primary base", typeof mintedUrl === "string" && String(bases[0]?.url ?? "").replace(/\/$/, "") === mintedUrl.slice(0, mintedUrl.indexOf("/pair/")), {
expected: { primaryBase: bases[0]?.url, url: mintedUrl },
observed: { primaryBase: bases[0]?.url, url: mintedUrl },
});
// The scanned link: a redirect into the SPA, never an API call.
const scanned = await http("GET", `/pair/${code}`, { redirect: "manual" });
ctx.eq("GET /pair/<code> → 302", scanned.status, 302);
const pairLocation = scanned.location ?? "";
ctx.check(
"the scanned link redirects to /connect?code=<code>&auto=1",
/\/connect\?/.test(pairLocation) && pairLocation.includes(`code=${code}`) && pairLocation.includes("auto=1"),
{ expected: "/connect?code=<code>&auto=1", observed: pairLocation },
);
const redeemed = await http("POST", "/api/v1/pair/redeem", {
body: { code, kind: "laptop", deviceName: "E2E A0 device" },
});
ctx.eq("POST /api/v1/pair (redeem) → 200", redeemed.status, 200);
ctx.eq("POST /api/v1/pair/redeem → 200", redeemed.status, 200);
const token = redeemed.json?.token;
ctx.check("redeem returns {token, device}", typeof token === "string" && token.length > 10 && Boolean(redeemed.json?.device?.id), {
expected: "{token, device.id}",
@@ -995,26 +1073,24 @@ scenario("A0", "Bootstrap & auth", async (ctx) => {
ctx.check("redeemed token authorizes the API", false, { expected: "token", observed: "<no token>" });
}
const reuse = await http("POST", "/api/v1/pair", { body: { code, kind: "laptop", deviceName: "dup" } });
const reuse = await http("POST", "/api/v1/pair/redeem", { body: { code, kind: "laptop", deviceName: "dup" } });
ctx.eq("re-using the pairing code → 401", reuse.status, 401);
ctx.eq("re-use error code", reuse.json?.code, "E_UNAUTHORIZED");
if (PAIR_CODE) {
const consumed = await http("POST", "/api/v1/pair", {
const consumed = await http("POST", "/api/v1/pair/redeem", {
body: { code: PAIR_CODE, kind: "laptop", deviceName: "reuse of the suite code" },
});
ctx.eq("the suite's consumed pairing code → 401", consumed.status, 401);
}
const existingRedeem = await http("POST", "/api/v1/pair/redeem", {
token: CLI_TOKEN,
// The public redeem endpoint exists and is the only way to exchange a code:
// an unknown code is rejected with 401 (never 404 — the route is live).
const unknownRedeem = await http("POST", "/api/v1/pair/redeem", {
body: { code: "AAAAAAAA", kind: "laptop", deviceName: "nope" },
});
ctx.check("there is no /api/v1/pair/redeem endpoint", existingRedeem.status === 404, {
expected: 404,
observed: existingRedeem.status,
severity: "warn",
});
ctx.eq("POST /api/v1/pair/redeem exists (unknown code → 401, not 404)", unknownRedeem.status, 401);
ctx.eq("unknown-code redeem error code", unknownRedeem.json?.code, "E_UNAUTHORIZED");
const deviceId = redeemed.json?.device?.id;
if (typeof deviceId === "string") {
@@ -2885,12 +2961,21 @@ scenario("A13", "Console login handoff", async (ctx) => {
ctx.eq("the session names the local-browser device", first.json?.device?.name, "local browser");
ctx.eq("the local-browser device is a laptop", first.json?.device?.kind, "laptop");
ctx.eq("the local-browser device holds every scope", first.json?.device?.scopes, [
"read",
"steer",
"control",
"admin",
]);
// ADR 0001 deleted the scope model: the device payload carries identity and
// lifecycle timestamps only.
const deviceFields = Object.keys(first.json?.device ?? {}).sort();
ctx.check("the device payload carries no `scopes` field", !deviceFields.includes("scopes"), {
expected: { fields: ["createdAt", "id", "kind", "lastSeenAt", "name", "revokedAt"] },
observed: deviceFields,
});
ctx.check(
"the device payload is {id, name, kind, createdAt, lastSeenAt, revokedAt}",
["id", "name", "kind"].every((key) => typeof first.json?.device?.[key] === "string") &&
typeof first.json?.device?.createdAt === "number" &&
typeof first.json?.device?.lastSeenAt === "number" &&
"revokedAt" in (first.json?.device ?? {}),
{ expected: "identity + timestamps, no scopes", observed: first.json?.device },
);
ctx.check("the handoff url puts the token in the fragment", /\/#t=[A-Za-z0-9_-]{20,}$/.test(url), {
expected: "http://127.0.0.1:<port>/#t=<token>",
observed: url.replace(/#t=.{6}.*/, "#t=<redacted>"),
+14 -23
View File
@@ -384,7 +384,6 @@ class Ctx {
{ name: "pi2-endpoint", value: BASE },
// Raw token (web/src/lib/api.ts strips an optional `Bearer ` prefix).
{ name: "pi2-device-token", value: DEVICE_TOKEN },
{ name: "pi2-device-scopes", value: JSON.stringify(["read", "steer", "apply"]) },
{ name: "pi2-device", value: "Playwright" },
{ name: "pi2-connected-at", value: String(Date.now()) },
...Object.entries(localExtra).map(([name, value]) => ({ name, value: String(value) })),
@@ -947,7 +946,7 @@ async function fillManualForm(page, code, device = "Playwright") {
await page.locator('[data-testid="connect-submit"]').click();
}
scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair + redirect (wrong code → inline error)", async (ctx) => {
scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair/redeem + redirect (wrong code → inline error)", async (ctx) => {
const { page } = await ctx.openPage("unpaired");
await page.goto(`${BASE}/connect?next=%2Fworkspaces`, { waitUntil: "domcontentloaded" });
await page.locator('[data-testid="connect-pair-code"]').waitFor({ state: "visible", timeout: 15000 });
@@ -975,13 +974,13 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
return null;
}, 25000);
const pairCalls = ctx.apiCalls.filter((call) => call.method === "POST" && call.path === "/api/v1/pair");
const pairCalls = ctx.apiCalls.filter((call) => call.method === "POST" && call.path === "/api/v1/pair/redeem");
ctx.log(`redeem calls: ${JSON.stringify(pairCalls)}`);
ctx.check("the redeem posts the public POST /api/v1/pair", pairCalls.length >= 1, {
expected: "POST /api/v1/pair {code,deviceName,kind}",
ctx.check("the redeem posts the public POST /api/v1/pair/redeem", pairCalls.length >= 1, {
expected: "POST /api/v1/pair/redeem {code,deviceName,kind}",
observed: { pairCalls, cmdMethods: ctx.cmdRequests.map((request) => request.method) },
});
ctx.check("POST /api/v1/pair answered 200", pairCalls.some((call) => call.status === 200), {
ctx.check("POST /api/v1/pair/redeem answered 200", pairCalls.some((call) => call.status === 200), {
expected: 200,
observed: pairCalls,
});
@@ -1000,11 +999,10 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
const storage = await page.evaluate(() => ({
connection: localStorage.getItem("pi2-connection"),
token: localStorage.getItem("pi2-device-token"),
scopes: localStorage.getItem("pi2-device-scopes"),
endpoint: localStorage.getItem("pi2-endpoint"),
}));
const connWrites = await page.evaluate(() =>
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)),
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token"].includes(write.key)),
);
ctx.note(`pi2-* storage writes: ${short(connWrites, 700)}`);
ctx.note(`navigations: ${short(ctx.navigations, 400)}`);
@@ -1014,7 +1012,6 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
/^Bearer\s+/i,
"",
);
const mintedScopes = (connWrites.find((write) => write.key === "pi2-device-scopes" && write.op === "set")?.value ?? "").trim();
const wsErrors = socketErrors(ctx.wsFrames);
const wsAuthErrors = wsErrors.filter((entry) => entry.code === "E_UNAUTHORIZED");
@@ -1036,22 +1033,17 @@ scenario("B2", "Manual pairing: host/port/pair-code/device → POST /api/v1/pair
expected: "paired",
observed: { connection: storage.connection, setToken: Boolean(mintedRaw), writes: connWrites, navigations: ctx.navigations },
cause:
"the flow writes pi2-connection=paired (see the write log), then ~100 ms later the app removes the token + scopes and writes 'unpaired' " +
"the flow writes pi2-connection=paired (see the write log), then ~100 ms later the app removes the token and writes 'unpaired' " +
"because the socket auth of that same token fails with E_UNAUTHORIZED",
});
ctx.softCheck("localStorage pi2-device-token is still set", Boolean(storage.token), {
expected: "<device token>",
observed: storage.token ? "set" : { removedAfterMs: connWrites.at(-1)?.at, writes: connWrites },
});
let scopes = null;
try {
scopes = JSON.parse(storage.scopes ?? mintedScopes ?? "null");
} catch {
scopes = null;
}
ctx.softCheck("the paired scopes are a non-empty array", Array.isArray(scopes) && scopes.length > 0, {
expected: '["read", …]',
observed: storage.scopes ?? mintedScopes,
const legacyScopes = await page.evaluate(() => localStorage.getItem("pi2-device-scopes"));
ctx.softCheck("the browser writes no legacy pi2-device-scopes key (ADR 0001)", legacyScopes === null, {
expected: null,
observed: { legacyScopes },
});
// A paired browser shows the summary instead of the form.
@@ -1178,10 +1170,9 @@ scenario("B3", "Paste-link pairing: pi2:// and /pair/<code> links reach the conf
const linkStorage = await page.evaluate(() => ({
connection: localStorage.getItem("pi2-connection"),
token: localStorage.getItem("pi2-device-token"),
scopes: localStorage.getItem("pi2-device-scopes"),
}));
const linkWrites = await page.evaluate(() =>
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token", "pi2-device-scopes"].includes(write.key)),
(window.__pi2Writes ?? []).filter((write) => ["pi2-connection", "pi2-device-token"].includes(write.key)),
);
ctx.note(`link-flow pi2-* storage writes: ${short(linkWrites, 700)}`);
const linkWsErrors = socketErrors(ctx.wsFrames);
@@ -1194,7 +1185,7 @@ scenario("B3", "Paste-link pairing: pi2:// and /pair/<code> links reach the conf
cause: "same stored 'Bearer <token>' passed verbatim to the WS auth frame (web/src/lib/api.ts + web/src/lib/ws.ts:219)",
},
);
ctx.softCheck("the link flow keeps paired + token + scopes", linkStorage.connection === "paired" && Boolean(linkStorage.token), {
ctx.softCheck("the link flow keeps paired + token", linkStorage.connection === "paired" && Boolean(linkStorage.token), {
expected: { connection: "paired", token: "set" },
observed: { ...linkStorage, token: linkStorage.token ? "set" : null, writes: linkWrites },
cause: "the same write-then-clear sequence as B2 (socket auth of the fresh token is rejected → app-shell disconnects)",
@@ -2253,7 +2244,7 @@ scenario("B11", "Status: six API-backed cards + metrics strip, devices list/revo
const created = await cmd("pair.create", { ttlSec: 600 });
const code = created.json?.code;
ctx.check("pair.create returns a code", typeof code === "string" && code.length > 0, { observed: created.json });
const redeemed = await apiRaw("POST", "/api/v1/pair", { token: null, body: { code, deviceName: "e2e-second-device", kind: "phone" } });
const redeemed = await apiRaw("POST", "/api/v1/pair/redeem", { token: null, body: { code, deviceName: "e2e-second-device", kind: "phone" } });
ctx.check("second device pairs", redeemed.status === 200 && Boolean(redeemed.json?.token), {
expected: "200 with a device token",
observed: { status: redeemed.status, body: short(redeemed.json) },
+2 -2
View File
@@ -45,7 +45,7 @@ Options:
Environment:
PI2_PORT, PI2_HOST, PI2_STATIC_DIR, PI2_ORIGINS, PI2_RUNTIME_DIR,
PI2_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS,
PI2_ACCESS_MODE (local|lan|tailscale), PI2_PUBLIC_URL
PI2_PUBLIC_URL
Runtime files ($PI2_RUNTIME_DIR):
d.sock plugin unix socket (nvim → daemon)
@@ -181,7 +181,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
daemonId,
startedAt: Date.now(),
protocolVersion: PROTOCOL_VERSION,
access: config.access,
host: config.host,
publicUrl: config.publicUrl,
},
});
+22 -26
View File
@@ -11,7 +11,8 @@ import { homedir, platform as osPlatform } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { DEFAULT_PORT, loadConfig, type AccessMode } from "../config.js";
import { DEFAULT_HOST, DEFAULT_PORT, describeHost, loadConfig } from "../config.js";
import { isLoopbackHost } from "../core/network.js";
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { formatTable } from "./util.js";
@@ -43,8 +44,7 @@ export interface BinaryProbe {
error?: string;
}
export interface AccessModeContext {
mode: AccessMode;
export interface BindContext {
host: string;
port: number;
publicUrl: string | null;
@@ -62,7 +62,7 @@ export interface DoctorContext {
socket: { path: string; exists: boolean };
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
port: { configured: number; bound: boolean };
access: AccessModeContext;
bind: BindContext;
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
linger: { checked: boolean; enabled?: boolean; detail?: string };
webDist: { path: string; exists: boolean };
@@ -217,27 +217,24 @@ export function checkPort(probe: DoctorContext["port"]): DoctorCheck {
return { name: "port", status: "ok", detail: `${probe.configured} free` };
}
function isLoopbackHost(host: string): boolean {
return host === "127.0.0.1" || host === "::1" || host === "localhost";
}
/**
* `access`: local is fine; lan/tailscale warn because the daemon has no TLS of
* its own, and fail when a non-loopback bind is exposed without a public URL.
* `bind`: where the daemon listens. Loopback is private; anything else is
* reachable from the LAN, which is the point of the console — so a non-loopback
* bind only *warns*. Access is gated by pairing codes and per-device tokens,
* and an `https:` public URL (e.g. behind `tailscale serve`) covers TLS.
*/
export function checkAccess(probe: AccessModeContext): DoctorCheck {
if (probe.mode === "local") return { name: "access", status: "ok", detail: "local (loopback only)" };
const publicSuffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
const detail = `${probe.mode} (bind ${probe.host}/${probe.port}${publicSuffix})`;
if (probe.publicUrl === null && !isLoopbackHost(probe.host)) {
return { name: "access", status: "fail", detail };
export function checkBind(probe: BindContext): DoctorCheck {
const suffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
if (isLoopbackHost(probe.host)) {
return { name: "bind", status: "ok", detail: `${probe.host}/${probe.port} (loopback only)${suffix}` };
}
const detail = `${describeHost(probe.host)}/${probe.port}${suffix}`;
const tls = probe.publicUrl !== null && probe.publicUrl.startsWith("https:");
if (tls) return { name: "bind", status: "ok", detail };
return {
name: "access",
name: "bind",
status: "warn",
detail: tls ? detail : `${detail} — no TLS, prefer \`tailscale serve\``,
detail: `${detail} — no TLS; pairing codes gate access, set PI2_HOST=127.0.0.1 to restrict`,
};
}
@@ -286,7 +283,7 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
{ name: "port", run: () => checkPort(ctx.port) },
{ name: "access", run: () => checkAccess(ctx.access) },
{ name: "bind", run: () => checkBind(ctx.bind) },
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
@@ -370,15 +367,14 @@ function statOrUndefined(path: string): { exists: boolean; mode: number | undefi
}
}
/** Best-effort access context; an unparsable environment reports `local`. */
function accessContext(env: NodeJS.ProcessEnv, port: number): AccessModeContext {
/** Best-effort bind context; an unparsable environment reports the default bind. */
function bindContext(env: NodeJS.ProcessEnv, port: number): BindContext {
try {
const config = loadConfig(env);
return { mode: config.access, host: config.host, port, publicUrl: config.publicUrl };
return { host: config.host, port, publicUrl: config.publicUrl };
} catch {
return {
mode: "local",
host: env.PI2_HOST?.trim() || "127.0.0.1",
host: env.PI2_HOST?.trim() || DEFAULT_HOST,
port,
publicUrl: env.PI2_PUBLIC_URL?.trim().replace(/\/+$/, "") || null,
};
@@ -472,7 +468,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
socket: { path: socketPath, exists: existsSync(socketPath) },
daemon,
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
access: accessContext(env, daemon.port ?? configuredPort),
bind: bindContext(env, daemon.port ?? configuredPort),
serviceManager,
linger,
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
+6 -11
View File
@@ -6,11 +6,11 @@
*
* ```jsonc
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1,
* "access":"local","publicUrl":null}
* "host":"0.0.0.0","publicUrl":null}
* ```
*
* `access`/`publicUrl` are optional so readers built before the access modes
* keep working.
* `host`/`publicUrl` are optional so readers built before them keep working; a
* legacy `access` field is simply ignored.
*
* The lock is created with `wx` (atomic: only one daemon wins) and is
* considered **stale** when the pid is gone or the recorded boot id differs
@@ -23,7 +23,6 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from
import { randomBytes } from "node:crypto";
import { dirname, join } from "node:path";
import { daemonLockPath, ensureDir, runtimeDir } from "../core/paths.js";
import { ACCESS_MODES, type AccessMode } from "../config.js";
export const LOCK_FILE = "daemon.lock";
export const DAEMON_JSON_FILE = "daemon.json";
@@ -35,8 +34,8 @@ export interface DaemonLock {
daemonId: string;
startedAt: number;
protocolVersion: number;
/** Optional: written by daemons that know about access modes. */
access?: AccessMode;
/** Optional: the bind address the daemon actually used. */
host?: string;
/** Optional: external base URL (or explicit `null` when unset). */
publicUrl?: string | null;
}
@@ -88,10 +87,6 @@ export function isPidAlive(pid: number): boolean {
}
}
function isAccessMode(value: unknown): value is AccessMode {
return typeof value === "string" && (ACCESS_MODES as readonly string[]).includes(value);
}
function isLock(value: unknown): value is DaemonLock {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Partial<DaemonLock>;
@@ -105,7 +100,7 @@ function isLock(value: unknown): value is DaemonLock {
candidate.daemonId !== "" &&
typeof candidate.startedAt === "number" &&
typeof candidate.protocolVersion === "number" &&
(candidate.access === undefined || isAccessMode(candidate.access)) &&
(candidate.host === undefined || typeof candidate.host === "string") &&
(candidate.publicUrl === undefined || candidate.publicUrl === null || typeof candidate.publicUrl === "string")
);
}
+136 -33
View File
@@ -21,7 +21,6 @@ import { platform as osPlatform } from "node:os";
import { runtimeDir } from "../core/paths.js";
import type { InstanceResourcesSnapshot } from "../core/interfaces.js";
import type { WorkspaceInfo } from "../protocol/types.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { main as runDaemonMain } from "./daemon.js";
import { readDaemonJson, type DaemonLock } from "./lock.js";
import { cliTokenPath, readCliToken } from "./token.js";
@@ -54,15 +53,17 @@ Usage:
pi2 status [--json] daemon info, instances, resources, health
pi2 open [--print] [--no-browser] open the web console signed in (local only)
pi2 doctor [--json] environment checks
pi2 pairing [--public-url <url>] create a pairing code (URL + code + QR payload)
pi2 pairing [--base <url>] create a pairing code (URL + code + QR)
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 --version | --help
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
of launching a browser (--print implies --no-browser).
\`pi2 pairing\` flags: --public-url <url> rebuilds the URL on that public base
(defaults to daemon.json's publicUrl, then PI2_PUBLIC_URL).
\`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the
daemon advertises (it prints the alternatives; anything else is rejected).
The link prefers a phone-reachable address: the public URL when one is
configured, the primary LAN address, and loopback otherwise.
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
@@ -265,7 +266,7 @@ interface InfoBody {
platform: string;
capabilities: string[];
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
access?: string;
host?: string;
publicUrl?: string | null;
}
@@ -311,7 +312,7 @@ export async function runStatus(options: StatusOptions): Promise<number> {
url: client.baseUrl,
...info,
// Older daemons may not report them; daemon.json does.
access: info.access ?? client.daemon.access,
host: info.host ?? client.daemon.host ?? null,
publicUrl: info.publicUrl ?? client.daemon.publicUrl ?? null,
},
instances,
@@ -365,45 +366,147 @@ export async function runStatus(options: StatusOptions): Promise<number> {
export interface PairingOptions {
client: DaemonClient;
print?: (line: string) => void;
/** Rebuild the printed/QR url on this public base (e.g. `https://host.ts.net`). */
publicUrl?: string | null;
/** `--base <url>`: pin the link to one of the addresses the daemon advertises. */
base?: string | null;
}
function withoutTrailingSlash(value: string): string {
return value.trim().replace(/\/+$/, "");
/** One address the daemon says it is reachable on (`bases[]` in the mint response). */
export interface PairingBase {
kind: string;
name: string;
address: string;
url: string;
}
/** `--public-url` → `daemon.json.publicUrl` → `PI2_PUBLIC_URL`, first non-empty wins. */
export function resolvePublicUrl(client: DaemonClient, flag: string | undefined): string | null {
for (const candidate of [flag, client.daemon.publicUrl, process.env.PI2_PUBLIC_URL]) {
const value = candidate === undefined || candidate === null ? "" : withoutTrailingSlash(candidate);
if (value !== "") return value;
export interface PairingQr {
version: number;
ecc: string;
mask: number;
size: number;
/** One string per module row, `1` = dark, without a quiet zone. */
rows: string[];
}
export interface PairingResult {
code: string;
url: string;
expiresAt?: number;
nonce?: string;
qr?: PairingQr;
bases: PairingBase[];
}
/** Quiet zone around the terminal QR, in modules. */
const QR_QUIET_ZONE = 2;
/**
* Render a QR matrix for a terminal: one character per module, two module rows
* per text row via half blocks. The caller owns the width budget; a version 3
* symbol (29 modules) plus the quiet zone stays well inside 80 columns.
*/
export function renderTerminalQr(rows: readonly string[]): string[] {
const size = rows[0]?.length ?? 0;
if (size === 0) return [];
const width = size + QR_QUIET_ZONE * 2;
const blank = "0".repeat(width);
const frame = Array.from({ length: QR_QUIET_ZONE }, () => blank);
const padded = [
...frame,
...rows.map((row) => `${"0".repeat(QR_QUIET_ZONE)}${row}${"0".repeat(QR_QUIET_ZONE)}`),
...frame,
];
const lines: string[] = [];
for (let index = 0; index < padded.length; index += 2) {
const top = padded[index] ?? blank;
const bottom = padded[index + 1] ?? blank;
let line = "";
for (let column = 0; column < width; column += 1) {
const up = top[column] === "1";
const down = bottom[column] === "1";
line += up && down ? "█" : up ? "▀" : down ? "▄" : " ";
}
return null;
lines.push(line);
}
return lines;
}
function recordOf(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function pairingQrOf(raw: unknown): PairingQr | undefined {
const record = recordOf(raw);
if (!record || !Array.isArray(record.rows) || record.rows.length === 0) return undefined;
const rows = record.rows.filter((row: unknown): row is string => typeof row === "string");
if (rows.length === 0) return undefined;
return {
version: typeof record.version === "number" ? record.version : 0,
ecc: typeof record.ecc === "string" ? record.ecc : "M",
mask: typeof record.mask === "number" ? record.mask : 0,
size: typeof record.size === "number" ? record.size : (rows[0]?.length ?? 0),
rows,
};
}
function pairingBasesOf(raw: unknown): PairingBase[] {
if (!Array.isArray(raw)) return [];
return raw.flatMap((value) => {
const record = recordOf(value);
if (!record || typeof record.url !== "string") return [];
return [
{
kind: typeof record.kind === "string" ? record.kind : "other",
name: typeof record.name === "string" ? record.name : "",
address: typeof record.address === "string" ? record.address : "",
url: record.url,
},
];
});
}
/**
* `pi2 pairing` — mint a code and print a scannable link.
*
* The daemon owns the URL, the QR matrix and the list of usable bases (ADR
* 0001); the CLI only renders them. `--base` narrows the choice, and the daemon
* rejects anything it did not offer.
*/
export async function runPairing(options: PairingOptions): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const result = await options.client.post("/api/v1/pair", {});
const code = typeof result.body.code === "string" ? result.body.code : undefined;
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
// Rebuild the URL from the *actual* base URL (or the public base when one is
// known): the daemon's own `url` field is derived from the configured port,
// which is stale after a retry or `--port 0`.
const base = options.publicUrl === undefined || options.publicUrl === null || options.publicUrl.trim() === ""
? options.client.baseUrl
: withoutTrailingSlash(options.publicUrl);
const url = `${base}/pair/${code}`;
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
const base = options.base?.trim() ?? "";
const response = await options.client.post("/api/v1/pair", base === "" ? {} : { base });
const code = typeof response.body.code === "string" ? response.body.code : undefined;
const url = typeof response.body.url === "string" ? response.body.url : undefined;
if (code === undefined || url === undefined) throw new CliError("pairing failed: daemon returned no code");
const expiresAt = typeof response.body.expiresAt === "number" ? response.body.expiresAt : undefined;
const qr = pairingQrOf(response.body.qr);
const bases = pairingBasesOf(response.body.bases);
print(`url ${url}`);
print(`code ${code}`);
if (expiresAt !== undefined) {
print(`expires ${new Date(expiresAt).toISOString()} (${Math.max(0, Math.round((expiresAt - Date.now()) / 1000))}s)`);
const seconds = Math.max(0, Math.round((expiresAt - Date.now()) / 1000));
print(`expires in ${seconds}s (${new Date(expiresAt).toISOString()})`);
}
if (qr === undefined) {
print("");
print("note the link is too long to encode as a QR code; open the url on the phone instead.");
} else {
print("");
for (const line of renderTerminalQr(qr.rows)) print(line);
}
if (bases.length > 1) {
print("");
print("other addresses the phone could use (pi2 pairing --base <url>):");
for (const candidate of bases) {
print(` ${candidate.kind.padEnd(9)} ${candidate.name.padEnd(12)} ${candidate.url}`);
}
}
print(`qr ${payload}`);
return 0;
}
@@ -633,7 +736,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
case "pairing":
case "pair": {
const parsed = parseArgs(rest, {
values: ["--public-url"],
values: ["--base"],
booleans: ["--help"],
aliases: { "-h": "--help" },
});
@@ -645,7 +748,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
return await runPairing({
client,
print: out,
publicUrl: resolvePublicUrl(client, stringFlag(parsed.flags, "--public-url")),
base: stringFlag(parsed.flags, "--base"),
});
}
case "install-service":
-1
View File
@@ -93,7 +93,6 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
const cliTokenPath = join(runtime, CLI_TOKEN_FILE);
const auth = new AuthStore({
path: config.deviceStorePath,
baseUrl: `http://${config.host}:${config.port}`,
localTokenPath: cliTokenPath,
...(options.now === undefined ? {} : { now: options.now }),
});
+28 -80
View File
@@ -4,13 +4,18 @@
* Defaults follow `docs/protocol.md`; deployment-specific values come from the
* environment so `pi2 daemon` can be started without a config file.
*
* `PI2_ACCESS_MODE` picks the bind address and the derived CORS origins:
* `local` is loopback-only, `lan` adds the detected LAN address and
* `tailscale` adds the origin of `PI2_PUBLIC_URL`. `PI2_ORIGINS` is *additive*
* to the derived list; it never replaces it.
* The daemon binds `0.0.0.0` by default: the console is meant to be opened from
* a phone as well as from the desktop, and access is gated by the pairing code
* and the device token — never by the bind address. `PI2_HOST` narrows the bind
* (e.g. `127.0.0.1` for a loopback-only daemon), `PI2_PUBLIC_URL` adds the
* external base used behind `tailscale serve`, and `PI2_ORIGINS` is *additive*.
*
* The CORS allowlist is derived by `core/network` from the addresses the daemon
* is actually reachable on, so it always matches the pairing link.
*/
import { networkInterfaces } from "node:os";
import type { NetworkInterfaceInfo } from "node:os";
import { fileURLToPath } from "node:url";
import { isLoopbackHost, isWildcardHost, localOrigins } from "./core/network.js";
import { daemonTokenPath, dataDir } from "./core/paths.js";
export const DEFAULT_PORT = 7676;
@@ -18,8 +23,8 @@ export const DEFAULT_MAX_BODY_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_FRAME_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_CONNECTIONS = 64;
export type AccessMode = "local" | "lan" | "tailscale";
export const ACCESS_MODES: readonly AccessMode[] = ["local", "lan", "tailscale"];
/** Wildcard bind: reachable from the desktop, the LAN and a tailnet. */
export const DEFAULT_HOST = "0.0.0.0";
export interface Limits {
maxBodyBytes: number;
@@ -37,7 +42,6 @@ export interface Config {
limits: Limits;
tokenPath: string;
deviceStorePath: string;
access: AccessMode;
/** External base URL (no trailing slash), e.g. `https://host.tail1234.ts.net`. */
publicUrl: string | null;
}
@@ -45,8 +49,8 @@ export interface Config {
export type ConfigEnv = Record<string, string | undefined>;
export interface ConfigOptions {
/** LAN address probe for `PI2_ACCESS_MODE=lan`; overridable in tests. */
detectLanIp?: () => string | null;
/** Network interfaces used to derive the CORS origins; overridable in tests. */
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>;
}
function defaultStaticDir(): string {
@@ -63,14 +67,6 @@ function parsePort(raw: string | undefined): number {
return port;
}
/** Unknown modes fail fast; the daemon prints the message as a one-line `pi2: ` error. */
export function parseAccessMode(raw: string | undefined): AccessMode {
const value = raw?.trim() ?? "";
if (value === "") return "local";
if ((ACCESS_MODES as readonly string[]).includes(value)) return value as AccessMode;
throw new Error("PI2_ACCESS_MODE must be local, lan or tailscale");
}
/** Trailing slashes and empty strings are not meaningful origins. */
function normalizeOrigin(raw: string): string | null {
const value = raw.trim().replace(/\/+$/, "");
@@ -82,15 +78,6 @@ function normalizePublicUrl(raw: string | undefined): string | null {
return normalizeOrigin(raw);
}
/** `https://host/path?q=1` → `https://host`; unparsable values fall back verbatim. */
function originOf(url: string): string | null {
try {
return new URL(url).origin;
} catch {
return normalizeOrigin(url);
}
}
function parseOrigins(raw: string | undefined): string[] {
if (raw === undefined) return [];
return raw
@@ -103,61 +90,16 @@ function dedupe(origins: readonly string[]): string[] {
return [...new Set(origins)];
}
function defaultHostFor(access: AccessMode): string {
return access === "lan" ? "0.0.0.0" : "127.0.0.1";
}
function loopbackOrigins(port: number): string[] {
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`];
}
/**
* First non-internal IPv4 address, best effort: `lan` mode only *adds* an
* origin, and an unknown address just leaves the loopback list in place.
*/
export function detectLanIp(): string | null {
try {
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses ?? []) {
if (address.family !== "IPv4" || address.internal) continue;
if (address.address.startsWith("169.254.")) continue;
return address.address;
}
}
} catch {
// best effort only
}
return null;
}
function derivedOrigins(
access: AccessMode,
port: number,
publicUrl: string | null,
detect: () => string | null,
): string[] {
const origins = loopbackOrigins(port);
if (access === "lan") {
let lanIp: string | null = null;
try {
lanIp = detect();
} catch {
lanIp = null;
}
if (lanIp !== null && lanIp.trim() !== "") origins.push(`http://${lanIp.trim()}:${port}`);
} else if (access === "tailscale" && publicUrl !== null) {
const origin = originOf(publicUrl);
if (origin !== null) origins.push(origin);
}
return origins;
}
export function loadConfig(env: ConfigEnv = process.env, options: ConfigOptions = {}): Config {
const port = parsePort(env.PI2_PORT);
const access = parseAccessMode(env.PI2_ACCESS_MODE);
const publicUrl = normalizePublicUrl(env.PI2_PUBLIC_URL);
const host = env.PI2_HOST?.trim() || defaultHostFor(access);
const derived = derivedOrigins(access, port, publicUrl, options.detectLanIp ?? detectLanIp);
const host = env.PI2_HOST?.trim() || DEFAULT_HOST;
const derived = localOrigins({
port,
bindHost: host,
publicUrl,
...(options.interfaces === undefined ? {} : { interfaces: options.interfaces }),
});
return {
host,
@@ -171,7 +113,13 @@ export function loadConfig(env: ConfigEnv = process.env, options: ConfigOptions
},
tokenPath: daemonTokenPath(),
deviceStorePath: `${dataDir()}/devices.json`,
access,
publicUrl,
};
}
/** Human-readable bind summary, shared by `pi2 status` and `pi2 doctor`. */
export function describeHost(host: string): string {
if (isWildcardHost(host)) return "all interfaces";
if (isLoopbackHost(host)) return "loopback only";
return host;
}
+183
View File
@@ -0,0 +1,183 @@
/**
* Where the daemon can be reached, and in which order to advertise it.
*
* The console is phone-first: the daemon binds `0.0.0.0` by default, so a phone
* on the same network opens `http://<lan-ip>:<port>` and the browser sends an
* `Origin` header the daemon has to allow. Both the CORS allowlist and the
* pairing link need the same answer to "which addresses are we reachable on",
* so they share this module instead of each sniffing `os.networkInterfaces()`.
*
* `interfaces` is injectable so ordering and classification stay testable
* without the host's real NICs.
*/
import { networkInterfaces, type NetworkInterfaceInfo } from "node:os";
export type NetworkBaseKind = "public" | "lan" | "other" | "tailscale" | "loopback";
export interface NetworkBase {
kind: NetworkBaseKind;
/** Interface name, `loopback`, or `public-url` for the configured base. */
name: string;
/** IPv4 address; empty for the `public-url` entry. */
address: string;
/** Base URL, no trailing slash and no credentials. */
url: string;
}
export interface NetworkOptions {
port: number;
/** The configured bind address; decides what is reachable. Defaults to wildcard. */
bindHost?: string;
/** External base URL (e.g. behind `tailscale serve`). */
publicUrl?: string | null;
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>;
}
/** Wildcard binds: everything on the host is reachable. */
export const WILDCARD_HOSTS: readonly string[] = ["", "0.0.0.0", "::", "[::]"];
/** Interfaces that never reach a phone sitting next to the machine. */
const VIRTUAL_INTERFACE = /^(docker|veth|br-|virbr|vmnet|vboxnet|tun|tap|utun|tailscale|zt|wg|bridge|dummy)/i;
/** Interfaces a human would recognise as "the network cable / wifi". */
const PHYSICAL_INTERFACE = /^(eth|en|wlan|wl|eno|ens|enp|wlp)/i;
const PRIVATE_IPV4 = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/;
/** 100.64.0.0/10 — the tailnet range Tailscale hands out. */
const TAILSCALE_IPV4 = /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./;
/** 169.254.0.0/16 — link-local, never reachable from another device. */
const LINK_LOCAL_IPV4 = /^169\.254\./;
const KIND_ORDER: Record<NetworkBaseKind, number> = {
public: 0,
lan: 1,
other: 2,
tailscale: 3,
loopback: 4,
};
/** `127.0.0.1`, `::1`, `localhost` — only this machine can connect. */
export function isLoopbackHost(host: string | undefined | null): boolean {
const value = (host ?? "").trim().toLowerCase().replace(/^\[|\]$/g, "");
if (value === "" || value === "localhost") return true;
if (value === "::1" || value === "0:0:0:0:0:0:0:1") return true;
return value.startsWith("127.");
}
/** `0.0.0.0` / `::` / empty: every interface. */
export function isWildcardHost(host: string | undefined | null): boolean {
return WILDCARD_HOSTS.includes((host ?? "").trim().toLowerCase());
}
export function isVirtualInterface(name: string): boolean {
return VIRTUAL_INTERFACE.test(name);
}
export function classifyAddress(name: string, address: string): NetworkBaseKind {
if (address.startsWith("127.")) return "loopback";
if (/^tailscale/i.test(name) || TAILSCALE_IPV4.test(address)) return "tailscale";
if (PRIVATE_IPV4.test(address)) return "lan";
return "other";
}
function isIPv4(entry: NetworkInterfaceInfo): boolean {
// Node exposes `family` as a string ("IPv4") on modern versions and a number
// (4) on older ones; accept both.
return entry.family === "IPv4" || (entry.family as unknown as number) === 4;
}
function normalizeBase(raw: string): string {
return raw.trim().replace(/\/+$/, "");
}
function originOf(url: string): string | null {
try {
return new URL(url).origin;
} catch {
return normalizeBase(url) === "" ? null : normalizeBase(url);
}
}
/**
* Every base a browser could use, best first.
*
* `bindHost` decides reachability: a loopback bind only advertises loopback (a
* public URL still counts — `tailscale serve` proxies to the loopback port), a
* specific address advertises that address plus loopback, and a wildcard bind
* advertises everything the host has.
*/
export function networkBases(options: NetworkOptions): NetworkBase[] {
const port = options.port;
const bindHost = options.bindHost;
const bases: NetworkBase[] = [];
const publicUrl = normalizeBase(options.publicUrl ?? "");
if (publicUrl !== "") bases.push({ kind: "public", name: "public-url", address: "", url: publicUrl });
const loopback = (name: string, address: string): NetworkBase => ({
kind: "loopback",
name,
address,
url: `http://${address}:${port}`,
});
const wildcard = isWildcardHost(bindHost);
if (!wildcard && isLoopbackHost(bindHost)) {
// Loopback-only daemon: nothing else is reachable, not even its own NICs.
return [...bases, loopback("loopback", "127.0.0.1")];
}
const boundAddress = wildcard ? null : normalizeBase(String(bindHost));
const rows: NetworkBase[] = [];
for (const [name, addresses] of Object.entries(options.interfaces ?? networkInterfaces())) {
for (const entry of addresses ?? []) {
if (entry.internal) continue;
if (!isIPv4(entry)) continue;
if (LINK_LOCAL_IPV4.test(entry.address)) continue;
if (boundAddress !== null && entry.address !== boundAddress) continue;
rows.push({
kind: classifyAddress(name, entry.address),
name,
address: entry.address,
url: `http://${entry.address}:${port}`,
});
}
}
rows.sort((left, right) => {
const byKind = KIND_ORDER[left.kind] - KIND_ORDER[right.kind];
if (byKind !== 0) return byKind;
const physical = Number(isVirtualInterface(left.name)) - Number(isVirtualInterface(right.name));
if (physical !== 0) return physical;
return left.name.localeCompare(right.name) || left.address.localeCompare(right.address);
});
bases.push(...rows);
bases.push(loopback("loopback", "127.0.0.1"));
return bases;
}
/** The base the daemon advertises by default: public URL, else best LAN, else loopback. */
export function primaryBase(options: NetworkOptions): NetworkBase {
const bases = networkBases(options);
const first = bases[0];
if (first === undefined) throw new Error("no reachable base address");
return first;
}
/**
* CORS allowlist: every reachable base, plus the loopback aliases a browser may
* have typed (`localhost`, IPv6 loopback).
*/
export function localOrigins(options: NetworkOptions): string[] {
const origins = new Set<string>();
for (const base of networkBases(options)) {
const origin = base.kind === "public" ? originOf(base.url) : null;
origins.add(origin ?? base.url);
}
const port = options.port;
origins.add(`http://localhost:${port}`);
origins.add(`http://[::1]:${port}`);
return [...origins];
}
+587
View File
@@ -0,0 +1,587 @@
/**
* Minimal QR Code encoder — byte mode, error-correction level M, versions 1–10.
*
* Why hand-rolled: `pi2 pairing` must be able to print something a phone camera
* can scan, and the daemon keeps a deliberately tiny dependency set (`hono`,
* `ws`, `zod`). A byte-mode-only encoder with a single EC level is ~300 lines
* of tables and bit shuffling, and it is fully covered by `test/core/qr.test.ts`
* (decoded with `zbarimg` when it is on `PATH`).
*
* Output is presentation-agnostic: `rows` is one string per module row, `1` for
* a dark module and `0` for a light one, without a quiet zone — every renderer
* (a Neovim float, a terminal, a canvas) adds its own margin and colors.
*
* Reference: ISO/IEC 18004; structure mirrors the well-known
* `qrcode-generator` implementation (mask patterns, format/version placement).
*/
/** Error-correction level: M (15% recovery) is the screen-scanning sweet spot. */
export type QrEcc = "M";
export interface QrMatrix {
/** QR version (1..10): the symbol is `4 * version + 17` modules wide. */
version: number;
ecc: QrEcc;
/** Mask pattern (0..7) that produced the lowest penalty score. */
mask: number;
/** Module count per side (no quiet zone). */
size: number;
/** `size` rows of `size` characters: `1` = dark, `0` = light. */
rows: string[];
}
export interface QrOptions {
/** Force a version instead of picking the smallest one that fits. */
version?: number;
/** Force a mask (0..7) instead of choosing by penalty score. Debug/tests. */
mask?: number;
}
export const MIN_VERSION = 1;
export const MAX_VERSION = 10;
export const ECC: QrEcc = "M";
/** ECC level bits used in the format information (M = 00). */
const ECC_FORMAT_BITS = 0b00;
interface BlockGroup {
/** Number of identical blocks. */
count: number;
/** Data codewords per block. */
dataCodewords: number;
}
interface VersionSpec {
/** EC codewords appended to every block. */
ecCodewordsPerBlock: number;
groups: BlockGroup[];
/** Total codewords (data + EC) the symbol carries. */
totalCodewords: number;
}
/**
* ECC-M block layout per version (ISO/IEC 18004 table 9). `totalCodewords`
* checks out against `data + ec` for every row; `test/core/qr.test.ts` asserts
* it so a typo cannot silently ship a mis-sized symbol.
*/
const VERSIONS: Record<number, VersionSpec> = {
1: { ecCodewordsPerBlock: 10, groups: [{ count: 1, dataCodewords: 16 }], totalCodewords: 26 },
2: { ecCodewordsPerBlock: 16, groups: [{ count: 1, dataCodewords: 28 }], totalCodewords: 44 },
3: { ecCodewordsPerBlock: 26, groups: [{ count: 1, dataCodewords: 44 }], totalCodewords: 70 },
4: { ecCodewordsPerBlock: 18, groups: [{ count: 2, dataCodewords: 32 }], totalCodewords: 100 },
5: { ecCodewordsPerBlock: 24, groups: [{ count: 2, dataCodewords: 43 }], totalCodewords: 134 },
6: { ecCodewordsPerBlock: 16, groups: [{ count: 4, dataCodewords: 27 }], totalCodewords: 172 },
7: { ecCodewordsPerBlock: 18, groups: [{ count: 4, dataCodewords: 31 }], totalCodewords: 196 },
8: {
ecCodewordsPerBlock: 22,
groups: [
{ count: 2, dataCodewords: 38 },
{ count: 2, dataCodewords: 39 },
],
totalCodewords: 242,
},
9: {
ecCodewordsPerBlock: 22,
groups: [
{ count: 3, dataCodewords: 36 },
{ count: 2, dataCodewords: 37 },
],
totalCodewords: 292,
},
10: {
ecCodewordsPerBlock: 26,
groups: [
{ count: 4, dataCodewords: 43 },
{ count: 1, dataCodewords: 44 },
],
totalCodewords: 346,
},
};
/** Alignment-pattern centre coordinates per version (0 length = none). */
const ALIGNMENT_CENTERS: Record<number, number[]> = {
1: [],
2: [6, 18],
3: [6, 22],
4: [6, 26],
5: [6, 30],
6: [6, 34],
7: [6, 22, 38],
8: [6, 24, 42],
9: [6, 26, 46],
10: [6, 28, 50],
};
/** Remainder bits after the last full codeword (version 1 and 7+ have none). */
const REMAINDER_BITS: Record<number, number> = {
1: 0,
2: 7,
3: 7,
4: 7,
5: 7,
6: 7,
7: 0,
8: 0,
9: 0,
10: 0,
};
const dataCodewords = (spec: VersionSpec): number =>
spec.groups.reduce((total, group) => total + group.count * group.dataCodewords, 0);
/** Character-count indicator width for byte mode. */
const charCountBits = (version: number): number => (version <= 9 ? 8 : 16);
/* -------------------------------------------------------------------------- */
/* GF(256) arithmetic + Reed-Solomon */
/* -------------------------------------------------------------------------- */
const GF_EXP = new Uint8Array(512);
const GF_LOG = new Uint8Array(256);
{
let value = 1;
for (let i = 0; i < 255; i += 1) {
GF_EXP[i] = value;
GF_LOG[value] = i;
value <<= 1;
if ((value & 0x100) !== 0) value ^= 0x11d;
}
for (let i = 255; i < 512; i += 1) GF_EXP[i] = GF_EXP[i - 255] as number;
}
function gfMultiply(a: number, b: number): number {
if (a === 0 || b === 0) return 0;
return GF_EXP[(GF_LOG[a] as number) + (GF_LOG[b] as number)] as number;
}
/** Generator polynomial of the requested degree, highest-order coefficient first. */
function rsGenerator(degree: number): number[] {
let poly = [1];
for (let i = 0; i < degree; i += 1) {
const root = GF_EXP[i] as number;
const next = new Array<number>(poly.length + 1).fill(0);
next[0] = poly[0] as number;
for (let j = 1; j < poly.length; j += 1) {
next[j] = (poly[j] as number) ^ gfMultiply(root, poly[j - 1] as number);
}
next[poly.length] = gfMultiply(root, poly[poly.length - 1] as number);
poly = next;
}
return poly;
}
/** EC codewords for one block, computed as the polynomial remainder. */
function rsEncode(data: number[], generator: number[]): number[] {
const degree = generator.length - 1;
const remainder = new Array<number>(degree).fill(0);
for (const byte of data) {
const factor = byte ^ (remainder[0] as number);
remainder.shift();
remainder.push(0);
for (let i = 0; i < degree; i += 1) {
remainder[i] = (remainder[i] as number) ^ gfMultiply(generator[i + 1] as number, factor);
}
}
return remainder;
}
/* -------------------------------------------------------------------------- */
/* Bit stream + codewords */
/* -------------------------------------------------------------------------- */
function pushBits(bits: number[], value: number, length: number): void {
for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1);
}
/** Smallest version whose data capacity holds `byteLength` bytes. */
function pickVersion(byteLength: number): number {
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
const spec = VERSIONS[version] as VersionSpec;
const capacityBits = dataCodewords(spec) * 8;
const neededBits = 4 + charCountBits(version) + byteLength * 8;
if (neededBits <= capacityBits) return version;
}
throw new RangeError(
`qr: ${byteLength} bytes do not fit in a version-${MAX_VERSION} ECC-M symbol (max ${Math.floor(
(dataCodewords(VERSIONS[MAX_VERSION] as VersionSpec) * 8 - 4 - charCountBits(MAX_VERSION)) / 8,
)} bytes)`,
);
}
/** Header + payload, terminator, byte padding, alternating 0xEC/0x11 fill. */
function buildDataCodewords(bytes: number[], version: number): number[] {
const spec = VERSIONS[version] as VersionSpec;
const capacityBits = dataCodewords(spec) * 8;
const bits: number[] = [];
pushBits(bits, 0b0100, 4); // byte mode
pushBits(bits, bytes.length, charCountBits(version));
for (const byte of bytes) pushBits(bits, byte, 8);
pushBits(bits, 0, Math.min(4, capacityBits - bits.length));
while (bits.length % 8 !== 0) bits.push(0);
const codewords: number[] = [];
for (let i = 0; i < bits.length; i += 8) {
let byte = 0;
for (let bit = 0; bit < 8; bit += 1) byte = (byte << 1) | (bits[i + bit] as number);
codewords.push(byte);
}
let pad = 0;
while (codewords.length < dataCodewords(spec)) {
codewords.push(pad % 2 === 0 ? 0xec : 0x11);
pad += 1;
}
return codewords;
}
/** Split into blocks, append EC, then interleave (data first, then EC). */
function buildCodewordStream(bytes: number[], version: number): number[] {
const spec = VERSIONS[version] as VersionSpec;
const flat = buildDataCodewords(bytes, version);
const generator = rsGenerator(spec.ecCodewordsPerBlock);
const blocks: { data: number[]; ec: number[] }[] = [];
let offset = 0;
for (const group of spec.groups) {
for (let i = 0; i < group.count; i += 1) {
const data = flat.slice(offset, offset + group.dataCodewords);
offset += group.dataCodewords;
blocks.push({ data, ec: rsEncode(data, generator) });
}
}
const longestData = Math.max(...blocks.map((block) => block.data.length));
const stream: number[] = [];
for (let i = 0; i < longestData; i += 1) {
for (const block of blocks) {
const value = block.data[i];
if (value !== undefined) stream.push(value);
}
}
for (let i = 0; i < spec.ecCodewordsPerBlock; i += 1) {
for (const block of blocks) stream.push(block.ec[i] as number);
}
return stream;
}
/* -------------------------------------------------------------------------- */
/* Symbol construction */
/* -------------------------------------------------------------------------- */
type Grid = Int8Array[]; // -1 = unset, 0 = light, 1 = dark
const makeGrid = (size: number): Grid =>
Array.from({ length: size }, () => new Int8Array(size).fill(-1));
const inBounds = (size: number, row: number, col: number): boolean =>
row >= 0 && col >= 0 && row < size && col < size;
function setModule(grid: Grid, size: number, row: number, col: number, dark: boolean): void {
if (inBounds(size, row, col)) grid[row]![col] = dark ? 1 : 0;
}
function placeFinder(grid: Grid, size: number, row: number, col: number): void {
// 7x7 eye + the light separator ring around it.
for (let dr = -1; dr <= 7; dr += 1) {
for (let dc = -1; dc <= 7; dc += 1) {
const r = row + dr;
const c = col + dc;
if (!inBounds(size, r, c)) continue;
const inEye = dr >= 0 && dr <= 6 && dc >= 0 && dc <= 6;
const dark = inEye && (dr === 0 || dr === 6 || dc === 0 || dc === 6 || (dr >= 2 && dr <= 4 && dc >= 2 && dc <= 4));
grid[r]![c] = dark ? 1 : 0;
}
}
}
function placeAlignment(grid: Grid, size: number, centreRow: number, centreCol: number): void {
for (let dr = -2; dr <= 2; dr += 1) {
for (let dc = -2; dc <= 2; dc += 1) {
const dark = Math.abs(dr) === 2 || Math.abs(dc) === 2 || (dr === 0 && dc === 0);
setModule(grid, size, centreRow + dr, centreCol + dc, dark);
}
}
}
/** Finder eyes, separators, timing, alignment, dark module, reserved info areas. */
function placeFunctionPatterns(grid: Grid, size: number, version: number): void {
placeFinder(grid, size, 0, 0);
placeFinder(grid, size, 0, size - 7);
placeFinder(grid, size, size - 7, 0);
for (let i = 8; i < size - 8; i += 1) {
const dark = i % 2 === 0;
if (grid[6]![i] === -1) grid[6]![i] = dark ? 1 : 0;
if (grid[i]![6] === -1) grid[i]![6] = dark ? 1 : 0;
}
const centres = ALIGNMENT_CENTERS[version] as number[];
for (const row of centres) {
for (const col of centres) {
// Skip the three positions that collide with the finder eyes.
const overlapsFinder = (row <= 8 && col <= 8) || (row <= 8 && col >= size - 9) || (row >= size - 9 && col <= 8);
if (overlapsFinder) continue;
placeAlignment(grid, size, row, col);
}
}
// Format information areas (written later) and the always-dark module.
for (let i = 0; i < 9; i += 1) {
if (grid[8]![i] === -1) grid[8]![i] = 0;
if (grid[i]![8] === -1) grid[i]![8] = 0;
}
for (let i = 0; i < 8; i += 1) {
if (grid[8]![size - 1 - i] === -1) grid[8]![size - 1 - i] = 0;
if (grid[size - 1 - i]![8] === -1) grid[size - 1 - i]![8] = 0;
}
grid[size - 8]![8] = 1;
if (version >= 7) {
for (let i = 0; i < 18; i += 1) {
const row = Math.floor(i / 3);
const col = (i % 3) + size - 11;
if (grid[row]![col] === -1) grid[row]![col] = 0;
if (grid[col]![row] === -1) grid[col]![row] = 0;
}
}
}
/** Zigzag data placement, MSB first, skipping the vertical timing column. */
function placeData(grid: Grid, size: number, codewords: number[], mask: number): void {
let bitIndex = 7;
let byteIndex = 0;
let row = size - 1;
let direction = -1;
for (let col = size - 1; col > 0; col -= 2) {
if (col === 6) col -= 1;
for (;;) {
for (let offset = 0; offset < 2; offset += 1) {
const c = col - offset;
if (grid[row]![c] !== -1) continue;
const byte = codewords[byteIndex];
let dark = byte !== undefined && ((byte >>> bitIndex) & 1) === 1;
if (maskApplies(mask, row, c)) dark = !dark;
grid[row]![c] = dark ? 1 : 0;
bitIndex -= 1;
if (bitIndex < 0) {
bitIndex = 7;
byteIndex += 1;
}
}
row += direction;
if (row < 0 || row >= size) {
row -= direction;
direction = -direction;
break;
}
}
}
}
/** The eight mask conditions, `i` = row, `j` = column. */
function maskApplies(mask: number, row: number, col: number): boolean {
switch (mask) {
case 0:
return (row + col) % 2 === 0;
case 1:
return row % 2 === 0;
case 2:
return col % 3 === 0;
case 3:
return (row + col) % 3 === 0;
case 4:
return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0;
case 5:
return ((row * col) % 2) + ((row * col) % 3) === 0;
case 6:
return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0;
case 7:
return (((row * col) % 3) + ((row + col) % 2)) % 2 === 0;
default:
throw new RangeError(`qr: mask must be 0..7, got ${mask}`);
}
}
/** Polynomial remainder over GF(2): `data << shift` mod `poly`. */
function bchRemainder(data: number, poly: number, shift: number): number {
let remainder = data << shift;
while (remainder !== 0 && bitLength(remainder) >= bitLength(poly)) {
remainder ^= poly << (bitLength(remainder) - bitLength(poly));
}
return remainder;
}
/** BCH(15,5) remainder for the format information. */
function formatBits(mask: number): number {
const data = (ECC_FORMAT_BITS << 3) | mask;
return (((data << 10) | bchRemainder(data, 0x537, 10)) ^ 0x5412) & 0x7fff;
}
/** BCH(18,6) remainder for the version information (version >= 7). */
function versionBits(version: number): number {
return ((version << 12) | bchRemainder(version, 0x1f25, 12)) & 0x3ffff;
}
function bitLength(value: number): number {
let length = 0;
let rest = value;
while (rest !== 0) {
length += 1;
rest >>>= 1;
}
return length;
}
function writeFormatInfo(grid: Grid, size: number, mask: number): void {
const bits = formatBits(mask);
for (let i = 0; i < 15; i += 1) {
const dark = ((bits >>> i) & 1) === 1;
// Vertical strip (column 8) …
if (i < 6) grid[i]![8] = dark ? 1 : 0;
else if (i < 8) grid[i + 1]![8] = dark ? 1 : 0;
else grid[size - 15 + i]![8] = dark ? 1 : 0;
// … and its mirrored horizontal copy (row 8).
if (i < 8) grid[8]![size - 1 - i] = dark ? 1 : 0;
else if (i < 9) grid[8]![15 - i] = dark ? 1 : 0;
else grid[8]![14 - i] = dark ? 1 : 0;
}
grid[size - 8]![8] = 1;
}
function writeVersionInfo(grid: Grid, size: number, version: number): void {
if (version < 7) return;
const bits = versionBits(version);
for (let i = 0; i < 18; i += 1) {
const dark = ((bits >>> i) & 1) === 1;
const row = Math.floor(i / 3);
const col = (i % 3) + size - 11;
grid[row]![col] = dark ? 1 : 0;
grid[col]![row] = dark ? 1 : 0;
}
}
/** ISO/IEC 18004 §8.8.2 penalty rules N1..N4; the mask with the lowest score wins. */
function penaltyScore(grid: Grid, size: number): number {
let score = 0;
// N1: runs of five or more identical modules in a row/column.
for (let i = 0; i < size; i += 1) {
let rowRun = 1;
let colRun = 1;
for (let j = 1; j < size; j += 1) {
if (grid[i]![j] === grid[i]![j - 1]) rowRun += 1;
else {
if (rowRun >= 5) score += 3 + (rowRun - 5);
rowRun = 1;
}
if (grid[j]![i] === grid[j - 1]![i]) colRun += 1;
else {
if (colRun >= 5) score += 3 + (colRun - 5);
colRun = 1;
}
}
if (rowRun >= 5) score += 3 + (rowRun - 5);
if (colRun >= 5) score += 3 + (colRun - 5);
}
// N2: 2x2 blocks of one colour.
for (let row = 0; row < size - 1; row += 1) {
for (let col = 0; col < size - 1; col += 1) {
const value = grid[row]![col];
if (value === grid[row]![col + 1] && value === grid[row + 1]![col] && value === grid[row + 1]![col + 1]) {
score += 3;
}
}
}
// N3: finder-like 1:1:3:1:1 patterns with four light modules on either side.
const finderLike = [1, 0, 1, 1, 1, 0, 1] as const;
const matchesAt = (line: number[], start: number, pattern: readonly number[]): boolean =>
pattern.every((expected, offset) => line[start + offset] === expected);
const rows: number[][] = [];
const cols: number[][] = [];
for (let i = 0; i < size; i += 1) {
rows.push(Array.from(grid[i] as Int8Array));
cols.push(Array.from({ length: size }, (_, j) => grid[j]![i] as number));
}
for (const line of [...rows, ...cols]) {
for (let start = 0; start + 11 <= size; start += 1) {
if (matchesAt(line, start, finderLike) && line.slice(start + 7, start + 11).every((v) => v === 0)) score += 40;
if (matchesAt(line, start, [0, 0, 0, 0, ...finderLike])) score += 40;
}
}
// N4: deviation of the dark-module ratio from 50%.
let dark = 0;
for (const line of grid) for (const value of line) if (value === 1) dark += 1;
const percent = (dark * 100) / (size * size);
score += Math.floor(Math.abs(percent - 50) / 5) * 10;
return score;
}
function toRows(grid: Grid, size: number): string[] {
return grid.map((line) => Array.from({ length: size }, (_, col) => (line[col] === 1 ? "1" : "0")).join(""));
}
/**
* Encode `text` (UTF-8) as a QR symbol at ECC level M.
*
* @throws RangeError when the payload does not fit a version-10 symbol or an
* override is out of range.
*/
export function encodeQr(text: string, options: QrOptions = {}): QrMatrix {
const bytes = Array.from(Buffer.from(text, "utf8"));
const version = options.version ?? pickVersion(bytes.length);
if (!Number.isInteger(version) || version < MIN_VERSION || version > MAX_VERSION) {
throw new RangeError(`qr: version must be ${MIN_VERSION}..${MAX_VERSION}, got ${options.version}`);
}
if (bytes.length > capacityBytes(version)) {
throw new RangeError(`qr: ${bytes.length} bytes do not fit version ${version} at ECC M`);
}
if (options.mask !== undefined && (!Number.isInteger(options.mask) || options.mask < 0 || options.mask > 7)) {
throw new RangeError(`qr: mask must be 0..7, got ${options.mask}`);
}
const size = version * 4 + 17;
const codewords = buildCodewordStream(bytes, version);
// The mask is applied while the data modules are placed, so every candidate
// starts from a fresh copy of the function patterns.
const candidates = options.mask === undefined ? [0, 1, 2, 3, 4, 5, 6, 7] : [options.mask];
let best: { mask: number; grid: Grid; score: number } | undefined;
for (const mask of candidates) {
const grid = makeGrid(size);
placeFunctionPatterns(grid, size, version);
placeData(grid, size, codewords, mask);
writeFormatInfo(grid, size, mask);
writeVersionInfo(grid, size, version);
const score = penaltyScore(grid, size);
if (best === undefined || score < best.score) best = { mask, grid, score };
}
const chosen = best as { mask: number; grid: Grid };
return {
version,
ecc: ECC,
mask: chosen.mask,
size,
rows: toRows(chosen.grid, size),
};
}
/** Bytes a version-`version` ECC-M symbol can carry, excluding header bytes. */
export function capacityBytes(version: number = MAX_VERSION): number {
const spec = VERSIONS[version] as VersionSpec | undefined;
if (spec === undefined) throw new RangeError(`qr: unknown version ${version}`);
return Math.floor((dataCodewords(spec) * 8 - 4 - charCountBits(version)) / 8);
}
/** `true` when the whole payload fits at ECC M (used by callers to fail early). */
export function fitsQr(text: string): boolean {
return Buffer.byteLength(text, "utf8") <= capacityBytes(MAX_VERSION);
}
/** Version table exposed for tests (capacity assertions). */
export function versionSpecs(): Record<number, VersionSpec> {
return VERSIONS;
}
+6 -32
View File
@@ -6,7 +6,7 @@
*
* A second, non-persisted credential exists for local tooling: the CLI token in
* `<runtime>/cli.token` (written by `pi2 daemon`). It authenticates as the synthetic
* `local-cli` device with every scope; see `docs/deployment.md` §7.
* `local-cli` device; see `docs/deployment.md` §7.
*/
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -16,17 +16,13 @@ import { ERROR_CODES } from "../protocol/errors.js";
import { DaemonError } from "./errors.js";
export type DeviceKind = "phone" | "laptop" | "tablet";
export type Scope = "read" | "steer" | "control" | "admin";
export const DEVICE_KINDS: readonly DeviceKind[] = ["phone", "laptop", "tablet"];
export const SCOPES: readonly Scope[] = ["read", "steer", "control", "admin"];
export const DEFAULT_SCOPES: readonly Scope[] = ["read", "steer", "control"];
export interface DeviceRecord {
id: string;
name: string;
kind: DeviceKind;
scopes: Scope[];
tokenHash: string;
createdAt: number;
lastSeenAt: number;
@@ -38,12 +34,11 @@ export type DevicePublic = Omit<DeviceRecord, "tokenHash">;
export interface CreateDeviceInput {
name: string;
kind: DeviceKind;
scopes?: Scope[];
}
/** Minted code; the URL is built by the HTTP layer from `core/network`. */
export interface PairCode {
code: string;
url: string;
expiresAt: number;
nonce: string;
}
@@ -63,13 +58,12 @@ export interface AuthStoreOptions {
/** Defaults to `<dataDir>/devices.json`. */
path?: string;
now?: () => number;
baseUrl?: string;
/** `touchDevice` write throttle. */
touchIntervalMs?: number;
/**
* File holding the local CLI token (`<runtime>/cli.token`, written by `pi2 daemon`).
* A bearer token equal to its trimmed contents authenticates as the synthetic
* `local-cli` device with every scope. Checked after the persisted devices.
* `local-cli` device. Checked after the persisted devices.
*/
localTokenPath?: string;
/**
@@ -136,13 +130,9 @@ function isDeviceKind(value: unknown): value is DeviceKind {
return typeof value === "string" && (DEVICE_KINDS as readonly string[]).includes(value);
}
function isScope(value: unknown): value is Scope {
return typeof value === "string" && (SCOPES as readonly string[]).includes(value);
}
function publicDevice(record: DeviceRecord): DevicePublic {
const { tokenHash: _tokenHash, ...rest } = record;
return { ...rest, scopes: [...rest.scopes] };
return { ...rest };
}
function pairCode(): string {
@@ -158,7 +148,6 @@ export class AuthStore {
readonly localTokenPath: string | undefined;
readonly localBrowserTokenPath: string;
private readonly now: () => number;
private readonly baseUrl: string;
private readonly touchIntervalMs: number;
private readonly devices: DeviceRecord[] = [];
private readonly pairs = new Map<string, PairEntry>();
@@ -166,7 +155,6 @@ export class AuthStore {
constructor(options: AuthStoreOptions = {}) {
this.path = options.path ?? `${dataDir()}/devices.json`;
this.now = options.now ?? Date.now;
this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:7676").replace(/\/+$/, "");
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
this.localTokenPath =
options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath;
@@ -180,16 +168,12 @@ export class AuthStore {
}
if (!isDeviceKind(input.kind)) throw DaemonError.badRequest(`unknown device kind "${String(input.kind)}"`);
const scopes = input.scopes === undefined ? [...DEFAULT_SCOPES] : input.scopes.filter(isScope);
if (scopes.length === 0) scopes.push("read");
const token = randomBytes(32).toString("base64url");
const timestamp = this.now();
const record: DeviceRecord = {
id: `dev-${randomBytes(6).toString("hex")}`,
name: input.name.trim(),
kind: input.kind,
scopes,
tokenHash: hashToken(token),
createdAt: timestamp,
lastSeenAt: timestamp,
@@ -245,12 +229,7 @@ export class AuthStore {
const code = pairCode();
const nonce = randomBytes(16).toString("hex");
this.pairs.set(code, { code, nonce, expiresAt: timestamp + ttlSec * 1000, used: false });
return {
code,
url: `${this.baseUrl}/pair/${code}`,
expiresAt: timestamp + ttlSec * 1000,
nonce,
};
return { code, expiresAt: timestamp + ttlSec * 1000, nonce };
}
pairRedeem(input: RedeemPairInput): RedeemPairResult {
@@ -316,19 +295,16 @@ export class AuthStore {
const created = this.createDevice({
name: LOCAL_BROWSER_NAME,
kind: LOCAL_BROWSER_KIND,
scopes: [...SCOPES],
});
const record = this.devices.find((device) => device.id === created.device.id);
if (record === undefined) return created;
record.tokenHash = hash;
record.scopes = [...SCOPES];
this.persist();
this.writeLocalBrowserToken(token);
return { token, device: publicDevice(record) };
}
existing.tokenHash = hash;
existing.scopes = [...SCOPES];
existing.revokedAt = null;
this.persist();
this.writeLocalBrowserToken(token);
@@ -364,14 +340,13 @@ export class AuthStore {
}
}
/** The local CLI token grants every scope; it is not persisted or revocable. */
/** The local CLI token is the daemon's own admin credential; not persisted, not revocable. */
private localCliDevice(): DevicePublic {
const timestamp = this.now();
return {
id: LOCAL_CLI_DEVICE_ID,
name: "local CLI",
kind: "laptop",
scopes: [...SCOPES],
createdAt: 0,
lastSeenAt: timestamp,
revokedAt: null,
@@ -428,7 +403,6 @@ export class AuthStore {
id: candidate.id,
name: candidate.name,
kind: candidate.kind,
scopes: Array.isArray(candidate.scopes) ? candidate.scopes.filter(isScope) : ["read"],
tokenHash: candidate.tokenHash,
createdAt: candidate.createdAt,
lastSeenAt: typeof candidate.lastSeenAt === "number" ? candidate.lastSeenAt : candidate.createdAt,
+90 -10
View File
@@ -8,9 +8,12 @@ import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/inter
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import { networkBases } from "../core/network.js";
import { encodeQr, fitsQr } from "../core/qr.js";
import type { AuthStore, DevicePublic } from "./auth.js";
import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js";
import { DaemonError, toErrorPayload } from "./errors.js";
import { PairRateLimiter } from "./rate-limit.js";
import { CommandRouter } from "./router.js";
import { createSseHandler } from "./sse.js";
import { serveStatic } from "./static.js";
@@ -36,6 +39,8 @@ export interface AppDeps {
startedAt?: number;
now?: () => number;
metrics?: () => DaemonMetrics;
/** Redeem budget; injectable so tests can advance the clock. */
pairLimiter?: PairRateLimiter;
}
function bearer(c: Context<Env>): string | undefined {
@@ -50,6 +55,16 @@ function isLoopback(c: Context<Env>): boolean {
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
}
/** Rate-limit key for the public redeem endpoint. */
function clientAddress(c: Context<Env>): string {
return c.env?.incoming?.socket?.remoteAddress ?? "unknown";
}
/** `http://host:port` without a trailing slash, for `base` validation. */
function normalizeBase(raw: string): string {
return raw.trim().replace(/\/+$/, "");
}
/** Daemon package version; falls back to the v1 baseline when package.json is unavailable. */
function daemonVersion(): string {
try {
@@ -138,6 +153,7 @@ export function createApp(deps: AppDeps): Hono<Env> {
const startedAt = deps.startedAt ?? now();
const app = new Hono<Env>();
const router = new CommandRouter({ auth, instances, workspaces, logger, now, daemonId: deps.daemonId });
const pairLimiter = deps.pairLimiter ?? new PairRateLimiter(undefined, { now });
// Origin check + CORS. Applies to every surface, including SSE.
app.use("*", async (c, next) => {
@@ -163,8 +179,9 @@ export function createApp(deps: AppDeps): Hono<Env> {
if (path === "/api/v1/info" || path === "/api/v1/health") {
if (isLoopback(c)) return next();
}
// Pairing redeem is public; pair.create enforces auth in its handler.
if (path === "/api/v1/pair") return next();
// Redeeming a code is public by design (the code is the capability) and
// rate limited below; minting one requires a device token.
if (path === "/api/v1/pair/redeem") return next();
const token = bearer(c);
const device = token ? auth.verifyToken(token) : null;
if (!device) {
@@ -188,7 +205,7 @@ export function createApp(deps: AppDeps): Hono<Env> {
port: config.port,
capabilities: ["ws", "sse", "devices", "attention"],
limits: config.limits,
access: config.access,
host: config.host,
publicUrl: config.publicUrl,
}),
);
@@ -331,21 +348,84 @@ export function createApp(deps: AppDeps): Hono<Env> {
return json(result.status, result.body);
});
/**
* Mint a pairing code. Authenticated (a device token or the local CLI token);
* the response carries everything a renderer needs — the chosen URL, the QR
* matrix and every base a client may ask for next time (`base`).
*/
app.post("/api/v1/pair", async (c) => {
publicDeviceOrThrow(c, auth);
const body = await readJsonBody(c, config.limits.maxBodyBytes);
const ttlSec = typeof body.ttlSec === "number" ? body.ttlSec : undefined;
const pair = auth.pairCreate(ttlSec === undefined ? {} : { ttlSec });
const bases = networkBases({
port: config.port,
bindHost: config.host,
publicUrl: config.publicUrl,
});
const requested = typeof body.base === "string" ? normalizeBase(body.base) : null;
let base = bases[0]?.url ?? `http://127.0.0.1:${config.port}`;
if (requested !== null && requested !== "") {
const match = bases.find((candidate) => normalizeBase(candidate.url) === requested);
if (!match) {
throw DaemonError.badRequest(
`base must be one of: ${bases.map((candidate) => candidate.url).join(", ")}`,
);
}
base = match.url;
}
const url = `${normalizeBase(base)}/pair/${pair.code}`;
const qr = fitsQr(url) ? encodeQr(url) : null;
return c.json({
accepted: true,
code: pair.code,
url,
expiresAt: pair.expiresAt,
nonce: pair.nonce,
qr,
bases,
});
});
/**
* Redeem a code with no credentials — the code *is* the capability. Rate
* limited per client and globally so guessing is not worth the bandwidth.
*/
app.post("/api/v1/pair/redeem", async (c) => {
const decision = pairLimiter.check(clientAddress(c));
if (!decision.allowed) {
const retryAfter = Math.max(1, Math.ceil(decision.retryAfterMs / 1000));
return json(
429,
errorBody(ERROR_CODES.RATE_LIMITED, "too many pairing attempts, try again later"),
{ "retry-after": String(retryAfter) },
);
}
const body = await readJsonBody(c, config.limits.maxBodyBytes);
if (typeof body.code === "string") {
if (typeof body.kind !== "string") throw DaemonError.badRequest("kind is required");
const redeemed = auth.pairRedeem({
code: body.code,
code: typeof body.code === "string" ? body.code : "",
deviceName: typeof body.deviceName === "string" ? body.deviceName : "",
kind: body.kind as "phone" | "laptop" | "tablet",
});
return c.json({ token: redeemed.token, device: redeemed.device });
}
publicDeviceOrThrow(c, auth);
const ttlSec = typeof body.ttlSec === "number" ? body.ttlSec : undefined;
const pair = auth.pairCreate(ttlSec === undefined ? {} : { ttlSec });
return c.json({ accepted: true, ...pair });
});
/**
* The scanned link. A redirect rather than an API call: the phone's browser
* lands on the console with the code already in the query string, and the
* SPA's zero-input branch redeems it without a form.
*/
app.get("/pair/:code", (c) => {
const raw = (c.req.param("code") ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
const query = new URLSearchParams();
if (/^[A-Z0-9]{8}$/.test(raw)) query.set("code", raw);
const next = c.req.query("next");
if (next !== undefined && next !== "") query.set("next", next);
query.set("auto", "1");
return c.redirect(`/connect?${query.toString()}`, 302);
});
app.get("/events", createSseHandler({ auth, bus, corsOrigins: config.corsOrigins, logger }));
+86
View File
@@ -0,0 +1,86 @@
/**
* Sliding-window rate limiting for the public pairing endpoint.
*
* A pairing code is short enough to type and long enough that guessing it is
* hopeless *only* if the guesser cannot try millions of them. Redeem is
* unauthenticated by design (the code is the capability), so the endpoint that
* accepts it needs its own budget: a per-client window for a single noisy
* device, and a global window so a botnet cannot spread the attempts.
*
* `now` is injectable, which is how the tests advance time without sleeping.
*/
export interface RateLimitRule {
/** Attempts allowed inside the window. */
limit: number;
windowMs: number;
}
export interface RateLimitDecision {
allowed: boolean;
/** Only meaningful when `allowed` is false. */
retryAfterMs: number;
}
export interface PairRateLimitRules {
perClient: RateLimitRule;
global: RateLimitRule;
}
/** 5 attempts a minute from one address, 50 an hour overall. */
export const DEFAULT_PAIR_RATE_LIMITS: PairRateLimitRules = {
perClient: { limit: 5, windowMs: 60_000 },
global: { limit: 50, windowMs: 60 * 60_000 },
};
/** Drops entries older than the window so a long-lived daemon does not grow. */
function prune(timestamps: number[], now: number, windowMs: number): number[] {
const cutoff = now - windowMs;
let index = 0;
while (index < timestamps.length && (timestamps[index] ?? 0) <= cutoff) index += 1;
return index === 0 ? timestamps : timestamps.slice(index);
}
export class PairRateLimiter {
private readonly rules: PairRateLimitRules;
private readonly now: () => number;
private readonly clients = new Map<string, number[]>();
private global: number[] = [];
constructor(rules: PairRateLimitRules = DEFAULT_PAIR_RATE_LIMITS, options: { now?: () => number } = {}) {
this.rules = rules;
this.now = options.now ?? Date.now;
}
/**
* Count one attempt. Rejected attempts do not consume budget beyond the
* rejection itself, so a locked-out client recovers as soon as the window
* slides rather than being pushed further out on every retry.
*/
check(clientKey: string): RateLimitDecision {
const now = this.now();
this.global = prune(this.global, now, this.rules.global.windowMs);
const key = clientKey === "" ? "unknown" : clientKey;
const perClient = prune(this.clients.get(key) ?? [], now, this.rules.perClient.windowMs);
const globalFull = this.global.length >= this.rules.global.limit;
const clientFull = perClient.length >= this.rules.perClient.limit;
if (globalFull || clientFull) {
this.clients.set(key, perClient);
const window = globalFull ? this.rules.global : this.rules.perClient;
const oldest = (globalFull ? this.global : perClient)[0] ?? now;
return { allowed: false, retryAfterMs: Math.max(0, oldest + window.windowMs - now) };
}
perClient.push(now);
this.global.push(now);
this.clients.set(key, perClient);
return { allowed: true, retryAfterMs: 0 };
}
/** Test/ops hook: forget every window. */
reset(): void {
this.clients.clear();
this.global = [];
}
}
-1
View File
@@ -203,7 +203,6 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
id: state.device.id,
name: state.device.name,
kind: state.device.kind,
scopes: state.device.scopes,
},
});
};
+2 -4
View File
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { AuthStore, LOCAL_CLI_DEVICE_ID, SCOPES } from "../../src/daemon/auth.js";
import { AuthStore, LOCAL_CLI_DEVICE_ID } from "../../src/daemon/auth.js";
import { writeCliToken } from "../../src/cli/token.js";
import { removeDir, tempDir } from "./helpers.js";
@@ -27,8 +27,6 @@ describe("AuthStore local CLI token", () => {
expect(device!.id).toBe(LOCAL_CLI_DEVICE_ID);
expect(device!.id).toBe("local-cli");
expect(device!.name).toBe("local CLI");
expect(device!.scopes).toEqual([...SCOPES]);
expect(device!.scopes).toEqual(["read", "steer", "control", "admin"]);
expect(device!.revokedAt).toBeNull();
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
});
@@ -71,7 +69,7 @@ describe("AuthStore local CLI token", () => {
it("keeps paired devices working and never lists the synthetic one", () => {
writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
const { token } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read"] });
const { token } = auth.createDevice({ name: "Pixel", kind: "phone" });
expect(auth.verifyToken(token)?.name).toBe("Pixel");
expect(auth.listDevices().map((device) => device.id)).not.toContain(LOCAL_CLI_DEVICE_ID);
+31 -40
View File
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
checkAccess,
checkBind,
checkCliToken,
checkCurl,
checkLinger,
@@ -39,7 +39,7 @@ function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
port: { configured: 7676, bound: true },
access: { mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null },
bind: { host: "127.0.0.1", port: 7676, publicUrl: null },
serviceManager: { name: "systemd", available: true },
linger: { checked: true, enabled: true },
webDist: { path: "/repo/web/dist", exists: true },
@@ -70,7 +70,7 @@ describe("doctor checks (all passing)", () => {
"socket",
"daemon",
"port",
"access",
"bind",
"service-manager",
"linger",
"web-dist",
@@ -91,53 +91,44 @@ describe("doctor checks (all passing)", () => {
});
});
describe("doctor access check", () => {
it("is ok for local mode", () => {
const check = checkAccess({ mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null });
expect(check).toEqual({ name: "access", status: "ok", detail: "local (loopback only)" });
describe("doctor bind check", () => {
it("is ok for a loopback bind", () => {
const check = checkBind({ host: "127.0.0.1", port: 7676, publicUrl: null });
expect(check).toEqual({ name: "bind", status: "ok", detail: "127.0.0.1/7676 (loopback only)" });
});
it("warns for lan/tailscale with a TLS-terminated public URL", () => {
const lan = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: "https://host.ts.net" });
expect(lan.status).toBe("warn");
expect(lan.detail).toBe("lan (bind 0.0.0.0/7676, public https://host.ts.net)");
expect(lan.detail).not.toContain("no TLS");
const tailscale = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "https://host.ts.net" });
expect(tailscale.status).toBe("warn");
expect(tailscale.detail).toBe("tailscale (bind 127.0.0.1/7676, public https://host.ts.net)");
it("warns with the no-TLS hint for the default wildcard bind", () => {
const check = checkBind({ host: "0.0.0.0", port: 7676, publicUrl: null });
expect(check.status).toBe("warn");
expect(check.detail).toContain("all interfaces/7676");
expect(check.detail).toContain("no TLS");
expect(check.detail).toContain("PI2_HOST=127.0.0.1");
// A warn keeps the overall report ok — the default posture is not a failure.
expect(check.status).not.toBe("fail");
});
it("adds the no-TLS hint when the public URL is missing or plain http", () => {
const loopback = checkAccess({ mode: "lan", host: "127.0.0.1", port: 7676, publicUrl: null });
expect(loopback.status).toBe("warn");
expect(loopback.detail).toContain("lan (bind 127.0.0.1/7676)");
expect(loopback.detail).toContain("no TLS, prefer `tailscale serve`");
const plain = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "http://host.ts.net" });
expect(plain.status).toBe("warn");
expect(plain.detail).toContain("no TLS, prefer `tailscale serve`");
it("is ok behind an https public URL", () => {
const check = checkBind({ host: "0.0.0.0", port: 7676, publicUrl: "https://host.ts.net" });
expect(check).toEqual({
name: "bind",
status: "ok",
detail: "all interfaces/7676, public https://host.ts.net",
});
});
it("fails when a non-loopback bind has no public URL", () => {
const check = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null });
expect(check).toEqual({ name: "access", status: "fail", detail: "lan (bind 0.0.0.0/7676)" });
const tailscale = checkAccess({ mode: "tailscale", host: "100.64.0.1", port: 7676, publicUrl: null });
expect(tailscale.status).toBe("fail");
it("still warns for a plain-http public URL", () => {
const check = checkBind({ host: "192.168.11.7", port: 7676, publicUrl: "http://host.ts.net" });
expect(check.status).toBe("warn");
expect(check.detail).toContain("192.168.11.7/7676");
expect(check.detail).toContain("no TLS");
});
it("is wired into the default probe list after port", async () => {
const report = await checks({ access: { mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: null } });
const report = await checks({ bind: { host: "0.0.0.0", port: 7676, publicUrl: null } });
const names = report.checks.map((check) => check.name);
expect(names.indexOf("access")).toBe(names.indexOf("port") + 1);
expect(statusOf(report, "access")).toBe("warn");
// A warn keeps the overall report ok.
expect(names.indexOf("bind")).toBe(names.indexOf("port") + 1);
expect(statusOf(report, "bind")).toBe("warn");
expect(report.ok).toBe(true);
const failed = await checks({ access: { mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null } });
expect(statusOf(failed, "access")).toBe("fail");
expect(failed.ok).toBe(false);
});
});
@@ -379,7 +370,7 @@ describe("collectContext", () => {
expect(ctx.socket.exists).toBe(true);
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
expect(ctx.port).toEqual({ configured: 7712, bound: true });
expect(ctx.access).toEqual({ mode: "local", host: "127.0.0.1", port: 7712, publicUrl: null });
expect(ctx.bind).toEqual({ host: "0.0.0.0", port: 7712, publicUrl: null });
expect(ctx.serviceManager).toEqual({ name: "systemd", available: true });
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
expect(ctx.webDist.path).toBe(join(dir, "web"));
-1
View File
@@ -28,7 +28,6 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
limits: TEST_LIMITS,
tokenPath: "/tmp/pi2-daemon-cli-test.sock.token",
deviceStorePath: "/tmp/pi2-daemon-cli-test-devices.json",
access: "local",
publicUrl: null,
};
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
+11 -7
View File
@@ -183,33 +183,37 @@ describe("daemon.json", () => {
handle.release();
});
it("carries the optional access/publicUrl fields and stays readable without them", () => {
it("carries the optional host/publicUrl fields and stays readable without them", () => {
const handle = acquireLock({
lockPath,
payload: {
port: 7676,
daemonId: "d-access",
daemonId: "d-bind",
startedAt: 5,
protocolVersion: PROTOCOL_VERSION,
access: "tailscale",
host: "0.0.0.0",
publicUrl: "https://host.ts.net",
},
bootId: () => BOOT,
});
expect(readLockFile(lockPath)?.access).toBe("tailscale");
expect(readLockFile(lockPath)?.host).toBe("0.0.0.0");
expect(readLockFile(lockPath)?.publicUrl).toBe("https://host.ts.net");
handle.release();
// A legacy payload (no new fields) still parses.
const legacy = { ...payload(), pid: process.pid, bootId: BOOT };
writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`);
expect(readLockFile(lockPath)?.access).toBeUndefined();
expect(readLockFile(lockPath)?.host).toBeUndefined();
expect(readLockFile(lockPath)?.publicUrl).toBeUndefined();
});
it("refuses a malformed access field", () => {
const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "public" };
it("ignores a legacy access field and refuses a malformed host", () => {
const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "tailscale" };
writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`);
expect(readLockFile(lockPath)?.host).toBeUndefined();
const malformed = { ...payload(), pid: process.pid, bootId: BOOT, host: 7676 };
writeFileSync(lockPath, `${JSON.stringify(malformed)}\n`);
expect(readLockFile(lockPath)).toBeUndefined();
});
+63 -29
View File
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
import { basename, join } from "node:path";
import type { DaemonClient } from "../../src/cli/pi2.js";
import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runOpen, runPairing, runStatus } from "../../src/cli/pi2.js";
import { CliError, createClient, main, renderTerminalQr, resolveEndpoint, runAttach, runDoctorCommand, runOpen, runPairing, runStatus } from "../../src/cli/pi2.js";
import { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js";
import { writeCliToken } from "../../src/cli/token.js";
import type { WorkspaceInfo } from "../../src/protocol/types.js";
@@ -339,50 +339,84 @@ describe("pi2 status", () => {
});
describe("pi2 pairing", () => {
it("posts with the local token and prints url, code and qr payload", async () => {
const minted = (overrides: Record<string, unknown> = {}) => ({
accepted: true,
code: "ABCD2345",
url: "http://192.168.2.10:7712/pair/ABCD2345",
expiresAt: Date.now() + 600_000,
nonce: "abc123",
qr: {
version: 2,
ecc: "M",
mask: 3,
size: 25,
// A checkerboard keeps the terminal renderer honest: dark modules exist.
rows: Array.from({ length: 25 }, (_, y) =>
Array.from({ length: 25 }, (_, x) => ((x + y) % 2 === 0 ? "1" : "0")).join(""),
),
},
bases: [
{ kind: "lan", name: "wlan0", address: "192.168.2.10", url: "http://192.168.2.10:7712" },
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7712" },
],
...overrides,
});
it("prints the url, the code, the expiry and a terminal QR", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } });
const client = fakeClient({ pair: minted() });
const code = await runPairing({ client, print: (line) => lines.push(line) });
expect(code).toBe(0);
const text = lines.join("\n");
expect(text).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
expect(text).toContain("url http://192.168.2.10:7712/pair/ABCD2345");
expect(text).toContain("code ABCD2345");
expect(text).toContain('"code":"ABCD2345"');
expect(text).toContain('"v":1');
expect(text).toMatch(/expires in \d+s/);
// 25 modules + 2 modules of quiet zone a side = 29 module rows, two per
// text row → 15 rows, of which the first and last are pure quiet zone.
expect(lines.filter((line) => /[█▀▄]/.test(line))).toHaveLength(13);
expect(lines.some((line) => line.includes("wlan0"))).toBe(true);
expect(client.calls[0]).toBe("/api/v1/pair {}");
});
it("passes --base through so the operator can pin the interface", async () => {
const client = fakeClient({ pair: minted() });
await main(["pairing", "--base", "http://127.0.0.1:7712"], { out: () => {}, client: () => client });
expect(client.calls[0]).toBe('/api/v1/pair {"base":"http://127.0.0.1:7712"}');
});
it("prints a note instead of a QR when the daemon cannot encode the link", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: minted({ qr: null }) });
await runPairing({ client, print: (line) => lines.push(line) });
expect(lines.join("\n")).toContain("too long");
expect(lines.some((line) => /[█▀▄]/.test(line))).toBe(false);
});
it("exits non-zero when the daemon rejects the request", async () => {
await expect(
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
).rejects.toThrowError(/E_UNAUTHORIZED/);
});
});
it("rebuilds the URL on --public-url when given", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
await runPairing({ client, print: (line) => lines.push(line), publicUrl: "https://myhost.tail1234.ts.net/" });
const text = lines.join("\n");
expect(text).toContain("url https://myhost.tail1234.ts.net/pair/ABCD2345");
expect(text).toContain('"url":"https://myhost.tail1234.ts.net/pair/ABCD2345"');
expect(text).toContain("code ABCD2345");
describe("renderTerminalQr", () => {
it("packs two module rows per line and adds the quiet zone", () => {
const lines = renderTerminalQr(["10", "01"]);
// 2 modules + 2+2 quiet zone = 6 columns; (2 + 4) rows → 3 text rows.
expect(lines).toHaveLength(3);
expect(lines.every((line) => line.length === 6)).toBe(true);
expect(lines.join("")).not.toMatch(/[01]/);
expect(lines[1]).toBe(" ▀▄ ");
});
it("defaults --public-url to daemon.json's publicUrl", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
await main(["pairing"], {
out: (line) => lines.push(line),
client: () => ({ ...client, daemon: { ...DAEMON, publicUrl: "https://from-daemon.ts.net" } }),
});
expect(lines.join("\n")).toContain("url https://from-daemon.ts.net/pair/ABCD2345");
});
it("keeps the loopback URL without flags", async () => {
const lines: string[] = [];
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
await main(["pairing"], { out: (line) => lines.push(line), client: () => client });
expect(lines.join("\n")).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
it("returns nothing for an empty matrix", () => {
expect(renderTerminalQr([])).toEqual([]);
});
});
+1 -1
View File
@@ -32,7 +32,7 @@ describe("wireDaemon", () => {
expect(server.port).toBeGreaterThan(0);
expect(wired.config.port).toBe(server.port);
expect(wired.config.host).toBe("127.0.0.1");
expect(wired.config.host).toBe("0.0.0.0");
expect(wired.deps.daemonId).toMatch(/^d-/);
expect(wired.deps.instances).toBe(wired.instanceManager);
expect(wired.deps.workspaces).toBe(wired.workspaceStore);
+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, it } from "vitest";
import type { NetworkInterfaceInfo } from "node:os";
import {
classifyAddress,
isLoopbackHost,
isVirtualInterface,
isWildcardHost,
localOrigins,
networkBases,
primaryBase,
} from "../../src/core/network.js";
const ipv4 = (address: string, overrides: Partial<NetworkInterfaceInfo> = {}): NetworkInterfaceInfo => ({
address,
netmask: "255.255.255.0",
family: "IPv4",
mac: "00:00:00:00:00:00",
internal: false,
cidr: `${address}/24`,
...overrides,
});
const HOST: NodeJS.Dict<NetworkInterfaceInfo[]> = {
lo: [ipv4("127.0.0.1", { internal: true })],
wlan0: [ipv4("192.168.11.7")],
docker0: [ipv4("172.17.0.1")],
eth1: [ipv4("203.0.113.9")],
tailscale0: [ipv4("100.64.0.14")],
"br-1234": [ipv4("172.18.0.1")],
};
describe("address classification", () => {
it("maps an interface to the base kind a human would expect", () => {
expect(classifyAddress("wlan0", "192.168.11.7")).toBe("lan");
expect(classifyAddress("eth1", "203.0.113.9")).toBe("other");
expect(classifyAddress("tailscale0", "100.64.0.14")).toBe("tailscale");
expect(classifyAddress("utun3", "10.1.2.3")).toBe("lan");
expect(classifyAddress("lo", "127.0.0.1")).toBe("loopback");
});
it("recognises loopback and wildcard binds", () => {
for (const host of ["127.0.0.1", "127.1.2.3", "::1", "localhost", ""]) {
expect(isLoopbackHost(host), host).toBe(true);
}
for (const host of ["0.0.0.0", "::", "", "[::]"]) {
expect(isWildcardHost(host), host).toBe(true);
}
expect(isLoopbackHost("0.0.0.0")).toBe(false);
expect(isWildcardHost("192.168.11.7")).toBe(false);
});
it("treats container and tunnel interfaces as virtual", () => {
for (const name of ["docker0", "veth1234", "br-1234", "virbr0", "tun0", "wg0", "tailscale0"]) {
expect(isVirtualInterface(name), name).toBe(true);
}
for (const name of ["wlan0", "eth0", "enp3s0", "wlp2s0"]) {
expect(isVirtualInterface(name), name).toBe(false);
}
});
});
describe("networkBases", () => {
it("orders public → lan → other → tailscale, physical before virtual", () => {
const bases = networkBases({ port: 7676, bindHost: "0.0.0.0", interfaces: HOST });
expect(bases.map((base) => `${base.kind}:${base.name}`)).toEqual([
"lan:wlan0",
"lan:br-1234",
"lan:docker0",
"other:eth1",
"tailscale:tailscale0",
"loopback:loopback",
]);
expect(bases[0]!.url).toBe("http://192.168.11.7:7676");
});
it("puts the configured public URL first", () => {
const bases = networkBases({
port: 7676,
bindHost: "0.0.0.0",
publicUrl: "https://host.tail1234.ts.net/",
interfaces: HOST,
});
expect(bases[0]).toEqual({
kind: "public",
name: "public-url",
address: "",
url: "https://host.tail1234.ts.net",
});
});
it("skips link-local addresses entirely", () => {
const bases = networkBases({
port: 7676,
bindHost: "0.0.0.0",
interfaces: { eth0: [ipv4("169.254.10.1")] },
});
expect(bases.map((base) => base.kind)).toEqual(["loopback"]);
});
it("advertises only loopback for a loopback bind but keeps the public URL", () => {
expect(networkBases({ port: 7676, bindHost: "127.0.0.1", interfaces: HOST })).toEqual([
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7676" },
]);
const withPublic = networkBases({
port: 7676,
bindHost: "127.0.0.1",
publicUrl: "https://host.ts.net",
interfaces: HOST,
});
expect(withPublic.map((base) => base.kind)).toEqual(["public", "loopback"]);
});
it("advertises the pinned address plus loopback for a specific bind", () => {
const bases = networkBases({ port: 7676, bindHost: "192.168.11.7", interfaces: HOST });
expect(bases.map((base) => base.url)).toEqual(["http://192.168.11.7:7676", "http://127.0.0.1:7676"]);
});
it("falls back to loopback when the host has no NICs", () => {
const bases = networkBases({ port: 7676, bindHost: "0.0.0.0", interfaces: {} });
expect(bases).toEqual([
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7676" },
]);
});
it("picks the first base as the default advertisement", () => {
expect(primaryBase({ port: 7676, bindHost: "0.0.0.0", interfaces: HOST }).url).toBe("http://192.168.11.7:7676");
expect(primaryBase({ port: 7676, bindHost: "127.0.0.1", interfaces: HOST }).url).toBe("http://127.0.0.1:7676");
});
});
describe("localOrigins", () => {
it("covers every reachable address plus the loopback aliases", () => {
const origins = localOrigins({ port: 8080, bindHost: "0.0.0.0", interfaces: HOST });
expect(origins).toContain("http://192.168.11.7:8080");
expect(origins).toContain("http://100.64.0.14:8080");
expect(origins).toContain("http://127.0.0.1:8080");
expect(origins).toContain("http://localhost:8080");
expect(origins).toContain("http://[::1]:8080");
expect(origins.some((origin) => origin.includes("169.254"))).toBe(false);
});
it("reduces the public URL to its origin", () => {
const origins = localOrigins({
port: 8080,
bindHost: "0.0.0.0",
publicUrl: "https://host.ts.net/some/path?x=1",
interfaces: {},
});
expect(origins).toContain("https://host.ts.net");
expect(origins).not.toContain("https://host.ts.net/some/path?x=1");
});
it("keeps a loopback bind private", () => {
expect(localOrigins({ port: 8080, bindHost: "127.0.0.1", interfaces: HOST })).toEqual([
"http://127.0.0.1:8080",
"http://localhost:8080",
"http://[::1]:8080",
]);
});
});
+171
View File
@@ -0,0 +1,171 @@
import { describe, expect, it } from "vitest";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
capacityBytes,
encodeQr,
fitsQr,
MAX_VERSION,
MIN_VERSION,
versionSpecs,
} from "../../src/core/qr.js";
/** Render `rows` as a scaled PBM so an external decoder can read it back. */
function toPbm(rows: string[], scale = 5, quiet = 4): string {
const size = rows.length;
const total = (size + quiet * 2) * scale;
const out: string[] = ["P1", `${total} ${total}`];
for (let y = 0; y < total; y += 1) {
const row = rows[Math.floor(y / scale) - quiet];
const cells: string[] = [];
for (let x = 0; x < total; x += 1) {
const col = Math.floor(x / scale) - quiet;
cells.push(row !== undefined && col >= 0 && col < size && row[col] === "1" ? "1" : "0");
}
out.push(cells.join(" "));
}
return `${out.join("\n")}\n`;
}
function decoder<T>(command: string, args: string[], input?: string): T | undefined {
try {
const result = spawnSync(command, args, { encoding: "utf8", input, timeout: 5_000 });
return result.status === 0 ? (result.stdout as T) : undefined;
} catch {
return undefined;
}
}
const hasImageToolchain = (): boolean => {
const dir = mkdtempSync(join(tmpdir(), "pi2-qr-"));
try {
writeFileSync(join(dir, "probe.pbm"), "P1\n1 1\n0\n");
return (
decoder<string>("magick", [join(dir, "probe.pbm"), join(dir, "probe.png")]) !== undefined &&
decoder<number>("zbarimg", ["--version"]) !== undefined
);
} finally {
rmSync(dir, { recursive: true, force: true });
}
};
describe("qr encoder", () => {
it("keeps every version table internally consistent", () => {
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
const spec = versionSpecs()[version];
expect(spec, `version ${version}`).toBeDefined();
const data = spec!.groups.reduce((total, group) => total + group.count * group.dataCodewords, 0);
const blocks = spec!.groups.reduce((total, group) => total + group.count, 0);
expect(data + blocks * spec!.ecCodewordsPerBlock, `version ${version} codewords`).toBe(spec!.totalCodewords);
}
});
it("shapes the symbol and only reports dark/light modules", () => {
const qr = encodeQr("http://192.168.2.10:7676/pair/ABCD2345");
expect(qr.ecc).toBe("M");
expect(qr.size).toBe(qr.version * 4 + 17);
expect(qr.rows).toHaveLength(qr.size);
for (const row of qr.rows) {
expect(row).toHaveLength(qr.size);
expect(row).toMatch(/^[01]+$/);
}
expect(qr.mask).toBeGreaterThanOrEqual(0);
expect(qr.mask).toBeLessThanOrEqual(7);
});
it("grows the version only when the previous one no longer fits", () => {
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
expect(encodeQr("a".repeat(capacityBytes(version))).version).toBe(version);
if (version < MAX_VERSION) {
expect(encodeQr("a".repeat(capacityBytes(version) + 1)).version).toBeGreaterThan(version);
}
}
expect(encodeQr("a".repeat(capacityBytes(MAX_VERSION))).version).toBe(MAX_VERSION);
});
it("refuses payloads beyond the largest symbol", () => {
const tooBig = "a".repeat(capacityBytes(MAX_VERSION) + 1);
expect(fitsQr(tooBig)).toBe(false);
expect(() => encodeQr(tooBig)).toThrow(/do not fit/);
expect(fitsQr("a".repeat(capacityBytes(MAX_VERSION)))).toBe(true);
});
it("measures capacity in UTF-8 bytes, not characters", () => {
expect(fitsQr("扫一扫配对")).toBe(true);
// 6 characters, 18 UTF-8 bytes: too wide for a version-1 symbol (14 bytes).
expect(encodeQr("扫一扫配对").version).toBe(2);
expect(encodeQr("扫码").version).toBe(1);
// Three bytes per character: the version has to account for the encoding.
expect(encodeQr("扫".repeat(capacityBytes(1))).version).toBeGreaterThan(1);
});
it("honours forced version and mask overrides", () => {
expect(encodeQr("hello", { version: 5 }).version).toBe(5);
for (let mask = 0; mask <= 7; mask += 1) {
expect(encodeQr("hello", { mask }).mask).toBe(mask);
}
expect(() => encodeQr("hello", { version: 0 })).toThrow(/version/);
expect(() => encodeQr("hello", { mask: 8 })).toThrow(/mask/);
});
it("is deterministic", () => {
const first = encodeQr("https://myhost.tail1234.ts.net/pair/ZZZZ9999");
const second = encodeQr("https://myhost.tail1234.ts.net/pair/ZZZZ9999");
expect(second).toEqual(first);
});
it("matches the recorded matrices (decoded with zbarimg when the change landed)", () => {
// The hashes pin the whole symbol — data, EC, interleaving, mask choice
// and format/version bits. Each one was round-tripped through
// `magick` + `zbarimg` before being written down.
const golden = [
{
text: "pi2 pairing",
version: 1,
mask: 2,
sha: "96c5668a81f06621d3db59a1d33b703a6d1c4f7ff51db8ae61a9f84f8c13821c",
},
{
text: "http://192.168.2.10:7676/pair/ABCD2345",
version: 3,
mask: 4,
sha: "709a345cb1f9efaf69c839aea177da472921a8a964d27220076e9924d28f11fc",
},
{
text: "https://myhost.tail1234.ts.net/pair/ZZZZ9999",
version: 4,
mask: 4,
sha: "5b42b9ac0c90756e0db86c4941538ebe49809b5319299fb098813d219d627798",
},
];
for (const expected of golden) {
const qr = encodeQr(expected.text);
expect(qr.version, expected.text).toBe(expected.version);
expect(qr.mask, expected.text).toBe(expected.mask);
expect(createHash("sha256").update(qr.rows.join("\n")).digest("hex"), expected.text).toBe(expected.sha);
}
});
it.skipIf(!hasImageToolchain())("round-trips through a real decoder", () => {
const dir = mkdtempSync(join(tmpdir(), "pi2-qr-"));
try {
const payloads = [
"http://192.168.2.10:7676/pair/ABCD2345",
"https://myhost.tail1234.ts.net/pair/ZZZZ9999",
"扫一扫配对:pi2",
"x".repeat(capacityBytes(10)),
];
for (const [index, payload] of payloads.entries()) {
writeFileSync(join(dir, "qr.pbm"), toPbm(encodeQr(payload).rows));
expect(decoder<string>("magick", [join(dir, "qr.pbm"), join(dir, `qr-${index}.png`)]), "render").toBeDefined();
const decoded = decoder<string>("zbarimg", ["--raw", "-q", join(dir, `qr-${index}.png`)]).replace(/\n$/, "");
expect(decoded, payload).toBe(payload);
}
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});
+3 -6
View File
@@ -18,13 +18,12 @@ describe("auth device store", () => {
it("creates a device, persists its hash and never leaks it", () => {
const auth = new AuthStore({ path });
const { token, device } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read", "steer"] });
const { token, device } = auth.createDevice({ name: "Pixel", kind: "phone" });
expect(token.length).toBeGreaterThanOrEqual(40);
expect(device.id).toMatch(/^dev-/);
expect(device.name).toBe("Pixel");
expect(device.kind).toBe("phone");
expect(device.scopes).toEqual(["read", "steer"]);
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
const persisted = JSON.parse(readFileSync(path, "utf8")) as {
@@ -93,12 +92,11 @@ describe("auth device store", () => {
it("redeems a pairing code exactly once", () => {
let now = 1_700_000_000_000;
const auth = new AuthStore({ path, now: () => now, baseUrl: "http://127.0.0.1:7676" });
const auth = new AuthStore({ path, now: () => now });
const pair = auth.pairCreate({ ttlSec: 600 });
expect(pair.code).toMatch(/^[A-Z0-9]{8}$/);
expect(pair.nonce).toMatch(/^[0-9a-f]+$/);
expect(pair.url).toContain(pair.code);
expect(pair.expiresAt).toBe(now + 600_000);
const redeemed = auth.pairRedeem({ code: pair.code, deviceName: "Pixel", kind: "phone" });
@@ -138,13 +136,12 @@ describe("local browser session", () => {
afterEach(() => rmSync(dir, { recursive: true, force: true }));
it("creates exactly one local-browser device with every scope", () => {
it("creates exactly one local-browser device", () => {
const auth = new AuthStore({ path, now: () => 1_000 });
const session = auth.localBrowserSession();
expect(session.device.name).toBe("local browser");
expect(session.device.kind).toBe("laptop");
expect(session.device.scopes).toEqual(["read", "steer", "control", "admin"]);
expect(session.device.createdAt).toBe(1_000);
expect(session.device.lastSeenAt).toBe(1_000);
expect(session.device.revokedAt).toBeNull();
+58 -69
View File
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { loadConfig } from "../../src/config.js";
import type { NetworkInterfaceInfo } from "node:os";
import { DEFAULT_HOST, loadConfig } from "../../src/config.js";
import { localOrigins } from "../../src/core/network.js";
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
@@ -11,12 +13,22 @@ const LOOPBACK = (port: number): string[] => [
`http://[::1]:${port}`,
];
const ipv4 = (address: string, overrides: Partial<NetworkInterfaceInfo> = {}): NetworkInterfaceInfo => ({
address,
netmask: "255.255.255.0",
family: "IPv4",
mac: "00:00:00:00:00:00",
internal: false,
cidr: `${address}/24`,
...overrides,
});
describe("loadConfig", () => {
it("uses protocol defaults (access mode local)", () => {
const config = loadConfig({});
expect(config.host).toBe("127.0.0.1");
it("uses protocol defaults and binds every interface", () => {
const config = loadConfig({}, { interfaces: {} });
expect(DEFAULT_HOST).toBe("0.0.0.0");
expect(config.host).toBe("0.0.0.0");
expect(config.port).toBe(7676);
expect(config.access).toBe("local");
expect(config.publicUrl).toBeNull();
expect(config.staticDir).toBe(join(repoRoot, "web", "dist"));
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
@@ -28,14 +40,17 @@ describe("loadConfig", () => {
});
it("honours environment overrides; PI2_ORIGINS is additive", () => {
const config = loadConfig({
const config = loadConfig(
{
PI2_PORT: "0",
PI2_HOST: "0.0.0.0",
PI2_HOST: "127.0.0.1",
PI2_STATIC_DIR: "/srv/pi2/web",
PI2_ORIGINS: "http://a.test, http://b.test ,,",
});
},
{ interfaces: {} },
);
expect(config.port).toBe(0);
expect(config.host).toBe("0.0.0.0");
expect(config.host).toBe("127.0.0.1");
expect(config.staticDir).toBe("/srv/pi2/web");
// Loopback origins stay in place; the extras are appended, normalized,
// and empty entries dropped.
@@ -48,80 +63,54 @@ describe("loadConfig", () => {
expect(() => loadConfig({ PI2_PORT: "70000" })).toThrow(/PI2_PORT/);
});
it("derives loopback origins from the port", () => {
const config = loadConfig({ PI2_PORT: "8080" });
expect(config.corsOrigins).toEqual(LOOPBACK(8080));
});
it("derives local mode origins without a LAN address", () => {
it("allows every local IPv4 origin at the bound port", () => {
const config = loadConfig(
{ PI2_ACCESS_MODE: "local" },
{ detectLanIp: () => "192.168.2.10" },
);
expect(config.access).toBe("local");
expect(config.host).toBe("127.0.0.1");
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
});
it("lan mode binds 0.0.0.0 and adds the detected LAN origin", () => {
const config = loadConfig(
{ PI2_ACCESS_MODE: "lan" },
{ detectLanIp: () => "192.168.2.10" },
);
expect(config.access).toBe("lan");
expect(config.host).toBe("0.0.0.0");
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "http://192.168.2.10:7676"]);
});
it("lan mode skips the extra origin when detection fails or throws", () => {
expect(
loadConfig({ PI2_ACCESS_MODE: "lan" }, { detectLanIp: () => null }).corsOrigins,
).toEqual(LOOPBACK(7676));
expect(
loadConfig(
{ PI2_ACCESS_MODE: "lan" },
{ PI2_PORT: "8080" },
{
detectLanIp: () => {
throw new Error("no interfaces");
interfaces: {
lo: [ipv4("127.0.0.1", { internal: true })],
wlan0: [ipv4("192.168.11.7"), ipv4("169.254.10.1")],
tailscale0: [ipv4("100.64.0.14")],
},
},
).corsOrigins,
).toEqual(LOOPBACK(7676));
);
// Loopback aliases plus each reachable address; link-local is skipped.
for (const origin of [...LOOPBACK(8080), "http://192.168.11.7:8080", "http://100.64.0.14:8080"]) {
expect(config.corsOrigins).toContain(origin);
}
expect(config.corsOrigins).toHaveLength(LOOPBACK(8080).length + 2);
});
it("tailscale mode stays on loopback and adds the public URL origin", () => {
const config = loadConfig({
PI2_ACCESS_MODE: "tailscale",
PI2_PUBLIC_URL: "https://myhost.tail1234.ts.net/",
});
expect(config.access).toBe("tailscale");
it("narrows the bind on PI2_HOST", () => {
const config = loadConfig({ PI2_HOST: "127.0.0.1" }, { interfaces: { wlan0: [ipv4("192.168.11.7")] } });
expect(config.host).toBe("127.0.0.1");
expect(config.publicUrl).toBe("https://myhost.tail1234.ts.net");
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://myhost.tail1234.ts.net"]);
});
it("tailscale without PI2_PUBLIC_URL keeps only loopback origins", () => {
const config = loadConfig({ PI2_ACCESS_MODE: "tailscale" });
expect(config.publicUrl).toBeNull();
// A loopback-only daemon is unreachable from the LAN, so the allowlist
// must not advertise an address nothing is listening on.
expect(config.corsOrigins).toEqual(LOOPBACK(7676));
});
it("lets PI2_HOST win over the mode default", () => {
expect(loadConfig({ PI2_ACCESS_MODE: "lan", PI2_HOST: "127.0.0.1" }).host).toBe("127.0.0.1");
expect(loadConfig({ PI2_ACCESS_MODE: "tailscale", PI2_HOST: "0.0.0.0" }).host).toBe("0.0.0.0");
expect(loadConfig({ PI2_ACCESS_MODE: "local", PI2_HOST: "192.168.2.5" }).host).toBe("192.168.2.5");
it("adds the public URL origin and keeps loopback", () => {
const config = loadConfig({ PI2_PUBLIC_URL: "https://myhost.tail1234.ts.net/" }, { interfaces: {} });
expect(config.publicUrl).toBe("https://myhost.tail1234.ts.net");
expect(config.corsOrigins).toContain("https://myhost.tail1234.ts.net");
for (const origin of LOOPBACK(7676)) expect(config.corsOrigins).toContain(origin);
});
it("normalizes and de-duplicates explicit origins", () => {
const config = loadConfig({
PI2_ORIGINS: "https://a.test/, http://127.0.0.1:7676, ,http://a.test",
});
expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://a.test", "http://a.test"]);
const config = loadConfig(
{ PI2_ORIGINS: "https://a.test/, http://127.0.0.1:7676, ,http://a.test" },
{ interfaces: {} },
);
expect(config.corsOrigins.filter((origin) => origin.endsWith("a.test"))).toEqual([
"https://a.test",
"http://a.test",
]);
expect(config.corsOrigins.filter((origin) => origin === "http://127.0.0.1:7676")).toHaveLength(1);
});
it("fails fast on an unknown access mode", () => {
expect(() => loadConfig({ PI2_ACCESS_MODE: "public" })).toThrow(
"PI2_ACCESS_MODE must be local, lan or tailscale",
);
it("derives only loopback origins for link-local addresses", () => {
expect(
localOrigins({ port: 7676, bindHost: "0.0.0.0", interfaces: { wlan0: [ipv4("169.254.10.1")] } }),
).toEqual(LOOPBACK(7676));
});
});
+7 -10
View File
@@ -16,7 +16,6 @@ interface SessionBody {
id: string;
name: string;
kind: string;
scopes: string[];
createdAt: number;
lastSeenAt: number;
revokedAt: number | null;
@@ -61,7 +60,6 @@ describe("POST /api/v1/console/session", () => {
expect(body.device.name).toBe("local browser");
expect(body.device.kind).toBe("laptop");
expect(body.device.scopes).toEqual(["read", "steer", "control", "admin"]);
expect(body.token.length).toBeGreaterThanOrEqual(40);
expect(body.url).toBe(`http://127.0.0.1:${h.server.port}/#t=${encodeURIComponent(body.token)}`);
expect(body.url).not.toContain("?t=");
@@ -149,7 +147,6 @@ describe("POST /api/v1/console/session", () => {
limits: TEST_LIMITS,
tokenPath: join(dir, "d.sock.token"),
deviceStorePath: join(dir, "devices.json"),
access: "lan",
publicUrl: null,
};
@@ -168,12 +165,12 @@ describe("POST /api/v1/console/session", () => {
});
});
describe("GET /api/v1/info access fields", () => {
it("reports access always and publicUrl as string|null", async () => {
const h = await createHarness({ config: { access: "tailscale", publicUrl: "https://host.ts.net" } });
describe("GET /api/v1/info bind fields", () => {
it("reports the bind host always and publicUrl as string|null", async () => {
const h = await createHarness({ config: { host: "127.0.0.1", publicUrl: "https://host.ts.net" } });
try {
const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record<string, unknown>;
expect(body.access).toBe("tailscale");
expect(body.host).toBe("127.0.0.1");
expect(body.publicUrl).toBe("https://host.ts.net");
// Existing keys survive.
expect(body.v).toBe(1);
@@ -183,11 +180,11 @@ describe("GET /api/v1/info access fields", () => {
}
});
it("keeps the local default", async () => {
const h = await createHarness();
it("reports the default wildcard bind", async () => {
const h = await createHarness({ config: { host: "0.0.0.0" } });
try {
const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record<string, unknown>;
expect(body.access).toBe("local");
expect(body.host).toBe("0.0.0.0");
expect(body.publicUrl).toBeNull();
} finally {
await h.cleanup();
-2
View File
@@ -26,7 +26,6 @@ export function testConfig(overrides: Partial<Config> = {}): Config {
limits: TEST_LIMITS,
tokenPath: "/tmp/pi2-daemon-test.sock.token",
deviceStorePath: "/tmp/pi2-daemon-test-devices.json",
access: "local",
publicUrl: null,
};
return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } };
@@ -80,7 +79,6 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
const auth = new AuthStore({
path: join(dir, "devices.json"),
baseUrl: "http://127.0.0.1:0",
...(options.cliToken === undefined
? {}
: { localTokenPath: join(dir, "cli.token") }),
+85 -13
View File
@@ -317,30 +317,102 @@ describe("HTTP API", () => {
expect(h.auth.verifyToken(token)).toBeNull();
});
it("redeems a pairing code over HTTP", async () => {
const pair = h.auth.pairCreate();
const res = await fetch(`${h.url}/api/v1/pair`, {
/** `POST /api/v1/pair/redeem` — the public half of pairing (ADR 0001 §3). */
async function redeem(code: string, kind = "phone"): Promise<Response> {
return fetch(`${h.url}/api/v1/pair/redeem`, {
method: "POST",
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
body: JSON.stringify({ code, deviceName: "Pixel", kind }),
});
}
it("redeems a pairing code over the public endpoint, once", async () => {
const pair = h.auth.pairCreate();
const res = await redeem(pair.code);
expect(res.status).toBe(200);
const body = (await res.json()) as { token: string; device: { name: string } };
const body = (await res.json()) as { token: string; device: { name: string; scopes?: unknown } };
expect(body.device.name).toBe("Pixel");
expect(body.device.scopes).toBeUndefined();
expect(h.auth.verifyToken(body.token)?.name).toBe("Pixel");
const replay = await fetch(`${h.url}/api/v1/pair`, {
method: "POST",
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
});
expect(replay.status).toBe(401);
expect((await redeem(pair.code)).status).toBe(401);
});
it("creates a pairing code for an authenticated client", async () => {
it("rate limits repeated redeem attempts", async () => {
// The default budget is 5/minute per client; the 6th attempt is refused
// before it can touch the code store.
for (let attempt = 0; attempt < 5; attempt += 1) {
expect((await redeem("ZZZZZZZZ")).status).toBe(401);
}
const limited = await redeem("ZZZZZZZZ");
expect(limited.status).toBe(429);
expect(limited.headers.get("retry-after")).toMatch(/^\d+$/);
const body = (await limited.json()) as { code: string };
expect(body.code).toBe(ERROR_CODES.RATE_LIMITED);
});
it("mints a code, its QR matrix and every usable base for an authenticated client", async () => {
const res = await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }));
expect(res.status).toBe(200);
const body = (await res.json()) as { code: string; url: string; expiresAt: number };
const body = (await res.json()) as {
code: string;
url: string;
expiresAt: number;
nonce: string;
qr: { version: number; ecc: string; size: number; rows: string[] } | null;
bases: { kind: string; name: string; url: string }[];
};
expect(body.code).toMatch(/^[A-Z0-9]{8}$/);
expect(body.url).toContain(body.code);
expect(body.url).toContain(`/pair/${body.code}`);
expect(body.expiresAt).toBeGreaterThan(Date.now());
expect(body.nonce).toMatch(/^[0-9a-f]{32}$/);
expect(body.qr).not.toBeNull();
expect(body.qr!.size).toBe(body.qr!.version * 4 + 17);
expect(body.qr!.rows).toHaveLength(body.qr!.size);
expect(body.qr!.rows.every((row) => row.length === body.qr!.size && /^[01]+$/.test(row))).toBe(true);
expect(body.bases.length).toBeGreaterThan(0);
expect(body.bases.every((base) => typeof base.url === "string" && base.url.startsWith("http"))).toBe(true);
// The chosen URL is always one of the offered bases.
expect(body.bases.some((base) => body.url.startsWith(base.url))).toBe(true);
});
it("accepts a base it offered and rejects a foreign one", async () => {
const first = (await (await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }))).json()) as {
bases: { url: string }[];
};
const chosen = first.bases.at(-1)!.url;
const ok = await fetch(
`${h.url}/api/v1/pair`,
authed({ method: "POST", body: JSON.stringify({ base: chosen }) }),
);
expect(ok.status).toBe(200);
const minted = (await ok.json()) as { url: string };
expect(minted.url.startsWith(chosen)).toBe(true);
const foreign = await fetch(
`${h.url}/api/v1/pair`,
authed({ method: "POST", body: JSON.stringify({ base: "http://evil.example:9999" }) }),
);
expect(foreign.status).toBe(400);
});
it("requires a token to mint a code", async () => {
const res = await fetch(`${h.url}/api/v1/pair`, { method: "POST", body: "{}" });
expect(res.status).toBe(401);
});
it("redirects a scanned /pair/<code> link to the zero-input connect page", async () => {
const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" });
expect(res.status).toBe(302);
const location = res.headers.get("location") ?? "";
expect(location).toContain("/connect?");
expect(location).toContain("code=ABCD2345");
expect(location).toContain("auto=1");
// A malformed code still lands on the console, just without a code.
const malformed = await fetch(`${h.url}/pair/nope!`, { redirect: "manual" });
expect(malformed.status).toBe(302);
expect(malformed.headers.get("location")).not.toContain("code=");
expect(malformed.headers.get("location")).toContain("auto=1");
});
});
+65
View File
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import { PairRateLimiter } from "../../src/daemon/rate-limit.js";
/** A limiter whose clock the test drives, so windows slide without sleeping. */
function limiter(rules = { perClient: { limit: 3, windowMs: 1_000 }, global: { limit: 10, windowMs: 10_000 } }) {
let now = 1_000;
const instance = new PairRateLimiter(rules, { now: () => now });
return { instance, advance: (ms: number) => (now += ms) };
}
describe("PairRateLimiter", () => {
it("allows the budget and refuses the next attempt", () => {
const { instance } = limiter();
expect(instance.check("1.2.3.4").allowed).toBe(true);
expect(instance.check("1.2.3.4").allowed).toBe(true);
expect(instance.check("1.2.3.4").allowed).toBe(true);
const blocked = instance.check("1.2.3.4");
expect(blocked.allowed).toBe(false);
expect(blocked.retryAfterMs).toBeGreaterThan(0);
expect(blocked.retryAfterMs).toBeLessThanOrEqual(1_000);
});
it("recovers once the window slides", () => {
const { instance, advance } = limiter();
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
expect(instance.check("1.2.3.4").allowed).toBe(false);
advance(1_001);
expect(instance.check("1.2.3.4").allowed).toBe(true);
});
it("keeps per-client budgets separate", () => {
const { instance } = limiter();
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
expect(instance.check("1.2.3.4").allowed).toBe(false);
expect(instance.check("5.6.7.8").allowed).toBe(true);
});
it("applies the global budget across clients", () => {
const { instance } = limiter({ perClient: { limit: 5, windowMs: 1_000 }, global: { limit: 3, windowMs: 10_000 } });
expect(instance.check("a").allowed).toBe(true);
expect(instance.check("b").allowed).toBe(true);
expect(instance.check("c").allowed).toBe(true);
// A brand-new client is still refused: the global window is full.
const blocked = instance.check("d");
expect(blocked.allowed).toBe(false);
expect(blocked.retryAfterMs).toBeLessThanOrEqual(10_000);
});
it("forgets every window on reset", () => {
const { instance } = limiter();
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
expect(instance.check("1.2.3.4").allowed).toBe(false);
instance.reset();
expect(instance.check("1.2.3.4").allowed).toBe(true);
});
it("treats an empty client key as one bucket", () => {
const { instance } = limiter();
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("");
expect(instance.check("unknown").allowed).toBe(false);
});
});