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

+6 -32
View File
@@ -6,7 +6,7 @@
*
* A second, non-persisted credential exists for local tooling: the CLI token in
* `<runtime>/cli.token` (written by `pi2 daemon`). It authenticates as the synthetic
* `local-cli` device with every scope; see `docs/deployment.md` §7.
* `local-cli` device; see `docs/deployment.md` §7.
*/
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
@@ -16,17 +16,13 @@ import { ERROR_CODES } from "../protocol/errors.js";
import { DaemonError } from "./errors.js";
export type DeviceKind = "phone" | "laptop" | "tablet";
export type Scope = "read" | "steer" | "control" | "admin";
export const DEVICE_KINDS: readonly DeviceKind[] = ["phone", "laptop", "tablet"];
export const SCOPES: readonly Scope[] = ["read", "steer", "control", "admin"];
export const DEFAULT_SCOPES: readonly Scope[] = ["read", "steer", "control"];
export interface DeviceRecord {
id: string;
name: string;
kind: DeviceKind;
scopes: Scope[];
tokenHash: string;
createdAt: number;
lastSeenAt: number;
@@ -38,12 +34,11 @@ export type DevicePublic = Omit<DeviceRecord, "tokenHash">;
export interface CreateDeviceInput {
name: string;
kind: DeviceKind;
scopes?: Scope[];
}
/** Minted code; the URL is built by the HTTP layer from `core/network`. */
export interface PairCode {
code: string;
url: string;
expiresAt: number;
nonce: string;
}
@@ -63,13 +58,12 @@ export interface AuthStoreOptions {
/** Defaults to `<dataDir>/devices.json`. */
path?: string;
now?: () => number;
baseUrl?: string;
/** `touchDevice` write throttle. */
touchIntervalMs?: number;
/**
* File holding the local CLI token (`<runtime>/cli.token`, written by `pi2 daemon`).
* A bearer token equal to its trimmed contents authenticates as the synthetic
* `local-cli` device with every scope. Checked after the persisted devices.
* `local-cli` device. Checked after the persisted devices.
*/
localTokenPath?: string;
/**
@@ -136,13 +130,9 @@ function isDeviceKind(value: unknown): value is DeviceKind {
return typeof value === "string" && (DEVICE_KINDS as readonly string[]).includes(value);
}
function isScope(value: unknown): value is Scope {
return typeof value === "string" && (SCOPES as readonly string[]).includes(value);
}
function publicDevice(record: DeviceRecord): DevicePublic {
const { tokenHash: _tokenHash, ...rest } = record;
return { ...rest, scopes: [...rest.scopes] };
return { ...rest };
}
function pairCode(): string {
@@ -158,7 +148,6 @@ export class AuthStore {
readonly localTokenPath: string | undefined;
readonly localBrowserTokenPath: string;
private readonly now: () => number;
private readonly baseUrl: string;
private readonly touchIntervalMs: number;
private readonly devices: DeviceRecord[] = [];
private readonly pairs = new Map<string, PairEntry>();
@@ -166,7 +155,6 @@ export class AuthStore {
constructor(options: AuthStoreOptions = {}) {
this.path = options.path ?? `${dataDir()}/devices.json`;
this.now = options.now ?? Date.now;
this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:7676").replace(/\/+$/, "");
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
this.localTokenPath =
options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath;
@@ -180,16 +168,12 @@ export class AuthStore {
}
if (!isDeviceKind(input.kind)) throw DaemonError.badRequest(`unknown device kind "${String(input.kind)}"`);
const scopes = input.scopes === undefined ? [...DEFAULT_SCOPES] : input.scopes.filter(isScope);
if (scopes.length === 0) scopes.push("read");
const token = randomBytes(32).toString("base64url");
const timestamp = this.now();
const record: DeviceRecord = {
id: `dev-${randomBytes(6).toString("hex")}`,
name: input.name.trim(),
kind: input.kind,
scopes,
tokenHash: hashToken(token),
createdAt: timestamp,
lastSeenAt: timestamp,
@@ -245,12 +229,7 @@ export class AuthStore {
const code = pairCode();
const nonce = randomBytes(16).toString("hex");
this.pairs.set(code, { code, nonce, expiresAt: timestamp + ttlSec * 1000, used: false });
return {
code,
url: `${this.baseUrl}/pair/${code}`,
expiresAt: timestamp + ttlSec * 1000,
nonce,
};
return { code, expiresAt: timestamp + ttlSec * 1000, nonce };
}
pairRedeem(input: RedeemPairInput): RedeemPairResult {
@@ -316,19 +295,16 @@ export class AuthStore {
const created = this.createDevice({
name: LOCAL_BROWSER_NAME,
kind: LOCAL_BROWSER_KIND,
scopes: [...SCOPES],
});
const record = this.devices.find((device) => device.id === created.device.id);
if (record === undefined) return created;
record.tokenHash = hash;
record.scopes = [...SCOPES];
this.persist();
this.writeLocalBrowserToken(token);
return { token, device: publicDevice(record) };
}
existing.tokenHash = hash;
existing.scopes = [...SCOPES];
existing.revokedAt = null;
this.persist();
this.writeLocalBrowserToken(token);
@@ -364,14 +340,13 @@ export class AuthStore {
}
}
/** The local CLI token grants every scope; it is not persisted or revocable. */
/** The local CLI token is the daemon's own admin credential; not persisted, not revocable. */
private localCliDevice(): DevicePublic {
const timestamp = this.now();
return {
id: LOCAL_CLI_DEVICE_ID,
name: "local CLI",
kind: "laptop",
scopes: [...SCOPES],
createdAt: 0,
lastSeenAt: timestamp,
revokedAt: null,
@@ -428,7 +403,6 @@ export class AuthStore {
id: candidate.id,
name: candidate.name,
kind: candidate.kind,
scopes: Array.isArray(candidate.scopes) ? candidate.scopes.filter(isScope) : ["read"],
tokenHash: candidate.tokenHash,
createdAt: candidate.createdAt,
lastSeenAt: typeof candidate.lastSeenAt === "number" ? candidate.lastSeenAt : candidate.createdAt,
+94 -14
View File
@@ -8,9 +8,12 @@ import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/inter
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import { networkBases } from "../core/network.js";
import { encodeQr, fitsQr } from "../core/qr.js";
import type { AuthStore, DevicePublic } from "./auth.js";
import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js";
import { DaemonError, toErrorPayload } from "./errors.js";
import { PairRateLimiter } from "./rate-limit.js";
import { CommandRouter } from "./router.js";
import { createSseHandler } from "./sse.js";
import { serveStatic } from "./static.js";
@@ -36,6 +39,8 @@ export interface AppDeps {
startedAt?: number;
now?: () => number;
metrics?: () => DaemonMetrics;
/** Redeem budget; injectable so tests can advance the clock. */
pairLimiter?: PairRateLimiter;
}
function bearer(c: Context<Env>): string | undefined {
@@ -50,6 +55,16 @@ function isLoopback(c: Context<Env>): boolean {
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
}
/** Rate-limit key for the public redeem endpoint. */
function clientAddress(c: Context<Env>): string {
return c.env?.incoming?.socket?.remoteAddress ?? "unknown";
}
/** `http://host:port` without a trailing slash, for `base` validation. */
function normalizeBase(raw: string): string {
return raw.trim().replace(/\/+$/, "");
}
/** Daemon package version; falls back to the v1 baseline when package.json is unavailable. */
function daemonVersion(): string {
try {
@@ -138,6 +153,7 @@ export function createApp(deps: AppDeps): Hono<Env> {
const startedAt = deps.startedAt ?? now();
const app = new Hono<Env>();
const router = new CommandRouter({ auth, instances, workspaces, logger, now, daemonId: deps.daemonId });
const pairLimiter = deps.pairLimiter ?? new PairRateLimiter(undefined, { now });
// Origin check + CORS. Applies to every surface, including SSE.
app.use("*", async (c, next) => {
@@ -163,8 +179,9 @@ export function createApp(deps: AppDeps): Hono<Env> {
if (path === "/api/v1/info" || path === "/api/v1/health") {
if (isLoopback(c)) return next();
}
// Pairing redeem is public; pair.create enforces auth in its handler.
if (path === "/api/v1/pair") return next();
// Redeeming a code is public by design (the code is the capability) and
// rate limited below; minting one requires a device token.
if (path === "/api/v1/pair/redeem") return next();
const token = bearer(c);
const device = token ? auth.verifyToken(token) : null;
if (!device) {
@@ -188,7 +205,7 @@ export function createApp(deps: AppDeps): Hono<Env> {
port: config.port,
capabilities: ["ws", "sse", "devices", "attention"],
limits: config.limits,
access: config.access,
host: config.host,
publicUrl: config.publicUrl,
}),
);
@@ -331,21 +348,84 @@ export function createApp(deps: AppDeps): Hono<Env> {
return json(result.status, result.body);
});
/**
* Mint a pairing code. Authenticated (a device token or the local CLI token);
* the response carries everything a renderer needs — the chosen URL, the QR
* matrix and every base a client may ask for next time (`base`).
*/
app.post("/api/v1/pair", async (c) => {
const body = await readJsonBody(c, config.limits.maxBodyBytes);
if (typeof body.code === "string") {
if (typeof body.kind !== "string") throw DaemonError.badRequest("kind is required");
const redeemed = auth.pairRedeem({
code: body.code,
deviceName: typeof body.deviceName === "string" ? body.deviceName : "",
kind: body.kind as "phone" | "laptop" | "tablet",
});
return c.json({ token: redeemed.token, device: redeemed.device });
}
publicDeviceOrThrow(c, auth);
const body = await readJsonBody(c, config.limits.maxBodyBytes);
const ttlSec = typeof body.ttlSec === "number" ? body.ttlSec : undefined;
const pair = auth.pairCreate(ttlSec === undefined ? {} : { ttlSec });
return c.json({ accepted: true, ...pair });
const bases = networkBases({
port: config.port,
bindHost: config.host,
publicUrl: config.publicUrl,
});
const requested = typeof body.base === "string" ? normalizeBase(body.base) : null;
let base = bases[0]?.url ?? `http://127.0.0.1:${config.port}`;
if (requested !== null && requested !== "") {
const match = bases.find((candidate) => normalizeBase(candidate.url) === requested);
if (!match) {
throw DaemonError.badRequest(
`base must be one of: ${bases.map((candidate) => candidate.url).join(", ")}`,
);
}
base = match.url;
}
const url = `${normalizeBase(base)}/pair/${pair.code}`;
const qr = fitsQr(url) ? encodeQr(url) : null;
return c.json({
accepted: true,
code: pair.code,
url,
expiresAt: pair.expiresAt,
nonce: pair.nonce,
qr,
bases,
});
});
/**
* Redeem a code with no credentials — the code *is* the capability. Rate
* limited per client and globally so guessing is not worth the bandwidth.
*/
app.post("/api/v1/pair/redeem", async (c) => {
const decision = pairLimiter.check(clientAddress(c));
if (!decision.allowed) {
const retryAfter = Math.max(1, Math.ceil(decision.retryAfterMs / 1000));
return json(
429,
errorBody(ERROR_CODES.RATE_LIMITED, "too many pairing attempts, try again later"),
{ "retry-after": String(retryAfter) },
);
}
const body = await readJsonBody(c, config.limits.maxBodyBytes);
if (typeof body.kind !== "string") throw DaemonError.badRequest("kind is required");
const redeemed = auth.pairRedeem({
code: typeof body.code === "string" ? body.code : "",
deviceName: typeof body.deviceName === "string" ? body.deviceName : "",
kind: body.kind as "phone" | "laptop" | "tablet",
});
return c.json({ token: redeemed.token, device: redeemed.device });
});
/**
* The scanned link. A redirect rather than an API call: the phone's browser
* lands on the console with the code already in the query string, and the
* SPA's zero-input branch redeems it without a form.
*/
app.get("/pair/:code", (c) => {
const raw = (c.req.param("code") ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
const query = new URLSearchParams();
if (/^[A-Z0-9]{8}$/.test(raw)) query.set("code", raw);
const next = c.req.query("next");
if (next !== undefined && next !== "") query.set("next", next);
query.set("auto", "1");
return c.redirect(`/connect?${query.toString()}`, 302);
});
app.get("/events", createSseHandler({ auth, bus, corsOrigins: config.corsOrigins, logger }));
+86
View File
@@ -0,0 +1,86 @@
/**
* Sliding-window rate limiting for the public pairing endpoint.
*
* A pairing code is short enough to type and long enough that guessing it is
* hopeless *only* if the guesser cannot try millions of them. Redeem is
* unauthenticated by design (the code is the capability), so the endpoint that
* accepts it needs its own budget: a per-client window for a single noisy
* device, and a global window so a botnet cannot spread the attempts.
*
* `now` is injectable, which is how the tests advance time without sleeping.
*/
export interface RateLimitRule {
/** Attempts allowed inside the window. */
limit: number;
windowMs: number;
}
export interface RateLimitDecision {
allowed: boolean;
/** Only meaningful when `allowed` is false. */
retryAfterMs: number;
}
export interface PairRateLimitRules {
perClient: RateLimitRule;
global: RateLimitRule;
}
/** 5 attempts a minute from one address, 50 an hour overall. */
export const DEFAULT_PAIR_RATE_LIMITS: PairRateLimitRules = {
perClient: { limit: 5, windowMs: 60_000 },
global: { limit: 50, windowMs: 60 * 60_000 },
};
/** Drops entries older than the window so a long-lived daemon does not grow. */
function prune(timestamps: number[], now: number, windowMs: number): number[] {
const cutoff = now - windowMs;
let index = 0;
while (index < timestamps.length && (timestamps[index] ?? 0) <= cutoff) index += 1;
return index === 0 ? timestamps : timestamps.slice(index);
}
export class PairRateLimiter {
private readonly rules: PairRateLimitRules;
private readonly now: () => number;
private readonly clients = new Map<string, number[]>();
private global: number[] = [];
constructor(rules: PairRateLimitRules = DEFAULT_PAIR_RATE_LIMITS, options: { now?: () => number } = {}) {
this.rules = rules;
this.now = options.now ?? Date.now;
}
/**
* Count one attempt. Rejected attempts do not consume budget beyond the
* rejection itself, so a locked-out client recovers as soon as the window
* slides rather than being pushed further out on every retry.
*/
check(clientKey: string): RateLimitDecision {
const now = this.now();
this.global = prune(this.global, now, this.rules.global.windowMs);
const key = clientKey === "" ? "unknown" : clientKey;
const perClient = prune(this.clients.get(key) ?? [], now, this.rules.perClient.windowMs);
const globalFull = this.global.length >= this.rules.global.limit;
const clientFull = perClient.length >= this.rules.perClient.limit;
if (globalFull || clientFull) {
this.clients.set(key, perClient);
const window = globalFull ? this.rules.global : this.rules.perClient;
const oldest = (globalFull ? this.global : perClient)[0] ?? now;
return { allowed: false, retryAfterMs: Math.max(0, oldest + window.windowMs - now) };
}
perClient.push(now);
this.global.push(now);
this.clients.set(key, perClient);
return { allowed: true, retryAfterMs: 0 };
}
/** Test/ops hook: forget every window. */
reset(): void {
this.clients.clear();
this.global = [];
}
}
-1
View File
@@ -203,7 +203,6 @@ export function attachWsServer(options: WsServerOptions): WsServerHandle {
id: state.device.id,
name: state.device.name,
kind: state.device.kind,
scopes: state.device.scopes,
},
});
};