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

+2 -2
View File
@@ -45,7 +45,7 @@ Options:
Environment:
PI2_PORT, PI2_HOST, PI2_STATIC_DIR, PI2_ORIGINS, PI2_RUNTIME_DIR,
PI2_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS,
PI2_ACCESS_MODE (local|lan|tailscale), PI2_PUBLIC_URL
PI2_PUBLIC_URL
Runtime files ($PI2_RUNTIME_DIR):
d.sock plugin unix socket (nvim → daemon)
@@ -181,7 +181,7 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
daemonId,
startedAt: Date.now(),
protocolVersion: PROTOCOL_VERSION,
access: config.access,
host: config.host,
publicUrl: config.publicUrl,
},
});
+22 -26
View File
@@ -11,7 +11,8 @@ import { homedir, platform as osPlatform } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { DEFAULT_PORT, loadConfig, type AccessMode } from "../config.js";
import { DEFAULT_HOST, DEFAULT_PORT, describeHost, loadConfig } from "../config.js";
import { isLoopbackHost } from "../core/network.js";
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { formatTable } from "./util.js";
@@ -43,8 +44,7 @@ export interface BinaryProbe {
error?: string;
}
export interface AccessModeContext {
mode: AccessMode;
export interface BindContext {
host: string;
port: number;
publicUrl: string | null;
@@ -62,7 +62,7 @@ export interface DoctorContext {
socket: { path: string; exists: boolean };
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
port: { configured: number; bound: boolean };
access: AccessModeContext;
bind: BindContext;
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
linger: { checked: boolean; enabled?: boolean; detail?: string };
webDist: { path: string; exists: boolean };
@@ -217,27 +217,24 @@ export function checkPort(probe: DoctorContext["port"]): DoctorCheck {
return { name: "port", status: "ok", detail: `${probe.configured} free` };
}
function isLoopbackHost(host: string): boolean {
return host === "127.0.0.1" || host === "::1" || host === "localhost";
}
/**
* `access`: local is fine; lan/tailscale warn because the daemon has no TLS of
* its own, and fail when a non-loopback bind is exposed without a public URL.
* `bind`: where the daemon listens. Loopback is private; anything else is
* reachable from the LAN, which is the point of the console — so a non-loopback
* bind only *warns*. Access is gated by pairing codes and per-device tokens,
* and an `https:` public URL (e.g. behind `tailscale serve`) covers TLS.
*/
export function checkAccess(probe: AccessModeContext): DoctorCheck {
if (probe.mode === "local") return { name: "access", status: "ok", detail: "local (loopback only)" };
const publicSuffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
const detail = `${probe.mode} (bind ${probe.host}/${probe.port}${publicSuffix})`;
if (probe.publicUrl === null && !isLoopbackHost(probe.host)) {
return { name: "access", status: "fail", detail };
export function checkBind(probe: BindContext): DoctorCheck {
const suffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
if (isLoopbackHost(probe.host)) {
return { name: "bind", status: "ok", detail: `${probe.host}/${probe.port} (loopback only)${suffix}` };
}
const detail = `${describeHost(probe.host)}/${probe.port}${suffix}`;
const tls = probe.publicUrl !== null && probe.publicUrl.startsWith("https:");
if (tls) return { name: "bind", status: "ok", detail };
return {
name: "access",
name: "bind",
status: "warn",
detail: tls ? detail : `${detail} — no TLS, prefer \`tailscale serve\``,
detail: `${detail} — no TLS; pairing codes gate access, set PI2_HOST=127.0.0.1 to restrict`,
};
}
@@ -286,7 +283,7 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
{ name: "port", run: () => checkPort(ctx.port) },
{ name: "access", run: () => checkAccess(ctx.access) },
{ name: "bind", run: () => checkBind(ctx.bind) },
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
@@ -370,15 +367,14 @@ function statOrUndefined(path: string): { exists: boolean; mode: number | undefi
}
}
/** Best-effort access context; an unparsable environment reports `local`. */
function accessContext(env: NodeJS.ProcessEnv, port: number): AccessModeContext {
/** Best-effort bind context; an unparsable environment reports the default bind. */
function bindContext(env: NodeJS.ProcessEnv, port: number): BindContext {
try {
const config = loadConfig(env);
return { mode: config.access, host: config.host, port, publicUrl: config.publicUrl };
return { host: config.host, port, publicUrl: config.publicUrl };
} catch {
return {
mode: "local",
host: env.PI2_HOST?.trim() || "127.0.0.1",
host: env.PI2_HOST?.trim() || DEFAULT_HOST,
port,
publicUrl: env.PI2_PUBLIC_URL?.trim().replace(/\/+$/, "") || null,
};
@@ -472,7 +468,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
socket: { path: socketPath, exists: existsSync(socketPath) },
daemon,
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
access: accessContext(env, daemon.port ?? configuredPort),
bind: bindContext(env, daemon.port ?? configuredPort),
serviceManager,
linger,
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
+6 -11
View File
@@ -6,11 +6,11 @@
*
* ```jsonc
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1,
* "access":"local","publicUrl":null}
* "host":"0.0.0.0","publicUrl":null}
* ```
*
* `access`/`publicUrl` are optional so readers built before the access modes
* keep working.
* `host`/`publicUrl` are optional so readers built before them keep working; a
* legacy `access` field is simply ignored.
*
* The lock is created with `wx` (atomic: only one daemon wins) and is
* considered **stale** when the pid is gone or the recorded boot id differs
@@ -23,7 +23,6 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from
import { randomBytes } from "node:crypto";
import { dirname, join } from "node:path";
import { daemonLockPath, ensureDir, runtimeDir } from "../core/paths.js";
import { ACCESS_MODES, type AccessMode } from "../config.js";
export const LOCK_FILE = "daemon.lock";
export const DAEMON_JSON_FILE = "daemon.json";
@@ -35,8 +34,8 @@ export interface DaemonLock {
daemonId: string;
startedAt: number;
protocolVersion: number;
/** Optional: written by daemons that know about access modes. */
access?: AccessMode;
/** Optional: the bind address the daemon actually used. */
host?: string;
/** Optional: external base URL (or explicit `null` when unset). */
publicUrl?: string | null;
}
@@ -88,10 +87,6 @@ export function isPidAlive(pid: number): boolean {
}
}
function isAccessMode(value: unknown): value is AccessMode {
return typeof value === "string" && (ACCESS_MODES as readonly string[]).includes(value);
}
function isLock(value: unknown): value is DaemonLock {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Partial<DaemonLock>;
@@ -105,7 +100,7 @@ function isLock(value: unknown): value is DaemonLock {
candidate.daemonId !== "" &&
typeof candidate.startedAt === "number" &&
typeof candidate.protocolVersion === "number" &&
(candidate.access === undefined || isAccessMode(candidate.access)) &&
(candidate.host === undefined || typeof candidate.host === "string") &&
(candidate.publicUrl === undefined || candidate.publicUrl === null || typeof candidate.publicUrl === "string")
);
}
+136 -33
View File
@@ -21,7 +21,6 @@ import { platform as osPlatform } from "node:os";
import { runtimeDir } from "../core/paths.js";
import type { InstanceResourcesSnapshot } from "../core/interfaces.js";
import type { WorkspaceInfo } from "../protocol/types.js";
import { PROTOCOL_VERSION } from "../protocol/types.js";
import { main as runDaemonMain } from "./daemon.js";
import { readDaemonJson, type DaemonLock } from "./lock.js";
import { cliTokenPath, readCliToken } from "./token.js";
@@ -54,15 +53,17 @@ Usage:
pi2 status [--json] daemon info, instances, resources, health
pi2 open [--print] [--no-browser] open the web console signed in (local only)
pi2 doctor [--json] environment checks
pi2 pairing [--public-url <url>] create a pairing code (URL + code + QR payload)
pi2 pairing [--base <url>] create a pairing code (URL + code + QR)
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
pi2 uninstall-service [--dry-run|--write] remove the unit
pi2 --version | --help
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
of launching a browser (--print implies --no-browser).
\`pi2 pairing\` flags: --public-url <url> rebuilds the URL on that public base
(defaults to daemon.json's publicUrl, then PI2_PUBLIC_URL).
\`pi2 pairing\` flags: --base <url> pins the link to one of the addresses the
daemon advertises (it prints the alternatives; anything else is rejected).
The link prefers a phone-reachable address: the public URL when one is
configured, the primary LAN address, and loopback otherwise.
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
@@ -265,7 +266,7 @@ interface InfoBody {
platform: string;
capabilities: string[];
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
access?: string;
host?: string;
publicUrl?: string | null;
}
@@ -311,7 +312,7 @@ export async function runStatus(options: StatusOptions): Promise<number> {
url: client.baseUrl,
...info,
// Older daemons may not report them; daemon.json does.
access: info.access ?? client.daemon.access,
host: info.host ?? client.daemon.host ?? null,
publicUrl: info.publicUrl ?? client.daemon.publicUrl ?? null,
},
instances,
@@ -365,45 +366,147 @@ export async function runStatus(options: StatusOptions): Promise<number> {
export interface PairingOptions {
client: DaemonClient;
print?: (line: string) => void;
/** Rebuild the printed/QR url on this public base (e.g. `https://host.ts.net`). */
publicUrl?: string | null;
/** `--base <url>`: pin the link to one of the addresses the daemon advertises. */
base?: string | null;
}
function withoutTrailingSlash(value: string): string {
return value.trim().replace(/\/+$/, "");
/** One address the daemon says it is reachable on (`bases[]` in the mint response). */
export interface PairingBase {
kind: string;
name: string;
address: string;
url: string;
}
/** `--public-url` → `daemon.json.publicUrl` → `PI2_PUBLIC_URL`, first non-empty wins. */
export function resolvePublicUrl(client: DaemonClient, flag: string | undefined): string | null {
for (const candidate of [flag, client.daemon.publicUrl, process.env.PI2_PUBLIC_URL]) {
const value = candidate === undefined || candidate === null ? "" : withoutTrailingSlash(candidate);
if (value !== "") return value;
export interface PairingQr {
version: number;
ecc: string;
mask: number;
size: number;
/** One string per module row, `1` = dark, without a quiet zone. */
rows: string[];
}
export interface PairingResult {
code: string;
url: string;
expiresAt?: number;
nonce?: string;
qr?: PairingQr;
bases: PairingBase[];
}
/** Quiet zone around the terminal QR, in modules. */
const QR_QUIET_ZONE = 2;
/**
* Render a QR matrix for a terminal: one character per module, two module rows
* per text row via half blocks. The caller owns the width budget; a version 3
* symbol (29 modules) plus the quiet zone stays well inside 80 columns.
*/
export function renderTerminalQr(rows: readonly string[]): string[] {
const size = rows[0]?.length ?? 0;
if (size === 0) return [];
const width = size + QR_QUIET_ZONE * 2;
const blank = "0".repeat(width);
const frame = Array.from({ length: QR_QUIET_ZONE }, () => blank);
const padded = [
...frame,
...rows.map((row) => `${"0".repeat(QR_QUIET_ZONE)}${row}${"0".repeat(QR_QUIET_ZONE)}`),
...frame,
];
const lines: string[] = [];
for (let index = 0; index < padded.length; index += 2) {
const top = padded[index] ?? blank;
const bottom = padded[index + 1] ?? blank;
let line = "";
for (let column = 0; column < width; column += 1) {
const up = top[column] === "1";
const down = bottom[column] === "1";
line += up && down ? "█" : up ? "▀" : down ? "▄" : " ";
}
lines.push(line);
}
return null;
return lines;
}
function recordOf(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function pairingQrOf(raw: unknown): PairingQr | undefined {
const record = recordOf(raw);
if (!record || !Array.isArray(record.rows) || record.rows.length === 0) return undefined;
const rows = record.rows.filter((row: unknown): row is string => typeof row === "string");
if (rows.length === 0) return undefined;
return {
version: typeof record.version === "number" ? record.version : 0,
ecc: typeof record.ecc === "string" ? record.ecc : "M",
mask: typeof record.mask === "number" ? record.mask : 0,
size: typeof record.size === "number" ? record.size : (rows[0]?.length ?? 0),
rows,
};
}
function pairingBasesOf(raw: unknown): PairingBase[] {
if (!Array.isArray(raw)) return [];
return raw.flatMap((value) => {
const record = recordOf(value);
if (!record || typeof record.url !== "string") return [];
return [
{
kind: typeof record.kind === "string" ? record.kind : "other",
name: typeof record.name === "string" ? record.name : "",
address: typeof record.address === "string" ? record.address : "",
url: record.url,
},
];
});
}
/**
* `pi2 pairing` — mint a code and print a scannable link.
*
* The daemon owns the URL, the QR matrix and the list of usable bases (ADR
* 0001); the CLI only renders them. `--base` narrows the choice, and the daemon
* rejects anything it did not offer.
*/
export async function runPairing(options: PairingOptions): Promise<number> {
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
const result = await options.client.post("/api/v1/pair", {});
const code = typeof result.body.code === "string" ? result.body.code : undefined;
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
// Rebuild the URL from the *actual* base URL (or the public base when one is
// known): the daemon's own `url` field is derived from the configured port,
// which is stale after a retry or `--port 0`.
const base = options.publicUrl === undefined || options.publicUrl === null || options.publicUrl.trim() === ""
? options.client.baseUrl
: withoutTrailingSlash(options.publicUrl);
const url = `${base}/pair/${code}`;
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
const base = options.base?.trim() ?? "";
const response = await options.client.post("/api/v1/pair", base === "" ? {} : { base });
const code = typeof response.body.code === "string" ? response.body.code : undefined;
const url = typeof response.body.url === "string" ? response.body.url : undefined;
if (code === undefined || url === undefined) throw new CliError("pairing failed: daemon returned no code");
const expiresAt = typeof response.body.expiresAt === "number" ? response.body.expiresAt : undefined;
const qr = pairingQrOf(response.body.qr);
const bases = pairingBasesOf(response.body.bases);
print(`url ${url}`);
print(`code ${code}`);
if (expiresAt !== undefined) {
print(`expires ${new Date(expiresAt).toISOString()} (${Math.max(0, Math.round((expiresAt - Date.now()) / 1000))}s)`);
const seconds = Math.max(0, Math.round((expiresAt - Date.now()) / 1000));
print(`expires in ${seconds}s (${new Date(expiresAt).toISOString()})`);
}
if (qr === undefined) {
print("");
print("note the link is too long to encode as a QR code; open the url on the phone instead.");
} else {
print("");
for (const line of renderTerminalQr(qr.rows)) print(line);
}
if (bases.length > 1) {
print("");
print("other addresses the phone could use (pi2 pairing --base <url>):");
for (const candidate of bases) {
print(` ${candidate.kind.padEnd(9)} ${candidate.name.padEnd(12)} ${candidate.url}`);
}
}
print(`qr ${payload}`);
return 0;
}
@@ -633,7 +736,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
case "pairing":
case "pair": {
const parsed = parseArgs(rest, {
values: ["--public-url"],
values: ["--base"],
booleans: ["--help"],
aliases: { "-h": "--help" },
});
@@ -645,7 +748,7 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
return await runPairing({
client,
print: out,
publicUrl: resolvePublicUrl(client, stringFlag(parsed.flags, "--public-url")),
base: stringFlag(parsed.flags, "--base"),
});
}
case "install-service":
-1
View File
@@ -93,7 +93,6 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
const cliTokenPath = join(runtime, CLI_TOKEN_FILE);
const auth = new AuthStore({
path: config.deviceStorePath,
baseUrl: `http://${config.host}:${config.port}`,
localTokenPath: cliTokenPath,
...(options.now === undefined ? {} : { now: options.now }),
});
+28 -80
View File
@@ -4,13 +4,18 @@
* Defaults follow `docs/protocol.md`; deployment-specific values come from the
* environment so `pi2 daemon` can be started without a config file.
*
* `PI2_ACCESS_MODE` picks the bind address and the derived CORS origins:
* `local` is loopback-only, `lan` adds the detected LAN address and
* `tailscale` adds the origin of `PI2_PUBLIC_URL`. `PI2_ORIGINS` is *additive*
* to the derived list; it never replaces it.
* The daemon binds `0.0.0.0` by default: the console is meant to be opened from
* a phone as well as from the desktop, and access is gated by the pairing code
* and the device token — never by the bind address. `PI2_HOST` narrows the bind
* (e.g. `127.0.0.1` for a loopback-only daemon), `PI2_PUBLIC_URL` adds the
* external base used behind `tailscale serve`, and `PI2_ORIGINS` is *additive*.
*
* The CORS allowlist is derived by `core/network` from the addresses the daemon
* is actually reachable on, so it always matches the pairing link.
*/
import { networkInterfaces } from "node:os";
import type { NetworkInterfaceInfo } from "node:os";
import { fileURLToPath } from "node:url";
import { isLoopbackHost, isWildcardHost, localOrigins } from "./core/network.js";
import { daemonTokenPath, dataDir } from "./core/paths.js";
export const DEFAULT_PORT = 7676;
@@ -18,8 +23,8 @@ export const DEFAULT_MAX_BODY_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_FRAME_BYTES = 8 * 1024 * 1024;
export const DEFAULT_MAX_CONNECTIONS = 64;
export type AccessMode = "local" | "lan" | "tailscale";
export const ACCESS_MODES: readonly AccessMode[] = ["local", "lan", "tailscale"];
/** Wildcard bind: reachable from the desktop, the LAN and a tailnet. */
export const DEFAULT_HOST = "0.0.0.0";
export interface Limits {
maxBodyBytes: number;
@@ -37,7 +42,6 @@ export interface Config {
limits: Limits;
tokenPath: string;
deviceStorePath: string;
access: AccessMode;
/** External base URL (no trailing slash), e.g. `https://host.tail1234.ts.net`. */
publicUrl: string | null;
}
@@ -45,8 +49,8 @@ export interface Config {
export type ConfigEnv = Record<string, string | undefined>;
export interface ConfigOptions {
/** LAN address probe for `PI2_ACCESS_MODE=lan`; overridable in tests. */
detectLanIp?: () => string | null;
/** Network interfaces used to derive the CORS origins; overridable in tests. */
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>;
}
function defaultStaticDir(): string {
@@ -63,14 +67,6 @@ function parsePort(raw: string | undefined): number {
return port;
}
/** Unknown modes fail fast; the daemon prints the message as a one-line `pi2: ` error. */
export function parseAccessMode(raw: string | undefined): AccessMode {
const value = raw?.trim() ?? "";
if (value === "") return "local";
if ((ACCESS_MODES as readonly string[]).includes(value)) return value as AccessMode;
throw new Error("PI2_ACCESS_MODE must be local, lan or tailscale");
}
/** Trailing slashes and empty strings are not meaningful origins. */
function normalizeOrigin(raw: string): string | null {
const value = raw.trim().replace(/\/+$/, "");
@@ -82,15 +78,6 @@ function normalizePublicUrl(raw: string | undefined): string | null {
return normalizeOrigin(raw);
}
/** `https://host/path?q=1` → `https://host`; unparsable values fall back verbatim. */
function originOf(url: string): string | null {
try {
return new URL(url).origin;
} catch {
return normalizeOrigin(url);
}
}
function parseOrigins(raw: string | undefined): string[] {
if (raw === undefined) return [];
return raw
@@ -103,61 +90,16 @@ function dedupe(origins: readonly string[]): string[] {
return [...new Set(origins)];
}
function defaultHostFor(access: AccessMode): string {
return access === "lan" ? "0.0.0.0" : "127.0.0.1";
}
function loopbackOrigins(port: number): string[] {
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`];
}
/**
* First non-internal IPv4 address, best effort: `lan` mode only *adds* an
* origin, and an unknown address just leaves the loopback list in place.
*/
export function detectLanIp(): string | null {
try {
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses ?? []) {
if (address.family !== "IPv4" || address.internal) continue;
if (address.address.startsWith("169.254.")) continue;
return address.address;
}
}
} catch {
// best effort only
}
return null;
}
function derivedOrigins(
access: AccessMode,
port: number,
publicUrl: string | null,
detect: () => string | null,
): string[] {
const origins = loopbackOrigins(port);
if (access === "lan") {
let lanIp: string | null = null;
try {
lanIp = detect();
} catch {
lanIp = null;
}
if (lanIp !== null && lanIp.trim() !== "") origins.push(`http://${lanIp.trim()}:${port}`);
} else if (access === "tailscale" && publicUrl !== null) {
const origin = originOf(publicUrl);
if (origin !== null) origins.push(origin);
}
return origins;
}
export function loadConfig(env: ConfigEnv = process.env, options: ConfigOptions = {}): Config {
const port = parsePort(env.PI2_PORT);
const access = parseAccessMode(env.PI2_ACCESS_MODE);
const publicUrl = normalizePublicUrl(env.PI2_PUBLIC_URL);
const host = env.PI2_HOST?.trim() || defaultHostFor(access);
const derived = derivedOrigins(access, port, publicUrl, options.detectLanIp ?? detectLanIp);
const host = env.PI2_HOST?.trim() || DEFAULT_HOST;
const derived = localOrigins({
port,
bindHost: host,
publicUrl,
...(options.interfaces === undefined ? {} : { interfaces: options.interfaces }),
});
return {
host,
@@ -171,7 +113,13 @@ export function loadConfig(env: ConfigEnv = process.env, options: ConfigOptions
},
tokenPath: daemonTokenPath(),
deviceStorePath: `${dataDir()}/devices.json`,
access,
publicUrl,
};
}
/** Human-readable bind summary, shared by `pi2 status` and `pi2 doctor`. */
export function describeHost(host: string): string {
if (isWildcardHost(host)) return "all interfaces";
if (isLoopbackHost(host)) return "loopback only";
return host;
}
+183
View File
@@ -0,0 +1,183 @@
/**
* Where the daemon can be reached, and in which order to advertise it.
*
* The console is phone-first: the daemon binds `0.0.0.0` by default, so a phone
* on the same network opens `http://<lan-ip>:<port>` and the browser sends an
* `Origin` header the daemon has to allow. Both the CORS allowlist and the
* pairing link need the same answer to "which addresses are we reachable on",
* so they share this module instead of each sniffing `os.networkInterfaces()`.
*
* `interfaces` is injectable so ordering and classification stay testable
* without the host's real NICs.
*/
import { networkInterfaces, type NetworkInterfaceInfo } from "node:os";
export type NetworkBaseKind = "public" | "lan" | "other" | "tailscale" | "loopback";
export interface NetworkBase {
kind: NetworkBaseKind;
/** Interface name, `loopback`, or `public-url` for the configured base. */
name: string;
/** IPv4 address; empty for the `public-url` entry. */
address: string;
/** Base URL, no trailing slash and no credentials. */
url: string;
}
export interface NetworkOptions {
port: number;
/** The configured bind address; decides what is reachable. Defaults to wildcard. */
bindHost?: string;
/** External base URL (e.g. behind `tailscale serve`). */
publicUrl?: string | null;
interfaces?: NodeJS.Dict<NetworkInterfaceInfo[]>;
}
/** Wildcard binds: everything on the host is reachable. */
export const WILDCARD_HOSTS: readonly string[] = ["", "0.0.0.0", "::", "[::]"];
/** Interfaces that never reach a phone sitting next to the machine. */
const VIRTUAL_INTERFACE = /^(docker|veth|br-|virbr|vmnet|vboxnet|tun|tap|utun|tailscale|zt|wg|bridge|dummy)/i;
/** Interfaces a human would recognise as "the network cable / wifi". */
const PHYSICAL_INTERFACE = /^(eth|en|wlan|wl|eno|ens|enp|wlp)/i;
const PRIVATE_IPV4 = /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/;
/** 100.64.0.0/10 — the tailnet range Tailscale hands out. */
const TAILSCALE_IPV4 = /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./;
/** 169.254.0.0/16 — link-local, never reachable from another device. */
const LINK_LOCAL_IPV4 = /^169\.254\./;
const KIND_ORDER: Record<NetworkBaseKind, number> = {
public: 0,
lan: 1,
other: 2,
tailscale: 3,
loopback: 4,
};
/** `127.0.0.1`, `::1`, `localhost` — only this machine can connect. */
export function isLoopbackHost(host: string | undefined | null): boolean {
const value = (host ?? "").trim().toLowerCase().replace(/^\[|\]$/g, "");
if (value === "" || value === "localhost") return true;
if (value === "::1" || value === "0:0:0:0:0:0:0:1") return true;
return value.startsWith("127.");
}
/** `0.0.0.0` / `::` / empty: every interface. */
export function isWildcardHost(host: string | undefined | null): boolean {
return WILDCARD_HOSTS.includes((host ?? "").trim().toLowerCase());
}
export function isVirtualInterface(name: string): boolean {
return VIRTUAL_INTERFACE.test(name);
}
export function classifyAddress(name: string, address: string): NetworkBaseKind {
if (address.startsWith("127.")) return "loopback";
if (/^tailscale/i.test(name) || TAILSCALE_IPV4.test(address)) return "tailscale";
if (PRIVATE_IPV4.test(address)) return "lan";
return "other";
}
function isIPv4(entry: NetworkInterfaceInfo): boolean {
// Node exposes `family` as a string ("IPv4") on modern versions and a number
// (4) on older ones; accept both.
return entry.family === "IPv4" || (entry.family as unknown as number) === 4;
}
function normalizeBase(raw: string): string {
return raw.trim().replace(/\/+$/, "");
}
function originOf(url: string): string | null {
try {
return new URL(url).origin;
} catch {
return normalizeBase(url) === "" ? null : normalizeBase(url);
}
}
/**
* Every base a browser could use, best first.
*
* `bindHost` decides reachability: a loopback bind only advertises loopback (a
* public URL still counts — `tailscale serve` proxies to the loopback port), a
* specific address advertises that address plus loopback, and a wildcard bind
* advertises everything the host has.
*/
export function networkBases(options: NetworkOptions): NetworkBase[] {
const port = options.port;
const bindHost = options.bindHost;
const bases: NetworkBase[] = [];
const publicUrl = normalizeBase(options.publicUrl ?? "");
if (publicUrl !== "") bases.push({ kind: "public", name: "public-url", address: "", url: publicUrl });
const loopback = (name: string, address: string): NetworkBase => ({
kind: "loopback",
name,
address,
url: `http://${address}:${port}`,
});
const wildcard = isWildcardHost(bindHost);
if (!wildcard && isLoopbackHost(bindHost)) {
// Loopback-only daemon: nothing else is reachable, not even its own NICs.
return [...bases, loopback("loopback", "127.0.0.1")];
}
const boundAddress = wildcard ? null : normalizeBase(String(bindHost));
const rows: NetworkBase[] = [];
for (const [name, addresses] of Object.entries(options.interfaces ?? networkInterfaces())) {
for (const entry of addresses ?? []) {
if (entry.internal) continue;
if (!isIPv4(entry)) continue;
if (LINK_LOCAL_IPV4.test(entry.address)) continue;
if (boundAddress !== null && entry.address !== boundAddress) continue;
rows.push({
kind: classifyAddress(name, entry.address),
name,
address: entry.address,
url: `http://${entry.address}:${port}`,
});
}
}
rows.sort((left, right) => {
const byKind = KIND_ORDER[left.kind] - KIND_ORDER[right.kind];
if (byKind !== 0) return byKind;
const physical = Number(isVirtualInterface(left.name)) - Number(isVirtualInterface(right.name));
if (physical !== 0) return physical;
return left.name.localeCompare(right.name) || left.address.localeCompare(right.address);
});
bases.push(...rows);
bases.push(loopback("loopback", "127.0.0.1"));
return bases;
}
/** The base the daemon advertises by default: public URL, else best LAN, else loopback. */
export function primaryBase(options: NetworkOptions): NetworkBase {
const bases = networkBases(options);
const first = bases[0];
if (first === undefined) throw new Error("no reachable base address");
return first;
}
/**
* CORS allowlist: every reachable base, plus the loopback aliases a browser may
* have typed (`localhost`, IPv6 loopback).
*/
export function localOrigins(options: NetworkOptions): string[] {
const origins = new Set<string>();
for (const base of networkBases(options)) {
const origin = base.kind === "public" ? originOf(base.url) : null;
origins.add(origin ?? base.url);
}
const port = options.port;
origins.add(`http://localhost:${port}`);
origins.add(`http://[::1]:${port}`);
return [...origins];
}
+587
View File
@@ -0,0 +1,587 @@
/**
* Minimal QR Code encoder — byte mode, error-correction level M, versions 1–10.
*
* Why hand-rolled: `pi2 pairing` must be able to print something a phone camera
* can scan, and the daemon keeps a deliberately tiny dependency set (`hono`,
* `ws`, `zod`). A byte-mode-only encoder with a single EC level is ~300 lines
* of tables and bit shuffling, and it is fully covered by `test/core/qr.test.ts`
* (decoded with `zbarimg` when it is on `PATH`).
*
* Output is presentation-agnostic: `rows` is one string per module row, `1` for
* a dark module and `0` for a light one, without a quiet zone — every renderer
* (a Neovim float, a terminal, a canvas) adds its own margin and colors.
*
* Reference: ISO/IEC 18004; structure mirrors the well-known
* `qrcode-generator` implementation (mask patterns, format/version placement).
*/
/** Error-correction level: M (15% recovery) is the screen-scanning sweet spot. */
export type QrEcc = "M";
export interface QrMatrix {
/** QR version (1..10): the symbol is `4 * version + 17` modules wide. */
version: number;
ecc: QrEcc;
/** Mask pattern (0..7) that produced the lowest penalty score. */
mask: number;
/** Module count per side (no quiet zone). */
size: number;
/** `size` rows of `size` characters: `1` = dark, `0` = light. */
rows: string[];
}
export interface QrOptions {
/** Force a version instead of picking the smallest one that fits. */
version?: number;
/** Force a mask (0..7) instead of choosing by penalty score. Debug/tests. */
mask?: number;
}
export const MIN_VERSION = 1;
export const MAX_VERSION = 10;
export const ECC: QrEcc = "M";
/** ECC level bits used in the format information (M = 00). */
const ECC_FORMAT_BITS = 0b00;
interface BlockGroup {
/** Number of identical blocks. */
count: number;
/** Data codewords per block. */
dataCodewords: number;
}
interface VersionSpec {
/** EC codewords appended to every block. */
ecCodewordsPerBlock: number;
groups: BlockGroup[];
/** Total codewords (data + EC) the symbol carries. */
totalCodewords: number;
}
/**
* ECC-M block layout per version (ISO/IEC 18004 table 9). `totalCodewords`
* checks out against `data + ec` for every row; `test/core/qr.test.ts` asserts
* it so a typo cannot silently ship a mis-sized symbol.
*/
const VERSIONS: Record<number, VersionSpec> = {
1: { ecCodewordsPerBlock: 10, groups: [{ count: 1, dataCodewords: 16 }], totalCodewords: 26 },
2: { ecCodewordsPerBlock: 16, groups: [{ count: 1, dataCodewords: 28 }], totalCodewords: 44 },
3: { ecCodewordsPerBlock: 26, groups: [{ count: 1, dataCodewords: 44 }], totalCodewords: 70 },
4: { ecCodewordsPerBlock: 18, groups: [{ count: 2, dataCodewords: 32 }], totalCodewords: 100 },
5: { ecCodewordsPerBlock: 24, groups: [{ count: 2, dataCodewords: 43 }], totalCodewords: 134 },
6: { ecCodewordsPerBlock: 16, groups: [{ count: 4, dataCodewords: 27 }], totalCodewords: 172 },
7: { ecCodewordsPerBlock: 18, groups: [{ count: 4, dataCodewords: 31 }], totalCodewords: 196 },
8: {
ecCodewordsPerBlock: 22,
groups: [
{ count: 2, dataCodewords: 38 },
{ count: 2, dataCodewords: 39 },
],
totalCodewords: 242,
},
9: {
ecCodewordsPerBlock: 22,
groups: [
{ count: 3, dataCodewords: 36 },
{ count: 2, dataCodewords: 37 },
],
totalCodewords: 292,
},
10: {
ecCodewordsPerBlock: 26,
groups: [
{ count: 4, dataCodewords: 43 },
{ count: 1, dataCodewords: 44 },
],
totalCodewords: 346,
},
};
/** Alignment-pattern centre coordinates per version (0 length = none). */
const ALIGNMENT_CENTERS: Record<number, number[]> = {
1: [],
2: [6, 18],
3: [6, 22],
4: [6, 26],
5: [6, 30],
6: [6, 34],
7: [6, 22, 38],
8: [6, 24, 42],
9: [6, 26, 46],
10: [6, 28, 50],
};
/** Remainder bits after the last full codeword (version 1 and 7+ have none). */
const REMAINDER_BITS: Record<number, number> = {
1: 0,
2: 7,
3: 7,
4: 7,
5: 7,
6: 7,
7: 0,
8: 0,
9: 0,
10: 0,
};
const dataCodewords = (spec: VersionSpec): number =>
spec.groups.reduce((total, group) => total + group.count * group.dataCodewords, 0);
/** Character-count indicator width for byte mode. */
const charCountBits = (version: number): number => (version <= 9 ? 8 : 16);
/* -------------------------------------------------------------------------- */
/* GF(256) arithmetic + Reed-Solomon */
/* -------------------------------------------------------------------------- */
const GF_EXP = new Uint8Array(512);
const GF_LOG = new Uint8Array(256);
{
let value = 1;
for (let i = 0; i < 255; i += 1) {
GF_EXP[i] = value;
GF_LOG[value] = i;
value <<= 1;
if ((value & 0x100) !== 0) value ^= 0x11d;
}
for (let i = 255; i < 512; i += 1) GF_EXP[i] = GF_EXP[i - 255] as number;
}
function gfMultiply(a: number, b: number): number {
if (a === 0 || b === 0) return 0;
return GF_EXP[(GF_LOG[a] as number) + (GF_LOG[b] as number)] as number;
}
/** Generator polynomial of the requested degree, highest-order coefficient first. */
function rsGenerator(degree: number): number[] {
let poly = [1];
for (let i = 0; i < degree; i += 1) {
const root = GF_EXP[i] as number;
const next = new Array<number>(poly.length + 1).fill(0);
next[0] = poly[0] as number;
for (let j = 1; j < poly.length; j += 1) {
next[j] = (poly[j] as number) ^ gfMultiply(root, poly[j - 1] as number);
}
next[poly.length] = gfMultiply(root, poly[poly.length - 1] as number);
poly = next;
}
return poly;
}
/** EC codewords for one block, computed as the polynomial remainder. */
function rsEncode(data: number[], generator: number[]): number[] {
const degree = generator.length - 1;
const remainder = new Array<number>(degree).fill(0);
for (const byte of data) {
const factor = byte ^ (remainder[0] as number);
remainder.shift();
remainder.push(0);
for (let i = 0; i < degree; i += 1) {
remainder[i] = (remainder[i] as number) ^ gfMultiply(generator[i + 1] as number, factor);
}
}
return remainder;
}
/* -------------------------------------------------------------------------- */
/* Bit stream + codewords */
/* -------------------------------------------------------------------------- */
function pushBits(bits: number[], value: number, length: number): void {
for (let i = length - 1; i >= 0; i -= 1) bits.push((value >>> i) & 1);
}
/** Smallest version whose data capacity holds `byteLength` bytes. */
function pickVersion(byteLength: number): number {
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
const spec = VERSIONS[version] as VersionSpec;
const capacityBits = dataCodewords(spec) * 8;
const neededBits = 4 + charCountBits(version) + byteLength * 8;
if (neededBits <= capacityBits) return version;
}
throw new RangeError(
`qr: ${byteLength} bytes do not fit in a version-${MAX_VERSION} ECC-M symbol (max ${Math.floor(
(dataCodewords(VERSIONS[MAX_VERSION] as VersionSpec) * 8 - 4 - charCountBits(MAX_VERSION)) / 8,
)} bytes)`,
);
}
/** Header + payload, terminator, byte padding, alternating 0xEC/0x11 fill. */
function buildDataCodewords(bytes: number[], version: number): number[] {
const spec = VERSIONS[version] as VersionSpec;
const capacityBits = dataCodewords(spec) * 8;
const bits: number[] = [];
pushBits(bits, 0b0100, 4); // byte mode
pushBits(bits, bytes.length, charCountBits(version));
for (const byte of bytes) pushBits(bits, byte, 8);
pushBits(bits, 0, Math.min(4, capacityBits - bits.length));
while (bits.length % 8 !== 0) bits.push(0);
const codewords: number[] = [];
for (let i = 0; i < bits.length; i += 8) {
let byte = 0;
for (let bit = 0; bit < 8; bit += 1) byte = (byte << 1) | (bits[i + bit] as number);
codewords.push(byte);
}
let pad = 0;
while (codewords.length < dataCodewords(spec)) {
codewords.push(pad % 2 === 0 ? 0xec : 0x11);
pad += 1;
}
return codewords;
}
/** Split into blocks, append EC, then interleave (data first, then EC). */
function buildCodewordStream(bytes: number[], version: number): number[] {
const spec = VERSIONS[version] as VersionSpec;
const flat = buildDataCodewords(bytes, version);
const generator = rsGenerator(spec.ecCodewordsPerBlock);
const blocks: { data: number[]; ec: number[] }[] = [];
let offset = 0;
for (const group of spec.groups) {
for (let i = 0; i < group.count; i += 1) {
const data = flat.slice(offset, offset + group.dataCodewords);
offset += group.dataCodewords;
blocks.push({ data, ec: rsEncode(data, generator) });
}
}
const longestData = Math.max(...blocks.map((block) => block.data.length));
const stream: number[] = [];
for (let i = 0; i < longestData; i += 1) {
for (const block of blocks) {
const value = block.data[i];
if (value !== undefined) stream.push(value);
}
}
for (let i = 0; i < spec.ecCodewordsPerBlock; i += 1) {
for (const block of blocks) stream.push(block.ec[i] as number);
}
return stream;
}
/* -------------------------------------------------------------------------- */
/* Symbol construction */
/* -------------------------------------------------------------------------- */
type Grid = Int8Array[]; // -1 = unset, 0 = light, 1 = dark
const makeGrid = (size: number): Grid =>
Array.from({ length: size }, () => new Int8Array(size).fill(-1));
const inBounds = (size: number, row: number, col: number): boolean =>
row >= 0 && col >= 0 && row < size && col < size;
function setModule(grid: Grid, size: number, row: number, col: number, dark: boolean): void {
if (inBounds(size, row, col)) grid[row]![col] = dark ? 1 : 0;
}
function placeFinder(grid: Grid, size: number, row: number, col: number): void {
// 7x7 eye + the light separator ring around it.
for (let dr = -1; dr <= 7; dr += 1) {
for (let dc = -1; dc <= 7; dc += 1) {
const r = row + dr;
const c = col + dc;
if (!inBounds(size, r, c)) continue;
const inEye = dr >= 0 && dr <= 6 && dc >= 0 && dc <= 6;
const dark = inEye && (dr === 0 || dr === 6 || dc === 0 || dc === 6 || (dr >= 2 && dr <= 4 && dc >= 2 && dc <= 4));
grid[r]![c] = dark ? 1 : 0;
}
}
}
function placeAlignment(grid: Grid, size: number, centreRow: number, centreCol: number): void {
for (let dr = -2; dr <= 2; dr += 1) {
for (let dc = -2; dc <= 2; dc += 1) {
const dark = Math.abs(dr) === 2 || Math.abs(dc) === 2 || (dr === 0 && dc === 0);
setModule(grid, size, centreRow + dr, centreCol + dc, dark);
}
}
}
/** Finder eyes, separators, timing, alignment, dark module, reserved info areas. */
function placeFunctionPatterns(grid: Grid, size: number, version: number): void {
placeFinder(grid, size, 0, 0);
placeFinder(grid, size, 0, size - 7);
placeFinder(grid, size, size - 7, 0);
for (let i = 8; i < size - 8; i += 1) {
const dark = i % 2 === 0;
if (grid[6]![i] === -1) grid[6]![i] = dark ? 1 : 0;
if (grid[i]![6] === -1) grid[i]![6] = dark ? 1 : 0;
}
const centres = ALIGNMENT_CENTERS[version] as number[];
for (const row of centres) {
for (const col of centres) {
// Skip the three positions that collide with the finder eyes.
const overlapsFinder = (row <= 8 && col <= 8) || (row <= 8 && col >= size - 9) || (row >= size - 9 && col <= 8);
if (overlapsFinder) continue;
placeAlignment(grid, size, row, col);
}
}
// Format information areas (written later) and the always-dark module.
for (let i = 0; i < 9; i += 1) {
if (grid[8]![i] === -1) grid[8]![i] = 0;
if (grid[i]![8] === -1) grid[i]![8] = 0;
}
for (let i = 0; i < 8; i += 1) {
if (grid[8]![size - 1 - i] === -1) grid[8]![size - 1 - i] = 0;
if (grid[size - 1 - i]![8] === -1) grid[size - 1 - i]![8] = 0;
}
grid[size - 8]![8] = 1;
if (version >= 7) {
for (let i = 0; i < 18; i += 1) {
const row = Math.floor(i / 3);
const col = (i % 3) + size - 11;
if (grid[row]![col] === -1) grid[row]![col] = 0;
if (grid[col]![row] === -1) grid[col]![row] = 0;
}
}
}
/** Zigzag data placement, MSB first, skipping the vertical timing column. */
function placeData(grid: Grid, size: number, codewords: number[], mask: number): void {
let bitIndex = 7;
let byteIndex = 0;
let row = size - 1;
let direction = -1;
for (let col = size - 1; col > 0; col -= 2) {
if (col === 6) col -= 1;
for (;;) {
for (let offset = 0; offset < 2; offset += 1) {
const c = col - offset;
if (grid[row]![c] !== -1) continue;
const byte = codewords[byteIndex];
let dark = byte !== undefined && ((byte >>> bitIndex) & 1) === 1;
if (maskApplies(mask, row, c)) dark = !dark;
grid[row]![c] = dark ? 1 : 0;
bitIndex -= 1;
if (bitIndex < 0) {
bitIndex = 7;
byteIndex += 1;
}
}
row += direction;
if (row < 0 || row >= size) {
row -= direction;
direction = -direction;
break;
}
}
}
}
/** The eight mask conditions, `i` = row, `j` = column. */
function maskApplies(mask: number, row: number, col: number): boolean {
switch (mask) {
case 0:
return (row + col) % 2 === 0;
case 1:
return row % 2 === 0;
case 2:
return col % 3 === 0;
case 3:
return (row + col) % 3 === 0;
case 4:
return (Math.floor(row / 2) + Math.floor(col / 3)) % 2 === 0;
case 5:
return ((row * col) % 2) + ((row * col) % 3) === 0;
case 6:
return (((row * col) % 2) + ((row * col) % 3)) % 2 === 0;
case 7:
return (((row * col) % 3) + ((row + col) % 2)) % 2 === 0;
default:
throw new RangeError(`qr: mask must be 0..7, got ${mask}`);
}
}
/** Polynomial remainder over GF(2): `data << shift` mod `poly`. */
function bchRemainder(data: number, poly: number, shift: number): number {
let remainder = data << shift;
while (remainder !== 0 && bitLength(remainder) >= bitLength(poly)) {
remainder ^= poly << (bitLength(remainder) - bitLength(poly));
}
return remainder;
}
/** BCH(15,5) remainder for the format information. */
function formatBits(mask: number): number {
const data = (ECC_FORMAT_BITS << 3) | mask;
return (((data << 10) | bchRemainder(data, 0x537, 10)) ^ 0x5412) & 0x7fff;
}
/** BCH(18,6) remainder for the version information (version >= 7). */
function versionBits(version: number): number {
return ((version << 12) | bchRemainder(version, 0x1f25, 12)) & 0x3ffff;
}
function bitLength(value: number): number {
let length = 0;
let rest = value;
while (rest !== 0) {
length += 1;
rest >>>= 1;
}
return length;
}
function writeFormatInfo(grid: Grid, size: number, mask: number): void {
const bits = formatBits(mask);
for (let i = 0; i < 15; i += 1) {
const dark = ((bits >>> i) & 1) === 1;
// Vertical strip (column 8) …
if (i < 6) grid[i]![8] = dark ? 1 : 0;
else if (i < 8) grid[i + 1]![8] = dark ? 1 : 0;
else grid[size - 15 + i]![8] = dark ? 1 : 0;
// … and its mirrored horizontal copy (row 8).
if (i < 8) grid[8]![size - 1 - i] = dark ? 1 : 0;
else if (i < 9) grid[8]![15 - i] = dark ? 1 : 0;
else grid[8]![14 - i] = dark ? 1 : 0;
}
grid[size - 8]![8] = 1;
}
function writeVersionInfo(grid: Grid, size: number, version: number): void {
if (version < 7) return;
const bits = versionBits(version);
for (let i = 0; i < 18; i += 1) {
const dark = ((bits >>> i) & 1) === 1;
const row = Math.floor(i / 3);
const col = (i % 3) + size - 11;
grid[row]![col] = dark ? 1 : 0;
grid[col]![row] = dark ? 1 : 0;
}
}
/** ISO/IEC 18004 §8.8.2 penalty rules N1..N4; the mask with the lowest score wins. */
function penaltyScore(grid: Grid, size: number): number {
let score = 0;
// N1: runs of five or more identical modules in a row/column.
for (let i = 0; i < size; i += 1) {
let rowRun = 1;
let colRun = 1;
for (let j = 1; j < size; j += 1) {
if (grid[i]![j] === grid[i]![j - 1]) rowRun += 1;
else {
if (rowRun >= 5) score += 3 + (rowRun - 5);
rowRun = 1;
}
if (grid[j]![i] === grid[j - 1]![i]) colRun += 1;
else {
if (colRun >= 5) score += 3 + (colRun - 5);
colRun = 1;
}
}
if (rowRun >= 5) score += 3 + (rowRun - 5);
if (colRun >= 5) score += 3 + (colRun - 5);
}
// N2: 2x2 blocks of one colour.
for (let row = 0; row < size - 1; row += 1) {
for (let col = 0; col < size - 1; col += 1) {
const value = grid[row]![col];
if (value === grid[row]![col + 1] && value === grid[row + 1]![col] && value === grid[row + 1]![col + 1]) {
score += 3;
}
}
}
// N3: finder-like 1:1:3:1:1 patterns with four light modules on either side.
const finderLike = [1, 0, 1, 1, 1, 0, 1] as const;
const matchesAt = (line: number[], start: number, pattern: readonly number[]): boolean =>
pattern.every((expected, offset) => line[start + offset] === expected);
const rows: number[][] = [];
const cols: number[][] = [];
for (let i = 0; i < size; i += 1) {
rows.push(Array.from(grid[i] as Int8Array));
cols.push(Array.from({ length: size }, (_, j) => grid[j]![i] as number));
}
for (const line of [...rows, ...cols]) {
for (let start = 0; start + 11 <= size; start += 1) {
if (matchesAt(line, start, finderLike) && line.slice(start + 7, start + 11).every((v) => v === 0)) score += 40;
if (matchesAt(line, start, [0, 0, 0, 0, ...finderLike])) score += 40;
}
}
// N4: deviation of the dark-module ratio from 50%.
let dark = 0;
for (const line of grid) for (const value of line) if (value === 1) dark += 1;
const percent = (dark * 100) / (size * size);
score += Math.floor(Math.abs(percent - 50) / 5) * 10;
return score;
}
function toRows(grid: Grid, size: number): string[] {
return grid.map((line) => Array.from({ length: size }, (_, col) => (line[col] === 1 ? "1" : "0")).join(""));
}
/**
* Encode `text` (UTF-8) as a QR symbol at ECC level M.
*
* @throws RangeError when the payload does not fit a version-10 symbol or an
* override is out of range.
*/
export function encodeQr(text: string, options: QrOptions = {}): QrMatrix {
const bytes = Array.from(Buffer.from(text, "utf8"));
const version = options.version ?? pickVersion(bytes.length);
if (!Number.isInteger(version) || version < MIN_VERSION || version > MAX_VERSION) {
throw new RangeError(`qr: version must be ${MIN_VERSION}..${MAX_VERSION}, got ${options.version}`);
}
if (bytes.length > capacityBytes(version)) {
throw new RangeError(`qr: ${bytes.length} bytes do not fit version ${version} at ECC M`);
}
if (options.mask !== undefined && (!Number.isInteger(options.mask) || options.mask < 0 || options.mask > 7)) {
throw new RangeError(`qr: mask must be 0..7, got ${options.mask}`);
}
const size = version * 4 + 17;
const codewords = buildCodewordStream(bytes, version);
// The mask is applied while the data modules are placed, so every candidate
// starts from a fresh copy of the function patterns.
const candidates = options.mask === undefined ? [0, 1, 2, 3, 4, 5, 6, 7] : [options.mask];
let best: { mask: number; grid: Grid; score: number } | undefined;
for (const mask of candidates) {
const grid = makeGrid(size);
placeFunctionPatterns(grid, size, version);
placeData(grid, size, codewords, mask);
writeFormatInfo(grid, size, mask);
writeVersionInfo(grid, size, version);
const score = penaltyScore(grid, size);
if (best === undefined || score < best.score) best = { mask, grid, score };
}
const chosen = best as { mask: number; grid: Grid };
return {
version,
ecc: ECC,
mask: chosen.mask,
size,
rows: toRows(chosen.grid, size),
};
}
/** Bytes a version-`version` ECC-M symbol can carry, excluding header bytes. */
export function capacityBytes(version: number = MAX_VERSION): number {
const spec = VERSIONS[version] as VersionSpec | undefined;
if (spec === undefined) throw new RangeError(`qr: unknown version ${version}`);
return Math.floor((dataCodewords(spec) * 8 - 4 - charCountBits(version)) / 8);
}
/** `true` when the whole payload fits at ECC M (used by callers to fail early). */
export function fitsQr(text: string): boolean {
return Buffer.byteLength(text, "utf8") <= capacityBytes(MAX_VERSION);
}
/** Version table exposed for tests (capacity assertions). */
export function versionSpecs(): Record<number, VersionSpec> {
return VERSIONS;
}
+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,
},
});
};