diff --git a/client/src/components/KeyBackup.jsx b/client/src/components/KeyBackup.jsx
new file mode 100644
index 0000000..978db0e
--- /dev/null
+++ b/client/src/components/KeyBackup.jsx
@@ -0,0 +1,96 @@
+import { useState } from 'react'
+import axios from 'axios'
+import { useAuth } from '../context/AuthContext'
+import { exportKeyBackup, importKeyBackup } from '../lib/dmCrypto'
+import { KeyRound, Download, Upload } from 'lucide-react'
+
+// Passphrase-protected backup of this device's DM key, so message history can
+// move to another device. The exported blob is encrypted with the passphrase;
+// the server never sees it.
+export default function KeyBackup() {
+ const { user } = useAuth()
+ const [tab, setTab] = useState('export')
+ const [pass, setPass] = useState('')
+ const [blob, setBlob] = useState('')
+ const [msg, setMsg] = useState(null) // { kind: 'ok'|'err', text }
+
+ const doExport = async () => {
+ setMsg(null)
+ try {
+ const out = await exportKeyBackup(user.id, pass)
+ setBlob(out)
+ const url = URL.createObjectURL(new Blob([out], { type: 'application/json' }))
+ const a = document.createElement('a')
+ a.href = url
+ a.download = `beacon-key-${user.username}.txt`
+ a.click()
+ setTimeout(() => URL.revokeObjectURL(url), 30_000)
+ setMsg({ kind: 'ok', text: 'Backup downloaded. Keep it and the passphrase safe.' })
+ } catch (e) {
+ setMsg({ kind: 'err', text: e.message })
+ }
+ }
+
+ const doImport = async () => {
+ setMsg(null)
+ try {
+ const publicJwk = await importKeyBackup(user.id, pass, blob.trim())
+ // Republish the restored public key so peers encrypt to it.
+ await axios.post('/api/auth/public-key', { publicKey: JSON.stringify(publicJwk) }).catch(() => {})
+ setMsg({ kind: 'ok', text: 'Key restored. Reopen a conversation to read its history.' })
+ } catch (e) {
+ setMsg({ kind: 'err', text: e.message })
+ }
+ }
+
+ return (
+
+
+
+
+
+
Message key backup
+
+
+
+ Your messages are encrypted with a key that lives only on this device. Back it up with a passphrase
+ to read your history on another device. The backup is useless without the passphrase — keep both safe.
+
+ )
+}
diff --git a/client/src/lib/dmCrypto.js b/client/src/lib/dmCrypto.js
index ff32a8f..da37012 100644
--- a/client/src/lib/dmCrypto.js
+++ b/client/src/lib/dmCrypto.js
@@ -7,9 +7,11 @@
// envelope `{v:1, iv, ct}` and physically cannot read it. Sender and
// recipient derive the same key, so both can read the conversation history.
//
-// Known limitation (documented in QUESTIONS.md): keys are per-device. A new
-// device generates a new keypair and cannot read old ciphertext (passphrase
-// key backup is a planned follow-up).
+// Keys are per-device by default. To move history to another device, a user
+// can export a passphrase-encrypted backup of their private key (see
+// exportKeyBackup / importKeyBackup below). Keys are therefore generated
+// extractable — but the private key still only ever leaves the device through
+// that explicit, passphrase-gated action, never over the network.
const DB_NAME = 'beacon-keys'
const STORE = 'keys'
@@ -50,7 +52,7 @@ export async function getOrCreateKeyPair(userId) {
const pair = await crypto.subtle.generateKey(
{ name: 'ECDH', namedCurve: 'P-256' },
- false, // private key not extractable — it cannot leave this device
+ true, // extractable, so the key can be backed up under a passphrase
['deriveKey'],
)
const publicJwk = await crypto.subtle.exportKey('jwk', pair.publicKey)
@@ -156,3 +158,84 @@ export async function decryptGroupMessage(myPrivateKey, members, myId, senderId,
}
return '🔒 (sent to another device)'
}
+
+// ---------- Passphrase key backup ----------
+//
+// DM keys are per-device: a new device can't read old messages. Backup lets a
+// user carry their private key to another device, protected by a passphrase.
+// The key JWK is encrypted with AES-256-GCM under a key derived from the
+// passphrase via PBKDF2 (200k iterations, SHA-256, random salt). The resulting
+// blob is safe to store or send — it's useless without the passphrase.
+//
+// Keys are generated extractable so this export is possible. The private key
+// still only ever leaves the device through this explicit, passphrase-gated
+// action — never over the network, never to the server.
+
+const KDF_ITERATIONS = 200_000
+
+async function deriveBackupKey(passphrase, salt, usage) {
+ const material = await crypto.subtle.importKey(
+ 'raw', new TextEncoder().encode(passphrase), 'PBKDF2', false, ['deriveKey'],
+ )
+ return crypto.subtle.deriveKey(
+ { name: 'PBKDF2', salt, iterations: KDF_ITERATIONS, hash: 'SHA-256' },
+ material,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ usage,
+ )
+}
+
+/**
+ * Encrypt this device's DM private key under `passphrase`. Returns a JSON
+ * string blob the user can save. Throws if the key predates backup support
+ * (older keys were generated non-extractable).
+ */
+export async function exportKeyBackup(userId, passphrase) {
+ if (!passphrase || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters')
+ const record = await idbGet(`ecdh-${userId}`)
+ if (!record) throw new Error('No message key on this device yet')
+ let privateJwk
+ try {
+ privateJwk = await crypto.subtle.exportKey('jwk', record.privateKey)
+ } catch {
+ throw new Error('This device’s key predates backup support and can’t be exported')
+ }
+ const salt = crypto.getRandomValues(new Uint8Array(16))
+ const iv = crypto.getRandomValues(new Uint8Array(12))
+ const key = await deriveBackupKey(passphrase, salt, ['encrypt'])
+ const payload = new TextEncoder().encode(JSON.stringify({ userId, privateJwk, publicJwk: record.publicJwk }))
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, payload)
+ return JSON.stringify({ v: 1, kdf: 'PBKDF2', it: KDF_ITERATIONS, salt: b64(salt), iv: b64(iv), ct: b64(ct) })
+}
+
+/**
+ * Decrypt a backup blob with `passphrase` and install the key on this device
+ * (overwriting any existing key for this user). Returns the imported public
+ * JWK so the caller can republish it. Throws on a wrong passphrase or a blob
+ * for a different account.
+ */
+export async function importKeyBackup(userId, passphrase, blob) {
+ let parsed
+ try {
+ parsed = JSON.parse(blob)
+ } catch {
+ throw new Error('That doesn’t look like a backup file')
+ }
+ if (parsed.v !== 1 || !parsed.salt || !parsed.iv || !parsed.ct) throw new Error('Unrecognized backup format')
+ const key = await deriveBackupKey(passphrase, unb64(parsed.salt), ['decrypt'])
+ let plain
+ try {
+ plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: unb64(parsed.iv) }, key, unb64(parsed.ct))
+ } catch {
+ throw new Error('Wrong passphrase, or the backup is corrupted')
+ }
+ const data = JSON.parse(new TextDecoder().decode(plain))
+ if (data.userId !== userId) throw new Error('This backup belongs to a different account')
+ const privateKey = await crypto.subtle.importKey(
+ 'jwk', data.privateJwk, { name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveKey'],
+ )
+ await idbSet(`ecdh-${userId}`, { privateKey, publicJwk: data.publicJwk })
+ keyCache.clear() // shared-key cache is keyed on the other party, not us, but be safe
+ return data.publicJwk
+}
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index eac81c2..20a7323 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -3,6 +3,7 @@ import { Link, useNavigate } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import Appearance from '../components/Appearance'
import ThemeReset from '../components/ThemeReset'
+import KeyBackup from '../components/KeyBackup'
import { ArrowLeft, User, Palette, LogOut } from 'lucide-react'
export default function Settings() {
@@ -64,6 +65,13 @@ export default function Settings() {
+ {/* DM key backup — accounts only (guests have no persistent identity). */}
+ {!isGuest && (
+
+
+
+ )}
+
{/* Appearance / customization */}
{sectionTitle(Palette, 'Appearance')}
diff --git a/tests/e2e/key-backup.spec.ts b/tests/e2e/key-backup.spec.ts
new file mode 100644
index 0000000..6832a6e
--- /dev/null
+++ b/tests/e2e/key-backup.spec.ts
@@ -0,0 +1,64 @@
+import { test, expect } from '@playwright/test'
+
+// Passphrase key backup: a private key exported under a passphrase can be
+// restored on a "fresh" device (cleared IndexedDB) and then decrypts a message
+// that was encrypted to its public key. A wrong passphrase must fail.
+
+test('key backup round-trips and rejects a wrong passphrase', async ({ page }) => {
+ await page.goto('/')
+
+ const result = await page.evaluate(async () => {
+ const crypto_ = await import('/src/lib/dmCrypto.js')
+ const { getOrCreateKeyPair, exportKeyBackup, importKeyBackup, encryptMessage, decryptMessage } = crypto_
+
+ const userId = 'backup-user-' + Math.random().toString(36).slice(2)
+
+ // Device 1: make a key, note its public JWK, encrypt a message to it from a
+ // peer (simulate the peer with a second throwaway keypair).
+ const mine = await getOrCreateKeyPair(userId)
+ const myPubStr = JSON.stringify(mine.publicJwk)
+
+ const peerId = 'peer-' + Math.random().toString(36).slice(2)
+ const peer = await getOrCreateKeyPair(peerId)
+ const peerPubStr = JSON.stringify(peer.publicJwk)
+
+ const secret = 'meet at the lighthouse at dawn'
+ // Peer encrypts to me; I (mine) decrypt with the peer's public key.
+ const envelope = await encryptMessage(peer.privateKey, myPubStr, secret)
+
+ // Export my key under a passphrase.
+ const blob = await exportKeyBackup(userId, 'correct horse battery')
+
+ // Wipe this "device": delete the IndexedDB key store so the key is gone.
+ await new Promise((res, rej) => {
+ const req = indexedDB.deleteDatabase('beacon-keys')
+ req.onsuccess = () => res(undefined)
+ req.onerror = () => rej(req.error)
+ req.onblocked = () => res(undefined)
+ })
+
+ // Wrong passphrase must throw.
+ let wrongRejected = false
+ try {
+ await importKeyBackup(userId, 'nope nope nope', blob)
+ } catch {
+ wrongRejected = true
+ }
+
+ // Right passphrase restores the key; it must decrypt the earlier message.
+ const restoredPub = await importKeyBackup(userId, 'correct horse battery', blob)
+ const restored = await getOrCreateKeyPair(userId) // now reads the imported key
+ const plain = await decryptMessage(restored.privateKey, peerPubStr, envelope)
+
+ return {
+ wrongRejected,
+ restoredMatchesPublic: JSON.stringify(restoredPub) === myPubStr,
+ decrypted: plain,
+ expected: secret,
+ }
+ })
+
+ expect(result.wrongRejected).toBe(true)
+ expect(result.restoredMatchesPublic).toBe(true)
+ expect(result.decrypted).toBe(result.expected)
+})