diff --git a/CHANGELOG.md b/CHANGELOG.md index 3da7a8f6..166b7f34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **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 + secret-store, no SSH key). New **asymmetric mode** flips it: `kit memory keygen` + mints an X25519 keypair; the **public** recipient string (`kitmem-pub-…`, not a + secret — safe in a setup script, env var, or the repo) goes in `[memory.sync]` + as `recipient = "…"`, and push encrypts to it (`MAGIC_V3`: ephemeral X25519 → + HKDF-SHA256 → AES-256-GCM, libsodium sealed-box shape, **zero new deps** — pure + `node:crypto`). Only machines holding the **private** key (`~/.kit/memory-key.json`, + 0600) can decrypt on pull. So an ephemeral session needs only a public key + a + reachable private repo to contribute its memory — nothing secret leaves it, and + `push_on_end`/`pull_on_start` work passphrase-free when a recipient is set. + - **External timestamp anchor (command transport) — closes the same-machine forge gap.** The keyless chain + machine-local HMAC anchor proves *what happened on this machine*, but anyone with that machine's anchor key (UID) can diff --git a/src/commands/memory.ts b/src/commands/memory.ts index 4e3d69b2..85f8f282 100644 --- a/src/commands/memory.ts +++ b/src/commands/memory.ts @@ -18,7 +18,15 @@ import { mergeDb } from "../memory/merge.js"; import { buildSuggestPrompt } from "../memory/suggest.js"; import { getCurrentProjectRoot } from "../memory/project.js"; import { scanDbForSecrets } from "../memory/scan.js"; -import { backupEncrypted, restoreEncrypted } from "../memory/backup.js"; +import { + backupEncrypted, + restoreEncrypted, + generateMemoryKeypair, + saveMemoryKey, + loadMemoryKey, + publicKeyString, + getMemoryKeyPath, +} from "../memory/backup.js"; import { ensureKitWrapper } from "../kit-wrapper.js"; import { syncFromExport } from "../memory/sync.js"; import { @@ -91,6 +99,7 @@ export async function cmdMemory(): Promise { index: memIndex, merge: memMerge, sync: memSync, + keygen: memKeygen, push: memPush, pull: memPull, stats: memStats, @@ -259,6 +268,9 @@ async function memHelp(): Promise { console.log( " kit memory sync init Write ~/.kit/sync.toml (--remote | --command, --auto for hook sync)", ); + console.log( + " kit memory keygen Generate a public-key recipient (push with NO passphrase — for ephemeral sessions)", + ); console.log( " kit memory push Encrypt + push your store to your private remote (~/.kit/sync.toml)", ); @@ -443,9 +455,10 @@ async function memPush(): Promise { } if (!cfg) return syncNotConfigured(); const pass = process.env.KIT_MEMORY_PASSPHRASE ?? flagValue(process.argv, "--passphrase"); - if (!pass) { + // Public-key mode (recipient set) needs no secret; passphrase mode does. + if (!cfg.recipient && !pass) { console.error( - `${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase) — the blob pushed to ${cfg.remote} is encrypted${c.reset}`, + `${c.red}set KIT_MEMORY_PASSPHRASE (or --passphrase), or add a public-key \`recipient\` to [memory.sync] — the pushed blob is encrypted${c.reset}`, ); return false; } @@ -463,6 +476,35 @@ async function memPush(): Promise { } } +async function memKeygen(): Promise { + const force = hasFlag(process.argv, "--force"); + const existing = loadMemoryKey(); + if (existing && !force) { + // Never silently clobber: a new key makes every blob encrypted to the old key + // undecryptable. Show the existing public string so the user can re-share it. + console.log( + `${c.dim}a memory key already exists at ${getMemoryKeyPath()}${c.reset}\n` + + ` recipient: ${c.bold}${publicKeyString(existing.x)}${c.reset}\n` + + `${c.dim}pass --force to replace it (old public-key blobs become undecryptable).${c.reset}`, + ); + return true; + } + const { publicKey, privateJwk } = generateMemoryKeypair(); + const path = saveMemoryKey(privateJwk); + console.log( + `${c.green}✓${c.reset} wrote private key → ${c.bold}${path}${c.reset} ${c.dim}(0600)${c.reset}`, + ); + console.log( + `\nRecipient (public — safe to share / commit / put in a setup script):\n ${c.bold}${publicKey}${c.reset}\n`, + ); + console.log( + `${c.dim}Next: put this in [memory.sync] on the pushing machines →${c.reset}\n` + + ` recipient = "${publicKey}"\n` + + `${c.dim}Keep ${path} ONLY on machines that must decrypt (copy it to your other durable machines).${c.reset}`, + ); + return true; +} + async function memPull(): Promise { let cfg; try { diff --git a/src/memory/backup.test.ts b/src/memory/backup.test.ts index 993df118..c5bd728e 100644 --- a/src/memory/backup.test.ts +++ b/src/memory/backup.test.ts @@ -4,7 +4,16 @@ import { mkdtempSync, rmSync, existsSync, statSync, readFileSync } from "node:fs import { tmpdir } from "node:os"; import { join } from "node:path"; import { openMemoryDb, upsertSession, insertMessage, getStats } from "./db.js"; -import { backupEncrypted, restoreEncrypted } from "./backup.js"; +import { + backupEncrypted, + restoreEncrypted, + generateMemoryKeypair, + backupToRecipient, + restoreWithKey, + isAsymmetricBackup, + isEncryptedBackup, + parseRecipient, +} from "./backup.js"; describe("memory encrypted backup / restore", () => { it("roundtrips data; a wrong passphrase fails", () => { @@ -76,3 +85,51 @@ describe("memory encrypted backup / restore", () => { rmSync(tmp, { recursive: true, force: true }); }); }); + +describe("memory asymmetric (public-key) backup — no passphrase, ephemeral-safe", () => { + it("round-trips: encrypt to a PUBLIC key, decrypt only with the matching PRIVATE key", () => { + const tmp = mkdtempSync(join(tmpdir(), "kit-pk-")); + const src = join(tmp, "memory.db"); + const enc = join(tmp, "blob.enc"); + const dest = join(tmp, "restored.db"); + + let db = openMemoryDb(src); + upsertSession(db, { sessionId: "s1", harness: "claude-code" }); + insertMessage(db, { uuid: "u1", sessionId: "s1", type: "user", content: "asymmetric secret" }); + db.close(); + + const { publicKey, privateJwk } = generateMemoryKeypair(); + // encrypt with ONLY the public string — no passphrase anywhere + backupToRecipient(publicKey, src, enc); + assert.ok(isEncryptedBackup(enc), "V3 counts as an encrypted backup"); + assert.ok(isAsymmetricBackup(enc), "flagged as the public-key (V3) form"); + assert.equal(readFileSync(enc).subarray(0, 8).toString(), "KITMEM03"); + assert.equal(statSync(enc).mode & 0o777, 0o600, "blob is 0600"); + + restoreWithKey(privateJwk, enc, dest); + db = openMemoryDb(dest); + assert.equal(getStats(db).messages, 1); + db.close(); + rmSync(tmp, { recursive: true, force: true }); + }); + + it("a DIFFERENT private key cannot decrypt (confidentiality holds)", () => { + const tmp = mkdtempSync(join(tmpdir(), "kit-pk2-")); + const src = join(tmp, "memory.db"); + const enc = join(tmp, "blob.enc"); + openMemoryDb(src).close(); + + const alice = generateMemoryKeypair(); + const mallory = generateMemoryKeypair(); + backupToRecipient(alice.publicKey, src, enc); + // Mallory's key is a valid X25519 key but the wrong recipient → GCM auth fails + assert.throws(() => restoreWithKey(mallory.privateJwk, enc, join(tmp, "x.db")), /./); + assert.ok(!existsSync(join(tmp, "x.db")), "no plaintext written on a failed decrypt"); + rmSync(tmp, { recursive: true, force: true }); + }); + + it("parseRecipient rejects a malformed public key", () => { + assert.throws(() => parseRecipient("not-a-key"), /must start with/); + assert.throws(() => parseRecipient("kitmem-pub-deadbeef"), /X25519 public key/); + }); +}); diff --git a/src/memory/backup.ts b/src/memory/backup.ts index 8f87f821..c2b27d81 100644 --- a/src/memory/backup.ts +++ b/src/memory/backup.ts @@ -17,17 +17,26 @@ import { createDecipheriv, randomBytes, scryptSync, + generateKeyPairSync, + createPublicKey, + createPrivateKey, + diffieHellman, + hkdfSync, type ScryptOptions, + type KeyObject, } from "node:crypto"; -import { readFileSync, writeFileSync } from "node:fs"; -import { openMemoryDb, getMemoryDbPath } from "./db.js"; +import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { openMemoryDb, getMemoryDbPath, getMemoryDir } from "./db.js"; const MAGIC_V1 = Buffer.from("KITMEM01"); // legacy: scrypt defaults (N=16384, ~16 MB) const MAGIC_V2 = Buffer.from("KITMEM02"); // hardened: N=2^17 (~134 MB) — write path +const MAGIC_V3 = Buffer.from("KITMEM03"); // asymmetric: X25519 → HKDF → AES-256-GCM (no passphrase) const MAGIC_LEN = 8; const SALT_LEN = 16; const IV_LEN = 12; const TAG_LEN = 16; +const X25519_LEN = 32; // raw X25519 public key length // Hardened scrypt cost for new backups. The blob is the ONLY thing a passphrase // protects and is designed to sit on a USB stick / in the cloud, so make offline @@ -68,17 +77,26 @@ export function validatePassphrase(passphrase: string): void { } } -/** True if `inPath` begins with a kit memory backup MAGIC header (V1 or V2). - * Lets `kit memory sync` tell an encrypted backup from a raw .db export. */ -export function isEncryptedBackup(inPath: string): boolean { - let head: Buffer; +function magicOf(inPath: string): Buffer | null { try { - const fd = readFileSync(inPath); - head = fd.subarray(0, MAGIC_LEN); + return readFileSync(inPath).subarray(0, MAGIC_LEN); } catch { - return false; // unreadable/missing — let the caller surface a clean error + return null; // unreadable/missing — let the caller surface a clean error } - return head.equals(MAGIC_V1) || head.equals(MAGIC_V2); +} + +/** True if `inPath` begins with ANY kit memory backup MAGIC header (V1/V2 passphrase + * or V3 public-key). Lets `kit memory sync` tell an encrypted backup from a raw .db. */ +export function isEncryptedBackup(inPath: string): boolean { + const m = magicOf(inPath); + return !!m && (m.equals(MAGIC_V1) || m.equals(MAGIC_V2) || m.equals(MAGIC_V3)); +} + +/** True only for a V3 (asymmetric, public-key) blob — decrypts with the local + * private key, never a passphrase. The branch `kit memory pull` keys off. */ +export function isAsymmetricBackup(inPath: string): boolean { + const m = magicOf(inPath); + return !!m && m.equals(MAGIC_V3); } /** Encrypt the memory DB file into `outPath`. WAL is checkpointed first so the file is complete. */ @@ -133,3 +151,146 @@ export function restoreEncrypted(passphrase: string, inPath: string, destPath: s // this is the restore-time equivalent.) writeFileSync(destPath, data, { mode: 0o600 }); } + +// ── Asymmetric (public-key) mode ────────────────────────────────────────────── +// Why: the symmetric passphrase must live on EVERY machine that pushes — which an +// ephemeral session (no secret-safe env, no SSH key) can't do. Public-key mode +// flips it: a session encrypts to a PUBLIC recipient key (not a secret — safe in a +// setup script, env var, or the repo), and only the durable machines holding the +// PRIVATE key can decrypt. So an ephemeral session needs nothing secret to push. +// +// Scheme (libsodium sealed-box shape, pure node:crypto — zero deps): a fresh +// ephemeral X25519 keypair per blob; ECDH(eph_priv, recipient_pub) → HKDF-SHA256 +// (salt = eph_pub||recipient_pub, info = "kit-memory-v3") → 32-byte AES key → +// AES-256-GCM. Layout: MAGIC_V3(8) | eph_pub(32) | iv(12) | tag(16) | ciphertext. + +const HKDF_INFO = Buffer.from("kit-memory-v3"); +const PUB_PREFIX = "kitmem-pub-"; + +/** A stored X25519 private key (JWK OKP form: has both `d` and `x`). */ +export interface MemoryKeyJwk { + kty: "OKP"; + crv: "X25519"; + x: string; // base64url public component + d: string; // base64url private scalar +} + +function rawFromJwkComponent(b64url: string): Buffer { + return Buffer.from(b64url, "base64url"); +} + +/** The recipient public string for a JWK/`x` — safe to share (NOT a secret). */ +export function publicKeyString(x: string): string { + return PUB_PREFIX + x; +} + +/** Parse a `kitmem-pub-…` recipient string into an X25519 public KeyObject. */ +export function parseRecipient(pub: string): KeyObject { + if (!pub.startsWith(PUB_PREFIX)) { + throw new Error(`invalid recipient key: must start with "${PUB_PREFIX}"`); + } + const x = pub.slice(PUB_PREFIX.length).trim(); + if (rawFromJwkComponent(x).length !== X25519_LEN) { + throw new Error("invalid recipient key: not a 32-byte X25519 public key"); + } + try { + return createPublicKey({ key: { kty: "OKP", crv: "X25519", x }, format: "jwk" }); + } catch { + throw new Error("invalid recipient key: could not parse X25519 public key"); + } +} + +/** Where the local private decryption key lives (0600), honoring KIT_MEMORY_DIR. */ +export function getMemoryKeyPath(): string { + return join(getMemoryDir(), "memory-key.json"); +} + +/** Generate a fresh X25519 keypair. Returns the shareable public string and the + * private JWK to persist on durable machines only. */ +export function generateMemoryKeypair(): { publicKey: string; privateJwk: MemoryKeyJwk } { + const { publicKey, privateKey } = generateKeyPairSync("x25519"); + const priv = privateKey.export({ format: "jwk" }) as unknown as MemoryKeyJwk; + const pub = publicKey.export({ format: "jwk" }) as { x: string }; + return { publicKey: publicKeyString(pub.x), privateJwk: { ...priv, x: pub.x } }; +} + +/** Persist the private key (0600) and return the file path. */ +export function saveMemoryKey(privateJwk: MemoryKeyJwk): string { + const dir = getMemoryDir(); + if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 }); + const path = getMemoryKeyPath(); + writeFileSync(path, JSON.stringify(privateJwk), { mode: 0o600 }); + return path; +} + +/** Load the local private key, or null if none exists / is unreadable. */ +export function loadMemoryKey(): MemoryKeyJwk | null { + try { + const j = JSON.parse(readFileSync(getMemoryKeyPath(), "utf8")) as MemoryKeyJwk; + return j.kty === "OKP" && j.crv === "X25519" && j.d && j.x ? j : null; + } catch { + return null; + } +} + +function deriveSharedKey(ephPubRaw: Buffer, recipPubRaw: Buffer, shared: Buffer): Buffer { + const salt = Buffer.concat([ephPubRaw, recipPubRaw]); + return Buffer.from(hkdfSync("sha256", shared, salt, HKDF_INFO, 32)); +} + +/** Encrypt the memory DB to a PUBLIC recipient key (no passphrase). WAL-checkpoint first. */ +export function backupToRecipient( + recipient: string, + srcPath: string = getMemoryDbPath(), + outPath?: string, +): void { + if (!outPath) throw new Error("backupToRecipient requires an output path"); + const recipKey = parseRecipient(recipient); + const recipRaw = rawFromJwkComponent((recipKey.export({ format: "jwk" }) as { x: string }).x); + + const db = openMemoryDb(srcPath); + db.exec("PRAGMA wal_checkpoint(TRUNCATE)"); + db.close(); + const data = readFileSync(srcPath); + + const { publicKey: ephPub, privateKey: ephPriv } = generateKeyPairSync("x25519"); + const ephRaw = rawFromJwkComponent((ephPub.export({ format: "jwk" }) as { x: string }).x); + const shared = diffieHellman({ privateKey: ephPriv, publicKey: recipKey }); + const key = deriveSharedKey(ephRaw, recipRaw, shared); + + const iv = randomBytes(IV_LEN); + const cipher = createCipheriv("aes-256-gcm", key, iv, { authTagLength: TAG_LEN }); + const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]); + const tag = cipher.getAuthTag(); + writeFileSync(outPath, Buffer.concat([MAGIC_V3, ephRaw, iv, tag, ciphertext]), { mode: 0o600 }); +} + +/** Decrypt a V3 blob with the local private key. Throws on wrong key / tamper (GCM auth). */ +export function restoreWithKey(privateJwk: MemoryKeyJwk, inPath: string, destPath: string): void { + const blob = readFileSync(inPath); + if (!blob.subarray(0, MAGIC_LEN).equals(MAGIC_V3)) { + throw new Error("not a kit public-key backup (bad magic)"); + } + let off = MAGIC_LEN; + const ephRaw = blob.subarray(off, (off += X25519_LEN)); + const iv = blob.subarray(off, (off += IV_LEN)); + const tag = blob.subarray(off, (off += TAG_LEN)); + const ciphertext = blob.subarray(off); + + const privKey = createPrivateKey({ + key: { kty: "OKP", crv: "X25519", x: privateJwk.x, d: privateJwk.d }, + format: "jwk", + }); + const ephPub = createPublicKey({ + key: { kty: "OKP", crv: "X25519", x: ephRaw.toString("base64url") }, + format: "jwk", + }); + const shared = diffieHellman({ privateKey: privKey, publicKey: ephPub }); + const recipRaw = rawFromJwkComponent(privateJwk.x); + const key = deriveSharedKey(ephRaw, recipRaw, shared); + + 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 }); +} diff --git a/src/memory/remote-sync.ts b/src/memory/remote-sync.ts index 876b07fc..8c018c71 100644 --- a/src/memory/remote-sync.ts +++ b/src/memory/remote-sync.ts @@ -33,7 +33,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { parse } from "smol-toml"; import { getMemoryDir, getMemoryDbPath, openMemoryDb } from "./db.js"; -import { backupEncrypted } from "./backup.js"; +import { backupEncrypted, backupToRecipient } from "./backup.js"; import { syncFromExport } from "./sync.js"; import type { MergeResult } from "./merge.js"; @@ -59,6 +59,10 @@ export interface SyncConfig { pullOnStart?: boolean; /** Index + push the store at the end of each session (key for ephemeral containers). */ pushOnEnd?: boolean; + /** Public-key (X25519 `kitmem-pub-…`) recipient. When set, push encrypts to it + * instead of a passphrase — so an ephemeral session needs NO secret, only this + * (non-secret) public key. Only holders of the matching private key can decrypt. */ + recipient?: string; } const DEFAULT_BRANCH = "main"; @@ -97,6 +101,7 @@ export function loadSyncConfig(): SyncConfig | null { const bool = (v: unknown): boolean => v === true; const pullOnStart = bool(s.pull_on_start); const pushOnEnd = bool(s.push_on_end); + const recipient = str(s.recipient) || undefined; // public-key mode (optional) const transport: SyncTransport = s.transport === "command" ? "command" : "git"; if (transport === "command") { @@ -105,7 +110,7 @@ export function loadSyncConfig(): SyncConfig | null { if (!pushCmd || !pullCmd) { throw new Error('[memory.sync] transport = "command" requires both push_cmd and pull_cmd'); } - return { transport, file, pushCmd, pullCmd, pullOnStart, pushOnEnd }; + return { transport, file, pushCmd, pullCmd, pullOnStart, pushOnEnd, recipient }; } const remote = str(s.remote); @@ -113,7 +118,7 @@ export function loadSyncConfig(): SyncConfig | null { const branch = str(s.branch) || DEFAULT_BRANCH; assertSafeGitRef(remote, "remote"); assertSafeGitRef(branch, "branch"); - return { transport, file, remote, branch, pullOnStart, pushOnEnd }; + return { transport, file, remote, branch, pullOnStart, pushOnEnd, recipient }; } /** @@ -256,19 +261,43 @@ export interface PushResult { * passphrase (KIT_MEMORY_PASSPHRASE). Clones the remote, refreshes the blob, * commits and pushes only when it changed (so a no-op push is free and quiet). */ -export function pushMemory(cfg: SyncConfig, passphrase: string, projectRoot: string): PushResult { +/** Encrypt the live memory DB into `outPath`, picking the mode from the config: + * a configured `recipient` → public-key (V3, no passphrase); otherwise the + * passphrase (V2). Throws if neither is available. */ +function encryptBlobForSync( + cfg: SyncConfig, + passphrase: string | undefined, + outPath: string, +): void { + if (cfg.recipient) { + backupToRecipient(cfg.recipient, getMemoryDbPath(), outPath); + return; + } + if (!passphrase) { + throw new Error( + "no encryption configured — set KIT_MEMORY_PASSPHRASE, or add a public-key `recipient` to [memory.sync]", + ); + } + backupEncrypted(passphrase, getMemoryDbPath(), outPath); +} + +export function pushMemory( + cfg: SyncConfig, + passphrase: string | undefined, + projectRoot: string, +): PushResult { const dir = mkdtempSync(join(tmpdir(), "kit-memsync-")); try { if (cfg.transport === "command") { const blob = join(dir, cfg.file); - backupEncrypted(passphrase, getMemoryDbPath(), blob); + encryptBlobForSync(cfg, passphrase, blob); runTransportCmd(cfg.pushCmd!, blob); return { target: "command transport", file: cfg.file, pushed: true }; } // git transport — clone into the (empty) dir FIRST, then write the blob inside it. assertRemoteNotProjectOrigin(cfg.remote!, projectRoot); cloneOrInit(cfg.remote!, cfg.branch ?? DEFAULT_BRANCH, dir); - backupEncrypted(passphrase, getMemoryDbPath(), join(dir, cfg.file)); + encryptBlobForSync(cfg, passphrase, join(dir, cfg.file)); git(["add", "--", cfg.file], dir); const dirty = git(["status", "--porcelain"], dir).trim(); if (!dirty) return { target: cfg.remote!, file: cfg.file, pushed: false }; @@ -412,7 +441,9 @@ export function tryAutoPush(projectRoot: string): AutoSyncResult { return { ran: false }; } if (!cfg || !cfg.pushOnEnd) return { ran: false }; - if (!process.env.KIT_MEMORY_PASSPHRASE) { + // Public-key mode needs NO secret — that's the whole point for ephemeral + // sessions. Only the passphrase mode requires KIT_MEMORY_PASSPHRASE. + if (!cfg.recipient && !process.env.KIT_MEMORY_PASSPHRASE) { return { ran: false, note: "memory push skipped: KIT_MEMORY_PASSPHRASE not set" }; } try { diff --git a/src/memory/sync.ts b/src/memory/sync.ts index 6d5ecea3..2a02b8c7 100644 --- a/src/memory/sync.ts +++ b/src/memory/sync.ts @@ -21,7 +21,13 @@ import { existsSync, mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { mergeDb, type MergeResult } from "./merge.js"; -import { isEncryptedBackup, restoreEncrypted } from "./backup.js"; +import { + isEncryptedBackup, + isAsymmetricBackup, + restoreEncrypted, + restoreWithKey, + loadMemoryKey, +} from "./backup.js"; export interface SyncOptions { /** Passphrase for an encrypted backup export (KIT_MEMORY_PASSPHRASE). */ @@ -47,7 +53,14 @@ export function syncFromExport( return mergeDb(target, exportPath); } - if (!opts.passphrase) { + const asymmetric = isAsymmetricBackup(exportPath); + const privateKey = asymmetric ? loadMemoryKey() : null; + if (asymmetric && !privateKey) { + throw new Error( + "this is a public-key (V3) backup — no local private key found; run `kit memory keygen` on this machine and restore its key, or copy ~/.kit/memory-key.json from a machine that has it", + ); + } + if (!asymmetric && !opts.passphrase) { throw new Error( "this looks like an encrypted backup — set KIT_MEMORY_PASSPHRASE (or pass --passphrase) to decrypt it", ); @@ -57,7 +70,8 @@ export function syncFromExport( const dir = mkdtempSync(join(tmpdir(), "kit-sync-")); const tmpDb = join(dir, "decrypted.db"); try { - restoreEncrypted(opts.passphrase, exportPath, tmpDb); + if (asymmetric) restoreWithKey(privateKey!, exportPath, tmpDb); + else restoreEncrypted(opts.passphrase!, exportPath, tmpDb); return mergeDb(target, tmpDb); } finally { rmSync(dir, { recursive: true, force: true });