Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(remote): install and pair pi-host over SSH from the desktop
vastsab52abe626d0f
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.tsindex cc5664fa6..6b818186b 100644--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts@@ -7,17 +7,33 @@* handler byte-for-byte.** The transport factory is injected. Production wires it to- * `wsClientTransport` from `@pi-desktop/racp` (loopback for local dev, `-L`- * tunnel target for Stage 4's SSH bootstrap); tests wire the in-memory- * `MemoryLink` so this boot layer exercises the real `RacpClient` state- * machine without a socket.+ * `wsClientTransport` from `@pi-desktop/racp` (loopback for local dev, the+ * forwarded loopback port for an SSH-bootstrapped host); tests wire the+ * in-memory `MemoryLink` so this boot layer exercises the real `RacpClient`+ * state machine without a socket.+ *+ * Two shapes of paired host live here. A `direct` host stores the URL the user+ * pasted, including a forward they opened themselves. An `ssh` host stores a+ * descriptor instead, and this layer owns a live `ssh -N -L` forward for it+ * (`remote/ssh-tunnel.ts`) — the URL is derived from that forward on every+ * launch, so a restart re-establishes the tunnel before connecting.*/+import type {+ RemoteHostBootstrapRequest,+ RemoteHostBootstrapResult,+ RemoteHostSshMetadata,+ RemoteHostSummary,+ RemoteHostTransport,+} from "@pi-desktop/shared";+import { assertSshArgument } from "../remote/ssh-transport.js";import { wsClientTransport } from "@pi-desktop/racp";import type { BackendRouter } from "../remote/backend-router.js";+import { createRacpRemoteHostClient, exchangePairingToken, type RacpRemoteHostClient } from "../remote/racp-remote-host-client.js";import {- createRacpRemoteHostClient,- type RacpRemoteHostClient,-} from "../remote/racp-remote-host-client.js";+ createSshBootstrap,+ type SshBootstrapDeps,+} from "../remote/ssh-bootstrap.js";+import { createSshTunnelManager, type SshTunnelManager } from "../remote/ssh-tunnel.js";import {createRemoteHostConnection,type RemoteHostConnection,@@ -41,15 +57,13 @@ export type BootRemoteHostsOptions = {/** Optional override; the default uses the real `wsClientTransport`. */buildAdapter?: RemoteHostAdapterFactory;log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;+ /** Durable SSH forwards; created on demand when the first SSH host is used. */+ tunnels?: SshTunnelManager;+ /** Overrides for the SSH bootstrap's injected edges (tests only). */+ sshBootstrap?: Partial<SshBootstrapDeps>;};-/** Renderer-facing summary of one paired host (no secret material). */-export type RemoteHostSummary = {- hostKey: string;- label: string;- url: string;- connected: boolean;-};+export type { RemoteHostSummary };export interface RemoteHostsBoot {/** Read registry, connect every host, register their sessions. Returns@@ -61,11 +75,17 @@ export interface RemoteHostsBoot {list(): Promise<RemoteHostSummary[]>;/** Persist a paired record, then open one live connection for it. */addHost(record: RemoteHostRecord): Promise<RemoteHostSummary>;+ /**+ * Install and pair a `pi-host` over SSH and bring it online (spec §5.2).+ * The forward the bootstrap opened is adopted rather than reopened, so+ * pairing pays for exactly one tunnel.+ */+ bootstrapHost(request: RemoteHostBootstrapRequest): Promise<RemoteHostBootstrapResult>;/** Close and unregister the host, then remove it from the registry. */removeHost(hostKey: string): Promise<void>;/** The underlying registry, exposed for pairing flows that write directly. */readonly registry: RemoteHostRegistry;-};+}/*** Single-slot registry so `bootstrap/shutdown.ts` can wait on the same boot@@ -83,10 +103,102 @@ export function getActiveRemoteHostsBoot(): RemoteHostsBoot | null {return activeRemoteHostsBoot;}+/** Record metadata keys; `metadata` is the registry's forward-compatible slot. */+const TRANSPORT_KEY = "transport";+const SSH_KEY = "ssh";++/**+ * Read the SSH descriptor out of a record, or `null` for a `direct` host. The+ * shape is re-checked on read because `remote-hosts.json` is user-editable and+ * a malformed descriptor must degrade to "not an SSH host", never to a spawn+ * with garbage arguments.+ */+/**+ * A descriptor field that is safe to place in the `ssh` argv, or `null`. It+ * reuses the transport's own rule so the renderer path and the on-disk path+ * cannot drift apart.+ */+function safeSshField(value: unknown): string | null {+ if (typeof value !== "string") return null;+ try {+ return assertSshArgument(value, "ssh field");+ } catch {+ return null;+ }+}++/** `ssh -p` value, or `null` when absent or out of range. */+function safeSshPort(value: unknown): number | null {+ if (typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535) {+ return value;+ }+ return null;+}++export function sshMetadataOf(record: RemoteHostRecord): RemoteHostSshMetadata | null {+ const metadata = record.metadata;+ if (!metadata || metadata[TRANSPORT_KEY] !== "ssh") return null;+ const ssh = metadata[SSH_KEY];+ if (typeof ssh !== "object" || ssh === null) return null;+ const candidate = ssh as Partial<RemoteHostSshMetadata>;+ // `remote-hosts.json` is user-editable and every one of these values reaches+ // the `ssh` command line, where a leading `-` is read as an option+ // (`-oProxyCommand=…`) rather than as a destination. A record that fails the+ // check is not an SSH host at all — never a spawn with junk argv.+ const host = safeSshField(candidate.host);+ if (host === null) return null;+ const user = candidate.user === undefined ? null : safeSshField(candidate.user);+ if (user === null && candidate.user !== undefined) return null;+ const identityFile =+ candidate.identityFile === undefined ? null : safeSshField(candidate.identityFile);+ if (identityFile === null && candidate.identityFile !== undefined) return null;+ const port = candidate.port === undefined ? null : safeSshPort(candidate.port);+ if (port === null && candidate.port !== undefined) return null;+ if (+ typeof candidate.remotePort !== "number" ||+ !Number.isInteger(candidate.remotePort) ||+ candidate.remotePort <= 0 ||+ candidate.remotePort > 65_535+ ) {+ return null;+ }+ return {+ host,+ ...(port !== null ? { port } : {}),+ ...(user !== null ? { user } : {}),+ ...(identityFile !== null ? { identityFile } : {}),+ remotePort: candidate.remotePort,+ version: typeof candidate.version === "string" ? candidate.version : "",+ };+}++/** The registry record for a bootstrapped host. */+export function sshHostRecord(input: {+ hostKey: string;+ label: string;+ url: string;+ deviceToken: string;+ ssh: RemoteHostSshMetadata;+}): RemoteHostRecord {+ return {+ hostKey: input.hostKey,+ label: input.label,+ url: input.url,+ deviceToken: input.deviceToken,+ metadata: { [TRANSPORT_KEY]: "ssh", [SSH_KEY]: input.ssh },+ };+}++export function transportOf(record: RemoteHostRecord): RemoteHostTransport {+ return sshMetadataOf(record) ? "ssh" : "direct";+}+type OpenHost = {hostKey: string;adapter: RacpRemoteHostClient;connection: RemoteHostConnection;+ /** The URL this host is live on, which for an SSH host is the forward's. */+ url: string;};export function createRemoteHostsBoot(@@ -108,30 +220,59 @@ export function createRemoteHostsBoot(log: (level, message, data) => log(level, message, data),});+ const tunnels =+ options.tunnels ??+ createSshTunnelManager({ log: (level, message, data) => log(level, message, data) });++ const bootstrap = createSshBootstrap({+ version: options.clientInfo.version,+ exchangePairing: ({ url, pairingToken, label }) =>+ exchangePairingToken({+ url,+ pairingToken,+ label,+ clientInfo: options.clientInfo,+ log: (level, message, data) => log(level, message, data),+ }),+ log: (level, message, data) => log(level, message, data),+ ...options.sshBootstrap,+ });+const opened: OpenHost[] = [];/** Bring one record online: build adapter, connect, register the router* backends. Failure is thrown so the caller can decide (boot logs & skips;* a live pair-then-add refuses to persist a token that cannot be used). */const openHost = async (record: RemoteHostRecord): Promise<OpenHost> => {- const adapter = buildAdapter(record);- await adapter.connect();- const connection = createRemoteHostConnection({- hostKey: record.hostKey,- client: adapter.client,- router: options.router,- emit: options.emit,- log: (level, message, data) => log(level, message, data),- });+ const ssh = sshMetadataOf(record);+ // An SSH host is only reachable while its forward is up; opening one here+ // — rather than trusting the stored URL — is what makes a restart work.+ const url = ssh ? (await tunnels.open(record.hostKey, ssh)).url : record.url;try {- await connection.open();+ const adapter = buildAdapter({ ...record, url });+ await adapter.connect();+ const connection = createRemoteHostConnection({+ hostKey: record.hostKey,+ client: adapter.client,+ router: options.router,+ emit: options.emit,+ log: (level, message, data) => log(level, message, data),+ });+ try {+ await connection.open();+ } catch (error) {+ // A connection that failed to open leaves the adapter live; close it+ // before re-throwing so the ws socket does not leak.+ await adapter.close().catch(() => undefined);+ throw error;+ }+ return { hostKey: record.hostKey, adapter, connection, url };} catch (error) {- // A connection that failed to open leaves the adapter live; close it- // before re-throwing so the ws socket does not leak.- await adapter.close().catch(() => undefined);+ // The host is not online, so nothing needs this forward; drop it rather+ // than leave an idle ssh process behind.+ if (ssh) await tunnels.close(record.hostKey).catch(() => undefined);throw error;}- return { hostKey: record.hostKey, adapter, connection };};const closeHost = async (host: OpenHost): Promise<void> => {@@ -149,11 +290,54 @@ export function createRemoteHostsBoot(error: String(error),});}+ await tunnels.close(host.hostKey).catch((error: unknown) => {+ log("warn", `remote host ${host.hostKey} forward close threw`, {+ error: String(error),+ });+ });+ };++ /** Drop a live connection for one host key, if there is one. */+ const closeLive = async (hostKey: string): Promise<void> => {+ const index = opened.findIndex((host) => host.hostKey === hostKey);+ if (index < 0) return;+ const [host] = opened.splice(index, 1);+ if (host) await closeHost(host);};const isConnected = (hostKey: string): boolean =>opened.some((host) => host.hostKey === hostKey);+ const summaryOf = (record: RemoteHostRecord): RemoteHostSummary => {+ const live = opened.find((host) => host.hostKey === record.hostKey);+ return {+ hostKey: record.hostKey,+ label: record.label,+ url: live?.url ?? record.url,+ connected: live !== undefined,+ transport: transportOf(record),+ };+ };++ const addHost = async (record: RemoteHostRecord): Promise<RemoteHostSummary> => {+ // Persist before opening so a crash between the two leaves a record the+ // next boot can retry; a failed open is surfaced but the row stays.+ await registry.upsert(record);+ // Replace any prior live connection under the same hostKey (a re-pair+ // rotates the device token but the routing key stays stable).+ await closeLive(record.hostKey);+ try {+ const host = await openHost(record);+ opened.push(host);+ return { ...summaryOf(record), connected: true };+ } catch (error) {+ log("warn", `remote host ${record.hostKey} paired but failed to open`, {+ error: String(error),+ });+ return { ...summaryOf(record), connected: false };+ }+ };+return {registry,async open() {@@ -189,44 +373,39 @@ export function createRemoteHostsBoot(// Snapshot and clear first so a re-entrant close finds nothing to do.const hosts = opened.splice(0, opened.length);await Promise.allSettled(hosts.map((host) => closeHost(host)));+ // A tunnel can outlive its connection when the connect failed; sweep it.+ await tunnels.dispose();},async list() {const records = await registry.list();- return records.map((record) => ({- hostKey: record.hostKey,- label: record.label,- url: record.url,- connected: isConnected(record.hostKey),- }));+ return records.map(summaryOf);},- async addHost(record) {- // Persist before opening so a crash between the two leaves a record the- // next boot can retry; a failed open is surfaced but the row stays.- await registry.upsert(record);- // Replace any prior live connection under the same hostKey (a re-pair- // rotates the device token but the routing key stays stable).- const existing = opened.findIndex((host) => host.hostKey === record.hostKey);- if (existing >= 0) {- const [prior] = opened.splice(existing, 1);- if (prior) await closeHost(prior);- }- try {- const host = await openHost(record);- opened.push(host);- return { hostKey: record.hostKey, label: record.label, url: record.url, connected: true };- } catch (error) {- log("warn", `remote host ${record.hostKey} paired but failed to open`, {- error: String(error),- });- return { hostKey: record.hostKey, label: record.label, url: record.url, connected: false };- }+ addHost,+ async bootstrapHost(request) {+ const outcome = await bootstrap.bootstrap(request);+ // A re-pair under the same key must release the previous live+ // connection — and with it the previous forward — before the new+ // forward is adopted. Otherwise adopting would evict the very forward+ // the bootstrap just opened for us.+ await closeLive(outcome.hostKey);+ // Adopt before persisting: the forward is already live and the device+ // token only works over it.+ await tunnels.adopt(outcome.hostKey, outcome.ssh, outcome.forward);+ const host = await addHost(+ sshHostRecord({+ hostKey: outcome.hostKey,+ label: outcome.label,+ url: outcome.url,+ deviceToken: outcome.deviceToken,+ ssh: outcome.ssh,+ }),+ );+ return { host, ssh: outcome.ssh, steps: outcome.steps };},async removeHost(hostKey) {- const index = opened.findIndex((host) => host.hostKey === hostKey);- if (index >= 0) {- const [host] = opened.splice(index, 1);- if (host) await closeHost(host);- }+ await closeLive(hostKey);+ // A paired host that never came online still owns a tunnel slot.+ await tunnels.close(hostKey);await registry.remove(hostKey);},};diff --git a/apps/desktop/electron/main/ipc/remote-host-ipc.ts b/apps/desktop/electron/main/ipc/remote-host-ipc.tsindex f1c40ddca..25c9099f2 100644--- a/apps/desktop/electron/main/ipc/remote-host-ipc.ts+++ b/apps/desktop/electron/main/ipc/remote-host-ipc.ts@@ -1,19 +1,25 @@/**- * Renderer IPC for the R2b pairing UX (ADR 0286 §Registry).+ * Renderer IPC for the R2b pairing UX (ADR 0286 §Registry) and the SSH+ * bootstrap (spec `02-architecture/05-remote-agent-control.md` §5.2).*- * Three channels sit between the renderer's Settings page and the remote-hosts+ * Four channels sit between the renderer's Settings page and the remote-hosts* boot hook: `list` reports the currently paired hosts with their live status,- * `pair` exchanges a `ppt1.` pairing token for a durable device token and- * brings the connection online, and `remove` closes and forgets one host.+ * `pair` exchanges a pasted `ppt1.` pairing token for a durable device token,+ * `bootstrap` installs and pairs a host on a machine the user reaches over+ * SSH, and `remove` closes and forgets one host.** The renderer never sees a device token: the pairing exchange, the encrypted* write to `<dataDir>/remote-hosts.json`, and every subsequent live connection* live inside Electron main. `list` is safe to expose to any renderer surface.+ * The bootstrap channel never sees an SSH secret either — it passes a host,+ * and the system `ssh` client supplies the credentials from the user's own+ * configuration and agent.*/-import { wsClientTransport } from "@pi-desktop/racp";import {ErrorCodes,IPC,+ type RemoteHostBootstrapRequest,+ type RemoteHostBootstrapResult,type RemoteHostPairRequest,type RemoteHostPairResult,type RemoteHostRemoveRequest,@@ -24,7 +30,7 @@ import {getActiveRemoteHostsBoot,type RemoteHostsBoot,} from "../bootstrap/remote-hosts";-import { createRacpRemoteHostClient } from "../remote/racp-remote-host-client";+import { exchangePairingToken } from "../remote/racp-remote-host-client";import type { IpcRegistrar } from "./types";export type RegisterRemoteHostIpcOptions = {@@ -52,6 +58,13 @@ function trim(value: unknown): string {return typeof value === "string" ? value.trim() : "";}+function invalid(message: string, field?: string): Error {+ return Object.assign(new Error(message), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ ...(field ? { field } : {}),+ });+}+/*** Derive a routing key from a URL and a label when the renderer did not* supply one. The URL's hostname keeps the key readable in logs; the label's@@ -97,56 +110,51 @@ export function registerRemoteHostIpc(options: RegisterRemoteHostIpcOptions): voconst pairingToken = trim(request?.pairingToken);const label = trim(request?.label) || "desktop";if (!url || !pairingToken) {- throw Object.assign(new Error("url and pairingToken are required"), {- errorCode: ErrorCodes.INVALID_ARGUMENT,- });+ throw invalid("url and pairingToken are required");}const hostKey = trim(request?.hostKey) || synthesizeHostKey(url, label);if (hostKey.includes(":")) {- throw Object.assign(new Error("hostKey must not contain ':'"), {- errorCode: ErrorCodes.INVALID_ARGUMENT,- });+ throw invalid("hostKey must not contain ':'", "hostKey");}// Pair on a throwaway connection whose transport authenticates with the// single-use pairing token; call `connection/pair` for the device token,// then close it. The durable connection reopens under the device token// via `boot.addHost` below.- const pairing = createRacpRemoteHostClient({- transport: wsClientTransport({ url, token: pairingToken }),+ const deviceToken = await exchangePairingToken({+ url,+ pairingToken,+ label,clientInfo,log: (level, message, data) => log(level, message, data),});- let deviceToken: string;- try {- await pairing.connect();- const result = (await pairing.client.request("connection/pair", {- deviceLabel: label,- })) as { deviceToken?: unknown };- if (typeof result?.deviceToken !== "string" || result.deviceToken.length === 0) {- throw Object.assign(new Error("pi-host did not return a device token"), {- errorCode: "PAIRING_FAILED",- });- }- deviceToken = result.deviceToken;- } finally {- await pairing.close().catch(() => undefined);- }const summary = await boot.addHost({ hostKey, label, url, deviceToken });return { host: summary };},);+ registrar.handle(+ IPC.invoke.remoteHostBootstrap,+ async (request: RemoteHostBootstrapRequest): Promise<RemoteHostBootstrapResult> => {+ const boot = requireBoot(getRemoteHostsBoot());+ const host = trim(request?.host);+ if (!host) throw invalid("host is required", "host");+ const label = trim(request?.label) || host;+ // The descriptor's own validation (empty and leading-dash fields, port+ // range) lives with the bootstrap, which is the only place that knows+ // how the values reach the `ssh` command line.+ return await boot.bootstrapHost({ ...request, host, label });+ },+ );+registrar.handle(IPC.invoke.remoteHostRemove,async (request: RemoteHostRemoveRequest): Promise<{ ok: true }> => {const boot = requireBoot(getRemoteHostsBoot());const hostKey = trim(request?.hostKey);if (!hostKey) {- throw Object.assign(new Error("hostKey is required"), {- errorCode: ErrorCodes.INVALID_ARGUMENT,- });+ throw invalid("hostKey is required", "hostKey");}await boot.removeHost(hostKey);return { ok: true };diff --git a/apps/desktop/electron/main/remote/pi-host-bootstrap-script.ts b/apps/desktop/electron/main/remote/pi-host-bootstrap-script.tsnew file mode 100644index 000000000..208965294--- /dev/null+++ b/apps/desktop/electron/main/remote/pi-host-bootstrap-script.ts@@ -0,0 +1,319 @@+/**+ * The bootstrap script the desktop uploads over SSH (spec §5.2 step 2, §3.4).+ *+ * The script is the only artifact that runs on the remote machine. It downloads+ * the bundle the desktop pinned, verifies it against the digest the desktop+ * read from the published `.sha256`, installs it under the user's home, starts+ * `pi-host` on loopback with a single-use pairing token, and echoes the two+ * machine-readable lines the desktop parses.+ *+ * Two properties matter and both are tested:+ *+ * - The pairing token only ever lands in a `umask 077` file inside the+ * bootstrap work directory on the remote machine, and on stdout of the SSH+ * channel. It is never written to a world-readable path and never appears in+ * a URL (security §3.4).+ * - Every failure exits non-zero with a `PI_HOST_BOOTSTRAP_FAILED <step>` line+ * so the desktop can report a typed error instead of a bare exit code.+ *+ * Inputs are interpolated as single-quoted shell literals by+ * {@link shellQuote}; callers never build the script from untrusted text.+ */++export type PiHostBootstrapScriptInput = {+ /** Desktop version; the bundle must exist for this tag. */+ version: string;+ /** Asset URL on GitHub Releases. */+ artifactUrl: string;+ /** Tarball file name, e.g. `pi-host-0.15.1-beta.5-linux-x64.tar.gz`. */+ artifactName: string;+ /** Unpacked directory name, e.g. `pi-host-0.15.1-beta.5-linux-x64`. */+ bundleDir: string;+ /** Lower-case hex digest from the published `.sha256`. */+ expectedSha256: string;+ /** Loopback port for `pi-host`; `0` lets it pick a free port and report it. */+ port: number;+ /** Pairing token lifetime handed to `--pairing-lifetime-ms`. */+ pairingLifetimeMs: number;+ /** How long the script waits for the ready and pairing lines. */+ readyTimeoutSec: number;+};++/** Smallest Node major the bundle is built for (`bundle.mjs --target=node22`). */+const MIN_NODE_MAJOR = 22;++/** POSIX-safe single-quoted literal; `'` becomes `'\''`. */+export function shellQuote(value: string): string {+ return `'${value.replace(/'/g, "'\\''")}'`;+}+/** Script variables in declaration order; the template interpolates the block. */+const SCRIPT_VARIABLES = [+ "VERSION",+ "ARTIFACT_URL",+ "ARTIFACT_NAME",+ "BUNDLE_DIR",+ "EXPECTED_SHA256",+ "PORT",+ "PAIRING_LIFETIME_MS",+ "READY_TIMEOUT_SEC",+ "MIN_NODE_MAJOR",+] as const;++export function buildBootstrapScript(input: PiHostBootstrapScriptInput): string {+ const values: string[] = [+ input.version,+ input.artifactUrl,+ input.artifactName,+ input.bundleDir,+ input.expectedSha256,+ String(input.port),+ String(input.pairingLifetimeMs),+ String(input.readyTimeoutSec),+ String(MIN_NODE_MAJOR),+ ];+ const assignments = SCRIPT_VARIABLES.map(+ (name, index) => `${name}=${shellQuote(values[index] ?? "")}`,+ ).join("\n");++ return `#!/bin/sh+# pi-host bootstrap — generated by PI-Desktop. Idempotent: it replaces the+# bundle for its own version, restarts the host it previously started, and+# prints a fresh single-use pairing token.+set -eu+umask 077++${assignments}++step() { printf '%s\\n' "PI_HOST_BOOTSTRAP $1"; }+die() {+ printf '%s\\n' "PI_HOST_BOOTSTRAP_FAILED $1" >&2+ printf '%s\\n' "PI_HOST_FAILED {\\"code\\":\\"HOST_BOOTSTRAP_FAILED\\",\\"step\\":\\"$1\\"}"+ exit 1+}++need() {+ command -v "$1" >/dev/null 2>&1 || die "missing-$1"+}++[ -n "\${HOME:-}" ] || die "no-home"++need node+need tar++node_major=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || printf '0')+[ "$node_major" -ge "$MIN_NODE_MAJOR" ] 2>/dev/null || die "node-too-old"++work="$HOME/.pi-desktop/pi-host/.bootstrap"+mkdir -p "$work"+log="$work/pi-host.log"+err="$work/pi-host.err"+pidfile="$work/pi-host.pid"+: > "$log"+: > "$err"++# --- download the pinned bundle -------------------------------------------+step "download"+http_get() {+ if command -v curl >/dev/null 2>&1; then+ curl -fsSL --max-time 600 -o "$2" "$1"+ elif command -v wget >/dev/null 2>&1; then+ wget -q --timeout=600 -O "$2" "$1"+ else+ return 127+ fi+}++tarball="$work/$ARTIFACT_NAME"+rm -f "$tarball"+http_get "$ARTIFACT_URL" "$tarball" || die "download-failed"++# --- verify the published digest ------------------------------------------+step "verify"+sha256_of() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" | cut -d ' ' -f 1+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" | cut -d ' ' -f 1+ else+ return 127+ fi+}+actual_sha256=$(sha256_of "$tarball") || die "missing-sha256-tool"+[ "$actual_sha256" = "$EXPECTED_SHA256" ] || die "checksum-mismatch"++# --- install under the user's home ----------------------------------------+step "install"+unpack="$work/unpack"+rm -rf "$unpack"+mkdir -p "$unpack"+tar -xzf "$tarball" -C "$unpack" || die "extract-failed"+[ -d "$unpack/$BUNDLE_DIR" ] || die "unexpected-archive-layout"+sh "$unpack/$BUNDLE_DIR/install.sh" >/dev/null || die "install-failed"++# --- (re)start on loopback with a fresh pairing token ----------------------+step "start"+if [ -f "$pidfile" ]; then+ previous=$(cat "$pidfile" 2>/dev/null || true)+ # The pidfile is never removed, so a recycled PID could name an unrelated+ # process owned by the same user. Only signal it when it is still our+ # pi-host; anything else is left alone.+ if [ -n "$previous" ] && kill -0 "$previous" 2>/dev/null && \\+ ps -p "$previous" -o command= 2>/dev/null | grep -q 'pi-host.js'; then+ kill "$previous" 2>/dev/null || true+ waited=0+ while kill -0 "$previous" 2>/dev/null && [ "$waited" -lt 10 ]; do+ sleep 1+ waited=$((waited + 1))+ done+ fi+fi++nohup node "$HOME/.pi-desktop/pi-host/current/pi-host.js" \\+ --port "$PORT" \\+ --pair \\+ --pairing-lifetime-ms "$PAIRING_LIFETIME_MS" \\+ >"$log" 2>"$err" </dev/null &+host_pid=$!+printf '%s\\n' "$host_pid" > "$pidfile"++# --- wait for the ready and pairing lines ---------------------------------+step "await-ready"+waited=0+while [ "$waited" -lt "$READY_TIMEOUT_SEC" ]; do+ if grep -q '^PI_HOST_FAILED ' "$log" 2>/dev/null; then+ printf '%s\\n' "PI_HOST_FAILED {\\"code\\":\\"HOST_BOOTSTRAP_FAILED\\",\\"step\\":\\"host-start-failed\\"}"+ exit 1+ fi+ ready=$(grep -m1 '^PI_HOST_READY ' "$log" 2>/dev/null || true)+ token=$(grep -m1 '^PI_HOST_PAIRING_TOKEN ' "$log" 2>/dev/null || true)+ if [ -n "$ready" ] && [ -n "$token" ]; then+ printf '%s\\n' "$ready"+ printf '%s\\n' "$token"+ step "ok"+ exit 0+ fi+ if ! kill -0 "$host_pid" 2>/dev/null; then+ printf '%s\\n' "PI_HOST_FAILED {\\"code\\":\\"HOST_BOOTSTRAP_FAILED\\",\\"step\\":\\"host-exited\\"}"+ exit 1+ fi+ sleep 1+ waited=$((waited + 1))+done+die "ready-timeout"+`;+}++// ---------------------------------------------------------------------------+// Output parsing+// ---------------------------------------------------------------------------++export type PiHostReadyLine = {+ hostId: string;+ host: string;+ port: number;+ version: string;+};++export type PiHostPairingLine = {+ token: string;+ expiresAt: number;+};++export type PiHostBootstrapOutput = {+ ready: PiHostReadyLine | null;+ pairing: PiHostPairingLine | null;+ /** `PI_HOST_BOOTSTRAP <step>` progress lines, in order. */+ steps: string[];+ /** The `step` a `PI_HOST_FAILED` line reported, when the script failed. */+ failure: string | null;+};++function parseJsonObject(line: string, prefix: string): Record<string, unknown> | null {+ if (!line.startsWith(prefix)) return null;+ try {+ const parsed: unknown = JSON.parse(line.slice(prefix.length));+ return typeof parsed === "object" && parsed !== null+ ? (parsed as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}++/**+ * Read the bootstrap script's stdout. The script owns the format; this parser+ * is deliberately tolerant about interleaved progress lines and hostile about+ * missing fields, so a truncated channel cannot yield a half-built host.+ */+export function parseBootstrapOutput(stdout: string): PiHostBootstrapOutput {+ const output: PiHostBootstrapOutput = {+ ready: null,+ pairing: null,+ steps: [],+ failure: null,+ };++ for (const raw of stdout.split("\n")) {+ const line = raw.trim();+ if (!line) continue;++ if (line.startsWith("PI_HOST_BOOTSTRAP_FAILED ")) {+ if (!output.failure) output.failure = line.slice("PI_HOST_BOOTSTRAP_FAILED ".length).trim();+ continue;+ }+ if (line.startsWith("PI_HOST_BOOTSTRAP ")) {+ const step = line.slice("PI_HOST_BOOTSTRAP ".length).trim();+ if (step) output.steps.push(step);+ continue;+ }+ if (line.startsWith("PI_HOST_FAILED ")) {+ const payload = parseJsonObject(line, "PI_HOST_FAILED ");+ const code = payload?.code === "HOST_BOOTSTRAP_FAILED" ? payload.step : undefined;+ if (typeof code === "string" && !output.failure) output.failure = code;+ continue;+ }+ const ready = parseJsonObject(line, "PI_HOST_READY ");+ if (ready) {+ const { hostId, host, port, version } = ready;+ if (+ typeof hostId === "string" &&+ hostId.length > 0 &&+ typeof host === "string" &&+ typeof port === "number" &&+ Number.isInteger(port) &&+ port > 0 &&+ typeof version === "string"+ ) {+ output.ready = { hostId, host, port, version };+ }+ continue;+ }+ const pairing = parseJsonObject(line, "PI_HOST_PAIRING_TOKEN ");+ if (pairing) {+ const { token, expiresAt } = pairing;+ if (typeof token === "string" && token.length > 0) {+ output.pairing = {+ token,+ expiresAt: typeof expiresAt === "number" ? expiresAt : 0,+ };+ }+ }+ }++ return output;+}++/**+ * Replace the single-use pairing token in the script's stdout before it+ * reaches a log or an error payload. The token is only expected on stdout on+ * the success path, but a diagnostic that leaks a live token is worse than no+ * diagnostic at all.+ */+export function redactBootstrapOutput(stdout: string): string {+ return stdout+ .split("\n")+ .map((line) =>+ line.startsWith("PI_HOST_PAIRING_TOKEN ") ? "PI_HOST_PAIRING_TOKEN <redacted>" : line,+ )+ .join("\n");+}diff --git a/apps/desktop/electron/main/remote/pi-host-release.ts b/apps/desktop/electron/main/remote/pi-host-release.tsnew file mode 100644index 000000000..06f2da4d4--- /dev/null+++ b/apps/desktop/electron/main/remote/pi-host-release.ts@@ -0,0 +1,151 @@+/**+ * Release coordinates for the `pi-host` bundle the desktop installs on a+ * remote machine (spec `02-architecture/05-remote-agent-control.md` §5.2 step 2,+ * D375).+ *+ * The desktop never uploads executable bytes: it resolves the artifact for the+ * remote platform at *its own* version, keeps the SHA-256 the release publishes+ * as the trust anchor, and hands both to the bootstrap script that runs on the+ * remote machine. Everything here is pure so the URL, target, and checksum+ * rules stay testable without a network or an SSH connection.+ */+import { GITHUB_REPO } from "@pi-desktop/shared";++/** Platforms the bootstrap can classify from `uname -s`. */+export type PiHostPlatform = "linux" | "darwin";+/** Architectures the bootstrap can classify from `uname -m`. */+export type PiHostArch = "x64" | "arm64";++export type PiHostTarget = {+ platform: PiHostPlatform;+ arch: PiHostArch;+};++/**+ * Release-matrix parity. `release.yml`'s `pi-host-bundle` job publishes Linux+ * x64 only today; the desktop matrix ships no other Linux platform. A target+ * outside this list is refused with a typed failure instead of a 404 halfway+ * through a download.+ */+const PUBLISHED_TARGETS: readonly string[] = ["linux-x64"];++export function targetKey(target: PiHostTarget): string {+ return `${target.platform}-${target.arch}`;+}++export function isPublishedTarget(target: PiHostTarget): boolean {+ return PUBLISHED_TARGETS.includes(targetKey(target));+}++/** `uname -s` → a platform the release matrix can serve, or `null`. */+export function platformFromUname(systemName: string): PiHostPlatform | null {+ const value = systemName.trim().toLowerCase();+ if (value === "linux") return "linux";+ if (value === "darwin") return "darwin";+ return null;+}++/** `uname -m` → an architecture the release matrix can serve, or `null`. */+export function archFromUname(machine: string): PiHostArch | null {+ const value = machine.trim().toLowerCase();+ if (value === "x86_64" || value === "amd64") return "x64";+ if (value === "aarch64" || value === "arm64") return "arm64";+ return null;+}++/**+ * `uname -s` and `uname -m` are the only remote facts needed before a+ * download; they are collected in one exec so a host that answers at all+ * answers both.+ */+export function parseUnameOutput(stdout: string): { systemName: string; machine: string } {+ const lines = stdout+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0);+ return { systemName: lines[0] ?? "", machine: lines[1] ?? "" };+}++export function resolveTarget(stdout: string): PiHostTarget | null {+ const { systemName, machine } = parseUnameOutput(stdout);+ const platform = platformFromUname(systemName);+ const arch = archFromUname(machine);+ if (!platform || !arch) return null;+ return { platform, arch };+}++/** Directory name the tarball unpacks to, `bundle.mjs`'s `pi-host-<version>-<platform>-<arch>`. */+export function piHostBundleDir(version: string, target: PiHostTarget): string {+ return `pi-host-${version}-${targetKey(target)}`;+}++export function piHostArtifactName(version: string, target: PiHostTarget): string {+ return `${piHostBundleDir(version, target)}.tar.gz`;+}++/**+ * Release asset URLs. `release.yml` uploads both files to the `v<version>` tag,+ * so the desktop and the bootstrap script derive them without an API call.+ */+export function piHostArtifactUrls(+ version: string,+ target: PiHostTarget,+): { tarball: string; checksum: string } {+ const name = piHostArtifactName(version, target);+ const base = `https://github.com/${GITHUB_REPO}/releases/download/v${version}`;+ return { tarball: `${base}/${name}`, checksum: `${base}/${name}.sha256` };+}++const SHA256_HEX = /^[0-9a-f]{64}$/;++/** Lower-case a digest, or `null` when it is not 64 hex characters. */+export function normalizeChecksum(value: string): string | null {+ const trimmed = value.trim().toLowerCase();+ return SHA256_HEX.test(trimmed) ? trimmed : null;+}++/**+ * Read the digest out of a `sha256sum` file. `release.yml` writes+ * `<digest> <name>`; the file name is checked so a checksum for a different+ * artifact can never be mistaken for this one.+ */+export function parseChecksumFile(text: string, artifactName: string): string | null {+ for (const line of text.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ const [digest, ...rest] = trimmed.split(/\s+/);+ if (!digest) continue;+ const normalized = normalizeChecksum(digest);+ if (!normalized) continue;+ // `sha256sum` writes the bare name; some tools prefix `*` or a path.+ const named = rest.join(" ").replace(/^\*/, "").split("/").pop() ?? "";+ if (named && named !== artifactName) continue;+ return normalized;+ }+ return null;+}++/** Constant-work comparison of two normalized digests. */+export function checksumMatches(actual: string, expected: string): boolean {+ const left = normalizeChecksum(actual);+ const right = normalizeChecksum(expected);+ if (!left || !right) return false;+ let diff = 0;+ for (let index = 0; index < left.length; index += 1) {+ diff |= left.charCodeAt(index) ^ right.charCodeAt(index);+ }+ return diff === 0;+}++/**+ * A bootstrapped host must run the same release as the desktop: the bundle is+ * downloaded at the desktop's version and the RACP capability set is pinned to+ * it (D375). A leading `v` is tolerated on either side because the tag carries+ * one and `APP_VERSION` does not.+ */+export function versionsMatch(remote: string, local: string): boolean {+ const strip = (value: string) => value.trim().replace(/^v/, "");+ const a = strip(remote);+ const b = strip(local);+ return a.length > 0 && a === b;+}diff --git a/apps/desktop/electron/main/remote/racp-remote-host-client.ts b/apps/desktop/electron/main/remote/racp-remote-host-client.tsindex 704f22b6a..d543a8a73 100644--- a/apps/desktop/electron/main/remote/racp-remote-host-client.ts+++ b/apps/desktop/electron/main/remote/racp-remote-host-client.ts@@ -11,10 +11,56 @@* `packages/racp/src/test-harness.ts` so the adapter exercises the real* `RacpClient` state machine without a socket.*/-import { RacpClient, type ClientTransportFactory, type RacpClientState } from "@pi-desktop/racp";-import type { RacpEventEnvelope } from "@pi-desktop/shared";+import {+ RacpClient,+ wsClientTransport,+ type ClientTransportFactory,+ type RacpClientState,+} from "@pi-desktop/racp";+import { ErrorCodes, type RacpEventEnvelope } from "@pi-desktop/shared";import type { RemoteHostClient } from "./remote-host-connection.js";+export type PairingExchangeOptions = {+ /** Loopback RACP endpoint, either pasted by the user or forwarded by us. */+ url: string;+ /** Single-use `ppt1.` token the host printed at start. */+ pairingToken: string;+ /** Device label the host records against the minted device. */+ label: string;+ clientInfo: { name: string; version: string };+ log?: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;+};++/**+ * Spend a single-use pairing token on a throwaway connection and return the+ * durable `pdt1.` device token the host minted (spec §3.4).+ *+ * The connection is closed on every path — success, refusal, and transport+ * failure — because the token is consumed by the exchange and a lingering+ * unprivileged socket would only keep a half-paired session open.+ */+export async function exchangePairingToken(options: PairingExchangeOptions): Promise<string> {+ const pairing = createRacpRemoteHostClient({+ transport: wsClientTransport({ url: options.url, token: options.pairingToken }),+ clientInfo: options.clientInfo,+ log: options.log,+ });+ try {+ await pairing.connect();+ const result = (await pairing.client.request("connection/pair", {+ deviceLabel: options.label,+ })) as { deviceToken?: unknown };+ if (typeof result?.deviceToken !== "string" || result.deviceToken.length === 0) {+ throw Object.assign(new Error("pi-host did not return a device token"), {+ errorCode: ErrorCodes.PAIRING_FAILED,+ });+ }+ return result.deviceToken;+ } finally {+ await pairing.close().catch(() => undefined);+ }+}+export type RacpRemoteHostClientOptions = {transport: ClientTransportFactory;/** Identity sent in `connection/initialize`; the host records it as the device label. */diff --git a/apps/desktop/electron/main/remote/ssh-bootstrap.ts b/apps/desktop/electron/main/remote/ssh-bootstrap.tsnew file mode 100644index 000000000..519bda73f--- /dev/null+++ b/apps/desktop/electron/main/remote/ssh-bootstrap.ts@@ -0,0 +1,364 @@+/**+ * SSH bootstrap: install and pair a `pi-host` on a machine the user already+ * reaches over SSH (spec `02-architecture/05-remote-agent-control.md` §5.2,+ * security `05-security/02-remote-control-security.md` §3.4).+ *+ * The five steps mirror the spec exactly:+ *+ * 1. probe the remote with `uname` so the artifact is chosen for *its*+ * platform, not the desktop's;+ * 2. resolve the bundle at the desktop's version and read the SHA-256 the+ * release publishes — the desktop holds the trust anchor and never uploads+ * executable bytes;+ * 3. upload the bootstrap script through the SSH channel and run it, which+ * installs under the remote user's home and starts the host on loopback+ * with a single-use pairing token;+ * 4. forward a loopback port on this machine to the host's loopback port;+ * 5. spend the pairing token over that forward for a durable device token.+ *+ * Everything that touches the outside world is injected, so the whole flow is+ * exercised in tests against a fake transport and a fake pairing exchange.+ */+import {+ ErrorCodes,+ type RemoteHostBootstrapRequest,+ type RemoteHostSshMetadata,+} from "@pi-desktop/shared";+import {+ buildBootstrapScript,+ parseBootstrapOutput,+ redactBootstrapOutput,+} from "./pi-host-bootstrap-script.js";+import {+ isPublishedTarget,+ parseChecksumFile,+ piHostArtifactName,+ piHostArtifactUrls,+ piHostBundleDir,+ resolveTarget,+ targetKey,+ versionsMatch,+} from "./pi-host-release.js";+import {+ assertSshArgument,+ createSystemSshTransport,+ reserveLocalPort,+ type SshForward,+ type SshTarget,+ type SshExecResult,+ type SshTransport,+} from "./ssh-transport.js";+import { racpUrlForLocalPort } from "./ssh-tunnel.js";++/** Progress the Settings surface can render while a bootstrap runs. */+export type SshBootstrapStep =+ | "probe"+ | "resolve-release"+ | "download-checksum"+ | "install"+ | "forward"+ | "pair";++export type SshBootstrapDeps = {+ /** Release version the desktop runs; the bundle must exist for this tag. */+ version: string;+ /** Build the SSH transport for one target. Defaults to the system `ssh`. */+ buildTransport?: (target: SshTarget) => SshTransport;+ /** Read the published `.sha256` text. Defaults to an HTTPS GET. */+ fetchChecksum?: (url: string) => Promise<string>;+ /** Reserve the loopback port the forward binds. */+ reservePort?: () => Promise<number>;+ /**+ * Exchange the single-use pairing token for a durable device token over the+ * forwarded port. The boot layer injects this because it owns the RACP+ * client factory.+ */+ exchangePairing: (input: {+ url: string;+ pairingToken: string;+ label: string;+ }) => Promise<string>;+ /** Called once per completed step, in order. */+ onProgress?: (step: SshBootstrapStep) => void;+ log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;+ /** How long the script waits for the ready and pairing lines. */+ readyTimeoutSec?: number;+ /** Budget for the whole remote script, download included. */+ installTimeoutMs?: number;+};++export type SshBootstrapOutcome = {+ hostKey: string;+ label: string;+ /** Live forward; the caller adopts it and owns closing it. */+ forward: SshForward;+ /** The loopback RACP endpoint the pairing exchange used. */+ url: string;+ deviceToken: string;+ ssh: RemoteHostSshMetadata;+ /** Steps that completed, in order. */+ steps: SshBootstrapStep[];+};++export type SshBootstrap = {+ bootstrap(request: RemoteHostBootstrapRequest): Promise<SshBootstrapOutcome>;+};++const DEFAULT_READY_TIMEOUT_SEC = 120;+/**+ * Budget for the whole remote script. It must exceed the script's own worst+ * case — its `curl --max-time` plus the ready-timeout poll — or a slow+ * download would be killed from here and reported as a generic timeout.+ */+const DEFAULT_INSTALL_TIMEOUT_MS = 900_000;++function fail(message: string, errorCode: string, data?: Record<string, unknown>): Error {+ return Object.assign(new Error(message), { errorCode, ...(data ?? {}) });+}++/**+ * Stable routing key for a bootstrapped host. It lands inside+ * `remote:<hostKey>:<hostSessionId>`, so a colon would break the id — an IPv6+ * literal is folded to dashes rather than rejected, because the user typed it+ * in good faith and the key is only a routing label.+ */+export function synthesizeSshHostKey(ssh: SshTarget, label: string): string {+ const host = ssh.host.trim().toLowerCase().replace(/[^a-z0-9.-]+/g, "-").replace(/^-+|-+$/g, "");+ const slug = label+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 24);+ const base = host ? `ssh-${host}` : "ssh-host";+ return slug ? `${base}-${slug}` : base;+}++/** Translate the renderer request into the descriptor that gets persisted. */+export function sshMetadataFromTarget(target: SshTarget): Omit<RemoteHostSshMetadata, "remotePort" | "version"> {+ return {+ host: target.host,+ ...(target.port !== undefined ? { port: target.port } : {}),+ ...(target.user ? { user: target.user } : {}),+ ...(target.identityFile ? { identityFile: target.identityFile } : {}),+ };+}++async function defaultFetchChecksum(url: string): Promise<string> {+ const response = await fetch(url, {+ redirect: "follow",+ signal: AbortSignal.timeout(30_000),+ });+ if (!response.ok) {+ throw fail(`published checksum could not be downloaded (HTTP ${response.status})`, ErrorCodes.HOST_BOOTSTRAP_FAILED, {+ url,+ status: response.status,+ });+ }+ return await response.text();+}++function validateTarget(request: RemoteHostBootstrapRequest): SshTarget {+ const host = assertSshArgument(String(request?.host ?? ""), "host");+ const target: SshTarget = { host };+ if (request?.port !== undefined && request.port !== null) {+ const port = Number(request.port);+ if (!Number.isInteger(port) || port < 1 || port > 65_535) {+ throw fail("port must be an integer between 1 and 65535", ErrorCodes.INVALID_ARGUMENT, {+ field: "port",+ });+ }+ target.port = port;+ }+ if (request?.user) target.user = assertSshArgument(String(request.user), "user");+ if (request?.identityFile) {+ target.identityFile = assertSshArgument(String(request.identityFile), "identityFile");+ }+ return target;+}++/**+ * The port `pi-host` binds on the remote machine. Absent or `0` means "pick a+ * free one and report it", which is what the bootstrap normally wants; a+ * pinned port is range-checked here so it cannot reach the script as an+ * argument like `--port -5`.+ */+function resolveRemotePort(request: RemoteHostBootstrapRequest): number {+ const raw = request?.remotePort;+ if (raw === undefined || raw === null) return 0;+ const port = Number(raw);+ if (!Number.isInteger(port) || port < 0 || port > 65_535) {+ throw fail(+ "remotePort must be an integer between 0 and 65535",+ ErrorCodes.INVALID_ARGUMENT,+ { field: "remotePort" },+ );+ }+ return port;+}++export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {+ const log = deps.log ?? (() => undefined);+ const buildTransport =+ deps.buildTransport ??+ ((target: SshTarget) =>+ createSystemSshTransport(target, {+ log: (level, message, data) => log(level, message, data),+ }));+ const fetchChecksum = deps.fetchChecksum ?? defaultFetchChecksum;+ const reservePort = deps.reservePort ?? reserveLocalPort;+ const readyTimeoutSec = deps.readyTimeoutSec ?? DEFAULT_READY_TIMEOUT_SEC;+ const installTimeoutMs = deps.installTimeoutMs ?? DEFAULT_INSTALL_TIMEOUT_MS;++ return {+ async bootstrap(request) {+ const label = String(request?.label ?? "").trim() || "remote host";+ const target = validateTarget(request);+ const hostKey = (request?.hostKey ?? "").trim() || synthesizeSshHostKey(target, label);+ if (hostKey.includes(":")) {+ throw fail("hostKey must not contain ':'", ErrorCodes.INVALID_ARGUMENT, { field: "hostKey" });+ }++ const steps: SshBootstrapStep[] = [];+ const mark = (step: SshBootstrapStep): void => {+ steps.push(step);+ deps.onProgress?.(step);+ };++ const transport = buildTransport(target);+ let completed = false;+ try {+ // 1. Ask the remote machine what it is.+ mark("probe");+ const probe = await transport.exec("uname -s && uname -m");+ const remoteTarget = resolveTarget(probe.stdout);+ if (!remoteTarget) {+ throw fail(+ "the remote platform could not be identified",+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ { uname: probe.stdout.trim().slice(0, 200) },+ );+ }+ if (!isPublishedTarget(remoteTarget)) {+ throw fail(+ `no pi-host bundle is published for ${targetKey(remoteTarget)}`,+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ { target: targetKey(remoteTarget) },+ );+ }++ // 2. Resolve the artifact and the digest the release published for it.+ mark("resolve-release");+ const urls = piHostArtifactUrls(deps.version, remoteTarget);+ const artifactName = piHostArtifactName(deps.version, remoteTarget);+ mark("download-checksum");+ const expectedSha256 = parseChecksumFile(await fetchChecksum(urls.checksum), artifactName);+ if (!expectedSha256) {+ throw fail(+ `no usable SHA-256 published for ${artifactName}`,+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ { url: urls.checksum },+ );+ }++ // 3. Upload and run the script. It downloads the bundle itself, so no+ // executable bytes travel over this channel.+ mark("install");+ const script = buildBootstrapScript({+ version: deps.version,+ artifactUrl: urls.tarball,+ artifactName,+ bundleDir: piHostBundleDir(deps.version, remoteTarget),+ expectedSha256,+ port: resolveRemotePort(request),+ pairingLifetimeMs: 600_000,+ readyTimeoutSec,+ });+ let result: SshExecResult;+ try {+ result = await transport.execWithInput("sh -s", script, {+ timeoutMs: installTimeoutMs,+ });+ } catch (error) {+ // The script names the step it failed at on stdout even when it+ // exits non-zero, and the transport carries that stdout on the+ // error. Surfacing it is the difference between "exit code 1" and+ // "checksum-mismatch" in the user's toast.+ const reported = parseBootstrapOutput(+ String((error as { stdout?: unknown }).stdout ?? ""),+ );+ if (!reported.failure) throw error;+ throw fail(+ `the remote bootstrap failed at '${reported.failure}'`,+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ {+ step: reported.failure,+ stderr: String((error as { stderr?: unknown }).stderr ?? "").slice(-2000),+ },+ );+ }+ const parsed = parseBootstrapOutput(result.stdout);+ if (parsed.failure) {+ throw fail(`the remote bootstrap failed at '${parsed.failure}'`, ErrorCodes.HOST_BOOTSTRAP_FAILED, {+ step: parsed.failure,+ stderr: result.stderr.slice(-2000),+ });+ }+ if (!parsed.ready || !parsed.pairing) {+ throw fail(+ "the remote bootstrap produced no ready/pairing output",+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ {+ stdout: redactBootstrapOutput(result.stdout).slice(-2000),+ stderr: result.stderr.slice(-2000),+ },+ );+ }+ if (!versionsMatch(parsed.ready.version, deps.version)) {+ throw fail(+ `the remote host runs ${parsed.ready.version}; this desktop runs ${deps.version}`,+ ErrorCodes.HOST_VERSION_MISMATCH,+ { remote: parsed.ready.version, local: deps.version },+ );+ }++ // 4. Forward a loopback port to the host's loopback port.+ mark("forward");+ const localPort = await reservePort();+ const forward = await transport.forward({+ localPort,+ remoteHost: "127.0.0.1",+ remotePort: parsed.ready.port,+ });+ const url = racpUrlForLocalPort(localPort);++ // 5. Spend the pairing token over the forward.+ mark("pair");+ let deviceToken: string;+ try {+ deviceToken = await deps.exchangePairing({+ url,+ pairingToken: parsed.pairing.token,+ label,+ });+ } catch (error) {+ await forward.close().catch(() => undefined);+ throw error;+ }++ const ssh: RemoteHostSshMetadata = {+ ...sshMetadataFromTarget(target),+ remotePort: parsed.ready.port,+ version: parsed.ready.version,+ };+ completed = true;+ log("info", "ssh bootstrap completed", { hostKey, url, version: ssh.version });+ return { hostKey, label, forward, url, deviceToken, ssh, steps };+ } finally {+ // On success the caller adopts the forward, which is a child of this+ // transport — disposing here would tear down the tunnel it just got.+ if (!completed) transport.dispose();+ }+ },+ };+}diff --git a/apps/desktop/electron/main/remote/ssh-transport.ts b/apps/desktop/electron/main/remote/ssh-transport.tsnew file mode 100644index 000000000..1bafafd71--- /dev/null+++ b/apps/desktop/electron/main/remote/ssh-transport.ts@@ -0,0 +1,432 @@+/**+ * The SSH seam of the remote-host bootstrap (spec `05-remote-agent-control.md`+ * §5.2 step 1: "The desktop opens SSH with the user's existing configuration+ * and keys").+ *+ * Shelling out to the system `ssh` rather than linking an SSH client is the+ * deliberate choice here:+ *+ * - The user's `~/.ssh/config`, agent, `known_hosts`, and jump hosts apply+ * exactly as they do in their terminal, so a machine that is reachable from+ * the shell is reachable from the app with no second credential store.+ * - The desktop never holds, prompts for, or persists an SSH secret; there is+ * nothing for the app to leak.+ *+ * `BatchMode=yes` is what keeps that honest: a host that needs an interactive+ * password or passphrase fails immediately with a typed error instead of+ * hanging a modal behind an invisible prompt.+ *+ * The module is a port so the bootstrap orchestrator can be tested against a+ * fake; `createSystemSshTransport` is the only implementation that spawns.+ */+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { createServer, connect } from "node:net";+import { ErrorCodes } from "@pi-desktop/shared";+import { redactBootstrapOutput } from "./pi-host-bootstrap-script.js";++/** Where to reach a machine over SSH. */+export type SshTarget = {+ host: string;+ port?: number;+ user?: string;+ identityFile?: string;+};++export type SshExecResult = {+ stdout: string;+ stderr: string;+ code: number;+};++/** A live local→remote port forward; `close` is idempotent. */+export type SshForward = {+ /** The loopback port on this machine that reaches `remotePort`. */+ localPort: number;+ close(): Promise<void>;+};++export interface SshTransport {+ /** Run `command` through the remote user's shell. */+ exec(command: string, options?: { timeoutMs?: number }): Promise<SshExecResult>;+ /** Run `command` with `input` written to its stdin (used to upload the script). */+ execWithInput(+ command: string,+ input: string,+ options?: { timeoutMs?: number },+ ): Promise<SshExecResult>;+ /** Forward a loopback port on this machine to a loopback port on the remote. */+ forward(options: {+ localPort: number;+ remoteHost: string;+ remotePort: number;+ timeoutMs?: number;+ }): Promise<SshForward>;+ /** Kill anything still running. Safe to call twice. */+ dispose(): void;+}++export type SystemSshTransportOptions = {+ /**+ * `ssh` executable to spawn. Defaults to `ssh` on PATH; tests point it at a+ * fixture script.+ */+ binary?: string;+ /** Extra `-o` options appended after the ones this module always sets. */+ extraOptions?: string[];+ log?: (level: "info" | "warn", message: string, data?: unknown) => void;+};++const DEFAULT_EXEC_TIMEOUT_MS = 120_000;+const DEFAULT_FORWARD_TIMEOUT_MS = 30_000;++function fail(message: string, errorCode: string, data?: Record<string, unknown>): Error {+ return Object.assign(new Error(message), { errorCode, ...(data ?? {}) });+}++/**+ * Reject a value that would be read as an `ssh` option rather than as a+ * destination. `host` is passed as its own argv entry, so a leading `-` is the+ * only way it can influence the command line (`-oProxyCommand=…`).+ */+export function assertSshArgument(value: string, field: string): string {+ const trimmed = value.trim();+ if (!trimmed) {+ throw fail(`${field} must not be empty`, ErrorCodes.INVALID_ARGUMENT, { field });+ }+ if (trimmed.startsWith("-")) {+ throw fail(`${field} must not start with '-'`, ErrorCodes.INVALID_ARGUMENT, { field });+ }+ return trimmed;+}++/** The argv `ssh` receives, minus the final command. */+export function sshCommonArgs(target: SshTarget): string[] {+ const args = [+ // Fail instead of prompting: there is no terminal behind this spawn.+ "-o",+ "BatchMode=yes",+ // Trust-on-first-use, as `ssh` itself offers interactively.+ "-o",+ "StrictHostKeyChecking=accept-new",+ "-o",+ "ConnectTimeout=15",+ // A forward that cannot be set up must not leave a half-open session.+ "-o",+ "ExitOnForwardFailure=yes",+ ];+ if (target.port !== undefined) args.push("-p", String(target.port));+ if (target.identityFile) args.push("-i", target.identityFile);+ const user = target.user?.trim();+ args.push(user ? `${user}@${target.host}` : target.host);+ return args;+}++/** A loopback port nothing is listening on, for `-L` to claim. */+export function reserveLocalPort(): Promise<number> {+ return new Promise((resolvePort, rejectPort) => {+ const probe = createServer();+ probe.unref();+ probe.once("error", rejectPort);+ probe.listen(0, "127.0.0.1", () => {+ const address = probe.address();+ const port = typeof address === "object" && address ? address.port : 0;+ probe.close(() => {+ if (port > 0) resolvePort(port);+ else rejectPort(fail("could not reserve a loopback port", ErrorCodes.REMOTE_FORWARD_FAILED));+ });+ });+ });+}++/**+ * Resolve once something accepts a TCP connection on `port`.+ *+ * The poll is abortable because it outlives the decision it informs: when the+ * ssh child dies first the caller has already failed the forward, and a+ * referenced retry timer would otherwise keep polling — and keep the event+ * loop alive — until the full timeout elapsed.+ */+function waitForLoopbackConnect(+ port: number,+ timeoutMs: number,+ signal?: AbortSignal,+): Promise<void> {+ const deadline = Date.now() + timeoutMs;+ return new Promise((resolveConnected, rejectConnected) => {+ let pending: NodeJS.Timeout | null = null;+ let settled = false;+ const finish = (error?: Error): void => {+ if (settled) return;+ settled = true;+ if (pending) clearTimeout(pending);+ pending = null;+ if (error) rejectConnected(error);+ else resolveConnected();+ };+ signal?.addEventListener(+ "abort",+ () =>+ finish(+ fail(+ `port forward on 127.0.0.1:${port} was cancelled`,+ ErrorCodes.REMOTE_FORWARD_FAILED,+ ),+ ),+ { once: true },+ );+ const attempt = (): void => {+ if (settled) return;+ const socket = connect({ host: "127.0.0.1", port });+ socket.once("connect", () => {+ socket.destroy();+ finish();+ });+ socket.once("error", () => {+ socket.destroy();+ if (settled) return;+ if (Date.now() >= deadline) {+ finish(+ fail(+ `port forward on 127.0.0.1:${port} never became reachable`,+ ErrorCodes.REMOTE_FORWARD_FAILED,+ ),+ );+ return;+ }+ pending = setTimeout(attempt, 150);+ });+ };+ attempt();+ });+}++function runCommand(+ binary: string,+ args: string[],+ options: {+ input?: string;+ timeoutMs: number;+ /** Called with the spawned child so a transport can track and reap it. */+ onSpawn?: (child: ChildProcessWithoutNullStreams) => void;+ },+): Promise<SshExecResult> {+ return new Promise((resolveRun, rejectRun) => {+ let child: ChildProcessWithoutNullStreams;+ try {+ child = spawn(binary, args, { stdio: ["pipe", "pipe", "pipe"] });+ } catch (error) {+ rejectRun(+ fail(+ `${binary} could not be started: ${error instanceof Error ? error.message : String(error)}`,+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ ),+ );+ return;+ }++ // A caller that owns a lifetime (dispose) tracks the child from here.+ options.onSpawn?.(child);++ let stdout = "";+ let stderr = "";+ let settled = false;+ const timer = setTimeout(() => {+ if (settled) return;+ settled = true;+ child.kill("SIGKILL");+ rejectRun(+ fail(`${binary} timed out after ${options.timeoutMs} ms`, ErrorCodes.HOST_BOOTSTRAP_FAILED, {+ stderr: stderr.slice(-2000),+ }),+ );+ }, options.timeoutMs);++ child.stdout.on("data", (chunk: Buffer) => {+ stdout += chunk.toString("utf8");+ });+ child.stderr.on("data", (chunk: Buffer) => {+ stderr += chunk.toString("utf8");+ });+ child.once("error", (error: Error) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ // ENOENT here means the ssh client is not installed, which is a user+ // fix ("install OpenSSH"), not a remote-machine fault.+ rejectRun(+ fail(`${binary} could not be started: ${error.message}`, ErrorCodes.HOST_BOOTSTRAP_FAILED),+ );+ });+ child.once("close", (code: number | null) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ resolveRun({ stdout, stderr, code: code ?? -1 });+ });++ // A child that exits early closes the pipe under us; swallowing the write+ // error keeps it from surfacing as an unhandled stream error.+ child.stdin.on("error", () => undefined);+ if (options.input !== undefined) child.stdin.end(options.input);+ else child.stdin.end();+ });+}++export function createSystemSshTransport(+ target: SshTarget,+ options: SystemSshTransportOptions = {},+): SshTransport {+ const binary = options.binary ?? "ssh";+ const log = options.log ?? (() => undefined);+ const base = [...sshCommonArgs(target), ...(options.extraOptions ?? [])];+ const children = new Set<ChildProcessWithoutNullStreams>();++ const spawnTracked = (args: string[]): ChildProcessWithoutNullStreams => {+ const child = spawn(binary, args, { stdio: ["pipe", "pipe", "pipe"] });+ children.add(child);+ child.once("close", () => children.delete(child));+ child.once("error", () => children.delete(child));+ return child;+ };++ const execOnce = async (+ command: string,+ input: string | undefined,+ timeoutMs: number,+ ): Promise<SshExecResult> => {+ // `sh -s` reads the script from stdin, so the script never has to survive+ // an argv round trip and never lands in a remote file we must clean up.+ const args = input === undefined ? [...base, command] : [...base, "sh -s"];+ const result = await runCommand(binary, args, {+ input,+ timeoutMs,+ onSpawn: (child) => {+ children.add(child);+ child.once("close", () => children.delete(child));+ child.once("error", () => children.delete(child));+ },+ });+ if (result.code !== 0) {+ throw fail(+ `ssh command failed with exit code ${result.code}`,+ ErrorCodes.HOST_BOOTSTRAP_FAILED,+ {+ command,+ code: result.code,+ stderr: redactBootstrapOutput(result.stderr).slice(-2000),+ // The bootstrap script reports *where* it failed on stdout, so the+ // caller can turn a bare exit code into a named step.+ stdout: redactBootstrapOutput(result.stdout).slice(-4000),+ },+ );+ }+ return result;+ };++ return {+ exec: (command, execOptions) =>+ execOnce(command, undefined, execOptions?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS),+ execWithInput: (command, input, execOptions) =>+ execOnce(command, input, execOptions?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS),+ async forward({ localPort, remoteHost, remotePort, timeoutMs }) {+ const args = [+ ...base,+ "-N",+ "-L",+ `127.0.0.1:${localPort}:${remoteHost}:${remotePort}`,+ ];+ const child = spawnTracked(args);+ let stderr = "";+ child.stderr.on("data", (chunk: Buffer) => {+ stderr += chunk.toString("utf8");+ });+ // A forward that cannot bind must fail fast, and the ssh diagnostic on+ // stderr is the only thing that explains why. The gate is resolved from+ // the child's own exit and is registered before the race is awaited, so+ // a dead ssh rejects immediately instead of waiting out the probe.+ let exited = false;+ const earlyGate: { reject?: (error: Error) => void } = {};+ const early = new Promise<never>((_resolve, rejectEarly) => {+ earlyGate.reject = rejectEarly;+ });+ child.once("close", (code: number | null) => {+ exited = true;+ earlyGate.reject?.(+ fail(+ `ssh exited before the forward was ready (code ${code ?? -1}): ${+ stderr.trim().slice(-500) || "no diagnostic"+ }`,+ ErrorCodes.REMOTE_FORWARD_FAILED,+ ),+ );+ });+ child.once("error", (error: Error) => {+ exited = true;+ earlyGate.reject?.(+ fail(`${binary} could not be started: ${error.message}`, ErrorCodes.REMOTE_FORWARD_FAILED),+ );+ });++ // `ExitOnForwardFailure=yes` makes a doomed forward die, but a healthy+ // one prints nothing; the local port accepting connections is the only+ // readiness signal. It is not proof on its own — the reserved port was+ // released before ssh bound it, so an unrelated local listener could+ // answer the probe. A still-running ssh is what rules that out.+ const probeAbort = new AbortController();+ const probe = waitForLoopbackConnect(+ localPort,+ timeoutMs ?? DEFAULT_FORWARD_TIMEOUT_MS,+ probeAbort.signal,+ ).then(() => {+ if (exited) {+ throw fail(+ `ssh exited before the forward on 127.0.0.1:${localPort} was ready`,+ ErrorCodes.REMOTE_FORWARD_FAILED,+ );+ }+ });++ try {+ await Promise.race([probe, early]);+ } catch (error) {+ // The probe has already lost; stop its poll instead of letting it run+ // to its own deadline with a referenced timer.+ probeAbort.abort();+ child.kill("SIGKILL");+ throw error instanceof Error && "errorCode" in error+ ? error+ : fail(+ `port forward failed: ${stderr.trim().slice(-500) || String(error)}`,+ ErrorCodes.REMOTE_FORWARD_FAILED,+ );+ }++ let disposed = false;+ return {+ localPort,+ async close() {+ if (disposed) return;+ disposed = true;+ if (exited) return;+ child.kill("SIGTERM");+ await new Promise<void>((resolveClosed) => {+ const timer = setTimeout(() => {+ child.kill("SIGKILL");+ resolveClosed();+ }, 5_000);+ timer.unref();+ child.once("close", () => {+ clearTimeout(timer);+ resolveClosed();+ });+ });+ },+ };+ },+ dispose() {+ for (const child of children) child.kill("SIGKILL");+ children.clear();+ log("info", "ssh transport disposed", { host: target.host });+ },+ };+}diff --git a/apps/desktop/electron/main/remote/ssh-tunnel.ts b/apps/desktop/electron/main/remote/ssh-tunnel.tsnew file mode 100644index 000000000..0ae15aefa--- /dev/null+++ b/apps/desktop/electron/main/remote/ssh-tunnel.ts@@ -0,0 +1,155 @@+/**+ * Durable SSH port forwards for bootstrapped remote hosts (spec §5.2 step 4).+ *+ * A paired host is reached at `ws://127.0.0.1:<forwarded port>`, and that port+ * only exists while an `ssh -N -L` session is alive. The manager owns those+ * sessions for the lifetime of the app: one per host key, re-used while the+ * host stays paired, closed when the host is removed or the app quits.+ *+ * The forward is opened lazily by {@link SshTunnelManager.open} on the next+ * launch, and adopted from the bootstrap on the pairing path+ * ({@link SshTunnelManager.adopt}) so pairing never pays for a forward it is+ * about to throw away.+ */+import { RACP_WS_PATH, type RemoteHostSshMetadata } from "@pi-desktop/shared";+import {+ createSystemSshTransport,+ reserveLocalPort,+ type SshForward,+ type SshTarget,+ type SshTransport,+} from "./ssh-transport.js";++/** The loopback RACP endpoint a forward on `port` exposes. */+export function racpUrlForLocalPort(port: number): string {+ return `ws://127.0.0.1:${port}${RACP_WS_PATH}`;+}++/** Translate a persisted descriptor into `ssh` arguments. */+export function sshTargetOf(ssh: RemoteHostSshMetadata): SshTarget {+ return {+ host: ssh.host,+ ...(ssh.port !== undefined ? { port: ssh.port } : {}),+ ...(ssh.user ? { user: ssh.user } : {}),+ ...(ssh.identityFile ? { identityFile: ssh.identityFile } : {}),+ };+}++export type SshTunnel = {+ /** `ws://127.0.0.1:<localPort>/v1/racp/ws` for this host right now. */+ url: string;+ localPort: number;+};++export type SshTunnelManagerOptions = {+ /**+ * Build the transport for one host. Defaults to the system `ssh` client,+ * which is what makes the user's own `~/.ssh/config` and agent apply; tests+ * substitute a fake so no process is spawned.+ */+ buildTransport?: (ssh: RemoteHostSshMetadata) => SshTransport;+ /** Reserve the loopback port `-L` binds. Injectable for deterministic tests. */+ reservePort?: () => Promise<number>;+ log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;+};++export interface SshTunnelManager {+ /** Open the forward for `hostKey`, or return the live one. */+ open(hostKey: string, ssh: RemoteHostSshMetadata): Promise<SshTunnel>;+ /** Take ownership of a forward the bootstrap already opened. */+ adopt(hostKey: string, ssh: RemoteHostSshMetadata, forward: SshForward): Promise<SshTunnel>;+ /** Close the forward for one host; a missing key is a no-op. */+ close(hostKey: string): Promise<void>;+ /** Close every forward. Idempotent; safe before any `open`. */+ dispose(): Promise<void>;+}++type TunnelEntry = {+ ssh: RemoteHostSshMetadata;+ transport: SshTransport;+ forward: SshForward;+ tunnel: SshTunnel;+};++export function createSshTunnelManager(options: SshTunnelManagerOptions = {}): SshTunnelManager {+ const log = options.log ?? (() => undefined);+ const buildTransport =+ options.buildTransport ??+ ((ssh: RemoteHostSshMetadata) =>+ createSystemSshTransport(sshTargetOf(ssh), {+ log: (level, message, data) => log(level, message, data),+ }));+ const reservePort = options.reservePort ?? reserveLocalPort;+ const entries = new Map<string, TunnelEntry>();++ const closeEntry = async (entry: TunnelEntry): Promise<void> => {+ try {+ await entry.forward.close();+ } catch (error) {+ log("warn", "ssh forward close threw", { error: String(error) });+ }+ entry.transport.dispose();+ };++ const remember = (hostKey: string, ssh: RemoteHostSshMetadata, transport: SshTransport, forward: SshForward): SshTunnel => {+ const tunnel: SshTunnel = { url: racpUrlForLocalPort(forward.localPort), localPort: forward.localPort };+ entries.set(hostKey, { ssh, transport, forward, tunnel });+ return tunnel;+ };+++ /** Drop one entry and reap its process; shared by `close` and `adopt`. */+ const closeForKey = async (hostKey: string): Promise<void> => {+ const entry = entries.get(hostKey);+ if (!entry) return;+ entries.delete(hostKey);+ await closeEntry(entry);+ };+ return {+ async open(hostKey, ssh) {+ const existing = entries.get(hostKey);+ if (existing) return existing.tunnel;++ const transport = buildTransport(ssh);+ // A dead ssh client must not take the app with it; `forward` reports the+ // failure through its own rejection.+ let forward: SshForward;+ try {+ forward = await transport.forward({+ localPort: await reservePort(),+ remoteHost: "127.0.0.1",+ remotePort: ssh.remotePort,+ });+ } catch (error) {+ transport.dispose();+ throw error;+ }+ log("info", "ssh forward open", { hostKey, localPort: forward.localPort, remotePort: ssh.remotePort });+ return remember(hostKey, ssh, transport, forward);+ },++ async adopt(hostKey, ssh, forward) {+ const existing = entries.get(hostKey);+ if (existing) await closeForKey(hostKey);+ // The adopted forward already owns a live ssh process; the entry keeps a+ // transport only so `close` can reap anything else it started.+ const transport: SshTransport = {+ exec: () => Promise.reject(new Error("adopted tunnel transports are write-only")),+ execWithInput: () => Promise.reject(new Error("adopted tunnel transports are write-only")),+ forward: () => Promise.reject(new Error("adopted tunnel transports are write-only")),+ dispose: () => undefined,+ };+ return remember(hostKey, ssh, transport, forward);+ },++ async close(hostKey) {+ await closeForKey(hostKey);+ },++ async dispose() {+ const all = [...entries.values()];+ entries.clear();+ await Promise.allSettled(all.map((entry) => closeEntry(entry)));+ },+ };+}diff --git a/apps/desktop/src/components/settings/RemoteHostsPage.tsx b/apps/desktop/src/components/settings/RemoteHostsPage.tsxindex e7889acd6..4b962ee47 100644--- a/apps/desktop/src/components/settings/RemoteHostsPage.tsx+++ b/apps/desktop/src/components/settings/RemoteHostsPage.tsx@@ -24,6 +24,22 @@ type PairForm = {const EMPTY_FORM: PairForm = { url: "", pairingToken: "", label: "" };+type SshForm = {+ label: string;+ host: string;+ user: string;+ port: string;+ identityFile: string;+};++const EMPTY_SSH_FORM: SshForm = {+ label: "",+ host: "",+ user: "",+ port: "",+ identityFile: "",+};+export function RemoteHostsPage() {const { t } = useTranslation();const showToast = useAppStore((state) => state.showToast);@@ -32,6 +48,8 @@ export function RemoteHostsPage() {const [form, setForm] = useState<PairForm>(EMPTY_FORM);const [pairing, setPairing] = useState(false);const [removing, setRemoving] = useState<string | null>(null);+ const [sshForm, setSshForm] = useState<SshForm>(EMPTY_SSH_FORM);+ const [installing, setInstalling] = useState(false);const refresh = useCallback(async () => {try {@@ -92,6 +110,41 @@ export function RemoteHostsPage() {[refresh, showToast, t],);+ const submitSsh = useCallback(+ async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ const label = sshForm.label.trim();+ const host = sshForm.host.trim();+ if (!host || !label) return;+ const user = sshForm.user.trim();+ const identityFile = sshForm.identityFile.trim();+ const port = sshForm.port.trim();+ setInstalling(true);+ try {+ // Empty optional fields are dropped rather than sent blank, so main+ // falls back to the SSH config and the local user name.+ const result = await api.bootstrapRemoteHost({+ label,+ host,+ ...(user ? { user } : {}),+ ...(identityFile ? { identityFile } : {}),+ ...(port ? { port: Number(port) } : {}),+ });+ showToast(t("settings.remoteHosts.sshSucceeded", { label: result.host.label }), {+ variant: "info",+ });+ setSshForm(EMPTY_SSH_FORM);+ await refresh();+ } catch (caught) {+ const message = caught instanceof Error ? caught.message : String(caught);+ showToast(t("settings.remoteHosts.sshFailed", { message }), { variant: "error" });+ } finally {+ setInstalling(false);+ }+ },+ [sshForm, refresh, showToast, t],+ );+return (<div className="settings-stack"><SettingsCard title={t("settings.remoteHosts.listTitle")}>@@ -119,7 +172,10 @@ export function RemoteHostsPage() {key={host.hostKey}title={host.label}description={- <span className="font-mono text-xs-plus text-text-muted">{host.url}</span>+ <span className="font-mono text-xs-plus text-text-muted">+ {host.transport === "ssh" ? "ssh · " : ""}+ {host.url}+ </span>}><span@@ -220,6 +276,106 @@ export function RemoteHostsPage() {</button></SettingsRow></form>++ <SettingsCard title={t("settings.remoteHosts.sshTitle")}>+ <div className="settings-row-copy" role="note">+ <div className="settings-row-desc">{t("settings.remoteHosts.sshBody")}</div>+ </div>+ <form onSubmit={submitSsh} className="settings-remote-host-form">+ <SettingsRow+ title={t("settings.remoteHosts.fieldLabel")}+ description={t("settings.remoteHosts.fieldLabelDesc")}+ >+ <Input+ value={sshForm.label}+ onChange={(event) =>+ setSshForm((prev) => ({ ...prev, label: event.target.value }))+ }+ placeholder={t("settings.remoteHosts.fieldLabelPlaceholder")}+ aria-label={t("settings.remoteHosts.fieldLabel")}+ autoComplete="off"+ spellCheck={false}+ disabled={installing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.sshHost")}+ description={t("settings.remoteHosts.sshHostDesc")}+ >+ <Input+ value={sshForm.host}+ onChange={(event) =>+ setSshForm((prev) => ({ ...prev, host: event.target.value }))+ }+ placeholder={t("settings.remoteHosts.sshHostPlaceholder")}+ aria-label={t("settings.remoteHosts.sshHost")}+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ disabled={installing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.sshUser")}+ description={t("settings.remoteHosts.sshUserDesc")}+ >+ <Input+ value={sshForm.user}+ onChange={(event) =>+ setSshForm((prev) => ({ ...prev, user: event.target.value }))+ }+ aria-label={t("settings.remoteHosts.sshUser")}+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ disabled={installing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.sshPort")}+ description={t("settings.remoteHosts.sshPortDesc")}+ >+ <Input+ value={sshForm.port}+ onChange={(event) =>+ setSshForm((prev) => ({ ...prev, port: event.target.value }))+ }+ aria-label={t("settings.remoteHosts.sshPort")}+ inputMode="numeric"+ autoComplete="off"+ spellCheck={false}+ disabled={installing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.sshIdentityFile")}+ description={t("settings.remoteHosts.sshIdentityFileDesc")}+ >+ <Input+ value={sshForm.identityFile}+ onChange={(event) =>+ setSshForm((prev) => ({ ...prev, identityFile: event.target.value }))+ }+ aria-label={t("settings.remoteHosts.sshIdentityFile")}+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ disabled={installing}+ />+ </SettingsRow>+ <SettingsRow title={t("settings.remoteHosts.sshAction")}>+ <button+ type="submit"+ className="settings-button primary"+ disabled={installing || !sshForm.host.trim() || !sshForm.label.trim()}+ >+ {installing+ ? t("settings.remoteHosts.sshRunning")+ : t("settings.remoteHosts.sshAction")}+ </button>+ </SettingsRow>+ </form>+ </SettingsCard></SettingsCard></div>);diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 895e7ab8d..fbd52b76b 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -100,6 +100,8 @@ import type {PlanResolutionResult,PlanningStateEvent,PlansPendingResult,+ RemoteHostBootstrapRequest,+ RemoteHostBootstrapResult,RemoteHostPairRequest,RemoteHostPairResult,RemoteHostSummary,@@ -1375,6 +1377,13 @@ export const api = {/** Exchange `ppt1.` pairing token for a durable device token and connect. */pairRemoteHost: (request: RemoteHostPairRequest) =>invoke<RemoteHostPairResult>(IPC.invoke.remoteHostPair, request),+ /**+ * Install and pair a `pi-host` over SSH on a machine the user already+ * reaches, then bring it online (spec §5.2). Credentials come from the+ * user's own SSH configuration and agent.+ */+ bootstrapRemoteHost: (request: RemoteHostBootstrapRequest) =>+ invoke<RemoteHostBootstrapResult>(IPC.invoke.remoteHostBootstrap, request),/** Close and drop a paired host by its stable routing key. */removeRemoteHost: (hostKey: string) =>invoke<{ ok: true }>(IPC.invoke.remoteHostRemove, { hostKey }),diff --git a/apps/desktop/test/pairing-boot-add-remove.test.mjs b/apps/desktop/test/pairing-boot-add-remove.test.mjsindex edd7cad2d..8a30a5d6d 100644--- a/apps/desktop/test/pairing-boot-add-remove.test.mjs+++ b/apps/desktop/test/pairing-boot-add-remove.test.mjs@@ -219,13 +219,17 @@ test("list surface strips device tokens even when the record is on disk", asyncdeviceToken: "device-secret",});const listed = await boot.list();- // The summary shape has these four fields and nothing else.+ // The summary shape has exactly these five fields: the four the pairing UX+ // has always shown, plus the transport marker the SSH bootstrap added. A+ // record with no metadata is a direct host, so the marker defaults there.assert.deepEqual(Object.keys(listed[0]).sort(), ["connected","hostKey","label",+ "transport","url",]);+ assert.equal(listed[0].transport, "direct");await boot.closeAll();await cleanup();});diff --git a/apps/desktop/test/remote-host-bootstrap-script.test.mjs b/apps/desktop/test/remote-host-bootstrap-script.test.mjsnew file mode 100644index 000000000..bea2acefb--- /dev/null+++ b/apps/desktop/test/remote-host-bootstrap-script.test.mjs@@ -0,0 +1,357 @@+import assert from "node:assert/strict";+import test from "node:test";+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { existsSync } from "node:fs";+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { buildBootstrapScript, parseBootstrapOutput, shellQuote } = await import(+ "../electron/main/remote/pi-host-bootstrap-script.ts"+);++const VERSION = "0.15.1-beta.5";+const BUNDLE_DIR = `pi-host-${VERSION}-linux-x64`;+const ARTIFACT_NAME = `${BUNDLE_DIR}.tar.gz`;+const ARTIFACT_URL = `https://github.com/vastsa/PI-Desktop/releases/download/v${VERSION}/${ARTIFACT_NAME}`;+const DIGEST = "0123456789abcdef".repeat(4);+/** The sandbox the script's `HOME`/`PATH` point at, outside the real user's. */+const WORK_SUBDIR = ".pi-desktop/pi-host/.bootstrap";++/** Inputs every scenario starts from; callers override the digest or version. */+function scriptInput(overrides = {}) {+ return {+ version: VERSION,+ artifactUrl: ARTIFACT_URL,+ artifactName: ARTIFACT_NAME,+ bundleDir: BUNDLE_DIR,+ expectedSha256: DIGEST,+ port: 0,+ pairingLifetimeMs: 600_000,+ readyTimeoutSec: 30,+ ...overrides,+ };+}++async function tempDir(prefix) {+ const dir = await mkdtemp(join(tmpdir(), prefix));+ return { dir, cleanup: () => rm(dir, { recursive: true, force: true }) };+}++/**+ * Everything the generated script touches, faked on `PATH`: a `curl` that+ * copies a prepared tarball, a `node` that plays the host's ready/pairing+ * output, and a `sha256sum` that hashes with the real Node. The tarball is a+ * real `tar.gz` because the script unpacks and installs it.+ *+ * Returns the env for the run plus the digest the script will compute, which+ * is what `expectedSha256` has to be for a run that is meant to succeed.+ */+async function prepareSandbox(root, { readyVersion = VERSION } = {}) {+ const stage = join(root, "stage");+ const bin = join(root, "bin");+ const home = join(root, "home");+ await mkdir(join(stage, BUNDLE_DIR), { recursive: true });+ await mkdir(bin, { recursive: true });+ await mkdir(home, { recursive: true });+ await writeFile(join(stage, BUNDLE_DIR, "install.sh"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });++ const tarball = join(root, "artifact.tar.gz");+ execFileSync("tar", ["-czf", tarball, "-C", stage, BUNDLE_DIR]);+ const digest = createHash("sha256").update(await readFile(tarball)).digest("hex");++ // `sha256_of` prefers `sha256sum`; the stand-in delegates to the real Node so+ // the digest is computed the same way the release publishes it.+ const sha256Helper = join(root, "sha256.mjs");+ await writeFile(+ sha256Helper,+ [+ 'import { createHash } from "node:crypto";',+ 'import { readFileSync } from "node:fs";',+ "const file = process.argv[2];",+ 'process.stdout.write(`${createHash("sha256").update(readFileSync(file)).digest("hex")} ${file}\\n`);',+ "",+ ].join("\n"),+ );+ await writeFile(join(bin, "sha256sum"), `#!/bin/sh\nexec "${process.execPath}" "${sha256Helper}" "$1"\n`, {+ mode: 0o755,+ });++ await writeFile(+ join(bin, "curl"),+ [+ "#!/bin/sh",+ "# pretend the artifact URL served the tarball this test prepared",+ 'out=""',+ 'while [ "$#" -gt 0 ]; do',+ ' case "$1" in',+ ' -o) out="$2"; shift 2 ;;',+ " *) shift ;;",+ " esac",+ "done",+ '[ -n "$out" ] || { printf \'fake curl: missing -o\\n\' >&2; exit 2; }',+ 'cp "$PI_HOST_TEST_TARBALL" "$out"',+ "",+ ].join("\n"),+ { mode: 0o755 },+ );++ const readyLine = `PI_HOST_READY ${JSON.stringify({+ hostId: "host_x",+ host: "127.0.0.1",+ port: 41234,+ version: readyVersion,+ })}`;+ const pairingLine = `PI_HOST_PAIRING_TOKEN ${JSON.stringify({+ token: "ppt1.stub",+ expiresAt: 1_893_456_000_000,+ })}`;+ await writeFile(+ join(bin, "node"),+ [+ "#!/bin/sh",+ "# `node -p` is the script's version probe; answer with a modern major.",+ 'case " $* " in',+ " *\" -p \"*) printf '99\\n'; exit 0 ;;",+ "esac",+ `printf '%s\\n' '${readyLine}'`,+ `printf '%s\\n' '${pairingLine}'`,+ "# The script polls `kill -0` on this pid, so the fake host outlives the wait.",+ "sleep 5",+ "",+ ].join("\n"),+ { mode: 0o755 },+ );++ return {+ digest,+ home,+ tarball,+ env: {+ ...process.env,+ HOME: home,+ PATH: `${bin}:${process.env.PATH ?? ""}`,+ PI_HOST_TEST_TARBALL: tarball,+ },+ };+}++function runScript(scriptPath, env) {+ return execFileSync("sh", [scriptPath], {+ encoding: "utf8",+ timeout: 120_000,+ stdio: ["ignore", "pipe", "pipe"],+ env,+ });+}++test("shellQuote produces a single-quoted literal that cannot escape", () => {+ assert.equal(shellQuote("plain"), "'plain'");+ // The one character a single-quoted string cannot contain ends the literal,+ // emits an escaped quote, and reopens it — the POSIX `'\''` dance.+ assert.equal(shellQuote("it's"), "'it'\\''s'");+ // Command substitution and variable expansion are inert inside quotes; a+ // caller-supplied URL must never execute.+ assert.equal(shellQuote("$(touch /tmp/pwned)"), "'$(touch /tmp/pwned)'");+});++test("buildBootstrapScript interpolates every input as a quoted literal", () => {+ const script = buildBootstrapScript(scriptInput());+ assert.ok(script.startsWith("#!/bin/sh\n"), "the script is uploaded and run by `sh`");+ assert.ok(script.includes(`VERSION='${VERSION}'`));+ assert.ok(script.includes(`ARTIFACT_URL='${ARTIFACT_URL}'`));+ assert.ok(script.includes(`ARTIFACT_NAME='${ARTIFACT_NAME}'`));+ assert.ok(script.includes(`BUNDLE_DIR='${BUNDLE_DIR}'`));+ assert.ok(script.includes(`EXPECTED_SHA256='${DIGEST}'`));+ assert.ok(script.includes("PORT='0'"));+ assert.ok(script.includes("PAIRING_LIFETIME_MS='600000'"));+ assert.ok(script.includes("READY_TIMEOUT_SEC='30'"));+ // The Node floor is injected from the module, not left as an empty shell var.+ assert.match(script, /^MIN_NODE_MAJOR='\d+'$/m);+ assert.ok(script.includes('$MIN_NODE_MAJOR'));++ // Every `${…}` that reaches the shell must be deliberate. `${HOME:-}` is a+ // shell expansion; anything else would be a JS placeholder that never+ // interpolated and would run as garbage on the remote machine.+ const interpolations = [...script.matchAll(/\$\{([^}]*)\}/g)].map((match) => match[1]);+ assert.deepEqual(interpolations, ["HOME:-"]);+});++test("the generated script is valid POSIX shell, even with hostile inputs", async () => {+ const { dir, cleanup } = await tempDir("pi-host-script-syntax-");+ try {+ const plain = join(dir, "plain.sh");+ await writeFile(plain, buildBootstrapScript(scriptInput()));+ execFileSync("sh", ["-n", plain]);++ // Quoting is the only thing standing between a caller-supplied host or+ // label and the remote shell, so the syntax check runs on those too.+ const hostile = join(dir, "hostile.sh");+ await writeFile(+ hostile,+ buildBootstrapScript(+ scriptInput({+ version: "1.0.0'; touch \"$HOME/pwned\"; echo '",+ artifactUrl: "https://example.invalid/a'b",+ artifactName: "a b'c.tar.gz",+ bundleDir: "d'est",+ }),+ ),+ );+ execFileSync("sh", ["-n", hostile]);+ } finally {+ await cleanup();+ }+});++test("a hostile version stays one literal value when the assignments run", async () => {+ const { dir, cleanup } = await tempDir("pi-host-script-quote-");+ try {+ const hostileVersion = "1.0.0'; touch \"$HOME/pwned\"; echo '";+ const script = buildBootstrapScript(scriptInput({ version: hostileVersion }));+ const assignments = script.split("\n").filter((line) => /^[A-Z_]+='/.test(line));+ assert.ok(+ assignments.some((line) => line.startsWith("VERSION=")),+ "the assignment block must be visible to this test",+ );++ const echoed = execFileSync("sh", ["-c", `${assignments.join("\n")}\nprintf '%s' "$VERSION"`], {+ encoding: "utf8",+ env: { ...process.env, HOME: dir },+ });+ assert.equal(echoed, hostileVersion);+ assert.equal(existsSync(join(dir, "pwned")), false, "the injected command must not have run");+ } finally {+ await cleanup();+ }+});++test("the generated script installs, starts, and prints the ready/pairing lines", async () => {+ const { dir, cleanup } = await tempDir("pi-host-script-run-");+ try {+ const sandbox = await prepareSandbox(dir);+ const scriptPath = join(dir, "bootstrap.sh");+ await writeFile(scriptPath, buildBootstrapScript(scriptInput({ expectedSha256: sandbox.digest })));++ const stdout = runScript(scriptPath, sandbox.env);+ const parsed = parseBootstrapOutput(stdout);+ assert.equal(parsed.failure, null);+ assert.deepEqual(parsed.ready, {+ hostId: "host_x",+ host: "127.0.0.1",+ port: 41234,+ version: VERSION,+ });+ assert.deepEqual(parsed.pairing, { token: "ppt1.stub", expiresAt: 1_893_456_000_000 });+ assert.deepEqual(parsed.steps, ["download", "verify", "install", "start", "await-ready", "ok"]);++ // The host was started under the sandbox HOME and left running there.+ const pid = (await readFile(join(sandbox.home, WORK_SUBDIR, "pi-host.pid"), "utf8")).trim();+ assert.match(pid, /^\d+$/);+ } finally {+ await cleanup();+ }+});++test("a checksum mismatch fails the script before anything is installed", async () => {+ const { dir, cleanup } = await tempDir("pi-host-script-digest-");+ try {+ const sandbox = await prepareSandbox(dir);+ const scriptPath = join(dir, "bootstrap.sh");+ // A tampered download is the case the trust anchor exists for: the digest+ // travels over the same SSH channel as the script that checks it.+ await writeFile(scriptPath, buildBootstrapScript(scriptInput({ expectedSha256: "0".repeat(64) })));++ let failure;+ try {+ runScript(scriptPath, sandbox.env);+ } catch (error) {+ failure = error;+ }+ assert.ok(failure, "the script must exit non-zero");+ assert.notEqual(failure.status, 0);+ assert.match(String(failure.stderr), /PI_HOST_BOOTSTRAP_FAILED checksum-mismatch/);+ // The typed line is on stdout too, which is how the desktop reports the step.+ assert.match(String(failure.stdout), /PI_HOST_FAILED \{.*"step":"checksum-mismatch"/);+ assert.ok(!String(failure.stdout).includes("PI_HOST_READY"), "the host must not have been started");+ } finally {+ await cleanup();+ }+});++test("parseBootstrapOutput reads the ready and pairing lines", () => {+ const output = parseBootstrapOutput(+ [+ "PI_HOST_BOOTSTRAP download",+ 'PI_HOST_READY {"hostId":"host_x","host":"127.0.0.1","port":41234,"version":"0.15.1-beta.5"}',+ 'PI_HOST_PAIRING_TOKEN {"token":"ppt1.abc","expiresAt":123}',+ "PI_HOST_BOOTSTRAP ok",+ ].join("\n"),+ );+ assert.deepEqual(output.ready, {+ hostId: "host_x",+ host: "127.0.0.1",+ port: 41234,+ version: "0.15.1-beta.5",+ });+ assert.deepEqual(output.pairing, { token: "ppt1.abc", expiresAt: 123 });+ assert.deepEqual(output.steps, ["download", "ok"]);+ assert.equal(output.failure, null);+});++test("parseBootstrapOutput collects step lines and ignores interleaved noise", () => {+ const output = parseBootstrapOutput(+ [+ "Warning: Permanently added 'host' (ED25519) to the list of known hosts.",+ "PI_HOST_BOOTSTRAP download",+ "",+ "PI_HOST_BOOTSTRAP verify ",+ "some other chatter",+ "PI_HOST_BOOTSTRAP install",+ ].join("\n"),+ );+ assert.deepEqual(output.steps, ["download", "verify", "install"]);+ assert.equal(output.ready, null);+ assert.equal(output.pairing, null);+});++test("parseBootstrapOutput reports the failing step and ignores unrelated failures", () => {+ const timedOut = parseBootstrapOutput(+ ['PI_HOST_BOOTSTRAP await-ready', 'PI_HOST_FAILED {"code":"HOST_BOOTSTRAP_FAILED","step":"ready-timeout"}'].join(+ "\n",+ ),+ );+ assert.equal(timedOut.failure, "ready-timeout");++ // The script also writes its own bare failed-line; the first one wins.+ const mismatch = parseBootstrapOutput(+ ["PI_HOST_BOOTSTRAP_FAILED checksum-mismatch", "PI_HOST_BOOTSTRAP_FAILED download-failed"].join("\n"),+ );+ assert.equal(mismatch.failure, "checksum-mismatch");++ // A failure line for a different code, or malformed JSON, must not be read as+ // a bootstrap failure for this host.+ assert.equal(parseBootstrapOutput('PI_HOST_FAILED {"code":"OTHER","step":"x"}').failure, null);+ assert.equal(parseBootstrapOutput("PI_HOST_FAILED {not json").failure, null);+});++test("parseBootstrapOutput refuses a ready line with an unusable port", () => {+ const ready = (payload) => parseBootstrapOutput(`PI_HOST_READY ${JSON.stringify(payload)}`);+ const valid = { hostId: "host_x", host: "127.0.0.1", port: 41234, version: "0.15.1" };+ assert.equal(ready({ ...valid, port: 0 }).ready, null, "port 0 means the host never bound");+ assert.equal(ready({ ...valid, port: 41234.5 }).ready, null, "a fractional port is not a port");+ assert.equal(ready({ ...valid, port: "41234" }).ready, null, "a string port is not a port");+ assert.equal(ready({ ...valid, hostId: "" }).ready, null);+ assert.equal(parseBootstrapOutput("PI_HOST_READY {not json").ready, null);++ // The pairing line tolerates a missing expiry rather than dropping the token.+ const pairing = parseBootstrapOutput('PI_HOST_PAIRING_TOKEN {"token":"ppt1.abc"}');+ assert.deepEqual(pairing.pairing, { token: "ppt1.abc", expiresAt: 0 });+ assert.equal(parseBootstrapOutput('PI_HOST_PAIRING_TOKEN {"expiresAt":1}').pairing, null);+});diff --git a/apps/desktop/test/remote-host-pi-host-release.test.mjs b/apps/desktop/test/remote-host-pi-host-release.test.mjsnew file mode 100644index 000000000..4d98c408b--- /dev/null+++ b/apps/desktop/test/remote-host-pi-host-release.test.mjs@@ -0,0 +1,134 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const {+ archFromUname,+ checksumMatches,+ isPublishedTarget,+ normalizeChecksum,+ parseChecksumFile,+ parseUnameOutput,+ piHostArtifactName,+ piHostArtifactUrls,+ piHostBundleDir,+ platformFromUname,+ resolveTarget,+ targetKey,+ versionsMatch,+} = await import("../electron/main/remote/pi-host-release.ts");++const VERSION = "0.15.1-beta.5";+const LINUX_X64 = { platform: "linux", arch: "x64" };+const ARTIFACT_NAME = "pi-host-0.15.1-beta.5-linux-x64.tar.gz";+const RELEASE_BASE = "https://github.com/vastsa/PI-Desktop/releases/download/v0.15.1-beta.5";+/** 64 hex characters, so it passes `normalizeChecksum`. */+const DIGEST = "0123456789abcdef".repeat(4);+/** Same length as {@link DIGEST}, one nibble different: a tampered download. */+const TAMPERED = `${DIGEST.slice(0, -1)}${DIGEST.endsWith("f") ? "e" : "f"}`;++test("artifact name and URLs follow the release tag layout the desktop pins", () => {+ assert.equal(piHostBundleDir(VERSION, LINUX_X64), "pi-host-0.15.1-beta.5-linux-x64");+ assert.equal(piHostArtifactName(VERSION, LINUX_X64), ARTIFACT_NAME);+ const urls = piHostArtifactUrls(VERSION, LINUX_X64);+ // Both files are uploaded to the same v-tagged release by `release.yml`, so+ // the desktop can derive them without an API call.+ assert.equal(urls.tarball, `${RELEASE_BASE}/${ARTIFACT_NAME}`);+ assert.equal(urls.checksum, `${RELEASE_BASE}/${ARTIFACT_NAME}.sha256`);+});++test("resolveTarget maps uname output to a release target", () => {+ assert.deepEqual(parseUnameOutput("Linux\nx86_64\n"), { systemName: "Linux", machine: "x86_64" });+ // The remote probe answers `uname -s && uname -m`; anything past the second+ // line (a login banner, a stray echo) must not change the target.+ assert.deepEqual(resolveTarget("Linux\nx86_64\nextra noise"), { platform: "linux", arch: "x64" });+ assert.deepEqual(resolveTarget(" Darwin \n aarch64 \n"), { platform: "darwin", arch: "arm64" });+ assert.deepEqual(resolveTarget("darwin\narm64"), { platform: "darwin", arch: "arm64" });+ // `amd64` is what Linux uname reports for the same architecture as x86_64.+ assert.deepEqual(resolveTarget("linux\namd64"), { platform: "linux", arch: "x64" });+});++test("resolveTarget refuses a platform or architecture the release cannot serve", () => {+ assert.equal(platformFromUname("FreeBSD"), null);+ assert.equal(archFromUname("riscv64"), null);+ // A host that answered only half the probe must fail closed rather than+ // falling back to the desktop's own target.+ assert.equal(resolveTarget("Linux\nriscv64\n"), null);+ assert.equal(resolveTarget("FreeBSD\nx86_64\n"), null);+ assert.equal(resolveTarget("Linux"), null);+ assert.equal(resolveTarget(""), null);+});++test("isPublishedTarget matches the release matrix, which ships linux-x64 only", () => {+ assert.equal(targetKey(LINUX_X64), "linux-x64");+ assert.equal(isPublishedTarget(LINUX_X64), true);+ // Publishing parity: a 404 halfway through a download is what this guard+ // exists to prevent, so every unpublished cell must be refused here.+ assert.equal(isPublishedTarget({ platform: "linux", arch: "arm64" }), false);+ assert.equal(isPublishedTarget({ platform: "darwin", arch: "x64" }), false);+ assert.equal(isPublishedTarget({ platform: "darwin", arch: "arm64" }), false);+});++test("parseChecksumFile reads the digest of its own artifact from a sha256sum file", () => {+ assert.equal(parseChecksumFile(`${DIGEST} ${ARTIFACT_NAME}\n`, ARTIFACT_NAME), DIGEST);+ // Upper-case digests appear in hand-pasted files; they are the same digest.+ assert.equal(parseChecksumFile(`${DIGEST.toUpperCase()} ${ARTIFACT_NAME}\n`, ARTIFACT_NAME), DIGEST);+ // Binary mode marks the name with `*`, and some tools write a path.+ assert.equal(parseChecksumFile(`${DIGEST} *${ARTIFACT_NAME}\n`, ARTIFACT_NAME), DIGEST);+ assert.equal(parseChecksumFile(`${DIGEST} /tmp/build/${ARTIFACT_NAME}\n`, ARTIFACT_NAME), DIGEST);+ // A digest published for a different artifact (or a different version) must+ // never be trusted for this download.+ assert.equal(parseChecksumFile(`${DIGEST} pi-host-0.15.0-linux-x64.tar.gz\n`, ARTIFACT_NAME), null);+ // Garbage before the real line is tolerated; the digest is still found.+ assert.equal(parseChecksumFile(`# generated by release.sh\n\n${DIGEST} ${ARTIFACT_NAME}\n`, ARTIFACT_NAME), DIGEST);+});++test("parseChecksumFile rejects anything that is not a full sha256 digest", () => {+ assert.equal(parseChecksumFile(`${DIGEST.slice(0, 63)} ${ARTIFACT_NAME}\n`, ARTIFACT_NAME), null, "63 hex chars");+ assert.equal(parseChecksumFile(`${DIGEST}0 ${ARTIFACT_NAME}\n`, ARTIFACT_NAME), null, "65 hex chars");+ assert.equal(+ parseChecksumFile(`${DIGEST.slice(0, 60)}zzzz ${ARTIFACT_NAME}\n`, ARTIFACT_NAME),+ null,+ "non-hex characters",+ );+ assert.equal(parseChecksumFile("", ARTIFACT_NAME), null);+ assert.equal(parseChecksumFile("\n\n", ARTIFACT_NAME), null);+});++test("normalizeChecksum accepts only a trimmed, lower-case 64-hex digest", () => {+ assert.equal(normalizeChecksum(` ${DIGEST.toUpperCase()}\n`), DIGEST);+ assert.equal(normalizeChecksum(DIGEST.slice(0, 63)), null);+ assert.equal(normalizeChecksum(`${DIGEST}0`), null);+ assert.equal(normalizeChecksum(`${DIGEST.slice(0, 63)}g`), null);+ assert.equal(normalizeChecksum(""), null);+});++test("checksumMatches compares digests case-insensitively and refuses junk", () => {+ assert.equal(checksumMatches(DIGEST, DIGEST), true);+ assert.equal(checksumMatches(DIGEST.toUpperCase(), DIGEST), true);+ assert.equal(checksumMatches(DIGEST, DIGEST.toUpperCase()), true);+ // One differing nibble, a length mismatch, and a non-hex value are all false+ // rather than a throw: the caller turns false into a typed bootstrap failure.+ assert.equal(checksumMatches(TAMPERED, DIGEST), false);+ assert.equal(checksumMatches(DIGEST.slice(0, 63), DIGEST), false);+ assert.equal(checksumMatches("not-a-digest", DIGEST), false);+ assert.equal(checksumMatches("", ""), false);+});++test("versionsMatch requires the same release, tolerating a v prefix on either side", () => {+ assert.equal(versionsMatch("0.15.1-beta.5", "0.15.1-beta.5"), true);+ // The tag carries the `v` and `APP_VERSION` does not; either side may have it.+ assert.equal(versionsMatch("v0.15.1-beta.5", "0.15.1-beta.5"), true);+ assert.equal(versionsMatch("0.15.1-beta.5", "v0.15.1-beta.5"), true);+ assert.equal(versionsMatch(" v0.15.1-beta.5 ", "0.15.1-beta.5"), true);+ assert.equal(versionsMatch("0.15.2", "0.15.1"), false);+ assert.equal(versionsMatch("0.15.1-beta.4", "0.15.1-beta.5"), false);+ assert.equal(versionsMatch("", ""), false);+ assert.equal(versionsMatch("", "0.15.1"), false);+ assert.equal(versionsMatch("v", ""), false);+});diff --git a/apps/desktop/test/remote-host-ssh-bootstrap.test.mjs b/apps/desktop/test/remote-host-ssh-bootstrap.test.mjsnew file mode 100644index 000000000..1f1e67e70--- /dev/null+++ b/apps/desktop/test/remote-host-ssh-bootstrap.test.mjs@@ -0,0 +1,305 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { createSshBootstrap, synthesizeSshHostKey } = await import(+ "../electron/main/remote/ssh-bootstrap.ts"+);+const { sshHostRecord, sshMetadataOf, transportOf } = await import(+ "../electron/main/bootstrap/remote-hosts.ts"+);++const VERSION = "0.15.1-beta.5";+const ARTIFACT_NAME = `pi-host-${VERSION}-linux-x64.tar.gz`;+const ARTIFACT_URL = `https://github.com/vastsa/PI-Desktop/releases/download/v${VERSION}/${ARTIFACT_NAME}`;+const DIGEST = "0123456789abcdef".repeat(4);+const RESERVED_PORT = 49_152;++/** The two lines the remote script prints on success, with `41234` as the+ * loopback port the host bound on the remote machine. */+function scriptStdout({ version = VERSION, token = "ppt1.abc" } = {}) {+ return [+ "PI_HOST_BOOTSTRAP download",+ "PI_HOST_BOOTSTRAP ok",+ `PI_HOST_READY ${JSON.stringify({ hostId: "host_x", host: "127.0.0.1", port: 41_234, version })}`,+ `PI_HOST_PAIRING_TOKEN ${JSON.stringify({ token, expiresAt: 1_893_456_000_000 })}`,+ ].join("\n");+}++/** Stands in for the system `ssh` transport. Records every call so the test can+ * assert the orchestrator's ordering without spawning a process. */+function fakeTransport({ uname = "Linux\nx86_64\n", stdout = scriptStdout(), stderr = "" } = {}) {+ const calls = { exec: [], uploads: [], forwards: [], disposeCount: 0 };+ const forward = {+ localPort: 0,+ closed: 0,+ async close() {+ forward.closed += 1;+ },+ };+ return {+ calls,+ openedForward: forward,+ async exec(command) {+ calls.exec.push(command);+ return { stdout: uname, stderr: "", code: 0 };+ },+ async execWithInput(command, input) {+ calls.uploads.push({ command, input });+ return { stdout, stderr, code: 0 };+ },+ async forward(options) {+ calls.forwards.push(options);+ forward.localPort = options.localPort;+ return forward;+ },+ dispose() {+ calls.disposeCount += 1;+ },+ };+}++function harness({ transport = fakeTransport(), checksum, ports = [RESERVED_PORT], exchange } = {}) {+ const built = [];+ const fetched = [];+ const pairings = [];+ const progress = [];+ let portIndex = 0;+ const bootstrap = createSshBootstrap({+ version: VERSION,+ buildTransport: (target) => {+ built.push(target);+ return transport;+ },+ fetchChecksum: async (url) => {+ fetched.push(url);+ return checksum ?? `${DIGEST} ${ARTIFACT_NAME}\n`;+ },+ reservePort: async () => ports[Math.min(portIndex++, ports.length - 1)],+ exchangePairing: async (input) => {+ pairings.push(input);+ return exchange ? await exchange(input) : "dt_secret";+ },+ onProgress: (step) => progress.push(step),+ });+ return { bootstrap, built, fetched, pairings, progress, transport };+}++function request(overrides = {}) {+ return { label: "Prod box", host: "remote.example", port: 2222, user: "deploy", ...overrides };+}++/** Await `run()` and return the error it rejects with; fail when it resolves. */+async function catchError(run) {+ try {+ await run();+ } catch (error) {+ return error;+ }+ throw new Error("expected the call to reject");+}++test("bootstrap probes, installs, forwards, and pairs in order", async () => {+ const { bootstrap, built, fetched, pairings, progress, transport } = harness();+ const outcome = await bootstrap.bootstrap(request());++ // The artifact is chosen for the remote platform, never the desktop's.+ assert.deepEqual(built, [{ host: "remote.example", port: 2222, user: "deploy" }]);+ assert.equal(built.length, 1);+ assert.deepEqual(transport.calls.exec, ["uname -s && uname -m"]);+ // The desktop holds the trust anchor: the digest from the published file.+ assert.equal(fetched[0], `${ARTIFACT_URL}.sha256`);++ assert.deepEqual(outcome.steps, [+ "probe",+ "resolve-release",+ "download-checksum",+ "install",+ "forward",+ "pair",+ ]);+ assert.deepEqual(progress, outcome.steps, "each step is reported once, in order");+ assert.equal(outcome.hostKey, "ssh-remote.example-prod-box");+ assert.equal(outcome.label, "Prod box");+ assert.equal(outcome.deviceToken, "dt_secret");+ assert.deepEqual(outcome.ssh, {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ remotePort: 41_234,+ version: VERSION,+ });++ // One tunnel: reserved here, bound to the port the host reported remotely.+ assert.deepEqual(transport.calls.forwards, [+ { localPort: RESERVED_PORT, remoteHost: "127.0.0.1", remotePort: 41_234 },+ ]);+ assert.equal(outcome.forward, transport.openedForward);+ assert.equal(outcome.url, `ws://127.0.0.1:${RESERVED_PORT}/v1/racp/ws`);+ assert.equal(transport.calls.disposeCount, 0, "the caller adopts the forward, so its transport must stay alive");++ // Pairing spends the single-use token over the forwarded URL only.+ assert.deepEqual(pairings, [+ { url: `ws://127.0.0.1:${RESERVED_PORT}/v1/racp/ws`, pairingToken: "ppt1.abc", label: "Prod box" },+ ]);++ // What travelled over SSH is the script with the pinned digest and URL, not+ // any executable bytes.+ const upload = transport.calls.uploads[0];+ assert.equal(upload.command, "sh -s");+ assert.ok(upload.input.includes(`EXPECTED_SHA256='${DIGEST}'`));+ assert.ok(upload.input.includes(`ARTIFACT_URL='${ARTIFACT_URL}'`));+ // No `remotePort` in the request: the host picks a free port and reports it.+ assert.ok(upload.input.includes("PORT='0'"));+});++test("a remote host running a different release is refused before the forward", async () => {+ const transport = fakeTransport({ stdout: scriptStdout({ version: "0.14.9" }) });+ const { bootstrap, pairings } = harness({ transport });+ const error = await catchError(() => bootstrap.bootstrap(request()));+ assert.equal(error.errorCode, "HOST_VERSION_MISMATCH");+ assert.equal(error.remote, "0.14.9");+ assert.equal(error.local, VERSION);+ assert.deepEqual(transport.calls.forwards, [], "a mismatched host must not get a tunnel");+ assert.deepEqual(pairings, []);+ assert.equal(transport.calls.disposeCount, 1, "the failed attempt must shut its own transport down");+});++test("an unpublished target fails without downloading anything", async () => {+ // arm64 Linux is in the release matrix's shape but not in its published set.+ const transport = fakeTransport({ uname: "Linux\naarch64\n" });+ const { bootstrap, fetched } = harness({ transport });+ const error = await catchError(() => bootstrap.bootstrap(request()));+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.equal(error.target, "linux-arm64");+ assert.deepEqual(fetched, [], "no checksum request for a bundle that does not exist");+ assert.deepEqual(transport.calls.uploads, []);+});++test("a checksum file with no digest for this artifact fails the bootstrap", async () => {+ const transport = fakeTransport();+ const { bootstrap } = harness({ transport, checksum: `${DIGEST} pi-host-0.15.0-linux-x64.tar.gz\n` });+ const error = await catchError(() => bootstrap.bootstrap(request()));+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.deepEqual(transport.calls.uploads, [], "the script must not run without a digest to verify");+});++test("a failed remote script reports the step it failed at", async () => {+ const transport = fakeTransport({+ stdout: "PI_HOST_BOOTSTRAP download\nPI_HOST_BOOTSTRAP_FAILED checksum-mismatch\n",+ stderr: "PI_HOST_BOOTSTRAP_FAILED checksum-mismatch\n",+ });+ const { bootstrap } = harness({ transport });+ const error = await catchError(() => bootstrap.bootstrap(request()));+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.equal(error.step, "checksum-mismatch");+ assert.deepEqual(transport.calls.forwards, []);+ assert.equal(transport.calls.disposeCount, 1);+});++test("a failed pairing exchange closes the forward it can no longer use", async () => {+ const transport = fakeTransport();+ const { bootstrap } = harness({+ transport,+ exchange: async () => {+ throw Object.assign(new Error("pairing token already spent"), { errorCode: "REMOTE_CONNECTION_FAILED" });+ },+ });+ const error = await catchError(() => bootstrap.bootstrap(request()));+ assert.equal(error.errorCode, "REMOTE_CONNECTION_FAILED");+ assert.equal(transport.openedForward.closed, 1, "a forward with no paired token is dead weight");+});++test("arguments that would reach the ssh argv are refused before any transport exists", async () => {+ const cases = [+ { name: "empty host", patch: { host: "" }, field: "host" },+ { name: "host that reads as an ssh option", patch: { host: "-oProxyCommand=evil" }, field: "host" },+ { name: "user that reads as an ssh option", patch: { user: "-x" }, field: "user" },+ { name: "port outside the tcp range", patch: { port: 70_000 }, field: "port" },+ { name: "hostKey containing ':'", patch: { hostKey: "remote:host" }, field: "hostKey" },+ ];+ for (const { name, patch, field } of cases) {+ const { bootstrap, built } = harness();+ const error = await catchError(() => bootstrap.bootstrap(request(patch)));+ assert.equal(error.errorCode, "INVALID_ARGUMENT", name);+ assert.equal(error.field, field, name);+ assert.deepEqual(built, [], `${name}: no ssh process may be spawned`);+ }+});++test("synthesizeSshHostKey folds an IPv6 literal and is stable", () => {+ const ipv6 = synthesizeSshHostKey({ host: "2001:db8::1", user: "deploy" }, "Prod Box");+ // The key lands inside `remote:<hostKey>:<sessionId>`, where a colon would+ // split the routing id, so the address is folded to dashes instead.+ assert.ok(!ipv6.includes(":"), "hostKey must never contain ':'");+ assert.equal(ipv6, "ssh-2001-db8-1-prod-box");+ assert.equal(synthesizeSshHostKey({ host: "2001:db8::1", user: "deploy" }, "Prod Box"), ipv6);+ // The user is not part of the key: the same machine reached as two users+ // stays one host, and the label keeps the two rows apart.+ assert.equal(+ synthesizeSshHostKey({ host: "2001:db8::1", user: "other" }, "Prod Box"),+ ipv6,+ );+});++test("sshMetadataOf parses the descriptor a bootstrapped host is stored with", () => {+ const descriptor = {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ identityFile: "/home/deploy/.ssh/id_ed25519",+ remotePort: 41_234,+ version: VERSION,+ };+ const metadata = { transport: "ssh", ssh: descriptor };+ assert.deepEqual(sshMetadataOf({ hostKey: "h", label: "H", url: "u", deviceToken: "t", metadata }), descriptor);+ assert.equal(transportOf({ hostKey: "h", label: "H", url: "u", deviceToken: "t", metadata }), "ssh");+ // Absent metadata is a record written before the SSH bootstrap existed.+ assert.equal(transportOf({ hostKey: "h", label: "H", url: "u", deviceToken: "t" }), "direct");++ // Round trip through the writer the boot layer persists with.+ const written = sshHostRecord({+ hostKey: "k",+ label: "L",+ url: "u",+ deviceToken: "t",+ ssh: descriptor,+ });+ assert.equal(written.metadata.transport, "ssh");+ assert.deepEqual(sshMetadataOf(written), descriptor);+});++test("sshMetadataOf refuses direct, missing, and malformed descriptors", () => {+ const descriptor = {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ identityFile: "/home/deploy/.ssh/id_ed25519",+ remotePort: 41_234,+ version: VERSION,+ };+ const record = (metadata) => ({ hostKey: "h", label: "H", url: "u", deviceToken: "t", metadata });++ assert.equal(sshMetadataOf(record({ transport: "direct", ssh: descriptor })), null);+ assert.equal(sshMetadataOf(record({ transport: "direct" })), null);+ assert.equal(sshMetadataOf(record(undefined)), null);+ assert.equal(sshMetadataOf(record({ ssh: descriptor })), null, "metadata without a transport is not ssh");+ assert.equal(sshMetadataOf(record({ transport: "ssh" })), null);+ assert.equal(sshMetadataOf(record({ transport: "ssh", ssh: "not-an-object" })), null);+ assert.equal(sshMetadataOf(record({ transport: "ssh", ssh: { ...descriptor, host: " " } })), null);++ // `remote-hosts.json` is user-editable, so a bad port must degrade to "not an+ // SSH host" rather than reaching an `ssh -L` argument.+ for (const remotePort of [undefined, 0, -1, 65_536, 41_234.5, "41234"]) {+ assert.equal(+ sshMetadataOf(record({ transport: "ssh", ssh: { ...descriptor, remotePort } })),+ null,+ `remotePort ${String(remotePort)}`,+ );+ }+});diff --git a/apps/desktop/test/remote-host-ssh-transport.test.mjs b/apps/desktop/test/remote-host-ssh-transport.test.mjsnew file mode 100644index 000000000..9efa300d0--- /dev/null+++ b/apps/desktop/test/remote-host-ssh-transport.test.mjs@@ -0,0 +1,458 @@+/**+ * Direct tests for the SSH transport itself.+ *+ * `ssh-transport.ts` spawns processes, races a socket probe against a dead+ * `ssh`, and owns forward lifetimes, so it is driven here with fixture+ * executables instead of the real client: nothing in this file depends on a+ * network, a host key, or an ssh binary being installed. Each fixture is+ * written into `os.tmpdir()`, made executable, and removed afterwards; every+ * test is bounded so a regression cannot hang the suite.+ */+import assert from "node:assert/strict";+import test from "node:test";+import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { register } from "node:module";+import { connect, createServer } from "node:net";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { assertSshArgument, createSystemSshTransport, reserveLocalPort } = await import(+ "../electron/main/remote/ssh-transport.ts"+);++/** Every test is bounded well below the module's own 30 s / 120 s defaults. */+const TEST_TIMEOUT_MS = 20_000;++const FIXTURES = {+ /** Prints the argv it was handed, one entry per line. */+ argvEcho: `#!/bin/sh+for arg in "$@"; do+ printf '%s\\n' "$arg"+done+`,+ /** Prints its argv between markers, then echoes its stdin. */+ argvAndStdin: `#!/bin/sh+echo "ARGV-BEGIN"+for arg in "$@"; do+ printf '%s\\n' "$arg"+done+echo "ARGV-END"+cat+`,+ /** Writes to both streams and fails, like a remote bootstrap step. */+ failing: `#!/bin/sh+echo "STDOUT-MARKER-the remote step failed"+echo "STDERR-MARKER-connection reset by peer" >&2+exit 3+`,+ /** Leaks a pairing token on stdout, then fails. */+ tokenLeak: `#!/bin/sh+echo 'PI_HOST_PAIRING_TOKEN {"token":"ppt1.secret","expiresAt":1}'+echo "bootstrap step 3 failed on the remote host"+exit 7+`,+ /** Outlives any sane timeout; `exec` makes the kill land on the sleeper. */+ sleeper: `#!/bin/sh+exec sleep 30+`,+ /** The shape of a refused connection: a diagnostic and a dead client. */+ deadSsh: `#!/bin/sh+echo "Permission denied (publickey)." >&2+exit 255+`,+};++/**+ * Stands in for `ssh` in both roles: without `-N -L` it records its pid, prints+ * its argv and exits (an exec); with them it listens on the `-L` port like a+ * real forward, recording the pid its test can poll to prove it was reaped.+ */+const NODE_FIXTURE = `#!/usr/bin/env node+const fs = require("node:fs");+const net = require("node:net");++const args = process.argv.slice(2);+const forwardAt = args.indexOf("-L");+const pidFile = process.argv[1] + (forwardAt === -1 ? ".exec.pid" : ".forward.pid");++if (forwardAt === -1) {+ fs.writeFileSync(pidFile, String(process.pid));+ fs.writeSync(1, args.join("\\n") + "\\n");+ process.exit(0);+}++const port = Number(String(args[forwardAt + 1]).split(":")[1]);+if (!Number.isInteger(port) || port <= 0) {+ fs.writeSync(2, "fixture received no usable -L argument\\n");+ process.exit(2);+}+const server = net.createServer((socket) => socket.end());+server.listen(port, "127.0.0.1", () => {+ fs.writeFileSync(pidFile, String(process.pid));+});+`;++/** Write an executable fixture; its directory goes away when the test ends. */+async function writeFixture(t, body, name) {+ const dir = await mkdtemp(join(tmpdir(), "pi-desktop-ssh-fixture-"));+ t.after(() => rm(dir, { recursive: true, force: true }));+ const file = join(dir, name);+ await writeFile(file, body, "utf8");+ await chmod(file, 0o755);+ return file;+}++function delay(ms) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++function pairIndex(argv, name, value) {+ return argv.findIndex((arg, index) => arg === name && argv[index + 1] === value);+}++function hasPair(argv, name, value) {+ return pairIndex(argv, name, value) !== -1;+}++function processAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++/** Resolve `true` if something accepts a TCP connection on the loopback port. */+function portAccepts(port) {+ return new Promise((resolveAccepts) => {+ const socket = connect({ host: "127.0.0.1", port });+ socket.once("connect", () => {+ socket.destroy();+ resolveAccepts(true);+ });+ socket.once("error", () => {+ socket.destroy();+ resolveAccepts(false);+ });+ });+}++async function readPid(file) {+ try {+ const pid = Number.parseInt((await readFile(file, "utf8")).trim(), 10);+ return Number.isInteger(pid) && pid > 0 ? pid : null;+ } catch {+ return null;+ }+}++/** Poll until `condition` holds, so no test depends on a fixed sleep. */+async function waitFor(condition, label, timeoutMs = 5_000) {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ if (await condition()) return;+ if (Date.now() >= deadline) {+ throw new Error(`timed out after ${timeoutMs} ms waiting for ${label}`);+ }+ await delay(25);+ }+}++async function waitForPid(file) {+ let pid = null;+ await waitFor(async () => {+ pid = await readPid(file);+ return pid !== null;+ }, `the fixture to record its pid in ${file}`);+ return pid;+}++test("exec passes the command as one argv entry behind the common options", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.argvEcho, "ssh-argv-echo");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });++ const plain = await transport.exec("uname -s");+ assert.equal(plain.code, 0);+ const argv = plain.stdout.split("\n").filter(Boolean);++ // A single argv entry: `uname -s` must never split into two arguments.+ assert.equal(argv.at(-1), "uname -s");+ assert.equal(argv.at(-2), "remote.example", "the command follows the destination");+ const command = argv.length - 1;+ for (const [name, value] of [+ ["-o", "BatchMode=yes"],+ ["-o", "StrictHostKeyChecking=accept-new"],+ ["-o", "ExitOnForwardFailure=yes"],+ ]) {+ const index = pairIndex(argv, name, value);+ assert.notEqual(index, -1, `${name} ${value} is missing`);+ assert.ok(index < command, `${name} ${value} must precede the command`);+ }++ const targeted = createSystemSshTransport(+ {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ identityFile: "/home/deploy/.ssh/id_ed25519",+ },+ { binary, extraOptions: ["-o", "ServerAliveInterval=15"] },+ );+ const withTarget = await targeted.exec("id -u");+ const argv2 = withTarget.stdout.split("\n").filter(Boolean);+ const destination = argv2.indexOf("[email protected]");++ assert.ok(hasPair(argv2, "-p", "2222"));+ assert.ok(hasPair(argv2, "-i", "/home/deploy/.ssh/id_ed25519"));+ assert.ok(hasPair(argv2, "-o", "ServerAliveInterval=15"), "extraOptions reach ssh");+ assert.ok(destination > pairIndex(argv2, "-p", "2222"));+ assert.ok(destination > pairIndex(argv2, "-i", "/home/deploy/.ssh/id_ed25519"));+ assert.ok(pairIndex(argv2, "-o", "ServerAliveInterval=15") < argv2.length - 1);+ assert.equal(argv2.at(-1), "id -u");++ transport.dispose();+ targeted.dispose();+});++test("execWithInput runs the script through `sh -s` with the body on stdin", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.argvAndStdin, "ssh-argv-and-stdin");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });+ const script = [+ "#!/bin/sh",+ "set -eu",+ "# SCRIPT-BODY-MARKER must never travel as an ssh argument",+ 'echo "$PI_HOST_PAIRING_TOKEN"',+ ].join("\n");++ const result = await transport.execWithInput("sh -s", script);+ assert.equal(result.code, 0);++ const argvSection = result.stdout.slice(+ result.stdout.indexOf("ARGV-BEGIN"),+ result.stdout.indexOf("ARGV-END"),+ );+ assert.equal(argvSection.split("\n").filter(Boolean).at(-1), "sh -s");+ // The script is delivered on stdin, so it cannot land in argv (where it would+ // be visible in `ps` and could be re-split by the remote shell).+ assert.ok(!argvSection.includes("SCRIPT-BODY-MARKER"), "the script must not reach argv");+ assert.ok(!argvSection.includes("set -eu"));++ const stdinSection = result.stdout.slice(result.stdout.indexOf("ARGV-END"));+ assert.ok(+ stdinSection.includes("SCRIPT-BODY-MARKER"),+ `the script must reach stdin: ${result.stdout}`,+ );+ assert.ok(stdinSection.includes('echo "$PI_HOST_PAIRING_TOKEN"'));++ transport.dispose();+});++test("a non-zero exit becomes a typed error carrying both streams", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.failing, "ssh-failing");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });++ await assert.rejects(+ () => transport.exec("bootstrap"),+ (error) => {+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.equal(error.code, 3);+ assert.equal(error.command, "bootstrap");+ assert.match(error.stderr, /STDERR-MARKER-connection reset by peer/);+ assert.match(error.stdout, /STDOUT-MARKER-the remote step failed/);+ return true;+ },+ );++ transport.dispose();+});++test("the stdout of that error is redacted of a live pairing token", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.tokenLeak, "ssh-token-leak");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });++ await assert.rejects(+ () => transport.exec("bootstrap"),+ (error) => {+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.equal(error.code, 7);+ assert.ok(+ error.stdout.includes("PI_HOST_PAIRING_TOKEN <redacted>"),+ `the token line must be redacted: ${error.stdout}`,+ );+ assert.ok(!error.stdout.includes("ppt1.secret"), "the token itself must be gone");+ // Redaction is targeted: the surrounding diagnostics survive.+ assert.ok(error.stdout.includes("bootstrap step 3 failed on the remote host"));+ return true;+ },+ );++ transport.dispose();+});++test("a command outliving timeoutMs is killed, not awaited", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.sleeper, "ssh-sleeper");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });++ const started = Date.now();+ await assert.rejects(+ () => transport.exec("sleep 30", { timeoutMs: 400 }),+ (error) => {+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.match(error.message, /timed out after 400 ms/);+ return true;+ },+ );+ const elapsed = Date.now() - started;+ assert.ok(elapsed < 5_000, `the timeout must cut the command short, took ${elapsed} ms`);++ transport.dispose();+});++test("a binary that does not exist rejects instead of crashing", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.argvEcho, "ssh-argv-echo");+ const missing = join(dirname(binary), "ssh-that-is-not-installed");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary: missing });++ await assert.rejects(+ () => transport.exec("uname -s", { timeoutMs: 5_000 }),+ (error) => {+ assert.equal(error.errorCode, "HOST_BOOTSTRAP_FAILED");+ assert.match(error.message, /could not be started/);+ return true;+ },+ );++ transport.dispose();+});++test("forward rejects fast, with the ssh diagnostic, when ssh exits instead", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, FIXTURES.deadSsh, "ssh-dead");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });+ const localPort = await reserveLocalPort();++ const started = Date.now();+ await assert.rejects(+ () => transport.forward({ localPort, remoteHost: "127.0.0.1", remotePort: 1, timeoutMs: 30_000 }),+ (error) => {+ assert.equal(error.errorCode, "REMOTE_FORWARD_FAILED");+ // The half the dead-code path lost: ssh's own reason for giving up.+ assert.match(error.message, /Permission denied \(publickey\)/, error.message);+ assert.match(error.message, /code 255/);+ return true;+ },+ );+ const elapsed = Date.now() - started;+ assert.ok(+ elapsed < 5_000,+ `a dead ssh must reject immediately, but the forward took ${elapsed} ms (probe timeout is 30 s)`,+ );++ transport.dispose();+});++test("forward resolves once the port answers and close() is idempotent", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, NODE_FIXTURE, "ssh-forward");+ const transport = createSystemSshTransport({ host: "remote.example" }, { binary });+ const localPort = await reserveLocalPort();++ const forward = await transport.forward({+ localPort,+ remoteHost: "127.0.0.1",+ remotePort: 41_234,+ timeoutMs: 10_000,+ });+ try {+ assert.equal(forward.localPort, localPort, "the forward reports the port that was claimed");+ const pid = await waitForPid(`${binary}.forward.pid`);+ assert.equal(await portAccepts(localPort), true);++ await forward.close();+ await forward.close();+ await waitFor(() => !processAlive(pid), "the forward's ssh process to be reaped");+ await waitFor(+ async () => !(await portAccepts(localPort)),+ "the forwarded port to stop accepting connections",+ );+ } finally {+ // dispose() reaps the child whatever path the assertions took.+ transport.dispose();+ }+});++test("dispose reaps a live forward and leaves a finished exec alone", { timeout: TEST_TIMEOUT_MS }, async (t) => {+ const binary = await writeFixture(t, NODE_FIXTURE, "ssh-dispose");+ const logged = [];+ const transport = createSystemSshTransport(+ { host: "remote.example" },+ { binary, log: (level, message, data) => logged.push({ level, message, data }) },+ );++ try {+ const exec = await transport.exec("uname -s");+ assert.equal(exec.code, 0, exec.stderr);+ const execPid = await waitForPid(`${binary}.exec.pid`);+ assert.equal(processAlive(execPid), false, "a completed exec has already exited");++ const localPort = await reserveLocalPort();+ await transport.forward({+ localPort,+ remoteHost: "127.0.0.1",+ remotePort: 41_234,+ timeoutMs: 10_000,+ });+ const forwardPid = await waitForPid(`${binary}.forward.pid`);+ assert.equal(processAlive(forwardPid), true);++ transport.dispose();++ // An open forward must not outlive the transport that owns it.+ await waitFor(() => !processAlive(forwardPid), "dispose to reap the forward's ssh process");+ assert.ok(+ logged.some(+ (entry) => entry.message === "ssh transport disposed" && entry.data?.host === "remote.example",+ ),+ `dispose must log through the injected logger: ${JSON.stringify(logged)}`,+ );+ } finally {+ transport.dispose();+ }+});++test("reserveLocalPort hands out a port it has already released", { timeout: TEST_TIMEOUT_MS }, async () => {+ const port = await reserveLocalPort();+ assert.ok(Number.isInteger(port) && port > 0, `expected a usable port, got ${port}`);++ // Binding it here only succeeds if the probe really closed its socket.+ const server = createServer();+ try {+ await new Promise((resolveBound, rejectBound) => {+ server.once("error", rejectBound);+ server.listen(port, "127.0.0.1", resolveBound);+ });+ assert.equal(await portAccepts(port), true);+ } finally {+ await new Promise((resolveClosed) => server.close(resolveClosed));+ }+});++test("assertSshArgument rejects option-shaped values and trims the rest", { timeout: TEST_TIMEOUT_MS }, () => {+ for (const value of ["", " ", "-oProxyCommand=x", "\t-oFoo=bar"]) {+ assert.throws(+ () => assertSshArgument(value, "host"),+ (error) => {+ assert.equal(error.errorCode, "INVALID_ARGUMENT");+ assert.equal(error.field, "host");+ return true;+ },+ `expected ${JSON.stringify(value)} to be rejected`,+ );+ }++ assert.equal(assertSshArgument(" remote.example ", "host"), "remote.example");+ assert.equal(assertSshArgument("deploy", "user"), "deploy");+});diff --git a/apps/desktop/test/remote-host-ssh-tunnel.test.mjs b/apps/desktop/test/remote-host-ssh-tunnel.test.mjsnew file mode 100644index 000000000..bf455fa5c--- /dev/null+++ b/apps/desktop/test/remote-host-ssh-tunnel.test.mjs@@ -0,0 +1,213 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { createSshTunnelManager, racpUrlForLocalPort, sshTargetOf } = await import(+ "../electron/main/remote/ssh-tunnel.ts"+);+const { sshCommonArgs } = await import("../electron/main/remote/ssh-transport.ts");++const VERSION = "0.15.1-beta.5";+const SSH = {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ identityFile: "/home/deploy/.ssh/id_ed25519",+ remotePort: 41_234,+ version: VERSION,+};++function fakeForward(localPort) {+ const forward = {+ localPort,+ closes: 0,+ async close() {+ forward.closes += 1;+ },+ };+ return forward;+}++/**+ * Manager wired to fakes: no `ssh` is spawned and the reserved loopback port+ * comes from a fixed sequence. `armFailure` makes the *next* transport the+ * factory builds fail its forward, which is how a refused connection looks.+ */+function harness({ ports = [41_001, 41_002, 41_003] } = {}) {+ const built = [];+ const transports = [];+ let portIndex = 0;+ let pendingFailure = null;+ const manager = createSshTunnelManager({+ reservePort: async () => ports[Math.min(portIndex++, ports.length - 1)],+ buildTransport: (ssh) => {+ built.push(ssh);+ const entry = { ssh, forwards: [], disposed: 0, lastForward: null, nextFailure: pendingFailure };+ pendingFailure = null;+ transports.push(entry);+ return {+ exec: async () => {+ throw new Error("the tunnel never execs");+ },+ execWithInput: async () => {+ throw new Error("the tunnel never execs");+ },+ async forward(options) {+ entry.forwards.push(options);+ if (entry.nextFailure) {+ const failure = entry.nextFailure;+ entry.nextFailure = null;+ throw failure;+ }+ entry.lastForward = fakeForward(options.localPort);+ return entry.lastForward;+ },+ dispose() {+ entry.disposed += 1;+ },+ };+ },+ });+ return { manager, built, transports, armFailure: (error) => { pendingFailure = error; } };+}++test("racpUrlForLocalPort is the loopback RACP endpoint of a forward", () => {+ assert.equal(racpUrlForLocalPort(1234), "ws://127.0.0.1:1234/v1/racp/ws");+});++test("sshTargetOf keeps only the fields ssh can use", () => {+ const target = sshTargetOf(SSH);+ assert.deepEqual(target, {+ host: "remote.example",+ port: 2222,+ user: "deploy",+ identityFile: "/home/deploy/.ssh/id_ed25519",+ });+ // `remotePort` and `version` are RACP facts, not ssh arguments.+ assert.ok(!("remotePort" in target));+ assert.ok(!("version" in target));+ // Absent optional fields must be absent, not `undefined` entries: an argv+ // containing the string "undefined" would reach ssh.+ assert.deepEqual(sshTargetOf({ host: "h", remotePort: 1, version: VERSION }), { host: "h" });+ assert.deepEqual(+ sshTargetOf({ host: "h", port: undefined, user: "", identityFile: undefined, remotePort: 1, version: VERSION }),+ { host: "h" },+ );+});++test("the descriptor becomes an ssh argv that never prompts", () => {+ const args = sshCommonArgs(sshTargetOf(SSH));+ const hasOption = (name, value) => args.some((arg, index) => arg === name && args[index + 1] === value);+ // There is no terminal behind the spawn, so a password prompt would hang.+ assert.ok(hasOption("-o", "BatchMode=yes"));+ assert.ok(hasOption("-o", "StrictHostKeyChecking=accept-new"));+ // A forward that cannot be set up must fail the connection, not linger.+ assert.ok(hasOption("-o", "ExitOnForwardFailure=yes"));+ assert.ok(hasOption("-p", "2222"));+ assert.ok(hasOption("-i", "/home/deploy/.ssh/id_ed25519"));+ assert.equal(args.at(-1), "[email protected]");++ // Without a user the destination is the bare host, and no port/identity flags+ // are invented for it.+ assert.deepEqual(sshCommonArgs({ host: "h" }).at(-1), "h");+ assert.ok(!sshCommonArgs({ host: "h" }).includes("-p"));+});++test("open reuses the forward for a host key instead of stacking tunnels", async () => {+ const { manager, built, transports } = harness();+ const first = await manager.open("k1", SSH);+ const second = await manager.open("k1", SSH);++ assert.equal(second, first, "the same tunnel object is handed out again");+ assert.equal(first.url, racpUrlForLocalPort(first.localPort));+ assert.equal(built.length, 1);+ assert.equal(built[0], SSH);+ assert.equal(transports.length, 1);+ assert.equal(transports[0].forwards.length, 1);+ assert.deepEqual(transports[0].forwards[0], {+ localPort: first.localPort,+ remoteHost: "127.0.0.1",+ remotePort: SSH.remotePort,+ });+});++test("close tears the forward down once and a later open starts a new one", async () => {+ const { manager, transports } = harness();+ await manager.open("k1", SSH);++ await manager.close("k1");+ assert.equal(transports[0].lastForward.closes, 1);+ assert.equal(transports[0].disposed, 1, "the ssh process behind the forward must be reaped");++ await manager.close("k1");+ assert.equal(transports[0].lastForward.closes, 1, "closing a host twice must be a no-op");++ // The entry is gone, so the next connect pays for a fresh forward.+ const reopened = await manager.open("k1", SSH);+ assert.equal(transports.length, 2);+ assert.equal(reopened.localPort, 41_002);+ assert.equal(reopened.url, racpUrlForLocalPort(41_002));+});++test("dispose closes every open tunnel", async () => {+ const { manager, transports } = harness();+ await manager.open("k1", SSH);+ await manager.open("k2", { ...SSH, remotePort: 50_000 });++ await manager.dispose();+ assert.equal(transports.length, 2);+ for (const entry of transports) {+ assert.equal(entry.lastForward.closes, 1, `${entry.ssh.host} forward must be closed`);+ assert.equal(entry.disposed, 1);+ }+ await manager.dispose();+ assert.equal(transports[1].lastForward.closes, 1, "dispose is idempotent");+});++test("adopt takes over the bootstrap's forward and retires the one it replaces", async () => {+ const { manager, transports } = harness();+ const opened = await manager.open("k1", SSH);+ const previous = transports[0].lastForward;++ const adopted = fakeForward(45_555);+ const tunnel = await manager.adopt("k1", SSH, adopted);+ assert.equal(tunnel.localPort, 45_555);+ assert.equal(tunnel.url, racpUrlForLocalPort(45_555));+ assert.notEqual(tunnel.localPort, opened.localPort, "the URL must follow the adopted forward");+ assert.equal(previous.closes, 1, "replacing a tunnel must not leak its ssh process");+ assert.equal(transports.length, 1, "adopting must not spawn a second ssh");++ // A host without an entry adopts straight into the registry.+ const fresh = await manager.adopt("k2", SSH, fakeForward(45_556));+ assert.equal(fresh.url, racpUrlForLocalPort(45_556));++ // Ownership moved: the host key now closes the adopted forward.+ await manager.close("k1");+ assert.equal(adopted.closes, 1);+});++test("a refused forward propagates and leaves nothing half-registered", async () => {+ const { manager, transports, armFailure } = harness();+ const refusal = Object.assign(new Error("ssh: connect to host remote.example port 2222: Connection refused"), {+ errorCode: "REMOTE_FORWARD_FAILED",+ });+ armFailure(refusal);++ await assert.rejects(+ () => manager.open("k1", SSH),+ (error) => error === refusal,+ );+ assert.equal(transports[0].forwards.length, 1);+ assert.equal(transports[0].disposed, 1, "a dead ssh client must not be left running");++ // No cached entry, so the next attempt builds a new transport.+ const tunnel = await manager.open("k1", SSH);+ assert.equal(transports.length, 2);+ assert.equal(transports[1].forwards.length, 1);+ assert.equal(tunnel.url, racpUrlForLocalPort(tunnel.localPort));+});diff --git a/docs/adr/0291-ssh-remote-host-bootstrap.md b/docs/adr/0291-ssh-remote-host-bootstrap.mdnew file mode 100644index 000000000..f4b0b3565--- /dev/null+++ b/docs/adr/0291-ssh-remote-host-bootstrap.md@@ -0,0 +1,177 @@+# ADR 0291: SSH bootstrap for remote hosts++- Status: Accepted for implementation+- Date: 2026-09-19+- Decision: D452+- Related: ADR 0205 (D373 / D374 / D375), ADR 0285 (D448), ADR 0286 (D449),+ `02-architecture/05-remote-agent-control.md` §5.2,+ `05-security/02-remote-control-security.md` §3.4,+ `06-delivery/07-remote-control-rollout.md` §2 R2b++## Context++ADR 0286 delivered the desktop-side R2a kernel and left the bootstrap explicitly+out of scope: "Every paired host today assumes the loopback URL already exists."+Reaching another machine meant the user installed `pi-host` there, started it,+opened `ssh -L` themselves, and pasted the resulting URL and a pairing token into+Settings.++R2's exit criteria do not accept that (rollout §2 R2b, security §3.4). The+desktop has to install and pair a host on a machine the user already reaches over+SSH, under two boundaries the security spec fixes: the desktop never uploads+executable bytes, and it never holds an SSH secret.++Three properties of the system as it stands shaped the design:++- `release.yml` publishes `pi-host-<version>-<platform>-<arch>.tar.gz` and its+ `.sha256` to the `v<version>` GitHub Release, and the bundle matrix is Linux+ x64 only.+- A paired host is a URL in `remote-hosts.json`, but a bootstrapped host has no+ stable URL: the local port of a forward is chosen per launch.+- `bootstrap/remote-hosts.ts` already owns every host's lifecycle, so the+ bootstrap plugs into that layer instead of beside it.++## Decision++The bootstrap is five modules under `apps/desktop/electron/main/remote/`, one+extended boot hook, and one new IPC channel.++1. **The system `ssh` client is the transport.** Shelling out to `ssh` beats+ linking an SSH library because the user's `~/.ssh/config`, agent, jump hosts,+ and `known_hosts` then apply unchanged, and the app never holds a secret to+ leak. `BatchMode=yes` is what keeps that honest: a host needing an interactive+ password or passphrase fails immediately with a typed error instead of hanging+ a modal behind an invisible prompt. The module always sets+ `StrictHostKeyChecking=accept-new`, `ConnectTimeout=15`, and+ `ExitOnForwardFailure=yes`.++2. **Pure release coordinates (`pi-host-release.ts`).** The artifact is resolved+ for the *remote* platform at the *desktop's* version, and the SHA-256 the+ release publishes is the trust anchor. `PUBLISHED_TARGETS` is the release+ matrix (`linux-x64` today), so any other target is refused with+ `HOST_BOOTSTRAP_FAILED` before a download starts rather than as a 404 halfway+ through one. URL derivation, `uname` parsing, checksum-file parsing,+ constant-work digest comparison, and the version-parity rule are all pure+ functions with no network and no SSH.++3. **One script runs remotely (`pi-host-bootstrap-script.ts`).** It downloads the+ pinned URL, verifies the digest, installs under `$HOME/.pi-desktop/pi-host`,+ (re)starts the host on loopback with `--pair`, and echoes `PI_HOST_READY` /+ `PI_HOST_PAIRING_TOKEN`. It runs under `umask 077`, so the single-use pairing+ token only ever exists in a work file inside the bootstrap directory and on+ the SSH channel's stdout — never a world-readable path, never a URL+ (security §3.4). Every failure exits non-zero after a+ `PI_HOST_BOOTSTRAP_FAILED <step>` line, so the desktop reports the step that+ failed instead of a bare exit code. Generating it is pure and every input is+ shell-quoted by `shellQuote`, which is what lets the tests execute the+ generated text for real.++4. **`ssh-transport.ts` is a port, not a dependency.** `exec` / `execWithInput` /+ `forward` / `dispose` let the orchestrator be tested end to end against a fake+ with no process spawned; `createSystemSshTransport` is the only implementation+ that spawns. `execWithInput` pipes the script into `sh -s`, so the script+ never survives an argv round trip and never lands in a remote file to clean+ up. Values that reach the `ssh` argv are refused by `assertSshArgument` when+ they are empty or start with `-`: passed as its own argv entry, a leading dash+ becomes an option (`-oProxyCommand=…`), not a destination.++5. **Forwards are durable and owned, not incidental (`ssh-tunnel.ts`).** The+ persisted record stores the SSH descriptor, not a URL; the manager reserves a+ loopback port, runs `ssh -N -L 127.0.0.1:<local>:127.0.0.1:<remotePort>`, and+ derives `ws://127.0.0.1:<port>/v1/racp/ws` per launch, so a restart+ re-establishes the tunnel before connecting instead of dialling a stale port.+ The bootstrap's own forward is *adopted*, not closed and reopened, so pairing+ pays for exactly one tunnel. A forward counts as ready only once its local+ port accepts a connection, because a healthy `ssh -N -L` prints nothing.++6. **Version parity is checked before a forward exists.** The desktop's version+ is what gets downloaded — there is no version negotiation — and+ `PI_HOST_READY.version` must equal it (`v` prefix tolerated either way). A+ mismatch raises `HOST_VERSION_MISMATCH` (D375) before any forward exists, and+ the desktop tears down the SSH processes it spawned on the way out instead of+ leaving a half-connected host behind.++7. **The registry keeps a descriptor, not a URL.** `metadata.transport = "ssh"`+ plus `metadata.ssh` (host, optional port / user / identity file,+ `remotePort`, `version`). `remote-hosts.json` is user-editable, so the+ descriptor is re-validated on every read: a missing host or a `remotePort`+ outside 1..65535 degrades the record to "not an SSH host" instead of+ producing an `ssh` spawn with garbage arguments. Records written before this+ change carry no `transport` and read as `direct`.++8. **One IPC channel and one pairing exchange.**+ `pi-desktop/remoteHost/bootstrap` joins `list` / `pair` / `remove` and carries+ a host, never a credential. The `connection/pair` exchange was factored into+ `exchangePairingToken`, used by both the pasted-URL path and the bootstrap+ path, and it closes its throwaway connection on every path. `bootstrapHost`+ adopts the forward before persisting the record, because the device token only+ works over that forward.++## Invariants++- No SSH secret is stored, prompted for, or transmitted by the app. The only+ credentials the bootstrap touches are the ones the system `ssh` client+ resolves itself.+- No executable bytes travel over the SSH channel. The remote script downloads+ the bundle; the bytes the desktop sends are the script text on stdin.+- `pi-host` keeps binding loopback only. The desktop reaches it through a+ forward and never opens a listener of its own.+- The renderer stays transport-agnostic. `RemoteHostSummary.transport` is+ optional and rendered as a label; no renderer call branches on it.+- An empty registry stays a full no-op: nothing connects and no tunnel opens.+- A failed bootstrap leaves nothing running: its transport is disposed unless+ the caller adopts the forward, and an SSH host whose connect fails has its+ tunnel closed rather than left idle.++## Out of scope++Still open for R2b and later:++- **Terminal work-panel client (Stage 5)** and **reverse tool relay (Stage 6)**+ from ADR 0286. Both remain unbuilt.+- **Provider configuration over the SSH channel.** Spec §3.4 and §5.2 name it as+ part of the bootstrap step, but it needs host-side provider schema work and is+ not in this change, so a freshly bootstrapped host still fails `turn/start`+ closed with `MODEL_NOT_CONFIGURED` until a provider is configured on it.+- **The resync watchdog**: `resync.required` events are still dropped.+- **Non-Linux remote targets, and Windows as a *remote* target.** Only+ `linux-x64` is published, so both are refused before a download starts.++## Alternatives considered++- **An `ssh2`-style library instead of the system client.** Rejected: it+ re-implements config, agent, and jump-host semantics the user already has, and+ asks them to re-enter credentials the app should never hold.+- **Download the artifact on the desktop and upload it.** Rejected by security+ §3.4: the desktop never uploads executable bytes.+- **Let the script read the published `.sha256` itself.** Rejected: the desktop+ should hold the trust anchor, and this keeps the script's only input a URL plus+ a digest.+- **Store the forwarded URL in the registry.** Simpler read path, but the local+ port is not stable across launches, so a restart would dial a port nothing+ listens on. Rejected in favour of the descriptor.+- **Install the host into a user-level service manager.** Rejected: the script+ installs under `$HOME` and restarts the process its own pidfile tracks, which+ keeps the bootstrap privilege-free.++## Testing++The release rules and the script generator are pure and covered by `node --test`+fixtures; the generator's tests run `sh -n` over the produced text and execute it+against a stubbed `PATH`. The orchestrator runs end to end against a fake+transport, a fake checksum fetch, reserved ports, and a fake pairing exchange, so+step order, the digest failure path, the version-mismatch path with no forward,+and the adopt-don't-reopen rule are asserted without spawning a process.++## Consequences++- `remote-hosts.json` gains a second record shape and stays backward compatible:+ existing records have no `transport` and are read as `direct`.+- A machine without outbound GitHub access still cannot be bootstrapped (D375).+- The desktop now spawns `ssh` processes, which is new and visible to+ endpoint-security tooling; until now the remote stack only opened outbound+ WebSocket connections.+- The 16 new `settings.remoteHosts` i18n keys must be translated in every shipped+ locale, because the catalog type is exhaustive.+- No new runtime dependency: the bootstrap adds no SSH library, no HTTP client,+ and no archive tool to `apps/desktop`.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 774427b77..2dd462ac8 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -317,4 +317,5 @@ Each ADR includes:| 0288 | [Package-local theme assets remain available](0288-package-local-theme-assets.md) | Accepted for implementation (amends ADR 0255) || 0289 | [Signed macOS GitHub Releases and in-app update delivery](0289-signed-macos-github-releases.md) | Accepted (D450; amends ADR 0022 / 0145 / 0191 / 0204 / D078) || 0290 | [Restore resizable sidebar width with collapse-below-threshold](0290-resizable-sidebar-collapse-threshold.md) | Accepted (D451; amends ADR 0141 / ADR 0238) |+| 0291 | [SSH bootstrap for remote hosts](0291-ssh-remote-host-bootstrap.md) | Accepted for implementation (D452; ADR 0205 R2b, extends ADR 0286) || turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |diff --git a/docs/spec/06-delivery/07-remote-control-rollout.md b/docs/spec/06-delivery/07-remote-control-rollout.mdindex 93b87327c..e23c6f1e8 100644--- a/docs/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/spec/06-delivery/07-remote-control-rollout.md@@ -434,8 +434,26 @@ Recorded on the `feat/remote-agent-host` branch, 2026-09-10:server and client cores, the `ws` binding on loopback, and device-tokenpairing; handshake, authorization, idempotency, queue order, approvals,cursor replay, eviction, epoch change, slow clients, and reconnect without- duplicate execution are package tests. The `pi-host` bundle, the SSH- bootstrap, and the desktop adapter are not started.+ duplicate execution are package tests. The `pi-host` bundle, the desktop+ adapter, and the SSH bootstrap have since started: the R2a desktop kernel+ (D449 / ADR 0286) brought the adapter and the bundle, and the SSH bootstrap+ followed in D452 / ADR 0291.+- R2b partial (2026-09-19, D452 / ADR 0291): the desktop installs and pairs+ a `pi-host` over the user's own `ssh` client with `BatchMode=yes`, so the+ user's configuration, agent, and jump hosts apply and no SSH secret reaches+ the app. `remote/pi-host-release.ts` holds the pure release coordinates+ (remote platform, desktop version, published SHA-256, refusal of unpublished+ targets) and `remote/pi-host-bootstrap-script.ts` generates the single+ `umask 077` script that downloads, verifies, installs under the remote+ `$HOME`, restarts the host on loopback with `--pair`, and echoes+ `PI_HOST_READY` / `PI_HOST_PAIRING_TOKEN`; `remote/ssh-transport.ts` is the+ injectable transport port and `remote/ssh-tunnel.ts` owns one durable+ `ssh -N -L` forward per host, re-established on every launch and adopted+ from the bootstrap so pairing opens exactly one tunnel. Records carry+ `metadata.transport = "ssh"` plus an SSH descriptor instead of a URL, and+ `pi-desktop/remoteHost/bootstrap` joins `list` / `pair` / `remove`. The+ terminal work-panel client, the reverse tool relay, and provider-configuration+ propagation over the SSH channel are not in this slice.## 8. Amendment historydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 5daefa366..c69afed2d 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -6078,3 +6078,37 @@ that was sitting at the bottom — including after the turn had finished.the expanded sidebar at that threshold.- Renderer only: existing `pi.desktop.sidebarWidth` preference, no IPC or nativewindow change. See ADR 0290 and E2E-168.++## 2026-09-19 — SSH bootstrap for remote hosts (D452)++- The desktop installs and pairs a `pi-host` on a machine the user already+ reaches over SSH using the system `ssh` client, so `~/.ssh/config`, the agent,+ and jump hosts apply unchanged and the app holds no SSH secret; `BatchMode=yes`+ makes a host that needs an interactive password or passphrase fail with a+ typed error instead of hanging behind an invisible prompt.+- The desktop resolves the bundle for the remote platform at its own version,+ holds the SHA-256 the release publishes, and refuses an unpublished target+ (`linux-x64` only today) before any download. The uploaded script downloads,+ verifies, and installs the bundle under the remote `$HOME`; no executable+ bytes cross the SSH channel.+- The script runs under `umask 077` and echoes `PI_HOST_READY` /+ `PI_HOST_PAIRING_TOKEN`, so the single-use pairing token exists only in a work+ file and on the SSH channel, never in a world-readable path or a URL+ (security §3.4). `PI_HOST_READY.version` must equal the desktop's; a mismatch+ is `HOST_VERSION_MISMATCH` (D375) and is checked before a forward exists.+- A paired host now stores an SSH descriptor (`metadata.transport = "ssh"`)+ instead of a URL, because the local forward port is not stable across+ launches; the tunnel manager re-establishes `ssh -N -L` on every launch and+ adopts the bootstrap's own live forward so pairing opens exactly one tunnel.+ The descriptor is re-validated on every registry read, and a malformed one+ degrades to "not an SSH host" rather than spawning `ssh` with garbage+ arguments.+- `pi-desktop/remoteHost/bootstrap` joins `list` / `pair` / `remove`, and the+ `connection/pair` exchange was factored into one `exchangePairingToken` used+ by the pasted-URL path and the bootstrap path alike.+- Not in this slice: the terminal work-panel client (Stage 5), the reverse tool+ relay (Stage 6), the resync watchdog, non-Linux and Windows remote targets,+ and provider configuration over the SSH channel — a freshly bootstrapped host+ still fails `turn/start` closed with `MODEL_NOT_CONFIGURED` until a provider is+ configured on it. See ADR 0291, `06-delivery/07-remote-control-rollout.md` §7,+ and `05-security/02-remote-control-security.md` §3.4.diff --git a/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md b/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.mdindex 74689f894..bce8503b9 100644--- a/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md+++ b/docs/zh-CN/spec/06-delivery/07-remote-control-rollout.md@@ -147,7 +147,8 @@ runbook 写明 feature flag、配对撤销路径、远端机器上的数据保镜像 `agent/event/queueChanged`,“立即发送”即 `turn/prioritize` 加优雅停止。- R1 部分完成(2026-09-18):运行时级别的逐回合权限上限已在 JS 端全链路串通(`AgentPromptRequest.permissionMode` → agent-ipc → `RuntimeService.startTurn` → sidecar `agent.prompt`),桥接层不再对每一处会话/生效模式不一致直接拒绝。生效模式比会话更宽的请求(提权)仍作为深度防御拒绝;更窄的上限透传并在 sidecar 侧作为文档化的占位收下。turn 级的真正执行还差 host-core 一步(`session.beginTurn` 接受覆盖参数),因此本地回合上的收紧目前尚未夹紧工具决策。- R2 已开始(2026-09-18,D447 / ADR 0284):`packages/host-runtime` 承载与 Electron 无关的运行时层 —— host-core 与 sidecar 的 stdio 传输、重启监督器、`RuntimeService`(模块的 `RuntimePort`,含持久回合生命周期)、转录持久化、无头启动解析器与已批准 Plan/Goal 的派发 —— Electron main 通过薄适配层运行其上。-- R2(2026-09-18,D448 / ADR 0285):`packages/racp` 承载 `RACP-WS` 服务端与客户端核心、回环上的 `ws` 绑定与设备令牌配对;握手、鉴权、幂等、队列顺序、审批、游标重放、驱逐、epoch 变更、慢客户端与不重复执行的重连都是包内测试。`pi-host` 包、SSH 引导与桌面适配器尚未开始。+- R2(2026-09-18,D448 / ADR 0285):`packages/racp` 承载 `RACP-WS` 服务端与客户端核心、回环上的 `ws` 绑定与设备令牌配对;握手、鉴权、幂等、队列顺序、审批、游标重放、驱逐、epoch 变更、慢客户端与不重复执行的重连都是包内测试。`pi-host` 包、桌面适配器与 SSH 引导此后均已开始:R2a 桌面内核(D449 / ADR 0286)带来了适配器与 `pi-host` 包,SSH 引导随后在 D452 / ADR 0291 落地。+- R2b 部分完成(2026-09-19,D452 / ADR 0291):桌面使用用户自己的 `ssh` 客户端并以 `BatchMode=yes` 在远端安装并配对 `pi-host`,用户的配置、agent 与跳板机照常生效,应用不持有任何 SSH 密钥。`remote/pi-host-release.ts` 承载纯发布坐标(远端平台、桌面版本、已发布的 SHA-256、拒绝未发布的目标),`remote/pi-host-bootstrap-script.ts` 生成唯一的 `umask 077` 脚本:下载、校验、安装到远端 `$HOME`、以 `--pair` 在回环上重启主机,并回显 `PI_HOST_READY` / `PI_HOST_PAIRING_TOKEN`;`remote/ssh-transport.ts` 是可注入的传输端口,`remote/ssh-tunnel.ts` 为每台主机维护一条持久的 `ssh -N -L` 转发,每次启动重新建立,并在引导时被收编(adopt),使配对只建立一条隧道。记录以 `metadata.transport = "ssh"` 加 SSH 描述符取代 URL,`pi-desktop/remoteHost/bootstrap` 加入 `list` / `pair` / `remove`。终端工作面板客户端、反向工具中继,以及经 SSH 通道下发 provider 配置均不在本次范围内。## 8. 修订记录diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 69e6ca762..c2eb2a87d 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -4426,3 +4426,12 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.- 插件浮层从刻度外的 `80` 与 `60` 归回到 `z-dialog`(40)(`plugins.css`,发行说明浮层一并处理):路由表面不再困住它们之后,它们就在根堆叠上下文中参与比较,而在 80 上会盖住对话框自身弹出的叶子级弹出层(60)与 toast(50)—— 其中包括安装对话框的「已复制」提示。现在有源测试钉住这一关系。- 仅渲染层:无 IPC、存储、schema、协议或插件 SDK 改动,也没有新增默认值。见 `04-ux/07-ui-design-system.md` §9、`apps/desktop/test/settings-dialog-overlay.test.mjs`,以及 `06-delivery/04-e2e-test-plan.md` 的 E2E-LAYOUT-three-column-width-priority(其四条浮层断言位于 `scripts/e2e-three-column-layout.mjs`)。- 未做、留作后续的事项:真正的模态 —— 不可交互化、焦点收束、快捷键让位 —— 需要这些浮层进入浏览器顶层(`<dialog>.showModal()`)。在它们打开的弹出菜单、工具提示与 toast(portal 到 `document.body`)同样迁入顶层之前,这一步无法进行,因为顶层内容会绘制在它们之上并使其不可用;此前的一次尝试正因此被撤回。++## 2026-09-19 —— 远端主机的 SSH 引导(D452)++- 桌面用系统 `ssh` 客户端在用户已能通过 SSH 到达的机器上安装并配对 `pi-host`,因此 `~/.ssh/config`、agent 与跳板机照常生效,应用不持有任何 SSH 密钥;`BatchMode=yes` 让需要交互式密码或口令短语的主机立即以带类型的错误失败,而不是把模态框吊在一个不可见的提示后面。+- 桌面按远端平台、以自己的版本解析 `pi-host` 包,持有发布随附的 SHA-256,并在任何下载之前拒绝未发布的目标(目前只有 `linux-x64`)。上传的脚本在远端 `$HOME` 下下载、校验并安装该包;SSH 通道上不传输任何可执行字节。+- 脚本以 `umask 077` 运行并回显 `PI_HOST_READY` / `PI_HOST_PAIRING_TOKEN`,因此一次性配对令牌只存在于工作文件和 SSH 通道上,既不落在全局可读路径,也不出现在 URL 中(安全规格 §3.4)。`PI_HOST_READY.version` 必须与桌面版本一致;不一致为 `HOST_VERSION_MISMATCH`(D375),并在建立转发之前就已检查。+- 已配对主机的记录改存 SSH 描述符(`metadata.transport = "ssh"`)而非 URL,因为本地转发端口在每次启动间并不稳定;隧道管理器在每次启动时重新建立 `ssh -N -L`,并收编(adopt)引导自己打开的存活转发,使配对只建立一条隧道。描述符在每次读取注册表时都会重新校验,格式不合规时降级为「非 SSH 主机」,而不会用垃圾参数去 spawn `ssh`。+- `pi-desktop/remoteHost/bootstrap` 加入 `list` / `pair` / `remove`,`connection/pair` 交换被抽成单一的 `exchangePairingToken`,粘贴 URL 与 SSH 引导两条路径共用。+- 本次不做:终端工作面板客户端(Stage 5)、反向工具中继(Stage 6)、resync 看门狗、非 Linux 与 Windows 远端目标,以及经 SSH 通道下发 provider 配置 —— 刚引导好的主机在配置 provider 之前,`turn/start` 仍以 `MODEL_NOT_CONFIGURED` 关闭。见 ADR 0291、`06-delivery/07-remote-control-rollout.md` §7 与 `05-security/02-remote-control-security.md` §3.4。diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 986d29ec2..961a266d3 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -835,9 +835,25 @@ sklm: {"fieldLabelDesc": "Wird in der Liste angezeigt und auf dem gekoppelten Host gespeichert.","fieldLabelPlaceholder": "Heim-Linux","fieldUrl": "RACP-URL",- "fieldUrlDesc": "Der Loopback-Endpunkt von pi-host, z. B. ws://127.0.0.1:9443/racp (über SSH weitergeleitet).",+ "fieldUrlDesc": "Der Loopback-Endpunkt von pi-host, z. B. ws://127.0.0.1:9443/v1/racp/ws (über SSH weitergeleitet). Für einen Host, den Sie selbst gestartet haben; die SSH-Installation unten erledigt das für Sie.","fieldPairingToken": "Kopplungstoken",- "fieldPairingTokenDesc": "Einmaliger ppt1.*-Token aus der pi-host-Bootstrap-Ausgabe. Wird beim Koppeln verbraucht."+ "fieldPairingTokenDesc": "Einmaliger ppt1.*-Token aus der pi-host-Bootstrap-Ausgabe. Wird beim Koppeln verbraucht.",+ "sshTitle": "Installation auf einem Server (SSH)",+ "sshBody": "PI-Desktop installiert pi-host auf einem Rechner, den Sie bereits per ssh erreichen, prüft die vom Release veröffentlichte Prüfsumme, startet ihn auf Loopback und koppelt sich damit. Ihre eigenen SSH-Schlüssel authentifizieren — es wird kein Passwort gespeichert.",+ "sshHost": "SSH-Host",+ "sshHostDesc": "Hostname oder Adresse, genau so, wie ssh sie erhält.",+ "sshHostPlaceholder": "build-box.local",+ "sshUser": "Benutzer",+ "sshUserDesc": "Anmeldebenutzer; leer lassen, um Ihren lokalen Benutzernamen zu verwenden.",+ "sshPort": "SSH-Port",+ "sshPortDesc": "Leer lassen für den ssh-Standard (22).",+ "sshIdentityFile": "Identitätsdatei",+ "sshIdentityFileDesc": "Pfad zum privaten Schlüssel; leer lassen, damit der Agent und ~/.ssh/config entscheiden.",+ "sshAction": "Installieren und koppeln",+ "sshRunning": "Wird installiert…",+ "sshSucceeded": "{{label}} installiert und gekoppelt.",+ "sshFailed": "Installation fehlgeschlagen: {{message}}",+ "transportSsh": "SSH"},"importTitle": "Import aus anderen Tools","importScan": "Scannen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex e0c03b74a..5f4da422c 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -844,10 +844,28 @@ sklm: {fieldLabelPlaceholder: "Home Linux",fieldUrl: "RACP URL",fieldUrlDesc:- "The pi-host loopback endpoint, e.g. ws://127.0.0.1:9443/racp (forwarded over SSH).",+ "The pi-host loopback endpoint, e.g. ws://127.0.0.1:9443/v1/racp/ws (forwarded over SSH). For a host you started yourself; the SSH install below does this for you.",fieldPairingToken: "Pairing token",fieldPairingTokenDesc:"Single-use ppt1.* token from the pi-host bootstrap output. Consumed on pair.",+ sshTitle: "Install on a server (SSH)",+ sshBody:+ "PI-Desktop installs pi-host on a machine you already reach with ssh, verifies the checksum the release publishes, starts it on loopback, and pairs with it. Your own SSH keys authenticate — no password is stored.",+ sshHost: "SSH host",+ sshHostDesc: "Host name or address, exactly as ssh receives it.",+ sshHostPlaceholder: "build-box.local",+ sshUser: "User",+ sshUserDesc: "Login user; leave empty to use your local user name.",+ sshPort: "SSH port",+ sshPortDesc: "Leave empty for the ssh default (22).",+ sshIdentityFile: "Identity file",+ sshIdentityFileDesc:+ "Private key path; leave empty to let the agent and ~/.ssh/config decide.",+ sshAction: "Install and pair",+ sshRunning: "Installing…",+ sshSucceeded: "{{label}} installed and paired.",+ sshFailed: "Install failed: {{message}}",+ transportSsh: "SSH",},importTitle: "Import from other tools",importScan: "Scan",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 470291582..fe34d98eb 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -835,9 +835,25 @@ sklm: {"fieldLabelDesc": "Se muestra en la lista y se registra en el host emparejado.","fieldLabelPlaceholder": "Linux de casa","fieldUrl": "URL de RACP",- "fieldUrlDesc": "Punto final de bucle de retorno de pi-host, p. ej. ws://127.0.0.1:9443/racp (reenviado por SSH).",+ "fieldUrlDesc": "Punto final de bucle de retorno de pi-host, p. ej. ws://127.0.0.1:9443/v1/racp/ws (reenviado por SSH). Para un host que usted mismo inició; la instalación SSH de abajo lo hace por usted.","fieldPairingToken": "Token de emparejamiento",- "fieldPairingTokenDesc": "Token ppt1.* de un solo uso del inicio de pi-host. Se consume al emparejar."+ "fieldPairingTokenDesc": "Token ppt1.* de un solo uso del inicio de pi-host. Se consume al emparejar.",+ "sshTitle": "Instalar en un servidor (SSH)",+ "sshBody": "PI-Desktop instala pi-host en una máquina a la que ya accede por ssh, verifica la suma de comprobación que publica la versión, lo inicia en bucle de retorno y se empareja con él. Sus propias claves SSH autentican; no se almacena ninguna contraseña.",+ "sshHost": "Host SSH",+ "sshHostDesc": "Nombre de host o dirección, exactamente como lo recibe ssh.",+ "sshHostPlaceholder": "build-box.local",+ "sshUser": "Usuario",+ "sshUserDesc": "Usuario de inicio de sesión; déjelo vacío para usar su nombre de usuario local.",+ "sshPort": "Puerto SSH",+ "sshPortDesc": "Déjelo vacío para el valor predeterminado de ssh (22).",+ "sshIdentityFile": "Archivo de identidad",+ "sshIdentityFileDesc": "Ruta de la clave privada; déjela vacía para que lo decidan el agente y ~/.ssh/config.",+ "sshAction": "Instalar y emparejar",+ "sshRunning": "Instalando…",+ "sshSucceeded": "{{label}} instalado y emparejado.",+ "sshFailed": "Error de instalación: {{message}}",+ "transportSsh": "SSH"},"importTitle": "Importar desde otras herramientas","importScan": "Escanear",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 76b74e181..c8ef0df6f 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -835,9 +835,25 @@ sklm: {"fieldLabelDesc": "Affichée dans la liste et enregistrée sur l'hôte apparié.","fieldLabelPlaceholder": "Linux à la maison","fieldUrl": "URL RACP",- "fieldUrlDesc": "Point d'accès en boucle locale de pi-host, ex. ws://127.0.0.1:9443/racp (transmis via SSH).",+ "fieldUrlDesc": "Point d'accès en boucle locale de pi-host, ex. ws://127.0.0.1:9443/v1/racp/ws (transmis via SSH). Pour un hôte que vous avez démarré vous-même ; l'installation SSH ci-dessous s'en charge pour vous.","fieldPairingToken": "Jeton d'appariement",- "fieldPairingTokenDesc": "Jeton ppt1.* à usage unique de la sortie de démarrage de pi-host. Consommé à l'appariement."+ "fieldPairingTokenDesc": "Jeton ppt1.* à usage unique de la sortie de démarrage de pi-host. Consommé à l'appariement.",+ "sshTitle": "Installation sur un serveur (SSH)",+ "sshBody": "PI-Desktop installe pi-host sur une machine à laquelle vous accédez déjà par ssh, vérifie la somme de contrôle publiée par la version, le démarre sur la boucle locale et s'y apparie. Vos propres clés SSH authentifient — aucun mot de passe n'est stocké.",+ "sshHost": "Hôte SSH",+ "sshHostDesc": "Nom d'hôte ou adresse, exactement tel que ssh le reçoit.",+ "sshHostPlaceholder": "build-box.local",+ "sshUser": "Utilisateur",+ "sshUserDesc": "Utilisateur de connexion ; laissez vide pour utiliser votre nom d'utilisateur local.",+ "sshPort": "Port SSH",+ "sshPortDesc": "Laissez vide pour la valeur par défaut de ssh (22).",+ "sshIdentityFile": "Fichier d'identité",+ "sshIdentityFileDesc": "Chemin de la clé privée ; laissez vide pour que l'agent et ~/.ssh/config décident.",+ "sshAction": "Installer et apparier",+ "sshRunning": "Installation…",+ "sshSucceeded": "{{label}} installé et apparié.",+ "sshFailed": "Échec de l'installation : {{message}}",+ "transportSsh": "SSH"},"importTitle": "Importer à partir d'autres outils","importScan": "Scanner",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 5ce6eff29..0394fddb2 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -845,10 +845,27 @@ sklm: {fieldLabelPlaceholder: "집 Linux",fieldUrl: "RACP URL",fieldUrlDesc:- "pi-host의 루프백 엔드포인트, 예: ws://127.0.0.1:9443/racp (SSH로 포워딩).",+ "pi-host의 루프백 엔드포인트, 예: ws://127.0.0.1:9443/v1/racp/ws (SSH로 포워딩). 직접 시작한 호스트용이며, 아래 SSH 설치가 대신 처리합니다.",fieldPairingToken: "페어링 토큰",fieldPairingTokenDesc:"pi-host 부트스트랩 출력의 일회용 ppt1.* 토큰. 페어링 시 소비됩니다.",+ sshTitle: "서버에 설치(SSH)",+ sshBody:+ "PI-Desktop은 이미 ssh로 접속할 수 있는 머신에 pi-host를 설치하고, 릴리스가 공개한 체크섬을 검증한 뒤 루프백에서 시작해 그와 페어링합니다. 직접 가진 SSH 키로 인증하며 비밀번호는 저장되지 않습니다.",+ sshHost: "SSH 호스트",+ sshHostDesc: "ssh가 받는 그대로의 호스트 이름 또는 주소입니다.",+ sshHostPlaceholder: "build-box.local",+ sshUser: "사용자",+ sshUserDesc: "로그인 사용자입니다. 비워 두면 로컬 사용자 이름을 사용합니다.",+ sshPort: "SSH 포트",+ sshPortDesc: "비워 두면 ssh 기본값(22)을 사용합니다.",+ sshIdentityFile: "ID 파일",+ sshIdentityFileDesc: "개인 키 경로입니다. 비워 두면 에이전트와 ~/.ssh/config가 결정합니다.",+ sshAction: "설치 및 페어링",+ sshRunning: "설치 중…",+ sshSucceeded: "{{label}} 설치 및 페어링됨.",+ sshFailed: "설치 실패: {{message}}",+ transportSsh: "SSH",},importTitle: "다른 도구에서 가져오기",importScan: "스캔",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 6b7dc4233..41080469f 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -845,10 +845,27 @@ sklm: {fieldLabelPlaceholder: "Evdeki Linux",fieldUrl: "RACP URL",fieldUrlDesc:- "pi-host geri döngü uç noktası, örn. ws://127.0.0.1:9443/racp (SSH üzerinden yönlendirilir).",+ "pi-host geri döngü uç noktası, örn. ws://127.0.0.1:9443/v1/racp/ws (SSH üzerinden yönlendirilir). Kendiniz başlattığınız bir ana bilgisayar içindir; aşağıdaki SSH kurulumu bunu sizin için yapar.",fieldPairingToken: "Eşleşme belirteci",fieldPairingTokenDesc:"pi-host önyükleme çıktısından tek kullanımlık ppt1.* belirteci. Eşleşme sırasında tüketilir.",+ sshTitle: "Bir sunucuya kurun (SSH)",+ sshBody:+ "PI-Desktop, ssh ile zaten erişebildiğiniz bir makineye pi-host kurar, sürümün yayımladığı sağlama toplamını doğrular, geri döngüde başlatır ve onunla eşleşir. Kimlik doğrulamayı kendi SSH anahtarlarınız yapar — hiçbir parola saklanmaz.",+ sshHost: "SSH ana bilgisayarı",+ sshHostDesc: "Ana bilgisayar adı veya adresi, ssh'in aldığı haliyle.",+ sshHostPlaceholder: "build-box.local",+ sshUser: "Kullanıcı",+ sshUserDesc: "Oturum açma kullanıcısı; yerel kullanıcı adınızı kullanmak için boş bırakın.",+ sshPort: "SSH bağlantı noktası",+ sshPortDesc: "ssh varsayılanı (22) için boş bırakın.",+ sshIdentityFile: "Kimlik dosyası",+ sshIdentityFileDesc: "Özel anahtar yolu; aracı ve ~/.ssh/config karar versin diye boş bırakın.",+ sshAction: "Kur ve eşle",+ sshRunning: "Kuruluyor…",+ sshSucceeded: "{{label}} kuruldu ve eşlendi.",+ sshFailed: "Kurulum başarısız: {{message}}",+ transportSsh: "SSH",},importTitle: "Diğer araçlardan içe aktar",importScan: "Tara",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex e143c7f95..a0c8f9b87 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -834,10 +834,27 @@ sklm: {fieldLabelPlaceholder: "家里的 Linux",fieldUrl: "RACP 地址",fieldUrlDesc:- "pi-host 的回环端点,例如 ws://127.0.0.1:9443/racp(经 SSH 转发)。",+ "pi-host 的回环端点,例如 ws://127.0.0.1:9443/v1/racp/ws(经 SSH 转发)。适用于你自己启动的主机;下面的 SSH 安装会替你完成这一步。",fieldPairingToken: "配对令牌",fieldPairingTokenDesc:"来自 pi-host 引导输出的一次性 ppt1.* 令牌,配对后即消耗。",+ sshTitle: "在服务器上安装(SSH)",+ sshBody:+ "PI-Desktop 会在你已能用 ssh 登录的机器上安装 pi-host,校验发布方公布的 checksum,在回环上启动并与它配对。认证使用你自己的 SSH 密钥,不保存任何密码。",+ sshHost: "SSH 主机",+ sshHostDesc: "主机名或地址,按 ssh 的原样传入。",+ sshHostPlaceholder: "build-box.local",+ sshUser: "用户",+ sshUserDesc: "登录用户;留空则使用本机用户名。",+ sshPort: "SSH 端口",+ sshPortDesc: "留空使用 ssh 默认值(22)。",+ sshIdentityFile: "私钥文件",+ sshIdentityFileDesc: "私钥路径;留空则由 agent 与 ~/.ssh/config 决定。",+ sshAction: "安装并配对",+ sshRunning: "安装中…",+ sshSucceeded: "已安装并配对 {{label}}。",+ sshFailed: "安装失败:{{message}}",+ transportSsh: "SSH",},importTitle: "从其他工具导入",importScan: "扫描",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 83de00ceb..fd376b626 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -834,10 +834,27 @@ sklm: {fieldLabelPlaceholder: "家裡的 Linux",fieldUrl: "RACP 位址",fieldUrlDesc:- "pi-host 的迴環端點,例如 ws://127.0.0.1:9443/racp(經 SSH 轉發)。",+ "pi-host 的迴環端點,例如 ws://127.0.0.1:9443/v1/racp/ws(經 SSH 轉發)。適用於你自己啟動的主機;下方的 SSH 安裝會替你完成這一步。",fieldPairingToken: "配對權杖",fieldPairingTokenDesc:"來自 pi-host 引導輸出的一次性 ppt1.* 權杖,配對後即消耗。",+ sshTitle: "在伺服器上安裝(SSH)",+ sshBody:+ "PI-Desktop 會在你已能用 ssh 登入的機器上安裝 pi-host,校驗發行方公布的 checksum,在迴環上啟動並與它配對。認證使用你自己的 SSH 金鑰,不會儲存任何密碼。",+ sshHost: "SSH 主機",+ sshHostDesc: "主機名稱或位址,與 ssh 收到的原樣相同。",+ sshHostPlaceholder: "build-box.local",+ sshUser: "使用者",+ sshUserDesc: "登入使用者;留空則使用本機使用者名稱。",+ sshPort: "SSH 連接埠",+ sshPortDesc: "留空使用 ssh 預設值(22)。",+ sshIdentityFile: "私密金鑰檔案",+ sshIdentityFileDesc: "私密金鑰路徑;留空則由 agent 與 ~/.ssh/config 決定。",+ sshAction: "安裝並配對",+ sshRunning: "安裝中…",+ sshSucceeded: "已安裝並配對 {{label}}。",+ sshFailed: "安裝失敗:{{message}}",+ transportSsh: "SSH",},importTitle: "從其他工具匯入",importScan: "掃描",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 55eb14c56..566decab2 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -158,6 +158,14 @@ export const IPC = {remoteHostPair: "pi-desktop/remoteHost/pair",/** Close the live connection for `hostKey` and drop its persisted record. */remoteHostRemove: "pi-desktop/remoteHost/remove",+ /**+ * Install and pair a `pi-host` on a machine the user reaches over SSH:+ * upload the bootstrap script, download and verify the published bundle+ * there, start the host, forward its loopback port, and exchange the+ * pairing token (spec §5.2). Uses the user's own SSH keys; no credential+ * crosses this channel.+ */+ remoteHostBootstrap: "pi-desktop/remoteHost/bootstrap",providersList: "pi-desktop/providers/list",providersCreate: "pi-desktop/providers/create",providersUpdate: "pi-desktop/providers/update",diff --git a/packages/shared/src/types/remote-host.ts b/packages/shared/src/types/remote-host.tsindex 18bb3ee54..6531a2a28 100644--- a/packages/shared/src/types/remote-host.ts+++ b/packages/shared/src/types/remote-host.ts@@ -7,11 +7,45 @@* Companion of `RemoteHostRecord` inside main (which additionally carries* `deviceToken`). See ADR 0286 §Registry and R2b pairing UX.*/++/**+ * How the desktop reaches a paired host.+ *+ * - `direct`: a URL the user supplied, including a forward they opened+ * themselves with `ssh -L` (`RemoteHostPairRequest`).+ * - `ssh`: a host the desktop bootstrapped itself and keeps a port forward+ * open for (spec §5.2). The stored URL is derived from that forward, so the+ * SSH descriptor is the durable half of the record.+ */+export type RemoteHostTransport = "direct" | "ssh";++/**+ * The SSH descriptor a bootstrapped host reconnects through. Persisted in the+ * host record so the forward can be re-established on the next launch without+ * another bootstrap.+ */+export type RemoteHostSshMetadata = {+ /** Host name or address as `ssh` receives it (no `user@` prefix). */+ host: string;+ /** `ssh -p` value; absent means the SSH default. */+ port?: number;+ /** `ssh` login user; absent means the local user name. */+ user?: string;+ /** `ssh -i` value; absent means the agent and `~/.ssh/config` decide. */+ identityFile?: string;+ /** `pi-host`'s loopback port on the remote machine. */+ remotePort: number;+ /** Release version the bootstrap installed, checked against `APP_VERSION`. */+ version: string;+};+export type RemoteHostSummary = {hostKey: string;label: string;url: string;connected: boolean;+ /** Absent on records written before the SSH bootstrap existed → `direct`. */+ transport?: RemoteHostTransport;};/**@@ -41,3 +75,37 @@ export type RemoteHostPairResult = {export type RemoteHostRemoveRequest = {hostKey: string;};++/**+ * Input for `remoteHostBootstrap`: install and pair a `pi-host` on a machine+ * the user can already reach over SSH (spec §5.2). The desktop uses the user's+ * own SSH configuration and keys, so no credential ever crosses this IPC+ * channel.+ */+export type RemoteHostBootstrapRequest = {+ /** Human label for the host list, and the device label the host records. */+ label: string;+ /** SSH host name or address, without a `user@` prefix. */+ host: string;+ /** `ssh -p` value; absent means the SSH default. */+ port?: number;+ /** SSH login user; absent means the local user name. */+ user?: string;+ /** `ssh -i` value; absent means the agent and `~/.ssh/config` decide. */+ identityFile?: string;+ /**+ * Loopback port `pi-host` should bind on the remote machine. `0` or absent+ * lets the host pick a free port and report it back.+ */+ remotePort?: number;+ /** Optional stable routing key; absent means the desktop mints one. */+ hostKey?: string;+};++export type RemoteHostBootstrapResult = {+ host: RemoteHostSummary;+ /** The descriptor the desktop reconnects through on later launches. */+ ssh: RemoteHostSshMetadata;+ /** Ordered bootstrap steps that completed, for a Settings progress line. */+ steps: string[];+};