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.

fix(remote): reject malformed key files instead of accepting garbage keys

enesec606224ec0d
diff --git a/src/main/remote/e2ee.ts b/src/main/remote/e2ee.ts
index 5f075121c..11e986d86 100644
--- a/src/main/remote/e2ee.ts
+++ b/src/main/remote/e2ee.ts
@@ -27,6 +27,17 @@ export function publicKeyFromB64(b64: string): Uint8Array {
return key
}
+// Same strictness for a secret key: `Buffer.from(x, 'base64')` silently drops non-alphabet
+// characters and truncates, so a corrupt/short blob would otherwise decode to a short-but-accepted
+// key that only blows up ("bad secret key size") deep inside a later nacl.box call.
+export function secretKeyFromB64(b64: string): Uint8Array {
+ const key = Uint8Array.from(Buffer.from(b64, 'base64'))
+ if (key.length !== nacl.box.secretKeyLength) {
+ throw new Error(`Invalid secret key: expected ${nacl.box.secretKeyLength} bytes, got ${key.length}`)
+ }
+ return key
+}
+
// Derive the shared secret (ECDH precompute) from the peer's base64 public key
// and our secret key. Both sides arrive at the same value. This is the STABLE
// per-device-pair key (both endpoints use static keys for pin-once), so it must
diff --git a/src/main/remote/key-file-codec.test.ts b/src/main/remote/key-file-codec.test.ts
index 54cd5858c..ca074af0d 100644
--- a/src/main/remote/key-file-codec.test.ts
+++ b/src/main/remote/key-file-codec.test.ts
@@ -67,4 +67,57 @@ describe('key-file-codec', () => {
const enc = encodeKeyFile(genKeyPair(), safe)
expect(decodeKeyFile(enc, throwing)).toBeNull()
})
+
+ // --- negative half: a corrupt file must NEVER decode to an accepted identity ---------------
+ // The caller treats null as "regenerate a fresh identity", so every malformed input below has to
+ // return null (and never throw) — an accepted-but-wrong keypair would surface much later as a
+ // tweetnacl "bad key size" throw deep inside the transport.
+
+ const b64 = (bytes: number) => Buffer.alloc(bytes, 7).toString('base64')
+
+ it('returns null on non-object JSON literals (including the `null` literal)', () => {
+ const safe = fakeSafe(false)
+ for (const raw of ['null', '[]', '123', '"str"', 'true', '']) {
+ expect(decodeKeyFile(raw, safe), `input: ${JSON.stringify(raw)}`).toBeNull()
+ }
+ })
+
+ it('returns null on a wrong-length public key (short or long)', () => {
+ const safe = fakeSafe(false)
+ const secretKey = b64(32)
+ expect(decodeKeyFile(JSON.stringify({ publicKey: b64(16), secretKey }), safe)).toBeNull()
+ expect(decodeKeyFile(JSON.stringify({ publicKey: b64(64), secretKey }), safe)).toBeNull()
+ })
+
+ it('returns null on a wrong-length secret key (short or long)', () => {
+ const safe = fakeSafe(false)
+ const publicKey = b64(32)
+ expect(decodeKeyFile(JSON.stringify({ publicKey, secretKey: b64(15) }), safe)).toBeNull()
+ expect(decodeKeyFile(JSON.stringify({ publicKey, secretKey: b64(48) }), safe)).toBeNull()
+ })
+
+ it('returns null on truncated / non-base64 garbage instead of accepting empty keys', () => {
+ const safe = fakeSafe(false)
+ // `Buffer.from(x, 'base64')` is lenient: it drops non-alphabet chars and truncates.
+ const garbage = ['x', 'y', '!!!!', '@@@ not base64 @@@', b64(32).slice(0, 10)]
+ for (const bad of garbage) {
+ expect(decodeKeyFile(JSON.stringify({ publicKey: bad, secretKey: b64(32) }), safe)).toBeNull()
+ expect(decodeKeyFile(JSON.stringify({ publicKey: b64(32), secretKey: bad }), safe)).toBeNull()
+ }
+ expect(decodeKeyFile('{"publicKey":"x","secretKey":"y"}', safe)).toBeNull()
+ })
+
+ it('returns null when the keychain decrypts to junk instead of throwing', () => {
+ // We cannot verify what real Electron safeStorage does on a keychain reset (throw vs. garbage),
+ // so the codec must be robust to BOTH.
+ const junk = (out: string): SafeStorageLike => ({
+ isEncryptionAvailable: () => true,
+ encryptString: (s) => Buffer.from(s, 'utf-8'),
+ decryptString: () => out
+ })
+ const enc = encodeKeyFile(genKeyPair(), fakeSafe(true))
+ expect(decodeKeyFile(enc, junk('garbage not base64'))).toBeNull()
+ expect(decodeKeyFile(enc, junk(''))).toBeNull()
+ expect(decodeKeyFile(enc, junk(b64(15)))).toBeNull() // right shape, wrong length
+ })
})
diff --git a/src/main/remote/key-file-codec.ts b/src/main/remote/key-file-codec.ts
index 9f4bc6419..eaafa4196 100644
--- a/src/main/remote/key-file-codec.ts
+++ b/src/main/remote/key-file-codec.ts
@@ -7,7 +7,7 @@
// 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'
+import { publicKeyFromB64, secretKeyFromB64, type KeyPair } from './e2ee'
export interface SafeStorageLike {
isEncryptionAvailable(): boolean
@@ -41,31 +41,37 @@ export function decodeKeyFile(
raw: string,
safe: SafeStorageLike
): { keys: KeyPair; migrate: boolean } | null {
- let body: KeyFileBody
+ let body: unknown
try {
- body = JSON.parse(raw) as KeyFileBody
+ body = JSON.parse(raw)
} 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'))
+ // `JSON.parse` happily yields null / arrays / numbers for a truncated or aborted write; only a
+ // plain object can be a key file. (Without this, the literal `null` threw a TypeError below.)
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return null
+ const file = body as KeyFileBody
+ if (!file.publicKey) return null
+
+ // Both key parsers are STRICT about the 32-byte length and throw otherwise — base64 decoding is
+ // lenient (drops junk chars, truncates), so a corrupt file would otherwise decode to a
+ // 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.
+ const secretB64 = safe.decryptString(Buffer.from(file.secretKeyEnc, 'base64'))
+ return { keys: { publicKey, secretKey: secretKeyFromB64(secretB64) }, migrate: false }
+ }
+ if (file.secretKey) {
return {
- keys: { publicKey, secretKey: Uint8Array.from(Buffer.from(secretB64, 'base64')) },
- migrate: false
+ keys: { publicKey, secretKey: secretKeyFromB64(file.secretKey) },
+ // Legacy plaintext but a keyring now exists → the caller should re-persist encrypted.
+ migrate: safe.isEncryptionAvailable()
}
- } 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()
}
+ } catch {
+ return null
}
return null
}