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
96 changes: 96 additions & 0 deletions client/src/components/KeyBackup.jsx
Original file line number Diff line number Diff line change
@@ -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 (
<div>
<div className="flex items-center gap-3 mb-5">
<div className="w-9 h-9 rounded-xl grid place-items-center" style={{ background: 'rgb(var(--accent) / 0.14)', color: 'rgb(var(--accent))' }}>
<KeyRound size={17} />
</div>
<h3 className="text-sm font-bold uppercase tracking-wider" style={{ color: 'var(--text-primary)' }}>Message key backup</h3>
</div>

<p className="text-[11px] leading-relaxed mb-4" style={{ color: 'var(--text-secondary)' }}>
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.
</p>

<div className="flex gap-1 mb-4 p-1 rounded-xl" style={{ background: 'var(--surface-raised)' }}>
{['export', 'import'].map((t) => (
<button key={t} onClick={() => { setTab(t); setMsg(null) }}
className="flex-1 h-8 rounded-lg text-xs font-bold capitalize transition-colors"
style={tab === t
? { background: 'rgb(var(--accent))', color: '#1a0f0d' }
: { color: 'var(--text-secondary)' }}
data-testid={`keybackup-tab-${t}`}>
{t === 'export' ? 'Back up' : 'Restore'}
</button>
))}
</div>

<div className="space-y-3">
<input type="password" className="input-field" placeholder="Passphrase (8+ characters)"
value={pass} onChange={(e) => setPass(e.target.value)} data-testid="keybackup-pass" />

{tab === 'import' && (
<textarea className="input-field !h-24 resize-none font-mono !text-[10px]" placeholder="Paste your backup here"
value={blob} onChange={(e) => setBlob(e.target.value)} data-testid="keybackup-blob" />
)}

<button onClick={tab === 'export' ? doExport : doImport}
className="btn btn-primary w-full h-11 text-xs" data-testid="keybackup-go">
{tab === 'export' ? <><Download size={15} /> Download backup</> : <><Upload size={15} /> Restore key</>}
</button>

{msg && (
<p className="text-[11px] text-center leading-relaxed"
style={{ color: msg.kind === 'ok' ? '#52b788' : '#fb7185' }} data-testid="keybackup-msg">
{msg.text}
</p>
)}
</div>
</div>
)
}
91 changes: 87 additions & 4 deletions client/src/lib/dmCrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
8 changes: 8 additions & 0 deletions client/src/pages/Settings.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -64,6 +65,13 @@ export default function Settings() {
</div>
</section>

{/* DM key backup — accounts only (guests have no persistent identity). */}
{!isGuest && (
<section className="glass-card p-6">
<KeyBackup />
</section>
)}

{/* Appearance / customization */}
<section className="glass-card p-6">
{sectionTitle(Palette, 'Appearance')}
Expand Down
64 changes: 64 additions & 0 deletions tests/e2e/key-backup.spec.ts
Original file line number Diff line number Diff line change
@@ -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)
})
Loading