Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(desktop): connect SSH computers on Windows (#133)

Sean Fergusoncd820654abfe
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 5146135d..df3dfe7d 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -207,6 +207,7 @@ jobs:
# Unsigned for now: SmartScreen warns on first launch until the app has a code signing certificate.
run: |
npm ci
+ node --test --experimental-strip-types src/shared/ssh-platform.test.ts
npm run dist:win:main -- --publish never
cd dist
sha256sum codync-windows-x64.exe > codync-windows-x64.exe.sha256
diff --git a/README.md b/README.md
index 08b19f11..e5cfa220 100644
--- a/README.md
+++ b/README.md
@@ -55,7 +55,7 @@ Codync turns the coding agents on your computer — Claude Code, Codex, Cursor,
- **One app per kind of device.** Native SwiftUI on the iPhone, one desktop app for Mac, Windows and Linux (Electron), and a terminal UI for SSH.
- **A Grok Bot, Muse and Dots alternative.** Persistent named bots, group chats, quote replies, bots asking each other for help, approval cards, per-bot memory, remote screen, voice calls and "needs you / done" notifications — the same features, without being tied to one model or one subscription.
- **Reach your computer from anywhere, free.** The hosted Cloudflare relay is included at no cost: no Tailscale, no VPN, no port forwarding. Traffic is end-to-end encrypted between your phone and your computer, so the relay only forwards ciphertext. Same Wi-Fi or Tailscale? The phone connects directly instead.
-- **Every computer, one app.** Sign in and your iPhone lists every computer on your account (Mac, Windows PC, Linux desktop, server or cloud VM); open Computers and tap **Ask for access**, confirm a 6-digit code on that computer, and its bots show up next to the others. A new bot can live on any of them, and the Mac app reaches your SSH machines too. Each computer approves each device itself, so an account alone never unlocks a computer.
+- **Every computer, one app.** Sign in and your iPhone lists every computer on your account (Mac, Windows PC, Linux desktop, server or cloud VM); open Computers and tap **Ask for access**, confirm a 6-digit code on that computer, and its bots show up next to the others. A new bot can live on any of them, and the desktop app on Mac, Windows and Linux reaches your SSH machines too. Each computer approves each device itself, so an account alone never unlocks a computer.
- **Remote screen.** See and control your computer from the iPhone over WebRTC (hardware H.264), and let bots use the screen themselves through the built-in `computer` tool.
- **Voice calls.** Talk to a bot hands-free from the iPhone and hear its replies read aloud.
- **Private push.** Notification text is sealed to your phone's key, so the push relay never sees what your bots said.
diff --git a/apps/desktop/src/main/ssh-command.ts b/apps/desktop/src/main/ssh-command.ts
index c1e29823..c4692727 100644
--- a/apps/desktop/src/main/ssh-command.ts
+++ b/apps/desktop/src/main/ssh-command.ts
@@ -1,4 +1,6 @@
+import { win32 } from 'node:path'
import type { SSHProfile } from '../shared/ssh.ts'
+import type { Resolved } from './ssh-parse.ts'
// Preserve the login shell's PATH, then try the supported installers and the Mac app bundle.
const REMOTE_PATH = '$PATH:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.local/bin:/Applications/Codync.app/Contents/Resources'
@@ -13,11 +15,28 @@ export const remoteInfoCommand = (port: number, folder = '.codync') => {
return `sh -lc 'PATH="${REMOTE_PATH}" codync-host info --json --port ${port}'`
}
-/** `dir` is this app's host data folder (`~/.codync`, or a development sandbox's). */
-export const knownHostsFiles = (h: string, dir = `${h}/.codync`) => [`${h}/.ssh/known_hosts`, `${dir}/ssh_known_hosts`]
+/** Codync's own known_hosts file in `dir`, this app's host data folder (`~/.codync`, or a development sandbox's). */
+export const codyncKnownHosts = (dir: string) => `${dir.replaceAll('\\', '/')}/ssh_known_hosts`
+
+export const knownHostsFiles = (h: string, dir = `${h}/.codync`) => [`${h.replaceAll('\\', '/')}/.ssh/known_hosts`, codyncKnownHosts(dir)]
+
+const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
/** `pkill -f` pattern for the tunnels that use `dir`'s known_hosts file: this copy's own, never another copy's. */
-export const orphanTunnelPattern = (dir: string) => `^/usr/bin/ssh -N .*${dir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/ssh_known_hosts`
+export const orphanTunnelPattern = (binary: string, dir: string) => `^${escapeRegExp(binary)} -N .*${escapeRegExp(codyncKnownHosts(dir))}`
+
+export interface WindowsProcess { ProcessId: number; ExecutablePath: string | null; CommandLine: string | null }
+
+/** Windows' `orphanTunnelPattern`: a native ssh tunnel carrying `dir`'s exact quoted known_hosts file. */
+export function ownsWindowsTunnel(candidate: WindowsProcess, binary: string, dir: string) {
+ const { ProcessId: pid, ExecutablePath: path, CommandLine: command } = candidate
+ if (!path || !command || !Number.isSafeInteger(pid) || pid <= 0) return false
+ if (win32.normalize(path).toLowerCase() !== win32.normalize(binary).toLowerCase()) return false
+ const marker = codyncKnownHosts(dir)
+ return /\s-N\s+-T\s/.test(command) && command.includes('UserKnownHostsFile=') &&
+ (command.includes(`\\"${marker}\\"`) || command.includes(`"${marker}"`)) &&
+ /\s-L\s+127\.0\.0\.1:\d+:127\.0\.0\.1:\d+(?:\s|$)/.test(command)
+}
/** ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes. */
export const hostKeyOptions = (h: string, dir?: string) => [
@@ -33,6 +52,23 @@ function targetOptions(p: SSHProfile) {
return args
}
+export const keyscanArguments = (r: Resolved) => ['-T', '5', '-p', String(r.port), '--', r.hostname]
+
+/**
+ * Like ssh-keyscan, but ssh itself files the key the host presents in `file` (accept-new) and stops at sign-in: no
+ * config and no sign-in method, with the algorithms the connection resolved, so the key filed is the one it will check.
+ */
+export function presentedKeyArguments(r: Resolved, file: string) {
+ const known = `"${file.replaceAll('\\', '/')}"`
+ const algorithms = [['HostKeyAlgorithms', r.hostKeyAlgorithms], ['KexAlgorithms', r.kexAlgorithms]]
+ .flatMap(([name, value]) => value ? ['-o', `${name}=${value}`] : [])
+ return [
+ '-F', 'none', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5', '-o', 'PreferredAuthentications=none',
+ '-o', 'StrictHostKeyChecking=accept-new', '-o', `UserKnownHostsFile=${known}`, '-o', `GlobalKnownHostsFile=${known}`,
+ ...algorithms, '-p', String(r.port), '--', r.hostname,
+ ]
+}
+
export function resolveArguments(p: SSHProfile) {
const args = ['-G']
if (p.port !== null) args.push('-p', String(p.port))
diff --git a/apps/desktop/src/main/ssh-parse.ts b/apps/desktop/src/main/ssh-parse.ts
new file mode 100644
index 00000000..1b4ae2be
--- /dev/null
+++ b/apps/desktop/src/main/ssh-parse.ts
@@ -0,0 +1,90 @@
+import { createHash } from 'node:crypto'
+
+/** The far side rejected our key (BatchMode never prompts, so a password or passphrase can't help). */
+export const authRefused = (stderr: string) => stderr.includes('Permission denied') || stderr.includes('Too many authentication failures')
+
+/** What `ssh -G` resolved the destination to. */
+export interface Resolved {
+ hostname: string
+ port: number
+ hostKeyAlias: string | null
+ proxyJump: string | null
+ proxyCommand: string | null
+ /** What the connection will negotiate, so a key read before it (Windows) is one the connection accepts. */
+ hostKeyAlgorithms: string | null
+ kexAlgorithms: string | null
+}
+
+export const usesProxy = (r: Resolved) => r.proxyJump !== null || r.proxyCommand !== null
+/** The name ssh looks up in known_hosts. */
+export const knownHostsName = (r: Resolved) => {
+ const name = r.hostKeyAlias ?? r.hostname
+ return r.port === 22 ? name : `[${name}]:${r.port}`
+}
+
+export function parseConfig(text: string): Resolved | null {
+ const values = new Map<string, string>()
+ for (const line of text.split(/\r?\n/)) {
+ const at = line.indexOf(' ')
+ if (at < 0) continue
+ const key = line.slice(0, at).toLowerCase()
+ if (!values.has(key)) values.set(key, line.slice(at + 1).trim())
+ }
+ const set = (k: string) => {
+ const v = values.get(k)
+ return v && v !== 'none' ? v : null
+ }
+ const hostname = set('hostname')
+ const port = Number(values.get('port'))
+ if (!hostname || !Number.isInteger(port) || !values.get('port')) return null
+ return {
+ hostname, port, hostKeyAlias: set('hostkeyalias'), proxyJump: set('proxyjump'), proxyCommand: set('proxycommand'),
+ hostKeyAlgorithms: set('hostkeyalgorithms'), kexAlgorithms: set('kexalgorithms'),
+ }
+}
+
+/** `type key` of each host key line (known_hosts or ssh-keyscan output); comments and revoked keys skipped. */
+export function hostKeys(text: string, certAuthorities = true): Set<string> {
+ const keys = new Set<string>()
+ for (const line of text.split(/\r?\n/)) {
+ const fields = line.split(/\s+/).filter(Boolean)
+ const first = fields[0]
+ if (!first || first.startsWith('#')) continue
+ if (first.startsWith('@')) {
+ if (!certAuthorities || first !== '@cert-authority') continue
+ fields.shift()
+ }
+ if (fields.length >= 3) keys.add(`${fields[1]} ${fields[2]}`)
+ }
+ return keys
+}
+
+/** ssh-keyscan's lines, filed under the name ssh will look up. */
+export const knownHostsLines = (scan: string, name: string) => [...hostKeys(scan)].sort().map((k) => `${name} ${k}`)
+
+/** A computer id is the first 16 bytes of SHA-256 of its signing key, base64url. */
+export function consistent(id: string, signKey: string) {
+ const key = Buffer.from(signKey, 'base64url')
+ return key.length === 32 && createHash('sha256').update(key).digest().subarray(0, 16).toString('base64url') === id
+}
+
+/** What `codync-host info --json` prints. */
+interface RemoteInfo {
+ name: string
+ computerId: string
+ signKey: string
+ boxKey?: string | null
+ token: string
+ running: boolean
+}
+
+export function parseInfo(text: string): RemoteInfo | null {
+ try {
+ const v = JSON.parse(text) as Partial<RemoteInfo>
+ return typeof v.name === 'string' && typeof v.computerId === 'string' && typeof v.signKey === 'string' && typeof v.token === 'string' && typeof v.running === 'boolean'
+ ? (v as RemoteInfo)
+ : null
+ } catch {
+ return null
+ }
+}
diff --git a/apps/desktop/src/main/ssh-process.ts b/apps/desktop/src/main/ssh-process.ts
new file mode 100644
index 00000000..729539d6
--- /dev/null
+++ b/apps/desktop/src/main/ssh-process.ts
@@ -0,0 +1,118 @@
+import { spawn, type ChildProcess } from 'node:child_process'
+import { existsSync, promises as fs } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, win32 } from 'node:path'
+import { keyscanArguments, orphanTunnelPattern, ownsWindowsTunnel, presentedKeyArguments, type WindowsProcess } from './ssh-command.ts'
+import type { Resolved } from './ssh-parse.ts'
+
+const systemRoot = process.env.SystemRoot ?? 'C:\\Windows'
+
+export function sshTools(os = process.platform, root = systemRoot) {
+ const directory = os === 'win32' ? win32.join(root, 'System32', 'OpenSSH') : '/usr/bin'
+ const tool = (name: string) => os === 'win32' ? win32.join(directory, `${name}.exe`) : `${directory}/${name}`
+ return { ssh: tool('ssh'), keygen: tool('ssh-keygen'), keyscan: tool('ssh-keyscan') }
+}
+
+const tools = sshTools()
+export const SSH = tools.ssh
+export const KEYGEN = tools.keygen
+export const KEYSCAN = tools.keyscan
+const POWERSHELL = win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
+const LSOF = ['/usr/sbin/lsof', '/usr/bin/lsof'].find((p) => existsSync(p)) ?? null
+
+/** How to install the OpenSSH tools when one is missing, or null. */
+export function missingTools(): string | null {
+ if ([SSH, KEYGEN, KEYSCAN].every((tool) => existsSync(tool))) return null
+ return process.platform === 'win32' ? 'Install OpenSSH Client in Windows Settings → Optional features, then connect again.' : 'Install OpenSSH, then connect again.'
+}
+
+/** The last thing the tool said, for showing next to an error. */
+export const lastLine = (text: string) => text.split(/\r?\n/).filter(Boolean).pop() ?? ''
+
+interface Result { status: number; stdout: string; stderr: string }
+
+/** Runs a tool with hidden Windows consoles while draining both output pipes; one that hangs is killed after 30 s. */
+export function run(bin: string, args: string[], input?: string): Promise<Result> {
+ return new Promise((resolve) => {
+ let stdout = ''
+ let stderr = ''
+ let child: ChildProcess
+ try {
+ child = spawn(bin, args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], windowsHide: true, timeout: 30_000 })
+ } catch (error) {
+ return resolve({ status: -1, stdout, stderr: String(error) })
+ }
+ child.stdout?.on('data', (d: Buffer) => (stdout += d.toString()))
+ child.stderr?.on('data', (d: Buffer) => (stderr += d.toString()))
+ child.once('error', (error) => { resolve({ status: -1, stdout, stderr: error.message }) })
+ child.once('close', (code) => { resolve({ status: code ?? -1, stdout, stderr }) })
+ child.stdin?.on('error', () => { /* A tool can exit before consuming its input. */ })
+ if (input !== undefined) child.stdin?.end(input)
+ })
+}
+
+/**
+ * The host's keys in known_hosts form, read before any sign-in. Windows' ssh-keyscan (OpenSSH 9.5) offers a key exchange
+ * it can't run and reads nothing from current servers, so there ssh records the one key the host presents instead.
+ */
+export async function scanHostKeys(r: Resolved): Promise<string> {
+ if (process.platform !== 'win32') return (await run(KEYSCAN, keyscanArguments(r))).stdout
+ const dir = await fs.mkdtemp(join(tmpdir(), 'codync-ssh-')).catch(() => null)
+ if (dir === null) return ''
+ const file = join(dir, 'known_hosts')
+ await run(SSH, presentedKeyArguments(r, file))
+ const text = await fs.readFile(file, 'utf8').catch(() => '')
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => { /* A scratch folder left in temp is harmless. */ })
+ return text
+}
+
+function powershell(script: string) {
+ return run(POWERSHELL, ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')])
+}
+
+export function listenerCommand(pid: number, port: number) {
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid listener')
+ return `Get-NetTCPConnection -LocalAddress 127.0.0.1 -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue | Where-Object { $_.OwningProcess -eq ${pid} } | ForEach-Object { $_.OwningProcess }`
+}
+
+/** Never send the host token until the listener is owned by the exact ssh child. */
+export async function sshListens(pid: number, port: number): Promise<boolean> {
+ if (process.platform === 'win32') {
+ const found = await powershell(listenerCommand(pid, port))
+ return found.status === 0 && found.stdout.split(/\r?\n/).some((line) => line.trim() === String(pid))
+ }
+ if (LSOF) {
+ const found = await run(LSOF, ['-a', '-n', '-P', '-p', String(pid), `[email protected]:${port}`, '-sTCP:LISTEN', '-t'])
+ return found.status === 0 && found.stdout.split(/\r?\n/).includes(String(pid))
+ }
+ if (process.platform !== 'linux') return false
+ try {
+ const local = `0100007F:${port.toString(16).toUpperCase().padStart(4, '0')}`
+ const tcp = await fs.readFile('/proc/net/tcp', 'utf8')
+ const inodes = tcp.split('\n').map((line) => line.trim().split(/\s+/))
+ .filter((f) => f[1] === local && f[3] === '0A').map((f) => `socket:[${f[9]}]`)
+ if (inodes.length === 0) return false
+ const descriptors = await fs.readdir(`/proc/${pid}/fd`)
+ for (const fd of descriptors) {
+ const link = await fs.readlink(`/proc/${pid}/fd/${fd}`).catch(() => '')
+ if (inodes.includes(link)) return true
+ }
+ } catch { /* A process can exit while its sockets are inspected. */ }
+ return false
+}
+
+/** Tunnels a crashed or force-quit copy of this app left running: only they carry `dir`'s known_hosts file. */
+export async function killOrphanTunnels(dir: string) {
+ if (process.platform !== 'win32') {
+ await run('/usr/bin/pkill', ['-f', '--', orphanTunnelPattern(SSH, dir)])
+ return
+ }
+ const result = await powershell(`$ErrorActionPreference='Stop'; $p = @(Get-CimInstance Win32_Process -Filter "Name='ssh.exe'" | Select-Object ProcessId, ExecutablePath, CommandLine); ConvertTo-Json -InputObject $p -Compress -Depth 2`)
+ if (result.status !== 0) { console.error('ssh: could not inspect leftover tunnels'); return }
+ try {
+ for (const candidate of JSON.parse(result.stdout) as WindowsProcess[]) {
+ if (!ownsWindowsTunnel(candidate, SSH, dir)) continue
+ try { process.kill(candidate.ProcessId) } catch { /* Already exited. */ }
+ }
+ } catch (error) { console.error('ssh: could not inspect leftover tunnels', error) }
+}
diff --git a/apps/desktop/src/main/ssh-profile.ts b/apps/desktop/src/main/ssh-profile.ts
new file mode 100644
index 00000000..1bf946e0
--- /dev/null
+++ b/apps/desktop/src/main/ssh-profile.ts
@@ -0,0 +1,26 @@
+import { statSync } from 'node:fs'
+import { posix } from 'node:path'
+import { isSSHHost, type SSHProfile } from '../shared/ssh.ts'
+
+/** Only native absolute paths: a drive-relative Windows key is ambiguous. */
+export const isAbsoluteKeyPath = (path: string, os = process.platform) =>
+ os === 'win32' ? /^(?:[A-Za-z]:[\\/]|\\\\[^\\]+\\[^\\]+)/.test(path) : posix.isAbsolute(path)
+
+/** A reason the profile can't be used, or null. */
+export function validate(p: SSHProfile): string | null {
+ if (!isSSHHost(p.host)) {
+ return 'Use an SSH alias or a hostname: letters, digits, dots, dashes and underscores.'
+ }
+ if (p.user !== null && !/^[A-Za-z_][A-Za-z0-9._-]*$/.test(p.user)) return "That user name isn't valid."
+ const inRange = (n: number) => Number.isInteger(n) && n >= 1 && n <= 65535
+ if (p.port !== null && !inRange(p.port)) return 'The SSH port must be between 1 and 65535.'
+ if (!inRange(p.remotePort)) return 'The Codync port must be between 1 and 65535.'
+ if (p.identityFile !== null) {
+ let ok = false
+ try {
+ ok = isAbsoluteKeyPath(p.identityFile) && statSync(p.identityFile).isFile()
+ } catch {}
+ if (!ok) return "The key file doesn't exist."
+ }
+ return null
+}
diff --git a/apps/desktop/src/main/ssh.ts b/apps/desktop/src/main/ssh.ts
index 3b2b8772..ca9e6055 100644
--- a/apps/desktop/src/main/ssh.ts
+++ b/apps/desktop/src/main/ssh.ts
@@ -1,142 +1,24 @@
import { identity } from './environment'
import { spawn, type ChildProcess } from 'node:child_process'
-import { createHash } from 'node:crypto'
-import { existsSync, promises as fs, readFileSync, statSync } from 'node:fs'
+import { existsSync, promises as fs, readFileSync } from 'node:fs'
import { createServer } from 'node:net'
-import { homedir, platform } from 'node:os'
+import { homedir } from 'node:os'
import { join } from 'node:path'
import { app, dialog, ipcMain, type BrowserWindow } from 'electron'
-import { isSSHHost, type SSHAttachment, type SSHProfile, type SSHState, type SSHStatus } from '../shared/ssh'
import { dataDir } from './host-controller'
-import { infoArguments, knownHostsFiles, orphanTunnelPattern, resolveArguments, tunnelArguments } from './ssh-command'
+import type { SSHAttachment, SSHProfile, SSHState, SSHStatus } from '../shared/ssh'
+import { codyncKnownHosts, infoArguments, keyscanArguments, knownHostsFiles, resolveArguments, tunnelArguments } from './ssh-command'
+import { authRefused, consistent, hostKeys, knownHostsLines, knownHostsName, parseConfig, parseInfo, usesProxy } from './ssh-parse'
+import { KEYGEN, KEYSCAN, SSH, killOrphanTunnels, lastLine, missingTools, run, scanHostKeys, sshListens } from './ssh-process'
+import { validate } from './ssh-profile'
// SSH computers: profiles, host key checks and one
// OpenSSH tunnel per connected profile. Arguments are always an argv array, never a shell string.
-const SSH = '/usr/bin/ssh'
-const KEYGEN = '/usr/bin/ssh-keygen'
-const KEYSCAN = '/usr/bin/ssh-keyscan'
-const LSOF = ['/usr/sbin/lsof', '/usr/bin/lsof'].find((p) => existsSync(p)) ?? null
const home = homedir()
-// MARK: pure helpers
-
-/** A reason the profile can't be used, or null. */
-export function validate(p: SSHProfile): string | null {
- if (!isSSHHost(p.host)) {
- return 'Use an SSH alias or a hostname: letters, digits, dots, dashes and underscores.'
- }
- if (p.user !== null && !/^[A-Za-z_][A-Za-z0-9._-]*$/.test(p.user)) return "That user name isn't valid."
- const inRange = (n: number) => Number.isInteger(n) && n >= 1 && n <= 65535
- if (p.port !== null && !inRange(p.port)) return 'The SSH port must be between 1 and 65535.'
- if (!inRange(p.remotePort)) return 'The Codync port must be between 1 and 65535.'
- if (p.identityFile !== null) {
- let ok = false
- try {
- ok = p.identityFile.startsWith('/') && statSync(p.identityFile).isFile()
- } catch {}
- if (!ok) return "The key file doesn't exist."
- }
- return null
-}
-
-/** The far side rejected our key (BatchMode never prompts, so a password or passphrase can't help). */
-export const authRefused = (stderr: string) => stderr.includes('Permission denied') || stderr.includes('Too many authentication failures')
-
-/** What `ssh -G` resolved the destination to. */
-export interface Resolved {
- hostname: string
- port: number
- hostKeyAlias: string | null
- proxyJump: string | null
- proxyCommand: string | null
-}
-
-const usesProxy = (r: Resolved) => r.proxyJump !== null || r.proxyCommand !== null
-/** The name ssh looks up in known_hosts. */
-export const knownHostsName = (r: Resolved) => {
- const name = r.hostKeyAlias ?? r.hostname
- return r.port === 22 ? name : `[${name}]:${r.port}`
-}
-
-export function parseConfig(text: string): Resolved | null {
- const values = new Map<string, string>()
- for (const line of text.split(/\r?\n/)) {
- const at = line.indexOf(' ')
- if (at < 0) continue
- const key = line.slice(0, at).toLowerCase()
- if (!values.has(key)) values.set(key, line.slice(at + 1).trim())
- }
- const set = (k: string) => {
- const v = values.get(k)
- return v && v !== 'none' ? v : null
- }
- const hostname = set('hostname')
- const port = Number(values.get('port'))
- if (!hostname || !Number.isInteger(port) || !values.get('port')) return null
- return { hostname, port, hostKeyAlias: set('hostkeyalias'), proxyJump: set('proxyjump'), proxyCommand: set('proxycommand') }
-}
-
-const keyscanArguments = (r: Resolved) => ['-T', '5', '-p', String(r.port), '--', r.hostname]
-
-/** `type key` of each host key line (known_hosts or ssh-keyscan output); comments and revoked keys skipped. */
-export function hostKeys(text: string, certAuthorities = true): Set<string> {
- const keys = new Set<string>()
- for (const line of text.split(/\r?\n/)) {
- const fields = line.split(/\s+/).filter(Boolean)
- const first = fields[0]
- if (!first || first.startsWith('#')) continue
- if (first.startsWith('@')) {
- if (!certAuthorities || first !== '@cert-authority') continue
- fields.shift()
- }
- if (fields.length >= 3) keys.add(`${fields[1]} ${fields[2]}`)
- }
- return keys
-}
-
-/** ssh-keyscan's lines, filed under the name ssh will look up. */
-export const knownHostsLines = (scan: string, name: string) => [...hostKeys(scan)].sort().map((k) => `${name} ${k}`)
-
-/** A computer id is the first 16 bytes of SHA-256 of its signing key, base64url. */
-function consistent(id: string, signKey: string) {
- const key = Buffer.from(signKey, 'base64url')
- return key.length === 32 && createHash('sha256').update(key).digest().subarray(0, 16).toString('base64url') === id
-}
-
// MARK: processes
-interface Result {
- status: number
- stdout: string
- stderr: string
-}
-
-/** The last thing the tool said, for showing next to an error. */
-const lastLine = (text: string) => text.split(/\r?\n/).filter(Boolean).pop() ?? ''
-
-/** Runs a tool to completion; both pipes are drained while it runs. */
-function run(bin: string, args: string[], input?: string): Promise<Result> {
- return new Promise((resolve) => {
- let stdout = ''
- let stderr = ''
- let child: ChildProcess
- try {
- child = spawn(bin, args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] })
- } catch {
- return resolve({ status: -1, stdout, stderr })
- }
- child.stdout?.on('data', (d: Buffer) => (stdout += d.toString()))
- child.stderr?.on('data', (d: Buffer) => (stderr += d.toString()))
- child.on('error', () => resolve({ status: -1, stdout, stderr }))
- child.on('close', (code) => resolve({ status: code ?? -1, stdout, stderr }))
- if (input !== undefined) child.stdin?.end(input)
- })
-}
-
-/** Tunnels a crashed or force-quit Codync left running: only Codync's tunnels carry this known_hosts file. */
-const killOrphanTunnels = () => run('/usr/bin/pkill', ['-f', '--', orphanTunnelPattern(dataDir)])
-
/** Binds port 0 on loopback to learn a free port. */
function freeLocalPort(): Promise<number | null> {
return new Promise((resolve) => {
@@ -149,30 +31,6 @@ function freeLocalPort(): Promise<number | null> {
})
}
-/** Whether process `pid` holds the listening socket on 127.0.0.1:`port`. */
-async function sshListens(pid: number, port: number): Promise<boolean> {
- if (LSOF) {
- const found = await run(LSOF, ['-a', '-n', '-P', '-p', String(pid), `[email protected]:${port}`, '-sTCP:LISTEN', '-t'])
- return found.status === 0 && found.stdout.split(/\r?\n/).includes(String(pid))
- }
- if (platform() !== 'linux') return false
- // No lsof: the listening socket's inode from /proc/net/tcp, then whether `pid` holds it.
- try {
- const local = `0100007F:${port.toString(16).toUpperCase().padStart(4, '0')}`
- const inodes = (await fs.readFile('/proc/net/tcp', 'utf8'))
- .split('\n')
- .map((l) => l.trim().split(/\s+/))
- .filter((f) => f[1] === local && f[3] === '0A')
- .map((f) => `socket:[${f[9]}]`)
- if (inodes.length === 0) return false
- for (const fd of await fs.readdir(`/proc/${pid}/fd`)) {
- const link = await fs.readlink(`/proc/${pid}/fd/${fd}`).catch(() => '')
- if (inodes.includes(link)) return true
- }
- } catch {}
- return false
-}
-
async function healthOf(baseURL: string): Promise<{ computerId?: string } | null> {
try {
const res = await fetch(`${baseURL}/health`, { signal: AbortSignal.timeout(1000) })
@@ -184,27 +42,6 @@ async function healthOf(baseURL: string): Promise<{ computerId?: string } | null
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
-/** What `codync-host info --json` prints. */
-interface RemoteInfo {
- name: string
- computerId: string
- signKey: string
- boxKey?: string | null
- token: string
- running: boolean
-}
-
-function parseInfo(text: string): RemoteInfo | null {
- try {
- const v = JSON.parse(text) as Partial<RemoteInfo>
- return typeof v.name === 'string' && typeof v.computerId === 'string' && typeof v.signKey === 'string' && typeof v.token === 'string' && typeof v.running === 'boolean'
- ? (v as RemoteInfo)
- : null
- } catch {
- return null
- }
-}
-
// MARK: the manager
type Outcome = { kind: 'attached' } | { kind: 'stop'; status: SSHStatus } | { kind: 'retry'; message: string }
@@ -247,7 +84,7 @@ class SSHComputers {
async connectAll() {
// Before this copy has tunnels of its own, so only leftovers from an earlier copy match.
- if (this.tunnels.size === 0 && this.tasks.size === 0) await killOrphanTunnels()
+ if (this.tunnels.size === 0 && this.tasks.size === 0) await killOrphanTunnels(dataDir)
for (const p of this.profiles) if (!this.tasks.has(p.id) && !this.tunnels.has(p.id)) this.connect(p.id)
}
@@ -304,7 +141,7 @@ class SSHComputers {
if (this.status.get(id)?.kind !== 'confirmHostKey' || !lines) return
try {
await fs.mkdir(dataDir, { recursive: true, mode: 0o700 })
- await fs.appendFile(join(dataDir, 'ssh_known_hosts'), lines.join('\n') + '\n', { mode: 0o600 })
+ await fs.appendFile(codyncKnownHosts(dataDir), lines.join('\n') + '\n', { mode: 0o600 })
} catch (e) {
return this.setStatus(id, { kind: 'failed', message: `Couldn't save the host key: ${e instanceof Error ? e.message : String(e)}` })
}
@@ -344,7 +181,7 @@ class SSHComputers {
const id = profile.id
const stop = (status: SSHStatus): Outcome => ({ kind: 'stop', status })
const idle = stop({ kind: 'idle' })
- const problem = validate(profile)
+ const problem = missingTools() ?? validate(profile)
if (problem) return stop({ kind: 'failed', message: problem })
this.setStatus(id, { kind: 'connecting', step: 'Reading SSH settings…' })
const config = await run(SSH, resolveArguments(profile))
@@ -354,13 +191,13 @@ class SSHComputers {
const name = knownHostsName(resolved)
// Host key (never by reading ssh's error text).
- if ((await this.recordedKeys(name)).size === 0) {
+ const recorded = await this.recordedKeys(name)
+ if (recorded.size === 0) {
if (usesProxy(resolved)) {
return stop({ kind: 'failed', message: `${profile.host} goes through a jump host. Connect once with ssh in Terminal to confirm its host key, then try again.` })
}
this.setStatus(id, { kind: 'connecting', step: 'Reading the host key…' })
- const scan = await run(KEYSCAN, keyscanArguments(resolved))
- const lines = knownHostsLines(scan.stdout, name)
+ const lines = knownHostsLines(await scanHostKeys(resolved), name)
if (lines.length === 0) return { kind: 'retry', message: `Can't reach ${resolved.hostname}:${resolved.port}.` }
const prints = await run(KEYGEN, ['-l', '-f', '-'], lines.join('\n') + '\n')
const fingerprints = prints.stdout.split(/\r?\n/).filter(Boolean)
@@ -374,8 +211,10 @@ class SSHComputers {
if (token.cancelled) return idle
if (result.status === 255) {
if (authRefused(result.stderr)) return stop({ kind: 'failed', message: signInRefused(profile) })
- if (!usesProxy(resolved)) {
- const current = hostKeys((await run(KEYSCAN, keyscanArguments(resolved))).stdout)
+ // Windows reads only the one key the host presents, which needn't be the pinned key's type.
+ if (!usesProxy(resolved) && process.platform !== 'win32') {
+ const scan = await run(KEYSCAN, keyscanArguments(resolved))
+ const current = hostKeys(scan.stdout)
// Only plain host keys can be compared: a `@cert-authority` key is never what keyscan returns.
const pinned = await this.recordedKeys(name, false)
if (current.size > 0 && pinned.size > 0 && ![...current].some((k) => pinned.has(k))) {
@@ -429,7 +268,7 @@ class SSHComputers {
}
// /health is public, so the answer alone doesn't prove it came through ssh: another
// local user could have taken the port. Only a listener ssh owns gets the token.
- const listens = child.pid !== undefined && (await sshListens(child.pid, port))
+ const listens = child.pid !== undefined ? await sshListens(child.pid, port) : false
// Disconnected, removed or edited meanwhile: this attempt must not register its tunnel.
if (token.cancelled) {
child.kill()
@@ -473,7 +312,7 @@ class SSHComputers {
let done = false
let child: ChildProcess
try {
- child = spawn(SSH, tunnelArguments(profile, localPort, home, dataDir), { stdio: ['ignore', 'ignore', 'pipe'] })
+ child = spawn(SSH, tunnelArguments(profile, localPort, home, dataDir), { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })
} catch {
return null
}
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 83eda7de..ee23007d 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -394,7 +394,7 @@ function SSHProfileEditor({ profile: initial, isNew }: { profile: SSHProfile; is
<div className="settings-row">
<span>Key</span>
<Spacer />
- <Text tone="secondary">{profile.identityFile?.split('/').pop() ?? tr(`ssh-agent / SSH config`)}</Text>
+ <Text tone="secondary">{profile.identityFile?.split(/[\\/]/).pop() ?? tr(`ssh-agent / SSH config`)}</Text>
<IconButton
title="Choose key file"
icon="key"
diff --git a/apps/desktop/src/shared/ssh-command.test.ts b/apps/desktop/src/shared/ssh-command.test.ts
index c064e9b2..c85b13b9 100644
--- a/apps/desktop/src/shared/ssh-command.test.ts
+++ b/apps/desktop/src/shared/ssh-command.test.ts
@@ -177,9 +177,9 @@ for (const [preferred, fallback] of [
test('each copy of the app clears only its own leftover tunnels', () => {
const tunnel = (dir: string) => ['/usr/bin/ssh', ...tunnelArguments(profile, 19333, '/Users/me', dir)].join(' ')
- const dev = new RegExp(orphanTunnelPattern('/Users/me/.codync-dev'))
+ const dev = new RegExp(orphanTunnelPattern('/usr/bin/ssh', '/Users/me/.codync-dev'))
assert.match(tunnel('/Users/me/.codync-dev'), dev)
assert.doesNotMatch(tunnel('/Users/me/.codync-dev-feat-x'), dev)
assert.doesNotMatch(tunnel('/Users/me/xcodync-dev'), dev)
- assert.doesNotMatch(tunnel('/Users/me/.codync-dev'), new RegExp(orphanTunnelPattern('/Users/me/.codync-dev-feat-x')))
+ assert.doesNotMatch(tunnel('/Users/me/.codync-dev'), new RegExp(orphanTunnelPattern('/usr/bin/ssh', '/Users/me/.codync-dev-feat-x')))
})
diff --git a/apps/desktop/src/shared/ssh-platform.test.ts b/apps/desktop/src/shared/ssh-platform.test.ts
new file mode 100644
index 00000000..bded7c40
--- /dev/null
+++ b/apps/desktop/src/shared/ssh-platform.test.ts
@@ -0,0 +1,91 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import test from 'node:test'
+import { knownHostsFiles, ownsWindowsTunnel, presentedKeyArguments, tunnelArguments } from '../main/ssh-command.ts'
+import { listenerCommand, run, sshListens, sshTools } from '../main/ssh-process.ts'
+import { isAbsoluteKeyPath, validate } from '../main/ssh-profile.ts'
+import type { SSHProfile } from './ssh.ts'
+
+const profile: SSHProfile = { id: 'test', host: 'test-host', user: null, port: null, identityFile: null, remotePort: 19222, computerId: null, name: '' }
+
+test('Windows uses native OpenSSH and normalizes quoted known_hosts paths', async () => {
+ const tools = sshTools('win32', 'C:\\Windows')
+ assert.equal(tools.ssh, 'C:\\Windows\\System32\\OpenSSH\\ssh.exe')
+ assert.equal(tools.keygen, 'C:\\Windows\\System32\\OpenSSH\\ssh-keygen.exe')
+ assert.equal(tools.keyscan, 'C:\\Windows\\System32\\OpenSSH\\ssh-keyscan.exe')
+ assert.equal(sshTools('darwin').ssh, '/usr/bin/ssh')
+ assert.equal(sshTools('linux').ssh, '/usr/bin/ssh')
+ const home = 'C:\\Users\\Test User'
+ assert.deepEqual(knownHostsFiles(home), ['C:/Users/Test User/.ssh/known_hosts', 'C:/Users/Test User/.codync/ssh_known_hosts'])
+ const args = tunnelArguments(profile, 19333, home)
+ const result = await run(sshTools().ssh, ['-G', '-F', process.platform === 'win32' ? 'NUL' : '/dev/null', ...args])
+ assert.equal(result.status, 0, result.stderr)
+ assert.match(result.stdout, /userknownhostsfile .*C:\/Users\/Test User\/\.ssh\/known_hosts.*C:\/Users\/Test User\/\.codync\/ssh_known_hosts/)
+ assert.match(result.stdout, /stricthostkeychecking (true|yes)/)
+ assert.match(result.stdout, /forwardagent no/)
+ assert.match(result.stdout, /localforward (?:\[)?127\.0\.0\.1(?:\])?:19333 (?:\[)?127\.0\.0\.1(?:\])?:19222/)
+})
+
+test('Windows host key scan files the presented key in a scratch known_hosts and never signs in', async () => {
+ const resolved = {
+ hostname: '127.0.0.1', port: 2222, hostKeyAlias: null, proxyJump: null, proxyCommand: null,
+ hostKeyAlgorithms: 'rsa-sha2-512,rsa-sha2-256', kexAlgorithms: 'curve25519-sha256',
+ }
+ const args = presentedKeyArguments(resolved, 'C:\\Users\\Test User\\Temp\\known_hosts')
+ const result = await run(sshTools().ssh, ['-G', ...args])
+ assert.equal(result.status, 0, result.stderr)
+ assert.match(result.stdout, /^userknownhostsfile C:\/Users\/Test User\/Temp\/known_hosts$/m)
+ assert.match(result.stdout, /^globalknownhostsfile C:\/Users\/Test User\/Temp\/known_hosts$/m)
+ assert.match(result.stdout, /^stricthostkeychecking accept-new$/m)
+ assert.match(result.stdout, /^preferredauthentications none$/m)
+ assert.match(result.stdout, /^batchmode yes$/m)
+ assert.match(result.stdout, /^port 2222$/m)
+ assert.match(result.stdout, /^hostkeyalgorithms rsa-sha2-512,rsa-sha2-256$/m)
+ assert.match(result.stdout, /^kexalgorithms curve25519-sha256$/m)
+})
+
+test('key selection accepts native absolute paths and rejects drive-relative paths', () => {
+ for (const path of ['C:\\Users\\Test User\\key.pub', 'D:/SSH/key', '\\\\server\\share\\key']) assert.equal(isAbsoluteKeyPath(path, 'win32'), true, path)
+ for (const path of ['key', 'C:key', '\\key', '/key', '~/key']) assert.equal(isAbsoluteKeyPath(path, 'win32'), false, path)
+ assert.equal(isAbsoluteKeyPath('/Users/test/key', 'darwin'), true)
+ const root = mkdtempSync(join(tmpdir(), 'codync-key-'))
+ try {
+ const key = join(root, 'key with spaces.pub')
+ writeFileSync(key, 'public key fixture')
+ assert.equal(validate({ ...profile, identityFile: key }), null)
+ assert.match(validate({ ...profile, identityFile: root })!, /doesn't exist/)
+ assert.match(validate({ ...profile, identityFile: join(root, 'missing') })!, /doesn't exist/)
+ } finally { rmSync(root, { recursive: true, force: true }) }
+})
+
+test('Windows orphan cleanup recognizes only this variant and its native ssh executable', () => {
+ const binary = 'C:\\Windows\\System32\\OpenSSH\\ssh.exe'
+ const dir = 'C:\\Users\\Test User\\.codync'
+ const options = String.raw`"UserKnownHostsFile=\"C:/Users/Test User/.ssh/known_hosts\" \"C:/Users/Test User/.codync/ssh_known_hosts\""`
+ const owned = { ProcessId: 123, ExecutablePath: binary, CommandLine: `"${binary}" -N -T -o ${options} -L 127.0.0.1:19333:127.0.0.1:19222 -- test-host` }
+ assert.equal(ownsWindowsTunnel(owned, binary, dir), true)
+ assert.equal(ownsWindowsTunnel(owned, binary, `${dir}-dev`), false)
+ assert.equal(ownsWindowsTunnel(owned, binary, dir.replace('Test User', 'Other User')), false)
+ assert.equal(ownsWindowsTunnel({ ...owned, ExecutablePath: 'C:\\Other\\ssh.exe' }, binary, dir), false)
+ assert.equal(ownsWindowsTunnel({ ...owned, CommandLine: owned.CommandLine.replace(' -N ', ' ') }, binary, dir), false)
+ assert.equal(ownsWindowsTunnel({ ...owned, CommandLine: owned.CommandLine.replace('ssh_known_hosts', 'ssh_known_hosts_other') }, binary, dir), false)
+ assert.equal(ownsWindowsTunnel({ ...owned, CommandLine: null }, binary, dir), false)
+})
+
+test('listener ownership accepts the listening process and rejects another process', async () => {
+ const server = createServer()
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ try {
+ const address = server.address()
+ assert.ok(address && typeof address === 'object')
+ const ownListener = await sshListens(process.pid, address.port)
+ const otherListener = await sshListens(process.pid === 1 ? 2 : 1, address.port)
+ assert.equal(ownListener, true)
+ assert.equal(otherListener, false)
+ } finally { await new Promise<void>((resolve) => server.close(() => resolve())) }
+ assert.throws(() => listenerCommand(123, -1))
+ assert.throws(() => listenerCommand(NaN, 19222))
+})
diff --git a/apps/desktop/tools/ssh-e2e.mjs b/apps/desktop/tools/ssh-e2e.mjs
index 99b85956..bc27afd8 100644
--- a/apps/desktop/tools/ssh-e2e.mjs
+++ b/apps/desktop/tools/ssh-e2e.mjs
@@ -1,19 +1,20 @@
// Read-only integration checks against a real SSH host. No bots or settings are changed.
// node --experimental-strip-types tools/ssh-e2e.mjs <ssh-alias>
import assert from 'node:assert/strict'
-import { spawn, spawnSync } from 'node:child_process'
+import { spawn } from 'node:child_process'
import { once } from 'node:events'
import { createServer } from 'node:net'
import { homedir } from 'node:os'
import { setTimeout as delay } from 'node:timers/promises'
import { infoArguments, tunnelArguments } from '../src/main/ssh-command.ts'
+import { run, SSH, sshListens } from '../src/main/ssh-process.ts'
const host = process.argv[2]
if (!host || host.startsWith('-') || !/^[A-Za-z0-9._-]+$/.test(host)) {
throw new Error('Pass the SSH alias of a trusted, already configured test computer.')
}
const profile = {
- id: 'e2e', host, user: null, port: null, identityFile: null,
+ id: 'e2e', host, user: process.argv[3] ?? null, port: null, identityFile: process.argv[4] ?? null,
remotePort: 19222, computerId: null, name: 'SSH integration test',
}
const children = new Set()
@@ -26,10 +27,6 @@ async function listeningServer() {
return { server, port: server.address().port }
}
const close = (server) => new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()))
-const listeners = (port, pid) => spawnSync('/usr/sbin/lsof', [
- '-a', '-n', '-P', ...(pid ? ['-p', String(pid)] : []),
- `[email protected]:${port}`, '-sTCP:LISTEN', '-t',
-], { encoding: 'utf8' }).stdout.trim()
async function healthThrough(base, child) {
for (let attempt = 0; attempt < 50; attempt++) {
@@ -54,7 +51,7 @@ async function api(base, token, method, body = {}) {
async function verifyEvents(base, token) {
const controller = new AbortController()
- const timer = setTimeout(() => controller.abort(), 5000)
+ const timer = setTimeout(() => controller.abort(), 25_000)
try {
const response = await fetch(`${base}/events?since=0&client=codync-ssh-e2e`, {
headers: { Authorization: `Bearer ${token}` }, signal: controller.signal,
@@ -63,6 +60,9 @@ async function verifyEvents(base, token) {
const reader = response.body.getReader()
const decoder = new TextDecoder()
let pending = ''
+ let revision = null
+ let caughtUp = 0
+ const bots = new Map()
for (;;) {
const { value, done } = await reader.read()
assert.equal(done, false, 'SSE must deliver hello before closing')
@@ -71,9 +71,16 @@ async function verifyEvents(base, token) {
while ((newline = pending.indexOf('\n')) !== -1) {
const line = pending.slice(0, newline)
pending = pending.slice(newline + 1)
- if (line.startsWith('data:') && JSON.parse(line.slice(5)).type === 'hello') {
+ if (line.startsWith('data:')) {
+ const event = JSON.parse(line.slice(5))
+ if (event.type === 'hello') revision = event.rev
+ else caughtUp = Math.max(caughtUp, event.rev ?? 0)
+ if (event.type === 'bot') bots.set(event.bot.id, event.bot)
+ }
+ // A keepalive is emitted only after the ready catch-up has drained.
+ if (revision !== null && (caughtUp >= revision || line.startsWith(':'))) {
await reader.cancel()
- return
+ return [...bots.values()].filter((bot) => !bot.deleted)
}
}
}
@@ -83,7 +90,7 @@ async function verifyEvents(base, token) {
}
}
-const result = spawnSync('/usr/bin/ssh', infoArguments(profile, homedir()), { encoding: 'utf8', timeout: 20_000 })
+const result = await run(SSH, infoArguments(profile, homedir()))
assert.equal(result.status, 0, result.stderr)
const info = JSON.parse(result.stdout)
assert.equal(info.running, true)
@@ -92,7 +99,7 @@ console.log(`PASS remote discovery: host version ${info.version}`)
for (let round = 1; round <= 2; round++) {
const { server, port } = await listeningServer()
await close(server)
- const child = spawn('/usr/bin/ssh', tunnelArguments(profile, port, homedir()), { stdio: ['ignore', 'ignore', 'pipe'] })
+ const child = spawn(SSH, tunnelArguments(profile, port, homedir()), { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true })
children.add(child)
let error = ''
child.stderr.on('data', (data) => { error = (error + data).slice(-4096) })
@@ -101,7 +108,8 @@ for (let round = 1; round <= 2; round++) {
try {
const health = await healthThrough(base, child)
assert.equal(health.computerId, info.computerId, error)
- assert.equal(listeners(port, child.pid), String(child.pid))
+ const ownsListener = await sshListens(child.pid, port)
+ assert.equal(ownsListener, true)
const denied = await api(base, null, 'hello')
assert.equal(denied.status, 401)
await denied.body?.cancel()
@@ -109,24 +117,30 @@ for (let round = 1; round <= 2; round++) {
assert.equal(helloResponse.status, 200)
const hello = await helloResponse.json()
assert.equal(hello.computerId, info.computerId)
- const syncResponse = await api(base, info.token, 'sync', { since: 0 })
- assert.equal(syncResponse.status, 200)
- const sync = await syncResponse.json()
- assert.ok(Array.isArray(sync.bots))
- await verifyEvents(base, info.token)
- console.log(`PASS round ${round}: owned listener, host identity, authentication, ${sync.bots.length} bots, SSE hello`)
+ const bots = await verifyEvents(base, info.token)
+ const bot = bots.find((b) => !b.parentBotId)
+ if (bot) {
+ const historyResponse = await api(base, info.token, 'history', { botId: bot.id, limit: 1 })
+ assert.equal(historyResponse.status, 200)
+ const history = await historyResponse.json()
+ assert.ok(Array.isArray(history.entries))
+ }
+ const historyCheck = bot ? 'history' : 'history skipped (no bot on that computer)'
+ console.log(`PASS round ${round}: owned listener, host identity, authentication, ${bots.length} bots, SSE catch-up, ${historyCheck}`)
} finally {
child.kill()
await exited
children.delete(child)
}
- assert.equal(listeners(port), '')
+ const released = createServer()
+ await new Promise((resolve, reject) => { released.once('error', reject); released.listen(port, '127.0.0.1', resolve) })
+ await close(released)
console.log(`PASS round ${round}: disconnect releases the listener`)
}
const { server, port } = await listeningServer()
try {
- const collision = spawnSync('/usr/bin/ssh', tunnelArguments(profile, port, homedir()), { encoding: 'utf8', timeout: 15_000 })
+ const collision = await run(SSH, tunnelArguments(profile, port, homedir()))
assert.notEqual(collision.status, 0)
assert.match(collision.stderr, /Address already in use|cannot listen to port/)
assert.equal(server.listening, true)
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 8f4bfc90..fb5cf165 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -69,9 +69,13 @@ The TUI connects to one host at a time, so it keeps its single roster.
filter distinguishes connecting, attention, disconnected and opening states and
keeps local recovery actions reachable when a remote computer is already online.
iOS uses direct/encrypted host connections, and the TUI connects to one host;
- neither manages desktop SSH profiles. Windows exposes the same profile UI, but
- the tunnel backend still uses `/usr/bin/ssh*` and Unix socket ownership checks;
- Windows tunnel support has not been implemented.
+ neither manages desktop SSH profiles. Windows uses the native OpenSSH Client
+ in `%SystemRoot%\System32\OpenSSH` and checks the listener's owning process
+ through `Get-NetTCPConnection` before sending the host token. Install OpenSSH
+ Client in Windows Optional features if it is missing. Keys stay in the local
+ SSH agent or selected key file, including a public key that selects a 1Password
+ agent identity. Windows drive and UNC key paths are supported. Disconnect and
+ quit close the tunnel; startup removes leftover tunnels for this app variant.
- **Icons**: SF Symbols may only ship in apps for Apple platforms, so the masks are generated
on macOS at build time and never committed; Linux draws the closest Lucide icons.
- **On-device speech** is macOS only; Linux calls use OpenAI or Gemini on the user's key.
@@ -86,8 +90,7 @@ The TUI connects to one host at a time, so it keeps its single roster.
Agents start through `cmd /c` (`host/src/shell.rs`), setup terminals use ConPTY
(`portable-pty`), and the vault key lives in Credential Manager. Not on Windows yet: Remote
screen and the `computer` MCP (no screen helper), on-device speech, the Claude Code status
- line hook (usage still comes from `claude -p /usage`, ACP and each agent's own report), SSH tunnels to other
- computers, and `curl | bash` installers (npm installs and Claude Code's PowerShell installer
+ line hook (usage still comes from `claude -p /usage`, ACP and each agent's own report), and `curl | bash` installers (npm installs and Claude Code's PowerShell installer
work). The tray icon is the app icon; left-click opens the chat, right-click the menu.
- **Remote screen** on macOS registers `CodyncScreen.app` (built from the Xcode `Screen` target)
as an SMAppService agent; Linux starts its helper from the host, as before.
@@ -115,11 +118,13 @@ child must own the listening socket and stay alive until disconnect. This keeps
`ControlMaster` / `ControlPersist` in the user's config from transferring the
forward to a shared master that outlives the app.
-For a read-only macOS integration check against an already trusted SSH computer,
+For a read-only integration check against an already trusted SSH computer,
run `node --experimental-strip-types tools/ssh-e2e.mjs <ssh-alias>` from
`apps/desktop`. It checks discovery, listener ownership, host identity, API
-authentication and sync, SSE, disconnect/reconnect, and an occupied local port.
+authentication, bot sync and history, SSE, disconnect/reconnect, and an occupied local port.
It uses port 19222 on the remote computer and leaves bots and settings unchanged.
+An explicit user and identity file can follow the alias; Windows uses its native
+OpenSSH Client and listener ownership check, just like the app.
```sh
cd apps/desktop
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index ec57bf25..e1a9a753 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -225,15 +225,20 @@ revealed its code.
SSH computers use the system OpenSSH (`apps/desktop/src/main/ssh.ts`): `ssh -G` to
resolve the target, `ssh-keygen -F` against `~/.ssh/known_hosts` and
-`~/.codync/ssh_known_hosts`, a fingerprint confirmation on first contact (no proxy),
+`~/.codync/ssh_known_hosts`, a fingerprint confirmation on first contact (no proxy; the key comes
+from `ssh-keyscan`, on Windows from `ssh` itself, since its `ssh-keyscan` can't negotiate with current servers),
`codync-host info --json` for the identity and loopback token, then
`ssh -N -L 127.0.0.1:<free port>:127.0.0.1:<remote port>` with keepalive and backoff.
A changed host key or a different computer ID blocks the connection. Sign-in is key or
ssh-agent only (`BatchMode`: nothing prompts for a password or passphrase); a refused key
stops with a message instead of retrying. The remote command searches Homebrew,
`~/.local/bin` and the Mac app bundle for `codync-host` too, since `sh -l` doesn't read
-`~/.zprofile`. At launch the app kills tunnels a crashed or force-quit copy left behind
-(`pkill` on the `.codync/ssh_known_hosts` argument only Codync's tunnels carry).
+`~/.zprofile`. At launch the app removes tunnels a crashed or force-quit copy left behind.
+Unix uses `pkill` with this app's exact data directory and `ssh_known_hosts` path,
+so development sandboxes stay separate. Windows inspects native OpenSSH
+processes and terminates only tunnels whose executable and quoted known-hosts
+path match this app. It uses Windows' OpenSSH Client feature and the device's
+existing SSH config and agent.
*Over SSH* also offers the `Host` entries of `~/.ssh/config` and the files it `Include`s
(`main/ssh-config.ts`, parser in `shared/ssh-config.ts`): named hosts only, not patterns, `Match`
diff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.md
index af1df883..025057e6 100644
--- a/docs/guides/linux-servers.md
+++ b/docs/guides/linux-servers.md
@@ -37,7 +37,7 @@ The phone connects over the encrypted device channel. The pairing link lists onl
- **Tailscale (recommended for VMs):** install Tailscale on the VM and on the phone, then `codync-host pair`. The Tailscale name comes first in the link. You don't need to open port 19222 in the cloud firewall.
- **Codync relay (on by default):** a release host connects to the production cloud (`https://api.codync.dev`), so a paired phone reaches it from anywhere with nothing to open. `codync-host cloud --disable` turns it off; `codync-host cloud --url https://relay.example.com --token` points it at a [private relay](../../private-relay/README.md) you run yourself (the token is read without echo or from stdin); `CODYNC_CLOUD_URL=https://…` points the host at a Codync cloud you run yourself (see [environments](environments-and-deployment.md)).
- **Your own HTTPS reverse proxy:** forward only `/channel` (WebSocket upgrade) at the root of a hostname to the host; don't forward `/api`, `/events`, `/term` or `/oauth`: through a local proxy every request looks like it comes from this computer, so the loopback-only checks no longer protect them. Then set `CODYNC_EXTERNAL_URL=https://codync.example.com` (comma-separated for several) in the host's environment: `systemctl --user edit codync-host`, add `[Service]` and `Environment=CODYNC_EXTERNAL_URL=https://codync.example.com`, then `systemctl --user restart codync-host`. The host advertises those URLs first, in the pairing link and on every connection, so the phone keeps them (a phone keeps only the addresses the host advertises). Under your own supervisor, `CODYNC_EXTERNAL_URL=… codync-host serve --bind 127.0.0.1` keeps the host on loopback behind the proxy. The phone dials `<url>/channel?v=1`. Opening `/channel` in a browser or with `curl` gets `400` (no WebSocket upgrade), and an upgrade without `?v=1` gets `426` `upgradeRequired`: that means the proxy works. A working proxy answers the phone's upgrade with `101`.
-- **Desktop app over SSH:** the desktop app (macOS or Linux) can attach an SSH computer and tunnel to its loopback API ([Accounts and SSH](accounts-and-ssh.md)). From any terminal: `ssh -L 19222:127.0.0.1:19222 vm`, then `codync-host tui` locally.
+- **Desktop app over SSH:** the desktop app (macOS, Linux or Windows) can attach an SSH computer and tunnel to its loopback API ([Accounts and SSH](accounts-and-ssh.md)). From any terminal: `ssh -L 19222:127.0.0.1:19222 vm`, then `codync-host tui` locally.
The host listens on `0.0.0.0:19222`. The local API (`/api/*`, `/events`, terminals; bearer token) answers **loopback callers only**, so a public address never exposes it. From outside, only `/health` (host id, computer id, version, environment; the binary path and hash, `busy` and `updateRequested` go to loopback callers only), local routine webhooks (`/hooks/routines/{id}`, which need the routine's key) and the end-to-end encrypted device channel answer, and the channel only serves devices holding this host's pairing keys. Keep 19222 closed in the cloud firewall anyway unless you deliberately pair over a VPN or private network.
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 27543615..5a3ecd43 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -570,7 +570,7 @@ The following implemented clarifications take precedence over the original contr
- **Mailbox 重試**:沿用同一個 `clientNonce`,但每次重新 seal。
- **ACL**:列表中 `grant` 為 null 的已封鎖 dk 會被解除封鎖;被封鎖的 dk 仍可開 pairing socket。
- **帳號裝置 mailbox**:第一次拉取 state 之前收到的 item 先保留、不 ack。
-- **SSH forward**:以 `lsof` 確認本機 listener 屬於我們啟動的 `ssh`。
+- **SSH forward**:確認本機 listener 屬於我們啟動的 `ssh` 子行程才送出 host token:macOS/Linux 用 `lsof` 或 `/proc`,Windows 用 `Get-NetTCPConnection`。
- **取消 access request**:iOS SAS sheet 有取消按鈕(`DELETE /v1/access-requests/{id}`)。
## 15. Limits and risks
diff --git a/web/app/components/computers.tsx b/web/app/components/computers.tsx
index 2110ec80..7cffa091 100644
--- a/web/app/components/computers.tsx
+++ b/web/app/components/computers.tsx
@@ -89,8 +89,8 @@ export default function Computers() {
</h2>
<p className="mt-5 max-w-[32rem] text-lg leading-relaxed text-neutral-400">
Add a server, a cloud VM or another desktop by its SSH alias. Its bots sit beside your own, grouped by
- computer, and a new bot can live on any of them. It needs codync-host on that machine; the Mac and Linux
- apps connect over SSH.
+ computer, and a new bot can live on any of them. It needs codync-host on that machine; the desktop app on Mac,
+ Windows and Linux connects over SSH.
</p>
<Points points={points} />
</Reveal>
diff --git a/web/app/components/questions.tsx b/web/app/components/questions.tsx
index d49d8379..0acf26f4 100644
--- a/web/app/components/questions.tsx
+++ b/web/app/components/questions.tsx
@@ -29,7 +29,7 @@ const questions: [string, string][] = [
],
[
"Which computers can run it?",
- "A Mac, a Windows PC, or a Linux desktop or headless server. The iPhone app and the terminal UI over SSH talk to the same host, and the Mac and Linux apps add other machines over SSH, with their bots in the same sidebar.",
+ "A Mac, a Windows PC, or a Linux desktop or headless server. The iPhone app and the terminal UI over SSH talk to the same host, and the desktop app on Mac, Windows and Linux adds other machines over SSH, with their bots in the same sidebar.",
],
[
"What happens when my agent runs out of usage?",
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index 4178759a..30f9a67b 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -58,11 +58,11 @@ CODYNC_TOKEN=$(ssh your-server 'cat ~/.codync/token') codync-host tui --url http
## Use the desktop app over SSH
-The desktop app on a Mac or Linux desktop can run the server's bots alongside its own. Open **Settings → Computers**, and under **Over SSH** choose **Add SSH computer**. Fill in the host (an SSH alias or hostname) and, if your SSH config doesn't already set them, the user, port and key. Sign-in must work with a key or ssh-agent: nothing prompts for a password. On the first connection, compare the host key fingerprint with the server's, then choose **Trust and connect**.
+The desktop app on macOS, Linux or Windows can run the server's bots alongside its own. Open **Settings → Computers**, and under **Over SSH** choose **Add SSH computer**. Fill in the host (an SSH alias or hostname) and, if your SSH config doesn't already set them, the user, port and key. Sign-in must work with a key or ssh-agent: nothing prompts for a password. On the first connection, compare the host key fingerprint with the server's, then choose **Trust and connect**.
From that computer's card you can also show its pairing code, turn the relay on or off, and choose **Add to account** to put the server in your Codync account.
-The desktop app on Windows doesn't connect to SSH computers.
+On Windows, enable **OpenSSH Client** in **Windows Settings → Optional features** if it is missing. Codync uses the Windows SSH config, keys and agent; keys stay on that computer.
## Reach it from your phone
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index 3fba5344..467913bd 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -116,7 +116,9 @@ The host puts these URLs first in the pairing code and sends its current address
## SSH computers in the desktop app
-The desktop app on macOS and Linux can also run bots on another computer you reach with SSH, such as a Linux server or a Mac mini. Open **Settings → Computers**, and under **Over SSH** choose **Add SSH computer**. The other computer needs `codync-host` installed. Codync opens an SSH tunnel to that computer's host using your SSH config and keys (or ssh-agent); your keys stay on the computer running the desktop app. On the first connection, check the host key fingerprint, then choose **Trust and connect**.
+The desktop app on macOS, Linux and Windows can also run bots on another computer you reach with SSH, such as a Linux server or a Mac mini. Open **Settings → Computers**, and under **Over SSH** choose **Add SSH computer**. The other computer needs `codync-host` installed. Codync opens an SSH tunnel to that computer's host using your SSH config and keys (or ssh-agent); your keys stay on the computer running the desktop app. On the first connection, check the host key fingerprint, then choose **Trust and connect**.
+
+On Windows, enable **OpenSSH Client** in **Windows Settings → Optional features** if it is missing. Codync uses Windows' native OpenSSH tools and your Windows SSH config and agent.
Codync can also list the computers in your SSH config. The first time you open **Over SSH**, it asks whether it may read `~/.ssh/config`. Choose **Allow**, and each host in it that you haven't added yet shows up with a **+** to add it. Nothing is sent anywhere, and nothing connects until you add a host. If you chose **Not now**, the magnifying glass next to **Over SSH** turns the list on.