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

+84 -1
View File
@@ -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"];
+88 -6
View File
@@ -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",
);
});
});
+196
View File
@@ -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<Response> {
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<SessionBody> => {
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<SessionBody> => {
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<string, unknown>;
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<string, unknown>;
expect(body.access).toBe("local");
expect(body.publicUrl).toBeNull();
} finally {
await h.cleanup();
}
});
});
+14 -1
View File
@@ -26,6 +26,8 @@ export function testConfig(overrides: Partial<Config> = {}): 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<Config>;
staticFiles?: Record<string, string>;
/** Written to `<dir>/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<Harne
writeFileSync(target, content);
}
const auth = new AuthStore({ path: join(dir, "devices.json"), baseUrl: "http://127.0.0.1:0" });
const auth = new AuthStore({
path: join(dir, "devices.json"),
baseUrl: "http://127.0.0.1:0",
...(options.cliToken === undefined
? {}
: { localTokenPath: join(dir, "cli.token") }),
});
if (options.cliToken !== undefined) {
writeFileSync(join(dir, "cli.token"), `${options.cliToken}\n`, { mode: 0o600 });
}
const instances = new FakeInstanceManager();
for (const workspaceId of options.seedInstances ?? []) instances.addWorkspace(workspaceId);
const workspaces = new FakeWorkspaceStore(options.workspaces ?? []);