diff --git a/CHANGELOG.md b/CHANGELOG.md index 166b7f34..1844cd37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **Memory sync blobs are now gzip-compressed before encryption (~3× smaller).** A + SQLite store compresses well (a real store: 6.3 MB → 2.1 MB; large stores + ~139 MB → ~30 MB), which keeps the blob under a git host's 100 MB file limit and + speeds every transport. Compression happens INSIDE the encryption, so the remote + still only ever sees ciphertext. Fully backward-compatible on read: an older, + uncompressed blob decrypts to a raw SQLite file (no gzip header) and is passed + through untouched — no new format version, works for both the passphrase and + public-key modes. This is what makes a private **GitHub** repo viable as the + ephemeral-session hub (alongside a self-hosted remote, which has no size cap). - **Public-key memory sync — an ephemeral session can push with NO secret.** The passphrase mode (AES-256-GCM + scrypt) requires the *same secret on every machine that pushes*, which an ephemeral cloud session can't safely hold (no diff --git a/src/memory/backup.test.ts b/src/memory/backup.test.ts index c5bd728e..a3536325 100644 --- a/src/memory/backup.test.ts +++ b/src/memory/backup.test.ts @@ -133,3 +133,41 @@ describe("memory asymmetric (public-key) backup — no passphrase, ephemeral-saf assert.throws(() => parseRecipient("kitmem-pub-deadbeef"), /X25519 public key/); }); }); + +describe("memory backup — gzip compression (fits under host size caps)", () => { + it("the encrypted blob is much smaller than the raw DB, and still round-trips", () => { + const tmp = mkdtempSync(join(tmpdir(), "kit-gz-")); + const src = join(tmp, "memory.db"); + const enc = join(tmp, "blob.enc"); + const dest = join(tmp, "restored.db"); + + const db = openMemoryDb(src); + upsertSession(db, { sessionId: "s1", harness: "claude-code" }); + // highly compressible, repetitive content — like real transcripts + for (let i = 0; i < 500; i++) { + insertMessage(db, { + uuid: `u${i}`, + sessionId: "s1", + type: "user", + content: "the quick brown fox jumps over the lazy dog ".repeat(20), + }); + } + db.close(); + + const rawSize = statSync(src).size; + backupToRecipient(generateMemoryKeypair().publicKey, src, enc); // any mode compresses + const blobSize = statSync(enc).size; + assert.ok( + blobSize < rawSize / 2, + `blob (${blobSize}) should be < half the raw db (${rawSize})`, + ); + + // and a passphrase-mode blob restores intact (compression is transparent) + backupEncrypted("Galaxy-Vortex-Quartz-2026-x9", src, enc); + restoreEncrypted("Galaxy-Vortex-Quartz-2026-x9", enc, dest); + const rdb = openMemoryDb(dest); + assert.equal(getStats(rdb).messages, 500); + rdb.close(); + rmSync(tmp, { recursive: true, force: true }); + }); +}); diff --git a/src/memory/backup.ts b/src/memory/backup.ts index c2b27d81..275407fa 100644 --- a/src/memory/backup.ts +++ b/src/memory/backup.ts @@ -25,6 +25,7 @@ import { type ScryptOptions, type KeyObject, } from "node:crypto"; +import { gzipSync, gunzipSync } from "node:zlib"; import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs"; import { join } from "node:path"; import { openMemoryDb, getMemoryDbPath, getMemoryDir } from "./db.js"; @@ -47,6 +48,22 @@ function deriveKey(passphrase: string, salt: Buffer, opts?: ScryptOptions): Buff return scryptSync(passphrase, salt, 32, opts); } +// The plaintext DB is gzip-compressed BEFORE encryption (a SQLite file is highly +// compressible — ~139 MB → ~30 MB — which keeps the blob under a 100 MB git host +// limit and speeds every transport). Compression is INSIDE the encryption, so the +// remote still only ever sees ciphertext. Backward-compatible on read: an older +// (uncompressed) blob decrypts to a raw SQLite file that lacks the gzip header, so +// `maybeGunzip` passes it through untouched — no new format version needed. +function readMemoryDbCompressed(srcPath: string): Buffer { + return gzipSync(readFileSync(srcPath)); +} + +/** Gunzip if the buffer carries the gzip magic (0x1f 0x8b); otherwise return as-is + * (a pre-compression blob, whose plaintext is a raw SQLite file). */ +function maybeGunzip(buf: Buffer): Buffer { + return buf.length >= 2 && buf[0] === 0x1f && buf[1] === 0x8b ? gunzipSync(buf) : buf; +} + const MIN_PASSPHRASE_LEN = 12; // Substrings that mark an obviously guessable / placeholder passphrase. A long // phrase is worthless if it is predictable — the passphrase is the ONLY thing @@ -112,7 +129,7 @@ export function backupEncrypted( db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); db.close(); - const data = readFileSync(srcPath); + const data = readMemoryDbCompressed(srcPath); const salt = randomBytes(SALT_LEN); const iv = randomBytes(IV_LEN); const cipher = createCipheriv("aes-256-gcm", deriveKey(passphrase, salt, SCRYPT_V2), iv, { @@ -149,7 +166,7 @@ export function restoreEncrypted(passphrase: string, inPath: string, destPath: s // 0600: never leave the decrypted plaintext brain world-readable, even when // restoring to a custom path outside ~/.kit. (openMemoryDb chmods the live DB; // this is the restore-time equivalent.) - writeFileSync(destPath, data, { mode: 0o600 }); + writeFileSync(destPath, maybeGunzip(data), { mode: 0o600 }); } // ── Asymmetric (public-key) mode ────────────────────────────────────────────── @@ -251,7 +268,7 @@ export function backupToRecipient( const db = openMemoryDb(srcPath); db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); db.close(); - const data = readFileSync(srcPath); + const data = readMemoryDbCompressed(srcPath); const { publicKey: ephPub, privateKey: ephPriv } = generateKeyPairSync("x25519"); const ephRaw = rawFromJwkComponent((ephPub.export({ format: "jwk" }) as { x: string }).x); @@ -292,5 +309,5 @@ export function restoreWithKey(privateJwk: MemoryKeyJwk, inPath: string, destPat const decipher = createDecipheriv("aes-256-gcm", key, iv, { authTagLength: TAG_LEN }); decipher.setAuthTag(tag); const data = Buffer.concat([decipher.update(ciphertext), decipher.final()]); // throws if wrong key - writeFileSync(destPath, data, { mode: 0o600 }); + writeFileSync(destPath, maybeGunzip(data), { mode: 0o600 }); }