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:
1 parent
01db49fb38
commit
9ab0830223
5 files changed
+385
-16
No files matched your search
+58
-6
@@ -111,9 +111,11 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
|||||||
| Variable | Default | Meaning |
|
| Variable | Default | Meaning |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `PI2_PORT` | `7676` | HTTP/WS port, `0` = ephemeral |
|
| `PI2_PORT` | `7676` | HTTP/WS port, `0` = ephemeral |
|
||||||
| `PI2_HOST` | `127.0.0.1` | bind address |
|
| `PI2_HOST` | `127.0.0.1` (`0.0.0.0` in `lan` mode) | bind address; wins over the mode default |
|
||||||
|
| `PI2_ACCESS_MODE` | `local` | `local` / `lan` / `tailscale` (see below) |
|
||||||
|
| `PI2_PUBLIC_URL` | – | external base URL, e.g. `https://myhost.tail1234.ts.net` (no trailing slash) |
|
||||||
|
| `PI2_ORIGINS` | – | **extra** CORS/Origin allowlist entries (comma separated), added to the derived origins |
|
||||||
| `PI2_STATIC_DIR` | `<repo>/web/dist` | built web UI |
|
| `PI2_STATIC_DIR` | `<repo>/web/dist` | built web UI |
|
||||||
| `PI2_ORIGINS` | `http://127.0.0.1:<port>,http://localhost:<port>` | CORS/Origin allowlist (comma separated) |
|
|
||||||
| `PI2_RUNTIME_DIR` | Linux `$XDG_RUNTIME_DIR/pi2`, macOS `~/Library/Caches/pi2/run` | sockets, lock, tokens |
|
| `PI2_RUNTIME_DIR` | Linux `$XDG_RUNTIME_DIR/pi2`, macOS `~/Library/Caches/pi2/run` | sockets, lock, tokens |
|
||||||
| `PI2_DATA_DIR` | Linux `$XDG_DATA_HOME/pi2`, macOS `~/Library/Application Support/pi2` | `devices.json`, `workspaces.json` |
|
| `PI2_DATA_DIR` | Linux `$XDG_DATA_HOME/pi2`, macOS `~/Library/Application Support/pi2` | `devices.json`, `workspaces.json` |
|
||||||
| `PI2_STATE_DIR` | Linux `$XDG_STATE_HOME/pi2`, macOS `~/Library/Logs/pi2` | instance logs |
|
| `PI2_STATE_DIR` | Linux `$XDG_STATE_HOME/pi2`, macOS `~/Library/Logs/pi2` | instance logs |
|
||||||
@@ -126,6 +128,22 @@ Everything is environment-driven (`src/config.ts` + `src/core/paths.ts`):
|
|||||||
|
|
||||||
There is no config file: the environment *is* the configuration.
|
There is no config file: the environment *is* the configuration.
|
||||||
|
|
||||||
|
### Access modes
|
||||||
|
|
||||||
|
| `PI2_ACCESS_MODE` | bind (unless `PI2_HOST`) | derived `corsOrigins` |
|
||||||
|
|---|---|---|
|
||||||
|
| `local` (default) | `127.0.0.1` | `http://127.0.0.1:<port>`, `http://localhost:<port>`, `http://[::1]:<port>` |
|
||||||
|
| `lan` | `0.0.0.0` | loopback three **plus** `http://<detected-lan-ip>:<port>` |
|
||||||
|
| `tailscale` | `127.0.0.1` | loopback three **plus** the origin of `PI2_PUBLIC_URL` |
|
||||||
|
|
||||||
|
Origins are normalized (trailing `/` stripped, empties dropped) and
|
||||||
|
`PI2_ORIGINS` is appended — never a replacement. LAN detection is best effort:
|
||||||
|
when the address is unknown that extra origin is simply skipped. `tailscale`
|
||||||
|
assumes `tailscale serve` terminates TLS in front of the loopback daemon; the
|
||||||
|
daemon never does TLS itself. An unknown mode fails startup with one line:
|
||||||
|
`pi2: PI2_ACCESS_MODE must be local, lan or tailscale`. Changing the mode
|
||||||
|
requires restarting `pi2 daemon`.
|
||||||
|
|
||||||
## 5. Runtime files
|
## 5. Runtime files
|
||||||
|
|
||||||
All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|
All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|
||||||
@@ -134,7 +152,7 @@ All of these live in `PI2_RUNTIME_DIR` (created `0700`):
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `d.sock` | `0600` | plugin ↔ daemon JSONL socket (nvim dials it) |
|
| `d.sock` | `0600` | plugin ↔ daemon JSONL socket (nvim dials it) |
|
||||||
| `d.sock.token` | `0600` | handshake token for `hello`; rotated per daemon start |
|
| `d.sock.token` | `0600` | handshake token for `hello`; rotated per daemon start |
|
||||||
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion}` |
|
| `daemon.lock` | `0600` | singleton lock: `{pid, bootId, port, daemonId, startedAt, protocolVersion, access?, publicUrl?}` |
|
||||||
| `daemon.json` | `0600` | same payload, written **after** `listen()` so tools learn the real port |
|
| `daemon.json` | `0600` | same payload, written **after** `listen()` so tools learn the real port |
|
||||||
| `cli.token` | `0600` | 32-byte hex local admin token, rotated per daemon start |
|
| `cli.token` | `0600` | 32-byte hex local admin token, rotated per daemon start |
|
||||||
|
|
||||||
@@ -178,6 +196,20 @@ a token; everything else under `/api/*` needs `Authorization: Bearer …`.
|
|||||||
Unknown `/api/*` paths answer `401` when unauthenticated and `404` when
|
Unknown `/api/*` paths answer `401` when unauthenticated and `404` when
|
||||||
authenticated (auth runs before routing).
|
authenticated (auth runs before routing).
|
||||||
|
|
||||||
|
### Local-browser login (`POST /api/v1/console/session`)
|
||||||
|
|
||||||
|
`pi2 open` calls this endpoint (loopback **and** local CLI token required) to
|
||||||
|
sign the browser in without a pairing code: it rotates the single
|
||||||
|
`local browser` device (`kind:"laptop"`, all four scopes) and answers
|
||||||
|
`{token, device, url}` with
|
||||||
|
`url = http://127.0.0.1:<actual bound port>/#t=<token>`. The token lives in the
|
||||||
|
fragment, so it never reaches a request line, a `Referer` header or a proxy
|
||||||
|
access log, and the daemon never logs it. Every call rotates the token (same
|
||||||
|
device `id`) and invalidates the previous URL.
|
||||||
|
|
||||||
|
Non-loopback callers get `403 E_FORBIDDEN` (`console login is loopback-only`);
|
||||||
|
remote browsers pair instead (see §8.5).
|
||||||
|
|
||||||
## 8. The `pi2` CLI
|
## 8. The `pi2` CLI
|
||||||
|
|
||||||
`pi2` discovers the daemon from `daemon.json` (port) and `cli.token` (auth) in
|
`pi2` discovers the daemon from `daemon.json` (port) and `cli.token` (auth) in
|
||||||
@@ -240,6 +272,7 @@ object `{daemon, instances, resources, health}`.
|
|||||||
| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers |
|
| `socket` | `d.sock` missing (and no daemon) | missing but daemon answers |
|
||||||
| `daemon` | `/api/v1/info` unreachable | – |
|
| `daemon` | `/api/v1/info` unreachable | – |
|
||||||
| `port` | – (reports bound/free) | – |
|
| `port` | – (reports bound/free) | – |
|
||||||
|
| `access` | `lan`/`tailscale` with a non-loopback bind and no `PI2_PUBLIC_URL` | `lan`/`tailscale` (adds `— no TLS, prefer \`tailscale serve\`` without an `https:` public URL) |
|
||||||
| `service-manager` | – | systemd/launchd not found |
|
| `service-manager` | – | systemd/launchd not found |
|
||||||
| `linger` (Linux) | – | `Linger=no` |
|
| `linger` (Linux) | – | `Linger=no` |
|
||||||
| `web-dist` | – | missing |
|
| `web-dist` | – | missing |
|
||||||
@@ -249,7 +282,21 @@ object `{daemon, instances, resources, health}`.
|
|||||||
only `fail` makes `ok:false`/exit `1`. All probes are injectable, so the checks
|
only `fail` makes `ok:false`/exit `1`. All probes are injectable, so the checks
|
||||||
are unit tested without touching the host.
|
are unit tested without touching the host.
|
||||||
|
|
||||||
### 8.4 `pi2 pairing`
|
### 8.4 `pi2 open [--print] [--no-browser]`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pi2 open # mint a loopback session and open the browser, signed in
|
||||||
|
pi2 open --print # print the signed-in URL only (implies --no-browser)
|
||||||
|
pi2 open --no-browser # print the URL instead of launching a browser
|
||||||
|
```
|
||||||
|
|
||||||
|
Resolves `daemon.json` + `cli.token`, `POST`s `/api/v1/console/session`, then
|
||||||
|
launches `xdg-open` (Linux) / `open` (macOS) detached. The opener never blocks
|
||||||
|
the command: if it is missing or fails, `pi2 open` prints the URL and still
|
||||||
|
exits `0`. This is a local-only shortcut; use `pi2 pairing` for LAN/Tailscale
|
||||||
|
browsers.
|
||||||
|
|
||||||
|
### 8.5 `pi2 pairing [--public-url <url>]`
|
||||||
|
|
||||||
`POST /api/v1/pair` with the local token and prints:
|
`POST /api/v1/pair` with the local token and prints:
|
||||||
|
|
||||||
@@ -262,9 +309,12 @@ qr {"v":1,"code":"ABCD2345","url":"…","expiresAt":…,"nonce":"…"}
|
|||||||
|
|
||||||
The URL is rebuilt from the *actual* daemon base URL because the daemon's own
|
The URL is rebuilt from the *actual* daemon base URL because the daemon's own
|
||||||
`url` field is derived from the configured port (stale after a retry or
|
`url` field is derived from the configured port (stale after a retry or
|
||||||
`--port 0`).
|
`--port 0`). `--public-url <url>` rebuilds both the printed `url` and the QR
|
||||||
|
payload's `url` on that base (e.g. `https://host.ts.net/pair/ABCD2345`); it
|
||||||
|
defaults to `daemon.json`'s `publicUrl`, then `PI2_PUBLIC_URL`. The code, expiry
|
||||||
|
and nonce are unchanged.
|
||||||
|
|
||||||
### 8.5 `pi2 install-service` / `pi2 uninstall-service`
|
### 8.6 `pi2 install-service` / `pi2 uninstall-service`
|
||||||
|
|
||||||
See [§9](#9-services-systemd--launchd). `--dry-run` (default) prints the file
|
See [§9](#9-services-systemd--launchd). `--dry-run` (default) prints the file
|
||||||
and the follow-up commands; `--write` writes the file (`0644`) and prints the
|
and the follow-up commands; `--write` writes the file (`0644`) and prints the
|
||||||
@@ -373,6 +423,8 @@ debugging.
|
|||||||
| `401 E_UNAUTHORIZED` from `curl` | send `Authorization: Bearer $(cat $PI2_RUNTIME_DIR/cli.token)` |
|
| `401 E_UNAUTHORIZED` from `curl` | send `Authorization: Bearer $(cat $PI2_RUNTIME_DIR/cli.token)` |
|
||||||
| `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) |
|
| `EADDRINUSE` on an explicit port | pick another `--port` (only the default port retries) |
|
||||||
| `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) |
|
| `403` with the browser console | origin not in `PI2_ORIGINS` (derived from the port) |
|
||||||
|
| `pi2 open` → `403 console login is loopback-only` | the request came from a non-loopback address; pair the device instead |
|
||||||
|
| `pi2 doctor` → `access FAIL` | `PI2_ACCESS_MODE=lan/tailscale` binds a non-loopback address without `PI2_PUBLIC_URL`; set it or use `tailscale serve` |
|
||||||
| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` |
|
| `health: static=FAIL` | `web/dist` missing — build the web UI or set `PI2_STATIC_DIR` |
|
||||||
| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project |
|
| Browser console loads but no workspaces | no nvim with the plugin has connected yet; run `pi2 attach` in a project |
|
||||||
| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout |
|
| `pi2 doctor` → `plugin FAIL` | install pi2.nvim, or point `PI2_PLUGIN_DIR` at the checkout |
|
||||||
|
|||||||
+50
-1
@@ -11,7 +11,7 @@ import { homedir, platform as osPlatform } from "node:os";
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { DEFAULT_PORT } from "../config.js";
|
import { DEFAULT_PORT, loadConfig, type AccessMode } from "../config.js";
|
||||||
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
|
import { daemonSocketPath, runtimeDir } from "../core/paths.js";
|
||||||
import { PROTOCOL_VERSION } from "../protocol/types.js";
|
import { PROTOCOL_VERSION } from "../protocol/types.js";
|
||||||
import { formatTable } from "./util.js";
|
import { formatTable } from "./util.js";
|
||||||
@@ -43,6 +43,13 @@ export interface BinaryProbe {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AccessModeContext {
|
||||||
|
mode: AccessMode;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
publicUrl: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface DoctorContext {
|
export interface DoctorContext {
|
||||||
platform: NodeJS.Platform;
|
platform: NodeJS.Platform;
|
||||||
nodeVersion: string;
|
nodeVersion: string;
|
||||||
@@ -54,6 +61,7 @@ export interface DoctorContext {
|
|||||||
socket: { path: string; exists: boolean };
|
socket: { path: string; exists: boolean };
|
||||||
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
|
daemon: { reachable: boolean; port?: number; protocolVersion?: number; error?: string };
|
||||||
port: { configured: number; bound: boolean };
|
port: { configured: number; bound: boolean };
|
||||||
|
access: AccessModeContext;
|
||||||
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
|
serviceManager: { name: "systemd" | "launchd"; available: boolean; detail?: string };
|
||||||
linger: { checked: boolean; enabled?: boolean; detail?: string };
|
linger: { checked: boolean; enabled?: boolean; detail?: string };
|
||||||
webDist: { path: string; exists: boolean };
|
webDist: { path: string; exists: boolean };
|
||||||
@@ -182,6 +190,30 @@ export function checkPort(probe: DoctorContext["port"]): DoctorCheck {
|
|||||||
return { name: "port", status: "ok", detail: `${probe.configured} free` };
|
return { name: "port", status: "ok", detail: `${probe.configured} free` };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isLoopbackHost(host: string): boolean {
|
||||||
|
return host === "127.0.0.1" || host === "::1" || host === "localhost";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `access`: local is fine; lan/tailscale warn because the daemon has no TLS of
|
||||||
|
* its own, and fail when a non-loopback bind is exposed without a public URL.
|
||||||
|
*/
|
||||||
|
export function checkAccess(probe: AccessModeContext): DoctorCheck {
|
||||||
|
if (probe.mode === "local") return { name: "access", status: "ok", detail: "local (loopback only)" };
|
||||||
|
|
||||||
|
const publicSuffix = probe.publicUrl === null ? "" : `, public ${probe.publicUrl}`;
|
||||||
|
const detail = `${probe.mode} (bind ${probe.host}/${probe.port}${publicSuffix})`;
|
||||||
|
if (probe.publicUrl === null && !isLoopbackHost(probe.host)) {
|
||||||
|
return { name: "access", status: "fail", detail };
|
||||||
|
}
|
||||||
|
const tls = probe.publicUrl !== null && probe.publicUrl.startsWith("https:");
|
||||||
|
return {
|
||||||
|
name: "access",
|
||||||
|
status: "warn",
|
||||||
|
detail: tls ? detail : `${detail} — no TLS, prefer \`tailscale serve\``,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function checkServiceManager(probe: DoctorContext["serviceManager"]): DoctorCheck {
|
export function checkServiceManager(probe: DoctorContext["serviceManager"]): DoctorCheck {
|
||||||
return {
|
return {
|
||||||
name: "service-manager",
|
name: "service-manager",
|
||||||
@@ -226,6 +258,7 @@ export function defaultProbes(ctx: DoctorContext): DoctorProbe[] {
|
|||||||
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
|
{ name: "socket", run: () => checkSocket(ctx.socket, ctx.daemon.reachable) },
|
||||||
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
|
{ name: "daemon", run: () => checkDaemon(ctx.daemon) },
|
||||||
{ name: "port", run: () => checkPort(ctx.port) },
|
{ name: "port", run: () => checkPort(ctx.port) },
|
||||||
|
{ name: "access", run: () => checkAccess(ctx.access) },
|
||||||
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
|
{ name: "service-manager", run: () => checkServiceManager(ctx.serviceManager) },
|
||||||
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
|
...(isLinux ? [{ name: "linger", run: () => checkLinger(ctx.linger) }] : []),
|
||||||
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
|
{ name: "web-dist", run: () => checkWebDist(ctx.webDist) },
|
||||||
@@ -309,6 +342,21 @@ function statOrUndefined(path: string): { exists: boolean; mode: number | undefi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Best-effort access context; an unparsable environment reports `local`. */
|
||||||
|
function accessContext(env: NodeJS.ProcessEnv, port: number): AccessModeContext {
|
||||||
|
try {
|
||||||
|
const config = loadConfig(env);
|
||||||
|
return { mode: config.access, host: config.host, port, publicUrl: config.publicUrl };
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
mode: "local",
|
||||||
|
host: env.PI2_HOST?.trim() || "127.0.0.1",
|
||||||
|
port,
|
||||||
|
publicUrl: env.PI2_PUBLIC_URL?.trim().replace(/\/+$/, "") || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function binaryProbe(command: string, args: readonly string[], options: DoctorOptions, env: NodeJS.ProcessEnv): Promise<BinaryProbe> {
|
async function binaryProbe(command: string, args: readonly string[], options: DoctorOptions, env: NodeJS.ProcessEnv): Promise<BinaryProbe> {
|
||||||
const path = (options.which ?? ((name: string) => whichSync(name, env)))(command);
|
const path = (options.which ?? ((name: string) => whichSync(name, env)))(command);
|
||||||
if (path === undefined) return { found: false, error: `${command} not found on PATH` };
|
if (path === undefined) return { found: false, error: `${command} not found on PATH` };
|
||||||
@@ -394,6 +442,7 @@ export async function collectContext(options: DoctorOptions = {}): Promise<Docto
|
|||||||
socket: { path: socketPath, exists: existsSync(socketPath) },
|
socket: { path: socketPath, exists: existsSync(socketPath) },
|
||||||
daemon,
|
daemon,
|
||||||
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
|
port: { configured: daemon.port ?? configuredPort, bound: daemon.reachable },
|
||||||
|
access: accessContext(env, daemon.port ?? configuredPort),
|
||||||
serviceManager,
|
serviceManager,
|
||||||
linger,
|
linger,
|
||||||
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
|
webDist: { path: env.PI2_STATIC_DIR?.trim() || defaultWebDist(), exists: existsSync(env.PI2_STATIC_DIR?.trim() || defaultWebDist()) },
|
||||||
|
|||||||
+118
-8
@@ -14,7 +14,7 @@
|
|||||||
* bound port, `cli.token` the local admin token (see docs/deployment.md).
|
* bound port, `cli.token` the local admin token (see docs/deployment.md).
|
||||||
*/
|
*/
|
||||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
import { mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||||
import { spawnSync } from "node:child_process";
|
import { spawn, spawnSync } from "node:child_process";
|
||||||
import { dirname, resolve } from "node:path";
|
import { dirname, resolve } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { platform as osPlatform } from "node:os";
|
import { platform as osPlatform } from "node:os";
|
||||||
@@ -33,6 +33,7 @@ import {
|
|||||||
packageVersion,
|
packageVersion,
|
||||||
parseArgs,
|
parseArgs,
|
||||||
realpathOrSelf,
|
realpathOrSelf,
|
||||||
|
stringFlag,
|
||||||
UsageError,
|
UsageError,
|
||||||
} from "./util.js";
|
} from "./util.js";
|
||||||
import {
|
import {
|
||||||
@@ -51,12 +52,18 @@ Usage:
|
|||||||
pi2 daemon [start] [options] run the web-console daemon (foreground)
|
pi2 daemon [start] [options] run the web-console daemon (foreground)
|
||||||
pi2 attach [path] attach nvim to the workspace instance, else open nvim
|
pi2 attach [path] attach nvim to the workspace instance, else open nvim
|
||||||
pi2 status [--json] daemon info, instances, resources, health
|
pi2 status [--json] daemon info, instances, resources, health
|
||||||
|
pi2 open [--print] [--no-browser] open the web console signed in (local only)
|
||||||
pi2 doctor [--json] environment checks
|
pi2 doctor [--json] environment checks
|
||||||
pi2 pairing create a pairing code (URL + code + QR payload)
|
pi2 pairing [--public-url <url>] create a pairing code (URL + code + QR payload)
|
||||||
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
|
pi2 install-service [--dry-run|--write] systemd user unit / LaunchAgent
|
||||||
pi2 uninstall-service [--dry-run|--write] remove the unit
|
pi2 uninstall-service [--dry-run|--write] remove the unit
|
||||||
pi2 --version | --help
|
pi2 --version | --help
|
||||||
|
|
||||||
|
\`pi2 open\` flags: --print prints the URL only; --no-browser prints it instead
|
||||||
|
of launching a browser (--print implies --no-browser).
|
||||||
|
\`pi2 pairing\` flags: --public-url <url> rebuilds the URL on that public base
|
||||||
|
(defaults to daemon.json's publicUrl, then PI2_PUBLIC_URL).
|
||||||
|
|
||||||
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
|
The daemon endpoint comes from $PI2_RUNTIME_DIR/daemon.json (port) and
|
||||||
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
|
$PI2_RUNTIME_DIR/cli.token (local admin token). Start it with \`pi2 daemon\`.
|
||||||
See docs/deployment.md.`;
|
See docs/deployment.md.`;
|
||||||
@@ -258,6 +265,8 @@ interface InfoBody {
|
|||||||
platform: string;
|
platform: string;
|
||||||
capabilities: string[];
|
capabilities: string[];
|
||||||
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
|
limits: { maxBodyBytes: number; maxFrameBytes: number; maxConnections: number };
|
||||||
|
access?: string;
|
||||||
|
publicUrl?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface HealthBody {
|
interface HealthBody {
|
||||||
@@ -298,7 +307,13 @@ export async function runStatus(options: StatusOptions): Promise<number> {
|
|||||||
print(
|
print(
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
{
|
{
|
||||||
daemon: { url: client.baseUrl, ...info },
|
daemon: {
|
||||||
|
url: client.baseUrl,
|
||||||
|
...info,
|
||||||
|
// Older daemons may not report them; daemon.json does.
|
||||||
|
access: info.access ?? client.daemon.access,
|
||||||
|
publicUrl: info.publicUrl ?? client.daemon.publicUrl ?? null,
|
||||||
|
},
|
||||||
instances,
|
instances,
|
||||||
resources,
|
resources,
|
||||||
health,
|
health,
|
||||||
@@ -350,6 +365,21 @@ export async function runStatus(options: StatusOptions): Promise<number> {
|
|||||||
export interface PairingOptions {
|
export interface PairingOptions {
|
||||||
client: DaemonClient;
|
client: DaemonClient;
|
||||||
print?: (line: string) => void;
|
print?: (line: string) => void;
|
||||||
|
/** Rebuild the printed/QR url on this public base (e.g. `https://host.ts.net`). */
|
||||||
|
publicUrl?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withoutTrailingSlash(value: string): string {
|
||||||
|
return value.trim().replace(/\/+$/, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `--public-url` → `daemon.json.publicUrl` → `PI2_PUBLIC_URL`, first non-empty wins. */
|
||||||
|
export function resolvePublicUrl(client: DaemonClient, flag: string | undefined): string | null {
|
||||||
|
for (const candidate of [flag, client.daemon.publicUrl, process.env.PI2_PUBLIC_URL]) {
|
||||||
|
const value = candidate === undefined || candidate === null ? "" : withoutTrailingSlash(candidate);
|
||||||
|
if (value !== "") return value;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function runPairing(options: PairingOptions): Promise<number> {
|
export async function runPairing(options: PairingOptions): Promise<number> {
|
||||||
@@ -359,9 +389,13 @@ export async function runPairing(options: PairingOptions): Promise<number> {
|
|||||||
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
|
if (code === undefined) throw new CliError("pairing failed: daemon returned no code");
|
||||||
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
|
const expiresAt = typeof result.body.expiresAt === "number" ? result.body.expiresAt : undefined;
|
||||||
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
|
const nonce = typeof result.body.nonce === "string" ? result.body.nonce : undefined;
|
||||||
// Rebuild the URL from the *actual* base URL: the daemon's own `url` field is
|
// Rebuild the URL from the *actual* base URL (or the public base when one is
|
||||||
// derived from the configured port, which is stale after a retry or `--port 0`.
|
// known): the daemon's own `url` field is derived from the configured port,
|
||||||
const url = `${options.client.baseUrl}/pair/${code}`;
|
// which is stale after a retry or `--port 0`.
|
||||||
|
const base = options.publicUrl === undefined || options.publicUrl === null || options.publicUrl.trim() === ""
|
||||||
|
? options.client.baseUrl
|
||||||
|
: withoutTrailingSlash(options.publicUrl);
|
||||||
|
const url = `${base}/pair/${code}`;
|
||||||
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
|
const payload = JSON.stringify({ v: PROTOCOL_VERSION, code, url, ...(expiresAt === undefined ? {} : { expiresAt }), ...(nonce === undefined ? {} : { nonce }) });
|
||||||
|
|
||||||
print(`url ${url}`);
|
print(`url ${url}`);
|
||||||
@@ -373,6 +407,52 @@ export async function runPairing(options: PairingOptions): Promise<number> {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// open
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export interface OpenOptions {
|
||||||
|
client: DaemonClient;
|
||||||
|
print?: (line: string) => void;
|
||||||
|
/** `--print`: print the URL only and exit. */
|
||||||
|
printOnly?: boolean;
|
||||||
|
/** `--no-browser`: print the URL instead of launching one. */
|
||||||
|
noBrowser?: boolean;
|
||||||
|
/** Opener override; call `onError` when the launch fails. */
|
||||||
|
openUrl?: (url: string, onError: () => void) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Detached platform opener: `pi2 open` never waits for the browser. */
|
||||||
|
export function openInBrowser(url: string, onError: () => void): void {
|
||||||
|
const command = osPlatform() === "darwin" ? "open" : "xdg-open";
|
||||||
|
try {
|
||||||
|
const child = spawn(command, [url], { detached: true, stdio: "ignore" });
|
||||||
|
child.once("error", onError);
|
||||||
|
child.unref();
|
||||||
|
} catch {
|
||||||
|
onError();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `pi2 open`: mint a loopback browser session and put the browser on it. The
|
||||||
|
* token stays inside the returned URL (fragment), and only the URL is printed.
|
||||||
|
*/
|
||||||
|
export async function runOpen(options: OpenOptions): Promise<number> {
|
||||||
|
const print = options.print ?? ((line: string) => process.stdout.write(`${line}\n`));
|
||||||
|
const result = await options.client.post("/api/v1/console/session", {});
|
||||||
|
const url = typeof result.body.url === "string" ? result.body.url : undefined;
|
||||||
|
if (url === undefined) throw new CliError("console session failed: daemon returned no url");
|
||||||
|
|
||||||
|
if (options.printOnly === true || options.noBrowser === true) {
|
||||||
|
print(url);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// A missing xdg-open only costs the auto-launch; the URL is still useful.
|
||||||
|
(options.openUrl ?? openInBrowser)(url, () => print(url));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// doctor
|
// doctor
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -522,6 +602,24 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
|||||||
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||||
return await runStatus({ client, json: boolFlag(parsed.flags, "--json"), print: out });
|
return await runStatus({ client, json: boolFlag(parsed.flags, "--json"), print: out });
|
||||||
}
|
}
|
||||||
|
case "open": {
|
||||||
|
const parsed = parseArgs(rest, {
|
||||||
|
booleans: ["--print", "--no-browser", "--help"],
|
||||||
|
aliases: { "-h": "--help" },
|
||||||
|
});
|
||||||
|
if (boolFlag(parsed.flags, "--help")) {
|
||||||
|
out(USAGE);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (parsed.positionals.length > 0) throw new UsageError("open takes no arguments");
|
||||||
|
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||||
|
return await runOpen({
|
||||||
|
client,
|
||||||
|
print: out,
|
||||||
|
printOnly: boolFlag(parsed.flags, "--print"),
|
||||||
|
noBrowser: boolFlag(parsed.flags, "--no-browser"),
|
||||||
|
});
|
||||||
|
}
|
||||||
case "doctor": {
|
case "doctor": {
|
||||||
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
|
const parsed = parseArgs(rest, { booleans: ["--json", "--help"], aliases: { "-h": "--help" } });
|
||||||
if (boolFlag(parsed.flags, "--help")) {
|
if (boolFlag(parsed.flags, "--help")) {
|
||||||
@@ -534,9 +632,21 @@ export async function main(argv: readonly string[], options: Pi2Options = {}): P
|
|||||||
}
|
}
|
||||||
case "pairing":
|
case "pairing":
|
||||||
case "pair": {
|
case "pair": {
|
||||||
parseArgs(rest, { booleans: ["--help"], aliases: { "-h": "--help" } });
|
const parsed = parseArgs(rest, {
|
||||||
|
values: ["--public-url"],
|
||||||
|
booleans: ["--help"],
|
||||||
|
aliases: { "-h": "--help" },
|
||||||
|
});
|
||||||
|
if (boolFlag(parsed.flags, "--help")) {
|
||||||
|
out(USAGE);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
const client = (options.client ?? (() => createClient({ ...(options.runtime === undefined ? {} : { runtime: options.runtime }) })))();
|
||||||
return await runPairing({ client, print: out });
|
return await runPairing({
|
||||||
|
client,
|
||||||
|
print: out,
|
||||||
|
publicUrl: resolvePublicUrl(client, stringFlag(parsed.flags, "--public-url")),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
case "install-service":
|
case "install-service":
|
||||||
case "uninstall-service": {
|
case "uninstall-service": {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|||||||
import { mkdirSync, writeFileSync } from "node:fs";
|
import { mkdirSync, writeFileSync } from "node:fs";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import {
|
import {
|
||||||
|
checkAccess,
|
||||||
checkCliToken,
|
checkCliToken,
|
||||||
checkLinger,
|
checkLinger,
|
||||||
checkNvim,
|
checkNvim,
|
||||||
@@ -31,6 +32,7 @@ function context(overrides: Partial<DoctorContext> = {}): DoctorContext {
|
|||||||
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
|
socket: { path: "/run/user/1000/pi2/d.sock", exists: true },
|
||||||
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
|
daemon: { reachable: true, port: 7676, protocolVersion: 1 },
|
||||||
port: { configured: 7676, bound: true },
|
port: { configured: 7676, bound: true },
|
||||||
|
access: { mode: "local", host: "127.0.0.1", port: 7676, publicUrl: null },
|
||||||
serviceManager: { name: "systemd", available: true },
|
serviceManager: { name: "systemd", available: true },
|
||||||
linger: { checked: true, enabled: true },
|
linger: { checked: true, enabled: true },
|
||||||
webDist: { path: "/repo/web/dist", exists: true },
|
webDist: { path: "/repo/web/dist", exists: true },
|
||||||
@@ -60,6 +62,7 @@ describe("doctor checks (all passing)", () => {
|
|||||||
"socket",
|
"socket",
|
||||||
"daemon",
|
"daemon",
|
||||||
"port",
|
"port",
|
||||||
|
"access",
|
||||||
"service-manager",
|
"service-manager",
|
||||||
"linger",
|
"linger",
|
||||||
"web-dist",
|
"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", () => {
|
describe("doctor failure cases", () => {
|
||||||
it("fails on node < 22", async () => {
|
it("fails on node < 22", async () => {
|
||||||
const report = await checks({ nodeVersion: "v20.11.0" });
|
const report = await checks({ nodeVersion: "v20.11.0" });
|
||||||
@@ -262,6 +315,7 @@ describe("collectContext", () => {
|
|||||||
expect(ctx.socket.exists).toBe(true);
|
expect(ctx.socket.exists).toBe(true);
|
||||||
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
|
expect(ctx.daemon).toEqual({ reachable: true, port: 7712, protocolVersion: 1 });
|
||||||
expect(ctx.port).toEqual({ configured: 7712, bound: true });
|
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.serviceManager).toEqual({ name: "systemd", available: true });
|
||||||
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
|
expect(ctx.linger).toMatchObject({ checked: true, enabled: true });
|
||||||
expect(ctx.webDist.path).toBe(join(dir, "web"));
|
expect(ctx.webDist.path).toBe(join(dir, "web"));
|
||||||
|
|||||||
+105
-1
@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|||||||
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
|
import { mkdirSync, realpathSync, writeFileSync } from "node:fs";
|
||||||
import { basename, join } from "node:path";
|
import { basename, join } from "node:path";
|
||||||
import type { DaemonClient } from "../../src/cli/pi2.js";
|
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 { writeDaemonJson, type DaemonLock } from "../../src/cli/lock.js";
|
||||||
import { writeCliToken } from "../../src/cli/token.js";
|
import { writeCliToken } from "../../src/cli/token.js";
|
||||||
import type { WorkspaceInfo } from "../../src/protocol/types.js";
|
import type { WorkspaceInfo } from "../../src/protocol/types.js";
|
||||||
@@ -54,6 +54,7 @@ interface FakeData {
|
|||||||
resources?: Record<string, unknown>;
|
resources?: Record<string, unknown>;
|
||||||
health?: Record<string, unknown>;
|
health?: Record<string, unknown>;
|
||||||
pair?: Record<string, unknown>;
|
pair?: Record<string, unknown>;
|
||||||
|
session?: Record<string, unknown>;
|
||||||
postError?: Error;
|
postError?: Error;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,6 +97,9 @@ function fakeClient(data: FakeData = {}): DaemonClient & { calls: string[] } {
|
|||||||
if (path === "/api/v1/pair") {
|
if (path === "/api/v1/pair") {
|
||||||
return { status: 202, body: data.pair ?? { accepted: true, code: "ABCD2345", expiresAt: Date.now() + 60_000 } };
|
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}`);
|
throw new CliError(`unexpected POST ${path}`);
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -353,6 +357,106 @@ describe("pi2 pairing", () => {
|
|||||||
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
|
runPairing({ client: fakeClient({ postError: new CliError("pair failed: E_UNAUTHORIZED") }) }),
|
||||||
).rejects.toThrowError(/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)", () => {
|
describe("pi2 doctor (daemon probe wiring)", () => {
|
||||||
|
|||||||
Reference in new issue
Block a user