feat(cli): add pi2 open, pi2 pairing --public-url and the access check

`pi2 open [--print] [--no-browser]` mints a loopback browser session and hands
the URL to the platform opener without waiting for it, so "open the console" is
one command that never hangs. `pi2 pairing --public-url` (or `daemon.json.publicUrl`
/ `PI2_PUBLIC_URL`) rebuilds the printed URL and QR payload for a tailnet or
reverse-proxy base.

`pi2 doctor` gains an `access` check: ok on loopback, warn for `lan`/`tailscale`,
fail when a non-loopback bind has neither a public URL nor TLS.
This commit is contained in:
yuez committed 2026-10-23 08:34:48 +08:00
1 parent 01db49fb38
commit 9ab0830223
5 files changed
+385 -16

No files matched your search

+54
View File
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
checkAccess,
checkCliToken,
checkLinger,
checkNvim,
@@ -31,6 +32,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 },
serviceManager: { name: "systemd", available: true },
linger: { checked: true, enabled: true },
webDist: { path: "/repo/web/dist", exists: true },
@@ -60,6 +62,7 @@ describe("doctor checks (all passing)", () => {
"socket",
"daemon",
"port",
"access",
"service-manager",
"linger",
"web-dist",
@@ -80,6 +83,56 @@ 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)" });
});
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("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("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("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 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(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);
});
});
describe("doctor failure cases", () => {
it("fails on node < 22", async () => {
const report = await checks({ nodeVersion: "v20.11.0" });
@@ -262,6 +315,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.serviceManager).toEqual({ name: "systemd", available: true });
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
expect(ctx.webDist.path).toBe(join(dir, "web"));
+105 -1
View File
@@ -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, runPairing, runStatus } from "../../src/cli/pi2.js";
import { CliError, createClient, main, 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";
@@ -54,6 +54,7 @@ interface FakeData {
resources?: Record<string, unknown>;
health?: Record<string, unknown>;
pair?: Record<string, unknown>;
session?: Record<string, unknown>;
postError?: Error;
}
@@ -96,6 +97,9 @@ function fakeClient(data: FakeData = {}): DaemonClient & { calls: string[] } {
if (path === "/api/v1/pair") {
return { status: 202, body: data.pair ?? { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } };
}
if (path === "/api/v1/console/session") {
return { status: 200, body: data.session ?? { token: "browser-token", url: "http://127.0.0.1:7712/#t=browser-token" } };
}
throw new CliError(`unexpected POST ${path}`);
},
};
@@ -353,6 +357,106 @@ describe("pi2 pairing", () => {
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");
});
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");
});
});
describe("pi2 open", () => {
it("--print posts the console session and prints only the URL", async () => {
const lines: string[] = [];
const client = fakeClient({
session: { token: "tok", url: "http://127.0.0.1:7712/#t=tok" },
});
const code = await runOpen({ client, print: (line) => lines.push(line), printOnly: true });
expect(code).toBe(0);
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
expect(client.calls).toEqual(["/api/v1/console/session {}"]);
});
it("--print implies --no-browser (never launches an opener)", async () => {
const lines: string[] = [];
const opens: string[] = [];
const code = await runOpen({
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
print: (line) => lines.push(line),
printOnly: true,
openUrl: (url) => opens.push(url),
});
expect(code).toBe(0);
expect(opens).toEqual([]);
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
});
it("launches the opener with the URL", async () => {
const opens: string[] = [];
const lines: string[] = [];
const code = await runOpen({
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
print: (line) => lines.push(line),
openUrl: (url) => opens.push(url),
});
expect(code).toBe(0);
expect(opens).toEqual(["http://127.0.0.1:7712/#t=tok"]);
expect(lines).toEqual([]);
});
it("prints the URL and still exits 0 when the opener fails", async () => {
const lines: string[] = [];
const code = await runOpen({
client: fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
print: (line) => lines.push(line),
openUrl: (_url, onError) => onError(),
});
expect(code).toBe(0);
expect(lines).toEqual(["http://127.0.0.1:7712/#t=tok"]);
});
it("routes `pi2 open --print` through main", async () => {
const out: string[] = [];
const code = await main(["open", "--print"], {
out: (line) => out.push(line),
client: () => fakeClient({ session: { url: "http://127.0.0.1:7712/#t=tok" } }),
});
expect(code).toBe(0);
expect(out).toEqual(["http://127.0.0.1:7712/#t=tok"]);
});
it("exits 1 with the daemon-resolution message when no daemon runs", async () => {
const err: string[] = [];
const code = await main(["open", "--print"], {
err: (line) => err.push(line),
client: () => {
throw new CliError("no running pi2 daemon (…/daemon.json missing). Start it with `pi2 daemon`.");
},
});
expect(code).toBe(1);
expect(err[0]).toContain("no running pi2 daemon");
});
});
describe("pi2 doctor (daemon probe wiring)", () => {