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(remote): never destroy a pinned peer identity on a transient keyring outage
enese85a5fef89f7
diff --git a/src/main/remote/key-file-codec.test.ts b/src/main/remote/key-file-codec.test.tsindex ca074af0d..f68991f68 100644--- a/src/main/remote/key-file-codec.test.ts+++ b/src/main/remote/key-file-codec.test.ts@@ -1,6 +1,11 @@import { describe, it, expect } from 'vitest'-import { encodeKeyFile, decodeKeyFile, type SafeStorageLike } from './key-file-codec'-import { genKeyPair, publicKeyToB64 } from './e2ee'+import {+ encodeKeyFile,+ decodeKeyFile,+ type KeyFileDecoded,+ type SafeStorageLike+} from './key-file-codec'+import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'// A reversible fake keychain: "encryption" is a byte-flip so we can prove the plaintext secret is// NOT stored verbatim, yet decode round-trips. isEncryptionAvailable is toggled per test.@@ -13,6 +18,13 @@ function fakeSafe(available: boolean): SafeStorageLike {}}+// Narrow the three-way result to the usable one. The union is deliberately NOT `T | null`, so a+// caller cannot reach `.keys` without first ruling out 'locked' — that is the whole point.+function usable(decoded: KeyFileDecoded): { keys: KeyPair; migrate: boolean } {+ if (!decoded || decoded === 'locked') throw new Error(`expected a usable key file, got ${decoded}`)+ return decoded+}+describe('key-file-codec', () => {it('round-trips an encrypted key file and never stores the raw secret', () => {const safe = fakeSafe(true)@@ -22,12 +34,11 @@ describe('key-file-codec', () => {expect(parsed.publicKey).toBe(publicKeyToB64(keys.publicKey))expect(parsed.secretKeyEnc).toBeTypeOf('string')expect(parsed.secretKey).toBeUndefined() // secret is not on disk in the clear- const back = decodeKeyFile(raw, safe)- expect(back).not.toBeNull()- expect(Buffer.from(back!.keys.secretKey).toString('hex')).toBe(+ const back = usable(decodeKeyFile(raw, safe))+ expect(Buffer.from(back.keys.secretKey).toString('hex')).toBe(Buffer.from(keys.secretKey).toString('hex'))- expect(back!.migrate).toBe(false)+ expect(back.migrate).toBe(false)})it('writes plaintext when encryption is unavailable and reads it back', () => {@@ -37,20 +48,47 @@ describe('key-file-codec', () => {const parsed = JSON.parse(raw) as Record<string, string>expect(parsed.secretKey).toBeTypeOf('string')expect(parsed.secretKeyEnc).toBeUndefined()- const back = decodeKeyFile(raw, safe)- expect(Buffer.from(back!.keys.publicKey).toString('hex')).toBe(+ const back = usable(decodeKeyFile(raw, safe))+ expect(Buffer.from(back.keys.publicKey).toString('hex')).toBe(Buffer.from(keys.publicKey).toString('hex'))- expect(back!.migrate).toBe(false)+ expect(back.migrate).toBe(false)})it('flags legacy plaintext for migration when encryption becomes available (same identity)', () => {const keys = genKeyPair()const legacy = encodeKeyFile(keys, fakeSafe(false)) // written on a machine with no keyring- const back = decodeKeyFile(legacy, fakeSafe(true)) // now a keyring exists- expect(back).not.toBeNull()- expect(back!.migrate).toBe(true)- expect(back!.keys.secretKey).toEqual(keys.secretKey) // identity preserved, never regenerated+ const back = usable(decodeKeyFile(legacy, fakeSafe(true))) // now a keyring exists+ expect(back.migrate).toBe(true)+ expect(back.keys.secretKey).toEqual(keys.secretKey) // identity preserved, never regenerated+ })++ // --- the 'locked' outcome: encrypted file, keyring temporarily gone ------------------------+ // This is NOT corruption. The bytes are fine; only the OS keyring is unavailable right now+ // (gnome-keyring not yet unlocked, no session bus). Returning null here would make the caller+ // regenerate and DESTROY a pinned identity, so the codec reports a distinct third outcome.++ it("reports 'locked' for an encrypted file when encryption is currently unavailable", () => {+ const enc = encodeKeyFile(genKeyPair(), fakeSafe(true))+ expect(decodeKeyFile(enc, fakeSafe(false))).toBe('locked')+ })++ it("reports 'locked' even when a stale legacy plaintext secret is also present", () => {+ // A half-migrated file: the encrypted secret is authoritative and the plaintext one may be+ // stale, so with no keyring we must still refuse rather than fall back or regenerate.+ const raw = JSON.stringify({+ publicKey: Buffer.alloc(32, 7).toString('base64'),+ secretKey: Buffer.alloc(32, 7).toString('base64'),+ secretKeyEnc: Buffer.from('whatever').toString('base64')+ })+ expect(decodeKeyFile(raw, fakeSafe(false))).toBe('locked')+ })++ it("does NOT report 'locked' for a plain corrupt file (regenerating is correct there)", () => {+ const safe = fakeSafe(false)+ const pub = Buffer.alloc(32, 7).toString('base64')+ expect(decodeKeyFile('not json', safe)).toBeNull()+ expect(decodeKeyFile(JSON.stringify({ publicKey: pub }), safe)).toBeNull() // no secret at all})it('returns null on malformed JSON, missing fields, and an undecryptable blob', () => {diff --git a/src/main/remote/key-file-codec.ts b/src/main/remote/key-file-codec.tsindex eaafa4196..82a993e71 100644--- a/src/main/remote/key-file-codec.ts+++ b/src/main/remote/key-file-codec.ts@@ -32,15 +32,23 @@ export function encodeKeyFile(keys: KeyPair, safe: SafeStorageLike): string {}/**- * Parse a key file. Returns the keypair plus `migrate:true` when the file is legacy plaintext but- * encryption is now available (caller should re-persist to upgrade in place, KEEPING the identity).- * Returns null on malformed input or an undecryptable blob (e.g. keychain reset) — the caller then- * generates a fresh identity, exactly as host-service.ts does.+ * The three outcomes of reading a key file. They are NOT interchangeable — the caller must branch:+ *+ * - `{ keys, migrate }` — usable. `migrate:true` means the file is legacy plaintext but encryption+ * is now available: re-persist to upgrade in place, KEEPING the identity.+ * - `null` — unusable: malformed JSON, a wrong-length key, or an encrypted blob the (available)+ * keychain cannot decrypt (keychain reset ⇒ the secret is gone for good). Regenerating is the+ * only way forward and is CORRECT here.+ * - `'locked'` — the file is well-formed and holds an ENCRYPTED secret, but `isEncryptionAvailable()`+ * is false RIGHT NOW (keyring not yet unlocked, no session bus, safeStorage backend down). The+ * identity is intact on disk, merely unreadable at this moment. The caller MUST NOT write:+ * regenerating would replace a pinned identity with a fresh (plaintext) one, forcing re-approval+ * on every host that pinned it — unrecoverably. Fail the operation and tell the user to unlock.*/-export function decodeKeyFile(- raw: string,- safe: SafeStorageLike-): { keys: KeyPair; migrate: boolean } | null {+export type KeyFileDecoded = { keys: KeyPair; migrate: boolean } | null | 'locked'++/** Parse a key file. See `KeyFileDecoded` — the three outcomes must not be collapsed into one. */+export function decodeKeyFile(raw: string, safe: SafeStorageLike): KeyFileDecoded {let body: unknowntry {body = JSON.parse(raw)@@ -58,8 +66,12 @@ export function decodeKeyFile(// short/empty "identity" that the caller accepts and only fails much later inside nacl.try {const publicKey = publicKeyFromB64(file.publicKey)- if (file.secretKeyEnc && safe.isEncryptionAvailable()) {- // decryptString may throw (keychain reset) OR return junk — either way we return null.+ if (file.secretKeyEnc) {+ // An encrypted secret is AUTHORITATIVE: never silently fall back to a (possibly stale)+ // plaintext one, and never mistake "no keyring right now" for corruption.+ if (!safe.isEncryptionAvailable()) return 'locked'+ // decryptString may throw (keychain reset) OR return junk — either way the secret is+ // genuinely gone, so that is `null` (regenerate), not `'locked'`.const secretB64 = safe.decryptString(Buffer.from(file.secretKeyEnc, 'base64'))return { keys: { publicKey, secretKey: secretKeyFromB64(secretB64) }, migrate: false }}diff --git a/src/main/remote/peer-identity.test.ts b/src/main/remote/peer-identity.test.tsindex 6a15f0dad..4245e0e0d 100644--- a/src/main/remote/peer-identity.test.ts+++ b/src/main/remote/peer-identity.test.ts@@ -19,19 +19,24 @@ vi.mock('electron', () => ({}}))-import { loadOrCreatePeerKeyPair } from './peer-identity'+import { loadOrCreatePeerKeyPair, PeerKeyLockedError, resetPeerKeyCache } from './peer-identity'import { publicKeyToB64 } from './e2ee'const PEER_FILE = 'remote-peer-key.json'const peerPath = () => path.join(userData, PEER_FILE)const readFile = async () => JSON.parse(await fs.readFile(peerPath(), 'utf-8'))+// The key is loaded once per app run (in-process cache), so a test that simulates a RESTART — a+// changed keyring state, an externally rewritten file — has to drop it, like a new process would.+const restart = () => resetPeerKeyCache()describe('peer-identity: persistent client keypair', () => {beforeEach(async () => {userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-peer-'))encryptionAvailable = false // plaintext path: no keyring needed in CI+ resetPeerKeyCache()})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(userData, { recursive: true, force: true })})@@ -71,6 +76,7 @@ describe('peer-identity: persistent client keypair', () => {expect(onDisk.secretKey).toBeUndefined()expect(onDisk.secretKeyEnc).toBeTypeOf('string')// ...and still loads back to the same identity.+ restart()const again = await loadOrCreatePeerKeyPair()expect(Buffer.from(again.secretKey)).toEqual(Buffer.from(keys.secretKey))})@@ -79,6 +85,7 @@ describe('peer-identity: persistent client keypair', () => {const first = await loadOrCreatePeerKeyPair() // written plaintext (no keyring)expect((await readFile()).secretKey).toBeTypeOf('string')encryptionAvailable = true // machine gains a keyring+ restart()const second = await loadOrCreatePeerKeyPair()expect(publicKeyToB64(second.publicKey)).toBe(publicKeyToB64(first.publicKey))const onDisk = await readFile()@@ -89,11 +96,86 @@ describe('peer-identity: persistent client keypair', () => {it('regenerates and overwrites when the stored file is corrupt', async () => {const first = await loadOrCreatePeerKeyPair()await fs.writeFile(peerPath(), '{"publicKey":"zzz","secretKey":"@@@"}', 'utf-8')+ restart()const second = await loadOrCreatePeerKeyPair()expect(second.publicKey).toHaveLength(32)expect(publicKeyToB64(second.publicKey)).not.toBe(publicKeyToB64(first.publicKey))// The fresh identity is persisted, so it is itself stable from here on.+ restart()const third = await loadOrCreatePeerKeyPair()expect(publicKeyToB64(third.publicKey)).toBe(publicKeyToB64(second.publicKey))})++ // --- keyring locked: the pinned identity must SURVIVE, not be silently replaced -------------+ describe('when the keyring is temporarily unavailable', () => {+ it('fails loudly and leaves the encrypted file untouched (identity survives)', async () => {+ encryptionAvailable = true+ const original = await loadOrCreatePeerKeyPair()+ const before = await fs.readFile(peerPath(), 'utf-8')++ // Next boot: the app starts before gnome-keyring/kwallet is unlocked.+ encryptionAvailable = false+ restart()+ await expect(loadOrCreatePeerKeyPair()).rejects.toBeInstanceOf(PeerKeyLockedError)++ // Nothing was written: the file is byte-identical and still encrypted.+ expect(await fs.readFile(peerPath(), 'utf-8')).toBe(before)+ expect((await readFile()).secretKeyEnc).toBeTypeOf('string')+ expect((await readFile()).secretKey).toBeUndefined()++ // Once the keyring is unlocked, the SAME pinned identity comes back.+ encryptionAvailable = true+ restart()+ const after = await loadOrCreatePeerKeyPair()+ expect(publicKeyToB64(after.publicKey)).toBe(publicKeyToB64(original.publicKey))+ expect(Buffer.from(after.secretKey)).toEqual(Buffer.from(original.secretKey))+ })++ it('does not cache the failure: a later call succeeds once the keyring is back', async () => {+ encryptionAvailable = true+ const original = await loadOrCreatePeerKeyPair()+ encryptionAvailable = false+ restart()+ await expect(loadOrCreatePeerKeyPair()).rejects.toThrow(/keyring/i)+ // No restart() here: the user unlocks the keyring and reconnects in the SAME app run.+ encryptionAvailable = true+ const again = await loadOrCreatePeerKeyPair()+ expect(publicKeyToB64(again.publicKey)).toBe(publicKeyToB64(original.publicKey))+ })+ })++ // --- concurrency: two connects racing on the very first run --------------------------------+ it('two concurrent calls return the SAME keypair and write the file ONCE', async () => {+ const write = vi.spyOn(fs, 'writeFile')+ const [a, b] = await Promise.all([loadOrCreatePeerKeyPair(), loadOrCreatePeerKeyPair()])+ expect(publicKeyToB64(a.publicKey)).toBe(publicKeyToB64(b.publicKey))+ expect(Buffer.from(a.secretKey)).toEqual(Buffer.from(b.secretKey))+ expect(write).toHaveBeenCalledTimes(1)+ // ...and the key that is on disk is the one BOTH callers hold (no silent loser).+ expect((await readFile()).publicKey).toBe(publicKeyToB64(a.publicKey))+ })++ it('reuses the in-process key without re-reading the file on every call', async () => {+ await loadOrCreatePeerKeyPair()+ const read = vi.spyOn(fs, 'readFile')+ await loadOrCreatePeerKeyPair()+ expect(read).not.toHaveBeenCalled()+ })++ // --- the 0600 mode is enforced on EVERY write, not only at create ---------------------------+ it('tightens a pre-existing 0644 file to 0600 when migrating it', async () => {+ await loadOrCreatePeerKeyPair() // plaintext file+ await fs.chmod(peerPath(), 0o644) // e.g. recreated by a backup/restore tool+ encryptionAvailable = true // triggers the in-place migration write+ restart()+ await loadOrCreatePeerKeyPair()+ expect((await fs.stat(peerPath())).mode & 0o777).toBe(0o600)+ })++ it('tightens a pre-existing 0644 file to 0600 when regenerating over it', async () => {+ await fs.writeFile(peerPath(), 'garbage', { encoding: 'utf-8', mode: 0o644 })+ await fs.chmod(peerPath(), 0o644)+ await loadOrCreatePeerKeyPair()+ expect((await fs.stat(peerPath())).mode & 0o777).toBe(0o600)+ })})diff --git a/src/main/remote/peer-identity.ts b/src/main/remote/peer-identity.tsindex ef97968da..e10d2a3fc 100644--- a/src/main/remote/peer-identity.ts+++ b/src/main/remote/peer-identity.ts@@ -4,10 +4,15 @@// presents a different box public key on every reconnect and can never be pinned. This gives the// client a long-lived NaCl box keypair — the STABLE public identity a host pins on first pair and// recognises across reconnects. It mirrors host-service.ts's loadOrCreateKeyPair (same on-disk-// shape, same failure posture) but uses its OWN file, so the peer and host identities never share-// bytes. Encrypted at rest with Electron safeStorage; 0600 plaintext fallback when no keyring is-// available — availability is re-checked on every load, so a machine that gains a keyring migrates-// in place on the next start, KEEPING the identity.+// shape) but uses its OWN file, so the peer and host identities never share bytes. Encrypted at+// rest with Electron safeStorage; 0600 plaintext fallback when no keyring is available —+// availability is re-checked on every start, so a machine that gains a keyring migrates in place,+// KEEPING the identity.+//+// The key is an IDENTITY, not a session artefact: losing a connection is recoverable, losing the+// key means every host that pinned it must re-approve this peer. 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): that fails loudly instead. See PeerKeyLockedError.//// 4c wires this into client-service.ts in place of `genKeyPair()`.import { promises as fs } from 'fs'@@ -16,36 +21,90 @@ import { app, safeStorage } from 'electron'import { genKeyPair, type KeyPair } from './e2ee'import { encodeKeyFile, decodeKeyFile } from './key-file-codec'+/**+ * The stored 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.+ * The connection path should surface this to the user: unlock the keyring and reconnect.+ */+export class PeerKeyLockedError extends Error {+ readonly code = 'E_PEER_KEY_LOCKED'+ constructor() {+ super(+ 'Your device identity is encrypted, but the OS keyring is locked or unavailable. ' ++ 'Unlock it and reconnect — the key is intact and will not be replaced.'+ )+ this.name = 'PeerKeyLockedError'+ }+}+function keyFile(): string {return path.join(app.getPath('userData'), 'remote-peer-key.json')}-async function persistKeyPair(keys: KeyPair): Promise<void> {- // 0o600 either way: the file still binds the pinned public identity.- await fs.writeFile(keyFile(), encodeKeyFile(keys, safeStorage), {- encoding: 'utf-8',- mode: 0o600- })+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)}-/**- * Load the long-lived client (peer) keypair, generating + persisting it on first use. The public key- * is what a host pins, so it must be stable across reconnects and app restarts. A legacy plaintext- * file upgrades to the encrypted form in place (same identity); a malformed file or an undecryptable- * blob (keychain reset) decodes to null and falls through to a fresh identity, which is written back- * so it is itself stable from then on — a new pairing then pins the new key.- */-export async function loadOrCreatePeerKeyPair(): Promise<KeyPair> {+async function readKeyFile(file: string): Promise<string | null> {try {- const decoded = decodeKeyFile(await fs.readFile(keyFile(), 'utf-8'), safeStorage)+ 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 PeerKeyLockedError() // intact identity: do NOT writeif (decoded) {- if (decoded.migrate) await persistKeyPair(decoded.keys).catch(() => {})+ if (decoded.migrate) await persistKeyPair(file, decoded.keys).catch(() => {})return decoded.keys}- } catch {- // No stored key (first run) or an unreadable file — generate a fresh one below.+ // decoded === null → malformed or undecryptable for good; a fresh identity is the only option.}const keys = genKeyPair()- await persistKeyPair(keys).catch(() => {})+ await persistKeyPair(file, keys).catch(() => {})return keys}++// One identity per app run. Without this, two connects racing on the very FIRST run each generate a+// key and each write: last write wins and the loser holds a key that is not on disk — if that one+// gets pinned, the host pins an identity that never comes back. Caching the promise also drops a+// disk read per reconnect. 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 client (peer) keypair, generating + persisting it on first use. The public+ * key is what a host pins, so it must be stable across reconnects and app restarts.+ *+ * @throws PeerKeyLockedError when an encrypted key exists but the keyring is currently unavailable.+ */+export function loadOrCreatePeerKeyPair(): 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 resetPeerKeyCache(): void {+ inflight = null+ inflightFile = null+}