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(remote): pure safeStorage-agnostic keypair file codec

enes335bb66a3398
diff --git a/src/main/remote/key-file-codec.test.ts b/src/main/remote/key-file-codec.test.ts
new file mode 100644
index 000000000..54cd5858c
--- /dev/null
+++ b/src/main/remote/key-file-codec.test.ts
@@ -0,0 +1,70 @@
+import { describe, it, expect } from 'vitest'
+import { encodeKeyFile, decodeKeyFile, type SafeStorageLike } from './key-file-codec'
+import { genKeyPair, publicKeyToB64 } 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.
+function fakeSafe(available: boolean): SafeStorageLike {
+ const flip = (b: Buffer) => Buffer.from(b.map((x) => x ^ 0xff))
+ return {
+ isEncryptionAvailable: () => available,
+ encryptString: (s) => flip(Buffer.from(s, 'utf-8')),
+ decryptString: (b) => flip(b).toString('utf-8')
+ }
+}
+
+describe('key-file-codec', () => {
+ it('round-trips an encrypted key file and never stores the raw secret', () => {
+ const safe = fakeSafe(true)
+ const keys = genKeyPair()
+ const raw = encodeKeyFile(keys, safe)
+ const parsed = JSON.parse(raw) as Record<string, string>
+ 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(
+ Buffer.from(keys.secretKey).toString('hex')
+ )
+ expect(back!.migrate).toBe(false)
+ })
+
+ it('writes plaintext when encryption is unavailable and reads it back', () => {
+ const safe = fakeSafe(false)
+ const keys = genKeyPair()
+ const raw = encodeKeyFile(keys, safe)
+ 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(
+ Buffer.from(keys.publicKey).toString('hex')
+ )
+ 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
+ })
+
+ it('returns null on malformed JSON, missing fields, and an undecryptable blob', () => {
+ const safe = fakeSafe(true)
+ expect(decodeKeyFile('not json', safe)).toBeNull()
+ expect(decodeKeyFile(JSON.stringify({ publicKey: 'x' }), safe)).toBeNull()
+ const throwing: SafeStorageLike = {
+ isEncryptionAvailable: () => true,
+ encryptString: () => Buffer.alloc(0),
+ decryptString: () => {
+ throw new Error('keychain reset')
+ }
+ }
+ const enc = encodeKeyFile(genKeyPair(), safe)
+ expect(decodeKeyFile(enc, throwing)).toBeNull()
+ })
+})
diff --git a/src/main/remote/key-file-codec.ts b/src/main/remote/key-file-codec.ts
new file mode 100644
index 000000000..9f4bc6419
--- /dev/null
+++ b/src/main/remote/key-file-codec.ts
@@ -0,0 +1,71 @@
+// Pure encode/decode for a persisted NaCl box keypair file, with encrypt-at-rest and a legacy
+// plaintext fallback + in-place migration. The Electron `safeStorage` is injected as `SafeStorageLike`
+// so this stays free of `electron` and unit-tests without a keychain. The on-disk byte format mirrors
+// host-service.ts's persistKeyPair/loadOrCreateKeyPair exactly (public key always plaintext base64 —
+// it is a pinned identity, not a secret — the secret key either safeStorage-encrypted or 0600 plaintext).
+//
+// NOTE (intentional duplication): host-service.ts still inlines the same format. We do NOT refactor it
+// to use this codec — that file is Stage 4c's to rewrite, and editing it here would collide. 4c may
+// adopt this codec when it rewrites the handshake.
+import type { KeyPair } from './e2ee'
+
+export interface SafeStorageLike {
+ isEncryptionAvailable(): boolean
+ encryptString(plaintext: string): Buffer
+ decryptString(ciphertext: Buffer): string
+}
+
+interface KeyFileBody {
+ publicKey?: string
+ secretKey?: string // legacy plaintext base64
+ secretKeyEnc?: string // safeStorage ciphertext, base64
+}
+
+/** Serialize a keypair to the on-disk JSON string; encrypted when safeStorage is available. */
+export function encodeKeyFile(keys: KeyPair, safe: SafeStorageLike): string {
+ const publicKey = Buffer.from(keys.publicKey).toString('base64')
+ const secretB64 = Buffer.from(keys.secretKey).toString('base64')
+ const body: KeyFileBody = safe.isEncryptionAvailable()
+ ? { publicKey, secretKeyEnc: safe.encryptString(secretB64).toString('base64') }
+ : { publicKey, secretKey: secretB64 }
+ return JSON.stringify(body)
+}
+
+/**
+ * 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.
+ */
+export function decodeKeyFile(
+ raw: string,
+ safe: SafeStorageLike
+): { keys: KeyPair; migrate: boolean } | null {
+ let body: KeyFileBody
+ try {
+ body = JSON.parse(raw) as KeyFileBody
+ } catch {
+ return null
+ }
+ if (!body.publicKey) return null
+ const publicKey = Uint8Array.from(Buffer.from(body.publicKey, 'base64'))
+ if (body.secretKeyEnc && safe.isEncryptionAvailable()) {
+ try {
+ const secretB64 = safe.decryptString(Buffer.from(body.secretKeyEnc, 'base64'))
+ return {
+ keys: { publicKey, secretKey: Uint8Array.from(Buffer.from(secretB64, 'base64')) },
+ migrate: false
+ }
+ } catch {
+ return null
+ }
+ }
+ if (body.secretKey) {
+ return {
+ keys: { publicKey, secretKey: Uint8Array.from(Buffer.from(body.secretKey, 'base64')) },
+ // Legacy plaintext but a keyring now exists → the caller should re-persist encrypted.
+ migrate: safe.isEncryptionAvailable()
+ }
+ }
+ return null
+}