Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(relay): P3 desktop host — standing phone relay host + pin-once approval
enes49038188b72a
diff --git a/src/main/index.ts b/src/main/index.tsindex bb8b981d0..5ea63dd32 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -42,12 +42,19 @@ import { initCanvasControl, installCanvasSkillInto } from './canvas-control'import { initTranscriptIndex, searchTranscripts } from './transcript-index'import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'-import { initLicense } from './license'+import { initLicense, isPremium, getStoredEntitlement } from './license'import { initClaudeAccounts, claudeConfigDirFor } from './claude-accounts'import { isSafeLocalTranscriptPath } from './claude-accounts-core'import { installClaudeHooksInto } from './agents/hooks/claude'import { createPairingService } from './pairing-service'-import { initRemoteHost } from './remote/host-service'+import {+ initRemoteHost,+ loadOrCreateKeyPair,+ relayAllowed,+ API_BASE as RELAY_API_BASE,+ RELAY_URL+} from './remote/host-service'+import { initStandingHost } from './remote/standing-host'import { initRemoteClient } from './remote/client-service'import { initSshProject } from './remote-ssh/ssh-project'import { setGitRemoteResolver, type GitRemoteRef } from './remote-ssh/remote-git'@@ -356,7 +363,15 @@ app.whenReady().then(async () => {// Phone pairing (nodeterm iOS "scan a QR" flow): a one-shot LAN listener that installs the// phone's Ed25519 key into ~/.ssh/authorized_keys. The completion result is forwarded to the// window over `pairing:done` so the settings section can show the paired/timeout state.- const pairingService = createPairingService()+ const pairingService = createPairingService({+ getSettings: () => settingsStore.get(),+ isPremium,+ getEntitlement: getStoredEntitlement,+ loadHostKeyPair: loadOrCreateKeyPair,+ relayEndpoint: RELAY_URL,+ apiBase: RELAY_API_BASE,+ relayAllowed+ })ipcMain.handle(IPC.pairingStart, () =>pairingService.start((result) => {const w = getMainWindow()@@ -814,6 +829,12 @@ app.whenReady().then(async () => {// after the user has connected an SSH project) always sees the live manager.initClaudeAccounts(() => sshProjectManager)initRemoteHost(win, ptyManager)+ // Standing (phone) relay host: keep a host connection registered so a paired phone can reach+ // this Mac from anywhere. Honors settings.phoneAccessEnabled + the Pro gate internally.+ const standingHost = initStandingHost(win, ptyManager, () => settingsStore.get())+ ipcMain.on(IPC.remoteStandingHostSet, (_e, enabled: boolean) => standingHost.setEnabled(!!enabled))+ // Reconcile from persisted settings on launch (starts hosting if enabled + Pro).+ standingHost.syncFromSettings()initRemoteClient(win, { isPackaged: app.isPackaged })sshProjectManager = initSshProject(win)// Route git-service + commit-message git ops over the active SSH project's master only — and onlydiff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.tsindex e4e54fc8f..3b2eaa464 100644--- a/src/main/pairing-core.test.ts+++ b/src/main/pairing-core.test.ts@@ -61,6 +61,38 @@ describe('buildPairingPayload', () => {})expect(JSON.parse(json).port).toBe(2222)})++ it('omits the relay block when absent (byte-for-byte legacy LAN-only shape)', () => {+ const json = buildPairingPayload({+ host: 'h',+ user: 'u',+ token: 't',+ pairPort: 1,+ name: 'n'+ })+ expect(json).not.toContain('relay')+ expect(JSON.parse(json)).not.toHaveProperty('relay')+ })++ it('appends the relay block after name when supplied', () => {+ const relay = {+ hostId: 'abcABC012_-def012ghij',+ hostPublicKeyB64: 'AAAA',+ relayEndpoint: 'wss://relay.nodeterm.dev'+ }+ const json = buildPairingPayload({+ host: '192.168.1.5',+ user: 'enes',+ token: 'tok',+ pairPort: 5,+ name: 'Mac',+ relay+ })+ expect(json).toBe(+ '{"v":1,"host":"192.168.1.5","port":22,"user":"enes","token":"tok","pairPort":5,"nodeterm":true,"name":"Mac","relay":{"hostId":"abcABC012_-def012ghij","hostPublicKeyB64":"AAAA","relayEndpoint":"wss://relay.nodeterm.dev"}}'+ )+ expect(JSON.parse(json).relay).toEqual(relay)+ })})describe('isValidEd25519PublicKey', () => {diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.tsindex 53bce12e2..75ded09d6 100644--- a/src/main/pairing-core.ts+++ b/src/main/pairing-core.ts@@ -3,6 +3,21 @@// The QR payload + the authorized_keys line validation are the two bits of the pairing flow// with a fixed on-the-wire contract shared with the nodeterm iOS app — keep them here, pure.+/**+ * The relay block optionally embedded in the QR payload (and the /pair HTTP response). Present+ * only when this host has phone-access (standing relay host) enabled + Pro, so the phone can+ * reach it over the relay from anywhere. Absent → the phone is LAN-only (pre-P3 behavior).+ * Matches the iOS contract exactly.+ */+export interface RelayPairingBlock {+ /** The relay broker room id: base64url(sha256(hostPublicKey)).slice(0,22). */+ hostId: string+ /** The host's NaCl box public key (standard base64), for the phone's E2EE handshake. */+ hostPublicKeyB64: string+ /** The relay WebSocket endpoint the phone connects to. */+ relayEndpoint: string+}+/** Inputs for the QR payload the iOS app scans. `port` defaults to 22 (SSH). */export interface PairingPayloadInput {host: string@@ -11,15 +26,19 @@ export interface PairingPayloadInput {token: stringpairPort: numbername: string+ /** Optional relay reachability block (standing host). Omitted from the payload when absent. */+ relay?: RelayPairingBlock}/*** Build the single-line JSON the QR encodes. The key order + compact separators match the* contract the phone parses:* {"v":1,"host":"…","port":22,"user":"…","token":"…","pairPort":N,"nodeterm":true,"name":"…"}+ * When a relay block is supplied it is appended as `"relay":{…}` after `name`; otherwise the+ * payload is byte-for-byte the legacy LAN-only shape.*/export function buildPairingPayload(input: PairingPayloadInput): string {- return JSON.stringify({+ const base = {v: 1,host: input.host,port: input.port ?? 22,@@ -28,7 +47,8 @@ export function buildPairingPayload(input: PairingPayloadInput): string {pairPort: input.pairPort,nodeterm: true,name: input.name- })+ }+ return JSON.stringify(input.relay ? { ...base, relay: input.relay } : base)}/**diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex 050c95d5b..674659bb7 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -31,11 +31,94 @@ import {toPublicDevices,upsertDevice,type DeviceEntry,- type PublicDevice+ type PublicDevice,+ type RelayPairingBlock} from './pairing-core'+import type { Settings } from '../shared/types'+import { publicKeyToB64, type KeyPair } from './remote/e2ee'+import { hostIdFromPublicKeyB64 } from './remote/relay-id'const execFileAsync = promisify(execFile)+/**+ * Optional relay dependencies injected into the pairing service. When present AND phone access is+ * enabled + Pro, a successful LAN pair ALSO provisions the phone for the relay (a device token ++ * the host's relay identity), so it can reach this Mac from anywhere. Injected (not imported) so+ * `pairing-core` stays pure and this stays testable. Absent / any failure ⇒ LAN-only (the phone+ * still pairs; it just won't get relay access).+ */+export interface PairingRelayDeps {+ getSettings(): Settings+ isPremium(): boolean+ getEntitlement(): string | null+ loadHostKeyPair(): Promise<KeyPair>+ /** The relay WebSocket endpoint advertised to the phone. */+ relayEndpoint: string+ /** The API base for the /v1/relay/device mint. */+ apiBase: string+ /** Dev gate: never hit the prod relay/API from an unpackaged build (mirrors host-service). */+ relayAllowed(): boolean+}++interface RelayDeviceResponse {+ deviceToken: string+ hostId: string+ exp: number+}++/** Mint a relay device token so a freshly-paired phone can reach this host over the relay. */+async function mintRelayDevice(+ apiBase: string,+ body: { entitlement: string; deviceId: string; hostPublicKeyB64: string; label?: string }+): Promise<RelayDeviceResponse | null> {+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), 8000)+ try {+ const res = await fetch(`${apiBase}/v1/relay/device`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal: ctrl.signal+ })+ if (!res.ok) return null+ const json = (await res.json().catch(() => ({}))) as Partial<RelayDeviceResponse>+ if (!json.deviceToken) return null+ return { deviceToken: json.deviceToken, hostId: json.hostId ?? '', exp: json.exp ?? 0 }+ } catch {+ return null+ } finally {+ clearTimeout(timer)+ }+}++/**+ * Compute this host's relay reachability block WITHOUT any network call (just the host key →+ * hostId), so the QR renders instantly. Returns null (LAN-only) when phone access is off, not Pro,+ * blocked in dev, or no entitlement is stored.+ */+async function buildRelayContext(+ deps: PairingRelayDeps | undefined+): Promise<{ block: RelayPairingBlock; entitlement: string } | null> {+ if (!deps || !deps.relayAllowed()) return null+ if (!deps.getSettings().phoneAccessEnabled || !deps.isPremium()) return null+ const entitlement = deps.getEntitlement()+ if (!entitlement) return null+ try {+ const keys = await deps.loadHostKeyPair()+ const hostPublicKeyB64 = publicKeyToB64(keys.publicKey)+ return {+ block: {+ hostId: hostIdFromPublicKeyB64(hostPublicKeyB64),+ hostPublicKeyB64,+ relayEndpoint: deps.relayEndpoint+ },+ entitlement+ }+ } catch {+ return null+ }+}+/** How long the listener waits for the phone before giving up. */const PAIR_TIMEOUT_MS = 2 * 60 * 1000/** Probe timeout for the "is sshd listening on :22?" check. */@@ -190,7 +273,7 @@ function readBody(req: IncomingMessage): Promise<string> {})}-export function createPairingService(): PairingService {+export function createPairingService(relayDeps?: PairingRelayDeps): PairingService {let server: Server | null = nulllet timer: ReturnType<typeof setTimeout> | null = nulllet onDoneCb: ((result: PairingDone) => void) | null = null@@ -245,7 +328,18 @@ export function createPairingService(): PairingService {const addr = srv.address()const pairPort = typeof addr === 'object' && addr ? addr.port : 0const [name, sshOpen] = await Promise.all([computerName(), probeSsh()])- const payload = buildPairingPayload({ host, port: 22, user, token, pairPort, name })+ // Relay reachability (network-free) — embedded in the QR so the phone can reach us over the+ // relay too. Also reused in handleRequest to mint the phone's device token. LAN-only when null.+ const relayCtx = await buildRelayContext(relayDeps)+ const payload = buildPairingPayload({+ host,+ port: 22,+ user,+ token,+ pairPort,+ name,+ relay: relayCtx?.block+ })// Give up after 2 minutes with a timeout result.timer = setTimeout(() => finish({ ok: false }), PAIR_TIMEOUT_MS)@@ -258,7 +352,7 @@ export function createPairingService(): PairingService {}try {const raw = await readBody(req)- let body: { token?: unknown; publicKey?: unknown; deviceName?: unknown }+ let body: { token?: unknown; publicKey?: unknown; deviceName?: unknown; deviceId?: unknown }try {body = JSON.parse(raw)} catch {@@ -287,9 +381,30 @@ export function createPairingService(): PairingService {pairedAt: Date.now(),lastSeenAt: 0})+ // Provision relay access for the phone when enabled + Pro. Any failure ⇒ LAN-only: we+ // never fail the pairing over a relay hiccup (the phone still got its SSH key installed).+ let relayFields: { relay?: RelayPairingBlock; relayDeviceToken?: string } = {}+ if (relayCtx) {+ const phoneDeviceId =+ typeof body.deviceId === 'string' && body.deviceId.trim()+ ? body.deviceId.trim()+ : deviceId+ const minted = await mintRelayDevice(relayDeps!.apiBase, {+ entitlement: relayCtx.entitlement,+ deviceId: phoneDeviceId,+ hostPublicKeyB64: relayCtx.block.hostPublicKeyB64,+ label: name+ })+ if (minted?.deviceToken) {+ relayFields = {+ relay: { ...relayCtx.block, hostId: minted.hostId || relayCtx.block.hostId },+ relayDeviceToken: minted.deviceToken+ }+ }+ }res.writeHead(200, { 'Content-Type': 'application/json' })- .end(JSON.stringify({ ok: true, deviceId, agentToken }))+ .end(JSON.stringify({ ok: true, deviceId, agentToken, ...relayFields }))finish({ ok: true })} catch (err) {res.writeHead(500).end('pairing failed')diff --git a/src/main/remote/approved-devices-core.test.ts b/src/main/remote/approved-devices-core.test.tsnew file mode 100644index 000000000..1deec9f27--- /dev/null+++ b/src/main/remote/approved-devices-core.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest'+import {+ emptyApprovedDevices,+ isPinned,+ parseApprovedDevices,+ pinDevice,+ unpinDevice+} from './approved-devices-core'++describe('approved-devices-core', () => {+ describe('parseApprovedDevices', () => {+ it('returns empty for missing / malformed input', () => {+ expect(parseApprovedDevices(undefined)).toEqual({ pubkeys: [] })+ expect(parseApprovedDevices(null)).toEqual({ pubkeys: [] })+ expect(parseApprovedDevices(42)).toEqual({ pubkeys: [] })+ expect(parseApprovedDevices({})).toEqual({ pubkeys: [] })+ expect(parseApprovedDevices({ pubkeys: 'nope' })).toEqual({ pubkeys: [] })+ })++ it('keeps non-empty string entries and drops junk, de-duping in order', () => {+ expect(+ parseApprovedDevices({ pubkeys: ['a', '', 'b', 42, 'a', null, 'c'] })+ ).toEqual({ pubkeys: ['a', 'b', 'c'] })+ })+ })++ describe('isPinned', () => {+ it('matches an exact pinned key and rejects empty / unknown', () => {+ const store = { pubkeys: ['keyA', 'keyB'] }+ expect(isPinned(store, 'keyA')).toBe(true)+ expect(isPinned(store, 'keyB')).toBe(true)+ expect(isPinned(store, 'keyC')).toBe(false)+ expect(isPinned(store, '')).toBe(false)+ expect(isPinned(emptyApprovedDevices(), 'keyA')).toBe(false)+ })+ })++ describe('pinDevice', () => {+ it('appends a new key', () => {+ expect(pinDevice({ pubkeys: ['a'] }, 'b')).toEqual({ pubkeys: ['a', 'b'] })+ })++ it('is idempotent and returns the same object when already pinned', () => {+ const store = { pubkeys: ['a'] }+ expect(pinDevice(store, 'a')).toBe(store)+ })++ it('ignores an empty key', () => {+ const store = { pubkeys: ['a'] }+ expect(pinDevice(store, '')).toBe(store)+ })+ })++ describe('unpinDevice', () => {+ it('removes a pinned key and is a no-op otherwise', () => {+ expect(unpinDevice({ pubkeys: ['a', 'b'] }, 'a')).toEqual({ pubkeys: ['b'] })+ const store = { pubkeys: ['a'] }+ expect(unpinDevice(store, 'zzz')).toBe(store)+ })+ })+})diff --git a/src/main/remote/approved-devices-core.ts b/src/main/remote/approved-devices-core.tsnew file mode 100644index 000000000..7715eebe8--- /dev/null+++ b/src/main/remote/approved-devices-core.ts@@ -0,0 +1,52 @@+// Pure pin/lookup logic for the standing (phone) host's "pin once" device approval.+//+// The FIRST time a phone (identified by its NaCl box public key, base64) connects over the relay+// the host human approves it via the SAS dialog; on approval its pubkey is pinned here so future+// connects auto-approve with no prompt. These are PUBLIC keys, not credentials — safe to persist.+//+// Kept pure (no I/O) so it can be unit-tested; the disk read/write wrapper lives in+// `approved-devices.ts`.++/** The persisted shape of <userData>/remote-approved-devices.json. */+export interface ApprovedDevices {+ /** Base64 NaCl box public keys of phones the host has approved at least once. */+ pubkeys: string[]+}++export function emptyApprovedDevices(): ApprovedDevices {+ return { pubkeys: [] }+}++/** Coerce arbitrary parsed JSON into a well-formed ApprovedDevices (drops non-string / empty entries). */+export function parseApprovedDevices(raw: unknown): ApprovedDevices {+ if (!raw || typeof raw !== 'object') return emptyApprovedDevices()+ const pubkeys = (raw as { pubkeys?: unknown }).pubkeys+ if (!Array.isArray(pubkeys)) return emptyApprovedDevices()+ // De-dupe while preserving order; keep only non-empty strings.+ const seen = new Set<string>()+ const out: string[] = []+ for (const k of pubkeys) {+ if (typeof k === 'string' && k.length > 0 && !seen.has(k)) {+ seen.add(k)+ out.push(k)+ }+ }+ return { pubkeys: out }+}++/** True when `pubkeyB64` has been pinned before. Empty input is never pinned. */+export function isPinned(store: ApprovedDevices, pubkeyB64: string): boolean {+ return pubkeyB64.length > 0 && store.pubkeys.includes(pubkeyB64)+}++/** Return a store with `pubkeyB64` pinned. Idempotent; returns the same object when already present. */+export function pinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {+ if (pubkeyB64.length === 0 || store.pubkeys.includes(pubkeyB64)) return store+ return { pubkeys: [...store.pubkeys, pubkeyB64] }+}++/** Return a store with `pubkeyB64` unpinned (revoke). Idempotent. */+export function unpinDevice(store: ApprovedDevices, pubkeyB64: string): ApprovedDevices {+ if (!store.pubkeys.includes(pubkeyB64)) return store+ return { pubkeys: store.pubkeys.filter((k) => k !== pubkeyB64) }+}diff --git a/src/main/remote/approved-devices.ts b/src/main/remote/approved-devices.tsnew file mode 100644index 000000000..67fb0ed24--- /dev/null+++ b/src/main/remote/approved-devices.ts@@ -0,0 +1,35 @@+// Disk read/write for the standing (phone) host's pinned-device list. The pure pin/lookup logic+// lives in `approved-devices-core.ts`; this only touches the filesystem.+//+// Stored at <userData>/remote-approved-devices.json. The contents are PUBLIC keys (device box+// public keys the host has approved once), never credentials.++import { promises as fs } from 'fs'+import path from 'path'+import { app } from 'electron'+import {+ emptyApprovedDevices,+ parseApprovedDevices,+ type ApprovedDevices+} from './approved-devices-core'++function file(): string {+ return path.join(app.getPath('userData'), 'remote-approved-devices.json')+}++/** Load the pinned-device list; returns an empty list when the file is absent or malformed. */+export async function loadApprovedDevices(): Promise<ApprovedDevices> {+ try {+ return parseApprovedDevices(JSON.parse(await fs.readFile(file(), 'utf-8')))+ } catch {+ return emptyApprovedDevices()+ }+}++/** Persist the pinned-device list atomically (temp + rename, 0600). */+export async function saveApprovedDevices(store: ApprovedDevices): Promise<void> {+ const target = file()+ const tmp = `${target}.tmp`+ await fs.writeFile(tmp, JSON.stringify(store), { encoding: 'utf-8', mode: 0o600 })+ await fs.rename(tmp, target)+}diff --git a/src/main/remote/host-canvas-hub.ts b/src/main/remote/host-canvas-hub.tsnew file mode 100644index 000000000..19d8b79aa--- /dev/null+++ b/src/main/remote/host-canvas-hub.ts@@ -0,0 +1,40 @@+// Shared source of the host renderer's latest active-project canvas snapshot.+//+// The renderer pushes its serialized canvas over `remoteHostCanvasState`; both the interactive+// remote host (host-service) and the standing phone host (standing-host) mirror that same canvas+// to their respective clients. Centralizing the single IPC listener here (installed once) lets+// both host sessions read the current snapshot and subscribe to updates without duplicating the+// listener or fighting over `latestCanvas`.++import { ipcMain } from 'electron'+import { IPC } from '../../shared/ipc'+import type { CanvasState } from '../../shared/types'++type Sub = (state: CanvasState) => void++const subs = new Set<Sub>()+let latest: CanvasState | null = null+let installed = false++/** Install the single `remoteHostCanvasState` IPC listener. Idempotent — safe to call from each host. */+export function initHostCanvasHub(): void {+ if (installed) return+ installed = true+ ipcMain.on(IPC.remoteHostCanvasState, (_e, state: CanvasState) => {+ latest = state+ for (const s of subs) s(state)+ })+}++/** The most recent canvas snapshot the renderer pushed, or null before the first push. */+export function currentCanvas(): CanvasState | null {+ return latest+}++/** Subscribe to canvas updates. Returns an unsubscribe function. */+export function subscribeCanvas(cb: Sub): () => void {+ subs.add(cb)+ return () => {+ subs.delete(cb)+ }+}diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 00b8cd6a0..07bb290ec 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -33,12 +33,13 @@ import { OP, type Frame } from './framing'import { encodeOffer } from './pairing'import { sanitizeClientMutation } from './canvas-sync'import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'+import { initHostCanvasHub, currentCanvas, subscribeCanvas } from './host-canvas-hub'// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).-const RELAY_URL = process.env.NODETERM_RELAY_URL || 'wss://relay.nodeterm.dev'+export const RELAY_URL = process.env.NODETERM_RELAY_URL || 'wss://relay.nodeterm.dev'-const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'+export const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'const textEncoder = new TextEncoder()const textDecoder = new TextDecoder()@@ -477,7 +478,10 @@ async function persistKeyPair(keys: KeyPair): Promise<void> {// migrated to the encrypted form in place, KEEPING the identity (never regenerate on migrate);// an undecryptable blob (OS keychain reset) falls through to a fresh identity — old offers are// single-use pairing tokens, so new offers simply carry the new key.-async function loadOrCreateKeyPair(): Promise<KeyPair> {+//+// Exported so the standing (phone) host and the pairing service can advertise the SAME host+// identity (public key → hostId) the interactive host uses.+export async function loadOrCreateKeyPair(): Promise<KeyPair> {try {const raw = JSON.parse(await fs.readFile(keyFile(), 'utf-8')) as {publicKey?: string@@ -512,64 +516,171 @@ async function loadOrCreateKeyPair(): Promise<KeyPair> {// Never hit the real relay/API from an unpackaged build unless a relay is explicitly targeted// (mirrors license.ts's `allowed()` gate). Packaged builds are always allowed.-function relayAllowed(): boolean {+export function relayAllowed(): boolean {return app.isPackaged || !!process.env.NODETERM_RELAY_URL}-// --- IPC wiring --------------------------------------------------------------+// --- shared host session (interactive host + standing phone host) ------------/**- * Wire the host-mode IPC. `remote:host:start` gates on Pro, mints a pairing token, connects to- * the relay as host, and returns the offer string. `remote:host:stop` closes the relay socket- * (which kills the served PTYs and drops the client's access).+ * A live host<->client relay session: the bridged relay socket plus its RPC/frame handlers and+ * canvas mirror, gated by an approval flag. Both the interactive remote host and the standing+ * phone host build one of these; they differ only in how a freshly-bridged peer is approved+ * (interactive SAS prompt vs. pin-once auto-approve).*/-export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void {- let socket: RelaySocket | null = null+export interface HostSession {+ /** Approve the currently-bridged peer → begin serving its pty/fs RPCs + input frames. */+ approve(): void+ /** Currently approved? */+ isApproved(): boolean+ /** Channel SAS (for the approval prompt), or null before the handshake derives a key. */+ sas(): string | null+ /** The bridged peer's box public key (base64), or null before `e2ee_hello`. */+ peerPublicKeyB64(): string | null+ /** Tear down: kill served PTYs + close the relay socket. */+ close(): void+}++export interface HostSessionOptions {+ /** Relay wss URL. */+ url: string+ /** Single-use pairing token gating entry at the relay. */+ token: string+ /** The long-lived host NaCl keypair. */+ ourKeys: KeyPair+ /** The real pty-manager whose tmux sessions the peer attaches to. */+ pty: PtyManager+ /** The host renderer's latest active-project canvas snapshot (source of the mirror). */+ getLatestCanvas(): CanvasState | null+ /** Subscribe to canvas updates so the mirror re-broadcasts. Returns unsubscribe. */+ subscribeCanvas(cb: (state: CanvasState) => void): () => void+ /** Forward a (sanitized) client canvas mutation to the host renderer (the single writer). */+ applyMutation(mutation: CanvasMutation): void+ /**+ * A peer completed the E2EE handshake and awaits an approval decision. The caller inspects the+ * session (sas / peerPublicKeyB64) and either approves immediately (pin-once) or prompts the+ * host human, later calling `approve()`.+ */+ onPeerReady(session: HostSession): void+ /** The relay socket dropped (client/relay gone). */+ onClose(): void+}++/**+ * Build a host relay session: connect as the host, wire the RPC/frame handlers + canvas mirror,+ * and gate everything behind an approval flag. Extracted so the interactive host (initRemoteHost)+ * and the standing phone host share one implementation.+ */+export function connectHostSession(opts: HostSessionOptions): HostSession {+ // Approval gate: a freshly-bridged peer serves NO pty/fs RPCs or input frames until approved,+ // so a leaked/guessed pairing cannot grant silent access. Reset on every (re)connect.+ let approved = falselet handlers: HostHandlers | null = nulllet canvasSync: HostCanvasSync | null = null- // Connection-approval gate: a freshly-bridged client serves NO pty/fs RPCs or input frames- // until the host human approves it (so a leaked offer cannot grant silent access). Reset on- // every (re)connect and teardown.- let approved = false- // Latest snapshot pushed from the renderer, kept across (re)connects so a freshly joined- // client always gets the current state even if it connected after the last edit.- let latestCanvas: CanvasState | null = null-- function send(channel: string, ...args: unknown[]): void {- if (!win.isDestroyed()) win.webContents.send(channel, ...args)- }+ let unsubCanvas: (() => void) | null = null+ // Small main-side debounce to coalesce bursts of renderer canvas updates.+ let broadcastTimer: ReturnType<typeof setTimeout> | null = null- function teardown(): void {- if (broadcastTimer) {- clearTimeout(broadcastTimer)- broadcastTimer = null- }- approved = false- handlers?.closeAll()- handlers = null- canvasSync = null- socket?.close()- socket = null+ function pushCurrentCanvas(): void {+ const state = opts.getLatestCanvas()+ if (state) canvasSync?.setState(state)}-- // Re-broadcasting the *full* canvas on every renderer keystroke would be wasteful; the- // renderer already debounces, but a small main-side debounce coalesces bursts further.- let broadcastTimer: ReturnType<typeof setTimeout> | null = nullfunction scheduleBroadcast(): void {if (broadcastTimer) returnbroadcastTimer = setTimeout(() => {broadcastTimer = null- if (latestCanvas) canvasSync?.setState(latestCanvas)+ pushCurrentCanvas()}, 120)broadcastTimer.unref?.()}- // Renderer pushes its serialized active-project canvas; remember it and (debounced) broadcast.- // Safe to receive when not hosting — it just updates the snapshot a future client will get.- ipcMain.on(IPC.remoteHostCanvasState, (_e, state: CanvasState) => {- latestCanvas = state- scheduleBroadcast()+ const session: HostSession = {+ approve() {+ approved = true+ },+ isApproved() {+ return approved+ },+ sas() {+ return socket.sas()+ },+ peerPublicKeyB64() {+ return socket.peerPublicKeyB64()+ },+ close() {+ if (broadcastTimer) {+ clearTimeout(broadcastTimer)+ broadcastTimer = null+ }+ approved = false+ unsubCanvas?.()+ unsubCanvas = null+ handlers?.closeAll()+ handlers = null+ canvasSync = null+ socket.close()+ }+ }++ const socket: RelaySocket = connectRelay({+ url: opts.url,+ token: opts.token,+ role: 'host',+ ourKeys: opts.ourKeys,+ onReady: () => {+ // Bridge established. Require approval before serving any pty/fs RPC. Canvas state still+ // pushes (read-only mirror) so the client isn't staring at a blank screen while pending.+ approved = false+ opts.onPeerReady(session)+ pushCurrentCanvas()+ },+ onRpc: (req) => {+ // A client asking for a fresh canvas snapshot → re-push the current one (read-only).+ if (req.method === CANVAS_REQUEST_METHOD) {+ canvasSync?.broadcastCurrent()+ return+ }+ // Until approved, refuse every state-changing request (pty/fs RPCs + client mutations).+ if (!approved) {+ if (req.id) socket.respond(req.id, false, { message: 'Awaiting host approval.' })+ return+ }+ if (canvasSync?.handleRpc(req)) return+ handlers?.onRpc(req)+ },+ onFrame: (frame) => {+ if (approved) handlers?.onFrame(frame)+ },+ onClose: () => {+ approved = false+ handlers?.closeAll()+ opts.onClose()+ }})+ // Confine the client's fs.* access to the cwds of the host's currently-shared canvas nodes.+ handlers = createHostHandlers(opts.pty, socket, fsOps, () =>+ rootsFromCanvas(opts.getLatestCanvas())+ )+ canvasSync = createHostCanvasSync(socket, opts.applyMutation)+ unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())++ return session+}++// --- IPC wiring --------------------------------------------------------------++/**+ * Wire the host-mode IPC. `remote:host:start` gates on Pro, mints a pairing token, connects to+ * the relay as host, and returns the offer string. `remote:host:stop` closes the relay socket+ * (which kills the served PTYs and drops the client's access).+ */+export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void {+ initHostCanvasHub()+ let session: HostSession | null = null++ function send(channel: string, ...args: unknown[]): void {+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)+ }ipcMain.handle(IPC.remoteHostStart, async (): Promise<{ offer: string }> => {if (!isPremium()) {@@ -584,60 +695,24 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void}// Already hosting → tear the old session down before starting a fresh one.- teardown()+ session?.close()+ session = nullconst keys = await loadOrCreateKeyPair()const { pairingToken } = await mintPairingToken(entitlement)- // Connect FIRST and register as the pending host (the client joins later to trigger the- // bridge). The RPC/frame handlers are bound to this socket once it is created.- socket = connectRelay({+ session = connectHostSession({url: RELAY_URL,token: pairingToken,- role: 'host',ourKeys: keys,- onReady: () => {- // Bridge established with a client. Require explicit host approval before serving any- // pty/fs RPC — surface the SAS so the human can verify + allow. Canvas state still pushes- // (read-only mirror) so the client isn't staring at a blank screen while pending.- approved = false- send(IPC.remoteHostPeerPending, { sas: socket?.sas() ?? null })- if (latestCanvas) canvasSync?.setState(latestCanvas)- },- onRpc: (req) => {- // A client asking for a fresh canvas snapshot → re-push the current one (read-only).- if (req.method === CANVAS_REQUEST_METHOD) {- canvasSync?.broadcastCurrent()- return- }- // Until the host approves this device, refuse every state-changing request: pty/fs RPCs- // and client canvas mutations. (canvas:request above is the only allowed pre-approval op.)- if (!approved) {- if (req.id) socket?.respond(req.id, false, { message: 'Awaiting host approval.' })- return- }- // Canvas mutations route to the canvas sync (which forwards them to the host renderer,- // the single writer); everything else is a pty RPC.- if (canvasSync?.handleRpc(req)) return- handlers?.onRpc(req)- },- // Input/resize frames are dropped until approved (no keystrokes reach a host PTY).- onFrame: (frame) => {- if (approved) handlers?.onFrame(frame)- },- onClose: () => {- // The client (or relay) dropped — kill served PTYs. relay-socket may reconnect; the- // handlers stay bound to the same socket object across reconnects. Re-require approval.- approved = false- handlers?.closeAll()- }+ pty: ptyManager,+ getLatestCanvas: currentCanvas,+ subscribeCanvas,+ applyMutation: (mutation) => send(IPC.remoteHostApplyMutation, mutation),+ // Interactive host: surface the SAS so the human can verify + approve.+ onPeerReady: (s) => send(IPC.remoteHostPeerPending, { sas: s.sas() }),+ onClose: () => {}})- // Confine the client's fs.* access to the cwds of the host's currently-shared canvas nodes.- handlers = createHostHandlers(ptyManager, socket, fsOps, () => rootsFromCanvas(latestCanvas))- // The host renderer applies inbound client mutations to its React Flow (single writer).- canvasSync = createHostCanvasSync(socket, (mutation) =>- send(IPC.remoteHostApplyMutation, mutation)- )return {offer: encodeOffer({@@ -648,16 +723,22 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void}})- // Host human approved the pending device → start serving its pty/fs RPCs.+ // Host human approved the pending device → start serving its pty/fs RPCs. Only act on a+ // still-pending session: the approve/reject channels are shared with the standing phone host,+ // so an event meant for the phone must not disturb an already-approved interactive session.ipcMain.on(IPC.remoteHostApprove, () => {- if (socket) approved = true+ if (session && !session.isApproved()) session.approve()})- // Host human rejected the device → drop the connection entirely.+ // Host human rejected the pending device → drop the connection entirely (pending sessions only).ipcMain.on(IPC.remoteHostReject, () => {- teardown()+ if (session && !session.isApproved()) {+ session.close()+ session = null+ }})ipcMain.handle(IPC.remoteHostStop, () => {- teardown()+ session?.close()+ session = null})}diff --git a/src/main/remote/relay-id.test.ts b/src/main/remote/relay-id.test.tsnew file mode 100644index 000000000..42fdeffcb--- /dev/null+++ b/src/main/remote/relay-id.test.ts@@ -0,0 +1,35 @@+import { describe, it, expect } from 'vitest'+import { createHash } from 'node:crypto'+import { hostIdFromPublicKey, hostIdFromPublicKeyB64 } from './relay-id'+import { genKeyPair, publicKeyToB64 } from './e2ee'++describe('relay-id', () => {+ it('derives base64url(sha256(pub)).slice(0,22), no padding', () => {+ const pub = new Uint8Array(32).fill(7)+ const expected = createHash('sha256').update(pub).digest('base64url').slice(0, 22)+ const id = hostIdFromPublicKey(pub)+ expect(id).toBe(expected)+ expect(id).toHaveLength(22)+ // base64url alphabet only (no +, /, or = padding).+ expect(id).toMatch(/^[A-Za-z0-9_-]{22}$/)+ })++ it('is stable and matches the b64 variant against publicKeyToB64', () => {+ const keys = genKeyPair()+ const b64 = publicKeyToB64(keys.publicKey)+ expect(hostIdFromPublicKeyB64(b64)).toBe(hostIdFromPublicKey(keys.publicKey))+ })++ it('is deterministic for a known vector (guards against a hashing/encoding drift)', () => {+ // 32 zero bytes → sha256 is a fixed, well-known digest.+ const zero = new Uint8Array(32)+ const full = createHash('sha256').update(zero).digest('base64url')+ expect(hostIdFromPublicKey(zero)).toBe(full.slice(0, 22))+ })++ it('different keys yield different ids', () => {+ expect(hostIdFromPublicKey(new Uint8Array(32).fill(1))).not.toBe(+ hostIdFromPublicKey(new Uint8Array(32).fill(2))+ )+ })+})diff --git a/src/main/remote/relay-id.ts b/src/main/remote/relay-id.tsnew file mode 100644index 000000000..59f0c652f--- /dev/null+++ b/src/main/remote/relay-id.ts@@ -0,0 +1,21 @@+// Host-id derivation for the standing (phone) relay path.+//+// The relay broker matches a host and its clients by a short `hostId` derived from the host's+// NaCl box public key. This MUST match the server's `src/lib/relay-id.ts` byte-for-byte:+// hostId = base64url(sha256(rawPublicKeyBytes)).slice(0, 22) (base64url, no padding)+// where the raw bytes are the 32-byte Curve25519 public key (the same bytes `publicKeyToB64`+// standard-base64-encodes). Keep this in sync with the server — a mismatch means the phone and+// this host would register under different rooms and never bridge.++import { createHash } from 'node:crypto'++/** Derive the broker host id from the raw 32-byte NaCl box public key. */+export function hostIdFromPublicKey(pub: Uint8Array): string {+ // Node's 'base64url' digest is already unpadded RFC 4648 §5, matching the server.+ return createHash('sha256').update(pub).digest('base64url').slice(0, 22)+}++/** Derive the broker host id from a standard-base64 NaCl box public key (what publicKeyToB64 emits). */+export function hostIdFromPublicKeyB64(b64: string): string {+ return hostIdFromPublicKey(Uint8Array.from(Buffer.from(b64, 'base64')))+}diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.tsindex 2cb09885c..2b9f1ab8d 100644--- a/src/main/remote/relay-socket.ts+++ b/src/main/remote/relay-socket.ts@@ -67,6 +67,10 @@ export type RelaySocket = {// The Short Authentication String for this channel (derived from the shared key), or null// before the handshake has derived a key. Both peers compute the same value.sas(): string | null+ // The peer's NaCl box public key (base64) once known: for a client it is the pinned host key+ // passed in; for a host it is learned from the client's `e2ee_hello`. Null before then. Used by+ // the standing (phone) host to look the connecting device up in its pin-once approval list.+ peerPublicKeyB64(): string | null// Tear down: stops reconnects and closes the transport.close(): void}@@ -122,6 +126,9 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {let transport: RelayTransport | null = nulllet sharedKey: Uint8Array | null = null+ // The peer's base64 public key. Known up front for a client (the pinned host key); learned from+ // `e2ee_hello` for a host. Exposed via peerPublicKeyB64() for the standing host's pin-once check.+ let peerPubB64: string | null = opts.role === 'client' ? opts.theirPubB64 ?? null : nulllet state: State = 'connecting'let intentionallyClosed = falselet reconnectAttempt = 0@@ -288,6 +295,7 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {if (typeof control.publicKeyB64 !== 'string') {return}+ peerPubB64 = control.publicKeyB64sharedKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)sendControl({ type: 'e2ee_ready' })return@@ -487,6 +495,9 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {sas() {return sharedKey ? sasFromSharedKey(sharedKey) : null},+ peerPublicKeyB64() {+ return peerPubB64+ },close() {intentionallyClosed = trueif (reconnectTimer) {diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsnew file mode 100644index 000000000..64a0a7a1e--- /dev/null+++ b/src/main/remote/standing-host.ts@@ -0,0 +1,299 @@+// Standing (always-on) phone host — the desktop side of the iOS relay-client "reach my Mac from+// anywhere" flow.+//+// When Settings → phoneAccessEnabled is on AND the device is Pro, this keeps a HOST relay+// connection registered under the host's stable id (base64url(sha256(hostPublicKey)).slice(0,22)),+// so a previously-paired phone can join over the relay at any time and attach to the host's tmux+// sessions after approval. Unlike the interactive host (a single-use offer you hand out), the+// standing host:+// - mints its token from `POST /v1/relay/host-token` (role:'host', hostId as the broker room);+// - AUTO-REFRESHES: relay tokens are short-lived (~120s TTL) and single-use, so we re-mint + a+// reconnect before expiry, and reconnect with bounded backoff on socket close;+// - uses PIN-ONCE approval: the first connect from a given phone (its box public key) prompts+// the host human via the shared SAS dialog; on approval the pubkey is pinned, so later+// connects auto-approve silently.+//+// The heavy lifting (relay wiring, RPC/frame handlers, fs jail, canvas mirror, approval gate) is+// shared with the interactive host via `connectHostSession`. Pin/lookup logic is the pure,+// unit-tested `approved-devices-core`.++import { ipcMain, type BrowserWindow } from 'electron'+import { IPC } from '../../shared/ipc'+import type { CanvasMutation, Settings } from '../../shared/types'+import { PtyManager } from '../pty-manager'+import { getStoredEntitlement, isPremium } from '../license'+import { publicKeyToB64 } from './e2ee'+import {+ API_BASE,+ RELAY_URL,+ connectHostSession,+ loadOrCreateKeyPair,+ relayAllowed,+ type HostSession+} from './host-service'+import { currentCanvas, initHostCanvasHub, subscribeCanvas } from './host-canvas-hub'+import { isPinned, pinDevice } from './approved-devices-core'+import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'++// Re-mint the token this long before its expiry (TTL is ~120s). Floored so a bogus/short exp can't+// spin us.+const REFRESH_LEAD_MS = 30_000+const MIN_REFRESH_MS = 15_000+const DEFAULT_TTL_MS = 120_000+// Bounded backoff for reconnect after a socket close / mint failure.+const RECONNECT_DELAYS_MS = [1000, 2000, 4000, 8000, 15_000]++interface HostTokenResponse {+ pairingToken: string+ hostId: string+ exp: number+}++/** Mint a standing host token from the API, proving Pro entitlement. Returns null on any failure. */+async function mintHostToken(+ entitlement: string,+ hostPublicKeyB64: string+): Promise<HostTokenResponse | null> {+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), 8000)+ try {+ const res = await fetch(`${API_BASE}/v1/relay/host-token`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ entitlement, hostPublicKeyB64 }),+ signal: ctrl.signal+ })+ if (!res.ok) return null+ const json = (await res.json().catch(() => ({}))) as Partial<HostTokenResponse>+ if (!json.pairingToken) return null+ return { pairingToken: json.pairingToken, hostId: json.hostId ?? '', exp: json.exp ?? 0 }+ } catch {+ return null+ } finally {+ clearTimeout(timer)+ }+}++export interface StandingHost {+ /** Explicit toggle (from the Settings switch). Reconciles the connection immediately. */+ setEnabled(enabled: boolean): void+ /** Read the desired state from settings (launch / external change) and reconcile. */+ syncFromSettings(): void+ /** Tear everything down (e.g. app quit). */+ stop(): void+}++/**+ * Wire the standing phone host. Idempotent to construct once; `setEnabled` / `syncFromSettings`+ * reconcile the live connection against (enabled && Pro && relay-allowed).+ */+export function initStandingHost(+ win: BrowserWindow,+ ptyManager: PtyManager,+ getSettings: () => Settings+): StandingHost {+ initHostCanvasHub()++ // Desired state (from the toggle / settings) and live state.+ let enabled = false+ let running = false+ let session: HostSession | null = null+ // A bridged-but-not-yet-approved peer awaiting the host human's decision (unpinned device).+ let pendingPeer: HostSession | null = null+ let refreshTimer: ReturnType<typeof setTimeout> | null = null+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null+ let reconnectAttempt = 0++ function send(channel: string, ...args: unknown[]): void {+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)+ }++ function clearTimers(): void {+ if (refreshTimer) {+ clearTimeout(refreshTimer)+ refreshTimer = null+ }+ if (reconnectTimer) {+ clearTimeout(reconnectTimer)+ reconnectTimer = null+ }+ }++ function dropSession(): void {+ pendingPeer = null+ session?.close()+ session = null+ }++ function scheduleReconnect(): void {+ if (!running || reconnectTimer) return+ const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]+ reconnectAttempt += 1+ reconnectTimer = setTimeout(() => {+ reconnectTimer = null+ void connectOnce()+ }, delay)+ reconnectTimer.unref?.()+ }++ function scheduleRefresh(exp: number): void {+ if (refreshTimer) {+ clearTimeout(refreshTimer)+ refreshTimer = null+ }+ const untilExpMs = exp > 0 ? exp * 1000 - Date.now() : DEFAULT_TTL_MS+ const delay = Math.max(MIN_REFRESH_MS, untilExpMs - REFRESH_LEAD_MS)+ refreshTimer = setTimeout(() => {+ refreshTimer = null+ if (!running) return+ // Don't cut an actively-approved phone mid-session for a token refresh — defer briefly and+ // re-check. When the relay eventually drops us at TTL, onClose reconnect takes over.+ if (session?.isApproved()) {+ scheduleRefresh(0) // re-arm ~DEFAULT_TTL_MS/… → MIN_REFRESH_MS later+ return+ }+ // Idle → re-mint with a fresh token by reconnecting.+ dropSession()+ void connectOnce()+ }, delay)+ refreshTimer.unref?.()+ }++ // A phone completed the E2EE handshake. Pinned device → auto-approve; else prompt the human.+ async function onPeerReady(s: HostSession): Promise<void> {+ const pub = s.peerPublicKeyB64()+ let store+ try {+ store = await loadApprovedDevices()+ } catch {+ store = { pubkeys: [] as string[] }+ }+ // The session may have been torn down while the disk read was in flight.+ if (s !== session) return+ if (pub && isPinned(store, pub)) {+ s.approve()+ return+ }+ // Unknown device → require the host human's approval (shared SAS dialog). Pin on approve.+ pendingPeer = s+ send(IPC.remoteHostPeerPending, { sas: s.sas() })+ }++ async function connectOnce(): Promise<void> {+ if (!running || session) return+ // Re-verify Pro on every (re)connect so a lapsed entitlement tears the standing host down.+ if (!isPremium()) {+ stop()+ return+ }+ const entitlement = getStoredEntitlement()+ if (!entitlement) {+ stop()+ return+ }+ const keys = await loadOrCreateKeyPair()+ const token = await mintHostToken(entitlement, publicKeyToB64(keys.publicKey))+ if (!running) return+ if (!token) {+ scheduleReconnect()+ return+ }+ reconnectAttempt = 0+ session = connectHostSession({+ url: RELAY_URL,+ token: token.pairingToken,+ ourKeys: keys,+ pty: ptyManager,+ getLatestCanvas: currentCanvas,+ subscribeCanvas,+ applyMutation: (mutation: CanvasMutation) => send(IPC.remoteHostApplyMutation, mutation),+ onPeerReady: (s) => void onPeerReady(s),+ onClose: () => {+ // Peer/relay dropped. Fully reset this session and re-register (fresh token).+ pendingPeer = null+ session = null+ scheduleReconnect()+ }+ })+ scheduleRefresh(token.exp)+ }++ function start(): void {+ if (running) return+ running = true+ reconnectAttempt = 0+ void connectOnce()+ }++ function stop(): void {+ running = false+ clearTimers()+ dropSession()+ }++ function reconcile(): void {+ const want = enabled && isPremium() && relayAllowed()+ if (want && !running) start()+ else if (!want && running) stop()+ }++ // Host human approved / rejected the pending phone. These channels are shared with the+ // interactive host; guarding on our own `pendingPeer` keeps the two independent.+ ipcMain.on(IPC.remoteHostApprove, () => {+ const s = pendingPeer+ if (!s) return+ pendingPeer = null+ const pub = s.peerPublicKeyB64()+ if (pub) {+ void loadApprovedDevices()+ .then((store) => saveApprovedDevices(pinDevice(store, pub)))+ .catch(() => {+ // A failed pin is non-fatal: the device still works this session, it just re-prompts+ // next time. Never block approval on a disk write.+ })+ }+ s.approve()+ })+ ipcMain.on(IPC.remoteHostReject, () => {+ const s = pendingPeer+ if (!s) return+ pendingPeer = null+ // Drop this connection and re-register so a different phone can still connect later.+ dropSession()+ scheduleReconnect()+ })++ return {+ setEnabled(next) {+ enabled = next+ reconcile()+ },+ syncFromSettings() {+ enabled = !!getSettings().phoneAccessEnabled+ reconcile()+ },+ stop+ }+}++// ---------------------------------------------------------------------------------------------+// MANUAL SMOKE TEST (documented here, NOT automated — the live round-trip needs the deployed or a+// local relay + the iOS client, like test/remote/relay-e2e.test.ts's block):+//+// Prereqs: a Pro-entitled desktop build (or NODETERM_RELAY_URL + NODETERM_API_BASE pointing at a+// local relay/API), the nodeterm iOS app, and a phone already paired over the LAN.+// 1. Desktop: Settings → Phone → toggle "Remote access from your phone" ON. Main mints a+// host-token (POST /v1/relay/host-token) and registers as role:'host' under hostId =+// base64url(sha256(hostPublicKey)).slice(0,22).+// 2. Re-pair (or pair) the phone: the /pair response + QR now carry `relay {hostId,+// hostPublicKeyB64, relayEndpoint}` + `relayDeviceToken`. Confirm the phone stored them.+// 3. Put the phone on cellular (OFF the LAN). It joins the relay (POST /v1/relay/join →+// role:'client' under the same hostId) and bridges to the standing host.+// 4. FIRST connect: the desktop shows the SAS approval dialog. Approve → the phone attaches to+// a tmux session (pty.attach) and the terminal streams. The device pubkey is pinned.+// 5. Disconnect + reconnect the phone: it now auto-approves (no dialog) — pin-once verified.+// 6. Leave it idle ~2 min: the host re-mints its token + reconnects (watch it stay reachable).+// 7. Toggle the setting OFF (or deactivate Pro): the standing host tears down; the phone can+// no longer reach the Mac over the relay (LAN pairing still works).+// Throughout, the relay only forwards opaque E2EE boxes — it never sees plaintext.+// ---------------------------------------------------------------------------------------------diff --git a/src/preload/index.ts b/src/preload/index.tsindex d8d0c3dd3..a09f3003a 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -292,7 +292,8 @@ const api: NodeTerminalApi = {onApplyMutation: subscribeMutation,onPeerPending: subscribePeerPending,approve: () => ipcRenderer.send(IPC.remoteHostApprove),- reject: () => ipcRenderer.send(IPC.remoteHostReject)+ reject: () => ipcRenderer.send(IPC.remoteHostReject),+ setPhoneAccess: (enabled) => ipcRenderer.send(IPC.remoteStandingHostSet, enabled)},remoteClient: {connect: (offer) => ipcRenderer.invoke(IPC.remoteClientConnect, offer),diff --git a/src/renderer/components/settings/sections/PhoneSection.tsx b/src/renderer/components/settings/sections/PhoneSection.tsxindex e42210067..98092b22b 100644--- a/src/renderer/components/settings/sections/PhoneSection.tsx+++ b/src/renderer/components/settings/sections/PhoneSection.tsx@@ -5,8 +5,15 @@ import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { ConfirmDialog } from '../../ConfirmDialog'import { Button } from '@renderer/ui/Button'+import { Switch } from '@renderer/ui/Switch'+import { useSettings } from '@renderer/state/settings'+import { useEntitlement } from '@renderer/state/entitlement'const ROWS = {+ remote: {+ title: 'Remote access from your phone',+ keywords: ['phone', 'remote', 'anywhere', 'relay', 'encrypted', 'pro', 'access', 'cellular']+ },pair: {title: 'Pair phone',keywords: ['phone', 'pair', 'qr', 'ios', 'mobile', 'ssh', 'scan', 'nodeterm']@@ -41,6 +48,16 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele// Track whether a pairing listener is currently running so unmount can stop it.const runningRef = useRef(false)+ const isPremium = useEntitlement((s) => s.isPremium)+ const phoneAccessEnabled = useSettings((s) => s.settings.phoneAccessEnabled)+ const updateSettings = useSettings((s) => s.update)++ const togglePhoneAccess = (next: boolean): void => {+ updateSettings({ phoneAccessEnabled: next })+ // Start/stop the standing relay host immediately (main also honors the Pro gate).+ window.nodeTerminal.remoteHost.setPhoneAccess(next)+ }+const refreshDevices = useCallback(async (): Promise<void> => {try {setDevices(await window.nodeTerminal.pairing.listDevices())@@ -118,6 +135,34 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.EleisActive={isActive}searchEntries={ENTRIES}>+ <SearchableRow {...ROWS.remote}>+ <div className="space-y-3">+ <div className="flex items-start justify-between gap-4">+ <div className="min-w-0">+ <h4 className="text-[13px] font-medium text-text">Remote access from your phone</h4>+ <p className="mt-1 text-sm text-muted">+ Reach this Mac from anywhere — not just your local network — end-to-end encrypted+ over the relay. Your paired phone connects through the relay; the connection is+ verified with a code the first time.+ </p>+ </div>+ {isPremium ? (+ <Switch+ checked={phoneAccessEnabled}+ onChange={togglePhoneAccess}+ ariaLabel="Remote access from your phone"+ />+ ) : null}+ </div>+ {!isPremium ? (+ <p className="text-sm text-muted">+ Remote access from anywhere requires nodeterm Pro. Pairing over your local network is+ free — set it up below.+ </p>+ ) : null}+ </div>+ </SearchableRow>+<SearchableRow {...ROWS.pair}><div className="space-y-4"><h4 className="text-[13px] font-medium text-text">Pair phone</h4>diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 2d98b1f7b..9003ecd42 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -151,6 +151,9 @@ export const IPC = {// main pushes a client's mutation back to the host renderer to apply.remoteHostCanvasState: 'remote:host:canvas-state',remoteHostApplyMutation: 'remote:host:apply-mutation',+ // Standing (phone) relay host: renderer toggles it on/off (settings.phoneAccessEnabled). Main+ // starts/stops the always-on host connection so a paired phone can reach this Mac over the relay.+ remoteStandingHostSet: 'remote:standing-host:set',// Remote-access CLIENT (drives a host's PTYs over the relay).remoteClientConnect: 'remote:client:connect',remoteClientDisconnect: 'remote:client:disconnect',diff --git a/src/shared/types.ts b/src/shared/types.tsindex ae8e655ca..76a0a343d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -361,6 +361,9 @@ export interface Settings {/** Send anonymous usage data (version/OS) to the telemetry backend. Opt-in (default off)* so we never collect without explicit consent (GDPR). Toggle in Settings → Privacy. */telemetryEnabled: boolean+ /** Keep a standing relay host connection so a paired phone can reach this Mac from anywhere+ * (end-to-end encrypted). Pro-only; default off. Toggle in Settings → Phone. */+ phoneAccessEnabled: boolean}export const DEFAULT_SETTINGS: Settings = {@@ -390,7 +393,8 @@ export const DEFAULT_SETTINGS: Settings = {// Existing users keep whatever they've saved (their persisted disabledAgents overrides this).disabledAgents: ['codex', 'gemini'],defaultAgent: 'claude',- telemetryEnabled: false+ telemetryEnabled: false,+ phoneAccessEnabled: false}export interface SettingsApi {@@ -912,6 +916,11 @@ export interface RemoteHostApi {approve(): void/** Reject the pending client → the connection is dropped. */reject(): void+ /**+ * Start/stop the standing (phone) relay host so a paired phone can reach this Mac from anywhere.+ * Mirrors `settings.phoneAccessEnabled`; the host also honors the Pro gate internally.+ */+ setPhoneAccess(enabled: boolean): void}export interface RemoteClientApi {