diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts index d0388e4..aa1f75b 100644 --- a/src/cli/daemon.ts +++ b/src/cli/daemon.ts @@ -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: diff --git a/src/cli/lock.ts b/src/cli/lock.ts index 7f26d60..f34e001 100644 --- a/src/cli/lock.ts +++ b/src/cli/lock.ts @@ -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; @@ -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") ); } diff --git a/src/config.ts b/src/config.ts index 1102fbd..50e67c6 100644 --- a/src/config.ts +++ b/src/config.ts @@ -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; +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, }; } diff --git a/src/daemon/auth.ts b/src/daemon/auth.ts index 3fcff2a..9e2ae30 100644 --- a/src/daemon/auth.ts +++ b/src/daemon/auth.ts @@ -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 + * `/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 + * `/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(); diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 5e4eee2..4103a48 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -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 = { }); } -async function readJsonBody(c: Context, maxBytes: number): Promise> { +interface ReadJsonOptions { + /** An absent body is `{}` (used by `console/session`, whose body is optional). */ + optional?: boolean; +} + +async function readJsonBody( + c: Context, + maxBytes: number, + options: ReadJsonOptions = {}, +): Promise> { const declared = c.req.header("content-length"); if (declared !== undefined) { const length = Number(declared); @@ -80,7 +89,10 @@ async function readJsonBody(c: Context, maxBytes: number): Promise 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 { 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) => { const instanceStates = instances.list(); const degraded = instanceStates.filter((instance) => instance.status === "degraded"); diff --git a/test/cli/helpers.ts b/test/cli/helpers.ts index d57bb12..755a861 100644 --- a/test/cli/helpers.ts +++ b/test/cli/helpers.ts @@ -28,6 +28,8 @@ export function testConfig(overrides: Partial = {}): Config { limits: TEST_LIMITS, tokenPath: "/tmp/pi2-daemon-cli-test.sock.token", deviceStorePath: "/tmp/pi2-daemon-cli-test-devices.json", + access: "local", + publicUrl: null, }; return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; } diff --git a/test/cli/lock.test.ts b/test/cli/lock.test.ts index e50bfda..3ae362c 100644 --- a/test/cli/lock.test.ts +++ b/test/cli/lock.test.ts @@ -183,6 +183,36 @@ describe("daemon.json", () => { handle.release(); }); + it("carries the optional access/publicUrl fields and stays readable without them", () => { + const handle = acquireLock({ + lockPath, + payload: { + port: 7676, + daemonId: "d-access", + startedAt: 5, + protocolVersion: PROTOCOL_VERSION, + access: "tailscale", + publicUrl: "https://host.ts.net", + }, + bootId: () => BOOT, + }); + expect(readLockFile(lockPath)?.access).toBe("tailscale"); + expect(readLockFile(lockPath)?.publicUrl).toBe("https://host.ts.net"); + handle.release(); + + // A legacy payload (no new fields) still parses. + const legacy = { ...payload(), pid: process.pid, bootId: BOOT }; + writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`); + expect(readLockFile(lockPath)?.access).toBeUndefined(); + expect(readLockFile(lockPath)?.publicUrl).toBeUndefined(); + }); + + it("refuses a malformed access field", () => { + const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "public" }; + writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`); + expect(readLockFile(lockPath)).toBeUndefined(); + }); + it("is removed by release() and missing files read as undefined", () => { const handle = acquireLock({ lockPath, diff --git a/test/daemon/auth.test.ts b/test/daemon/auth.test.ts index fdf029a..6bbbe23 100644 --- a/test/daemon/auth.test.ts +++ b/test/daemon/auth.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { mkdtempSync, readFileSync, rmSync, statSync } from "node:fs"; +import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { AuthStore, hashToken, isAllowedOrigin, timingSafeEqualHex } from "../../src/daemon/auth.js"; @@ -127,6 +127,89 @@ describe("auth device store", () => { }); }); +describe("local browser session", () => { + let dir: string; + let path: string; + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "pi2-auth-browser-")); + path = join(dir, "devices.json"); + }); + + afterEach(() => rmSync(dir, { recursive: true, force: true })); + + it("creates exactly one local-browser device with every scope", () => { + const auth = new AuthStore({ path, now: () => 1_000 }); + const session = auth.localBrowserSession(); + + expect(session.device.name).toBe("local browser"); + expect(session.device.kind).toBe("laptop"); + expect(session.device.scopes).toEqual(["read", "steer", "control", "admin"]); + expect(session.device.createdAt).toBe(1_000); + expect(session.device.lastSeenAt).toBe(1_000); + expect(session.device.revokedAt).toBeNull(); + expect(auth.listDevices()).toHaveLength(1); + expect(auth.verifyToken(session.token)?.id).toBe(session.device.id); + }); + + it("reuses the same token across logins, so a second :PiWeb keeps the open tab alive", () => { + const auth = new AuthStore({ path, now: () => 2_000 }); + const first = auth.localBrowserSession(); + const second = auth.localBrowserSession(); + + expect(second.token).toBe(first.token); + expect(second.device.id).toBe(first.device.id); + expect(auth.verifyToken(first.token)?.id).toBe(first.device.id); + expect(auth.listDevices()).toHaveLength(1); + + const persisted = JSON.parse(readFileSync(path, "utf8")) as { + devices: { tokenHash: string; name: string }[]; + }; + expect(persisted.devices).toHaveLength(1); + expect(persisted.devices[0]!.tokenHash).toBe(hashToken(first.token)); + + const tokenPath = join(dir, "local-browser.token"); + expect(readFileSync(tokenPath, "utf8").trim()).toBe(first.token); + expect(statSync(tokenPath).mode & 0o777).toBe(0o600); + }); + + it("mints a new token once the device is revoked", () => { + const auth = new AuthStore({ path, now: () => 3_000 }); + const first = auth.localBrowserSession(); + expect(auth.revokeDevice(first.device.id)).toBe(true); + expect(auth.verifyToken(first.token)).toBeNull(); + + const second = auth.localBrowserSession(); + expect(second.device.id).toBe(first.device.id); + expect(second.device.revokedAt).toBeNull(); + expect(second.token).not.toBe(first.token); + expect(auth.verifyToken(first.token)).toBeNull(); + expect(auth.verifyToken(second.token)?.revokedAt).toBeNull(); + }); + + it("mints a new token when the stored plaintext is missing or stale", () => { + const auth = new AuthStore({ path, now: () => 4_000 }); + const first = auth.localBrowserSession(); + + unlinkSync(join(dir, "local-browser.token")); + const second = auth.localBrowserSession(); + expect(second.token).not.toBe(first.token); + expect(auth.verifyToken(second.token)?.id).toBe(first.device.id); + expect(auth.listDevices()).toHaveLength(1); + }); + + it("survives a store reload with the same token", () => { + const first = new AuthStore({ path }); + const session = first.localBrowserSession(); + const reloaded = new AuthStore({ path }); + expect(reloaded.verifyToken(session.token)?.name).toBe("local browser"); + const again = reloaded.localBrowserSession(); + expect(again.token).toBe(session.token); + expect(again.device.id).toBe(session.device.id); + expect(reloaded.listDevices()).toHaveLength(1); + }); +}); + describe("isAllowedOrigin", () => { const allow = ["http://127.0.0.1:7676", "http://localhost:7676"]; diff --git a/test/daemon/config.test.ts b/test/daemon/config.test.ts index d1ef1cc..d02e74b 100644 --- a/test/daemon/config.test.ts +++ b/test/daemon/config.test.ts @@ -5,13 +5,21 @@ import { loadConfig } from "../../src/config.js"; const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", ".."); +const LOOPBACK = (port: number): string[] => [ + `http://127.0.0.1:${port}`, + `http://localhost:${port}`, + `http://[::1]:${port}`, +]; + describe("loadConfig", () => { - it("uses protocol defaults", () => { + it("uses protocol defaults (access mode local)", () => { const config = loadConfig({}); expect(config.host).toBe("127.0.0.1"); expect(config.port).toBe(7676); + expect(config.access).toBe("local"); + expect(config.publicUrl).toBeNull(); expect(config.staticDir).toBe(join(repoRoot, "web", "dist")); - expect(config.corsOrigins).toEqual(["http://127.0.0.1:7676", "http://localhost:7676"]); + expect(config.corsOrigins).toEqual(LOOPBACK(7676)); expect(config.limits.maxBodyBytes).toBe(8 * 1024 * 1024); expect(config.limits.maxFrameBytes).toBe(8 * 1024 * 1024); expect(config.limits.maxConnections).toBe(64); @@ -19,7 +27,7 @@ describe("loadConfig", () => { expect(config.deviceStorePath).toMatch(/devices\.json$/); }); - it("honours environment overrides", () => { + it("honours environment overrides; PI2_ORIGINS is additive", () => { const config = loadConfig({ PI2_PORT: "0", PI2_HOST: "0.0.0.0", @@ -29,7 +37,9 @@ describe("loadConfig", () => { expect(config.port).toBe(0); expect(config.host).toBe("0.0.0.0"); expect(config.staticDir).toBe("/srv/pi2/web"); - expect(config.corsOrigins).toEqual(["http://a.test", "http://b.test"]); + // Loopback origins stay in place; the extras are appended, normalized, + // and empty entries dropped. + expect(config.corsOrigins).toEqual([...LOOPBACK(0), "http://a.test", "http://b.test"]); }); it("rejects invalid ports", () => { @@ -38,8 +48,80 @@ describe("loadConfig", () => { expect(() => loadConfig({ PI2_PORT: "70000" })).toThrow(/PI2_PORT/); }); - it("derives default origins from the port", () => { + it("derives loopback origins from the port", () => { const config = loadConfig({ PI2_PORT: "8080" }); - expect(config.corsOrigins).toEqual(["http://127.0.0.1:8080", "http://localhost:8080"]); + expect(config.corsOrigins).toEqual(LOOPBACK(8080)); + }); + + it("derives local mode origins without a LAN address", () => { + const config = loadConfig( + { PI2_ACCESS_MODE: "local" }, + { detectLanIp: () => "192.168.2.10" }, + ); + expect(config.access).toBe("local"); + expect(config.host).toBe("127.0.0.1"); + expect(config.corsOrigins).toEqual(LOOPBACK(7676)); + }); + + it("lan mode binds 0.0.0.0 and adds the detected LAN origin", () => { + const config = loadConfig( + { PI2_ACCESS_MODE: "lan" }, + { detectLanIp: () => "192.168.2.10" }, + ); + expect(config.access).toBe("lan"); + expect(config.host).toBe("0.0.0.0"); + expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "http://192.168.2.10:7676"]); + }); + + it("lan mode skips the extra origin when detection fails or throws", () => { + expect( + loadConfig({ PI2_ACCESS_MODE: "lan" }, { detectLanIp: () => null }).corsOrigins, + ).toEqual(LOOPBACK(7676)); + expect( + loadConfig( + { PI2_ACCESS_MODE: "lan" }, + { + detectLanIp: () => { + throw new Error("no interfaces"); + }, + }, + ).corsOrigins, + ).toEqual(LOOPBACK(7676)); + }); + + it("tailscale mode stays on loopback and adds the public URL origin", () => { + const config = loadConfig({ + PI2_ACCESS_MODE: "tailscale", + PI2_PUBLIC_URL: "https://myhost.tail1234.ts.net/", + }); + expect(config.access).toBe("tailscale"); + expect(config.host).toBe("127.0.0.1"); + expect(config.publicUrl).toBe("https://myhost.tail1234.ts.net"); + expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://myhost.tail1234.ts.net"]); + }); + + it("tailscale without PI2_PUBLIC_URL keeps only loopback origins", () => { + const config = loadConfig({ PI2_ACCESS_MODE: "tailscale" }); + expect(config.publicUrl).toBeNull(); + expect(config.corsOrigins).toEqual(LOOPBACK(7676)); + }); + + it("lets PI2_HOST win over the mode default", () => { + expect(loadConfig({ PI2_ACCESS_MODE: "lan", PI2_HOST: "127.0.0.1" }).host).toBe("127.0.0.1"); + expect(loadConfig({ PI2_ACCESS_MODE: "tailscale", PI2_HOST: "0.0.0.0" }).host).toBe("0.0.0.0"); + expect(loadConfig({ PI2_ACCESS_MODE: "local", PI2_HOST: "192.168.2.5" }).host).toBe("192.168.2.5"); + }); + + it("normalizes and de-duplicates explicit origins", () => { + const config = loadConfig({ + PI2_ORIGINS: "https://a.test/, http://127.0.0.1:7676, ,http://a.test", + }); + expect(config.corsOrigins).toEqual([...LOOPBACK(7676), "https://a.test", "http://a.test"]); + }); + + it("fails fast on an unknown access mode", () => { + expect(() => loadConfig({ PI2_ACCESS_MODE: "public" })).toThrow( + "PI2_ACCESS_MODE must be local, lan or tailscale", + ); }); }); diff --git a/test/daemon/console-session.test.ts b/test/daemon/console-session.test.ts new file mode 100644 index 0000000..5f283da --- /dev/null +++ b/test/daemon/console-session.test.ts @@ -0,0 +1,196 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AuthStore } from "../../src/daemon/auth.js"; +import { createApp } from "../../src/daemon/http.js"; +import type { Config } from "../../src/config.js"; +import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js"; +import { createHarness, TEST_LIMITS, type Harness } from "./harness.js"; + +const CLI_TOKEN = "c".repeat(64); + +interface SessionBody { + token: string; + device: { + id: string; + name: string; + kind: string; + scopes: string[]; + createdAt: number; + lastSeenAt: number; + revokedAt: number | null; + }; + url: string; +} + +/** Non-loopback requests only exist behind the socket; drive Hono directly. */ +async function appWithRemoteAddress(config: Config, auth: AuthStore, remoteAddress: string): Promise { + const app = createApp({ + config, + auth, + instances: new FakeInstanceManager(), + workspaces: new FakeWorkspaceStore(), + bus: new FakeBus(), + daemonId: "d-test", + }); + return app.request( + "/api/v1/console/session", + { method: "POST", headers: { authorization: `Bearer ${CLI_TOKEN}` } }, + { incoming: { socket: { remoteAddress } } } as never, + ); +} + +describe("POST /api/v1/console/session", () => { + let h: Harness; + + afterEach(async () => { + await h.cleanup(); + }); + + it("mints a loopback browser session for the local CLI token", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + + const res = await fetch(`${h.url}/api/v1/console/session`, { + method: "POST", + headers: { authorization: `Bearer ${CLI_TOKEN}`, "content-type": "application/json" }, + body: JSON.stringify({}), + }); + expect(res.status).toBe(200); + const body = (await res.json()) as SessionBody; + + expect(body.device.name).toBe("local browser"); + expect(body.device.kind).toBe("laptop"); + expect(body.device.scopes).toEqual(["read", "steer", "control", "admin"]); + expect(body.token.length).toBeGreaterThanOrEqual(40); + expect(body.url).toBe(`http://127.0.0.1:${h.server.port}/#t=${encodeURIComponent(body.token)}`); + expect(body.url).not.toContain("?t="); + expect(h.auth.verifyToken(body.token)?.id).toBe(body.device.id); + // Exactly one device record, and no local-CLI record leaks into it. + expect(h.auth.listDevices().map((device) => device.name)).toEqual(["local browser"]); + }); + + it("accepts an absent body ({} is optional)", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + const res = await fetch(`${h.url}/api/v1/console/session`, { + method: "POST", + headers: { authorization: `Bearer ${CLI_TOKEN}` }, + }); + expect(res.status).toBe(200); + }); + + it("reuses one device and one token across calls, so reopening keeps the tab alive", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + const call = async (): Promise => { + const res = await fetch(`${h.url}/api/v1/console/session`, { + method: "POST", + headers: { authorization: `Bearer ${CLI_TOKEN}` }, + }); + return (await res.json()) as SessionBody; + }; + + const first = await call(); + const second = await call(); + expect(second.device.id).toBe(first.device.id); + expect(second.token).toBe(first.token); + expect(second.url).toBe(first.url); + expect(h.auth.verifyToken(second.token)?.id).toBe(first.device.id); + expect(h.auth.listDevices()).toHaveLength(1); + expect(second.url).toContain(`#t=${encodeURIComponent(second.token)}`); + }); + + it("mints a new token after the local browser is revoked", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + const call = async (): Promise => { + const res = await fetch(`${h.url}/api/v1/console/session`, { + method: "POST", + headers: { authorization: `Bearer ${CLI_TOKEN}` }, + }); + return (await res.json()) as SessionBody; + }; + + const first = await call(); + expect(h.auth.revokeDevice(first.device.id)).toBe(true); + + const second = await call(); + expect(second.device.id).toBe(first.device.id); + expect(second.token).not.toBe(first.token); + expect(h.auth.verifyToken(first.token)).toBeNull(); + expect(h.auth.verifyToken(second.token)?.id).toBe(first.device.id); + }); + + it("answers 401 without a token", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + const res = await fetch(`${h.url}/api/v1/console/session`, { method: "POST" }); + expect(res.status).toBe(401); + expect(((await res.json()) as { code: string }).code).toBe("E_UNAUTHORIZED"); + }); + + it("answers 401 for a paired device token (the CLI token is required)", async () => { + h = await createHarness({ cliToken: CLI_TOKEN }); + const deviceToken = h.createToken("paired phone"); + const res = await fetch(`${h.url}/api/v1/console/session`, { + method: "POST", + headers: { authorization: `Bearer ${deviceToken}` }, + }); + expect(res.status).toBe(401); + }); + + it("answers 403 from a non-loopback client", async () => { + const dir = mkdtempSync(join(tmpdir(), "pi2-console-")); + try { + writeFileSync(join(dir, "cli.token"), `${CLI_TOKEN}\n`, { mode: 0o600 }); + const auth = new AuthStore({ path: join(dir, "devices.json"), localTokenPath: join(dir, "cli.token") }); + const config: Config = { + host: "0.0.0.0", + port: 7676, + staticDir: join(dir, "web"), + corsOrigins: [], + limits: TEST_LIMITS, + tokenPath: join(dir, "d.sock.token"), + deviceStorePath: join(dir, "devices.json"), + access: "lan", + publicUrl: null, + }; + + for (const remoteAddress of ["192.168.2.50", "100.101.102.103"]) { + const res = await appWithRemoteAddress(config, auth, remoteAddress); + expect(res.status).toBe(403); + const body = (await res.json()) as { code: string; message: string }; + expect(body.code).toBe("E_FORBIDDEN"); + expect(body.message).toBe("console login is loopback-only"); + } + // No device was created by the rejected calls. + expect(auth.listDevices()).toEqual([]); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe("GET /api/v1/info access fields", () => { + it("reports access always and publicUrl as string|null", async () => { + const h = await createHarness({ config: { access: "tailscale", publicUrl: "https://host.ts.net" } }); + try { + const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record; + expect(body.access).toBe("tailscale"); + expect(body.publicUrl).toBe("https://host.ts.net"); + // Existing keys survive. + expect(body.v).toBe(1); + expect(body.port).toBe(h.server.port); + } finally { + await h.cleanup(); + } + }); + + it("keeps the local default", async () => { + const h = await createHarness(); + try { + const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record; + expect(body.access).toBe("local"); + expect(body.publicUrl).toBeNull(); + } finally { + await h.cleanup(); + } + }); +}); diff --git a/test/daemon/harness.ts b/test/daemon/harness.ts index 9cd5f04..20fd452 100644 --- a/test/daemon/harness.ts +++ b/test/daemon/harness.ts @@ -26,6 +26,8 @@ export function testConfig(overrides: Partial = {}): Config { limits: TEST_LIMITS, tokenPath: "/tmp/pi2-daemon-test.sock.token", deviceStorePath: "/tmp/pi2-daemon-test-devices.json", + access: "local", + publicUrl: null, }; return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; } @@ -35,6 +37,8 @@ export interface HarnessOptions { seedInstances?: string[]; config?: Partial; staticFiles?: Record; + /** Written to `/cli.token` and accepted by the daemon's AuthStore. */ + cliToken?: string; heartbeatMs?: number; wsOverrides?: { maxBufferedBytes?: number; @@ -74,7 +78,16 @@ export async function createHarness(options: HarnessOptions = {}): Promise