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
+2157 -488

No files matched your search

+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 });
}
});
});