// ssh-mode e2e — the DEFAULT (SSH-style login) path, end to end over hyperdht:
// connectSSH -> hyperdht -> serveSSH -> (tunnel) -> throwaway sshd -> mosh-server
// -> MOSH CONNECT parsed -> mosh-client (in a PTY) runs a command through the tunnel.
//
// Uses an ISOLATED sshd on a high port with its own host/client keys, so it never
// touches the system sshd or authorized_keys. Skips cleanly if sshd/mosh/python3
// are unavailable or the sandbox can't run a non-root sshd.
import DHT from 'hyperdht'
import { spawn, execSync } from 'child_process'
import fs from 'fs'
import os from 'os'
import path from 'path'
import { fileURLToPath } from 'url'
import { serveSSH, connectSSH } from '../lib/ssh-mode.mjs'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
function have (bin) { try { execSync('command -v ' + bin, { stdio: 'ignore' }); return true } catch { return false } }
const sshdBin = ['/usr/sbin/sshd', '/usr/bin/sshd', '/sbin/sshd'].find((p) => { try { fs.accessSync(p); return true } catch { return false } })
if (!sshdBin || !have('mosh-server') || !have('mosh-client') || !have('python3') || !have('ssh')) {
console.log('[ssh-mode] SKIPPED (need sshd + mosh + python3 + ssh)')
process.exit(0)
}
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hm-sshmode-'))
const port = 49000 + Math.floor((Date.now() % 1000)) // low-collision high port (Date.now ok in a node test)
const F = (n) => path.join(dir, n)
let sshd = null
let failed = false
function cleanup () {
try { if (sshd) sshd.kill('SIGKILL') } catch {}
try { fs.rmSync(dir, { recursive: true, force: true }) } catch {}
}
try {
execSync(`ssh-keygen -q -t ed25519 -f ${F('hostkey')} -N ''`)
execSync(`ssh-keygen -q -t ed25519 -f ${F('clientkey')} -N ''`)
fs.copyFileSync(F('clientkey.pub'), F('authorized_keys'))
fs.chmodSync(F('authorized_keys'), 0o600)
fs.writeFileSync(F('sshd_config'),
`Port ${port}\nListenAddress 127.0.0.1\nHostKey ${F('hostkey')}\n` +
`AuthorizedKeysFile ${F('authorized_keys')}\nPidFile ${F('sshd.pid')}\n` +
'UsePAM no\nPermitRootLogin no\nPasswordAuthentication no\nPubkeyAuthentication yes\nStrictModes no\n')
console.log('[ssh-mode] connectSSH -> hyperdht -> serveSSH -> sshd -> mosh-server -> mosh-client')
sshd = spawn(sshdBin, ['-f', F('sshd_config'), '-D', '-E', F('sshd.log')])
await new Promise((r) => setTimeout(r, 1500))
const keyPair = DHT.keyPair()
const s = await serveSSH({ keyPair, sshdPort: port })
const user = os.userInfo().username
const marker = 'HYPERMOSH_SSH_OK_' + port
const done = new Promise((resolve) => {
const timer = setTimeout(() => { console.log(' ❌ FAIL — no session in 45s'); failed = true; resolve() }, 45000)
const session = connectSSH({
remoteKey: keyPair.publicKey, user,
cmd: ['bash', '-lc', `echo ${marker}; sleep 8`],
sshOpts: ['-i', F('clientkey'), '-o', 'IdentitiesOnly=yes'],
onerror: (e) => { console.log(' ❌ FAIL — ' + e.message); failed = true; clearTimeout(timer); resolve() },
onstarted: (moshKey, localPort) => {
console.log(' logged in via sshd, mosh-server up; driving mosh-client on 127.0.0.1:' + localPort)
const drv = spawn('python3', [path.join(__dirname, 'pty-mosh.py'), moshKey, '127.0.0.1', String(localPort), '12'])
let cap = ''
drv.stdout.on('data', (d) => { cap += d })
drv.on('exit', async () => {
const clean = cap.replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
if (clean.includes(marker)) console.log(' ✅ PASS — SSH-style login + mosh session ran end-to-end over hyperdht')
else { console.log(' ❌ FAIL — marker not seen'); failed = true }
clearTimeout(timer)
await session.close()
resolve()
})
}
})
})
await done
await s.close()
} catch (e) {
console.log(' ⏭ SKIPPED — environment could not run the isolated sshd: ' + e.message)
cleanup()
process.exit(0)
}
cleanup()
console.log(failed ? '\n❌ ssh-mode test failed' : '\n✅ ssh-mode test passed')
process.exit(failed ? 1 : 0)