feat(daemon): add access modes and the local-browser login handshake

`PI2_ACCESS_MODE` (local|lan|tailscale) picks the bind address and the derived
CORS origins, `PI2_PUBLIC_URL` adds the external origin, and `PI2_ORIGINS` is now
additive instead of replacing the derived list. `daemon.json` and
`/api/v1/info` carry the mode and the public URL.

`POST /api/v1/console/session` is the `:PiWeb` handshake: loopback + the local
CLI token only, it mints or reuses the single "local browser" device and answers
`http://127.0.0.1:<port>/#t=<token>`. The token is stored plaintext next to
`devices.json` (0600) so repeated logins return the same credentials instead of
logging the already-open tab out; revoking the device drops it.
This commit is contained in:
yuez committed 2026-10-23 08:34:39 +08:00
1 parent 9eb857465c
commit 01db49fb38
11 files changed
+690 -26

No files matched your search

+4 -1
View File
@@ -44,7 +44,8 @@ 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_DATA_DIR, PI2_STATE_DIR, PI2_LOG_LEVEL, PI2_WORKSPACE_ROOTS,
PI2_ACCESS_MODE (local|lan|tailscale), PI2_PUBLIC_URL
Runtime files ($PI2_RUNTIME_DIR):
d.sock plugin unix socket (nvim → daemon)
@@ -180,6 +181,8 @@ export async function main(argv: readonly string[], ioOptions: RunDaemonOptions
daemonId,
startedAt: Date.now(),
protocolVersion: PROTOCOL_VERSION,
access: config.access,
publicUrl: config.publicUrl,
},
});
// Rotate the local CLI token only when this process owns the lock:
+17 -2
View File
@@ -5,9 +5,13 @@
* Both files carry the same payload:
*
* ```jsonc
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1}
* {"pid":1234,"bootId":"…","port":7676,"daemonId":"d-…","startedAt":1733,"protocolVersion":1,
* "access":"local","publicUrl":null}
* ```
*
* `access`/`publicUrl` are optional so readers built before the access modes
* keep working.
*
* 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
* from the current one (pid reuse after a reboot). `--force` ignores a live
@@ -19,6 +23,7 @@ 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";
@@ -30,6 +35,10 @@ export interface DaemonLock {
daemonId: string;
startedAt: number;
protocolVersion: number;
/** Optional: written by daemons that know about access modes. */
access?: AccessMode;
/** Optional: external base URL (or explicit `null` when unset). */
publicUrl?: string | null;
}
export type LockErrorCode = "E_LOCKED";
@@ -79,6 +88,10 @@ 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>;
@@ -91,7 +104,9 @@ function isLock(value: unknown): value is DaemonLock {
typeof candidate.daemonId === "string" &&
candidate.daemonId !== "" &&
typeof candidate.startedAt === "number" &&
typeof candidate.protocolVersion === "number"
typeof candidate.protocolVersion === "number" &&
(candidate.access === undefined || isAccessMode(candidate.access)) &&
(candidate.publicUrl === undefined || candidate.publicUrl === null || typeof candidate.publicUrl === "string")
);
}
+113 -11
View File
@@ -3,7 +3,13 @@
*
* 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.
*/
import { networkInterfaces } from "node:os";
import { fileURLToPath } from "node:url";
import { daemonTokenPath, dataDir } from "./core/paths.js";
@@ -12,6 +18,9 @@ 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"];
export interface Limits {
maxBodyBytes: number;
maxFrameBytes: number;
@@ -28,10 +37,18 @@ 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;
}
export type ConfigEnv = Record<string, string | undefined>;
export interface ConfigOptions {
/** LAN address probe for `PI2_ACCESS_MODE=lan`; overridable in tests. */
detectLanIp?: () => string | null;
}
function defaultStaticDir(): string {
return fileURLToPath(new URL("../web/dist", import.meta.url));
}
@@ -46,24 +63,107 @@ function parsePort(raw: string | undefined): number {
return port;
}
function parseOrigins(raw: string | undefined, port: number): string[] {
if (raw !== undefined) {
return raw
.split(",")
.map((origin) => origin.trim())
.filter((origin) => origin.length > 0);
}
return [`http://127.0.0.1:${port}`, `http://localhost:${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");
}
export function loadConfig(env: ConfigEnv = process.env): Config {
/** Trailing slashes and empty strings are not meaningful origins. */
function normalizeOrigin(raw: string): string | null {
const value = raw.trim().replace(/\/+$/, "");
return value === "" ? null : value;
}
function normalizePublicUrl(raw: string | undefined): string | null {
if (raw === undefined) return 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
.split(",")
.map((origin) => normalizeOrigin(origin))
.filter((origin): origin is string => origin !== null);
}
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 host = env.PI2_HOST?.trim() || "127.0.0.1";
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);
return {
host,
port,
staticDir: env.PI2_STATIC_DIR?.trim() || defaultStaticDir(),
corsOrigins: parseOrigins(env.PI2_ORIGINS, port),
corsOrigins: dedupe([...derived, ...parseOrigins(env.PI2_ORIGINS)]),
limits: {
maxBodyBytes: DEFAULT_MAX_BODY_BYTES,
maxFrameBytes: DEFAULT_MAX_FRAME_BYTES,
@@ -71,5 +171,7 @@ export function loadConfig(env: ConfigEnv = process.env): Config {
},
tokenPath: daemonTokenPath(),
deviceStorePath: `${dataDir()}/devices.json`,
access,
publicUrl,
};
}
+104 -1
View File
@@ -9,7 +9,7 @@
* `local-cli` device with every scope; see `docs/deployment.md` §7.
*/
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { dataDir } from "../core/paths.js";
import { ERROR_CODES } from "../protocol/errors.js";
@@ -72,11 +72,25 @@ export interface AuthStoreOptions {
* `local-cli` device with every scope. Checked after the persisted devices.
*/
localTokenPath?: string;
/**
* Where the plaintext local-browser token lives. Defaults to
* `<dataDir>/local-browser.token` (mode 0600), next to `devices.json`.
*/
localBrowserTokenPath?: string;
}
/** Synthetic device id used for the local CLI token (never persisted). */
export const LOCAL_CLI_DEVICE_ID = "local-cli";
/** The single device that represents the browser opened by `pi2 open`. */
export const LOCAL_BROWSER_NAME = "local browser";
export const LOCAL_BROWSER_KIND: DeviceKind = "laptop";
export interface LocalBrowserSession {
token: string;
device: DevicePublic;
}
/** Constant-time string compare; the token length itself is not a secret. */
function tokensEqual(expected: string, candidate: string): boolean {
const left = Buffer.from(expected, "utf8");
@@ -142,6 +156,7 @@ function pairCode(): string {
export class AuthStore {
readonly path: string;
readonly localTokenPath: string | undefined;
readonly localBrowserTokenPath: string;
private readonly now: () => number;
private readonly baseUrl: string;
private readonly touchIntervalMs: number;
@@ -155,6 +170,7 @@ export class AuthStore {
this.touchIntervalMs = options.touchIntervalMs ?? 60_000;
this.localTokenPath =
options.localTokenPath === undefined || options.localTokenPath === "" ? undefined : options.localTokenPath;
this.localBrowserTokenPath = options.localBrowserTokenPath ?? `${dirname(this.path)}/local-browser.token`;
this.load();
}
@@ -206,6 +222,9 @@ export class AuthStore {
if (!record || record.revokedAt !== null) return false;
record.revokedAt = this.now();
this.persist();
// Revoking the local browser also drops the plaintext token, so the next
// `:PiWeb` / `pi2 open` mints a fresh one instead of handing out a dead URL.
if (record.name === LOCAL_BROWSER_NAME && record.kind === LOCAL_BROWSER_KIND) this.clearLocalBrowserToken();
return true;
}
@@ -261,6 +280,90 @@ export class AuthStore {
return this.pairs.has(code);
}
/**
* The local-browser login handshake (`POST /api/v1/console/session`).
*
* There is exactly one "local browser" device and, until it is revoked, one
* stable token: `pi2 open` and `:PiWeb` hand the same credentials to the
* browser on every call, so opening the console twice never invalidates the
* tab that is already open. The plaintext lives in
* `<dataDir>/local-browser.token` (0600, like `cli.token`); `devices.json`
* keeps only the hash.
*
* Revoking the device (or deleting the file) forces a new token on the next
* login; that path also covers a `devices.json` whose hash no longer matches
* the stored plaintext.
*/
localBrowserSession(): LocalBrowserSession {
const existing = this.devices.find(
(device) => device.name === LOCAL_BROWSER_NAME && device.kind === LOCAL_BROWSER_KIND,
);
const stored = this.readLocalBrowserToken();
if (
existing !== undefined &&
existing.revokedAt === null &&
stored !== null &&
timingSafeEqualHex(existing.tokenHash, hashToken(stored))
) {
return { token: stored, device: publicDevice(existing) };
}
const token = randomBytes(32).toString("base64url");
const hash = hashToken(token);
if (existing === undefined) {
// `createDevice` mints its own token; overwrite it so the created and
// rotated paths end in the same state (one record, this token).
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);
return { token, device: publicDevice(existing) };
}
/** Stored plaintext for the local browser; `null` when absent or unreadable. */
private readLocalBrowserToken(): string | null {
if (!existsSync(this.localBrowserTokenPath)) return null;
try {
const contents = readFileSync(this.localBrowserTokenPath, "utf8").trim();
return contents === "" ? null : contents;
} catch {
return null;
}
}
/** Atomic 0600 write, same pattern as `persist()`. */
private writeLocalBrowserToken(token: string): void {
const directory = dirname(this.localBrowserTokenPath);
if (!existsSync(directory)) mkdirSync(directory, { recursive: true, mode: 0o700 });
const temporary = `${this.localBrowserTokenPath}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
writeFileSync(temporary, `${token}\n`, { mode: 0o600 });
renameSync(temporary, this.localBrowserTokenPath);
}
/** Drop the stored token; the next login mints a new one. */
private clearLocalBrowserToken(): void {
try {
if (existsSync(this.localBrowserTokenPath)) unlinkSync(this.localBrowserTokenPath);
} catch {
/* best effort: a missing file is the desired state */
}
}
/** The local CLI token grants every scope; it is not persisted or revocable. */
private localCliDevice(): DevicePublic {
const timestamp = this.now();
+38 -3
View File
@@ -9,7 +9,7 @@ import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import type { AuthStore, DevicePublic } from "./auth.js";
import { isAllowedOrigin } from "./auth.js";
import { isAllowedOrigin, LOCAL_CLI_DEVICE_ID } from "./auth.js";
import { DaemonError, toErrorPayload } from "./errors.js";
import { CommandRouter } from "./router.js";
import { createSseHandler } from "./sse.js";
@@ -68,7 +68,16 @@ function json(status: number, body: unknown, headers: Record<string, string> = {
});
}
async function readJsonBody(c: Context<Env>, maxBytes: number): Promise<Record<string, unknown>> {
interface ReadJsonOptions {
/** An absent body is `{}` (used by `console/session`, whose body is optional). */
optional?: boolean;
}
async function readJsonBody(
c: Context<Env>,
maxBytes: number,
options: ReadJsonOptions = {},
): Promise<Record<string, unknown>> {
const declared = c.req.header("content-length");
if (declared !== undefined) {
const length = Number(declared);
@@ -80,7 +89,10 @@ async function readJsonBody(c: Context<Env>, maxBytes: number): Promise<Record<s
if (Buffer.byteLength(text, "utf8") > maxBytes) {
throw DaemonError.payloadTooLarge(`body exceeds ${maxBytes} bytes`);
}
if (text.trim() === "") throw DaemonError.badRequest("request body is required");
if (text.trim() === "") {
if (options.optional === true) return {};
throw DaemonError.badRequest("request body is required");
}
let parsed: unknown;
try {
parsed = JSON.parse(text);
@@ -176,9 +188,32 @@ export function createApp(deps: AppDeps): Hono<Env> {
port: config.port,
capabilities: ["ws", "sse", "devices", "attention"],
limits: config.limits,
access: config.access,
publicUrl: config.publicUrl,
}),
);
/**
* Local-browser login handshake: loopback + the local CLI token only.
* The token in the returned URL lives in the fragment (`#t=`), so it never
* reaches an HTTP request line, a `Referer` header or a proxy access log.
*/
app.post("/api/v1/console/session", async (c) => {
// Remote clients pair instead; refuse before touching the device store.
if (!isLoopback(c)) return json(403, errorBody(ERROR_CODES.FORBIDDEN, "console login is loopback-only"));
const callerToken = bearer(c);
const caller = callerToken === undefined ? null : auth.verifyToken(callerToken);
if (caller === null || caller.id !== LOCAL_CLI_DEVICE_ID) {
return json(401, errorBody(ERROR_CODES.UNAUTHORIZED, "console login requires the local CLI token"));
}
await readJsonBody(c, config.limits.maxBodyBytes, { optional: true });
const session = auth.localBrowserSession();
// Always loopback and the *actual* bound port (`config.port` already
// reflects retries/ephemeral ports), even when the daemon binds 0.0.0.0.
const url = `http://127.0.0.1:${config.port}/#t=${encodeURIComponent(session.token)}`;
return c.json({ token: session.token, device: session.device, url });
});
const health = (c: Context<Env>) => {
const instanceStates = instances.list();
const degraded = instanceStates.filter((instance) => instance.status === "degraded");