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

+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();
+63 -74
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({
PI2_PORT: "0",
PI2_HOST: "0.0.0.0",
PI2_STATIC_DIR: "/srv/pi2/web",
PI2_ORIGINS: "http://a.test, http://b.test ,,",
});
const config = loadConfig(
{
PI2_PORT: "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" },
{
detectLanIp: () => {
throw new Error("no interfaces");
},
{ PI2_PORT: "8080" },
{
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);
});
});