Files
backnotprop__plannotator/apps/pi-extension/server/network.ts
Michael Ramos 5f33b72b2f feat(remote): tailnet auto-advertise, ready QR code, and a first-class --tailscale mode (#1280)
* feat(remote): resolve urlHost auto from Tailscale for advertised URLs

PLANNOTATOR_URL_HOST=auto (or config urlHost: "auto") detects this
machine's tailnet host at first use in a remote session: MagicDNS name
from tailscale status --json, falling back to the single tailscale ip -4
CGNAT address. Detection is cached per process, never spawns in local
sessions, warns once and falls back to localhost on failure, and stays
strictly display-only: binding remains governed by PLANNOTATOR_REMOTE.

Pure parsers live in the new @plannotator/shared/tailscale module,
vendored to the Pi extension; both runtimes mirror the resolution.

* feat(remote): render a terminal QR code for remote-ready session URLs

Remote sessions print their advertised URL as the lifeline; the usual
next step is opening it on another device (iPad, phone, laptop off the
VPS). handleServerReady now also renders a compact unicode QR of that
URL via the zero-dependency uqr package, TTY-gated so piped stderr and
hook transcripts keep only the plain URL line.

Pi keeps URL-only parity: its ready surface is an in-chat notification,
not a TTY stream, so a QR block would not render there.

* feat(cli): first-class --tailscale mode for review and annotate sessions

plannotator review --tailscale (also annotate and annotate-last/last)
publishes the session over the user's tailnet: the server stays
loopback-bound and the CLI orchestrates tailscale serve --bg
--https=<port> http://127.0.0.1:<port>, then advertises the HTTPS
tailnet URL with a terminal QR code. Nothing listens beyond localhost
and nothing is ever public (serve, never funnel).

Guarantees: preconditions fail with actionable errors (CLI missing,
daemon down or logged out); a pre-existing serve mapping on the chosen
port aborts instead of being stolen and other ports are never touched;
every mapping the process creates is torn down on normal completion,
SIGINT/SIGTERM, and errors via the exit-routed cleanup handler. When
combined with PLANNOTATOR_REMOTE or SSH detection, --tailscale wins and
forces local mode with a stderr notice, which also restores the random
local port so simultaneous sessions get distinct serve mappings.

* fix(remote): await tailscale-ready failures, harden serve teardown and conflict detection

Review fixes for #1280 (external review plus internal security review).

Startup failures no longer hang the session: startReviewServer and
startAnnotateServer now await async ready handlers and stop the server
on rejection, and the CLI's --tailscale ready path resolves publishing
failures itself with an actionable stderr message and exit 1. Under the
bang-prefix skill a hanging loopback server blocked the whole Claude
Code prompt.

Serve teardown is checked, not assumed: a failed off retries once, then
warns with the exact manual command, and a port is only forgotten after
a successful off. SIGHUP (terminal close) is now routed through
process.exit like SIGINT/SIGTERM so exit-time cleanup runs. Docs no
longer claim guaranteed cleanup: --bg mappings survive SIGKILL and
reboots, and the manual removal command is documented.

Conflict detection sees foreground serve sessions (Foreground.*.TCP),
which Tailscale prefers over background mappings, and fails CLOSED on
unrecognizable serve status output instead of assuming the port is
free. The extracted serve URL must match the requested port, so a
version-dependent output shape cannot advertise another mapping's URL.

The annotate agent terminal is gated off by default under --tailscale
behind the existing PLANNOTATOR_AGENT_TERMINAL_REMOTE opt-in: the PTY
token is not an auth boundary against network peers, and tailnet
reachability implies terminal reachability.

Also: --tailscale is rejected with a clear error on unsupported
subcommands and documented in review/annotate/annotate-last and
top-level help; the remote-ready QR renders only for URLs actually
reachable off-machine (never localhost); urlHost is suppressed for
--tailscale runs so the local-session warning cannot mislead; the
duplicated auto-host resolution moved into the shared vendored module;
tailscale-serve tests restore module and process state via a reset
seam.
2026-08-12 12:07:30 -07:00

364 lines
10 KiB
TypeScript

/**
* Network utilities — remote detection, port binding, browser opening.
* isRemoteSession, getServerPort, listenOnPort, openBrowser
*/
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import type { Server } from "node:http";
import { release } from "node:os";
import { delimiter, join } from "node:path";
import { loadConfig, resolveUrlHost, resolveUseGlimpse } from "../generated/config.ts";
import { parsePortSelection } from "../generated/port-range.ts";
import { isAutoUrlHost, resolveAutoHostCached } from "../generated/tailscale.ts";
const DEFAULT_REMOTE_PORT = 19432;
const LOOPBACK_HOST = "127.0.0.1";
const NOOP_BROWSER_VALUES = new Set(["true", "false", "none", ":", "0", "1"]);
function isAddressInUseError(err: unknown): boolean {
return err instanceof Error && (
(err as NodeJS.ErrnoException).code === "EADDRINUSE" ||
err.message.includes("EADDRINUSE")
);
}
export function isNoOpBrowserSentinel(value: string | undefined): boolean {
if (!value) return false;
return NOOP_BROWSER_VALUES.has(value.trim().toLowerCase());
}
/**
* Check if running in a remote session (SSH, devcontainer, etc.)
* Honors PLANNOTATOR_REMOTE as a tri-state override, or detects SSH_TTY/SSH_CONNECTION.
*/
function getRemoteOverride(): boolean | null {
const remote = process.env.PLANNOTATOR_REMOTE;
if (remote === undefined) {
return null;
}
if (remote === "1" || remote?.toLowerCase() === "true") {
return true;
}
if (remote === "0" || remote?.toLowerCase() === "false") {
return false;
}
return null;
}
export function isRemoteSession(): boolean {
const remoteOverride = getRemoteOverride();
if (remoteOverride !== null) {
return remoteOverride;
}
// Legacy SSH detection
if (process.env.SSH_TTY || process.env.SSH_CONNECTION) {
return true;
}
return false;
}
/**
* Get the server ports to try, in order.
* - PLANNOTATOR_PORT accepts a fixed port or inclusive range
* - Remote sessions default to 19432 (for port forwarding)
* - Local sessions use a random port
*/
export function getServerPorts(): {
ports: number[];
portSource: "env" | "remote-default" | "random";
} {
const configuration = getServerPortConfiguration();
return {
ports: configuration.ports,
portSource: configuration.portSource,
};
}
function getServerPortConfiguration(): {
ports: number[];
portSource: "env" | "remote-default" | "random";
isRange: boolean;
} {
const envPort = process.env.PLANNOTATOR_PORT;
if (envPort) {
const parsed = parsePortSelection(envPort);
if (parsed) {
return {
ports: parsed.ports,
portSource: "env",
isRange: parsed.kind === "range",
};
}
// Invalid port - fall back silently, caller can check env var themselves
}
if (isRemoteSession()) {
return {
ports: [DEFAULT_REMOTE_PORT],
portSource: "remote-default",
isRange: false,
};
}
return { ports: [0], portSource: "random", isRange: false };
}
export function getServerPort(): {
port: number;
portSource: "env" | "remote-default" | "random";
} {
const { ports, portSource } = getServerPorts();
return { port: ports[0], portSource };
}
export function getServerHostname(): string {
return isRemoteSession() ? "0.0.0.0" : LOOPBACK_HOST;
}
/** True when the advertised-URL host is overridden away from localhost. */
export function isUrlHostOverridden(): boolean {
const host = resolveUrlHost(loadConfig());
if (host === undefined) return false;
if (isAutoUrlHost(host)) return isRemoteSession() && resolveAutoHostCached() !== undefined;
return true;
}
let warnedLocalUrlHost = false;
/**
* Compose the URL advertised to the user for a bound port (issue #657).
* Display-only: the PLANNOTATOR_URL_HOST / urlHost override changes what is
* printed and opened, never which interface the server listens on
* (getServerHostname). Remote sessions only: a local session binds loopback,
* so honoring the override would advertise (and auto-open) a URL nothing is
* listening on — the override is ignored with a once-per-process warning.
* The "auto" sentinel resolves the host from Tailscale (resolveAutoHost).
* Same-machine subprocesses must not use this — they get a loopback URL so a
* tailnet-only hostname can't break local agent jobs.
* Mirrors packages/server/remote.ts — keep the two behaviorally identical.
*/
export function buildAdvertisedUrl(port: number): string {
const host = resolveUrlHost(loadConfig());
if (host === undefined) return `http://localhost:${port}`;
if (!isRemoteSession()) {
if (!warnedLocalUrlHost) {
warnedLocalUrlHost = true;
process.stderr.write(
`[plannotator] Warning: advertised URL host ${JSON.stringify(host)} ignored — this is a local session, so the server binds loopback and only localhost is reachable. Set PLANNOTATOR_REMOTE=1 to use the override.\n`,
);
}
return `http://localhost:${port}`;
}
const resolved = isAutoUrlHost(host) ? resolveAutoHostCached() : host;
if (resolved === undefined) return `http://localhost:${port}`;
return `http://${resolved}:${port}`;
}
const MAX_RETRIES = 5;
const RETRY_DELAY_MS = 500;
export async function listenOnPort(
server: Server,
): Promise<{ port: number; portSource: "env" | "remote-default" | "random" }> {
const { ports, portSource, isRange } = getServerPortConfiguration();
const portsToTry = isRange ? ports : Array(MAX_RETRIES).fill(ports[0]);
for (const [index, port] of portsToTry.entries()) {
try {
await new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
cleanup();
reject(error);
};
const onListening = () => {
cleanup();
resolve();
};
const cleanup = () => {
server.removeListener("error", onError);
server.removeListener("listening", onListening);
};
server.once("error", onError);
server.once("listening", onListening);
try {
server.listen(port, getServerHostname());
} catch (error: unknown) {
cleanup();
reject(error);
}
});
const addr = server.address() as { port: number };
return { port: addr.port, portSource };
} catch (err: unknown) {
const isAddressInUse = isAddressInUseError(err);
if (isAddressInUse && index < portsToTry.length - 1) {
if (!isRange) {
await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
}
continue;
}
if (isAddressInUse) {
if (!isRange) {
const hint = isRemoteSession()
? " (set PLANNOTATOR_PORT to use a different port)"
: "";
throw new Error(`Port ${port} in use after ${MAX_RETRIES} retries${hint}`);
}
const configured = `${ports[0]}-${ports.at(-1)}`;
const hint = isRemoteSession()
? " (set PLANNOTATOR_PORT to use a different port or range)"
: "";
throw new Error(`Port selection ${configured} exhausted${hint}`);
}
throw err;
}
}
// Unreachable, but satisfies TypeScript
throw new Error("Failed to bind port");
}
/**
* Open URL in system browser (Node-compatible, no Bun $ dependency).
* Honors PLANNOTATOR_BROWSER and BROWSER env vars.
* Returns { opened: true } if browser was opened, { opened: false, isRemote: true, url } if remote session.
*/
function findCommandOnPath(command: string): string | null {
const extensions = process.platform === "win32" ? [".cmd", ".exe", ".bat", ""] : [""];
for (const dir of (process.env.PATH || "").split(delimiter)) {
if (!dir) continue;
for (const ext of extensions) {
const candidate = join(dir, `${command}${ext}`);
if (existsSync(candidate)) return candidate;
}
}
return null;
}
function buildGlimpseHtml(url: string): string {
const encodedUrl = JSON.stringify(url);
return `<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Plannotator</title>
<style>
html, body { width: 100%; height: 100%; margin: 0; }
body { overflow: hidden; background: #0f1115; }
</style>
</head>
<body>
<script>
location.replace(${encodedUrl});
</script>
</body>
</html>`;
}
async function openGlimpse(url: string): Promise<boolean> {
const glimpseCli = findCommandOnPath("glimpseui");
if (!glimpseCli) return false;
const args = [
"--width",
String(Number(process.env.PLANNOTATOR_GLIMPSE_WIDTH || 1280)),
"--height",
String(Number(process.env.PLANNOTATOR_GLIMPSE_HEIGHT || 900)),
"--title",
"Plannotator",
"--open-links",
];
const html = buildGlimpseHtml(url);
return await new Promise<boolean>((resolve) => {
let settled = false;
let successTimer: ReturnType<typeof setTimeout> | undefined;
const finish = (opened: boolean) => {
if (settled) return;
settled = true;
if (successTimer) clearTimeout(successTimer);
resolve(opened);
};
const child = spawn(glimpseCli, args, {
detached: true,
stdio: ["pipe", "ignore", "ignore"],
});
successTimer = setTimeout(() => {
child.unref();
finish(true);
}, 750);
child.once("error", () => finish(false));
child.once("exit", () => finish(false));
child.stdin.once("error", () => finish(false));
child.stdin.end(html);
});
}
export async function openBrowser(url: string): Promise<{
opened: boolean;
isRemote?: boolean;
url?: string;
}> {
const rawPlannotatorBrowser = process.env.PLANNOTATOR_BROWSER;
const rawBrowser = process.env.BROWSER;
const plannotatorBrowser = isNoOpBrowserSentinel(rawPlannotatorBrowser)
? undefined
: rawPlannotatorBrowser;
const envBrowser = isNoOpBrowserSentinel(rawBrowser) ? undefined : rawBrowser;
const browser = plannotatorBrowser || envBrowser;
if (isRemoteSession() && !browser) {
return { opened: false, isRemote: true, url };
}
if (!browser && resolveUseGlimpse(loadConfig())) {
const openedViaGlimpse = await openGlimpse(url);
if (openedViaGlimpse) {
return { opened: true };
}
}
try {
const platform = process.platform;
const wsl =
platform === "linux" && release().toLowerCase().includes("microsoft");
let cmd: string;
let args: string[];
if (browser) {
if (plannotatorBrowser && platform === "darwin") {
cmd = "open";
args = ["-a", plannotatorBrowser, url];
} else if ((platform === "win32" || wsl) && plannotatorBrowser) {
cmd = "cmd.exe";
args = ["/c", "start", "", plannotatorBrowser, url];
} else {
cmd = browser;
args = [url];
}
} else if (platform === "win32" || wsl) {
cmd = "cmd.exe";
args = ["/c", "start", "", url];
} else if (platform === "darwin") {
cmd = "open";
args = [url];
} else {
cmd = "xdg-open";
args = [url];
}
const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
child.once("error", () => {});
child.unref();
return { opened: true };
} catch {
return { opened: false };
}
}