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:
1 parent
9eb857465c
commit
01db49fb38
11 files changed
+690
-26
No files matched your search
+104
-1
@@ -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
@@ -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");
|
||||
|
||||
Reference in new issue
Block a user