Files
pi2d/test/cli/auth-local-token.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

100 lines
4.3 KiB
TypeScript

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 } from "../../src/daemon/auth.js";
import { writeCliToken } from "../../src/cli/token.js";
import { removeDir, tempDir } from "./helpers.js";
describe("AuthStore local CLI token", () => {
let dir: string;
let tokenPath: string;
let storePath: string;
beforeEach(() => {
dir = tempDir("pi2-local-token-");
tokenPath = join(dir, "cli.token");
storePath = join(dir, "devices.json");
});
afterEach(() => removeDir(dir));
it("accepts the token file contents as the synthetic admin device", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
const device = auth.verifyToken(token);
expect(device).not.toBeNull();
expect(device!.id).toBe(LOCAL_CLI_DEVICE_ID);
expect(device!.id).toBe("local-cli");
expect(device!.name).toBe("local CLI");
expect(device!.revokedAt).toBeNull();
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
});
it("tolerates a trailing newline in the token file", () => {
const token = writeCliToken(tokenPath);
writeFileSync(tokenPath, `${token}\n\n`, { mode: 0o600 });
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
it("rejects wrong, truncated, empty and missing tokens", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken("")).toBeNull();
expect(auth.verifyToken("not-a-token")).toBeNull();
expect(auth.verifyToken(token.slice(0, -1))).toBeNull();
expect(auth.verifyToken(token.slice(0, -1) + (token.endsWith("a") ? "b" : "a"))).toBeNull();
writeFileSync(tokenPath, "\n", { mode: 0o600 });
expect(auth.verifyToken("")).toBeNull();
expect(auth.verifyToken(token)).toBeNull();
rmSync(tokenPath, { force: true });
expect(auth.verifyToken(token)).toBeNull();
});
it("rotates: a rewritten token file invalidates the previous one", () => {
const first = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(auth.verifyToken(first)?.id).toBe(LOCAL_CLI_DEVICE_ID);
const second = writeCliToken(tokenPath);
expect(second).not.toBe(first);
expect(auth.verifyToken(first)).toBeNull();
expect(auth.verifyToken(second)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
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" });
expect(auth.verifyToken(token)?.name).toBe("Pixel");
expect(auth.listDevices().map((device) => device.id)).not.toContain(LOCAL_CLI_DEVICE_ID);
expect(auth.listDevices()).toHaveLength(1);
// The synthetic device is not revocable; a paired device is.
expect(auth.revokeDevice(LOCAL_CLI_DEVICE_ID)).toBe(false);
expect(auth.revokeDevice(auth.listDevices()[0]!.id)).toBe(true);
expect(auth.verifyToken(token)).toBeNull();
});
it("is inert without localTokenPath (existing API unchanged)", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath });
expect(auth.localTokenPath).toBeUndefined();
expect(auth.verifyToken(token)).toBeNull();
});
it("does not persist anything to the device store", () => {
const token = writeCliToken(tokenPath);
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
auth.verifyToken(token);
const reloaded = new AuthStore({ path: storePath, localTokenPath: tokenPath });
expect(reloaded.listDevices()).toHaveLength(0);
expect(reloaded.verifyToken(token)?.id).toBe(LOCAL_CLI_DEVICE_ID);
});
});