Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(pairing): carry the SSH host-key fingerprints in the pairing QR
reviewedf621766e72
diff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.tsindex c3c895f86..d15dbd537 100644--- a/src/main/pairing-core.test.ts+++ b/src/main/pairing-core.test.ts@@ -513,6 +513,55 @@ describe('ssh:false in the pairing payload', () => {})})+describe('sshHostKeys in the pairing payload (the phone pins this host\'s SSH key at pairing)', () => {+ const input = { host: 'h', user: 'u', token: 't', pairPort: 1, name: 'n' }+ const FP1 = 'SHA256:4hkcemIeUAnjVwt5EwB/CU/rymSk1jz+o5uJWjj16e4'+ const FP2 = 'SHA256:KvCpHJYyTp5MLlmTTswZrJdnfnG1ukad9uzDw1PHE8I'+ const FP3 = 'SHA256:13Wz/nq9riSY3UhwCTNTh+tHZoA2v/gMWgsnDt10ySY'+ const relay = { hostId: 'abcABC012_-def012ghij', hostPublicKeyB64: 'AAAAhostpub', relayEndpoint: 'wss://relay.nodeterm.dev' }++ it('is placed after relay (the exact byte order the phones parse)', () => {+ expect(buildPairingPayload({ ...input, hostKey: 'AAAAhostpub', relay, sshHostKeys: [FP1, FP2, FP3] })).toBe(+ '{"v":1,"host":"h","port":22,"user":"u","token":"t","pairPort":1,"nodeterm":true,"name":"n","hostKey":"AAAAhostpub",' ++ '"relay":{"hostId":"abcABC012_-def012ghij","hostPublicKeyB64":"AAAAhostpub","relayEndpoint":"wss://relay.nodeterm.dev"},' ++ `"sshHostKeys":["${FP1}","${FP2}","${FP3}"]}`+ )+ })++ it('is placed after hostKey, or after name, when the blocks before it are absent', () => {+ expect(buildPairingPayload({ ...input, hostKey: 'K', sshHostKeys: [FP1] })).toBe(+ `{"v":1,"host":"h","port":22,"user":"u","token":"t","pairPort":1,"nodeterm":true,"name":"n","hostKey":"K","sshHostKeys":["${FP1}"]}`+ )+ expect(buildPairingPayload({ ...input, sshHostKeys: [FP1] })).toBe(+ `{"v":1,"host":"h","port":22,"user":"u","token":"t","pairPort":1,"nodeterm":true,"name":"n","sshHostKeys":["${FP1}"]}`+ )+ })++ it('is omitted when there is none (byte-for-byte the old payload)', () => {+ expect(buildPairingPayload({ ...input, sshHostKeys: [] })).toBe(buildPairingPayload(input))+ expect(buildPairingPayload({ ...input, sshHostKeys: undefined })).toBe(buildPairingPayload(input))+ })++ it('is ALWAYS omitted on a relay-only host (ssh:false): that payload is unchanged', () => {+ expect(buildPairingPayload({ ...input, relay, ssh: false, sshHostKeys: [FP1] })).toBe(+ buildPairingPayload({ ...input, relay, ssh: false })+ )+ expect(buildPairingPayload({ ...input, ssh: false, sshHostKeys: [FP1] })).toBe(+ '{"v":1,"host":"h","port":22,"user":"u","token":"t","pairPort":1,"nodeterm":true,"name":"n","ssh":false}'+ )+ })++ it('carries only well-formed fingerprints, at most four', () => {+ const json = buildPairingPayload({+ ...input,+ sshHostKeys: ['junk', FP1, 'SHA256:short', `${FP2}=`, FP2, FP3, FP1.replace('SHA256:', 'MD5:'), FP3, FP2]+ })+ expect(JSON.parse(json).sshHostKeys).toEqual([FP1, FP2, FP3])+ const five = Array.from({ length: 5 }, (_, i) => `SHA256:${String(i).repeat(43)}`)+ expect(JSON.parse(buildPairingPayload({ ...input, sshHostKeys: five })).sshHostKeys).toEqual(five.slice(0, 4))+ })+})+describe('pickPairingIPv4', () => {const nic = (address: string, internal = false) => ({ address, family: 'IPv4', internal })const ifaces = {diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.tsindex 0ce2e1c24..bb86ee6b2 100644--- a/src/main/pairing-core.ts+++ b/src/main/pairing-core.ts@@ -4,6 +4,7 @@// with a fixed on-the-wire contract shared with the nodeterm iOS app — keep them here, pure.import { CONTROL_RE } from '../core/relay/team-admin'+import { SSH_HOST_KEY_FINGERPRINT_RE, SSH_HOST_KEYS_MAX } from './ssh-host-key-fingerprint'/*** The relay block optionally embedded in the QR payload (and the /pair HTTP response). Present@@ -44,6 +45,25 @@ export interface PairingPayloadInput {* every other platform's payload byte-identical.*/ssh?: false+ /**+ * This host's SSH host-key fingerprints (`SHA256:<unpadded base64>`, `ssh-keygen -lf` spelling),+ * ordered ed25519, ecdsa, rsa (ssh-host-key-fingerprint.ts). The phone REFUSES an SSH connect+ * whose key is not one of these, so the reader hands over every key sshd serves or none at all+ * (never a subset). Only well-formed entries are carried, at most SSH_HOST_KEYS_MAX; omitted when+ * none — and ALWAYS omitted with `ssh:false` (no SSH on that host), so that payload stays+ * byte-identical.+ */+ sshHostKeys?: readonly string[]+}++/** The fingerprints the payload may carry: well-formed, distinct, at most SSH_HOST_KEYS_MAX. */+function payloadSshHostKeys(keys: readonly string[] | undefined): string[] {+ const out: string[] = []+ for (const k of keys ?? []) {+ if (out.length >= SSH_HOST_KEYS_MAX) break+ if (typeof k === 'string' && SSH_HOST_KEY_FINGERPRINT_RE.test(k) && !out.includes(k)) out.push(k)+ }+ return out}/**@@ -51,8 +71,9 @@ export interface PairingPayloadInput {* contract the phone parses:* {"v":1,"host":"…","port":22,"user":"…","token":"…","pairPort":N,"nodeterm":true,"name":"…"}* When a host key is supplied it is appended as `"hostKey":"…"` after `name`; when a relay block is- * supplied it is appended as `"relay":{…}` after that. With neither, the payload is byte-for-byte- * the legacy LAN-only shape.+ * supplied it is appended as `"relay":{…}` after that; then `"sshHostKeys":[…]` (never together with+ * `ssh:false`); then `"ssh":false`. With none of them, the payload is byte-for-byte the legacy+ * LAN-only shape.*/export function buildPairingPayload(input: PairingPayloadInput): string {const base = {@@ -67,7 +88,9 @@ export function buildPairingPayload(input: PairingPayloadInput): string {}const withKey = input.hostKey ? { ...base, hostKey: input.hostKey } : baseconst withRelay = input.relay ? { ...withKey, relay: input.relay } : withKey- return JSON.stringify(input.ssh === false ? { ...withRelay, ssh: false } : withRelay)+ if (input.ssh === false) return JSON.stringify({ ...withRelay, ssh: false })+ const sshHostKeys = payloadSshHostKeys(input.sshHostKeys)+ return JSON.stringify(sshHostKeys.length > 0 ? { ...withRelay, sshHostKeys } : withRelay)}/**diff --git a/src/main/pairing-service.test.ts b/src/main/pairing-service.test.tsindex 9439c3939..18d72e836 100644--- a/src/main/pairing-service.test.ts+++ b/src/main/pairing-service.test.ts@@ -45,7 +45,8 @@ vi.mock('../core/device-id', () => ({ getDeviceId: () => 'test-host-device-id' }import os from 'os'import { createPairingService, type PairingRelayDeps } from './pairing-service'import { rewriteKeyComment, type DeviceEntry } from './pairing-core'-import { genKeyPair, publicKeyToB64 } from './remote/e2ee'+import nacl from 'tweetnacl'+import { encrypt, genKeyPair, publicKeyToB64 } from './remote/e2ee'import type { Settings } from '../shared/types'const HOME = os.homedir()@@ -280,6 +281,31 @@ describe('revokeDevice', () => {})})+describe('the QR carries this host\'s SSH host-key fingerprints', () => {+ const FP = 'SHA256:4hkcemIeUAnjVwt5EwB/CU/rymSk1jz+o5uJWjj16e4'+ it('as `sshHostKeys`, from the reader, so the phone pins its first SSH connect', async () => {+ const service = createPairingService(undefined, { readSshHostKeys: async () => [FP] })+ try {+ const started = await service.start(() => {})+ expect(JSON.parse(started.payload).sshHostKeys).toEqual([FP])+ } finally {+ service.stop()+ }+ })++ it('omits the field when the reader finds none or fails (the phone falls back to TOFU, as before)', async () => {+ for (const readSshHostKeys of [async () => [], async () => Promise.reject(new Error('EACCES'))]) {+ const service = createPairingService(undefined, { readSshHostKeys })+ try {+ const started = await service.start(() => {})+ expect(JSON.parse(started.payload)).not.toHaveProperty('sshHostKeys')+ } finally {+ service.stop()+ }+ }+ })+})+describe('pairing POST vs revoke', () => {// The pairing POST mutates the same two files: it APPENDS to authorized_keys and upserts into// agent.json. Overlapping a revoke, an unserialized pairing either appends onto the inode the@@ -414,6 +440,27 @@ describe('pairing remembers the phone’s relay device id', () => {service.stop()}})++ it('refuses a sealed /pair whose epk is a low-order key (a public-constant shared key), pairing nothing', async () => {+ const service = createPairingService(relayDeps())+ try {+ const started = await service.start(() => {})+ const { token, pairPort, hostKey } = JSON.parse(started.payload) as { token: string; pairPort: number; hostKey: string }+ expect(hostKey).toBe(publicKeyToB64(hostKeys.publicKey))+ // Sealed under HSalsa20(0): the key ANY secret derives with a low-order epk — no secret needed.+ const constant = nacl.box.before(new Uint8Array(32), nacl.randomBytes(32))+ const plain = Buffer.from(JSON.stringify({ token, publicKey: freshEd25519Line(), deviceName: 'Weak' }))+ const box = encrypt(Uint8Array.from(plain), constant)+ const text = await post(pairPort, {+ epk: Buffer.from(new Uint8Array(32)).toString('base64'),+ box: Buffer.from(box).toString('base64')+ })+ expect(text).toBe('bad epk')+ expect(devices().map((d) => d.name)).not.toContain('Weak')+ } finally {+ service.stop()+ }+ })})describe('pairing names the phone platform-neutrally', () => {diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.tsindex cb6b016a0..0a8f0b124 100644--- a/src/main/pairing-service.ts+++ b/src/main/pairing-service.ts@@ -41,6 +41,7 @@ import {} from './pairing-core'import type { DeviceRevokeResult, DeviceRevokeServerOutcome, Settings } from '../shared/types'import { renameAtomic, sweepForeignTempFiles, tempNameFor } from '../core/fs-atomic'+import { readSshHostKeyFingerprints } from './ssh-host-key-fingerprint'import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'import { hostIdFromPublicKeyB64 } from './remote/relay-id'import { getDeviceId } from '../core/device-id'@@ -401,6 +402,12 @@ export interface PairingServiceOptions {* leg (tests, and any shell without a standing host).*/revokePhoneRelayTrust?: () => Promise<{ persisted: boolean; killed: boolean }>+ /**+ * This host's SSH host-key fingerprints for the QR's `sshHostKeys` (ssh-host-key-fingerprint.ts):+ * every key sshd would serve, per its own configuration, or [] when that cannot be established.+ * Never asked on Windows, where the QR says `ssh:false`.+ */+ readSshHostKeys?: () => Promise<string[]>}export function createPairingService(@@ -592,12 +599,19 @@ export function createPairingService(const addr = srv.address()const pairPort = typeof addr === 'object' && addr ? addr.port : 0- const [name, sshOpen, windowsKeyFile] = await Promise.all([+ const [name, sshOpen, windowsKeyFile, sshHostKeys] = await Promise.all([computerName(),probeSsh(),directSsh? Promise.resolve(undefined)- : (options.detectKeyFile ?? detectWindowsKeyFile)().catch((): WindowsKeyFile => 'unknown')+ : (options.detectKeyFile ?? detectWindowsKeyFile)().catch((): WindowsKeyFile => 'unknown'),+ // The phone pins its first SSH connect to one of these instead of trusting whatever answers+ // port 22 (the QR is on this screen: the same trust basis as `hostKey`). Complete or empty,+ // never a subset (the phone refuses a key not listed); empty means the QR carries none and the+ // phone's first contact is TOFU, as before.+ directSsh+ ? (options.readSshHostKeys ?? readSshHostKeyFingerprints)().catch((): string[] => [])+ : Promise.resolve(undefined)])// 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.@@ -626,7 +640,7 @@ export function createPairingService(name,hostKey,relay: relayCtx?.block,- ...(directSsh ? {} : { ssh: false as const })+ ...(directSsh ? { sshHostKeys } : { ssh: false as const })})// Give up after PAIR_TIMEOUT_MS with a timeout result.diff --git a/src/main/pairing-service.windows.test.ts b/src/main/pairing-service.windows.test.tsindex 5055a4cd1..966e4c579 100644--- a/src/main/pairing-service.windows.test.ts+++ b/src/main/pairing-service.windows.test.ts@@ -140,6 +140,19 @@ describe('Windows pairing: relay-only', () => {}})+ it('never reads or carries SSH host-key fingerprints (no SSH to pin on this host)', async () => {+ reset()+ const readSshHostKeys = vi.fn(async () => ['SHA256:' + 'A'.repeat(43)])+ const service = createPairingService(relayDeps(), { ...win, readSshHostKeys })+ try {+ const started = await service.start(() => {})+ expect(readSshHostKeys).not.toHaveBeenCalled()+ expect(JSON.parse(started.payload)).not.toHaveProperty('sshHostKeys')+ } 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 {diff --git a/src/main/ssh-host-key-fingerprint.test.ts b/src/main/ssh-host-key-fingerprint.test.tsnew file mode 100644index 000000000..5ad9a26fd--- /dev/null+++ b/src/main/ssh-host-key-fingerprint.test.ts@@ -0,0 +1,258 @@+// The SSH host-key fingerprints the pairing QR carries (`sshHostKeys`), so the phone can pin this+// host's SSH key at pairing instead of trusting whatever answers its first connect. The format is+// OpenSSH's own `ssh-keygen -lf` spelling, which the iOS and Android apps compare byte for byte.+import { describe, expect, it } from 'vitest'+import { execFileSync } from 'node:child_process'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { testTmpDir } from '../core/test-tmp'+import {+ SSH_HOST_KEY_FILES,+ SSH_HOST_KEYS_MAX,+ readSshHostKeyFingerprints,+ sshHostKeyFingerprint+} from './ssh-host-key-fingerprint'++// Generated with OpenSSH 9.6p1 (`ssh-keygen -t <type> -C root@fixture-host`), fingerprints from+// `ssh-keygen -lf` on the same files.+const ED25519 =+ 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIKC7DsD2KJNQX1y60LFjSgttopJTsr4BwfEgjvupmrXR root@fixture-host'+const ED25519_FP = 'SHA256:4hkcemIeUAnjVwt5EwB/CU/rymSk1jz+o5uJWjj16e4'+const ECDSA =+ 'ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBJhd3p8HakvNgiR+qUNF83TxfmZGRJJy3GBatE5+pnHb2zo6H2LUcOdA1EI1yYd8Mm+f0iRFpAQakJt/4nH9Lp0= root@fixture-host'+const ECDSA_FP = 'SHA256:KvCpHJYyTp5MLlmTTswZrJdnfnG1ukad9uzDw1PHE8I'+const RSA =+ 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCpSMA1Kv1A5YZYaZjDQa9nPBUZN46uamTMHc2MRcx5gaCWQGbvsiznifl6KQN0+sCmQMSX4jagJVHPdr9h86l+qycm3+J09BycicV6q/ksON8rZiApjs0qpfQ4YHC0Jlu7rQp9FgErqE6KSLvQsXBDEakusjyXEXeTlwyZaAWLtCvwT1+7n3jw613vVjXgSE5pb1qg8o7xSXgOr+F6nrNGCDysD9mH7e/YiYMQYRSEegYx999RrElXEQNOp8KET8DOoI1qquYbBm3ae4cjkb13fClTw5NFfqxYI9UUDOggPMi3ccnwMuJ68vYHG1eK1/2NqIjyYacFV/AuZYijlQ5FipSg4F3f6hOzb8BDgr1BUb3evEma/BvIvpOZqJWoeQSKgixpNA+o9zfMzs+76V52cf+V2snhQ89kPc7/EZ1WAGqjmIZnItG0iU51559LCXYLD/3pEw8rD77uhN5m2nXyqC6Kly8POcqhsO+lT3U+u0k/kZL+qnToURHTWzFzJj0= root@fixture-host'+const RSA_FP = 'SHA256:13Wz/nq9riSY3UhwCTNTh+tHZoA2v/gMWgsnDt10ySY'++describe('sshHostKeyFingerprint', () => {+ it("matches ssh-keygen -lf for ed25519, ecdsa and rsa", () => {+ expect(sshHostKeyFingerprint(ED25519)).toBe(ED25519_FP)+ expect(sshHostKeyFingerprint(ECDSA)).toBe(ECDSA_FP)+ expect(sshHostKeyFingerprint(RSA)).toBe(RSA_FP)+ })++ it('reads the first key line of a file (a trailing newline, no comment, leading blank lines)', () => {+ expect(sshHostKeyFingerprint(ED25519 + '\n')).toBe(ED25519_FP)+ expect(sshHostKeyFingerprint(ED25519.split(' ').slice(0, 2).join(' '))).toBe(ED25519_FP)+ expect(sshHostKeyFingerprint('\n\n' + ED25519 + '\r\n')).toBe(ED25519_FP)+ })++ it('refuses a blob whose embedded algorithm does not match the line (an ed25519 blob labelled rsa)', () => {+ const blob = ED25519.split(' ')[1]+ expect(sshHostKeyFingerprint(`ssh-rsa ${blob} x`)).toBeNull()+ expect(sshHostKeyFingerprint(`ecdsa-sha2-nistp256 ${RSA.split(' ')[1]}`)).toBeNull()+ })++ it('refuses junk: no blob, non-base64, a truncated blob, a lying length prefix, non-canonical base64', () => {+ expect(sshHostKeyFingerprint('')).toBeNull()+ expect(sshHostKeyFingerprint('ssh-ed25519')).toBeNull()+ expect(sshHostKeyFingerprint('ssh-ed25519 !!!not-base64!!!')).toBeNull()+ expect(sshHostKeyFingerprint('ssh-ed25519 AAAA')).toBeNull()+ const lying = Buffer.concat([Buffer.from([0, 0, 0, 0xff]), Buffer.from('ssh-ed25519')]).toString('base64')+ expect(sshHostKeyFingerprint(`ssh-ed25519 ${lying}`)).toBeNull()+ // Node's decoder would skip the junk and hand back the real blob.+ expect(sshHostKeyFingerprint(`ssh-ed25519 !!${ED25519.split(' ')[1]}`)).toBeNull()+ })+})++/** An in-memory filesystem. A path in `denied` throws EACCES on every access. */+function memFs(files: Record<string, string>, denied: string[] = []) {+ const err = (code: string, p: string) => Object.assign(new Error(`${code}: ${p}`), { code })+ const isDir = (p: string) => Object.keys(files).some((f) => f.startsWith(p.endsWith('/') ? p : p + '/'))+ return {+ readFile: async (p: string) => {+ if (denied.includes(p)) throw err('EACCES', p)+ if (!(p in files)) throw err('ENOENT', p)+ return files[p]+ },+ stat: async (p: string) => {+ if (denied.includes(p)) throw err('EACCES', p)+ if (p in files) return { isFile: () => true }+ if (isDir(p)) return { isFile: () => false }+ throw err('ENOENT', p)+ },+ readdir: async (d: string) => {+ if (denied.includes(d)) throw err('EACCES', d)+ if (!isDir(d)) throw err('ENOENT', d)+ const pre = d.endsWith('/') ? d : d + '/'+ return [...new Set(Object.keys(files).filter((f) => f.startsWith(pre)).map((f) => f.slice(pre.length).split('/')[0]))]+ }+ }+}++const PRIV = 'PRIVATE KEY (never read)'+/** sshd's three default keys, private and public halves. */+const defaults = (): Record<string, string> => ({+ '/etc/ssh/ssh_host_ed25519_key': PRIV,+ '/etc/ssh/ssh_host_ed25519_key.pub': ED25519,+ '/etc/ssh/ssh_host_ecdsa_key': PRIV,+ '/etc/ssh/ssh_host_ecdsa_key.pub': ECDSA,+ '/etc/ssh/ssh_host_rsa_key': PRIV,+ '/etc/ssh/ssh_host_rsa_key.pub': RSA+})+const UBUNTU_CONFIG = 'Include /etc/ssh/sshd_config.d/*.conf\n#HostKey /etc/ssh/ssh_host_rsa_key\nPermitRootLogin no\n'+const read = (files: Record<string, string>, denied: string[] = []) => readSshHostKeyFingerprints(memFs(files, denied))++describe('readSshHostKeyFingerprints — complete or absent, never partial', () => {+ it('a config naming no HostKey: sshd\'s defaults, ordered ed25519, ecdsa, rsa', async () => {+ expect(SSH_HOST_KEY_FILES).toEqual([+ '/etc/ssh/ssh_host_ed25519_key.pub',+ '/etc/ssh/ssh_host_ecdsa_key.pub',+ '/etc/ssh/ssh_host_rsa_key.pub'+ ])+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...defaults() })).toEqual([ED25519_FP, ECDSA_FP, RSA_FP])+ })++ it('a default whose PRIVATE key does not exist is not served, so it is left out (still complete)', async () => {+ const f = defaults()+ delete f['/etc/ssh/ssh_host_ecdsa_key']+ delete f['/etc/ssh/ssh_host_ecdsa_key.pub']+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...f })).toEqual([ED25519_FP, RSA_FP])+ })++ it('a served key whose .pub is missing, unreadable or malformed drops the WHOLE field', async () => {+ const missing = defaults()+ delete missing['/etc/ssh/ssh_host_rsa_key.pub']+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...missing })).toEqual([])+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...defaults() }, ['/etc/ssh/ssh_host_rsa_key.pub'])).toEqual([])+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...defaults(), '/etc/ssh/ssh_host_rsa_key.pub': 'ssh-rsa junk' })).toEqual([])+ })++ it('a private key we cannot even stat (not ENOENT) drops the field: we cannot tell if it is served', async () => {+ expect(await read({ '/etc/ssh/sshd_config': UBUNTU_CONFIG, ...defaults() }, ['/etc/ssh/ssh_host_ecdsa_key'])).toEqual([])+ })++ it('HostKey lines decide the set exactly: the defaults are ignored even when present', async () => {+ const files = {+ '/etc/ssh/sshd_config': 'HostKey /srv/keys/host_rsa\nhostkey=/srv/keys/host_ed\nHostKey "/srv/keys/host_ed" # again\n',+ ...defaults(),+ '/srv/keys/host_rsa': PRIV,+ '/srv/keys/host_rsa.pub': RSA,+ '/srv/keys/host_ed': PRIV,+ '/srv/keys/host_ed.pub': ED25519+ }+ expect(await read(files)).toEqual([ED25519_FP, RSA_FP])+ })++ it('HostKey lines in an Included file count, and a commented one does not', async () => {+ const files = {+ '/etc/ssh/sshd_config': UBUNTU_CONFIG,+ '/etc/ssh/sshd_config.d/10-keys.conf': 'HostKey /srv/keys/host_ed\n',+ '/etc/ssh/sshd_config.d/20-other.txt': 'HostKey /srv/keys/not_included\n', // not *.conf+ '/etc/ssh/sshd_config.d/.hidden.conf': 'HostKey /srv/keys/hidden\n', // glob * skips dotfiles+ ...defaults(),+ '/srv/keys/host_ed': PRIV,+ '/srv/keys/host_ed.pub': ED25519+ }+ expect(await read(files)).toEqual([ED25519_FP])+ })++ it('a relative Include is under /etc/ssh, a missing literal Include is skipped (glob no-match)', async () => {+ const files = {+ '/etc/ssh/sshd_config': 'Include sshd_config.d/keys.conf\nInclude /etc/ssh/absent.conf\n',+ '/etc/ssh/sshd_config.d/keys.conf': 'HostKey /srv/keys/host_ed\n',+ '/srv/keys/host_ed': PRIV,+ '/srv/keys/host_ed.pub': ED25519+ }+ expect(await read(files)).toEqual([ED25519_FP])+ })++ it('config unreadable: the defaults only if ALL three are present and consistent', async () => {+ const denied = ['/etc/ssh/sshd_config']+ expect(await read(defaults(), denied)).toEqual([ED25519_FP, ECDSA_FP, RSA_FP])+ const two = defaults()+ delete two['/etc/ssh/ssh_host_ecdsa_key']+ delete two['/etc/ssh/ssh_host_ecdsa_key.pub']+ expect(await read(two, denied)).toEqual([])+ // An rsa key in the ed25519 file is not "consistent".+ expect(await read({ ...defaults(), '/etc/ssh/ssh_host_ed25519_key.pub': RSA }, denied)).toEqual([])+ })++ it('an Included file we cannot read counts as an unreadable config (strict defaults)', async () => {+ const files: Record<string, string> = {+ '/etc/ssh/sshd_config': UBUNTU_CONFIG,+ '/etc/ssh/sshd_config.d/10-keys.conf': 'HostKey /srv/keys/host_ed\n',+ ...defaults()+ }+ expect(await read(files, ['/etc/ssh/sshd_config.d/10-keys.conf'])).toEqual([ED25519_FP, ECDSA_FP, RSA_FP])+ const two: Record<string, string> = { ...files }+ delete two['/etc/ssh/ssh_host_rsa_key']+ expect(await read(two, ['/etc/ssh/sshd_config.d/10-keys.conf'])).toEqual([])+ })++ it('an Include cycle stops at sshd\'s depth limit and counts as unreadable', async () => {+ const files = { '/etc/ssh/sshd_config': 'Include /etc/ssh/sshd_config\n', ...defaults() }+ expect(await read(files)).toEqual([ED25519_FP, ECDSA_FP, RSA_FP]) // strict defaults, all present+ })++ it('what we cannot model drops the field: HostKeyAgent, a relative or tokenized path, a [glob]', async () => {+ for (const config of [+ 'HostKeyAgent /run/agent.sock\n',+ 'HostKey ssh_host_ed25519_key\n',+ 'HostKey /etc/ssh/%h_key\n',+ 'HostKey ~/key\n',+ 'Include /etc/ssh/conf.[ab]\n',+ 'Include /etc/*/x.conf\n',+ 'HostKey "/unterminated\n'+ ]) {+ expect(await read({ '/etc/ssh/sshd_config': config, ...defaults() }), config).toEqual([])+ }+ expect(await read({ '/etc/ssh/sshd_config': 'HostKeyAgent none\n', ...defaults() })).toEqual([ED25519_FP, ECDSA_FP, RSA_FP])+ })++ it(`a host serving more than ${SSH_HOST_KEYS_MAX} keys gets none (a subset could lock the phone out)`, async () => {+ const lines = [ED25519, ECDSA, RSA]+ const files: Record<string, string> = { '/etc/ssh/sshd_config': '' }+ for (let i = 0; i < 5; i++) {+ // Five distinct keys: the three fixtures and two syntactically valid ed25519 lines.+ files['/etc/ssh/sshd_config'] += `HostKey /k/${i}\n`+ files[`/k/${i}`] = PRIV+ }+ files['/k/0.pub'] = lines[0]+ files['/k/1.pub'] = lines[1]+ files['/k/2.pub'] = lines[2]+ files['/k/3.pub'] = edLine(1)+ files['/k/4.pub'] = edLine(2)+ expect(await read(files)).toEqual([])+ delete files['/k/4']+ expect((await read(files)).length).toBe(4)+ })++ it('never throws, whatever the filesystem does', async () => {+ const boom = { readFile: async () => { throw new Error('x') }, stat: async () => { throw new Error('x') }, readdir: async () => { throw new Error('x') } }+ expect(await readSshHostKeyFingerprints(boom)).toEqual([])+ })+})++/** A syntactically valid ed25519 public key line with a fixed fake key (distinct per seed). */+function edLine(seed: number): string {+ const name = Buffer.from('ssh-ed25519')+ const len = (n: number) => { const b = Buffer.alloc(4); b.writeUInt32BE(n); return b }+ return `ssh-ed25519 ${Buffer.concat([len(name.length), name, len(32), Buffer.alloc(32, seed)]).toString('base64')} k`+}++// The fixtures above were checked against ssh-keygen once; this re-checks a FRESH key every run+// where an ssh-keygen exists, so a fixture typo cannot hide a wrong formula.+let sshKeygen = false+try {+ execFileSync('ssh-keygen', ['-?'], { stdio: 'ignore' })+ sshKeygen = true+} catch (e) {+ // `ssh-keygen -?` exits non-zero but runs; only a missing binary is ENOENT.+ sshKeygen = (e as NodeJS.ErrnoException).code !== 'ENOENT'+}++describe.skipIf(!sshKeygen || process.platform === 'win32')('against the real ssh-keygen', () => {+ for (const type of ['ed25519', 'ecdsa', 'rsa']) {+ it(`a freshly generated ${type} key`, () => {+ const dir = testTmpDir('nt-sshfp-')+ const key = path.join(dir, `k_${type}`)+ const size = type === 'rsa' ? ['-b', '2048'] : []+ execFileSync('ssh-keygen', ['-q', '-t', type, ...size, '-N', '', '-C', 'test', '-f', key], { stdio: 'ignore' })+ const want = execFileSync('ssh-keygen', ['-lf', `${key}.pub`], { encoding: 'utf8' }).split(' ')[1]+ expect(want).toMatch(/^SHA256:/)+ expect(sshHostKeyFingerprint(readFileSync(`${key}.pub`, 'utf8'))).toBe(want)+ }, 60_000) // key generation (rsa above all) is slow on a loaded CI box+ }+})diff --git a/src/main/ssh-host-key-fingerprint.ts b/src/main/ssh-host-key-fingerprint.tsnew file mode 100644index 000000000..6d23b58bd--- /dev/null+++ b/src/main/ssh-host-key-fingerprint.ts@@ -0,0 +1,283 @@+// SSH host-key fingerprints for the phone-pairing QR (`sshHostKeys`, pairing-core.ts).+//+// Why: the phone pins this host's SSH key trust-on-first-use, and pairing used to DROP any existing+// pin, so the phone's first SSH connect after pairing trusted whatever answered on port 22. An+// attacker on the LAN at that moment could then serve a forged ~/.nodeterm/agent.json (the phone+// would E2EE its agent traffic to the attacker's key) or a forged ~/.nodeterm/relay.json (adopted+// as the relay identity). The QR is on this host's own screen — the same trust basis as its+// `hostKey` — so carrying the fingerprints there lets the phone refuse a first connect whose key is+// not one of them.+//+// Format: OpenSSH's own `ssh-keygen -lf` spelling, `SHA256:<standard base64 of sha256(keyBlob),+// trailing '=' removed>`, which the phones compare byte for byte. keyBlob is the base64-decoded+// second field of the .pub line. A line whose blob names a different algorithm than its first field+// is refused (a mislabelled or tampered file), and so is non-canonical base64.+//+// COMPLETE OR ABSENT — never a partial list. The phones REFUSE an SSH connect whose host key is not+// in the QR set, and sshd presents whichever of its keys the client's algorithm preference picks,+// so a list missing one key sshd serves locks the phone out of this host until a corrected QR is+// scanned. Every doubt therefore drops the field, and the phone falls back to today's TOFU:+// - sshd's own configuration decides the set: the `HostKey` paths in /etc/ssh/sshd_config and the+// files it `Include`s (globs in the file name only, relative paths under /etc/ssh, at most 16+// levels, like sshd). No `HostKey` anywhere = sshd's defaults (rsa, ecdsa, ed25519).+// - a key sshd would serve is one whose PRIVATE file exists (stat only — it is never read; sshd+// skips a HostKey it cannot find). Its `.pub` must then read and parse, or the field is dropped.+// - when the configuration (or a file it includes) cannot be read, the defaults are used only if+// all three are present (private and `.pub`) and consistent (each `.pub` holds its file's+// algorithm); otherwise the field is dropped. A HostKey hidden in an unreadable configuration is+// the residual risk of that fallback.+// - `HostKeyAgent`, a non-absolute or tokenized (`%`, `~`) HostKey path, a glob form we do not+// implement, or more than SSH_HOST_KEYS_MAX keys: dropped.+// A superset is harmless (a fingerprint the server never presents just goes unused).+import { createHash } from 'node:crypto'+import { promises as fs } from 'node:fs'+import path from 'node:path'++/** sshd's default host keys (used when the configuration names none), in QR order. */+export const SSHD_DEFAULT_HOST_KEYS = [+ '/etc/ssh/ssh_host_ed25519_key',+ '/etc/ssh/ssh_host_ecdsa_key',+ '/etc/ssh/ssh_host_rsa_key'+] as const++/** The public halves of the defaults: ed25519, ecdsa, rsa. */+export const SSH_HOST_KEY_FILES: readonly string[] = SSHD_DEFAULT_HOST_KEYS.map((k) => `${k}.pub`)++export const SSHD_CONFIG = '/etc/ssh/sshd_config'++/** The QR carries at most this many fingerprints. A host serving more gets none (never a subset). */+export const SSH_HOST_KEYS_MAX = 4++/** The one shape a fingerprint has on the wire: sha256 = 32 bytes = 43 base64 chars unpadded. */+export const SSH_HOST_KEY_FINGERPRINT_RE = /^SHA256:[A-Za-z0-9+/]{43}$/++/** sshd's own include depth limit (SERVCONF_MAX_DEPTH). */+const MAX_INCLUDE_DEPTH = 16++interface ParsedKey {+ algo: string+ fingerprint: string+}++function parseKeyLine(text: string): ParsedKey | null {+ if (typeof text !== 'string') return null+ const line = text+ .split(/\r?\n/)+ .map((l) => l.trim())+ .find((l) => l.length > 0 && !l.startsWith('#'))+ if (!line) return null+ const [algo, b64] = line.split(/\s+/)+ if (!algo || !b64 || !/^[A-Za-z0-9+/]+={0,2}$/.test(b64)) return null+ const blob = Buffer.from(b64, 'base64')+ // One spelling per key: Node's decoder ignores what it cannot read, so re-encode and compare.+ if (blob.toString('base64') !== b64) return null+ // OpenSSH wire format: a uint32 length-prefixed algorithm name comes first.+ if (blob.length < 4) return null+ const nameLen = blob.readUInt32BE(0)+ if (nameLen === 0 || 4 + nameLen >= blob.length) return null+ if (blob.subarray(4, 4 + nameLen).toString('latin1') !== algo) return null+ return { algo, fingerprint: 'SHA256:' + createHash('sha256').update(blob).digest('base64').replace(/=+$/, '') }+}++/** A public key line's fingerprint, or null when it is not a well-formed OpenSSH public key. */+export function sshHostKeyFingerprint(text: string): string | null {+ return parseKeyLine(text)?.fingerprint ?? null+}++type Family = 'ed25519' | 'ecdsa' | 'rsa' | 'other'+function familyOf(algo: string): Family {+ if (algo === 'ssh-ed25519') return 'ed25519'+ if (algo.startsWith('ecdsa-sha2-')) return 'ecdsa'+ if (algo === 'ssh-rsa') return 'rsa'+ return 'other'+}+const FAMILY_RANK: Record<Family, number> = { ed25519: 0, ecdsa: 1, rsa: 2, other: 3 }+/** The family a DEFAULT key file must hold (the defaults' consistency check), or null. */+function defaultFamily(privatePath: string): Family | null {+ const m = /\/ssh_host_(ed25519|ecdsa|rsa)_key$/.exec(privatePath)+ return m ? (m[1] as Family) : null+}++/** The filesystem the reader needs (injected in tests). `stat` THROWS for a missing path (ENOENT)+ * and for any other failure, exactly like fs.promises.stat. */+export interface HostKeyFs {+ readFile(file: string): Promise<string>+ stat(file: string): Promise<{ isFile(): boolean }>+ readdir(dir: string): Promise<string[]>+}++const nodeFs: HostKeyFs = {+ readFile: (file) => fs.readFile(file, 'utf8'),+ stat: (file) => fs.stat(file),+ readdir: (dir) => fs.readdir(dir)+}++const errCode = (e: unknown): string | undefined => (e as NodeJS.ErrnoException | null)?.code++/** What sshd's configuration says about host keys. */+type ConfigVerdict =+ | { kind: 'keys'; paths: string[] } // HostKey paths, possibly none (= sshd's defaults)+ | { kind: 'unreadable' } // the config or an Include could not be read: strict defaults+ | { kind: 'unsupported' } // something we cannot model: no list++class Unreadable extends Error {}+class Unsupported extends Error {}++/** One sshd_config line as tokens: whitespace or one `=` after the keyword separates, double quotes+ * group, and a token that starts with `#` ends the line (sshd's argv_split). */+function tokens(line: string): string[] {+ const out: string[] = []+ const s = line.replace(/\f/g, ' ')+ let i = 0+ while (i < s.length) {+ while (i < s.length && /\s/.test(s[i])) i+++ if (i >= s.length) break+ if (out.length === 1 && s[i] === '=') {+ i+++ continue+ }+ if (s[i] === '#') break+ let tok = ''+ if (s[i] === '"') {+ const end = s.indexOf('"', i + 1)+ if (end < 0) throw new Unsupported('unbalanced quote')+ tok = s.slice(i + 1, end)+ i = end + 1+ } else {+ while (i < s.length && !/\s/.test(s[i]) && !(out.length === 0 && s[i] === '=')) tok += s[i++]+ }+ out.push(tok)+ }+ return out+}++function globToRegExp(pattern: string): RegExp {+ let re = '^'+ for (const c of pattern) {+ if (c === '*') re += '[^/]*'+ else if (c === '?') re += '[^/]'+ else re += c.replace(/[.+^${}()|\\]/g, '\\$&')+ }+ return new RegExp(re + '$')+}++/** The files one `Include` argument names, as sshd's glob(3) would (sorted, no dotfiles for `*`). */+async function includeTargets(io: HostKeyFs, arg: string, baseDir: string): Promise<string[]> {+ const abs = path.isAbsolute(arg) ? arg : path.join(baseDir, arg)+ const dir = path.dirname(abs)+ const name = path.basename(abs)+ if (/[*?[\]{}]/.test(dir) || /[[\]{}]/.test(name)) throw new Unsupported('glob form')+ if (!/[*?]/.test(name)) {+ // A literal path that does not exist is glob's "no match": sshd skips it.+ try {+ await io.stat(abs)+ } catch (e) {+ if (errCode(e) === 'ENOENT') return []+ throw new Unreadable(abs)+ }+ return [abs]+ }+ let names: string[]+ try {+ names = await io.readdir(dir)+ } catch (e) {+ if (errCode(e) === 'ENOENT') return []+ throw new Unreadable(dir)+ }+ const re = globToRegExp(name)+ return names+ .filter((n) => re.test(n) && (!n.startsWith('.') || name.startsWith('.')))+ .sort()+ .map((n) => path.join(dir, n))+}++async function collectHostKeys(io: HostKeyFs, file: string, baseDir: string, depth: number, acc: string[]): Promise<void> {+ if (depth > MAX_INCLUDE_DEPTH) throw new Unreadable('include depth')+ let text: string+ try {+ text = await io.readFile(file)+ } catch {+ throw new Unreadable(file)+ }+ for (const raw of text.split(/\r?\n/)) {+ const t = tokens(raw)+ if (t.length === 0) continue+ const key = t[0].toLowerCase()+ if (key === 'include') {+ for (const arg of t.slice(1)) {+ for (const target of await includeTargets(io, arg, baseDir)) {+ await collectHostKeys(io, target, baseDir, depth + 1, acc)+ }+ }+ } else if (key === 'hostkeyagent') {+ // Keys served from an agent are not files we can read: no complete list.+ if ((t[1] ?? '').toLowerCase() !== 'none') throw new Unsupported('HostKeyAgent')+ } else if (key === 'hostkey') {+ const p = t[1]+ if (!p || !path.isAbsolute(p) || /[%~]/.test(p)) throw new Unsupported('HostKey path')+ if (!acc.includes(p)) acc.push(p)+ }+ }+}++async function readConfig(io: HostKeyFs, configPath: string): Promise<ConfigVerdict> {+ const acc: string[] = []+ try {+ await collectHostKeys(io, configPath, path.dirname(configPath), 0, acc)+ return { kind: 'keys', paths: acc }+ } catch (e) {+ return e instanceof Unreadable ? { kind: 'unreadable' } : { kind: 'unsupported' }+ }+}++/** One key's public half, or 'skip' (sshd does not serve it: no private file), or 'fail'. */+async function servedKey(io: HostKeyFs, privatePath: string): Promise<ParsedKey | 'skip' | 'fail'> {+ try {+ if (!(await io.stat(privatePath)).isFile()) return 'fail'+ } catch (e) {+ return errCode(e) === 'ENOENT' ? 'skip' : 'fail'+ }+ let text: string+ try {+ text = await io.readFile(`${privatePath}.pub`)+ } catch {+ return 'fail'+ }+ const parsed = parseKeyLine(text)+ if (!parsed) return 'fail'+ const want = defaultFamily(privatePath)+ if (want && familyOf(parsed.algo) !== want) return 'fail'+ return parsed+}++/**+ * This host's SSH host-key fingerprints — COMPLETE (every key sshd would serve) or [] (see the+ * header). Ordered ed25519, ecdsa, rsa, others; distinct; at most SSH_HOST_KEYS_MAX. Never throws.+ */+export async function readSshHostKeyFingerprints(io: HostKeyFs = nodeFs, configPath: string = SSHD_CONFIG): Promise<string[]> {+ try {+ const config = await readConfig(io, configPath)+ if (config.kind === 'unsupported') return []+ const strict = config.kind === 'unreadable'+ const paths = config.kind === 'keys' && config.paths.length > 0 ? config.paths : [...SSHD_DEFAULT_HOST_KEYS]+ const keys: ParsedKey[] = []+ for (const p of paths) {+ const k = await servedKey(io, p)+ if (k === 'fail') return []+ if (k === 'skip') {+ // With the configuration unreadable, a missing default could mean sshd is configured with+ // a key elsewhere: the defaults must ALL be there.+ if (strict) return []+ continue+ }+ keys.push(k)+ }+ const out: string[] = []+ for (const k of [...keys].sort((a, b) => FAMILY_RANK[familyOf(a.algo)] - FAMILY_RANK[familyOf(b.algo)])) {+ if (!out.includes(k.fingerprint)) out.push(k.fingerprint)+ }+ return out.length > SSH_HOST_KEYS_MAX ? [] : out+ } catch {+ return []+ }+}