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
fix(pairing): pair a Windows desktop relay-only
enes90a0be9728fb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 34df00d72..c4b875f30 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts src/main/pairing-service.windows.test.ts src/main/windows-ssh-keys.test.ts src/shared/pairing-gate.test.ts src/renderer/components/settings/sections/PhoneSection.windows.test.tsxdiff --git a/CLAUDE.md b/CLAUDE.mdindex 1ce5bfc0d..d5ec5a39f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4214,6 +4214,20 @@ shared gate would freeze it permanently rather than while nobody is looking.`POST /v1/relay/host-token` / `/v1/relay/device` must admit deviceId (no-entitlement) mints, andthe relay server may rate-limit free hosts independently — a client-side gate must NOT bereintroduced to work around a backend refusal (fix the backend policy instead).+- **A Windows desktop pairs relay-only — no SSH key, and do not "fix" that by writing one.** The+ phone's direct-SSH path is POSIX sh + tmux end to end (nodeterm-ios `HostCommands`, `TmuxBinary`,+ the typed `tmux new-session -A` attach, workspace paths with no `%APPDATA%` candidate). Windows+ OpenSSH hands out `cmd.exe`, and sessions live in the session host, which nothing on the phone+ can attach to over SSH. So on win32 `createPairingService` installs no key, the QR carries+ `"ssh":false`, the QR is gated on the RELAY instead of sshd (`shared/pairing-gate.ts`), and a+ failed relay mint pairs NOTHING (502 to the phone, `reason:'relay-failed'` to the UI) instead of+ the SSH platforms' LAN-only degrade. **A key sshd accepts makes things worse, not better**: the+ phone tries SSH before the relay, so a working key pins it to a path that cannot work, where a+ rejected one lets it fall through. Issue #758's `administrators_authorized_keys` rule is detected+ (`main/windows-ssh-keys.ts`) only to explain the missing key; revoke still sweeps that file IN+ PLACE (a temp + rename would swap its Administrators+SYSTEM ACL for the directory's, and sshd+ would then refuse every admin key in it). Relay attach on Windows needs the session host+ shipped (#575/#579) — without it `pty.attach` spawns a new plain shell, not the node's session.## Speech / dictation (desktop + server)diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 66e12230e..633e12431 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -212,6 +212,13 @@ lane unaffected.arguments and lines above cmd's limit fail explicitly. Keep stdin direct: PowerShell's textpipeline changes Unicode and line endings under Windows PowerShell 5.1.+- **The phone reaches a Windows desktop through the relay only.** Everything the iOS app sends over+ SSH is POSIX sh plus tmux, and Windows OpenSSH hands out `cmd.exe`, so Windows pairing installs no+ SSH key and requires remote access instead of an SSH server (`src/shared/pairing-gate.ts`). Do not+ "fix" this by installing the key into `administrators_authorized_keys`. The phone tries SSH before+ the relay, so a key that works locks it onto a path that cannot work. CLAUDE.md, "Remote access",+ has the details.+- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized whereit is built and matched raw where it is used is a no-op on the machine you wrote it on and asilent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` whilediff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.tsindex 69e02b665..fa8f8716c 100644--- a/src/main/pairing-core.test.ts+++ b/src/main/pairing-core.test.ts@@ -8,6 +8,7 @@ import {normalizeAuthorizedKeysLine,normalizeDeviceName,pickLanIPv4,+ pickPairingIPv4,readDevices,removeDevice,rewriteKeyComment,@@ -402,3 +403,34 @@ describe('encodePairQr over a built payload', () => {expect(Buffer.from(code, 'base64url').toString('utf-8')).toBe(payload)})})++describe('ssh:false in the pairing payload', () => {+ const input = { host: 'h', user: 'u', token: 't', pairPort: 1, name: 'n' }+ it('is appended last on a relay-only host', () => {+ expect(buildPairingPayload({ ...input, ssh: false })).toBe(+ '{"v":1,"host":"h","port":22,"user":"u","token":"t","pairPort":1,"nodeterm":true,"name":"n","ssh":false}'+ )+ })+ it('leaves every other payload byte-identical', () => {+ expect(buildPairingPayload(input)).not.toContain('ssh')+ })+})++describe('pickPairingIPv4', () => {+ const nic = (address: string, internal = false) => ({ address, family: 'IPv4', internal })+ const ifaces = {+ 'vEthernet (WSL)': [nic('172.20.48.1')],+ 'Ethernet 2': [nic('169.254.3.3')],+ 'Wi-Fi': [nic('192.168.1.42')]+ }+ it('takes the default-route address when this machine owns it', () => {+ expect(pickPairingIPv4(ifaces, '172.20.48.1')).toBe('172.20.48.1')+ })+ it('ignores a route address that is not one of ours, and skips virtual adapters', () => {+ expect(pickPairingIPv4(ifaces, '10.9.9.9')).toBe('192.168.1.42')+ expect(pickPairingIPv4(ifaces, null)).toBe('192.168.1.42')+ })+ it('falls back to the old pick when only virtual adapters exist', () => {+ expect(pickPairingIPv4({ 'vEthernet (WSL)': [nic('172.20.48.1')] }, null)).toBe('172.20.48.1')+ })+})diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.tsindex 26f5d96f4..5ba786c28 100644--- a/src/main/pairing-core.ts+++ b/src/main/pairing-core.ts@@ -34,6 +34,14 @@ export interface PairingPayloadInput {hostKey?: string/** Optional relay reachability block (standing host). Omitted from the payload when absent. */relay?: RelayPairingBlock+ /**+ * `false` = this host installs NO SSH key and cannot be driven over SSH, so the phone must reach+ * it through the relay alone. Set on Windows, where every command the phone sends over SSH+ * assumes a POSIX login shell and tmux (Windows OpenSSH hands out cmd.exe, and sessions live in+ * the session host, which the phone cannot attach to over SSH). Omitted otherwise, which keeps+ * every other platform's payload byte-identical.+ */+ ssh?: false}/**@@ -56,7 +64,8 @@ export function buildPairingPayload(input: PairingPayloadInput): string {name: input.name}const withKey = input.hostKey ? { ...base, hostKey: input.hostKey } : base- return JSON.stringify(input.relay ? { ...withKey, relay: input.relay } : withKey)+ const withRelay = input.relay ? { ...withKey, relay: input.relay } : withKey+ return JSON.stringify(input.ssh === false ? { ...withRelay, ssh: false } : withRelay)}/**@@ -144,6 +153,12 @@ export interface DeviceEntry {* its presence names a row the server MAY hold, not one it certainly does.*/relayDeviceId?: string+ /**+ * `false` = no SSH key was installed for this device (a Windows pairing: the phone reaches this+ * host through the relay only). Absent on every pairing that did install one, including all+ * pairings made before this field existed. Revoke still sweeps the key files either way.+ */+ ssh?: false}/** The device shape safe to expose to the renderer (no `token`). */@@ -217,3 +232,32 @@ export function pickLanIPv4(}return null}++/**+ * The pairing host address on Windows, where the first adapter `os.networkInterfaces()` lists is+ * routinely a virtual one the phone cannot reach (WSL / Hyper-V `vEthernet`, VirtualBox, VMware,+ * VPN clients). `routeAddress` is the source address the OS picked for a route to the internet —+ * i.e. the default-route adapter — and wins when it is a real non-internal IPv4 on this machine.+ * Otherwise the first address on an adapter whose name does not look virtual, then+ * `pickLanIPv4`'s old answer, so this never returns null where the old pick would not have.+ */+export function pickPairingIPv4(+ interfaces: Record<string, NetInterfaceAddr[] | undefined>,+ routeAddress: string | null+): string | null {+ const usable = (a: NetInterfaceAddr): boolean =>+ (a.family === 'IPv4' || a.family === 4) && !a.internal && !a.address.startsWith('169.254.')+ if (routeAddress) {+ for (const addrs of Object.values(interfaces)) {+ if (addrs?.some((a) => usable(a) && a.address === routeAddress)) return routeAddress+ }+ }+ for (const [name, addrs] of Object.entries(interfaces)) {+ if (!addrs || VIRTUAL_ADAPTER.test(name)) continue+ const hit = addrs.find(usable)+ if (hit) return hit.address+ }+ return pickLanIPv4(interfaces)+}++const VIRTUAL_ADAPTER = /vEthernet|WSL|Hyper-V|VirtualBox|VMware|Loopback|Tailscale|ZeroTier|Npcap|TAP-|Docker/idiff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex f7a40ab9b..bdaa7f8fe 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -7,11 +7,15 @@// and stop the listener. The private key never leaves the phone; the only secret in the QR is the// single-use token.//+// Windows is relay-only: no key is installed (see `directSsh` in createPairingService), the QR+// says `"ssh":false`, and a pairing whose relay mint fails pairs nothing.+//// Pure bits (payload build, key validation, LAN-IPv4 pick) live in `pairing-core.ts` so they're// unit-tested without spinning up a server.import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'http'import { connect as netConnect } from 'net'+import { createSocket as createUdpSocket } from 'dgram'import { randomBytes, randomUUID } from 'crypto'import { promises as fs } from 'fs'import { execFile } from 'child_process'@@ -25,6 +29,7 @@ import {normalizeAuthorizedKeysLine,normalizeDeviceName,pickLanIPv4,+ pickPairingIPv4,readDevices,removeDevice,rewriteKeyComment,@@ -39,6 +44,7 @@ import { renameAtomic, tempNameFor } from '../core/fs-atomic'import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'import { hostIdFromPublicKeyB64 } from './remote/relay-id'import { getDeviceId } from '../core/device-id'+import { administratorsKeysPath, detectWindowsKeyFile, type WindowsKeyFile } from './windows-ssh-keys'const execFileAsync = promisify(execFile)@@ -201,6 +207,13 @@ export interface PairingStartResult {payload: string/** True when 127.0.0.1:22 accepted a connection — sshd is (probably) running. */sshOpen: boolean+ /** Will a scan install an SSH key? `false` on Windows: the phone reaches this host through the+ * relay only, so sshd is irrelevant and the QR is gated on the relay instead (see+ * `pairingGate`). */+ sshKey: boolean+ /** Windows only: which authorized_keys file sshd would read for this account — shown to explain+ * why no key is installed (issue #758). Never used to decide anything. */+ windowsKeyFile?: WindowsKeyFile/** What the QR on screen will mint: 'ok' = carries a relay block, 'dev' = unpackaged build* (relayAllowed() off — the QR is LAN-only regardless of the toggle), 'off' = toggle off.* Known at start, so the UI can warn BESIDE the QR instead of after the pairing. */@@ -210,6 +223,12 @@ export interface PairingStartResult {/** Fired once when pairing finishes: ok=true → a key was installed, ok=false → timeout/cancel. */export type PairingDone = {ok: boolean+ /** Only on ok=false: 'timeout' (nobody finished in time) or 'relay-failed' (a relay-only+ * pairing whose device mint failed — nothing was paired, and the phone was told so). */+ reason?: 'timeout' | 'relay-failed'+ /** Only on ok=false: did ANY request reach the listener? A Windows timeout with nothing reached+ * is the signature of the firewall (or a wrong adapter address) blocking the phone. */+ reached?: boolean/** Only on ok=true: did the pairing come with a relay leg? 'off' = toggle disabled,* 'failed' = enabled but the mint failed (the SILENT LAN-only degrade that cost a* field debugging session — surface it, never swallow it), 'dev' = unpackaged build,@@ -298,6 +317,41 @@ async function computerName(): Promise<string> {return os.hostname()}+/**+ * The source address the OS would use for a route to the internet — the default-route adapter.+ * A UDP `connect` only consults the routing table; no packet is sent. Null when there is no route+ * or anything fails.+ */+function defaultRouteIPv4(): Promise<string | null> {+ return new Promise((resolve) => {+ let settled = false+ const sock = createUdpSocket('udp4')+ const done = (addr: string | null): void => {+ if (settled) return+ settled = true+ try {+ sock.close()+ } catch {+ // already closed+ }+ resolve(addr)+ }+ sock.once('error', () => done(null))+ try {+ sock.connect(53, '8.8.8.8', () => {+ try {+ done(sock.address().address)+ } catch {+ done(null)+ }+ })+ } catch {+ done(null)+ }+ setTimeout(() => done(null), 500).unref?.()+ })+}+/** Quick TCP probe of 127.0.0.1:22 to guess whether Remote Login (sshd) is on. */function probeSsh(): Promise<boolean> {return new Promise((resolve) => {@@ -360,7 +414,31 @@ function readBody(req: IncomingMessage): Promise<string> {})}-export function createPairingService(relayDeps?: PairingRelayDeps): PairingService {+/** Seams for the platform decisions, so the Windows behaviour is testable on any runner. */+export interface PairingServiceOptions {+ /** Defaults to `process.platform`. */+ platform?: NodeJS.Platform+ /** Windows key-file detection (explanation only). Defaults to the real probe. */+ detectKeyFile?: () => Promise<WindowsKeyFile>+ /** Windows' machine-wide administrators key file, swept on revoke. */+ administratorsKeysPath?: string+ /** Default-route source address, for the Windows LAN-IP pick. */+ defaultRouteAddress?: () => Promise<string | null>+ /** Defaults to PAIR_TIMEOUT_MS. */+ timeoutMs?: number+}++export function createPairingService(+ relayDeps?: PairingRelayDeps,+ options: PairingServiceOptions = {}+): PairingService {+ const platform = options.platform ?? process.platform+ // Windows: no SSH key, relay only. Everything the phone sends over SSH is POSIX sh + tmux+ // (nodeterm-ios HostCommands / TmuxBinary / TerminalTransport), Windows OpenSSH hands out+ // cmd.exe, and sessions live in the session host — so a key sshd accepts only pins the phone to+ // a path that cannot work, where a rejected one lets it fall through to the relay.+ const directSsh = platform !== 'win32'+ const adminKeysPath = options.administratorsKeysPath ?? administratorsKeysPath()let server: Server | null = nulllet timer: ReturnType<typeof setTimeout> | null = nulllet onDoneCb: ((result: PairingDone) => void) | null = null@@ -451,6 +529,31 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServiawait fs.chmod(AUTH_KEYS_PATH, 0o600).catch(() => {})}+ /**+ * Windows: also remove the device's line from `%ProgramData%\ssh\administrators_authorized_keys`.+ * nodeterm never writes that file, but #758's manual workaround copies a paired key into it, and+ * a revoke that only rewrote the profile file would report the device removed while the copy+ * sshd actually reads stays authorized — for every administrator account on the machine.+ *+ * Rewritten IN PLACE, deliberately not temp + rename: the file's ACL must stay Administrators ++ * SYSTEM only, and a temp file inherits the directory's ACL instead, which sshd then refuses —+ * breaking every other administrator key in it. An unreadable file (the normal case: only an+ * elevated process may read it) is skipped; a line that IS there but cannot be removed throws,+ * so the revoke reports `local: false` rather than a removal that did not happen.+ */+ async function removeAdministratorsKeysForDevice(deviceId: string): Promise<void> {+ if (platform !== 'win32') return+ let content: string+ try {+ content = await fs.readFile(adminKeysPath, 'utf8')+ } catch {+ return+ }+ const next = filterAuthorizedKeys(content, deviceId)+ if (next === content) return+ await fs.writeFile(adminKeysPath, next)+ }+const cleanup = (): void => {if (timer) {clearTimeout(timer)@@ -476,13 +579,20 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServicleanup()onDoneCb = onDone- const host = pickLanIPv4(os.networkInterfaces())+ const host = directSsh+ ? pickLanIPv4(os.networkInterfaces())+ : pickPairingIPv4(+ os.networkInterfaces(),+ await (options.defaultRouteAddress ?? defaultRouteIPv4)().catch(() => null)+ )if (!host) {onDoneCb = nullthrow new Error("Couldn't detect a LAN IP address — connect to Wi-Fi and try again.")}const token = randomBytes(24).toString('base64url')const user = os.userInfo().username+ // Set by the first request of any kind — see PairingDone.reached.+ let reached = falseconst srv = createServer((req: IncomingMessage, res: ServerResponse) => {void handleRequest(req, res)@@ -500,7 +610,13 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServiconst addr = srv.address()const pairPort = typeof addr === 'object' && addr ? addr.port : 0- const [name, sshOpen] = await Promise.all([computerName(), probeSsh()])+ const [name, sshOpen, windowsKeyFile] = await Promise.all([+ computerName(),+ probeSsh(),+ directSsh+ ? Promise.resolve(undefined)+ : (options.detectKeyFile ?? detectWindowsKeyFile)().catch((): WindowsKeyFile => 'unknown')+ ])// 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)@@ -527,11 +643,15 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServipairPort,name,hostKey,- relay: relayCtx?.block+ relay: relayCtx?.block,+ ...(directSsh ? {} : { ssh: false as const })})- // Give up after 2 minutes with a timeout result.- timer = setTimeout(() => finish({ ok: false }), PAIR_TIMEOUT_MS)+ // Give up after PAIR_TIMEOUT_MS with a timeout result.+ timer = setTimeout(+ () => finish({ ok: false, reason: 'timeout', reached }),+ options.timeoutMs ?? PAIR_TIMEOUT_MS+ )timer.unref?.()// The phone reads /pair responses off a raw TCP socket (ATS blocks URLSession for bare-IP@@ -545,6 +665,7 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi}async function handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {+ reached = trueif (req.method !== 'POST' || req.url !== '/pair') {send(res, 404)return@@ -624,24 +745,9 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi// unchanged, and the mint still reads this same value.const phoneDeviceId =typeof body.deviceId === 'string' && body.deviceId.trim() ? body.deviceId.trim() : deviceId- // One unit, and queued behind any in-flight revoke: a pairing that interleaves with one- // would either append onto the inode the revoke is about to rename over, or lose its- // agent.json entry to the revoke's stale read.- await serialize(async () => {- await appendAuthorizedKey(rewriteKeyComment(publicKey, deviceId))- await persistDevice({- id: deviceId,- name,- token: agentToken,- pairedAt: Date.now(),- lastSeenAt: 0,- relayDeviceId: phoneDeviceId- })- })- // 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 mint = async (): Promise<void> => {+ if (!relayCtx) returnconst minted = await mintRelayDevice(relayDeps!.apiBase, {entitlement: relayCtx.entitlement,deviceId: phoneDeviceId,@@ -657,6 +763,60 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi}}}+ if (directSsh) {+ // One unit, and queued behind any in-flight revoke: a pairing that interleaves with one+ // would either append onto the inode the revoke is about to rename over, or lose its+ // agent.json entry to the revoke's stale read.+ await serialize(async () => {+ await appendAuthorizedKey(rewriteKeyComment(publicKey, deviceId))+ await persistDevice({+ id: deviceId,+ name,+ token: agentToken,+ pairedAt: Date.now(),+ lastSeenAt: 0,+ relayDeviceId: phoneDeviceId+ })+ })+ // Provision relay access for the phone when enabled. Any failure ⇒ LAN-only: we never+ // fail the pairing over a relay hiccup (the phone still got its SSH key installed).+ await mint()+ } else {+ // Relay-only (Windows). The relay IS the connection, so there is nothing to fall back+ // to: no relay leg ⇒ nothing is paired, and both ends are told so. Minted BEFORE the+ // device is recorded, so a failed mint leaves no half-paired entry behind. The body is+ // plain text because the phone shows a non-2xx body verbatim ("The computer rejected+ // pairing: …").+ if (!relayCtx) {+ send(+ res,+ 409,+ 'remote access is off on the computer. On Windows the phone connects only through remote access — turn it on in nodeterm and scan the new code.'+ )+ return+ }+ await mint()+ if (!relayFields.relayDeviceToken) {+ send(+ res,+ 502,+ "the computer couldn't set up remote access, and on Windows that is how the phone connects. Check its internet connection and scan a new code."+ )+ finish({ ok: false, reason: 'relay-failed', reached: true })+ return+ }+ await serialize(() =>+ persistDevice({+ id: deviceId,+ name,+ token: agentToken,+ pairedAt: Date.now(),+ lastSeenAt: 0,+ relayDeviceId: phoneDeviceId,+ ssh: false+ })+ )+ }// Build the response exactly as before; wrap it in the box only when the request was// encrypted (same shared key), so the relay device token never crosses the LAN in cleartext.const responseObj = { ok: true, deviceId, agentToken, ...relayFields }@@ -693,6 +853,8 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServireturn {payload,sshOpen,+ sshKey: directSsh,+ ...(windowsKeyFile ? { windowsKeyFile } : {}),relayPlan: relayCtx ? 'ok' : relayDeps && !relayDeps.relayAllowed() ? 'dev' : 'off'}}@@ -725,6 +887,7 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServiconst found = !!entrytry {await removeAuthorizedKeysForDevice(id)+ await removeAdministratorsKeysForDevice(id)const obj = await readAgentJson()const devices = removeDevice(readDevices(obj), id)await writeAgentJson({ ...obj, devices })diff --git a/src/main/pairing-service.windows.test.ts b/src/main/pairing-service.windows.test.tsnew file mode 100644index 000000000..e9e321e12--- /dev/null+++ b/src/main/pairing-service.windows.test.ts@@ -0,0 +1,278 @@+// Windows pairing is relay-only (issue #758 / the Windows phone breakpoint map): no SSH key, a+// `"ssh":false` QR, a failed relay mint pairs nothing, and revoke also sweeps the machine-wide+// administrators key file. The platform is INJECTED, so every case here runs on the Linux job and+// on windows-latest alike.+import { describe, it, expect, afterEach, afterAll, vi } from 'vitest'+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { randomBytes } from 'crypto'+import { request as httpRequest } from 'http'+import path from 'path'++const TEMP_HOME_MARKER = 'nt-pairing-win-'++// Same reason as pairing-service.test.ts: the key paths are frozen from os.homedir() at module load.+vi.mock('os', async (importOriginal) => {+ const actual = await importOriginal<typeof import('os')>()+ const { mkdtempSync } = await import('node:fs')+ const { join } = await import('node:path')+ const home = mkdtempSync(join(actual.tmpdir(), 'nt-pairing-win-'))+ const homedir = (): string => home+ const networkInterfaces = (): NodeJS.Dict<import('os').NetworkInterfaceInfo[]> => ({+ 'vEthernet (WSL)': [+ {+ address: '172.20.48.1',+ netmask: '255.255.240.0',+ family: 'IPv4',+ mac: '00:15:5d:00:00:01',+ internal: false,+ cidr: '172.20.48.1/20'+ }+ ],+ 'Wi-Fi': [+ {+ address: '192.168.1.42',+ netmask: '255.255.255.0',+ family: 'IPv4',+ mac: '02:00:00:00:00:01',+ internal: false,+ cidr: '192.168.1.42/24'+ }+ ]+ })+ const base = (actual as unknown as { default?: typeof actual }).default ?? actual+ return { ...actual, homedir, networkInterfaces, default: { ...base, homedir, networkInterfaces } }+})+vi.mock('../core/device-id', () => ({ getDeviceId: () => 'test-host-device-id' }))++import os from 'os'+import { createPairingService, type PairingDone, type PairingRelayDeps } from './pairing-service'+import { rewriteKeyComment, type DeviceEntry } from './pairing-core'+import { genKeyPair } from './remote/e2ee'+import type { Settings } from '../shared/types'++const HOME = os.homedir()+if (!path.basename(HOME).startsWith(TEMP_HOME_MARKER)) {+ throw new Error(`refusing to run: homedir() is "${HOME}", the os mock is not in effect`)+}+const AGENT_JSON = path.join(HOME, '.nodeterm', 'agent.json')+const AUTH_KEYS = path.join(HOME, '.ssh', 'authorized_keys')+const ADMIN_KEYS = path.join(HOME, 'ProgramData-ssh', 'administrators_authorized_keys')++const hostKeys = genKeyPair()+const relayDeps = (): PairingRelayDeps => ({+ getSettings: () => ({ phoneAccessEnabled: true }) as unknown as Settings,+ getEntitlement: () => null,+ loadHostKeyPair: async () => hostKeys,+ relayEndpoint: 'wss://relay.example/ws',+ apiBase: 'https://api.example',+ relayAllowed: () => true+})+const win = {+ platform: 'win32' as const,+ detectKeyFile: async () => 'administrators' as const,+ administratorsKeysPath: ADMIN_KEYS,+ defaultRouteAddress: async () => null+}++function freshEd25519Line(): string {+ const name = Buffer.from('ssh-ed25519', 'ascii')+ const len = (n: number): Buffer => {+ const b = Buffer.alloc(4)+ b.writeUInt32BE(n, 0)+ return b+ }+ const blob = Buffer.concat([len(name.length), name, len(32), randomBytes(32)])+ return `ssh-ed25519 ${blob.toString('base64')} phone@ios`+}++function post(port: number, body: unknown): Promise<{ status: number; text: string }> {+ return new Promise((resolve, reject) => {+ const payload = JSON.stringify(body)+ const req = httpRequest(+ {+ host: '127.0.0.1',+ port,+ path: '/pair',+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) }+ },+ (res) => {+ let text = ''+ res.setEncoding('utf8')+ res.on('data', (c) => (text += c))+ res.on('end', () => resolve({ status: res.statusCode ?? 0, text }))+ }+ )+ req.on('error', reject)+ req.end(payload)+ })+}++const devices = (): DeviceEntry[] =>+ existsSync(AGENT_JSON)+ ? ((JSON.parse(readFileSync(AGENT_JSON, 'utf8')).devices as DeviceEntry[] | undefined) ?? [])+ : []++const reset = (): void => {+ for (const d of ['.nodeterm', '.ssh', 'ProgramData-ssh']) rmSync(path.join(HOME, d), { recursive: true, force: true })+}++afterEach(() => {+ vi.restoreAllMocks()+ reset()+})+afterAll(() => rmSync(HOME, { recursive: true, force: true }))++describe('Windows pairing: relay-only', () => {+ it('says so in the start result and the QR, and prefers the real adapter over vEthernet', async () => {+ reset()+ const service = createPairingService(relayDeps(), win)+ try {+ const started = await service.start(() => {})+ expect(started.sshKey).toBe(false)+ expect(started.windowsKeyFile).toBe('administrators')+ expect(started.relayPlan).toBe('ok')+ const payload = JSON.parse(started.payload) as Record<string, unknown>+ expect(payload.ssh).toBe(false)+ expect(payload.host).toBe('192.168.1.42')+ } finally {+ service.stop()+ }+ })++ it('takes the default-route address when it belongs to this machine', async () => {+ const service = createPairingService(relayDeps(), { ...win, defaultRouteAddress: async () => '172.20.48.1' })+ try {+ const payload = JSON.parse((await service.start(() => {})).payload) as { host: string }+ expect(payload.host).toBe('172.20.48.1')+ } finally {+ service.stop()+ }+ })++ it('installs NO key and records the device as ssh:false when the relay mint succeeds', async () => {+ reset()+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ ok: true,+ json: async () => ({ deviceToken: 'device-token', hostId: 'host-id', exp: 0 })+ } as unknown as Response)+ const done: PairingDone[] = []+ const service = createPairingService(relayDeps(), win)+ try {+ const { payload } = await service.start((r) => done.push(r))+ const { token, pairPort } = JSON.parse(payload) as { token: string; pairPort: number }+ const res = await post(pairPort, { token, publicKey: freshEd25519Line(), deviceId: 'phone-w' })+ expect(res.status).toBe(200)+ const body = JSON.parse(res.text) as { ok: boolean; deviceId: string; relayDeviceToken: string }+ expect(body.relayDeviceToken).toBe('device-token')+ expect(existsSync(AUTH_KEYS)).toBe(false)+ expect(devices()).toHaveLength(1)+ expect(devices()[0]).toMatchObject({ id: body.deviceId, relayDeviceId: 'phone-w', ssh: false })+ expect(done).toEqual([{ ok: true, relay: 'ok' }])+ } finally {+ service.stop()+ }+ })++ it('pairs NOTHING when the relay mint fails, and tells both ends', async () => {+ reset()+ vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false, json: async () => ({}) } as unknown as Response)+ const done: PairingDone[] = []+ const service = createPairingService(relayDeps(), win)+ try {+ const { payload } = await service.start((r) => done.push(r))+ const { token, pairPort } = JSON.parse(payload) as { token: string; pairPort: number }+ const res = await post(pairPort, { token, publicKey: freshEd25519Line() })+ expect(res.status).toBe(502)+ expect(res.text).toMatch(/remote access/)+ expect(existsSync(AUTH_KEYS)).toBe(false)+ expect(devices()).toEqual([])+ expect(done).toEqual([{ ok: false, reason: 'relay-failed', reached: true }])+ } finally {+ service.stop()+ }+ })++ it('refuses a scan while remote access is off, without consuming the pairing', async () => {+ reset()+ const done: PairingDone[] = []+ const service = createPairingService(undefined, win)+ try {+ const started = await service.start((r) => done.push(r))+ expect(started.relayPlan).toBe('off')+ const { token, pairPort } = JSON.parse(started.payload) as { token: string; pairPort: number }+ const res = await post(pairPort, { token, publicKey: freshEd25519Line() })+ expect(res.status).toBe(409)+ expect(existsSync(AUTH_KEYS)).toBe(false)+ expect(devices()).toEqual([])+ expect(done).toEqual([])+ } finally {+ service.stop()+ }+ })++ it('reports whether anything reached the listener when it times out', async () => {+ const quiet: PairingDone[] = []+ const service = createPairingService(relayDeps(), { ...win, timeoutMs: 50 })+ await service.start((r) => quiet.push(r))+ await new Promise((r) => setTimeout(r, 150))+ expect(quiet).toEqual([{ ok: false, reason: 'timeout', reached: false }])++ const knocked: PairingDone[] = []+ const again = createPairingService(relayDeps(), { ...win, timeoutMs: 300 })+ const { pairPort } = JSON.parse((await again.start((r) => knocked.push(r))).payload) as { pairPort: number }+ await post(pairPort, { token: 'wrong', publicKey: freshEd25519Line() })+ await new Promise((r) => setTimeout(r, 450))+ expect(knocked).toEqual([{ ok: false, reason: 'timeout', reached: true }])+ })+})++describe('Windows revoke sweeps the administrators key file', () => {+ const KEY_A = rewriteKeyComment('ssh-ed25519 AAAAblobAAAA phone-a@ios', 'dev-a')+ const OTHER = 'ssh-ed25519 AAAAadminlaptop admin@laptop'+ const seed = (): void => {+ reset()+ mkdirSync(path.join(HOME, '.nodeterm'), { recursive: true })+ mkdirSync(path.dirname(ADMIN_KEYS), { recursive: true })+ writeFileSync(+ AGENT_JSON,+ JSON.stringify({ devices: [{ id: 'dev-a', name: 'A', token: 't', pairedAt: 1, lastSeenAt: 0 }] })+ )+ writeFileSync(ADMIN_KEYS, `${OTHER}\n${KEY_A}\n`)+ }++ it('removes the device line (the #758 manual-workaround copy) and keeps everyone else', async () => {+ seed()+ const result = await createPairingService(undefined, win).revokeDevice('dev-a')+ expect(result.local).toBe(true)+ expect(readFileSync(ADMIN_KEYS, 'utf8')).toBe(`${OTHER}\n`)+ expect(devices()).toEqual([])+ })++ it('never touches that file off Windows', async () => {+ seed()+ await createPairingService(undefined, { ...win, platform: 'linux' }).revokeDevice('dev-a')+ expect(readFileSync(ADMIN_KEYS, 'utf8')).toBe(`${OTHER}\n${KEY_A}\n`)+ })++ it('does not fail a revoke over a file it cannot read — the normal, unelevated case', async () => {+ seed()+ rmSync(ADMIN_KEYS)+ const result = await createPairingService(undefined, win).revokeDevice('dev-a')+ expect(result.local).toBe(true)+ })++ it('reports local:false when the line is there but cannot be removed', async () => {+ seed()+ const realWrite = (await import('fs')).promises.writeFile+ vi.spyOn((await import('fs')).promises, 'writeFile').mockImplementation((async (p: any, ...rest: any[]) => {+ if (String(p) === ADMIN_KEYS) throw Object.assign(new Error('EPERM'), { code: 'EPERM' })+ return (realWrite as any)(p, ...rest)+ }) as any)+ const result = await createPairingService(undefined, win).revokeDevice('dev-a')+ expect(result.local).toBe(false)+ expect(readFileSync(ADMIN_KEYS, 'utf8')).toContain('nodeterm-ios-dev-a')+ // Reported, not half-done: the device stays listed so the owner can retry.+ expect(devices().map((d) => d.id)).toEqual(['dev-a'])+ })+})diff --git a/src/main/windows-ssh-keys.test.ts b/src/main/windows-ssh-keys.test.tsnew file mode 100644index 000000000..1c409678a--- /dev/null+++ b/src/main/windows-ssh-keys.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect } from 'vitest'+import { execFileSync } from 'child_process'+import {+ adminKeysBlockActive,+ administratorsKeysPath,+ isAdministratorsMember,+ windowsKeyFileFor+} from './windows-ssh-keys'++// The tail of Microsoft's shipped sshd_config (PowerShell/openssh-portable+// contrib/win32/openssh/sshd_config), as measured on OpenSSH_for_Windows_9.5p2 in #758.+const STOCK = `# This is the sshd server system-wide configuration file.+AuthorizedKeysFile .ssh/authorized_keys+PasswordAuthentication yes+Subsystem sftp sftp-server.exe++Match Group administrators+ AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys+`++const ADMIN_ROW = '"BUILTIN\\Administrators","Alias","S-1-5-32-544","Group used for deny only"'+const USERS_ROW = '"BUILTIN\\Users","Alias","S-1-5-32-545","Mandatory group, Enabled by default, Enabled group"'++describe('adminKeysBlockActive', () => {+ it('finds the shipped block', () => {+ expect(adminKeysBlockActive(STOCK)).toBe(true)+ expect(adminKeysBlockActive(STOCK.replace(/\n/g, '\r\n'))).toBe(true)+ })++ it('ignores the block once an administrator comments it out', () => {+ expect(+ adminKeysBlockActive(STOCK.replace('Match Group', '#Match Group').replace(' Authorized', '# Authorized'))+ ).toBe(false)+ })++ it('does not credit a global AuthorizedKeysFile, nor another group, nor a block that points elsewhere', () => {+ expect(adminKeysBlockActive('AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys\n')).toBe(false)+ expect(adminKeysBlockActive('Match Group sshusers\n AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys\n')).toBe(false)+ expect(adminKeysBlockActive('Match Group administrators\n AuthorizedKeysFile .ssh/authorized_keys\n')).toBe(false)+ })++ it('ends a Match block at the next Match', () => {+ expect(+ adminKeysBlockActive('Match Group administrators\n PasswordAuthentication no\nMatch User bob\n AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys\n')+ ).toBe(false)+ })++ it('accepts sshd’s case-insensitive keywords, a quoted group list and a domain-qualified name', () => {+ expect(adminKeysBlockActive('match group "sshusers,Administrators"\n authorizedkeysfile __PROGRAMDATA__/ssh/administrators_authorized_keys')).toBe(true)+ expect(adminKeysBlockActive('Match User me Group BUILTIN\\Administrators\n AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys')).toBe(true)+ })+})++describe('isAdministratorsMember', () => {+ it('matches the SID, so a localized group name changes nothing', () => {+ expect(isAdministratorsMember(`${USERS_ROW}\r\n${ADMIN_ROW.replace('Administrators', 'Administratoren')}\r\n`)).toBe(true)+ expect(isAdministratorsMember(`${USERS_ROW}\r\n`)).toBe(false)+ })+})++describe('windowsKeyFileFor', () => {+ it('is the administrators file only for a member under an active block', () => {+ expect(windowsKeyFileFor({ sshdConfig: STOCK, whoamiGroupsCsv: ADMIN_ROW })).toBe('administrators')+ expect(windowsKeyFileFor({ sshdConfig: STOCK, whoamiGroupsCsv: USERS_ROW })).toBe('profile')+ expect(windowsKeyFileFor({ sshdConfig: 'PasswordAuthentication yes', whoamiGroupsCsv: ADMIN_ROW })).toBe('profile')+ })++ it('says unknown when either input could not be read, rather than guessing', () => {+ expect(windowsKeyFileFor({ sshdConfig: null, whoamiGroupsCsv: ADMIN_ROW })).toBe('unknown')+ expect(windowsKeyFileFor({ sshdConfig: STOCK, whoamiGroupsCsv: null })).toBe('unknown')+ })+})++describe('administratorsKeysPath', () => {+ it('resolves with Windows path rules on any runner', () => {+ expect(administratorsKeysPath({ ProgramData: 'D:\\PD' })).toBe('D:\\PD\\ssh\\administrators_authorized_keys')+ expect(administratorsKeysPath({})).toBe('C:\\ProgramData\\ssh\\administrators_authorized_keys')+ })+})++// Windows-only because it runs the real `whoami`: it proves the CSV shape the parser assumes. The+// GitHub windows-latest runner account is a local administrator.+describe('real whoami', () => {+ it.skipIf(process.platform !== 'win32')('prints the Administrators SID the way the parser reads it', () => {+ const csv = execFileSync('whoami', ['/groups', '/fo', 'csv', '/nh'], { encoding: 'utf8' })+ expect(isAdministratorsMember(csv)).toBe(true)+ })+})diff --git a/src/main/windows-ssh-keys.ts b/src/main/windows-ssh-keys.tsnew file mode 100644index 000000000..d44c82029--- /dev/null+++ b/src/main/windows-ssh-keys.ts@@ -0,0 +1,92 @@+// Which authorized_keys file Windows OpenSSH reads for THIS account — detected only to EXPLAIN+// why phone pairing installs no SSH key on Windows (issue #758). Nothing here writes a key.+//+// Microsoft's shipped sshd_config ends with+//+// Match Group administrators+// AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys+//+// so for an account in the local Administrators group sshd ignores `~/.ssh/authorized_keys` and+// reads a MACHINE-WIDE file that only an elevated process can write, and whose ACL must be+// Administrators + SYSTEM only (measured by the #758 reporter on OpenSSH_for_Windows_9.5p2). The+// decision is the server's EFFECTIVE configuration for the TARGET account — an administrator can+// delete that block — not whether nodeterm happens to run elevated, so both inputs are read.+//+// Every read fails soft to `unknown`: this feeds a sentence in the UI, never a decision.++import { execFile } from 'child_process'+import { promises as fs } from 'fs'+import path from 'path'++export type WindowsKeyFile = 'administrators' | 'profile' | 'unknown'++/** The well-known SID of BUILTIN\Administrators — matched by SID so a localized group name+ * ("Administratoren", "Administrateurs") changes nothing. */+const ADMINISTRATORS_SID = 'S-1-5-32-544'++/**+ * Does an active `Match Group …administrators…` block point `AuthorizedKeysFile` at the+ * administrators file? Comments and blank lines are ignored; a `Match` block ends at the next+ * `Match`. Keywords are case-insensitive, as sshd's are.+ */+export function adminKeysBlockActive(sshdConfig: string): boolean {+ let inAdminMatch = false+ for (const raw of sshdConfig.split(/\r?\n/)) {+ const line = raw.replace(/#.*/, '').trim()+ if (!line) continue+ const [keyword, ...rest] = line.split(/\s+/)+ const value = rest.join(' ')+ if (/^match$/i.test(keyword)) {+ // `Match Group administrators` / `Match Group "administrators,other"` / `Match User x Group y`+ const criteria = value.split(/\s+/)+ inAdminMatch = false+ for (let i = 0; i < criteria.length - 1; i++) {+ if (!/^group$/i.test(criteria[i])) continue+ const groups = criteria[i + 1].replace(/"/g, '').split(',')+ if (groups.some((g) => /(^|\\)administrators$/i.test(g.trim()))) inAdminMatch = true+ }+ continue+ }+ if (inAdminMatch && /^authorizedkeysfile$/i.test(keyword)) {+ if (/administrators_authorized_keys/i.test(value)) return true+ }+ }+ return false+}++/** Is `S-1-5-32-544` among the groups `whoami /groups /fo csv /nh` printed? A filtered UAC token+ * lists it as "Group used for deny only" — still a member, which is what sshd matches on. */+export function isAdministratorsMember(whoamiGroupsCsv: string): boolean {+ return whoamiGroupsCsv.split(/\r?\n/).some((row) => row.includes(`"${ADMINISTRATORS_SID}"`))+}++export function windowsKeyFileFor(input: {+ sshdConfig: string | null+ whoamiGroupsCsv: string | null+}): WindowsKeyFile {+ if (input.sshdConfig === null || input.whoamiGroupsCsv === null) return 'unknown'+ if (!adminKeysBlockActive(input.sshdConfig)) return 'profile'+ return isAdministratorsMember(input.whoamiGroupsCsv) ? 'administrators' : 'profile'+}++/** `%ProgramData%\ssh`, resolved with Windows path rules whatever OS runs this. */+export function programDataSshDir(env: NodeJS.ProcessEnv = process.env): string {+ return path.win32.join(env.ProgramData || env.PROGRAMDATA || 'C:\\ProgramData', 'ssh')+}++export function administratorsKeysPath(env: NodeJS.ProcessEnv = process.env): string {+ return path.win32.join(programDataSshDir(env), 'administrators_authorized_keys')+}++/** Read both inputs on a real Windows machine. `whoami` runs with a fixed argv, no shell. */+export async function detectWindowsKeyFile(env: NodeJS.ProcessEnv = process.env): Promise<WindowsKeyFile> {+ const sshdConfig = await fs+ .readFile(path.win32.join(programDataSshDir(env), 'sshd_config'), 'utf8')+ .catch(() => null)+ const whoamiGroupsCsv = await new Promise<string | null>((resolve) => {+ execFile('whoami', ['/groups', '/fo', 'csv', '/nh'], { timeout: 3000, windowsHide: true }, (err, stdout) =>+ resolve(err ? null : String(stdout))+ )+ })+ return windowsKeyFileFor({ sshdConfig, whoamiGroupsCsv })+}diff --git a/src/renderer/components/PhonePairPopover.tsx b/src/renderer/components/PhonePairPopover.tsxindex b02b8a53e..d5613f2fc 100644--- a/src/renderer/components/PhonePairPopover.tsx+++ b/src/renderer/components/PhonePairPopover.tsx@@ -5,6 +5,12 @@ import { useSettings } from '@renderer/state/settings'import { usePhonePairing } from './settings/usePhonePairing'import { IOS_APP_STORE_URL } from '@renderer/lib/links'import { hostOsFromNavigator, sshServerCopy } from '@shared/ssh-server'+import {+ pairingEndedMessage,+ pairingGate,+ relayGateMessage,+ relayOnlyExplanation+} from '@shared/pairing-gate'import { thisMachine } from '@renderer/lib/machineName'/** Same table the Phone settings section prints from — see @shared/ssh-server. */@@ -26,7 +32,21 @@ export function PhonePairPopover({onClose: () => voidonOpenSettings: () => void}): React.JSX.Element {- const { phase, qr, sshOpen, sshHealed, relayResult, relayPlan, error, busy, start } = usePhonePairing()+ const {+ phase,+ qr,+ sshOpen,+ sshHealed,+ sshKey,+ windowsKeyFile,+ ended,+ relayResult,+ relayPlan,+ error,+ busy,+ start+ } = usePhonePairing()+ const gate = pairingGate({ sshKey, sshOpen, relayPlan })const phoneAccessEnabled = useSettings((s) => s.settings.phoneAccessEnabled)const updateSettings = useSettings((s) => s.update)@@ -68,7 +88,11 @@ export function PhonePairPopover({<div className="phone-pair__title">Pair your phone</div>{phase === 'waiting' && qr ? (- !sshOpen ? (+ gate === 'relay-off' || gate === 'relay-dev' ? (+ <div className="phone-pair__warn">+ {relayGateMessage(gate, `Reach ${thisMachine()} from anywhere`)}+ </div>+ ) : gate === 'ssh-off' ? (// No QR while Remote Login is off — pairing against an unreachable sshd installs a// key the phone can never use. The live probe flips sshOpen and the QR appears.<div className="phone-pair__warn">@@ -94,7 +118,9 @@ export function PhonePairPopover({<><img src={qr} width={208} height={208} alt="Pairing QR code" className="phone-pair__qr" /><div className="phone-pair__hint">Scan with the nodeterm iOS app · waiting (10 min)</div>- {relayPlan === 'dev' ? (+ {!sshKey ? (+ <div className="phone-pair__hint">{relayOnlyExplanation(windowsKeyFile)}</div>+ ) : relayPlan === 'dev' ? (<div className="phone-pair__warn">Dev build: the relay is off regardless of the toggle, so this code pairsLAN-only. Run a packaged build — or set NODETERM_RELAY_URL — for remote access.@@ -112,7 +138,11 @@ export function PhonePairPopover({)) : phase === 'paired' ? (<>- <div className="phone-pair__ok">✓ Paired — your phone can now connect.</div>+ <div className="phone-pair__ok">+ {sshKey+ ? '✓ Paired — your phone can now connect.'+ : `✓ Paired — your phone connects to ${thisMachine()} through remote access.`}+ </div>{relayResult === 'ok' ? (<div className="phone-pair__ok">Remote access is set up — reachable from anywhere.</div>) : relayResult === 'failed' ? (@@ -130,7 +160,11 @@ export function PhonePairPopover({</>) : phase === 'timeout' ? (<>- <div className="phone-pair__hint">Pairing timed out.</div>+ <div className={ended?.reason === 'relay-failed' ? 'phone-pair__warn' : 'phone-pair__hint'}>+ {ended?.reason === 'relay-failed' || (!sshKey && ended?.reached === false)+ ? pairingEndedMessage({ ...ended, windows: !sshKey })+ : 'Pairing timed out.'}+ </div><button className="phone-pair__btn" disabled={busy} onClick={() => void start()}>Show a new code</button>diff --git a/src/renderer/components/settings/sections/PhoneSection.tsx b/src/renderer/components/settings/sections/PhoneSection.tsxindex 10e5616c2..d7eda3987 100644--- a/src/renderer/components/settings/sections/PhoneSection.tsx+++ b/src/renderer/components/settings/sections/PhoneSection.tsx@@ -9,6 +9,12 @@ import { useSettings } from '@renderer/state/settings'import { usePhonePairing } from '../usePhonePairing'import { IOS_APP_STORE_URL } from '@renderer/lib/links'import { hostOsFromNavigator, sshServerCopy } from '@shared/ssh-server'+import {+ pairingEndedMessage,+ pairingGate,+ relayGateMessage,+ relayOnlyExplanation+} from '@shared/pairing-gate'import { thisMachine } from '../../../lib/machineName'const ROWS = {@@ -70,6 +76,9 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.ElesetQrForm,sshOpen,sshHealed,+ sshKey,+ windowsKeyFile,+ ended,relayResult,relayPlan,error,@@ -83,6 +92,7 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Elevoid refreshDevices()})+ const gate = pairingGate({ sshKey, sshOpen, relayPlan })const togglePhoneAccess = (next: boolean): void => {updateSettings({ phoneAccessEnabled: next })@@ -204,9 +214,11 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele{phase === 'idle' || phase === 'timeout' ? (<div className="space-y-3">{phase === 'timeout' ? (- <p className="text-sm text-muted">- Pairing timed out — that code no longer works. Start again and scan the fresh- one within ten minutes.+ <p+ className={ended?.reason === 'relay-failed' ? 'text-sm' : 'text-sm text-muted'}+ style={ended?.reason === 'relay-failed' ? { color: '#ff9f0a' } : undefined}+ >+ {pairingEndedMessage({ ...ended, windows: !sshKey })}</p>) : null}<Button variant="primary" disabled={busy} onClick={() => void start()}>@@ -217,7 +229,13 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele{phase === 'waiting' && qr ? (<div className="space-y-3">- {!sshOpen ? (+ {gate === 'relay-off' || gate === 'relay-dev' ? (+ // Relay-only host (Windows): no key is installed, so the relay IS the connection+ // and a code without it would pair the phone to nothing.+ <p className="text-sm" style={{ color: '#ff9f0a' }}>+ {relayGateMessage(gate, 'Remote access from your phone')}+ </p>+ ) : gate === 'ssh-off' ? (// No QR until Remote Login is on: a pairing completed against an unreachable// sshd installs a key the phone can never use — the scan must wait, not the fix.// The live probe (usePhonePairing) flips sshOpen and the QR appears by itself.@@ -270,7 +288,9 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele</p>) : null}</div>- {relayPlan === 'dev' ? (+ {!sshKey ? (+ <p className="text-xs text-muted">{relayOnlyExplanation(windowsKeyFile)}</p>+ ) : relayPlan === 'dev' ? (<p className="text-sm" style={{ color: '#ff9f0a' }}>Dev build: the relay is off regardless of the toggle, so this code pairsLAN-only. Run a packaged build — or set NODETERM_RELAY_URL — for remote@@ -297,7 +317,9 @@ export function PhoneSection({ isActive }: { isActive: boolean }): React.JSX.Ele{phase === 'paired' ? (<div className="space-y-3"><p className="text-sm font-medium" style={{ color: '#30d158' }}>- ✓ Paired. Your phone can now connect with its own key.+ {sshKey+ ? '✓ Paired. Your phone can now connect with its own key.'+ : '✓ Paired. Your phone connects to this computer through remote access.'}</p>{relayResult === 'ok' ? (<p className="text-sm" style={{ color: '#30d158' }}>diff --git a/src/renderer/components/settings/sections/PhoneSection.windows.test.tsx b/src/renderer/components/settings/sections/PhoneSection.windows.test.tsxnew file mode 100644index 000000000..562ff2a83--- /dev/null+++ b/src/renderer/components/settings/sections/PhoneSection.windows.test.tsx@@ -0,0 +1,116 @@+// @vitest-environment jsdom+//+// Settings → Phone on a relay-only host (Windows, `sshKey: false`): the QR waits for the RELAY, not+// sshd; no "your phone connects with its own key" claim; a failed relay mint says nothing was+// paired; a timeout nothing reached points at the firewall. Platform comes from main's start+// result, so this runs on any runner.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { PhoneSection } from './PhoneSection'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++vi.mock('qrcode', () => ({ toDataURL: async () => 'data:image/png;base64,QR' }))++type Done = (r: { ok: boolean; relay?: string; reason?: string; reached?: boolean }) => void+let root: Root+let host: HTMLElement+let fireDone: Done++function stubBridge(start: Record<string, unknown>): void {+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ pairing: {+ start: vi.fn(async () => ({ payload: '{"v":1}', sshOpen: false, ...start })),+ stop: vi.fn(async () => undefined),+ onDone: vi.fn((cb: Done) => {+ fireDone = cb+ return () => undefined+ }),+ probeSsh: vi.fn(async () => false),+ openRemoteLoginSettings: vi.fn(),+ listDevices: vi.fn(async () => []),+ revokeDevice: vi.fn()+ },+ remoteHost: { setPhoneAccess: vi.fn() },+ shell: { openExternal: vi.fn() }+ }+}++async function startPairing(): Promise<string> {+ act(() => root.render(<PhoneSection isActive />))+ await act(async () => undefined)+ const btn = [...host.querySelectorAll('button')].find((b) => b.textContent?.trim() === 'Start pairing')+ expect(btn).toBeTruthy()+ await act(async () => btn!.click())+ await act(async () => undefined)+ return host.textContent ?? ''+}++const qrShown = (): boolean => !!host.querySelector('img[alt="Pairing QR code"]')++beforeEach(() => {+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ vi.restoreAllMocks()+})++describe('PhoneSection on a relay-only (Windows) host', () => {+ it('withholds the QR until remote access is on — and never asks for an SSH server', async () => {+ stubBridge({ sshKey: false, relayPlan: 'off' })+ const text = await startPairing()+ expect(qrShown()).toBe(false)+ expect(text).toMatch(/only through remote access/)+ expect(text).not.toMatch(/OpenSSH|Remote Login|SSH server/)+ })++ it('shows the QR with sshd down once the relay will be minted, and explains the missing key', async () => {+ stubBridge({ sshKey: false, relayPlan: 'ok', windowsKeyFile: 'administrators' })+ const text = await startPairing()+ expect(qrShown()).toBe(true)+ expect(text).toMatch(/installs no SSH key/)+ expect(text).toMatch(/administrators_authorized_keys/)+ })++ it('does not claim a key-based connection once paired', async () => {+ stubBridge({ sshKey: false, relayPlan: 'ok' })+ await startPairing()+ await act(async () => fireDone({ ok: true, relay: 'ok' }))+ expect(host.textContent).toMatch(/through remote access/)+ expect(host.textContent).not.toMatch(/connect with its own key/)+ })++ it('says nothing was paired when the relay mint failed', async () => {+ stubBridge({ sshKey: false, relayPlan: 'ok' })+ await startPairing()+ await act(async () => fireDone({ ok: false, reason: 'relay-failed', reached: true }))+ expect(host.textContent).toMatch(/nothing was paired/)+ })++ it('points at the firewall when the phone never reached this computer', async () => {+ stubBridge({ sshKey: false, relayPlan: 'ok' })+ await startPairing()+ await act(async () => fireDone({ ok: false, reason: 'timeout', reached: false }))+ expect(host.textContent).toMatch(/Windows Defender Firewall/)+ })+})++describe('PhoneSection on an SSH host is unchanged', () => {+ it('still withholds the QR while sshd is down, relay or not', async () => {+ stubBridge({ sshKey: true, relayPlan: 'ok' })+ const text = await startPairing()+ expect(qrShown()).toBe(false)+ expect(text).toMatch(/is off, so your phone wouldn/)+ })++ it('treats a start result with no sshKey field (older main) as an SSH host', async () => {+ stubBridge({ relayPlan: 'ok' })+ await startPairing()+ expect(qrShown()).toBe(false)+ })+})diff --git a/src/renderer/components/settings/usePhonePairing.ts b/src/renderer/components/settings/usePhonePairing.tsindex 3164e03e1..b611fe751 100644--- a/src/renderer/components/settings/usePhonePairing.ts+++ b/src/renderer/components/settings/usePhonePairing.ts@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from 'react'import { toDataURL } from 'qrcode'import { DEFAULT_PAIR_QR_FORM, encodePairQr, type PairQrForm } from '@shared/pair-qr'+import type { WindowsKeyFileHint } from '@shared/pairing-gate'export type PairingPhase = 'idle' | 'waiting' | 'paired' | 'timeout'@@ -23,6 +24,12 @@ export function usePhonePairing(onPaired?: () => void): {setQrForm: (form: PairQrForm) => voidsshOpen: booleansshHealed: boolean+ /** false = relay-only host (Windows) — see `pairingGate`. Kept after the pairing ends, so the+ * ended/paired copy can still tell which kind of host this is. */+ sshKey: boolean+ windowsKeyFile: WindowsKeyFileHint | undefined+ /** On phase 'timeout': why it ended and whether the phone ever reached the listener. */+ ended: { reason?: 'timeout' | 'relay-failed'; reached?: boolean } | null/** On phase 'paired': whether the pairing came with a relay leg ('off' = toggle disabled,* 'failed' = mint failed → LAN-only). Surfaced so the silent degrade is visible at the one* moment the user is looking. */@@ -46,6 +53,9 @@ export function usePhonePairing(onPaired?: () => void): {// Went from unreachable → reachable while the warning was showing: show a green confirmation// instead of silently dropping the warning (the user just flipped a toggle; acknowledge it).const [sshHealed, setSshHealed] = useState(false)+ const [sshKey, setSshKey] = useState(true)+ const [windowsKeyFile, setWindowsKeyFile] = useState<WindowsKeyFileHint | undefined>(undefined)+ const [ended, setEnded] = useState<{ reason?: 'timeout' | 'relay-failed'; reached?: boolean } | null>(null)const [relayResult, setRelayResult] = useState<'ok' | 'off' | 'failed' | 'dev' | null>(null)const [relayPlan, setRelayPlan] = useState<'ok' | 'dev' | 'off' | null>(null)const [error, setError] = useState('')@@ -58,7 +68,8 @@ export function usePhonePairing(onPaired?: () => void): {// in System Settings and nothing changes on screen. Poll only in that exact state (waiting +// unreachable); the interval dies with the warning.useEffect(() => {- if (phase !== 'waiting' || sshOpen) return+ // A relay-only host never shows the sshd warning, so there is nothing to re-probe for.+ if (phase !== 'waiting' || sshOpen || !sshKey) returnlet cancelled = falseconst timer = setInterval(() => {void window.nodeTerminal.pairing@@ -77,14 +88,23 @@ export function usePhonePairing(onPaired?: () => void): {cancelled = trueclearInterval(timer)}- }, [phase, sshOpen])+ }, [phase, sshOpen, sshKey])const start = async (): Promise<void> => {setError('')setBusy(true)try {- const { payload: built, sshOpen: open, relayPlan: plan } = await window.nodeTerminal.pairing.start()+ const {+ payload: built,+ sshOpen: open,+ relayPlan: plan,+ sshKey: key,+ windowsKeyFile: keyFile+ } = await window.nodeTerminal.pairing.start()setRelayPlan(plan ?? null)+ setSshKey(key !== false)+ setWindowsKeyFile(keyFile)+ setEnded(null)// The image itself is rendered by the effect below, which also handles a later switch// between the JSON and URL envelopes.setPayload(built)@@ -143,6 +163,7 @@ export function usePhonePairing(onPaired?: () => void): {setQr('')setPhase(result.ok ? 'paired' : 'timeout')setRelayResult(result.ok ? (result.relay ?? null) : null)+ setEnded(result.ok ? null : { reason: result.reason, reached: result.reached })if (result.ok) onPairedRef.current?.()})}, [])@@ -164,6 +185,9 @@ export function usePhonePairing(onPaired?: () => void): {setQrForm,sshOpen,sshHealed,+ sshKey,+ windowsKeyFile,+ ended,relayResult,relayPlan,error,diff --git a/src/shared/pairing-gate.test.ts b/src/shared/pairing-gate.test.tsnew file mode 100644index 000000000..fd98ce602--- /dev/null+++ b/src/shared/pairing-gate.test.ts@@ -0,0 +1,39 @@+import { describe, it, expect } from 'vitest'+import { pairingEndedMessage, pairingGate, relayGateMessage, relayOnlyExplanation } from './pairing-gate'++describe('pairingGate', () => {+ it('gates an SSH host on sshd alone — the relay plan does not matter there', () => {+ for (const relayPlan of ['ok', 'dev', 'off', null] as const) {+ expect(pairingGate({ sshKey: true, sshOpen: true, relayPlan })).toBe('qr')+ expect(pairingGate({ sshKey: true, sshOpen: false, relayPlan })).toBe('ssh-off')+ }+ })++ it('gates a relay-only (Windows) host on the relay alone — sshd does not matter there', () => {+ for (const sshOpen of [true, false]) {+ expect(pairingGate({ sshKey: false, sshOpen, relayPlan: 'ok' })).toBe('qr')+ expect(pairingGate({ sshKey: false, sshOpen, relayPlan: 'off' })).toBe('relay-off')+ expect(pairingGate({ sshKey: false, sshOpen, relayPlan: null })).toBe('relay-off')+ expect(pairingGate({ sshKey: false, sshOpen, relayPlan: 'dev' })).toBe('relay-dev')+ }+ })+})++describe('copy', () => {+ it('names the toggle of the surface it is shown on', () => {+ expect(relayGateMessage('relay-off', 'Reach this PC from anywhere')).toContain('“Reach this PC from anywhere”')+ })++ it('explains the administrators key file only when detected', () => {+ expect(relayOnlyExplanation('administrators')).toContain('administrators_authorized_keys')+ expect(relayOnlyExplanation('profile')).not.toContain('administrators_authorized_keys')+ expect(relayOnlyExplanation(undefined)).not.toContain('administrators_authorized_keys')+ })++ it('blames the firewall only for a Windows timeout that nothing reached', () => {+ expect(pairingEndedMessage({ reason: 'timeout', reached: false, windows: true })).toMatch(/Firewall/)+ expect(pairingEndedMessage({ reason: 'timeout', reached: true, windows: true })).not.toMatch(/Firewall/)+ expect(pairingEndedMessage({ reason: 'timeout', reached: false, windows: false })).not.toMatch(/Firewall/)+ expect(pairingEndedMessage({ reason: 'relay-failed', reached: true, windows: true })).toMatch(/nothing was paired/)+ })+})diff --git a/src/shared/pairing-gate.ts b/src/shared/pairing-gate.tsnew file mode 100644index 000000000..06c28afd9--- /dev/null+++ b/src/shared/pairing-gate.ts@@ -0,0 +1,68 @@+/**+ * What the phone-pairing surfaces show in place of (or beside) the QR — ONE decision shared by+ * Settings → Phone and the quick-pair popover, so the two cannot disagree about when a code is+ * scannable.+ *+ * Two kinds of host:+ * - SSH hosts (macOS, Linux): the scan installs an SSH key, so the QR waits for sshd — a pairing+ * against a dead sshd installs a key the phone can never use.+ * - Relay-only hosts (Windows, `sshKey: false`): the phone cannot drive a Windows host over SSH+ * (its commands are POSIX sh + tmux; Windows OpenSSH hands out cmd.exe and sessions live in the+ * session host), so no key is installed and sshd is irrelevant. The QR waits for the RELAY+ * instead, because without it the pairing would give the phone nothing to connect with.+ */++export type PairingGate = 'qr' | 'ssh-off' | 'relay-off' | 'relay-dev'++export function pairingGate(state: {+ sshKey: boolean+ sshOpen: boolean+ relayPlan: 'ok' | 'dev' | 'off' | null+}): PairingGate {+ if (state.sshKey) return state.sshOpen ? 'qr' : 'ssh-off'+ if (state.relayPlan === 'ok') return 'qr'+ return state.relayPlan === 'dev' ? 'relay-dev' : 'relay-off'+}++/** Which authorized_keys file Windows OpenSSH reads for this account (main's detection). */+export type WindowsKeyFileHint = 'administrators' | 'profile' | 'unknown'++/**+ * The one explanatory sentence on a relay-only (Windows) host. The administrators variant exists+ * for issue #758: a user who goes looking for the key will not find it, and if they add one by+ * hand, the profile file is the wrong place for their account.+ */+export function relayOnlyExplanation(keyFile: WindowsKeyFileHint | undefined): string {+ const base =+ 'On Windows your phone connects through remote access, so pairing installs no SSH key here — the phone cannot drive a Windows shell over SSH yet.'+ if (keyFile === 'administrators')+ return (+ base ++ ' (Your account is an administrator, so Windows’ SSH server reads keys only from the machine-wide %ProgramData%\\ssh\\administrators_authorized_keys, never ~/.ssh/authorized_keys.)'+ )+ return base+}++/** Copy for a relay-only host whose QR is withheld. `toggle` names the switch on that surface. */+export function relayGateMessage(gate: 'relay-off' | 'relay-dev', toggle: string): string {+ return gate === 'relay-dev'+ ? 'Dev build: the relay is off regardless of the toggle, and on Windows the phone connects only through it — so there is no code to scan. Run a packaged build, or set NODETERM_RELAY_URL.'+ : `On Windows your phone connects only through remote access. Turn on “${toggle}” and the code appears here.`+}++/** Copy for a pairing that ended without pairing. `windows` = relay-only host. */+export function pairingEndedMessage(end: {+ reason?: 'timeout' | 'relay-failed'+ reached?: boolean+ windows: boolean+}): string {+ if (end.reason === 'relay-failed')+ return 'Remote-access setup failed, so nothing was paired — on Windows that is how the phone connects. Check this computer’s internet connection and show a new code.'+ const base = 'Pairing timed out — that code no longer works. Start again and scan the fresh one within ten minutes.'+ if (end.windows && end.reached === false)+ return (+ base ++ ' Your phone never reached this computer: if it did scan the code, Windows Defender Firewall is probably blocking nodeterm on this network — allow it for Private networks (or set this Wi-Fi to Private) and try again.'+ )+ return base+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 9f4f84ef7..16f862f41 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3236,11 +3236,28 @@ export interface DeviceRevokeResult {/** Phone-pairing (nodeterm iOS "scan a QR" flow) bridge. */export interface PairingApi {/** Start the one-shot LAN listener; resolves with the QR payload + an SSH-reachable hint. */- start(): Promise<{ payload: string; sshOpen: boolean; relayPlan?: 'ok' | 'dev' | 'off' }>+ start(): Promise<{+ payload: string+ sshOpen: boolean+ relayPlan?: 'ok' | 'dev' | 'off'+ /** false = relay-only host (Windows): no SSH key is installed and the QR waits for the relay,+ * not sshd (`pairingGate`). Absent from an older main process ⇒ treat as true. */+ sshKey?: boolean+ /** Windows only, explanation only: which authorized_keys file sshd reads for this account. */+ windowsKeyFile?: 'administrators' | 'profile' | 'unknown'+ }>/** Cancel an in-flight pairing (e.g. when the settings section unmounts). */stop(): Promise<void>- /** Fires once when pairing finishes (ok=true paired, ok=false timeout). Returns unsubscribe. */- onDone(cb: (result: { ok: boolean; relay?: 'ok' | 'off' | 'failed' | 'dev' }) => void): () => void+ /** Fires once when pairing finishes (ok=true paired, ok=false timeout / relay-only mint failure).+ * Returns unsubscribe. */+ onDone(+ cb: (result: {+ ok: boolean+ relay?: 'ok' | 'off' | 'failed' | 'dev'+ reason?: 'timeout' | 'relay-failed'+ reached?: boolean+ }) => void+ ): () => void/** Live re-probe of 127.0.0.1:22, so the "SSH server is off" warning can clear the moment the* user turns it on (polled by the UI only while the warning is showing). */probeSsh(): Promise<boolean>