Files
pi2d/test/cli/wiring.test.ts
yuez a57c874095 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.
2026-10-27 10:44:08 +08:00

103 lines
4.4 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { writeCliToken } from "../../src/cli/token.js";
import { wireDaemon, type WiredDaemon } from "../../src/cli/wiring.js";
import { clearRuntimeEnv, removeDir, setRuntimeEnv, silentLogger, tempDir } from "./helpers.js";
describe("wireDaemon", () => {
let dir: string;
let wired: WiredDaemon | undefined;
beforeEach(() => {
dir = tempDir();
setRuntimeEnv(dir);
mkdirSync(join(dir, "web"), { recursive: true });
writeFileSync(join(dir, "web", "index.html"), "<!doctype html><title>pi2</title><div id=app></div>");
mkdirSync(join(dir, "sessions"), { recursive: true });
});
afterEach(async () => {
if (wired !== undefined) await wired.close();
wired = undefined;
clearRuntimeEnv();
removeDir(dir);
});
it("boots on port 0 with temp dirs and serves info, health and the static UI", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const token = writeCliToken(wired.cliTokenPath);
const server = await wired.start();
expect(server.port).toBeGreaterThan(0);
expect(wired.config.port).toBe(server.port);
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);
expect(wired.deps.auth).toBe(wired.auth);
const info = await fetch(`${server.url}/api/v1/info`);
expect(info.status).toBe(200);
const infoBody = (await info.json()) as { v: number; daemonId: string; capabilities: string[] };
expect(infoBody.v).toBe(PROTOCOL_VERSION);
expect(infoBody.daemonId).toBe(wired.deps.daemonId);
expect(infoBody.capabilities).toContain("ws");
const health = await fetch(`${server.url}/api/v1/health`);
expect(health.status).toBe(200);
const healthBody = (await health.json()) as { ok: boolean; items: { name: string; ok: boolean }[] };
expect(healthBody.ok).toBe(true);
expect(healthBody.items.find((item) => item.name === "static")?.ok).toBe(true);
const page = await fetch(`${server.url}/`);
expect(page.status).toBe(200);
expect(page.headers.get("content-type")).toContain("text/html");
expect(await page.text()).toContain("<div id=app>");
// The minted CLI token authenticates as the local admin device.
const authorized = await fetch(`${server.url}/api/v1/workspaces`, {
headers: { authorization: `Bearer ${token}` },
});
expect(authorized.status).toBe(200);
expect(Array.isArray(await authorized.json())).toBe(true);
const anonymous = await fetch(`${server.url}/api/v1/workspaces`);
expect(anonymous.status).toBe(401);
});
it("starts the plugin unix socket in the configured runtime dir", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const { existsSync } = await import("node:fs");
expect(existsSync(join(dir, "run", "d.sock"))).toBe(true);
expect(existsSync(join(dir, "run", "d.sock.token"))).toBe(true);
await wired.close();
wired = undefined;
expect(existsSync(join(dir, "run", "d.sock"))).toBe(false);
});
it("resolves workspace cwd through the store and rejects unknown workspaces", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
await expect(wired.instanceManager.ensure("ws-missing", { timeoutMs: 100 })).rejects.toMatchObject({
code: "E_NOT_FOUND",
});
});
it("is idempotent on start()", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
const first = await wired.start();
const second = await wired.start();
expect(second).toBe(first);
});
it("close() is idempotent", async () => {
wired = await wireDaemon({ logger: silentLogger, discoveryRoot: join(dir, "sessions") });
await wired.start();
await wired.close();
await wired.close();
wired = undefined;
});
});