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

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