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
fix(relay): a locked keyring never rotates the host identity (adopt key-file-codec)
enesa5b68b7782ca
diff --git a/src/main/remote/host-identity.test.ts b/src/main/remote/host-identity.test.tsnew file mode 100644index 000000000..0a2d9b959--- /dev/null+++ b/src/main/remote/host-identity.test.ts@@ -0,0 +1,151 @@+// The HOST's long-lived identity: the key every paired peer PINS. Losing it is not a recoverable+// blip — every peer must re-approve — so the one thing these tests really guard is that we never+// write over a key we merely cannot READ right now (locked keyring). Mirrors peer-identity.test.ts.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'++let userData = ''+let encryptionAvailable = false++const flip = (b: Buffer) => Buffer.from(b.map((x) => x ^ 0xff))++vi.mock('electron', () => ({+ app: { getPath: () => userData },+ safeStorage: {+ isEncryptionAvailable: () => encryptionAvailable,+ encryptString: (s: string) => flip(Buffer.from(s, 'utf-8')),+ decryptString: (b: Buffer) => flip(b).toString('utf-8')+ }+}))++import { loadOrCreateHostKeyPair, HostKeyLockedError, resetHostKeyCache } from './host-identity'+import { publicKeyToB64 } from './e2ee'++const hostPath = () => path.join(userData, 'remote-host-key.json')+const readFile = async () => JSON.parse(await fs.readFile(hostPath(), 'utf-8'))+/** Drop the in-process cache — i.e. simulate an app restart. */+const restart = () => resetHostKeyCache()++describe('host-identity: persistent host keypair', () => {+ beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-host-'))+ encryptionAvailable = false+ resetHostKeyCache()+ })+ afterEach(async () => {+ vi.restoreAllMocks()+ await fs.rm(userData, { recursive: true, force: true })+ })++ it('generates and persists a keypair on first use, 0600', async () => {+ const keys = await loadOrCreateHostKeyPair()+ expect(keys.publicKey).toHaveLength(32)+ expect((await readFile()).publicKey).toBe(publicKeyToB64(keys.publicKey))+ expect((await fs.stat(hostPath())).mode & 0o777).toBe(0o600)+ })++ it('returns the SAME public key across restarts (the pinned identity is stable)', async () => {+ const first = await loadOrCreateHostKeyPair()+ restart()+ const second = await loadOrCreateHostKeyPair()+ expect(publicKeyToB64(second.publicKey)).toBe(publicKeyToB64(first.publicKey))+ expect(Buffer.from(second.secretKey)).toEqual(Buffer.from(first.secretKey))+ })++ it('does not collide with the peer key file', async () => {+ await loadOrCreateHostKeyPair()+ await expect(fs.access(path.join(userData, 'remote-peer-key.json'))).rejects.toThrow()+ })++ it('writes the legacy plaintext shape when no keyring is available (byte-compatible)', async () => {+ const keys = await loadOrCreateHostKeyPair()+ const onDisk = await readFile()+ expect(Object.keys(onDisk).sort()).toEqual(['publicKey', 'secretKey'])+ expect(onDisk.secretKey).toBe(Buffer.from(keys.secretKey).toString('base64'))+ })++ it('encrypts the secret at rest when safeStorage is available', async () => {+ encryptionAvailable = true+ const keys = await loadOrCreateHostKeyPair()+ const onDisk = await readFile()+ expect(onDisk.secretKey).toBeUndefined()+ expect(onDisk.secretKeyEnc).toBeTypeOf('string')+ restart()+ expect(Buffer.from((await loadOrCreateHostKeyPair()).secretKey)).toEqual(+ Buffer.from(keys.secretKey)+ )+ })++ it('migrates a legacy plaintext file in place, KEEPING the identity', async () => {+ const first = await loadOrCreateHostKeyPair()+ encryptionAvailable = true+ restart()+ const second = await loadOrCreateHostKeyPair()+ expect(publicKeyToB64(second.publicKey)).toBe(publicKeyToB64(first.publicKey))+ const onDisk = await readFile()+ expect(onDisk.secretKey).toBeUndefined()+ expect(onDisk.secretKeyEnc).toBeTypeOf('string')+ })++ it('regenerates when the stored file is corrupt', async () => {+ const first = await loadOrCreateHostKeyPair()+ await fs.writeFile(hostPath(), '{"publicKey":"zzz","secretKey":"@@@"}', 'utf-8')+ restart()+ const second = await loadOrCreateHostKeyPair()+ expect(second.publicKey).toHaveLength(32)+ expect(publicKeyToB64(second.publicKey)).not.toBe(publicKeyToB64(first.publicKey))+ })++ // --- obligation 5: a locked keyring must NEVER rotate the host identity ----------------------+ it('a locked keyring NEVER overwrites the encrypted host key (obligation 5)', async () => {+ // Arrange: an encrypted key file written while the keyring was available.+ encryptionAvailable = true+ const first = await loadOrCreateHostKeyPair()+ const before = await fs.readFile(hostPath(), 'utf-8')+ restart()++ // Act: reboot with the keyring locked (gnome-keyring not yet unlocked, no session bus).+ encryptionAvailable = false+ await expect(loadOrCreateHostKeyPair()).rejects.toMatchObject({ code: 'E_HOST_KEY_LOCKED' })+ await expect(loadOrCreateHostKeyPair()).rejects.toBeInstanceOf(HostKeyLockedError)++ // Assert: the identity is intact on disk — byte for byte — and recoverable once unlocked.+ expect(await fs.readFile(hostPath(), 'utf-8')).toBe(before)+ encryptionAvailable = true+ restart()+ expect(publicKeyToB64((await loadOrCreateHostKeyPair()).publicKey)).toBe(+ publicKeyToB64(first.publicKey)+ )+ })++ it('does not cache the failure: a later call succeeds once the keyring is back', async () => {+ encryptionAvailable = true+ const original = await loadOrCreateHostKeyPair()+ encryptionAvailable = false+ restart()+ await expect(loadOrCreateHostKeyPair()).rejects.toThrow(/keyring/i)+ // No restart(): the user unlocks the keyring and re-enables hosting in the SAME app run.+ encryptionAvailable = true+ const again = await loadOrCreateHostKeyPair()+ expect(publicKeyToB64(again.publicKey)).toBe(publicKeyToB64(original.publicKey))+ })++ it('two concurrent callers share ONE keypair and write the file once', async () => {+ const write = vi.spyOn(fs, 'writeFile')+ const [a, b] = await Promise.all([loadOrCreateHostKeyPair(), loadOrCreateHostKeyPair()])+ expect(publicKeyToB64(a.publicKey)).toBe(publicKeyToB64(b.publicKey))+ expect(write).toHaveBeenCalledTimes(1)+ expect((await readFile()).publicKey).toBe(publicKeyToB64(a.publicKey))+ })++ it('tightens a pre-existing 0644 file to 0600 on migration', async () => {+ await loadOrCreateHostKeyPair()+ await fs.chmod(hostPath(), 0o644)+ encryptionAvailable = true+ restart()+ await loadOrCreateHostKeyPair()+ expect((await fs.stat(hostPath())).mode & 0o777).toBe(0o600)+ })+})diff --git a/src/main/remote/host-identity.ts b/src/main/remote/host-identity.tsnew file mode 100644index 000000000..89bfdf19f--- /dev/null+++ b/src/main/remote/host-identity.ts@@ -0,0 +1,113 @@+// Persistent HOST identity for the relay transport.+//+// The host's box public key IS its identity: it hashes to the hostId a peer dials, and every peer+// that pairs with this desktop PINS it. Rotating it is not a recoverable blip — every pinned peer+// must re-approve and the old key is gone for good.+//+// This is the same shape as peer-identity.ts (its reference implementation), against its OWN file+// `remote-host-key.json`, and the on-disk bytes are unchanged from the format host-service.ts used+// to inline: public key plaintext base64 (it is a pinned identity, not a secret), secret key either+// safeStorage-encrypted (`secretKeyEnc`) or 0600 plaintext (`secretKey`), migrated in place once a+// keyring appears.+//+// So we write on exactly three paths — first run, in-place migration, a genuinely unusable file —+// and NEVER on a file we merely cannot read RIGHT NOW (keyring locked, no session bus). That case+// fails loudly with HostKeyLockedError: the identity on disk is intact and must stay that way.+// The old inline loader got this wrong — it read `secretKeyEnc` only when+// `safeStorage.isEncryptionAvailable()`, so a boot before gnome-keyring/kwallet unlocked fell+// through to `genKeyPair()` and overwrote the good encrypted key with a fresh plaintext one.+import { promises as fs } from 'fs'+import path from 'path'+import { app, safeStorage } from 'electron'+import { genKeyPair, type KeyPair } from './e2ee'+import { encodeKeyFile, decodeKeyFile } from './key-file-codec'++/**+ * The stored host identity is encrypted and the OS keyring is unavailable right now (locked+ * gnome-keyring/kwallet, no session bus). The key is intact on disk and we refuse to overwrite it.+ * Hosting cannot start until it can be read: surface this to the user — unlock the keyring and+ * start hosting again.+ */+export class HostKeyLockedError extends Error {+ readonly code = 'E_HOST_KEY_LOCKED'+ constructor() {+ super(+ 'This computer’s host identity is encrypted, but the OS keyring is locked or unavailable. ' ++ 'Unlock it and start remote access again — the key is intact and will not be replaced.'+ )+ this.name = 'HostKeyLockedError'+ }+}++function keyFile(): string {+ return path.join(app.getPath('userData'), 'remote-host-key.json')+}++async function persistKeyPair(file: string, keys: KeyPair): Promise<void> {+ // `mode` in writeFile only applies when the file is CREATED — an existing file (migration,+ // regeneration, or one a backup tool restored 0644) keeps its old mode. So chmod on every write.+ await fs.writeFile(file, encodeKeyFile(keys, safeStorage), { encoding: 'utf-8', mode: 0o600 })+ await fs.chmod(file, 0o600)+}++async function readKeyFile(file: string): Promise<string | null> {+ try {+ return await fs.readFile(file, 'utf-8')+ } catch (err) {+ // ENOENT is the only "no identity yet" case. Any other read failure (EACCES, EIO) means a file+ // may well be there and simply unreadable — regenerating over it would destroy the identity.+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null+ throw err+ }+}++async function loadOrCreate(file: string): Promise<KeyPair> {+ const raw = await readKeyFile(file)+ if (raw !== null) {+ const decoded = decodeKeyFile(raw, safeStorage)+ if (decoded === 'locked') throw new HostKeyLockedError() // intact identity: do NOT write+ if (decoded) {+ if (decoded.migrate) await persistKeyPair(file, decoded.keys).catch(() => {})+ return decoded.keys+ }+ // decoded === null → malformed or undecryptable for good; a fresh identity is the only option.+ }+ const keys = genKeyPair()+ await persistKeyPair(file, keys).catch(() => {})+ return keys+}++// One identity per app run. Without this, the interactive host and the standing host racing on the+// very FIRST run each generate a key and each write: last write wins and the loser advertises a+// public key that is not on disk — a peer that pins it pins an identity that never comes back.+// Caching the promise also drops a disk read per connect. Failures are NOT cached: unlock the+// keyring and the next call retries.+let inflight: Promise<KeyPair> | null = null+let inflightFile: string | null = null++/**+ * Load the long-lived host keypair, generating + persisting it on first use. Its public key is+ * pinned by every paired peer, so it must be stable across runs.+ *+ * @throws HostKeyLockedError when an encrypted key exists but the keyring is currently unavailable.+ */+export function loadOrCreateHostKeyPair(): Promise<KeyPair> {+ const file = keyFile()+ if (inflight && inflightFile === file) return inflight+ const pending = loadOrCreate(file)+ inflight = pending+ inflightFile = file+ pending.catch(() => {+ if (inflight === pending) {+ inflight = null+ inflightFile = null+ }+ })+ return pending+}++/** Test seam: drop the in-process cache, i.e. simulate an app restart. */+export function resetHostKeyCache(): void {+ inflight = null+ inflightFile = null+}diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex e585917c9..f0ef69fe9 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -20,17 +20,17 @@// The pure RPC/frame -> pty-manager mapping lives in `createHostHandlers` so it is unit-// testable with fakes; `initRemoteHost` wires it to IPC, the license gate, and the API call.-import { promises as fs } from 'fs'import { randomUUID } from 'crypto'import path from 'path'-import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'+import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'import type { AgentId } from '../../shared/agents/config'import { PtyManager, type DetachedSinks } from '../../core/pty-manager'import * as fsOps from '../../core/fs-ops'import { getStoredEntitlement, isPremium } from '../../core/license'-import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'+import { publicKeyToB64, type KeyPair } from './e2ee'+import { loadOrCreateHostKeyPair, HostKeyLockedError } from './host-identity'import { OP, type Frame } from './framing'import { encodeOffer } from './pairing'import { sanitizeClientMutation } from './canvas-sync'@@ -518,63 +518,16 @@ async function mintPairingToken(entitlement: string): Promise<PairTokenResponse>// --- persisted host keypair ---------------------------------------------------function keyFile(): string {- return path.join(app.getPath('userData'), 'remote-host-key.json')-}--// R4: the secret key is encrypted at rest with Electron safeStorage (macOS: key held in the-// user's Keychain), so `remote-host-key.json` alone no longer yields the host's E2EE identity.-// Fallback when OS encryption is unavailable (e.g. Linux without a keyring): plaintext at-// 0o600, as before — availability is re-checked on every load, so a machine that gains a-// keyring migrates on the next start.-async function persistKeyPair(keys: KeyPair): Promise<void> {- const publicKey = Buffer.from(keys.publicKey).toString('base64')- const secretB64 = Buffer.from(keys.secretKey).toString('base64')- const body = safeStorage.isEncryptionAvailable()- ? { publicKey, secretKeyEnc: safeStorage.encryptString(secretB64).toString('base64') }- : { publicKey, secretKey: secretB64 }- // 0o600 either way: the file still binds the pinned public identity.- await fs.writeFile(keyFile(), JSON.stringify(body), { encoding: 'utf-8', mode: 0o600 })-}--// Load the long-lived host NaCl keypair, generating + persisting it on first use. The public-// key is pinned in every offer, so it must be stable across runs. Legacy plaintext files are-// migrated to the encrypted form in place, KEEPING the identity (never regenerate on migrate);-// an undecryptable blob (OS keychain reset) falls through to a fresh identity — old offers are-// single-use pairing tokens, so new offers simply carry the new key.+// The keypair now lives in host-identity.ts (same on-disk file + bytes: `remote-host-key.json`,+// public key plaintext base64, secret key safeStorage-encrypted or 0600 plaintext). The loader+// that used to be inlined here rotated the identity whenever the keyring happened to be locked at+// boot — it read `secretKeyEnc` only when `isEncryptionAvailable()`, missed both branches, and+// regenerated OVER the good encrypted key. host-identity refuses to write in that case+// (HostKeyLockedError) via key-file-codec's `'locked'` outcome.//-// Exported so the standing (phone) host and the pairing service can advertise the SAME host-// identity (public key → hostId) the interactive host uses.-export async function loadOrCreateKeyPair(): Promise<KeyPair> {- try {- const raw = JSON.parse(await fs.readFile(keyFile(), 'utf-8')) as {- publicKey?: string- secretKey?: string- secretKeyEnc?: string- }- if (raw.publicKey && raw.secretKeyEnc && safeStorage.isEncryptionAvailable()) {- const secretB64 = safeStorage.decryptString(Buffer.from(raw.secretKeyEnc, 'base64'))- return {- publicKey: Uint8Array.from(Buffer.from(raw.publicKey, 'base64')),- secretKey: Uint8Array.from(Buffer.from(secretB64, 'base64'))- }- }- if (raw.publicKey && raw.secretKey) {- const keys: KeyPair = {- publicKey: Uint8Array.from(Buffer.from(raw.publicKey, 'base64')),- secretKey: Uint8Array.from(Buffer.from(raw.secretKey, 'base64'))- }- // Legacy plaintext on disk → re-persist encrypted (same identity).- if (safeStorage.isEncryptionAvailable()) await persistKeyPair(keys).catch(() => {})- return keys- }- } catch {- // No (valid/decryptable) stored key — generate a fresh one below.- }- const keys = genKeyPair()- await persistKeyPair(keys).catch(() => {})- return keys-}+// Re-exported under the old name so the standing (phone) host and the pairing service keep+// advertising the SAME host identity through their existing import.+export { loadOrCreateHostKeyPair as loadOrCreateKeyPair, HostKeyLockedError }// --- dev gate ----------------------------------------------------------------@@ -806,7 +759,7 @@ export function initRemoteHost(// Already hosting → tear the old session down before starting a fresh one.endSession()- const keys = await loadOrCreateKeyPair()+ const keys = await loadOrCreateHostKeyPair()const { pairingToken } = await mintPairingToken(entitlement)// This session's presence slot, captured by its own callbacks (never read through `presence`,diff --git a/src/main/remote/standing-host.test.ts b/src/main/remote/standing-host.test.tsindex 484e0890d..41c1f26bf 100644--- a/src/main/remote/standing-host.test.ts+++ b/src/main/remote/standing-host.test.ts@@ -13,12 +13,16 @@ import { presenceHub } from '../../core/presence/hub'import type { HostSession, HostSessionOptions } from './host-service'const ipc: Record<string, (e: unknown, msg: unknown) => void> = {}+const errorBoxes: Array<{ title: string; body: string }> = []vi.mock('electron', () => ({ipcMain: {on: (ch: string, fn: (e: unknown, msg: unknown) => void) => {ipc[ch] = fn}+ },+ dialog: {+ showErrorBox: (title: string, body: string) => errorBoxes.push({ title, body })}}))vi.mock('../../core/pty-manager', () => ({ PtyManager: class {} }))@@ -39,11 +43,18 @@ vi.mock('./e2ee', () => ({ publicKeyToB64: () => 'host-pub' }))const sessions: Array<{ opts: HostSessionOptions; session: HostSession; closed: number }> = []+// Swappable: a locked OS keyring makes the host key unreadable, and loading it REJECTS rather than+// rotating the pinned identity (host-identity.ts). The standing host must handle that, loudly.+let keyError: Error | null = null+vi.mock('./host-service', () => ({API_BASE: 'https://api.test',RELAY_URL: 'wss://relay.test',relayAllowed: () => true,- loadOrCreateKeyPair: async () => ({ publicKey: new Uint8Array(), secretKey: new Uint8Array() }),+ loadOrCreateKeyPair: async () => {+ if (keyError) throw keyError+ return { publicKey: new Uint8Array(), secretKey: new Uint8Array() }+ },connectHostSession: (opts: HostSessionOptions): HostSession => {const entry = { opts, closed: 0, session: null as unknown as HostSession }entry.session = {@@ -94,6 +105,9 @@ function pendingApprovalId(): string {beforeEach(() => {initPlatform(fakePlatform())sessions.length = 0+ sentToWin.length = 0+ errorBoxes.length = 0+ keyError = nullfor (const key of Object.keys(ipc)) delete ipc[key]vi.stubGlobal('fetch',@@ -180,3 +194,27 @@ describe('standing host presence peers', () => {presenceHub.leave(id)})})++describe('standing host: the host key cannot be read (locked keyring)', () => {+ it('stops loudly instead of retrying into a dead listener', async () => {+ keyError = Object.assign(new Error('the OS keyring is locked'), {+ code: 'E_HOST_KEY_LOCKED'+ })+ const host = makeHost()+ host.setEnabled(true)+ await settle()++ // Nothing was registered at the relay (no key ⇒ no identity to advertise) and, crucially,+ // the failure is not swallowed: the user is told, once, what happened and how to recover.+ expect(sessions).toHaveLength(0)+ expect(errorBoxes).toHaveLength(1)+ expect(errorBoxes[0].body).toMatch(/keyring/i)++ // Bounded: no reconnect storm re-raising the dialog every second.+ await settle()+ expect(errorBoxes).toHaveLength(1)+ expect(sessions).toHaveLength(0)++ host.stop()+ })+})diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex fadd9cb33..d815a961b 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -18,13 +18,13 @@// unit-tested `approved-devices-core`.import { randomUUID } from 'crypto'-import { ipcMain, type BrowserWindow } from 'electron'+import { dialog, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import type { CanvasMutation, Settings } from '../../shared/types'import { PtyManager } from '../../core/pty-manager'import { getStoredEntitlement, isPremium } from '../../core/license'import { createPhonePresence, type PhonePresence } from './phone-presence'-import { publicKeyToB64 } from './e2ee'+import { publicKeyToB64, type KeyPair } from './e2ee'import {API_BASE,RELAY_URL,@@ -76,6 +76,32 @@ async function mintHostToken(}}+/**+ * The stored host identity is encrypted and the keyring is locked/unavailable right now (see+ * host-identity.ts). Matched by `code`, not `instanceof`: the error crosses a module re-export and+ * the code is the stable contract.+ */+function isHostKeyLocked(err: unknown): boolean {+ return (err as { code?: string } | null)?.code === 'E_HOST_KEY_LOCKED'+}++/**+ * A locked keyring is a LOUD, recoverable failure: the key on disk is intact, hosting simply+ * cannot start until the OS can decrypt it. The standing host runs with no UI of its own, so+ * without this the user would just find phone access mysteriously dead.+ */+function reportKeyLocked(err: Error): void {+ try {+ dialog.showErrorBox(+ 'Remote access could not start',+ `${err.message}\n\nPhone access is off until then. Turn it back on in Settings → Phone once your keyring is unlocked.`+ )+ } catch {+ // No dialog available (headless / very early boot): the console line is the fallback.+ }+ console.error('[standing-host] host identity is locked:', err.message)+}+export interface StandingHost {/** Explicit toggle (from the Settings switch). Reconciles the connection immediately. */setEnabled(enabled: boolean): void@@ -247,7 +273,22 @@ export function initStandingHost(if (!isPremium()) return stop()const entitlement = getStoredEntitlement()if (!entitlement) return stop()- const keys = await loadOrCreateKeyPair()+ // The host key is the identity every paired phone PINNED. If the OS keyring is locked we+ // cannot READ it (host-identity refuses to regenerate over it — that would rotate the+ // identity and force every phone to re-approve). There is nothing to advertise, so stop:+ // retrying would spin a dead listener and swallow the reason. Tell the human instead.+ let keys: KeyPair+ try {+ keys = await loadOrCreateKeyPair()+ } catch (err) {+ if (isHostKeyLocked(err)) {+ stop()+ reportKeyLocked(err as Error)+ return+ }+ scheduleReconnect() // transient disk error: back off and try again+ return+ }const token = await mintHostToken(entitlement, publicKeyToB64(keys.publicKey))if (!running) returnif (!token) {