Files
pi2d/test/cli/lock.test.ts
T
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

236 lines
8.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
acquireLock,
assessLock,
LockError,
readDaemonJson,
readLockFile,
writeDaemonJson,
type DaemonLock,
} from "../../src/cli/lock.js";
import { PROTOCOL_VERSION } from "../../src/protocol/types.js";
import { removeDir, tempDir } from "./helpers.js";
const BOOT = "boot-abc";
function payload(overrides: Partial<DaemonLock> = {}): Omit<DaemonLock, "pid" | "bootId"> & { pid?: number; bootId?: string } {
return {
port: 7676,
daemonId: "d-test",
startedAt: 1_700_000_000_000,
protocolVersion: PROTOCOL_VERSION,
...overrides,
};
}
describe("daemon lock", () => {
let dir: string;
let lockPath: string;
beforeEach(() => {
dir = tempDir("pi2-lock-");
mkdirSync(dir, { recursive: true });
lockPath = join(dir, "daemon.lock");
});
afterEach(() => removeDir(dir));
it("creates the lock with the payload and mode 0600", () => {
const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(handle.lock).toEqual({
pid: process.pid,
bootId: BOOT,
port: 7676,
daemonId: "d-test",
startedAt: 1_700_000_000_000,
protocolVersion: PROTOCOL_VERSION,
});
expect(readLockFile(lockPath)).toEqual(handle.lock);
expect(statSync(lockPath).mode & 0o777).toBe(0o600);
expect(readFileSync(lockPath, "utf8").endsWith("\n")).toBe(true);
handle.release();
expect(existsSync(lockPath)).toBe(false);
});
it("refuses a second daemon while the holder is alive", () => {
const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(() => acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT })).toThrow(
LockError,
);
try {
acquireLock({ lockPath, payload: payload({ daemonId: "d-two" }), bootId: () => BOOT });
} catch (error) {
const lockError = error as LockError;
expect(lockError.code).toBe("E_LOCKED");
expect(lockError.holder?.daemonId).toBe("d-test");
expect(lockError.holder?.pid).toBe(process.pid);
expect(lockError.message).toContain("--force");
}
// The original lock survived the failed attempt.
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
first.release();
});
it("overrides a live lock with --force", () => {
const first = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
const forced = acquireLock({ lockPath, payload: payload({ daemonId: "d-forced" }), bootId: () => BOOT, force: true });
expect(forced.lock.daemonId).toBe("d-forced");
expect(readLockFile(lockPath)?.daemonId).toBe("d-forced");
// The displaced daemon must not delete the new lock on shutdown.
first.release();
expect(readLockFile(lockPath)?.daemonId).toBe("d-forced");
forced.release();
expect(existsSync(lockPath)).toBe(false);
});
it("treats a dead pid as stale", () => {
acquireLock({ lockPath, payload: payload({ daemonId: "d-dead" }), bootId: () => BOOT });
const handle = acquireLock({
lockPath,
payload: payload({ daemonId: "d-new" }),
bootId: () => BOOT,
isPidAlive: () => false,
});
expect(handle.lock.daemonId).toBe("d-new");
handle.release();
});
it("treats a pid from a previous boot as stale (pid reuse)", () => {
acquireLock({ lockPath, payload: payload({ daemonId: "d-old" }), bootId: () => "boot-old" });
const handle = acquireLock({
lockPath,
payload: payload({ daemonId: "d-new" }),
bootId: () => BOOT,
isPidAlive: () => true,
});
expect(handle.lock.daemonId).toBe("d-new");
expect(handle.lock.bootId).toBe(BOOT);
handle.release();
});
it("ignores a malformed lock file (crash during write)", () => {
writeFileSync(lockPath, "{not json");
const handle = acquireLock({ lockPath, payload: payload(), bootId: () => BOOT });
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
handle.release();
});
it("update() rewrites the payload in place", () => {
const handle = acquireLock({ lockPath, payload: payload({ port: 0 }), bootId: () => BOOT });
handle.update({ port: 7712 });
expect(handle.lock.port).toBe(7712);
expect(readLockFile(lockPath)?.port).toBe(7712);
expect(readLockFile(lockPath)?.daemonId).toBe("d-test");
handle.release();
});
it("assessLock explains why a lock is stale", () => {
const lock: DaemonLock = {
pid: 42,
bootId: BOOT,
port: 7676,
daemonId: "d-1",
startedAt: 1,
protocolVersion: PROTOCOL_VERSION,
};
expect(assessLock(lock, { isPidAlive: () => true, bootId: () => BOOT })).toEqual({ live: true, reason: "alive" });
expect(assessLock(lock, { isPidAlive: () => false, bootId: () => BOOT })).toEqual({
live: false,
reason: "no-pid",
});
expect(assessLock(lock, { isPidAlive: () => true, bootId: () => "other" })).toEqual({
live: false,
reason: "boot-changed",
});
});
});
describe("daemon.json", () => {
let dir: string;
let lockPath: string;
let daemonJsonPath: string;
beforeEach(() => {
dir = tempDir("pi2-daemonjson-");
lockPath = join(dir, "daemon.lock");
daemonJsonPath = join(dir, "daemon.json");
});
afterEach(() => removeDir(dir));
it("publishes the same payload as the lock, mode 0600", () => {
const handle = acquireLock({
lockPath,
payload: { port: 7713, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION },
bootId: () => BOOT,
});
writeDaemonJson(handle.lock, daemonJsonPath);
const discovered = readDaemonJson(daemonJsonPath);
expect(discovered).toEqual({
pid: process.pid,
bootId: BOOT,
port: 7713,
daemonId: "d-json",
startedAt: 5,
protocolVersion: PROTOCOL_VERSION,
});
expect(statSync(daemonJsonPath).mode & 0o777).toBe(0o600);
handle.release();
});
it("carries the optional host/publicUrl fields and stays readable without them", () => {
const handle = acquireLock({
lockPath,
payload: {
port: 7676,
daemonId: "d-bind",
startedAt: 5,
protocolVersion: PROTOCOL_VERSION,
host: "0.0.0.0",
publicUrl: "https://host.ts.net",
},
bootId: () => BOOT,
});
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)?.host).toBeUndefined();
expect(readLockFile(lockPath)?.publicUrl).toBeUndefined();
});
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();
});
it("is removed by release() and missing files read as undefined", () => {
const handle = acquireLock({
lockPath,
payload: { port: 7676, daemonId: "d-json", startedAt: 5, protocolVersion: PROTOCOL_VERSION },
bootId: () => BOOT,
});
writeDaemonJson(handle.lock, daemonJsonPath);
handle.release();
expect(existsSync(daemonJsonPath)).toBe(false);
expect(readDaemonJson(daemonJsonPath)).toBeUndefined();
// A discovery file owned by another daemon is left alone.
writeDaemonJson({ ...handle.lock, daemonId: "d-other" }, daemonJsonPath);
expect(readDaemonJson(daemonJsonPath)?.daemonId).toBe("d-other");
});
});