Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions src/memory/backup.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
});
25 changes: 21 additions & 4 deletions src/memory/backup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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
Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -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 ──────────────────────────────────────────────
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 });
}
Loading