Skip to content

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.

feat(pairing): end-to-end encrypt LAN pairing to the QR host key

enesc0ac260f2c2d
diff --git a/src/main/pairing-core.test.ts b/src/main/pairing-core.test.ts
index 3b2eaa464..75345b12f 100644
--- a/src/main/pairing-core.test.ts
+++ b/src/main/pairing-core.test.ts
@@ -74,6 +74,54 @@ describe('buildPairingPayload', () => {
expect(JSON.parse(json)).not.toHaveProperty('relay')
})
+ it('appends hostKey after name when supplied (no relay)', () => {
+ const json = buildPairingPayload({
+ host: '192.168.1.5',
+ user: 'enes',
+ token: 'tok',
+ pairPort: 5,
+ name: 'Mac',
+ hostKey: 'AAAAhostpub'
+ })
+ expect(json).toBe(
+ '{"v":1,"host":"192.168.1.5","port":22,"user":"enes","token":"tok","pairPort":5,"nodeterm":true,"name":"Mac","hostKey":"AAAAhostpub"}'
+ )
+ expect(JSON.parse(json).hostKey).toBe('AAAAhostpub')
+ })
+
+ it('places hostKey before the relay block when both are supplied', () => {
+ const relay = {
+ hostId: 'abcABC012_-def012ghij',
+ hostPublicKeyB64: 'AAAAhostpub',
+ relayEndpoint: 'wss://relay.nodeterm.dev'
+ }
+ const json = buildPairingPayload({
+ host: '192.168.1.5',
+ user: 'enes',
+ token: 'tok',
+ pairPort: 5,
+ name: 'Mac',
+ hostKey: 'AAAAhostpub',
+ relay
+ })
+ expect(json).toBe(
+ '{"v":1,"host":"192.168.1.5","port":22,"user":"enes","token":"tok","pairPort":5,"nodeterm":true,"name":"Mac","hostKey":"AAAAhostpub","relay":{"hostId":"abcABC012_-def012ghij","hostPublicKeyB64":"AAAAhostpub","relayEndpoint":"wss://relay.nodeterm.dev"}}'
+ )
+ expect(JSON.parse(json)).toMatchObject({ hostKey: 'AAAAhostpub', relay })
+ })
+
+ it('omits hostKey when absent (byte-for-byte legacy shape)', () => {
+ const json = buildPairingPayload({
+ host: 'h',
+ user: 'u',
+ token: 't',
+ pairPort: 1,
+ name: 'n'
+ })
+ expect(json).not.toContain('hostKey')
+ expect(JSON.parse(json)).not.toHaveProperty('hostKey')
+ })
+
it('appends the relay block after name when supplied', () => {
const relay = {
hostId: 'abcABC012_-def012ghij',
diff --git a/src/main/pairing-core.ts b/src/main/pairing-core.ts
index 75ded09d6..18d7e7606 100644
--- a/src/main/pairing-core.ts
+++ b/src/main/pairing-core.ts
@@ -26,6 +26,12 @@ export interface PairingPayloadInput {
token: string
pairPort: number
name: string
+ /**
+ * The host's NaCl box public key (standard base64), authenticated by being shown on the host's
+ * own screen. When present, the phone encrypts the whole /pair exchange to it (E2EE). Omitted →
+ * the phone POSTs plaintext, exactly as before.
+ */
+ hostKey?: string
/** Optional relay reachability block (standing host). Omitted from the payload when absent. */
relay?: RelayPairingBlock
}
@@ -34,8 +40,9 @@ export interface PairingPayloadInput {
* Build the single-line JSON the QR encodes. The key order + compact separators match the
* contract the phone parses:
* {"v":1,"host":"…","port":22,"user":"…","token":"…","pairPort":N,"nodeterm":true,"name":"…"}
- * When a relay block is supplied it is appended as `"relay":{…}` after `name`; otherwise the
- * payload is byte-for-byte the legacy LAN-only shape.
+ * 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.
*/
export function buildPairingPayload(input: PairingPayloadInput): string {
const base = {
@@ -48,7 +55,8 @@ export function buildPairingPayload(input: PairingPayloadInput): string {
nodeterm: true,
name: input.name
}
- return JSON.stringify(input.relay ? { ...base, relay: input.relay } : base)
+ const withKey = input.hostKey ? { ...base, hostKey: input.hostKey } : base
+ return JSON.stringify(input.relay ? { ...withKey, relay: input.relay } : withKey)
}
/**
diff --git a/src/main/pairing-crypto.test.ts b/src/main/pairing-crypto.test.ts
new file mode 100644
index 000000000..af20a017f
--- /dev/null
+++ b/src/main/pairing-crypto.test.ts
@@ -0,0 +1,85 @@
+// End-to-end envelope test for encrypted LAN pairing.
+//
+// Proves the exact wire contract the phone (nodeterm-ios NaClBox) and the host (pairing-service)
+// implement: the phone seals the {token,publicKey,deviceId} request to the host's QR-authenticated
+// public key, the host opens it, seals the response with the same shared key, and the phone opens
+// that. Both sides here use src/main/remote/e2ee.ts (proven wire-compatible with tweetnacl/Sodium),
+// so this locks the envelope shape and the failure mode.
+
+import { describe, it, expect } from 'vitest'
+import {
+ genKeyPair,
+ publicKeyToB64,
+ deriveSharedKey,
+ encrypt,
+ decrypt
+} from './remote/e2ee'
+
+const enc = (s: string): Uint8Array => Uint8Array.from(Buffer.from(s, 'utf8'))
+const dec = (b: Uint8Array): string => Buffer.from(b).toString('utf8')
+
+describe('encrypted pairing envelope (host ↔ phone round-trip)', () => {
+ it('phone seals the request to the host key; host opens it and seals the response back', () => {
+ // Host: long-lived box keypair; its public key is what rides the QR as `hostKey`.
+ const host = genKeyPair()
+ const hostKeyB64 = publicKeyToB64(host.publicKey)
+
+ // --- Phone side ---
+ const eph = genKeyPair()
+ const phoneShared = deriveSharedKey(hostKeyB64, eph.secretKey)
+ const reqPlain = JSON.stringify({
+ token: 'one-time-token',
+ publicKey: 'ssh-ed25519 AAAA phone@nodeterm',
+ deviceId: 'phone-device-uuid'
+ })
+ const reqBox = encrypt(enc(reqPlain), phoneShared)
+ // Over the wire: POST { epk: base64(eph.public), box: base64(reqBox) }
+ const wire = {
+ epk: publicKeyToB64(eph.publicKey),
+ box: Buffer.from(reqBox).toString('base64')
+ }
+
+ // --- Host side ---
+ const hostShared = deriveSharedKey(wire.epk, host.secretKey)
+ const openedReq = decrypt(Uint8Array.from(Buffer.from(wire.box, 'base64')), hostShared)
+ expect(openedReq).not.toBeNull()
+ expect(JSON.parse(dec(openedReq!))).toEqual({
+ token: 'one-time-token',
+ publicKey: 'ssh-ed25519 AAAA phone@nodeterm',
+ deviceId: 'phone-device-uuid'
+ })
+
+ // Host seals the response with the SAME shared key.
+ const respPlain = JSON.stringify({
+ ok: true,
+ deviceId: 'minted-device',
+ agentToken: 'agent-bearer',
+ relay: { hostId: 'h', hostPublicKeyB64: hostKeyB64, relayEndpoint: 'wss://relay' },
+ relayDeviceToken: '90-day-secret'
+ })
+ const respBox = encrypt(enc(respPlain), hostShared)
+ const respWire = { box: Buffer.from(respBox).toString('base64') }
+
+ // --- Phone opens the response ---
+ const openedResp = decrypt(
+ Uint8Array.from(Buffer.from(respWire.box, 'base64')),
+ phoneShared
+ )
+ expect(openedResp).not.toBeNull()
+ const resp = JSON.parse(dec(openedResp!))
+ expect(resp.relayDeviceToken).toBe('90-day-secret')
+ expect(resp.ok).toBe(true)
+ })
+
+ it('a tampered box fails to open (MAC check)', () => {
+ const host = genKeyPair()
+ const eph = genKeyPair()
+ const shared = deriveSharedKey(publicKeyToB64(host.publicKey), eph.secretKey)
+ const box = encrypt(enc('{"token":"t"}'), deriveSharedKey(publicKeyToB64(eph.publicKey), host.secretKey))
+
+ // Flip a byte in the ciphertext region (past the 24-byte nonce).
+ const tampered = Uint8Array.from(box)
+ tampered[tampered.length - 1] ^= 0xff
+ expect(decrypt(tampered, shared)).toBeNull()
+ })
+})
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index 674659bb7..00919516e 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -35,7 +35,7 @@ import {
type RelayPairingBlock
} from './pairing-core'
import type { Settings } from '../shared/types'
-import { publicKeyToB64, type KeyPair } from './remote/e2ee'
+import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'
import { hostIdFromPublicKeyB64 } from './remote/relay-id'
const execFileAsync = promisify(execFile)
@@ -331,6 +331,21 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
// Relay reachability (network-free) — embedded in the QR so the phone can reach us over the
// relay too. Also reused in handleRequest to mint the phone's device token. LAN-only when null.
const relayCtx = await buildRelayContext(relayDeps)
+ // The host's NaCl box keypair — its public key rides the QR as `hostKey` (authenticated by
+ // being shown on this screen), so a new phone can E2EE the whole /pair exchange to it. Loaded
+ // once here and reused to decrypt the request in handleRequest. If the key can't be loaded we
+ // simply omit `hostKey` → the phone falls back to plaintext (never fail pairing over this).
+ let hostKeys: KeyPair | null = null
+ let hostKey: string | undefined
+ if (relayDeps) {
+ try {
+ hostKeys = await relayDeps.loadHostKeyPair()
+ hostKey = publicKeyToB64(hostKeys.publicKey)
+ } catch {
+ hostKeys = null
+ hostKey = undefined
+ }
+ }
const payload = buildPairingPayload({
host,
port: 22,
@@ -338,6 +353,7 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
token,
pairPort,
name,
+ hostKey,
relay: relayCtx?.block
})
@@ -352,13 +368,52 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
}
try {
const raw = await readBody(req)
- let body: { token?: unknown; publicKey?: unknown; deviceName?: unknown; deviceId?: unknown }
+ let outer: { epk?: unknown; box?: unknown } & Record<string, unknown>
try {
- body = JSON.parse(raw)
+ outer = JSON.parse(raw)
} catch {
res.writeHead(400).end('bad json')
return
}
+ // E2EE branch: when the phone sealed the request to our host key, the outer body is
+ // {epk, box}. Derive the shared key from the ephemeral public key + our secret and open
+ // the box to recover the SAME {token, publicKey, deviceId} JSON. A present-but-undecryptable
+ // envelope is a hard 400 — we never fall through to parsing ciphertext as plaintext.
+ let body: { token?: unknown; publicKey?: unknown; deviceName?: unknown; deviceId?: unknown }
+ let sealed: Uint8Array | null = null // the shared key, set only on the encrypted path
+ if (typeof outer.epk === 'string') {
+ if (!hostKeys) {
+ res.writeHead(400).end('no host key')
+ return
+ }
+ let shared: Uint8Array
+ try {
+ shared = deriveSharedKey(outer.epk, hostKeys.secretKey)
+ } catch {
+ res.writeHead(400).end('bad epk')
+ return
+ }
+ const boxB64 = typeof outer.box === 'string' ? outer.box : ''
+ const plain = decrypt(Uint8Array.from(Buffer.from(boxB64, 'base64')), shared)
+ if (!plain) {
+ res.writeHead(400).end('decrypt failed')
+ return
+ }
+ try {
+ body = JSON.parse(Buffer.from(plain).toString('utf8'))
+ } catch {
+ res.writeHead(400).end('bad json')
+ return
+ }
+ sealed = shared
+ } else {
+ body = outer as {
+ token?: unknown
+ publicKey?: unknown
+ deviceName?: unknown
+ deviceId?: unknown
+ }
+ }
if (body.token !== token) {
res.writeHead(403).end('bad token')
return
@@ -402,9 +457,22 @@ export function createPairingService(relayDeps?: PairingRelayDeps): PairingServi
}
}
}
- res
- .writeHead(200, { 'Content-Type': 'application/json' })
- .end(JSON.stringify({ ok: true, deviceId, agentToken, ...relayFields }))
+ // Build the response exactly as before; wrap it in the box only when the request was
+ // encrypted (same shared key), so the relay device token never crosses the LAN in cleartext.
+ const responseObj = { ok: true, deviceId, agentToken, ...relayFields }
+ if (sealed) {
+ const respBox = encrypt(
+ Uint8Array.from(Buffer.from(JSON.stringify(responseObj), 'utf8')),
+ sealed
+ )
+ res
+ .writeHead(200, { 'Content-Type': 'application/json' })
+ .end(JSON.stringify({ box: Buffer.from(respBox).toString('base64') }))
+ } else {
+ res
+ .writeHead(200, { 'Content-Type': 'application/json' })
+ .end(JSON.stringify(responseObj))
+ }
finish({ ok: true })
} catch (err) {
res.writeHead(500).end('pairing failed')