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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(desktop): connect to bundled SSH hosts reliably
leepokai8f766d0b1476
diff --git a/apps/desktop/src/main/ssh-command.ts b/apps/desktop/src/main/ssh-command.tsnew file mode 100644index 00000000..134b65f1--- /dev/null+++ b/apps/desktop/src/main/ssh-command.ts@@ -0,0 +1,50 @@+import type { SSHProfile } from '../shared/ssh.ts'++// Preserve the login shell's PATH, then try the supported installers and Mac app layouts.+// Resources is the Electron bundle; MacOS keeps older native app installs reachable.+const REMOTE_PATH = '$PATH:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.local/bin:/Applications/Codync.app/Contents/Resources:/Applications/Codync.app/Contents/MacOS'++/** The caller validates the port before constructing the remote shell command. */+export const remoteInfoCommand = (port: number) =>+ `sh -lc 'PATH="${REMOTE_PATH}" codync-host info --json --port ${port}'`++export const knownHostsFiles = (h: string) => [`${h}/.ssh/known_hosts`, `${h}/.codync/ssh_known_hosts`]++/** ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes. */+export const hostKeyOptions = (h: string) => [+ '-o', 'UserKnownHostsFile=' + knownHostsFiles(h).map((f) => `"${f}"`).join(' '),+ '-o', 'StrictHostKeyChecking=yes',+]++function targetOptions(p: SSHProfile) {+ const args: string[] = []+ if (p.port !== null) args.push('-p', String(p.port))+ if (p.identityFile !== null) args.push('-i', p.identityFile)+ if (p.user !== null) args.push('-l', p.user)+ return args+}++export function resolveArguments(p: SSHProfile) {+ const args = ['-G']+ if (p.port !== null) args.push('-p', String(p.port))+ if (p.user !== null) args.push('-l', p.user)+ return [...args, '--', p.host]+}++/** The remote command is fixed; only the validated port number goes into it. */+export const infoArguments = (p: SSHProfile, h: string) => [+ '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'ForwardAgent=no', '-o', 'ForwardX11=no',+ ...hostKeyOptions(h), ...targetOptions(p),+ '--', p.host, remoteInfoCommand(p.remotePort),+]++export const tunnelArguments = (p: SSHProfile, localPort: number, h: string) => [+ '-N', '-T', '-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3',+ // A shared master owns the listener and lets this child exit. The app must own+ // its tunnel process to verify the listener and close the forward on disconnect.+ '-S', 'none',+ '-o', 'ForwardAgent=no', '-o', 'ForwardX11=no', '-o', 'BatchMode=yes',+ ...hostKeyOptions(h),+ '-L', `127.0.0.1:${localPort}:127.0.0.1:${p.remotePort}`,+ ...targetOptions(p), '--', p.host,+]diff --git a/apps/desktop/src/main/ssh.ts b/apps/desktop/src/main/ssh.tsindex fbfb6b5e..4098e8d6 100644--- a/apps/desktop/src/main/ssh.ts+++ b/apps/desktop/src/main/ssh.ts@@ -6,6 +6,7 @@ import { homedir, platform } from 'node:os'import { join } from 'node:path'import { app, dialog, ipcMain, type BrowserWindow } from 'electron'import type { SSHAttachment, SSHProfile, SSHState, SSHStatus } from '../shared/ssh'+import { infoArguments, knownHostsFiles, resolveArguments, tunnelArguments } from './ssh-command'// SSH computers (port of the Mac app's SSHTunnel.swift): profiles, host key checks and one// OpenSSH tunnel per connected profile. Arguments are always an argv array, never a shell string.@@ -16,9 +17,6 @@ const KEYSCAN = '/usr/bin/ssh-keyscan'const LSOF = ['/usr/sbin/lsof', '/usr/bin/lsof'].find((p) => existsSync(p)) ?? nullconst home = homedir()-/** Where `codync-host` lives when `sh -l` doesn't see it (Homebrew, install.sh, the Mac app's bundle). */-const REMOTE_PATH = '$PATH:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.local/bin:/Applications/Codync.app/Contents/MacOS'-// MARK: pure helpers/** A reason the profile can't be used, or null. */@@ -40,44 +38,6 @@ export function validate(p: SSHProfile): string | null {return null}-const knownHostsFiles = (h: string) => [`${h}/.ssh/known_hosts`, `${h}/.codync/ssh_known_hosts`]--/** ssh's config tokenizer splits `UserKnownHostsFile` on spaces, so each path carries literal quotes. */-export const hostKeyOptions = (h: string) => [- '-o', 'UserKnownHostsFile=' + knownHostsFiles(h).map((f) => `"${f}"`).join(' '),- '-o', 'StrictHostKeyChecking=yes',-]--function targetOptions(p: SSHProfile) {- const args: string[] = []- if (p.port !== null) args.push('-p', String(p.port))- if (p.identityFile !== null) args.push('-i', p.identityFile)- if (p.user !== null) args.push('-l', p.user)- return args-}--export function resolveArguments(p: SSHProfile) {- const args = ['-G']- if (p.port !== null) args.push('-p', String(p.port))- if (p.user !== null) args.push('-l', p.user)- return [...args, '--', p.host]-}--/** The remote command is fixed; only the validated port number goes into it. */-export const infoArguments = (p: SSHProfile, h: string) => [- '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=10', '-o', 'ForwardAgent=no', '-o', 'ForwardX11=no',- ...hostKeyOptions(h), ...targetOptions(p),- '--', p.host, `sh -lc 'PATH="${REMOTE_PATH}" codync-host info --json --port ${p.remotePort}'`,-]--export const tunnelArguments = (p: SSHProfile, localPort: number, h: string) => [- '-N', '-T', '-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=3',- '-o', 'ForwardAgent=no', '-o', 'ForwardX11=no', '-o', 'BatchMode=yes',- ...hostKeyOptions(h),- '-L', `127.0.0.1:${localPort}:127.0.0.1:${p.remotePort}`,- ...targetOptions(p), '--', p.host,-]-/** 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')diff --git a/apps/desktop/src/shared/ssh-command.test.ts b/apps/desktop/src/shared/ssh-command.test.tsnew file mode 100644index 00000000..953dde0d--- /dev/null+++ b/apps/desktop/src/shared/ssh-command.test.ts@@ -0,0 +1,149 @@+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { test } from 'node:test'+import { infoArguments, remoteInfoCommand, resolveArguments, tunnelArguments } from '../main/ssh-command.ts'+import type { SSHProfile } from './ssh.ts'++// Remap absolute installation directories into an isolated filesystem fixture. Run the+// command inside sh -c so the machine's login scripts cannot supply an installed host.+const locations = [+ '/custom/bin',+ '/opt/homebrew/bin',+ '/usr/local/bin',+ '/home/linuxbrew/.linuxbrew/bin',+ '/user home/.local/bin',+ '/Applications/Codync.app/Contents/Resources',+ '/Applications/Codync.app/Contents/MacOS',+]++function probe(installed: string[]) {+ const root = mkdtempSync(join(tmpdir(), 'codync-ssh-'))+ try {+ for (const location of installed) {+ const directory = join(root, location)+ mkdirSync(directory, { recursive: true })+ const binary = join(directory, 'codync-host')+ writeFileSync(binary, '#!/bin/sh\nprintf "%s\\n" "$0" "$@"\n')+ chmodSync(binary, 0o755)+ }+ const command = remoteInfoCommand(19222)+ .replace(/^sh -lc '/, '').replace(/'$/, '')+ .replace(/:(\/[^:"]+)/g, (_, path: string) => `:${root}${path}`)+ const result = spawnSync('/bin/sh', ['-c', command], {+ encoding: 'utf8',+ env: { HOME: join(root, 'user home'), PATH: join(root, 'custom/bin') },+ })+ return { status: result.status, lines: result.stdout.trim().split('\n'), root }+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+}++for (const location of locations) {+ test(`SSH finds a host installed in ${location}`, { skip: process.platform === 'win32' }, () => {+ const result = probe([location])+ assert.equal(result.status, 0)+ assert.deepEqual(result.lines, [join(result.root, location, 'codync-host'), 'info', '--json', '--port', '19222'])+ })+}++test('SSH preserves the host selected by the remote PATH', { skip: process.platform === 'win32' }, () => {+ const result = probe(locations)+ assert.equal(result.status, 0)+ assert.equal(result.lines[0], join(result.root, 'custom/bin/codync-host'))+})++test('SSH reports command not found when no installation is reachable', { skip: process.platform === 'win32' }, () => {+ assert.equal(probe([]).status, 127)+})++const profile: SSHProfile = {+ id: 'test', host: 'test-mini', user: null, port: null, identityFile: null,+ remotePort: 19222, computerId: null, name: 'Test mini',+}++function withConfig(master: string, run: (config: string, home: string) => void) {+ const root = mkdtempSync(join(tmpdir(), 'codync-ssh-config-'))+ try {+ const config = join(root, 'config')+ writeFileSync(config, `Host test-mini+ HostName 192.0.2.1+ User test-user+ Port 2222+Host *+ ControlMaster ${master}+ ControlPath ${root}/master-%C+ ControlPersist 4h+ ForwardAgent yes+ ForwardX11 yes+ StrictHostKeyChecking no+`)+ run(config, join(root, 'user home'))+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+}++function resolved(config: string, args: string[]) {+ const result = spawnSync('/usr/bin/ssh', ['-G', '-F', config, ...args], { encoding: 'utf8' })+ assert.equal(result.status, 0, result.stderr)+ return new Map(result.stdout.trim().split('\n').map((line) => {+ const at = line.indexOf(' ')+ return [line.slice(0, at), line.slice(at + 1)]+ }))+}++for (const master of ['no', 'auto', 'yes', 'autoask']) {+ test(`managed tunnels own their connection with ControlMaster ${master}`, { skip: process.platform === 'win32' }, () => {+ withConfig(master, (config, home) => {+ const values = resolved(config, tunnelArguments(profile, 19333, home))+ // OpenSSH omits ControlPath entirely for -S none; there is no master to reuse.+ assert.equal(values.get('controlpath'), undefined)+ assert.equal(values.get('hostname'), '192.0.2.1')+ assert.equal(values.get('user'), 'test-user')+ assert.equal(values.get('port'), '2222')+ assert.equal(values.get('forwardagent'), 'no')+ assert.equal(values.get('forwardx11'), 'no')+ assert.equal(values.get('stricthostkeychecking'), 'true')+ assert.equal(values.get('exitonforwardfailure'), 'yes')+ assert.equal(values.get('batchmode'), 'yes')+ assert.equal(values.get('localforward')?.replace(/[\[\]]/g, ''), '127.0.0.1:19333 127.0.0.1:19222')+ assert.ok(values.get('userknownhostsfile')?.includes(`${home}/.ssh/known_hosts`))+ assert.ok(values.get('userknownhostsfile')?.includes(`${home}/.codync/ssh_known_hosts`))+ })+ })+}++for (const kind of ['info', 'tunnel', 'resolve'] as const) {+ test(`${kind} honors explicit user and port overrides`, { skip: process.platform === 'win32' }, () => {+ withConfig('auto', (config, home) => {+ mkdirSync(home)+ const key = join(home, 'key with spaces')+ writeFileSync(key, '')+ const overridden = { ...profile, user: 'override', port: 2201, remotePort: 19444, identityFile: key }+ const args = kind === 'info' ? infoArguments(overridden, home)+ : kind === 'tunnel' ? tunnelArguments(overridden, 19555, home) : resolveArguments(overridden)+ const values = resolved(config, args)+ assert.equal(values.get('user'), 'override')+ assert.equal(values.get('port'), '2201')+ assert.equal(values.get('hostname'), '192.0.2.1')+ if (kind !== 'resolve') assert.equal(values.get('identityfile'), key)+ if (kind === 'tunnel') assert.equal(values.get('localforward')?.replace(/[\[\]]/g, ''), '127.0.0.1:19555 127.0.0.1:19444')+ if (kind === 'info') assert.match(args.at(-1)!, /info --json --port 19444/)+ })+ })+}++for (const [preferred, fallback] of [+ ['/opt/homebrew/bin', '/Applications/Codync.app/Contents/Resources'],+ ['/Applications/Codync.app/Contents/Resources', '/Applications/Codync.app/Contents/MacOS'],+]) {+ test(`SSH prefers ${preferred} over ${fallback}`, { skip: process.platform === 'win32' }, () => {+ const result = probe([preferred, fallback])+ assert.equal(result.status, 0)+ assert.equal(result.lines[0], join(result.root, preferred, 'codync-host'))+ })+}diff --git a/apps/desktop/tools/ssh-e2e.mjs b/apps/desktop/tools/ssh-e2e.mjsnew file mode 100644index 00000000..99b85956--- /dev/null+++ b/apps/desktop/tools/ssh-e2e.mjs@@ -0,0 +1,136 @@+// 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 { 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'++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,+ remotePort: 19222, computerId: null, name: 'SSH integration test',+}+const children = new Set()+process.on('exit', () => { for (const child of children) child.kill() })++async function listeningServer() {+ const server = createServer()+ server.listen(0, '127.0.0.1')+ await once(server, 'listening')+ 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++) {+ assert.equal(child.exitCode, null, 'SSH must stay alive and own its tunnel')+ try {+ const response = await fetch(`${base}/health`, { signal: AbortSignal.timeout(500) })+ if (response.ok) return await response.json()+ } catch {+ // The listener may not yet exist while SSH authenticates.+ }+ await delay(100)+ }+ throw new Error('Tunnel did not become healthy within the startup deadline')+}++async function api(base, token, method, body = {}) {+ return fetch(`${base}/api/${method}`, {+ method: 'POST', body: JSON.stringify(body), signal: AbortSignal.timeout(5000),+ headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },+ })+}++async function verifyEvents(base, token) {+ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), 5000)+ try {+ const response = await fetch(`${base}/events?since=0&client=codync-ssh-e2e`, {+ headers: { Authorization: `Bearer ${token}` }, signal: controller.signal,+ })+ assert.equal(response.status, 200)+ const reader = response.body.getReader()+ const decoder = new TextDecoder()+ let pending = ''+ for (;;) {+ const { value, done } = await reader.read()+ assert.equal(done, false, 'SSE must deliver hello before closing')+ pending += decoder.decode(value, { stream: true })+ let newline+ 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') {+ await reader.cancel()+ return+ }+ }+ }+ } finally {+ clearTimeout(timer)+ controller.abort()+ }+}++const result = spawnSync('/usr/bin/ssh', infoArguments(profile, homedir()), { encoding: 'utf8', timeout: 20_000 })+assert.equal(result.status, 0, result.stderr)+const info = JSON.parse(result.stdout)+assert.equal(info.running, true)+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'] })+ children.add(child)+ let error = ''+ child.stderr.on('data', (data) => { error = (error + data).slice(-4096) })+ const exited = once(child, 'close')+ const base = `http://127.0.0.1:${port}`+ try {+ const health = await healthThrough(base, child)+ assert.equal(health.computerId, info.computerId, error)+ assert.equal(listeners(port, child.pid), String(child.pid))+ const denied = await api(base, null, 'hello')+ assert.equal(denied.status, 401)+ await denied.body?.cancel()+ const helloResponse = await api(base, info.token, 'hello')+ 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`)+ } finally {+ child.kill()+ await exited+ children.delete(child)+ }+ assert.equal(listeners(port), '')+ 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 })+ assert.notEqual(collision.status, 0)+ assert.match(collision.stderr, /Address already in use|cannot listen to port/)+ assert.equal(server.listening, true)+ console.log('PASS occupied local port fails without replacing the existing listener')+} finally {+ await close(server)+}diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex 17325d55..6c5616c9 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -76,6 +76,22 @@ same way; the shared desktop behavior covers macOS and Linux.## Development+SSH host discovery preserves the remote login shell's `PATH`, then searches+`/opt/homebrew/bin`, `/usr/local/bin`, `/home/linuxbrew/.linuxbrew/bin`,+`~/.local/bin`, and `/Applications/Codync.app/Contents/Resources` (Electron) or+`Contents/MacOS` (older native apps). Custom prefixes or relocated app bundles+must expose `codync-host` through the remote login shell's `PATH`.+Managed tunnels use `ssh -S none` to bypass connection sharing: the app's SSH+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,+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.+It uses port 19222 on the remote computer and leaves bots and settings unchanged.+```shcd apps/desktopnpm ci