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:
1 parent
3789394c85
commit
a57c874095
34 files changed
+2157
-488
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { AuthStore, LOCAL_CLI_DEVICE_ID, SCOPES } from "../../src/daemon/auth.js";
|
||||
import { AuthStore, LOCAL_CLI_DEVICE_ID } from "../../src/daemon/auth.js";
|
||||
import { writeCliToken } from "../../src/cli/token.js";
|
||||
import { removeDir, tempDir } from "./helpers.js";
|
||||
|
||||
@@ -27,8 +27,6 @@ describe("AuthStore local CLI token", () => {
|
||||
expect(device!.id).toBe(LOCAL_CLI_DEVICE_ID);
|
||||
expect(device!.id).toBe("local-cli");
|
||||
expect(device!.name).toBe("local CLI");
|
||||
expect(device!.scopes).toEqual([...SCOPES]);
|
||||
expect(device!.scopes).toEqual(["read", "steer", "control", "admin"]);
|
||||
expect(device!.revokedAt).toBeNull();
|
||||
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
|
||||
});
|
||||
@@ -71,7 +69,7 @@ describe("AuthStore local CLI token", () => {
|
||||
it("keeps paired devices working and never lists the synthetic one", () => {
|
||||
writeCliToken(tokenPath);
|
||||
const auth = new AuthStore({ path: storePath, localTokenPath: tokenPath });
|
||||
const { token } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read"] });
|
||||
const { token } = auth.createDevice({ name: "Pixel", kind: "phone" });
|
||||
|
||||
expect(auth.verifyToken(token)?.name).toBe("Pixel");
|
||||
expect(auth.listDevices().map((device) => device.id)).not.toContain(LOCAL_CLI_DEVICE_ID);
|
||||
|
||||
+31
-40
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
checkAccess,
|
||||
checkBind,
|
||||
checkCliToken,
|
||||
checkCurl,
|
||||
checkLinger,
|
||||
@@ -39,7 +39,7 @@ function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
|
||||
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
|
||||
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
|
||||
port: { configured: 7676, bound: true },
|
||||
access: { mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null },
|
||||
bind: { host: "127.0.0.1", port: 7676, publicUrl: null },
|
||||
serviceManager: { name: "systemd", available: true },
|
||||
linger: { checked: true, enabled: true },
|
||||
webDist: { path: "/repo/web/dist", exists: true },
|
||||
@@ -70,7 +70,7 @@ describe("doctor checks (all passing)", () => {
|
||||
"socket",
|
||||
"daemon",
|
||||
"port",
|
||||
"access",
|
||||
"bind",
|
||||
"service-manager",
|
||||
"linger",
|
||||
"web-dist",
|
||||
@@ -91,53 +91,44 @@ describe("doctor checks (all passing)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("doctor access check", () => {
|
||||
it("is ok for local mode", () => {
|
||||
const check = checkAccess({ mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null });
|
||||
expect(check).toEqual({ name: "access", status: "ok", detail: "local (loopback only)" });
|
||||
describe("doctor bind check", () => {
|
||||
it("is ok for a loopback bind", () => {
|
||||
const check = checkBind({ host: "127.0.0.1", port: 7676, publicUrl: null });
|
||||
expect(check).toEqual({ name: "bind", status: "ok", detail: "127.0.0.1/7676 (loopback only)" });
|
||||
});
|
||||
|
||||
it("warns for lan/tailscale with a TLS-terminated public URL", () => {
|
||||
const lan = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: "https://host.ts.net" });
|
||||
expect(lan.status).toBe("warn");
|
||||
expect(lan.detail).toBe("lan (bind 0.0.0.0/7676, public https://host.ts.net)");
|
||||
expect(lan.detail).not.toContain("no TLS");
|
||||
|
||||
const tailscale = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "https://host.ts.net" });
|
||||
expect(tailscale.status).toBe("warn");
|
||||
expect(tailscale.detail).toBe("tailscale (bind 127.0.0.1/7676, public https://host.ts.net)");
|
||||
it("warns with the no-TLS hint for the default wildcard bind", () => {
|
||||
const check = checkBind({ host: "0.0.0.0", port: 7676, publicUrl: null });
|
||||
expect(check.status).toBe("warn");
|
||||
expect(check.detail).toContain("all interfaces/7676");
|
||||
expect(check.detail).toContain("no TLS");
|
||||
expect(check.detail).toContain("PI2_HOST=127.0.0.1");
|
||||
// A warn keeps the overall report ok — the default posture is not a failure.
|
||||
expect(check.status).not.toBe("fail");
|
||||
});
|
||||
|
||||
it("adds the no-TLS hint when the public URL is missing or plain http", () => {
|
||||
const loopback = checkAccess({ mode: "lan", host: "127.0.0.1", port: 7676, publicUrl: null });
|
||||
expect(loopback.status).toBe("warn");
|
||||
expect(loopback.detail).toContain("lan (bind 127.0.0.1/7676)");
|
||||
expect(loopback.detail).toContain("no TLS, prefer `tailscale serve`");
|
||||
|
||||
const plain = checkAccess({ mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: "http://host.ts.net" });
|
||||
expect(plain.status).toBe("warn");
|
||||
expect(plain.detail).toContain("no TLS, prefer `tailscale serve`");
|
||||
it("is ok behind an https public URL", () => {
|
||||
const check = checkBind({ host: "0.0.0.0", port: 7676, publicUrl: "https://host.ts.net" });
|
||||
expect(check).toEqual({
|
||||
name: "bind",
|
||||
status: "ok",
|
||||
detail: "all interfaces/7676, public https://host.ts.net",
|
||||
});
|
||||
});
|
||||
|
||||
it("fails when a non-loopback bind has no public URL", () => {
|
||||
const check = checkAccess({ mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null });
|
||||
expect(check).toEqual({ name: "access", status: "fail", detail: "lan (bind 0.0.0.0/7676)" });
|
||||
|
||||
const tailscale = checkAccess({ mode: "tailscale", host: "100.64.0.1", port: 7676, publicUrl: null });
|
||||
expect(tailscale.status).toBe("fail");
|
||||
it("still warns for a plain-http public URL", () => {
|
||||
const check = checkBind({ host: "192.168.11.7", port: 7676, publicUrl: "http://host.ts.net" });
|
||||
expect(check.status).toBe("warn");
|
||||
expect(check.detail).toContain("192.168.11.7/7676");
|
||||
expect(check.detail).toContain("no TLS");
|
||||
});
|
||||
|
||||
it("is wired into the default probe list after port", async () => {
|
||||
const report = await checks({ access: { mode: "tailscale", host: "127.0.0.1", port: 7676, publicUrl: null } });
|
||||
const report = await checks({ bind: { host: "0.0.0.0", port: 7676, publicUrl: null } });
|
||||
const names = report.checks.map((check) => check.name);
|
||||
expect(names.indexOf("access")).toBe(names.indexOf("port") + 1);
|
||||
expect(statusOf(report, "access")).toBe("warn");
|
||||
// A warn keeps the overall report ok.
|
||||
expect(names.indexOf("bind")).toBe(names.indexOf("port") + 1);
|
||||
expect(statusOf(report, "bind")).toBe("warn");
|
||||
expect(report.ok).toBe(true);
|
||||
|
||||
const failed = await checks({ access: { mode: "lan", host: "0.0.0.0", port: 7676, publicUrl: null } });
|
||||
expect(statusOf(failed, "access")).toBe("fail");
|
||||
expect(failed.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -379,7 +370,7 @@ describe("collectContext", () => {
|
||||
expect(ctx.socket.exists).toBe(true);
|
||||
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
|
||||
expect(ctx.port).toEqual({ configured: 7712, bound: true });
|
||||
expect(ctx.access).toEqual({ mode: "local", host: "127.0.0.1", port: 7712, publicUrl: null });
|
||||
expect(ctx.bind).toEqual({ host: "0.0.0.0", port: 7712, publicUrl: null });
|
||||
expect(ctx.serviceManager).toEqual({ name: "systemd", available: true });
|
||||
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
|
||||
expect(ctx.webDist.path).toBe(join(dir, "web"));
|
||||
|
||||
@@ -28,7 +28,6 @@ export function testConfig(overrides: Partial<Config> = {}): 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 ?? {}) } };
|
||||
|
||||
+11
-7
@@ -183,33 +183,37 @@ describe("daemon.json", () => {
|
||||
handle.release();
|
||||
});
|
||||
|
||||
it("carries the optional access/publicUrl fields and stays readable without them", () => {
|
||||
it("carries the optional host/publicUrl fields and stays readable without them", () => {
|
||||
const handle = acquireLock({
|
||||
lockPath,
|
||||
payload: {
|
||||
port: 7676,
|
||||
daemonId: "d-access",
|
||||
daemonId: "d-bind",
|
||||
startedAt: 5,
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
access: "tailscale",
|
||||
host: "0.0.0.0",
|
||||
publicUrl: "https://host.ts.net",
|
||||
},
|
||||
bootId: () => BOOT,
|
||||
});
|
||||
expect(readLockFile(lockPath)?.access).toBe("tailscale");
|
||||
expect(readLockFile(lockPath)?.host).toBe("0.0.0.0");
|
||||
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)?.host).toBeUndefined();
|
||||
expect(readLockFile(lockPath)?.publicUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it("refuses a malformed access field", () => {
|
||||
const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "public" };
|
||||
it("ignores a legacy access field and refuses a malformed host", () => {
|
||||
const legacy = { ...payload(), pid: process.pid, bootId: BOOT, access: "tailscale" };
|
||||
writeFileSync(lockPath, `${JSON.stringify(legacy)}\n`);
|
||||
expect(readLockFile(lockPath)?.host).toBeUndefined();
|
||||
|
||||
const malformed = { ...payload(), pid: process.pid, bootId: BOOT, host: 7676 };
|
||||
writeFileSync(lockPath, `${JSON.stringify(malformed)}\n`);
|
||||
expect(readLockFile(lockPath)).toBeUndefined();
|
||||
});
|
||||
|
||||
|
||||
+63
-29
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
|
||||
import { basename, join } from "node:path";
|
||||
import type { DaemonClient } from "../../src/cli/pi2.js";
|
||||
import { CliError, createClient, main, resolveEndpoint, runAttach, runDoctorCommand, runOpen, runPairing, runStatus } from "../../src/cli/pi2.js";
|
||||
import { CliError, createClient, main, renderTerminalQr, resolveEndpoint, runAttach, runDoctorCommand, runOpen, runPairing, runStatus } from "../../src/cli/pi2.js";
|
||||
import { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js";
|
||||
import { writeCliToken } from "../../src/cli/token.js";
|
||||
import type { WorkspaceInfo } from "../../src/protocol/types.js";
|
||||
@@ -339,50 +339,84 @@ describe("pi2 status", () => {
|
||||
});
|
||||
|
||||
describe("pi2 pairing", () => {
|
||||
it("posts with the local token and prints url, code and qr payload", async () => {
|
||||
const minted = (overrides: Record<string, unknown> = {}) => ({
|
||||
accepted: true,
|
||||
code: "ABCD2345",
|
||||
url: "http://192.168.2.10:7712/pair/ABCD2345",
|
||||
expiresAt: Date.now() + 600_000,
|
||||
nonce: "abc123",
|
||||
qr: {
|
||||
version: 2,
|
||||
ecc: "M",
|
||||
mask: 3,
|
||||
size: 25,
|
||||
// A checkerboard keeps the terminal renderer honest: dark modules exist.
|
||||
rows: Array.from({ length: 25 }, (_, y) =>
|
||||
Array.from({ length: 25 }, (_, x) => ((x + y) % 2 === 0 ? "1" : "0")).join(""),
|
||||
),
|
||||
},
|
||||
bases: [
|
||||
{ kind: "lan", name: "wlan0", address: "192.168.2.10", url: "http://192.168.2.10:7712" },
|
||||
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7712" },
|
||||
],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
it("prints the url, the code, the expiry and a terminal QR", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } });
|
||||
const client = fakeClient({ pair: minted() });
|
||||
|
||||
const code = await runPairing({ client, print: (line) => lines.push(line) });
|
||||
|
||||
expect(code).toBe(0);
|
||||
const text = lines.join("\n");
|
||||
expect(text).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
|
||||
expect(text).toContain("url http://192.168.2.10:7712/pair/ABCD2345");
|
||||
expect(text).toContain("code ABCD2345");
|
||||
expect(text).toContain('"code":"ABCD2345"');
|
||||
expect(text).toContain('"v":1');
|
||||
expect(text).toMatch(/expires in \d+s/);
|
||||
// 25 modules + 2 modules of quiet zone a side = 29 module rows, two per
|
||||
// text row → 15 rows, of which the first and last are pure quiet zone.
|
||||
expect(lines.filter((line) => /[█▀▄]/.test(line))).toHaveLength(13);
|
||||
expect(lines.some((line) => line.includes("wlan0"))).toBe(true);
|
||||
expect(client.calls[0]).toBe("/api/v1/pair {}");
|
||||
});
|
||||
|
||||
it("passes --base through so the operator can pin the interface", async () => {
|
||||
const client = fakeClient({ pair: minted() });
|
||||
|
||||
await main(["pairing", "--base", "http://127.0.0.1:7712"], { out: () => {}, client: () => client });
|
||||
|
||||
expect(client.calls[0]).toBe('/api/v1/pair {"base":"http://127.0.0.1:7712"}');
|
||||
});
|
||||
|
||||
it("prints a note instead of a QR when the daemon cannot encode the link", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: minted({ qr: null }) });
|
||||
|
||||
await runPairing({ client, print: (line) => lines.push(line) });
|
||||
|
||||
expect(lines.join("\n")).toContain("too long");
|
||||
expect(lines.some((line) => /[█▀▄]/.test(line))).toBe(false);
|
||||
});
|
||||
|
||||
it("exits non-zero when the daemon rejects the request", async () => {
|
||||
await expect(
|
||||
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
|
||||
).rejects.toThrowError(/E_UNAUTHORIZED/);
|
||||
});
|
||||
});
|
||||
|
||||
it("rebuilds the URL on --public-url when given", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await runPairing({ client, print: (line) => lines.push(line), publicUrl: "https://myhost.tail1234.ts.net/" });
|
||||
const text = lines.join("\n");
|
||||
expect(text).toContain("url https://myhost.tail1234.ts.net/pair/ABCD2345");
|
||||
expect(text).toContain('"url":"https://myhost.tail1234.ts.net/pair/ABCD2345"');
|
||||
expect(text).toContain("code ABCD2345");
|
||||
describe("renderTerminalQr", () => {
|
||||
it("packs two module rows per line and adds the quiet zone", () => {
|
||||
const lines = renderTerminalQr(["10", "01"]);
|
||||
// 2 modules + 2+2 quiet zone = 6 columns; (2 + 4) rows → 3 text rows.
|
||||
expect(lines).toHaveLength(3);
|
||||
expect(lines.every((line) => line.length === 6)).toBe(true);
|
||||
expect(lines.join("")).not.toMatch(/[01]/);
|
||||
expect(lines[1]).toBe(" ▀▄ ");
|
||||
});
|
||||
|
||||
it("defaults --public-url to daemon.json's publicUrl", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await main(["pairing"], {
|
||||
out: (line) => lines.push(line),
|
||||
client: () => ({ ...client, daemon: { ...DAEMON, publicUrl: "https://from-daemon.ts.net" } }),
|
||||
});
|
||||
expect(lines.join("\n")).toContain("url https://from-daemon.ts.net/pair/ABCD2345");
|
||||
});
|
||||
|
||||
it("keeps the loopback URL without flags", async () => {
|
||||
const lines: string[] = [];
|
||||
const client = fakeClient({ pair: { accepted: true, code: "ABCD2345" } });
|
||||
await main(["pairing"], { out: (line) => lines.push(line), client: () => client });
|
||||
expect(lines.join("\n")).toContain("url http://127.0.0.1:7712/pair/ABCD2345");
|
||||
it("returns nothing for an empty matrix", () => {
|
||||
expect(renderTerminalQr([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ describe("wireDaemon", () => {
|
||||
|
||||
expect(server.port).toBeGreaterThan(0);
|
||||
expect(wired.config.port).toBe(server.port);
|
||||
expect(wired.config.host).toBe("127.0.0.1");
|
||||
expect(wired.config.host).toBe("0.0.0.0");
|
||||
expect(wired.deps.daemonId).toMatch(/^d-/);
|
||||
expect(wired.deps.instances).toBe(wired.instanceManager);
|
||||
expect(wired.deps.workspaces).toBe(wired.workspaceStore);
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
|
||||
import {
|
||||
classifyAddress,
|
||||
isLoopbackHost,
|
||||
isVirtualInterface,
|
||||
isWildcardHost,
|
||||
localOrigins,
|
||||
networkBases,
|
||||
primaryBase,
|
||||
} from "../../src/core/network.js";
|
||||
|
||||
const ipv4 = (address: string, overrides: Partial<NetworkInterfaceInfo> = {}): NetworkInterfaceInfo => ({
|
||||
address,
|
||||
netmask: "255.255.255.0",
|
||||
family: "IPv4",
|
||||
mac: "00:00:00:00:00:00",
|
||||
internal: false,
|
||||
cidr: `${address}/24`,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const HOST: NodeJS.Dict<NetworkInterfaceInfo[]> = {
|
||||
lo: [ipv4("127.0.0.1", { internal: true })],
|
||||
wlan0: [ipv4("192.168.11.7")],
|
||||
docker0: [ipv4("172.17.0.1")],
|
||||
eth1: [ipv4("203.0.113.9")],
|
||||
tailscale0: [ipv4("100.64.0.14")],
|
||||
"br-1234": [ipv4("172.18.0.1")],
|
||||
};
|
||||
|
||||
describe("address classification", () => {
|
||||
it("maps an interface to the base kind a human would expect", () => {
|
||||
expect(classifyAddress("wlan0", "192.168.11.7")).toBe("lan");
|
||||
expect(classifyAddress("eth1", "203.0.113.9")).toBe("other");
|
||||
expect(classifyAddress("tailscale0", "100.64.0.14")).toBe("tailscale");
|
||||
expect(classifyAddress("utun3", "10.1.2.3")).toBe("lan");
|
||||
expect(classifyAddress("lo", "127.0.0.1")).toBe("loopback");
|
||||
});
|
||||
|
||||
it("recognises loopback and wildcard binds", () => {
|
||||
for (const host of ["127.0.0.1", "127.1.2.3", "::1", "localhost", ""]) {
|
||||
expect(isLoopbackHost(host), host).toBe(true);
|
||||
}
|
||||
for (const host of ["0.0.0.0", "::", "", "[::]"]) {
|
||||
expect(isWildcardHost(host), host).toBe(true);
|
||||
}
|
||||
expect(isLoopbackHost("0.0.0.0")).toBe(false);
|
||||
expect(isWildcardHost("192.168.11.7")).toBe(false);
|
||||
});
|
||||
|
||||
it("treats container and tunnel interfaces as virtual", () => {
|
||||
for (const name of ["docker0", "veth1234", "br-1234", "virbr0", "tun0", "wg0", "tailscale0"]) {
|
||||
expect(isVirtualInterface(name), name).toBe(true);
|
||||
}
|
||||
for (const name of ["wlan0", "eth0", "enp3s0", "wlp2s0"]) {
|
||||
expect(isVirtualInterface(name), name).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("networkBases", () => {
|
||||
it("orders public → lan → other → tailscale, physical before virtual", () => {
|
||||
const bases = networkBases({ port: 7676, bindHost: "0.0.0.0", interfaces: HOST });
|
||||
expect(bases.map((base) => `${base.kind}:${base.name}`)).toEqual([
|
||||
"lan:wlan0",
|
||||
"lan:br-1234",
|
||||
"lan:docker0",
|
||||
"other:eth1",
|
||||
"tailscale:tailscale0",
|
||||
"loopback:loopback",
|
||||
]);
|
||||
expect(bases[0]!.url).toBe("http://192.168.11.7:7676");
|
||||
});
|
||||
|
||||
it("puts the configured public URL first", () => {
|
||||
const bases = networkBases({
|
||||
port: 7676,
|
||||
bindHost: "0.0.0.0",
|
||||
publicUrl: "https://host.tail1234.ts.net/",
|
||||
interfaces: HOST,
|
||||
});
|
||||
expect(bases[0]).toEqual({
|
||||
kind: "public",
|
||||
name: "public-url",
|
||||
address: "",
|
||||
url: "https://host.tail1234.ts.net",
|
||||
});
|
||||
});
|
||||
|
||||
it("skips link-local addresses entirely", () => {
|
||||
const bases = networkBases({
|
||||
port: 7676,
|
||||
bindHost: "0.0.0.0",
|
||||
interfaces: { eth0: [ipv4("169.254.10.1")] },
|
||||
});
|
||||
expect(bases.map((base) => base.kind)).toEqual(["loopback"]);
|
||||
});
|
||||
|
||||
it("advertises only loopback for a loopback bind but keeps the public URL", () => {
|
||||
expect(networkBases({ port: 7676, bindHost: "127.0.0.1", interfaces: HOST })).toEqual([
|
||||
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7676" },
|
||||
]);
|
||||
const withPublic = networkBases({
|
||||
port: 7676,
|
||||
bindHost: "127.0.0.1",
|
||||
publicUrl: "https://host.ts.net",
|
||||
interfaces: HOST,
|
||||
});
|
||||
expect(withPublic.map((base) => base.kind)).toEqual(["public", "loopback"]);
|
||||
});
|
||||
|
||||
it("advertises the pinned address plus loopback for a specific bind", () => {
|
||||
const bases = networkBases({ port: 7676, bindHost: "192.168.11.7", interfaces: HOST });
|
||||
expect(bases.map((base) => base.url)).toEqual(["http://192.168.11.7:7676", "http://127.0.0.1:7676"]);
|
||||
});
|
||||
|
||||
it("falls back to loopback when the host has no NICs", () => {
|
||||
const bases = networkBases({ port: 7676, bindHost: "0.0.0.0", interfaces: {} });
|
||||
expect(bases).toEqual([
|
||||
{ kind: "loopback", name: "loopback", address: "127.0.0.1", url: "http://127.0.0.1:7676" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("picks the first base as the default advertisement", () => {
|
||||
expect(primaryBase({ port: 7676, bindHost: "0.0.0.0", interfaces: HOST }).url).toBe("http://192.168.11.7:7676");
|
||||
expect(primaryBase({ port: 7676, bindHost: "127.0.0.1", interfaces: HOST }).url).toBe("http://127.0.0.1:7676");
|
||||
});
|
||||
});
|
||||
|
||||
describe("localOrigins", () => {
|
||||
it("covers every reachable address plus the loopback aliases", () => {
|
||||
const origins = localOrigins({ port: 8080, bindHost: "0.0.0.0", interfaces: HOST });
|
||||
expect(origins).toContain("http://192.168.11.7:8080");
|
||||
expect(origins).toContain("http://100.64.0.14:8080");
|
||||
expect(origins).toContain("http://127.0.0.1:8080");
|
||||
expect(origins).toContain("http://localhost:8080");
|
||||
expect(origins).toContain("http://[::1]:8080");
|
||||
expect(origins.some((origin) => origin.includes("169.254"))).toBe(false);
|
||||
});
|
||||
|
||||
it("reduces the public URL to its origin", () => {
|
||||
const origins = localOrigins({
|
||||
port: 8080,
|
||||
bindHost: "0.0.0.0",
|
||||
publicUrl: "https://host.ts.net/some/path?x=1",
|
||||
interfaces: {},
|
||||
});
|
||||
expect(origins).toContain("https://host.ts.net");
|
||||
expect(origins).not.toContain("https://host.ts.net/some/path?x=1");
|
||||
});
|
||||
|
||||
it("keeps a loopback bind private", () => {
|
||||
expect(localOrigins({ port: 8080, bindHost: "127.0.0.1", interfaces: HOST })).toEqual([
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost:8080",
|
||||
"http://[::1]:8080",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
capacityBytes,
|
||||
encodeQr,
|
||||
fitsQr,
|
||||
MAX_VERSION,
|
||||
MIN_VERSION,
|
||||
versionSpecs,
|
||||
} from "../../src/core/qr.js";
|
||||
|
||||
/** Render `rows` as a scaled PBM so an external decoder can read it back. */
|
||||
function toPbm(rows: string[], scale = 5, quiet = 4): string {
|
||||
const size = rows.length;
|
||||
const total = (size + quiet * 2) * scale;
|
||||
const out: string[] = ["P1", `${total} ${total}`];
|
||||
for (let y = 0; y < total; y += 1) {
|
||||
const row = rows[Math.floor(y / scale) - quiet];
|
||||
const cells: string[] = [];
|
||||
for (let x = 0; x < total; x += 1) {
|
||||
const col = Math.floor(x / scale) - quiet;
|
||||
cells.push(row !== undefined && col >= 0 && col < size && row[col] === "1" ? "1" : "0");
|
||||
}
|
||||
out.push(cells.join(" "));
|
||||
}
|
||||
return `${out.join("\n")}\n`;
|
||||
}
|
||||
|
||||
function decoder<T>(command: string, args: string[], input?: string): T | undefined {
|
||||
try {
|
||||
const result = spawnSync(command, args, { encoding: "utf8", input, timeout: 5_000 });
|
||||
return result.status === 0 ? (result.stdout as T) : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const hasImageToolchain = (): boolean => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi2-qr-"));
|
||||
try {
|
||||
writeFileSync(join(dir, "probe.pbm"), "P1\n1 1\n0\n");
|
||||
return (
|
||||
decoder<string>("magick", [join(dir, "probe.pbm"), join(dir, "probe.png")]) !== undefined &&
|
||||
decoder<number>("zbarimg", ["--version"]) !== undefined
|
||||
);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
};
|
||||
|
||||
describe("qr encoder", () => {
|
||||
it("keeps every version table internally consistent", () => {
|
||||
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
|
||||
const spec = versionSpecs()[version];
|
||||
expect(spec, `version ${version}`).toBeDefined();
|
||||
const data = spec!.groups.reduce((total, group) => total + group.count * group.dataCodewords, 0);
|
||||
const blocks = spec!.groups.reduce((total, group) => total + group.count, 0);
|
||||
expect(data + blocks * spec!.ecCodewordsPerBlock, `version ${version} codewords`).toBe(spec!.totalCodewords);
|
||||
}
|
||||
});
|
||||
|
||||
it("shapes the symbol and only reports dark/light modules", () => {
|
||||
const qr = encodeQr("http://192.168.2.10:7676/pair/ABCD2345");
|
||||
expect(qr.ecc).toBe("M");
|
||||
expect(qr.size).toBe(qr.version * 4 + 17);
|
||||
expect(qr.rows).toHaveLength(qr.size);
|
||||
for (const row of qr.rows) {
|
||||
expect(row).toHaveLength(qr.size);
|
||||
expect(row).toMatch(/^[01]+$/);
|
||||
}
|
||||
expect(qr.mask).toBeGreaterThanOrEqual(0);
|
||||
expect(qr.mask).toBeLessThanOrEqual(7);
|
||||
});
|
||||
|
||||
it("grows the version only when the previous one no longer fits", () => {
|
||||
for (let version = MIN_VERSION; version <= MAX_VERSION; version += 1) {
|
||||
expect(encodeQr("a".repeat(capacityBytes(version))).version).toBe(version);
|
||||
if (version < MAX_VERSION) {
|
||||
expect(encodeQr("a".repeat(capacityBytes(version) + 1)).version).toBeGreaterThan(version);
|
||||
}
|
||||
}
|
||||
expect(encodeQr("a".repeat(capacityBytes(MAX_VERSION))).version).toBe(MAX_VERSION);
|
||||
});
|
||||
|
||||
it("refuses payloads beyond the largest symbol", () => {
|
||||
const tooBig = "a".repeat(capacityBytes(MAX_VERSION) + 1);
|
||||
expect(fitsQr(tooBig)).toBe(false);
|
||||
expect(() => encodeQr(tooBig)).toThrow(/do not fit/);
|
||||
expect(fitsQr("a".repeat(capacityBytes(MAX_VERSION)))).toBe(true);
|
||||
});
|
||||
|
||||
it("measures capacity in UTF-8 bytes, not characters", () => {
|
||||
expect(fitsQr("扫一扫配对")).toBe(true);
|
||||
// 6 characters, 18 UTF-8 bytes: too wide for a version-1 symbol (14 bytes).
|
||||
expect(encodeQr("扫一扫配对").version).toBe(2);
|
||||
expect(encodeQr("扫码").version).toBe(1);
|
||||
// Three bytes per character: the version has to account for the encoding.
|
||||
expect(encodeQr("扫".repeat(capacityBytes(1))).version).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("honours forced version and mask overrides", () => {
|
||||
expect(encodeQr("hello", { version: 5 }).version).toBe(5);
|
||||
for (let mask = 0; mask <= 7; mask += 1) {
|
||||
expect(encodeQr("hello", { mask }).mask).toBe(mask);
|
||||
}
|
||||
expect(() => encodeQr("hello", { version: 0 })).toThrow(/version/);
|
||||
expect(() => encodeQr("hello", { mask: 8 })).toThrow(/mask/);
|
||||
});
|
||||
|
||||
it("is deterministic", () => {
|
||||
const first = encodeQr("https://myhost.tail1234.ts.net/pair/ZZZZ9999");
|
||||
const second = encodeQr("https://myhost.tail1234.ts.net/pair/ZZZZ9999");
|
||||
expect(second).toEqual(first);
|
||||
});
|
||||
|
||||
it("matches the recorded matrices (decoded with zbarimg when the change landed)", () => {
|
||||
// The hashes pin the whole symbol — data, EC, interleaving, mask choice
|
||||
// and format/version bits. Each one was round-tripped through
|
||||
// `magick` + `zbarimg` before being written down.
|
||||
const golden = [
|
||||
{
|
||||
text: "pi2 pairing",
|
||||
version: 1,
|
||||
mask: 2,
|
||||
sha: "96c5668a81f06621d3db59a1d33b703a6d1c4f7ff51db8ae61a9f84f8c13821c",
|
||||
},
|
||||
{
|
||||
text: "http://192.168.2.10:7676/pair/ABCD2345",
|
||||
version: 3,
|
||||
mask: 4,
|
||||
sha: "709a345cb1f9efaf69c839aea177da472921a8a964d27220076e9924d28f11fc",
|
||||
},
|
||||
{
|
||||
text: "https://myhost.tail1234.ts.net/pair/ZZZZ9999",
|
||||
version: 4,
|
||||
mask: 4,
|
||||
sha: "5b42b9ac0c90756e0db86c4941538ebe49809b5319299fb098813d219d627798",
|
||||
},
|
||||
];
|
||||
for (const expected of golden) {
|
||||
const qr = encodeQr(expected.text);
|
||||
expect(qr.version, expected.text).toBe(expected.version);
|
||||
expect(qr.mask, expected.text).toBe(expected.mask);
|
||||
expect(createHash("sha256").update(qr.rows.join("\n")).digest("hex"), expected.text).toBe(expected.sha);
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(!hasImageToolchain())("round-trips through a real decoder", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "pi2-qr-"));
|
||||
try {
|
||||
const payloads = [
|
||||
"http://192.168.2.10:7676/pair/ABCD2345",
|
||||
"https://myhost.tail1234.ts.net/pair/ZZZZ9999",
|
||||
"扫一扫配对:pi2",
|
||||
"x".repeat(capacityBytes(10)),
|
||||
];
|
||||
for (const [index, payload] of payloads.entries()) {
|
||||
writeFileSync(join(dir, "qr.pbm"), toPbm(encodeQr(payload).rows));
|
||||
expect(decoder<string>("magick", [join(dir, "qr.pbm"), join(dir, `qr-${index}.png`)]), "render").toBeDefined();
|
||||
const decoded = decoder<string>("zbarimg", ["--raw", "-q", join(dir, `qr-${index}.png`)]).replace(/\n$/, "");
|
||||
expect(decoded, payload).toBe(payload);
|
||||
}
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -18,13 +18,12 @@ describe("auth device store", () => {
|
||||
|
||||
it("creates a device, persists its hash and never leaks it", () => {
|
||||
const auth = new AuthStore({ path });
|
||||
const { token, device } = auth.createDevice({ name: "Pixel", kind: "phone", scopes: ["read", "steer"] });
|
||||
const { token, device } = auth.createDevice({ name: "Pixel", kind: "phone" });
|
||||
|
||||
expect(token.length).toBeGreaterThanOrEqual(40);
|
||||
expect(device.id).toMatch(/^dev-/);
|
||||
expect(device.name).toBe("Pixel");
|
||||
expect(device.kind).toBe("phone");
|
||||
expect(device.scopes).toEqual(["read", "steer"]);
|
||||
expect((device as unknown as Record<string, unknown>).tokenHash).toBeUndefined();
|
||||
|
||||
const persisted = JSON.parse(readFileSync(path, "utf8")) as {
|
||||
@@ -93,12 +92,11 @@ describe("auth device store", () => {
|
||||
|
||||
it("redeems a pairing code exactly once", () => {
|
||||
let now = 1_700_000_000_000;
|
||||
const auth = new AuthStore({ path, now: () => now, baseUrl: "http://127.0.0.1:7676" });
|
||||
const auth = new AuthStore({ path, now: () => now });
|
||||
const pair = auth.pairCreate({ ttlSec: 600 });
|
||||
|
||||
expect(pair.code).toMatch(/^[A-Z0-9]{8}$/);
|
||||
expect(pair.nonce).toMatch(/^[0-9a-f]+$/);
|
||||
expect(pair.url).toContain(pair.code);
|
||||
expect(pair.expiresAt).toBe(now + 600_000);
|
||||
|
||||
const redeemed = auth.pairRedeem({ code: pair.code, deviceName: "Pixel", kind: "phone" });
|
||||
@@ -138,13 +136,12 @@ describe("local browser session", () => {
|
||||
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
it("creates exactly one local-browser device with every scope", () => {
|
||||
it("creates exactly one local-browser device", () => {
|
||||
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();
|
||||
|
||||
+63
-74
@@ -1,7 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadConfig } from "../../src/config.js";
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import { DEFAULT_HOST, loadConfig } from "../../src/config.js";
|
||||
import { localOrigins } from "../../src/core/network.js";
|
||||
|
||||
const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
||||
|
||||
@@ -11,12 +13,22 @@ const LOOPBACK = (port: number): string[] => [
|
||||
`http://[::1]:${port}`,
|
||||
];
|
||||
|
||||
const ipv4 = (address: string, overrides: Partial<NetworkInterfaceInfo> = {}): NetworkInterfaceInfo => ({
|
||||
address,
|
||||
netmask: "255.255.255.0",
|
||||
family: "IPv4",
|
||||
mac: "00:00:00:00:00:00",
|
||||
internal: false,
|
||||
cidr: `${address}/24`,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("loadConfig", () => {
|
||||
it("uses protocol defaults (access mode local)", () => {
|
||||
const config = loadConfig({});
|
||||
expect(config.host).toBe("127.0.0.1");
|
||||
it("uses protocol defaults and binds every interface", () => {
|
||||
const config = loadConfig({}, { interfaces: {} });
|
||||
expect(DEFAULT_HOST).toBe("0.0.0.0");
|
||||
expect(config.host).toBe("0.0.0.0");
|
||||
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(LOOPBACK(7676));
|
||||
@@ -28,14 +40,17 @@ describe("loadConfig", () => {
|
||||
});
|
||||
|
||||
it("honours environment overrides; PI2_ORIGINS is additive", () => {
|
||||
const config = loadConfig({
|
||||
PI2_PORT: "0",
|
||||
PI2_HOST: "0.0.0.0",
|
||||
PI2_STATIC_DIR: "/srv/pi2/web",
|
||||
PI2_ORIGINS: "http://a.test, http://b.test ,,",
|
||||
});
|
||||
const config = loadConfig(
|
||||
{
|
||||
PI2_PORT: "0",
|
||||
PI2_HOST: "127.0.0.1",
|
||||
PI2_STATIC_DIR: "/srv/pi2/web",
|
||||
PI2_ORIGINS: "http://a.test, http://b.test ,,",
|
||||
},
|
||||
{ interfaces: {} },
|
||||
);
|
||||
expect(config.port).toBe(0);
|
||||
expect(config.host).toBe("0.0.0.0");
|
||||
expect(config.host).toBe("127.0.0.1");
|
||||
expect(config.staticDir).toBe("/srv/pi2/web");
|
||||
// Loopback origins stay in place; the extras are appended, normalized,
|
||||
// and empty entries dropped.
|
||||
@@ -48,80 +63,54 @@ describe("loadConfig", () => {
|
||||
expect(() => loadConfig({ PI2_PORT: "70000" })).toThrow(/PI2_PORT/);
|
||||
});
|
||||
|
||||
it("derives loopback origins from the port", () => {
|
||||
const config = loadConfig({ PI2_PORT: "8080" });
|
||||
expect(config.corsOrigins).toEqual(LOOPBACK(8080));
|
||||
});
|
||||
|
||||
it("derives local mode origins without a LAN address", () => {
|
||||
it("allows every local IPv4 origin at the bound port", () => {
|
||||
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");
|
||||
},
|
||||
{ PI2_PORT: "8080" },
|
||||
{
|
||||
interfaces: {
|
||||
lo: [ipv4("127.0.0.1", { internal: true })],
|
||||
wlan0: [ipv4("192.168.11.7"), ipv4("169.254.10.1")],
|
||||
tailscale0: [ipv4("100.64.0.14")],
|
||||
},
|
||||
).corsOrigins,
|
||||
).toEqual(LOOPBACK(7676));
|
||||
},
|
||||
);
|
||||
// Loopback aliases plus each reachable address; link-local is skipped.
|
||||
for (const origin of [...LOOPBACK(8080), "http://192.168.11.7:8080", "http://100.64.0.14:8080"]) {
|
||||
expect(config.corsOrigins).toContain(origin);
|
||||
}
|
||||
expect(config.corsOrigins).toHaveLength(LOOPBACK(8080).length + 2);
|
||||
});
|
||||
|
||||
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");
|
||||
it("narrows the bind on PI2_HOST", () => {
|
||||
const config = loadConfig({ PI2_HOST: "127.0.0.1" }, { interfaces: { wlan0: [ipv4("192.168.11.7")] } });
|
||||
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();
|
||||
// A loopback-only daemon is unreachable from the LAN, so the allowlist
|
||||
// must not advertise an address nothing is listening on.
|
||||
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("adds the public URL origin and keeps loopback", () => {
|
||||
const config = loadConfig({ PI2_PUBLIC_URL: "https://myhost.tail1234.ts.net/" }, { interfaces: {} });
|
||||
expect(config.publicUrl).toBe("https://myhost.tail1234.ts.net");
|
||||
expect(config.corsOrigins).toContain("https://myhost.tail1234.ts.net");
|
||||
for (const origin of LOOPBACK(7676)) expect(config.corsOrigins).toContain(origin);
|
||||
});
|
||||
|
||||
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"]);
|
||||
const config = loadConfig(
|
||||
{ PI2_ORIGINS: "https://a.test/, http://127.0.0.1:7676, ,http://a.test" },
|
||||
{ interfaces: {} },
|
||||
);
|
||||
expect(config.corsOrigins.filter((origin) => origin.endsWith("a.test"))).toEqual([
|
||||
"https://a.test",
|
||||
"http://a.test",
|
||||
]);
|
||||
expect(config.corsOrigins.filter((origin) => origin === "http://127.0.0.1:7676")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("fails fast on an unknown access mode", () => {
|
||||
expect(() => loadConfig({ PI2_ACCESS_MODE: "public" })).toThrow(
|
||||
"PI2_ACCESS_MODE must be local, lan or tailscale",
|
||||
);
|
||||
it("derives only loopback origins for link-local addresses", () => {
|
||||
expect(
|
||||
localOrigins({ port: 7676, bindHost: "0.0.0.0", interfaces: { wlan0: [ipv4("169.254.10.1")] } }),
|
||||
).toEqual(LOOPBACK(7676));
|
||||
});
|
||||
});
|
||||
@@ -16,7 +16,6 @@ interface SessionBody {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
scopes: string[];
|
||||
createdAt: number;
|
||||
lastSeenAt: number;
|
||||
revokedAt: number | null;
|
||||
@@ -61,7 +60,6 @@ describe("POST /api/v1/console/session", () => {
|
||||
|
||||
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=");
|
||||
@@ -149,7 +147,6 @@ describe("POST /api/v1/console/session", () => {
|
||||
limits: TEST_LIMITS,
|
||||
tokenPath: join(dir, "d.sock.token"),
|
||||
deviceStorePath: join(dir, "devices.json"),
|
||||
access: "lan",
|
||||
publicUrl: null,
|
||||
};
|
||||
|
||||
@@ -168,12 +165,12 @@ describe("POST /api/v1/console/session", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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" } });
|
||||
describe("GET /api/v1/info bind fields", () => {
|
||||
it("reports the bind host always and publicUrl as string|null", async () => {
|
||||
const h = await createHarness({ config: { host: "127.0.0.1", 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.host).toBe("127.0.0.1");
|
||||
expect(body.publicUrl).toBe("https://host.ts.net");
|
||||
// Existing keys survive.
|
||||
expect(body.v).toBe(1);
|
||||
@@ -183,11 +180,11 @@ describe("GET /api/v1/info access fields", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the local default", async () => {
|
||||
const h = await createHarness();
|
||||
it("reports the default wildcard bind", async () => {
|
||||
const h = await createHarness({ config: { host: "0.0.0.0" } });
|
||||
try {
|
||||
const body = (await (await fetch(`${h.url}/api/v1/info`)).json()) as Record<string, unknown>;
|
||||
expect(body.access).toBe("local");
|
||||
expect(body.host).toBe("0.0.0.0");
|
||||
expect(body.publicUrl).toBeNull();
|
||||
} finally {
|
||||
await h.cleanup();
|
||||
|
||||
@@ -26,7 +26,6 @@ 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 ?? {}) } };
|
||||
@@ -80,7 +79,6 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
|
||||
|
||||
const auth = new AuthStore({
|
||||
path: join(dir, "devices.json"),
|
||||
baseUrl: "http://127.0.0.1:0",
|
||||
...(options.cliToken === undefined
|
||||
? {}
|
||||
: { localTokenPath: join(dir, "cli.token") }),
|
||||
|
||||
+85
-13
@@ -317,30 +317,102 @@ describe("HTTP API", () => {
|
||||
expect(h.auth.verifyToken(token)).toBeNull();
|
||||
});
|
||||
|
||||
it("redeems a pairing code over HTTP", async () => {
|
||||
const pair = h.auth.pairCreate();
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, {
|
||||
/** `POST /api/v1/pair/redeem` — the public half of pairing (ADR 0001 §3). */
|
||||
async function redeem(code: string, kind = "phone"): Promise<Response> {
|
||||
return fetch(`${h.url}/api/v1/pair/redeem`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
|
||||
body: JSON.stringify({ code, deviceName: "Pixel", kind }),
|
||||
});
|
||||
}
|
||||
|
||||
it("redeems a pairing code over the public endpoint, once", async () => {
|
||||
const pair = h.auth.pairCreate();
|
||||
const res = await redeem(pair.code);
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { token: string; device: { name: string } };
|
||||
const body = (await res.json()) as { token: string; device: { name: string; scopes?: unknown } };
|
||||
expect(body.device.name).toBe("Pixel");
|
||||
expect(body.device.scopes).toBeUndefined();
|
||||
expect(h.auth.verifyToken(body.token)?.name).toBe("Pixel");
|
||||
|
||||
const replay = await fetch(`${h.url}/api/v1/pair`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ code: pair.code, deviceName: "Pixel", kind: "phone" }),
|
||||
});
|
||||
expect(replay.status).toBe(401);
|
||||
expect((await redeem(pair.code)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("creates a pairing code for an authenticated client", async () => {
|
||||
it("rate limits repeated redeem attempts", async () => {
|
||||
// The default budget is 5/minute per client; the 6th attempt is refused
|
||||
// before it can touch the code store.
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
expect((await redeem("ZZZZZZZZ")).status).toBe(401);
|
||||
}
|
||||
const limited = await redeem("ZZZZZZZZ");
|
||||
expect(limited.status).toBe(429);
|
||||
expect(limited.headers.get("retry-after")).toMatch(/^\d+$/);
|
||||
const body = (await limited.json()) as { code: string };
|
||||
expect(body.code).toBe(ERROR_CODES.RATE_LIMITED);
|
||||
});
|
||||
|
||||
it("mints a code, its QR matrix and every usable base for an authenticated client", async () => {
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }));
|
||||
expect(res.status).toBe(200);
|
||||
const body = (await res.json()) as { code: string; url: string; expiresAt: number };
|
||||
const body = (await res.json()) as {
|
||||
code: string;
|
||||
url: string;
|
||||
expiresAt: number;
|
||||
nonce: string;
|
||||
qr: { version: number; ecc: string; size: number; rows: string[] } | null;
|
||||
bases: { kind: string; name: string; url: string }[];
|
||||
};
|
||||
expect(body.code).toMatch(/^[A-Z0-9]{8}$/);
|
||||
expect(body.url).toContain(body.code);
|
||||
expect(body.url).toContain(`/pair/${body.code}`);
|
||||
expect(body.expiresAt).toBeGreaterThan(Date.now());
|
||||
expect(body.nonce).toMatch(/^[0-9a-f]{32}$/);
|
||||
expect(body.qr).not.toBeNull();
|
||||
expect(body.qr!.size).toBe(body.qr!.version * 4 + 17);
|
||||
expect(body.qr!.rows).toHaveLength(body.qr!.size);
|
||||
expect(body.qr!.rows.every((row) => row.length === body.qr!.size && /^[01]+$/.test(row))).toBe(true);
|
||||
expect(body.bases.length).toBeGreaterThan(0);
|
||||
expect(body.bases.every((base) => typeof base.url === "string" && base.url.startsWith("http"))).toBe(true);
|
||||
// The chosen URL is always one of the offered bases.
|
||||
expect(body.bases.some((base) => body.url.startsWith(base.url))).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a base it offered and rejects a foreign one", async () => {
|
||||
const first = (await (await fetch(`${h.url}/api/v1/pair`, authed({ method: "POST", body: "{}" }))).json()) as {
|
||||
bases: { url: string }[];
|
||||
};
|
||||
const chosen = first.bases.at(-1)!.url;
|
||||
|
||||
const ok = await fetch(
|
||||
`${h.url}/api/v1/pair`,
|
||||
authed({ method: "POST", body: JSON.stringify({ base: chosen }) }),
|
||||
);
|
||||
expect(ok.status).toBe(200);
|
||||
const minted = (await ok.json()) as { url: string };
|
||||
expect(minted.url.startsWith(chosen)).toBe(true);
|
||||
|
||||
const foreign = await fetch(
|
||||
`${h.url}/api/v1/pair`,
|
||||
authed({ method: "POST", body: JSON.stringify({ base: "http://evil.example:9999" }) }),
|
||||
);
|
||||
expect(foreign.status).toBe(400);
|
||||
});
|
||||
|
||||
it("requires a token to mint a code", async () => {
|
||||
const res = await fetch(`${h.url}/api/v1/pair`, { method: "POST", body: "{}" });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("redirects a scanned /pair/<code> link to the zero-input connect page", async () => {
|
||||
const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" });
|
||||
expect(res.status).toBe(302);
|
||||
const location = res.headers.get("location") ?? "";
|
||||
expect(location).toContain("/connect?");
|
||||
expect(location).toContain("code=ABCD2345");
|
||||
expect(location).toContain("auto=1");
|
||||
|
||||
// A malformed code still lands on the console, just without a code.
|
||||
const malformed = await fetch(`${h.url}/pair/nope!`, { redirect: "manual" });
|
||||
expect(malformed.status).toBe(302);
|
||||
expect(malformed.headers.get("location")).not.toContain("code=");
|
||||
expect(malformed.headers.get("location")).toContain("auto=1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PairRateLimiter } from "../../src/daemon/rate-limit.js";
|
||||
|
||||
/** A limiter whose clock the test drives, so windows slide without sleeping. */
|
||||
function limiter(rules = { perClient: { limit: 3, windowMs: 1_000 }, global: { limit: 10, windowMs: 10_000 } }) {
|
||||
let now = 1_000;
|
||||
const instance = new PairRateLimiter(rules, { now: () => now });
|
||||
return { instance, advance: (ms: number) => (now += ms) };
|
||||
}
|
||||
|
||||
describe("PairRateLimiter", () => {
|
||||
it("allows the budget and refuses the next attempt", () => {
|
||||
const { instance } = limiter();
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(true);
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(true);
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(true);
|
||||
|
||||
const blocked = instance.check("1.2.3.4");
|
||||
expect(blocked.allowed).toBe(false);
|
||||
expect(blocked.retryAfterMs).toBeGreaterThan(0);
|
||||
expect(blocked.retryAfterMs).toBeLessThanOrEqual(1_000);
|
||||
});
|
||||
|
||||
it("recovers once the window slides", () => {
|
||||
const { instance, advance } = limiter();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(false);
|
||||
|
||||
advance(1_001);
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps per-client budgets separate", () => {
|
||||
const { instance } = limiter();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(false);
|
||||
expect(instance.check("5.6.7.8").allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("applies the global budget across clients", () => {
|
||||
const { instance } = limiter({ perClient: { limit: 5, windowMs: 1_000 }, global: { limit: 3, windowMs: 10_000 } });
|
||||
expect(instance.check("a").allowed).toBe(true);
|
||||
expect(instance.check("b").allowed).toBe(true);
|
||||
expect(instance.check("c").allowed).toBe(true);
|
||||
// A brand-new client is still refused: the global window is full.
|
||||
const blocked = instance.check("d");
|
||||
expect(blocked.allowed).toBe(false);
|
||||
expect(blocked.retryAfterMs).toBeLessThanOrEqual(10_000);
|
||||
});
|
||||
|
||||
it("forgets every window on reset", () => {
|
||||
const { instance } = limiter();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("1.2.3.4");
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(false);
|
||||
instance.reset();
|
||||
expect(instance.check("1.2.3.4").allowed).toBe(true);
|
||||
});
|
||||
|
||||
it("treats an empty client key as one bucket", () => {
|
||||
const { instance } = limiter();
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) instance.check("");
|
||||
expect(instance.check("unknown").allowed).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user