Skip to main content

vector_core/db/
at_rest.rs

1//! Local Encryption at-rest sweep: enable, disable and rekey every encrypted
2//! column inside one transaction, so a crash leaves the store on one key.
3//!
4//! Adding an encrypted column is a two-place change: name it in
5//! `SWEEP` (enable finds plaintext by that list alone) and add its writer
6//! to `every_encrypting_writer_is_covered_by_the_at_rest_sweep`. Rekey and disable
7//! also run `sweep_residue_in_tx`, so a missed column still moves with the key.
8
9use zeroize::Zeroize;
10use crate::state::set_encryption_enabled;
11use crate::stored_event::event_kind;
12
13/// Known plaintext for the NIP-55 PIN verification canary. Encrypted under the
14/// derived key at setup (and when Local Encryption is toggled on) and
15/// re-decrypted at boot to reject a wrong PIN (a keyless account has no pkey
16/// whose failed decrypt would otherwise do this).
17pub const NIP55_PIN_CANARY: &str = "vector-nip55-pin-ok";
18
19fn encrypt_with_key(input: &str, key: &[u8; 32]) -> String {
20    crate::crypto::encrypt_with_key(input, key).expect("Encryption should not fail")
21}
22
23fn decrypt_with_key(ciphertext: &str, key: &[u8; 32]) -> Result<String, ()> {
24    crate::crypto::decrypt_with_key(ciphertext, key).map_err(|_| ())
25}
26
27/// Payload of the `encryption_migration_progress` event.
28#[derive(serde::Serialize, Clone)]
29pub struct MigrationProgress {
30    pub total: usize,
31    pub completed: usize,
32    pub phase: String,
33}
34
35// ============================================================================
36// Transactional Migrations (Crash-Safe)
37// ============================================================================
38
39/// Disable encryption inside a single SQLite transaction.
40///
41/// All mutations (event decryption, seed/pkey/PIVX decryption, flag updates)
42/// are wrapped in one transaction on the write connection. If anything fails
43/// or the app crashes before COMMIT, the database stays fully encrypted.
44/// This prevents the mixed plaintext/ciphertext state (audit C3/C4).
45///
46/// Memory-efficient: collects only event IDs upfront, processes one at a time.
47pub fn disable(
48    key: &[u8; 32],
49    progress: &dyn Fn(MigrationProgress),
50) -> Result<(), String> {
51    // Held from before the transaction until the vault and the flag show the result, so no
52    // write sealed under the outgoing key can land after it.
53    let _change = crate::crypto::gate::key_change()?;
54    if !crate::db::writes_to_live_account() {
55        return Err("The account changed before encryption could be turned off".to_string());
56    }
57    let mut conn = crate::db::get_write_connection_guard_static()?;
58    let tx = conn.transaction()
59        .map_err(|e| format!("Failed to begin transaction: {}", e))?;
60
61    // Set migration state inside the transaction — rolls back with everything else on crash
62    tx.execute(
63        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'decrypting')",
64        [],
65    ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
66
67    prove_key_in_tx(&tx, key, false)?;
68
69    // 1. Collect encrypted event IDs (memory-efficient: just ID strings)
70    let all_ids: Vec<String> = {
71        let mut stmt = tx.prepare(
72            r#"SELECT id FROM events
73               WHERE kind IN (?1, ?2, ?3, ?4)
74               AND length(content) >= 56
75               AND content NOT GLOB '*[^0-9a-f]*'"#,
76        ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
77
78        let rows = stmt.query_map(
79            rusqlite::params![
80                event_kind::CHAT_MESSAGE as i32,
81                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
82                event_kind::MESSAGE_EDIT as i32,
83                event_kind::FILE_ATTACHMENT as i32,
84            ],
85            |row| row.get::<_, String>(0),
86        ).map_err(|e| format!("Failed to query IDs: {}", e))?;
87
88        rows.filter_map(|r| r.ok()).collect()
89    };
90
91    let total = all_ids.len();
92    let mut completed = 0;
93    let mut last_emitted_percent: i32 = -1;
94    let mut skipped = 0;
95
96    // 2. Decrypt each event within the transaction
97    for id in &all_ids {
98        let content: Option<String> = tx.query_row(
99            "SELECT content FROM events WHERE id = ?1",
100            rusqlite::params![id],
101            |row| row.get(0),
102        ).ok();
103
104        if let Some(content) = content {
105            match decrypt_with_key(&content, key) {
106                Ok(plaintext) => {
107                    tx.execute(
108                        "UPDATE events SET content = ?1 WHERE id = ?2",
109                        rusqlite::params![plaintext, id],
110                    ).map_err(|e| format!("Failed to update event: {}", e))?;
111                }
112                Err(_) => {
113                    // Content looks encrypted (hex) but isn't — skip it
114                    crate::log_info!("[Encryption] Skipping event {} - looks encrypted but isn't", id);
115                    skipped += 1;
116                }
117            }
118        }
119
120        completed += 1;
121        let current_percent = if total > 0 {
122            ((completed as f64 / total as f64) * 100.0) as i32
123        } else {
124            100
125        };
126
127        if current_percent >= last_emitted_percent + 5 {
128            last_emitted_percent = current_percent;
129            progress(MigrationProgress {
130                total,
131                completed,
132                phase: "decrypting".to_string(),
133            });
134        }
135    }
136
137    // 3. Decrypt settings and PIVX keys within the same transaction
138    progress(MigrationProgress {
139        total,
140        completed,
141        phase: "finalizing".to_string(),
142    });
143
144    decrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
145    decrypt_setting_in_tx(&tx, "pkey", key, |v| v.starts_with("nsec"))?;
146    decrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
147    decrypt_pivx_in_tx(&tx, key)?;
148    decrypt_columns_in_tx(&tx, key)?;
149    sweep_residue_in_tx(&tx, key, None)?;
150
151    // 4. Verify plaintext state within the transaction (before committing)
152    verify_plaintext_state_in_tx(&tx)?;
153
154    // 5. Update flags within the transaction
155    tx.execute(
156        "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', 'false')",
157        [],
158    ).map_err(|e| format!("Failed to update encryption_enabled: {}", e))?;
159    super::settings::write_kdf_in_tx(&tx, None)?;
160
161    // Plaintext account needs no wrong-PIN detector and no unlock method —
162    // drop both in-tx so no reader can infer a mode that no longer exists.
163    tx.execute(
164        "DELETE FROM settings WHERE key = 'nip55_pin_check'",
165        [],
166    ).map_err(|e| format!("Failed to clear pin canary: {}", e))?;
167    tx.execute(
168        "DELETE FROM settings WHERE key = 'security_type'",
169        [],
170    ).map_err(|e| format!("Failed to clear security_type: {}", e))?;
171
172    // The biometric wrap holds the PRE-migration derived key — drop it in the
173    // SAME transaction so no crash window can leave a stale wrap behind.
174    tx.execute(
175        "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
176        [],
177    ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
178
179    tx.execute(
180        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
181        [],
182    ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
183
184    // 6. COMMIT — the atomic point. Everything succeeds or nothing does.
185    tx.commit().map_err(|e| format!("Failed to commit disable transaction: {}", e))?;
186
187    set_encryption_enabled(false);
188    crate::state::ENCRYPTION_KEY.clear(&[&crate::state::MY_SECRET_KEY]);
189    crate::crypto::forget_previous_key();
190
191    if skipped > 0 {
192        crate::log_info!("[Encryption] Skipped {} false-positive hex events", skipped);
193    }
194    crate::log_info!("[Encryption] Disable complete: decrypted {} events", total - skipped);
195
196    Ok(())
197}
198
199/// Enable encryption inside a single SQLite transaction.
200///
201/// All mutations (event encryption, seed/pkey/PIVX encryption, flag updates)
202/// are wrapped in one transaction on the write connection. If anything fails
203/// or the app crashes before COMMIT, the database stays fully plaintext.
204/// This prevents the mixed plaintext/ciphertext state (audit C3/C4).
205///
206/// Memory-efficient: collects only event IDs upfront, processes one at a time.
207pub fn enable(
208    key: &[u8; 32],
209    kdf: &crate::crypto::Kdf,
210    security_type: &str,
211    biometric_wrap: Option<&str>,
212    nip55_canary: Option<&str>,
213    progress: &dyn Fn(MigrationProgress),
214) -> Result<(), String> {
215    if kdf.is_legacy() {
216        return Err("A new key needs its own salt".to_string());
217    }
218    // Held from before the transaction until the vault and the flag show the result, so no
219    // write sealed under the outgoing key can land after it.
220    let _change = crate::crypto::gate::key_change()?;
221    if !crate::db::writes_to_live_account() {
222        return Err("The account changed before encryption could be turned on".to_string());
223    }
224    let mut conn = crate::db::get_write_connection_guard_static()?;
225    let tx = conn.transaction()
226        .map_err(|e| format!("Failed to begin transaction: {}", e))?;
227
228    // Set migration state inside the transaction — rolls back with everything else on crash
229    tx.execute(
230        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'encrypting')",
231        [],
232    ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
233
234    // 1. Collect plaintext event IDs (memory-efficient: just ID strings)
235    let all_ids: Vec<String> = {
236        let mut stmt = tx.prepare(
237            r#"SELECT id FROM events
238               WHERE kind IN (?1, ?2, ?3, ?4) AND content <> ''
239               AND (length(content) < 56 OR content GLOB '*[^0-9a-f]*')"#,
240        ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
241
242        let rows = stmt.query_map(
243            rusqlite::params![
244                event_kind::CHAT_MESSAGE as i32,
245                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
246                event_kind::MESSAGE_EDIT as i32,
247                event_kind::FILE_ATTACHMENT as i32,
248            ],
249            |row| row.get::<_, String>(0),
250        ).map_err(|e| format!("Failed to query IDs: {}", e))?;
251
252        rows.filter_map(|r| r.ok()).collect()
253    };
254
255    let total = all_ids.len();
256    let mut completed = 0;
257    let mut last_emitted_percent: i32 = -1;
258
259    // 2. Encrypt each event within the transaction
260    for id in &all_ids {
261        let content: Option<String> = tx.query_row(
262            "SELECT content FROM events WHERE id = ?1",
263            rusqlite::params![id],
264            |row| row.get(0),
265        ).ok();
266
267        if let Some(content) = content {
268            let encrypted = encrypt_with_key(&content, key);
269            tx.execute(
270                "UPDATE events SET content = ?1 WHERE id = ?2",
271                rusqlite::params![encrypted, id],
272            ).map_err(|e| format!("Failed to update event: {}", e))?;
273        }
274
275        completed += 1;
276        let current_percent = if total > 0 {
277            ((completed as f64 / total as f64) * 100.0) as i32
278        } else {
279            100
280        };
281
282        if current_percent >= last_emitted_percent + 5 {
283            last_emitted_percent = current_percent;
284            progress(MigrationProgress {
285                total,
286                completed,
287                phase: "encrypting".to_string(),
288            });
289        }
290    }
291
292    // 3. Encrypt settings and PIVX keys within the same transaction
293    progress(MigrationProgress {
294        total,
295        completed,
296        phase: "finalizing".to_string(),
297    });
298
299    // The loop above picks plaintext by its look; this catches text that only looks sealed.
300    seal_plain_messages_in_tx(&tx, key)?;
301    encrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
302    encrypt_setting_in_tx(&tx, "pkey", key, |v| v.starts_with("nsec"))?;
303    encrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
304    encrypt_pivx_in_tx(&tx, key)?;
305    encrypt_columns_in_tx(&tx, key)?;
306
307    // 4. Verify encrypted state within the transaction (before committing)
308    verify_encrypted_state_in_tx(&tx, key)?;
309
310    // 5. Update flags within the transaction
311    tx.execute(
312        "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', 'true')",
313        [],
314    ).map_err(|e| format!("Failed to update encryption_enabled: {}", e))?;
315    super::settings::write_kdf_in_tx(&tx, kdf.descriptor().as_deref())?;
316
317    tx.execute(
318        "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
319        rusqlite::params![security_type],
320    ).map_err(|e| format!("Failed to update security_type: {}", e))?;
321
322    // Keyless-account canary: same atomicity rule as the wrap — the only
323    // wrong-PIN detector must land with the flags that make it load-bearing.
324    if let Some(c) = nip55_canary {
325        tx.execute(
326            "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_pin_check', ?1)",
327            rusqlite::params![c],
328        ).map_err(|e| format!("Failed to set pin canary: {}", e))?;
329    }
330
331    // Biometric-only enable carries its wrap INTO this transaction — the row
332    // is the account's sole credential, so it must land atomically with the
333    // flags that lock the store to it. Otherwise drop any stale wrap (it
334    // holds a pre-migration key) in the same transaction.
335    match biometric_wrap {
336        Some(w) => {
337            tx.execute(
338                "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
339                rusqlite::params![w],
340            ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
341        }
342        None => {
343            tx.execute(
344                "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
345                [],
346            ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
347        }
348    }
349
350    tx.execute(
351        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
352        [],
353    ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
354
355    // 6. COMMIT — the atomic point. Everything succeeds or nothing does.
356    tx.commit().map_err(|e| format!("Failed to commit enable transaction: {}", e))?;
357
358    crate::state::ENCRYPTION_KEY.set(*key, &[&crate::state::MY_SECRET_KEY]);
359    set_encryption_enabled(true);
360
361    crate::log_info!("[Encryption] Enable complete: encrypted {} events", total);
362
363    Ok(())
364}
365
366// ============================================================================
367// In-Transaction Helpers
368// ============================================================================
369
370/// Decrypt a setting value within a transaction.
371fn decrypt_setting_in_tx(
372    tx: &rusqlite::Transaction,
373    key_name: &str,
374    key: &[u8; 32],
375    is_plaintext: fn(&str) -> bool,
376) -> Result<(), String> {
377    let val: Option<String> = tx.query_row(
378        "SELECT value FROM settings WHERE key = ?1",
379        rusqlite::params![key_name],
380        |row| row.get(0),
381    ).ok();
382
383    if let Some(current) = val {
384        if is_plaintext(&current) {
385            return Ok(()); // Already plaintext, nothing to decrypt
386        }
387
388        let decrypted = decrypt_with_key(&current, key)
389            .map_err(|_| format!("Failed to decrypt setting '{}'", key_name))?;
390
391        tx.execute(
392            "UPDATE settings SET value = ?1 WHERE key = ?2",
393            rusqlite::params![decrypted, key_name],
394        ).map_err(|e| format!("Failed to update setting '{}': {}", key_name, e))?;
395    }
396
397    Ok(())
398}
399
400/// Encrypt a setting value within a transaction.
401/// Only encrypts if the value is currently plaintext.
402fn encrypt_setting_in_tx(
403    tx: &rusqlite::Transaction,
404    key_name: &str,
405    key: &[u8; 32],
406    is_plaintext: fn(&str) -> bool,
407) -> Result<(), String> {
408    let val: Option<String> = tx.query_row(
409        "SELECT value FROM settings WHERE key = ?1",
410        rusqlite::params![key_name],
411        |row| row.get(0),
412    ).ok();
413
414    if let Some(current) = val {
415        if is_plaintext(&current) {
416            let encrypted = encrypt_with_key(&current, key);
417            tx.execute(
418                "UPDATE settings SET value = ?1 WHERE key = ?2",
419                rusqlite::params![encrypted, key_name],
420            ).map_err(|e| format!("Failed to update setting '{}': {}", key_name, e))?;
421        }
422    }
423
424    Ok(())
425}
426
427/// Decrypt all PIVX promo private keys within a transaction.
428fn decrypt_pivx_in_tx(
429    tx: &rusqlite::Transaction,
430    key: &[u8; 32],
431) -> Result<(), String> {
432    let keys: Vec<(i64, String)> = {
433        let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
434            .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
435        let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
436            .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
437        rows.filter_map(|r| r.ok()).collect()
438    };
439
440    for (id, key_val) in keys {
441        // Only decrypt if longer than a raw key (64 chars) — meaning it's encrypted
442        if key_val.len() > 64 {
443            let decrypted = decrypt_with_key(&key_val, key)
444                .map_err(|_| format!("Failed to decrypt PIVX key {}", id))?;
445            tx.execute(
446                "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
447                rusqlite::params![decrypted, id],
448            ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
449        }
450    }
451
452    Ok(())
453}
454
455/// Encrypt all PIVX promo private keys within a transaction.
456fn encrypt_pivx_in_tx(
457    tx: &rusqlite::Transaction,
458    key: &[u8; 32],
459) -> Result<(), String> {
460    let keys: Vec<(i64, String)> = {
461        let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
462            .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
463        let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
464            .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
465        rows.filter_map(|r| r.ok()).collect()
466    };
467
468    for (id, key_val) in keys {
469        // Raw PIVX keys are exactly 64 hex chars; encrypted output is always longer
470        if key_val.len() <= 64 {
471            let encrypted = encrypt_with_key(&key_val, key);
472            tx.execute(
473                "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
474                rusqlite::params![encrypted, id],
475            ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
476        }
477    }
478
479    Ok(())
480}
481
482// ============================================================================
483// Community (Concord) at-rest migration
484// ============================================================================
485//
486// The community tables hold their own secrets + identifying metadata, wrapped the same way as the
487// pkey/event-content/PIVX fields. One direction-agnostic engine: `dec` decrypts with the given key
488// first, then `enc` encrypts with the given key, so enable = enc only, disable = dec only, rekey =
489// dec(old) then enc(new).
490//
491// The discriminator in both directions is the AEAD tag: "already encrypted under `k`" iff the value
492// opens under `k`. A hex/length heuristic would mistake bare-hex plaintext (invite tokens, creator
493// pubkeys) for ciphertext; the tag can't be fooled, and a re-run never double-wraps.
494
495fn xform_text(v: &str, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>) -> Result<String, String> {
496    // Empty means unset in every sealed column, and queries test it with `<> ''`.
497    if v.is_empty() {
498        return Ok(String::new());
499    }
500    let mut s = zeroize::Zeroizing::new(v.to_string());
501    if let Some(k) = dec {
502        if let Ok(p) = decrypt_with_key(&s, k) {
503            s = zeroize::Zeroizing::new(p);
504        }
505    }
506    if let Some(k) = enc {
507        if decrypt_with_key(&s, k).map(zeroize::Zeroizing::new).is_err() {
508            return Ok(encrypt_with_key(&s, k));
509        }
510    }
511    Ok(s.to_string())
512}
513
514fn xform_blob(v: &[u8], enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>) -> Result<Vec<u8>, String> {
515    let mut b = zeroize::Zeroizing::new(v.to_vec());
516    if let Some(k) = dec {
517        if let Ok(p) = crate::crypto::decrypt_blob_with_key(&b, k) {
518            b = zeroize::Zeroizing::new(p);
519        }
520    }
521    if let Some(k) = enc {
522        if crate::crypto::decrypt_blob_with_key(&b, k).map(zeroize::Zeroizing::new).is_err() {
523            return crate::crypto::encrypt_blob_with_key(&b, k);
524        }
525    }
526    Ok(b.to_vec())
527}
528
529#[cfg(test)]
530mod xform_tests {
531    use super::*;
532    const K: [u8; 32] = [7u8; 32];
533    const K2: [u8; 32] = [9u8; 32];
534
535    #[test]
536    fn bare_hex_plaintext_is_encrypted_not_skipped() {
537        // C1 regression: a 64-char-hex plaintext (invite token / creator pubkey) must be wrapped,
538        // never mistaken for ciphertext.
539        let token = "de".repeat(32); // 64 lowercase hex chars
540        let wrapped = xform_text(&token, Some(&K), None).unwrap();
541        assert_ne!(wrapped, token, "bare-hex plaintext must be encrypted");
542        assert_eq!(decrypt_with_key(&wrapped, &K).unwrap(), token);
543    }
544
545    #[test]
546    fn encrypt_is_idempotent() {
547        let token = "de".repeat(32);
548        let once = xform_text(&token, Some(&K), None).unwrap();
549        let twice = xform_text(&once, Some(&K), None).unwrap();
550        assert_eq!(once, twice, "re-running encrypt must not double-wrap");
551        assert_eq!(decrypt_with_key(&twice, &K).unwrap(), token);
552    }
553
554    #[test]
555    fn disable_then_reenable_roundtrips_bare_hex() {
556        let token = "ab".repeat(32);
557        let enc = xform_text(&token, Some(&K), None).unwrap();
558        let dec = xform_text(&enc, None, Some(&K)).unwrap();
559        assert_eq!(dec, token, "disable decrypts back to plaintext");
560        let re = xform_text(&dec, Some(&K), None).unwrap();
561        assert_eq!(decrypt_with_key(&re, &K).unwrap(), token, "re-enable wraps the bare-hex again");
562    }
563
564    #[test]
565    fn rekey_rewraps_bare_hex_under_new_key() {
566        let token = "cd".repeat(32);
567        let old = xform_text(&token, Some(&K), None).unwrap();
568        let new = xform_text(&old, Some(&K2), Some(&K)).unwrap(); // dec old, enc new
569        assert!(decrypt_with_key(&new, &K).is_err(), "no longer under old key");
570        assert_eq!(decrypt_with_key(&new, &K2).unwrap(), token, "now under new key");
571    }
572
573    #[test]
574    fn nonhex_plaintext_roundtrips() {
575        assert_eq!(xform_text("", Some(&K), None).unwrap(), "", "empty stays empty");
576        for v in ["general", "{\"roles\":[]}", "wss://relay.example"] {
577            let enc = xform_text(v, Some(&K), None).unwrap();
578            assert_eq!(decrypt_with_key(&enc, &K).unwrap(), v);
579            assert_eq!(xform_text(&enc, None, Some(&K)).unwrap(), v);
580        }
581    }
582
583    /// The Concord tables exactly as the sweep addresses them (columns it does
584    /// not touch omitted).
585    fn migrate_test_schema(conn: &rusqlite::Connection) {
586        conn.execute_batch(
587            "CREATE TABLE communities (community_id TEXT, server_root_key BLOB, name TEXT, relays TEXT, description TEXT, icon TEXT, banner TEXT, banlist TEXT, banlist_marks TEXT, roles TEXT, invite_registry TEXT, owner_pubkey TEXT, owner_salt TEXT, meta_extra TEXT, control_pk TEXT, control_root BLOB);
588             CREATE TABLE community_channels (channel_id TEXT, channel_key BLOB, name TEXT, meta_extra TEXT);
589             CREATE TABLE community_epoch_keys (key BLOB);
590             CREATE TABLE community_message_keys (outer_event_id TEXT, ephemeral_secret BLOB, relays TEXT);
591             CREATE TABLE community_wrap_owners (outer_event_id TEXT, owner_secret BLOB, relays TEXT);
592             CREATE TABLE pending_channel_keys (id INTEGER PRIMARY KEY AUTOINCREMENT, channel_key BLOB, sender TEXT);
593             CREATE TABLE pending_community_invites (community_id TEXT, bundle_json TEXT, inviter_npub TEXT);
594             CREATE TABLE community_public_invites (token TEXT, url TEXT, label TEXT);
595             CREATE TABLE community_invite_link_sets (creator TEXT, locators TEXT);
596             CREATE TABLE community_guestbook (community_id TEXT, events TEXT, cursor_secs INTEGER);
597             CREATE TABLE community_guestbook_events (seq INTEGER PRIMARY KEY, book INTEGER, rumor_id BLOB, body BLOB);
598             CREATE TABLE community_departures_seen (seq INTEGER PRIMARY KEY, book INTEGER, body BLOB);
599             CREATE TABLE community_owed_authors (seq INTEGER PRIMARY KEY, book INTEGER, channel_id TEXT, body BLOB);
600             CREATE TABLE community_policies (community_id TEXT, policy_id TEXT, bytes TEXT, hash TEXT, enabled INTEGER, updated_at INTEGER);
601             CREATE TABLE community_pins (community_id TEXT, channel_id TEXT, content TEXT, PRIMARY KEY (community_id, channel_id));
602             CREATE TABLE community_writers (community_id TEXT, channel_id TEXT, content TEXT, PRIMARY KEY (community_id, channel_id));
603             CREATE TABLE attachments (key TEXT, nonce TEXT, name TEXT, url TEXT, fallback_urls TEXT, img_meta TEXT);
604             CREATE TABLE media_store (hash TEXT PRIMARY KEY, key TEXT, nonce TEXT);
605             CREATE TABLE events (preview_metadata TEXT);
606             CREATE TABLE nip17_wrap_keys (rumor_json TEXT);
607             CREATE TABLE community_bans (community_id TEXT, npub TEXT);
608             CREATE TABLE community_held_wraps (wrap_id TEXT PRIMARY KEY, wrap TEXT);
609             CREATE TABLE community_control_wraps (wrap_id BLOB PRIMARY KEY, wrap BLOB);
610             CREATE TABLE community_audit_local (id TEXT PRIMARY KEY, entry TEXT);
611             CREATE TABLE dm_held_wallpapers (chat_id TEXT, payload TEXT);",
612        ).unwrap();
613    }
614
615    /// Every encrypted store must survive a rekey. The guestbook was missed
616    /// when it landed: a PIN change left it under the old key, the read
617    /// swallowed the failure as an empty list, and every member count collapsed
618    /// until a full plane walk rebuilt it.
619    #[test]
620    fn guestbook_and_policies_survive_enable_rekey_disable() {
621        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
622        migrate_test_schema(&conn);
623        conn.execute(
624            "INSERT INTO community_guestbook (community_id, events, cursor_secs) VALUES (?1, ?2, 7)",
625            rusqlite::params!["aa".repeat(32), r#"[{"rumor_id":"x"}]"#],
626        )
627        .unwrap();
628        conn.execute(
629            "INSERT INTO community_policies (community_id, policy_id, bytes, hash, enabled, updated_at)
630             VALUES (?1, 'p1', ?2, 'hh', 1, 0)",
631            rusqlite::params!["aa".repeat(32), r#"{"format":1,"name":"x"}"#],
632        )
633        .unwrap();
634        let read = |c: &rusqlite::Connection| -> (String, String) {
635            (
636                c.query_row("SELECT events FROM community_guestbook", [], |r| r.get(0)).unwrap(),
637                c.query_row("SELECT bytes FROM community_policies", [], |r| r.get(0)).unwrap(),
638            )
639        };
640        let before = read(&conn);
641        let k1 = [0x21u8; 32];
642        let k2 = [0x22u8; 32];
643        let step = |c: &mut rusqlite::Connection, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>| {
644            let tx = c.transaction().unwrap();
645            sweep_columns_in_tx(&tx, enc, dec).unwrap();
646            tx.commit().unwrap();
647        };
648        step(&mut conn, Some(&k1), None);
649        // The teeth: a table the sweep never touches stays PLAINTEXT, and a
650        // round-trip over it would pass trivially. Assert the enable actually
651        // wrapped both stores before checking they come back.
652        let enabled = read(&conn);
653        assert_ne!(enabled.0, before.0, "the guestbook must actually be encrypted by the sweep");
654        assert_ne!(enabled.1, before.1, "the policy bytes must actually be encrypted by the sweep");
655
656        step(&mut conn, Some(&k2), Some(&k1));
657        step(&mut conn, None, Some(&k2));
658        assert_eq!(read(&conn), before, "a rekey round-trip must return the plaintext it started with");
659    }
660
661    /// Sweep parity for the v2 columns: the owner commitment and the CORD-02 §2
662    /// control pair must survive enable → rekey → disable. A missed column stays
663    /// under the old key — the pair silently drops to read-only on load, and a
664    /// garbled owner commitment fails the whole v2 load.
665    #[test]
666    fn v2_control_pair_survives_enable_rekey_disable() {
667        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
668        migrate_test_schema(&conn);
669        let control_root: Vec<u8> = vec![0x5Au8; 32];
670        conn.execute(
671            "INSERT INTO communities (community_id, server_root_key, name, relays, banlist, roles, invite_registry, owner_pubkey, owner_salt, meta_extra, control_pk, control_root)
672             VALUES (?1, ?2, 'n', '[]', '[]', '{}', '[]', ?3, ?4, '{\"custom\":null,\"extra\":{}}', ?5, ?6)",
673            rusqlite::params!["cc".repeat(32), vec![0x11u8; 32], "ab".repeat(32), "cd".repeat(32), "ef".repeat(32), control_root],
674        ).unwrap();
675        let read = |c: &rusqlite::Connection| -> (String, String, Vec<u8>) {
676            c.query_row("SELECT owner_pubkey, control_pk, control_root FROM communities", [], |r| {
677                Ok((r.get(0)?, r.get(1)?, r.get(2)?))
678            }).unwrap()
679        };
680
681        let tx = conn.transaction().unwrap();
682        encrypt_columns_in_tx(&tx, &K).unwrap();
683        tx.commit().unwrap();
684        let (owner_pk, control_pk, root) = read(&conn);
685        assert_ne!(owner_pk, "ab".repeat(32), "owner commitment must be wrapped after enable");
686        assert_ne!(control_pk, "ef".repeat(32), "control_pk must be wrapped after enable");
687        assert_ne!(root, vec![0x5Au8; 32], "control_root must be wrapped after enable");
688
689        let tx = conn.transaction().unwrap();
690        rekey_columns_in_tx(&tx, &K, &K2).unwrap();
691        tx.commit().unwrap();
692
693        let tx = conn.transaction().unwrap();
694        decrypt_columns_in_tx(&tx, &K2).unwrap();
695        tx.commit().unwrap();
696        let (owner_pk, control_pk, root) = read(&conn);
697        assert_eq!(owner_pk, "ab".repeat(32), "owner commitment survives enable → rekey → disable");
698        assert_eq!(control_pk, "ef".repeat(32), "control_pk survives enable → rekey → disable");
699        assert_eq!(root, vec![0x5Au8; 32], "control_root survives enable → rekey → disable");
700    }
701
702    /// Sweep parity: every encrypted community_public_invites column must survive
703    /// enable → rekey → disable (a column missed by the sweep garbles on the first rekey).
704    #[test]
705    fn public_invite_label_survives_enable_rekey_disable() {
706        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
707        migrate_test_schema(&conn);
708        conn.execute(
709            "INSERT INTO community_public_invites (token, url, label) VALUES (?1, ?2, ?3)",
710            rusqlite::params!["ab".repeat(32), "https://vectorapp.io/invite#x", "Reddit"],
711        ).unwrap();
712        let read_label = |c: &rusqlite::Connection| -> String {
713            c.query_row("SELECT label FROM community_public_invites", [], |r| r.get(0)).unwrap()
714        };
715
716        let tx = conn.transaction().unwrap();
717        encrypt_columns_in_tx(&tx, &K).unwrap();
718        tx.commit().unwrap();
719        assert_ne!(read_label(&conn), "Reddit", "label must be wrapped after enable");
720
721        let tx = conn.transaction().unwrap();
722        rekey_columns_in_tx(&tx, &K, &K2).unwrap();
723        tx.commit().unwrap();
724
725        let tx = conn.transaction().unwrap();
726        decrypt_columns_in_tx(&tx, &K2).unwrap();
727        tx.commit().unwrap();
728        assert_eq!(read_label(&conn), "Reddit", "label must survive enable → rekey → disable");
729    }
730
731    /// The sweep list must name real columns: a typo would fail every PIN change with
732    /// "no such column" instead of quietly sweeping nothing.
733    #[test]
734    fn sweep_list_matches_the_real_schema() {
735        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
736        conn.execute_batch(crate::db::schema::SQL_SCHEMA).unwrap();
737        crate::db::schema::run_migrations(&mut conn).unwrap();
738        for (table, cols) in SWEEP {
739            conn.prepare(&format!("SELECT {} FROM {table}", cols.join(", ")))
740                .unwrap_or_else(|e| panic!("{table}: {e}"));
741        }
742    }
743
744    /// Every listed column, with NULLs where a column allows them, round-trips through
745    /// enable, rekey and disable, and a NULL never costs its row the sweep.
746    #[test]
747    fn every_swept_column_survives_enable_rekey_disable() {
748        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
749        migrate_test_schema(&conn);
750        let mut n = 0u8;
751        for (table, cols) in SWEEP {
752            for with_nulls in [false, true] {
753                let vals: Vec<rusqlite::types::Value> = cols.iter().map(|c| {
754                    n += 1;
755                    let blob = conn
756                        .query_row("SELECT type FROM pragma_table_info(?1) WHERE name = ?2", [table, c], |r| r.get::<_, String>(0))
757                        .unwrap() == "BLOB";
758                    if with_nulls && *c != cols[0] {
759                        rusqlite::types::Value::Null
760                    } else if blob {
761                        rusqlite::types::Value::Blob(vec![n; 32])
762                    } else {
763                        rusqlite::types::Value::Text(format!("{c}-{n}"))
764                    }
765                }).collect();
766                let marks = vec!["?"; cols.len()].join(", ");
767                let sql = format!("INSERT OR REPLACE INTO {table} ({}) VALUES ({marks})", cols.join(", "));
768                conn.execute(&sql, rusqlite::params_from_iter(vals.iter())).unwrap();
769            }
770        }
771        let snapshot = |c: &rusqlite::Connection| -> Vec<Vec<rusqlite::types::Value>> {
772            SWEEP.iter().flat_map(|(table, cols)| {
773                let mut stmt = c.prepare(&format!("SELECT {} FROM {table} ORDER BY rowid", cols.join(", "))).unwrap();
774                let rows = stmt
775                    .query_map([], |r| (0..cols.len()).map(|i| r.get::<_, rusqlite::types::Value>(i)).collect())
776                    .unwrap()
777                    .map(|r| r.unwrap())
778                    .collect::<Vec<Vec<rusqlite::types::Value>>>();
779                rows
780            }).collect()
781        };
782        let before = snapshot(&conn);
783        let step = |c: &mut rusqlite::Connection, enc: Option<&[u8; 32]>, dec: Option<&[u8; 32]>| {
784            let tx = c.transaction().unwrap();
785            sweep_columns_in_tx(&tx, enc, dec).unwrap();
786            tx.commit().unwrap();
787        };
788
789        step(&mut conn, Some(&K), None);
790        let enabled = snapshot(&conn);
791        for (row_before, row_enabled) in before.iter().zip(&enabled) {
792            for (b, e) in row_before.iter().zip(row_enabled) {
793                match b {
794                    rusqlite::types::Value::Null => assert_eq!(e, b, "NULL stays NULL"),
795                    _ => assert_ne!(e, b, "every listed value must actually be wrapped by enable"),
796                }
797            }
798        }
799        step(&mut conn, Some(&K2), Some(&K));
800        {
801            let tx = conn.transaction().unwrap();
802            assert_eq!(sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(), 0, "the list alone leaves nothing on the old key");
803        }
804        step(&mut conn, None, Some(&K2));
805        assert_eq!(snapshot(&conn), before, "enable, rekey and disable return every value it started with");
806    }
807
808    /// The net under the lists: a column nobody listed still moves with the key, in its own
809    /// storage class, and only what opens under the old key is touched.
810    #[test]
811    fn residue_sweep_moves_unlisted_ciphertext_and_nothing_else() {
812        const K3: [u8; 32] = [11u8; 32];
813        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
814        conn.execute_batch("CREATE TABLE future (t TEXT, b BLOB, n INTEGER);").unwrap();
815        let text_ct = encrypt_with_key("hello", &K);
816        let blob_ct = crate::crypto::encrypt_blob_with_key(&[0x42u8; 32], &K).unwrap();
817        let foreign = encrypt_with_key("someone else's", &K3);
818        let bare_hex = "ab".repeat(32);
819        conn.execute("INSERT INTO future VALUES (?1, ?2, 1)", rusqlite::params![text_ct, blob_ct]).unwrap();
820        conn.execute("INSERT INTO future VALUES (?1, NULL, 2)", rusqlite::params![foreign]).unwrap();
821        conn.execute("INSERT INTO future VALUES (?1, x'00ff', 3)", rusqlite::params![bare_hex]).unwrap();
822
823        let tx = conn.transaction().unwrap();
824        assert_eq!(sweep_residue_in_tx(&tx, &K, Some(&K2)).unwrap(), 2);
825        tx.commit().unwrap();
826        let (t, b): (String, Vec<u8>) = conn.query_row("SELECT t, b FROM future WHERE n = 1", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap();
827        assert_eq!(decrypt_with_key(&t, &K2).unwrap(), "hello");
828        assert_eq!(crate::crypto::decrypt_blob_with_key(&b, &K2).unwrap(), vec![0x42u8; 32]);
829        let untouched: (String, String) = conn.query_row(
830            "SELECT (SELECT t FROM future WHERE n = 2), (SELECT t FROM future WHERE n = 3)", [], |r| Ok((r.get(0)?, r.get(1)?)),
831        ).unwrap();
832        assert_eq!(untouched, (foreign, bare_hex), "values not under the old key are left alone");
833
834        let tx = conn.transaction().unwrap();
835        assert_eq!(sweep_residue_in_tx(&tx, &K2, None).unwrap(), 2);
836        tx.commit().unwrap();
837        let (t, b): (String, Vec<u8>) = conn.query_row("SELECT t, b FROM future WHERE n = 1", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap();
838        assert_eq!((t.as_str(), b), ("hello", vec![0x42u8; 32]), "disable opens text to text and blob to blob");
839    }
840
841    /// Ciphertext the sweep cannot address or cannot open to text aborts the transaction
842    /// rather than being left on a key the store stops using.
843    #[test]
844    fn residue_sweep_refuses_what_it_cannot_move() {
845        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
846        conn.execute_batch("CREATE TABLE keyed (k TEXT PRIMARY KEY, v TEXT) WITHOUT ROWID;").unwrap();
847        conn.execute("INSERT INTO keyed VALUES ('a', ?1)", [encrypt_with_key("x", &K)]).unwrap();
848        let tx = conn.transaction().unwrap();
849        assert!(sweep_residue_in_tx(&tx, &K, Some(&K2)).is_err());
850        drop(tx);
851
852        let mut conn = rusqlite::Connection::open_in_memory().unwrap();
853        conn.execute_batch("CREATE TABLE odd (v TEXT);").unwrap();
854        let sealed = crate::crypto::encrypt_blob_with_key(&[0xff, 0xfe, 0x00], &K).unwrap();
855        conn.execute("INSERT INTO odd VALUES (?1)", [crate::simd::hex::bytes_to_hex_string(&sealed)]).unwrap();
856        let tx = conn.transaction().unwrap();
857        assert!(sweep_residue_in_tx(&tx, &K, None).is_err(), "bytes that are not text never land in a text column");
858    }
859
860    /// The key proof on the real schema: whichever anchor the store has decides, and a store
861    /// with none passes only when the caller does not need one.
862    #[test]
863    fn a_key_is_proven_by_whatever_the_store_holds() {
864        let fresh = || {
865            let mut c = rusqlite::Connection::open_in_memory().unwrap();
866            c.execute_batch(crate::db::schema::SQL_SCHEMA).unwrap();
867            crate::db::schema::run_migrations(&mut c).unwrap();
868            c
869        };
870        let proves = |c: &mut rusqlite::Connection, k: &[u8; 32], require: bool| {
871            let tx = c.transaction().unwrap();
872            prove_key_in_tx(&tx, k, require).is_ok()
873        };
874
875        let mut empty = fresh();
876        assert!(proves(&mut empty, &K, false), "nothing encrypted, nothing to lose");
877        assert!(!proves(&mut empty, &K, true), "an enable-direction pass needs an anchor");
878
879        let mut local = fresh();
880        local.execute("INSERT INTO settings (key, value) VALUES ('pkey', ?1)", [encrypt_with_key("nsec1abc", &K)]).unwrap();
881        assert!(proves(&mut local, &K, true));
882        assert!(!proves(&mut local, &K2, false));
883
884        let mut keyless = fresh();
885        keyless.execute("INSERT INTO settings (key, value) VALUES ('nip55_pin_check', ?1)", [encrypt_with_key(NIP55_PIN_CANARY, &K)]).unwrap();
886        assert!(proves(&mut keyless, &K, true));
887        assert!(!proves(&mut keyless, &K2, false));
888
889        let mut no_canary = fresh();
890        let blob = crate::crypto::encrypt_blob_with_key(&[7u8; 32], &K).unwrap();
891        no_canary.execute(
892            "INSERT INTO community_epoch_keys (community_id, scope_id, epoch, key, created_at) VALUES ('c', 's', 0, ?1, 0)",
893            [blob],
894        ).unwrap();
895        assert!(proves(&mut no_canary, &K, true), "a sealed community key is proof enough");
896        assert!(!proves(&mut no_canary, &K2, false), "a key that opens none of the samples is refused");
897    }
898
899    #[test]
900    fn blob_roundtrip_and_idempotent() {
901        let raw = [0x42u8; 32];
902        let enc = xform_blob(&raw, Some(&K), None).unwrap();
903        assert_eq!(enc.len(), 60);
904        assert_eq!(xform_blob(&enc, Some(&K), None).unwrap(), enc, "blob encrypt idempotent");
905        assert_eq!(xform_blob(&enc, None, Some(&K)).unwrap(), raw.to_vec());
906        // rekey path for blobs
907        let re = xform_blob(&enc, Some(&K2), Some(&K)).unwrap();
908        assert_eq!(crate::crypto::decrypt_blob_with_key(&re, &K2).unwrap(), raw.to_vec());
909    }
910}
911
912/// Every encrypted column outside the hand-swept message content, settings and PIVX rows, by
913/// table. Enable depends on this list alone (plaintext carries nothing to find it by); rekey and
914/// disable are also backed by `sweep_residue_in_tx`, which catches a column missing here by its tag.
915const SWEEP: &[(&str, &[&str])] = &[
916    ("attachments", &["key", "nonce", "name", "url", "fallback_urls", "img_meta"]),
917    ("media_store", &["key", "nonce"]),
918    ("events", &["preview_metadata"]),
919    ("nip17_wrap_keys", &["rumor_json"]),
920    ("communities", &[
921        "server_root_key", "name", "relays", "description", "icon", "banner", "banlist",
922        "banlist_marks", "roles", "invite_registry", "owner_pubkey", "owner_salt", "meta_extra",
923        "control_pk", "control_root",
924    ]),
925    ("community_channels", &["channel_key", "name", "meta_extra"]),
926    ("community_epoch_keys", &["key"]),
927    ("community_message_keys", &["ephemeral_secret", "relays"]),
928    ("community_wrap_owners", &["owner_secret", "relays"]),
929    ("pending_channel_keys", &["channel_key", "sender"]),
930    ("pending_community_invites", &["bundle_json", "inviter_npub"]),
931    ("community_guestbook", &["events"]),
932    ("community_guestbook_events", &["body"]),
933    ("community_departures_seen", &["body"]),
934    ("community_owed_authors", &["body"]),
935    ("community_policies", &["bytes"]),
936    ("community_public_invites", &["token", "url", "label"]),
937    ("community_invite_link_sets", &["creator", "locators"]),
938    ("community_pins", &["content"]),
939    ("community_writers", &["content"]),
940    ("community_bans", &["npub"]),
941    ("community_held_wraps", &["wrap"]),
942    ("community_control_wraps", &["wrap"]),
943    ("community_audit_local", &["entry"]),
944    ("dm_held_wallpapers", &["payload"]),
945];
946
947fn sweep_columns_in_tx(
948    tx: &rusqlite::Transaction,
949    enc: Option<&[u8; 32]>,
950    dec: Option<&[u8; 32]>,
951) -> Result<(), String> {
952    for (table, cols) in SWEEP {
953        xform_columns_in_tx(tx, table, cols, enc, dec)?;
954    }
955    Ok(())
956}
957
958/// Transform the named columns of every row by storage class (text, blob; NULL and numbers kept).
959/// A row that fails to read aborts the transaction: skipping it would leave it on the old key.
960/// A column this database never gained holds nothing to move, so it is skipped, not fatal.
961fn xform_columns_in_tx(
962    tx: &rusqlite::Transaction,
963    table: &str,
964    cols: &[&str],
965    enc: Option<&[u8; 32]>,
966    dec: Option<&[u8; 32]>,
967) -> Result<(), String> {
968    use rusqlite::types::Value;
969    let present: Vec<String> = {
970        let mut stmt = tx
971            .prepare("SELECT name FROM pragma_table_info(?1)")
972            .map_err(|e| format!("columns of {table}: {e}"))?;
973        let mapped = stmt.query_map([table], |r| r.get::<_, String>(0)).map_err(|e| format!("columns of {table}: {e}"))?;
974        mapped.collect::<Result<_, _>>().map_err(|e| format!("columns of {table}: {e}"))?
975    };
976    let cols: Vec<&str> = cols.iter().copied().filter(|c| present.iter().any(|p| p == c)).collect();
977    if cols.is_empty() {
978        crate::log_warn!("[Encryption] {table} is missing from this database; nothing to sweep there");
979        return Ok(());
980    }
981    let rows: Vec<(i64, Vec<Value>)> = {
982        let mut stmt = tx
983            .prepare(&format!("SELECT rowid, {} FROM {table}", cols.join(", ")))
984            .map_err(|e| format!("prepare {table}: {e}"))?;
985        let mapped = stmt
986            .query_map([], |r| {
987                let vals = (1..=cols.len()).map(|i| r.get::<_, Value>(i)).collect::<Result<Vec<_>, _>>()?;
988                Ok((r.get::<_, i64>(0)?, vals))
989            })
990            .map_err(|e| format!("query {table}: {e}"))?;
991        mapped.collect::<Result<_, _>>().map_err(|e| format!("read {table}: {e}"))?
992    };
993    let set = cols.iter().enumerate().map(|(i, c)| format!("{c} = ?{}", i + 1)).collect::<Vec<_>>().join(", ");
994    let mut update = tx
995        .prepare(&format!("UPDATE {table} SET {set} WHERE rowid = ?{}", cols.len() + 1))
996        .map_err(|e| format!("prepare update {table}: {e}"))?;
997    for (rowid, vals) in rows {
998        let mut out = Vec::with_capacity(vals.len() + 1);
999        for v in &vals {
1000            out.push(match v {
1001                Value::Text(s) => Value::Text(xform_text(s, enc, dec)?),
1002                Value::Blob(b) => Value::Blob(xform_blob(b, enc, dec)?),
1003                other => other.clone(),
1004            });
1005        }
1006        if out == vals {
1007            continue;
1008        }
1009        out.push(Value::Integer(rowid));
1010        update
1011            .execute(rusqlite::params_from_iter(out.iter()))
1012            .map_err(|e| format!("update {table}: {e}"))?;
1013    }
1014    Ok(())
1015}
1016
1017/// The tag-based net under the sweep lists: any text or blob cell, in any table, that opens under
1018/// `from` moves to `to` (None = plaintext). Nothing is left behind on a key the store stops using,
1019/// even in a column no list names yet. Returns how many cells the lists had missed.
1020pub(crate) fn sweep_residue_in_tx(
1021    tx: &rusqlite::Transaction,
1022    from: &[u8; 32],
1023    to: Option<&[u8; 32]>,
1024) -> Result<usize, String> {
1025    let tables: Vec<(String, bool)> = {
1026        let mut stmt = tx
1027            .prepare("SELECT name, wr FROM pragma_table_list WHERE schema = 'main' AND type = 'table' AND name NOT LIKE 'sqlite_%'")
1028            .map_err(|e| format!("residue: list tables: {e}"))?;
1029        let mapped = stmt
1030            .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?)))
1031            .map_err(|e| format!("residue: list tables: {e}"))?;
1032        mapped.collect::<Result<_, _>>().map_err(|e| format!("residue: list tables: {e}"))?
1033    };
1034
1035    let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));
1036    let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(from);
1037    let mut scratch = Vec::new();
1038    let mut total = 0;
1039    for (table, without_rowid) in tables {
1040        let cols: Vec<String> = {
1041            let mut stmt = tx
1042                .prepare("SELECT name FROM pragma_table_info(?1)")
1043                .map_err(|e| format!("residue: columns of {table}: {e}"))?;
1044            let mapped = stmt
1045                .query_map([&table], |r| r.get::<_, String>(0))
1046                .map_err(|e| format!("residue: columns of {table}: {e}"))?;
1047            mapped.collect::<Result<_, _>>().map_err(|e| format!("residue: columns of {table}: {e}"))?
1048        };
1049        if cols.is_empty() {
1050            continue;
1051        }
1052        let quoted: Vec<String> = cols.iter().map(|c| quote(c)).collect();
1053        let rowid = if without_rowid { "NULL" } else { "rowid" };
1054        // Positions only: holding the moved values for a whole table would put every
1055        // ciphertext it holds in memory at once.
1056        let mut found: Vec<(i64, usize)> = Vec::new();
1057        {
1058            let mut stmt = tx
1059                .prepare(&format!("SELECT {rowid}, {} FROM {}", quoted.join(", "), quote(&table)))
1060                .map_err(|e| format!("residue: scan {table}: {e}"))?;
1061            let mut rows = stmt.query([]).map_err(|e| format!("residue: scan {table}: {e}"))?;
1062            while let Some(row) = rows.next().map_err(|e| format!("residue: scan {table}: {e}"))? {
1063                for (i, col) in cols.iter().enumerate() {
1064                    let cell = row.get_ref(i + 1).map_err(|e| format!("residue: read {table}.{col}: {e}"))?;
1065                    if !opens_under(cell, &cipher, &mut scratch) {
1066                        continue;
1067                    }
1068                    if without_rowid {
1069                        return Err(format!("residue: {table}.{col} holds ciphertext but the table has no rowid to address it"));
1070                    }
1071                    found.push((row.get(0).map_err(|e| format!("residue: rowid of {table}: {e}"))?, i));
1072                }
1073            }
1074        }
1075        for &(id, i) in &found {
1076            let col = &quoted[i];
1077            let moved = tx
1078                .query_row(&format!("SELECT {col} FROM {} WHERE rowid = ?1", quote(&table)), [id], |r| {
1079                    Ok(move_cell(r.get_ref(0)?, from, to))
1080                })
1081                .map_err(|e| format!("residue: reread {table}.{}: {e}", cols[i]))?
1082                .map_err(|e| format!("residue: {table}.{}: {e}", cols[i]))?;
1083            let Some(moved) = moved else { continue };
1084            tx.execute(&format!("UPDATE {} SET {col} = ?1 WHERE rowid = ?2", quote(&table)), rusqlite::params![moved, id])
1085                .map_err(|e| format!("residue: update {table}.{}: {e}", cols[i]))?;
1086        }
1087        let mut by_col = std::collections::BTreeMap::<&str, usize>::new();
1088        for &(_, i) in &found {
1089            *by_col.entry(cols[i].as_str()).or_default() += 1;
1090        }
1091        for (col, n) in by_col {
1092            crate::log_warn!("[Encryption] {n} value(s) in {table}.{col} were outside the sweep lists; moved with the key");
1093        }
1094        total += found.len();
1095    }
1096    Ok(total)
1097}
1098
1099/// Seal every message, file caption and edit whose text is still plaintext under `key`: rows that
1100/// landed before encryption counted as on, and text a hex-looking heuristic once skipped. Sealed
1101/// rows open under `key` and are left as they are. Returns how many were sealed.
1102fn seal_plain_messages_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<usize, String> {
1103    let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(key);
1104    let mut scratch = Vec::new();
1105    let sealed: Vec<(i64, String)> = {
1106        let mut stmt = tx
1107            .prepare("SELECT rowid, content FROM events WHERE kind IN (?1, ?2, ?3, ?4) AND content <> ''")
1108            .map_err(|e| format!("plain messages: {e}"))?;
1109        let mut rows = stmt
1110            .query(rusqlite::params![
1111                event_kind::CHAT_MESSAGE as i32,
1112                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1113                event_kind::MESSAGE_EDIT as i32,
1114                event_kind::FILE_ATTACHMENT as i32,
1115            ])
1116            .map_err(|e| format!("plain messages: {e}"))?;
1117        let mut out = Vec::new();
1118        while let Some(row) = rows.next().map_err(|e| format!("plain messages: {e}"))? {
1119            let cell = row.get_ref(1).map_err(|e| format!("plain messages: {e}"))?;
1120            if opens_under(cell, &cipher, &mut scratch) {
1121                continue;
1122            }
1123            let rusqlite::types::ValueRef::Text(text) = cell else { continue };
1124            let Ok(text) = std::str::from_utf8(text) else { continue };
1125            out.push((row.get(0).map_err(|e| format!("plain messages: {e}"))?, encrypt_with_key(text, key)));
1126        }
1127        out
1128    };
1129    for (rowid, content) in &sealed {
1130        tx.execute("UPDATE events SET content = ?1 WHERE rowid = ?2", rusqlite::params![content, rowid])
1131            .map_err(|e| format!("seal message: {e}"))?;
1132    }
1133    Ok(sealed.len())
1134}
1135
1136/// Whether a cell is ciphertext under the cipher's key, in either at-rest encoding. `scratch`
1137/// holds each candidate's bytes and is wiped after every check.
1138fn opens_under(
1139    cell: rusqlite::types::ValueRef<'_>,
1140    cipher: &crate::crypto::chachapoly::ChaCha20Poly1305,
1141    scratch: &mut Vec<u8>,
1142) -> bool {
1143    use rusqlite::types::ValueRef;
1144    scratch.clear();
1145    match cell {
1146        ValueRef::Text(bytes) => match std::str::from_utf8(bytes) {
1147            Ok(s) if crate::crypto::looks_encrypted(s) => match crate::simd::hex::hex_string_to_bytes_checked(s) {
1148                Some(framed) => *scratch = framed,
1149                None => return false,
1150            },
1151            _ => return false,
1152        },
1153        ValueRef::Blob(bytes) => scratch.extend_from_slice(bytes),
1154        _ => return false,
1155    }
1156    let opened = cipher.open_framed_in_place(scratch).is_ok();
1157    crate::crypto::wipe(scratch);
1158    opened
1159}
1160
1161/// A cell under `from`, re-sealed under `to` or opened to plaintext in its own storage class.
1162/// None when the cell is not ciphertext under `from`.
1163fn move_cell(
1164    cell: rusqlite::types::ValueRef<'_>,
1165    from: &[u8; 32],
1166    to: Option<&[u8; 32]>,
1167) -> Result<Option<rusqlite::types::Value>, String> {
1168    use rusqlite::types::{Value, ValueRef};
1169    match cell {
1170        ValueRef::Text(bytes) => {
1171            let Ok(s) = std::str::from_utf8(bytes) else { return Ok(None) };
1172            if !crate::crypto::looks_encrypted(s) {
1173                return Ok(None);
1174            }
1175            let Some(framed) = crate::simd::hex::hex_string_to_bytes_checked(s) else { return Ok(None) };
1176            let Ok(mut plain) = crate::crypto::decrypt_blob_with_key(&framed, from) else { return Ok(None) };
1177            let moved = match to {
1178                Some(k) => crate::crypto::encrypt_blob_with_key(&plain, k)
1179                    .map(|sealed| Value::Text(crate::simd::hex::bytes_to_hex_string(&sealed))),
1180                None => String::from_utf8(plain.clone())
1181                    .map(Value::Text)
1182                    .map_err(|_| "opens to bytes that are not text".to_string()),
1183            };
1184            plain.zeroize();
1185            moved.map(Some)
1186        }
1187        ValueRef::Blob(bytes) => {
1188            let Ok(mut plain) = crate::crypto::decrypt_blob_with_key(bytes, from) else { return Ok(None) };
1189            let moved = match to {
1190                Some(k) => crate::crypto::encrypt_blob_with_key(&plain, k).map(Value::Blob),
1191                None => Ok(Value::Blob(plain.clone())),
1192            };
1193            plain.zeroize();
1194            moved.map(Some)
1195        }
1196        _ => Ok(None),
1197    }
1198}
1199
1200/// Encrypt all Concord secrets + metadata (enable flow).
1201fn encrypt_columns_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<(), String> {
1202    sweep_columns_in_tx(tx, Some(key), None)
1203}
1204/// Decrypt all Concord secrets + metadata (disable flow).
1205fn decrypt_columns_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32]) -> Result<(), String> {
1206    sweep_columns_in_tx(tx, None, Some(key))
1207}
1208/// Re-wrap all Concord secrets + metadata old key → new key (PIN-rekey flow).
1209pub(crate) fn rekey_columns_in_tx(tx: &rusqlite::Transaction, old_key: &[u8; 32], new_key: &[u8; 32]) -> Result<(), String> {
1210    sweep_columns_in_tx(tx, Some(new_key), Some(old_key))
1211}
1212
1213/// Bumped whenever `SWEEP` gains a column or the backfill gains a step: an account that turned
1214/// encryption on before then may still hold that data in plaintext, and the backfill runs once
1215/// more to wrap it.
1216/// The flag row keeps its first name, `community_at_rest_encrypted`.
1217const BACKFILL_VERSION: &str = "8";
1218
1219/// One-time backfill for an account whose Local Encryption predates some of what it now covers:
1220/// any swept column, message text, seed or bunker URL still in plaintext is sealed once, gated by a
1221/// per-account settings flag. Idempotent (the field discriminators skip already-wrapped rows), so a crash mid-pass
1222/// re-runs next login. No-op when encryption is off, the key vault is empty, or the flag is current.
1223/// Best-effort at the call site — a failure leaves the flag unset and retries, never blocks login.
1224pub fn backfill_at_rest() -> Result<(), String> {
1225    if !crate::state::is_encryption_enabled_fast() {
1226        return Ok(());
1227    }
1228    if crate::db::get_sql_setting("community_at_rest_encrypted".to_string())
1229        .ok()
1230        .flatten()
1231        .as_deref()
1232        == Some(BACKFILL_VERSION)
1233    {
1234        return Ok(());
1235    }
1236    let _change = crate::crypto::gate::key_change()?;
1237    let sealed = crate::state::ENCRYPTION_KEY.with_key(|key| -> Result<(), String> {
1238        let conn = crate::db::get_write_connection_guard_static()?;
1239        let tx = conn.unchecked_transaction().map_err(|e| format!("backfill tx: {e}"))?;
1240        // Setup used to seal the seed through the vault before encryption counted as on, which
1241        // stored it in plaintext; any plaintext seed or bunker URL is wrapped here too.
1242        prove_key_in_tx(&tx, key, true)?;
1243        encrypt_setting_in_tx(&tx, "seed", key, |v| v.contains(' '))?;
1244        encrypt_setting_in_tx(&tx, "bunker_url", key, |v| v.starts_with("bunker://"))?;
1245        encrypt_columns_in_tx(&tx, key)?;
1246        seal_plain_messages_in_tx(&tx, key)?;
1247        tx.execute(
1248            "INSERT OR REPLACE INTO settings (key, value) VALUES ('community_at_rest_encrypted', ?1)",
1249            [BACKFILL_VERSION],
1250        )
1251        .map_err(|e| format!("backfill flag: {e}"))?;
1252        tx.commit().map_err(|e| format!("backfill commit: {e}"))
1253    });
1254    // An empty vault is locked or not yet derived: retry on a later login.
1255    let Some(sealed) = sealed else { return Ok(()) };
1256    sealed?;
1257    crate::log_info!("[Encryption] Community at-rest backfill complete");
1258    Ok(())
1259}
1260
1261// ============================================================================
1262// Post-Migration Verification (In-Transaction)
1263// ============================================================================
1264
1265/// Verify all critical data is plaintext within a transaction.
1266/// Catches any bugs (double-encryption, missed fields) BEFORE committing.
1267fn verify_plaintext_state_in_tx(tx: &rusqlite::Transaction) -> Result<(), String> {
1268    // Verify pkey is plaintext (starts with "nsec")
1269    if let Ok(pkey) = tx.query_row::<String, _, _>(
1270        "SELECT value FROM settings WHERE key = 'pkey'", [], |row| row.get(0),
1271    ) {
1272        if !pkey.starts_with("nsec") {
1273            return Err(format!(
1274                "VERIFICATION FAILED: pkey is not plaintext after decryption (len={}, prefix={}). \
1275                 Aborting to protect your data — encryption status was NOT changed.",
1276                pkey.len(), &pkey[..pkey.len().min(8)]
1277            ));
1278        }
1279    }
1280
1281    // Verify seed is plaintext (contains spaces = BIP39 mnemonic)
1282    if let Ok(seed) = tx.query_row::<String, _, _>(
1283        "SELECT value FROM settings WHERE key = 'seed'", [], |row| row.get(0),
1284    ) {
1285        if !seed.contains(' ') {
1286            return Err(
1287                "VERIFICATION FAILED: seed is not plaintext after decryption. \
1288                 Aborting to protect your data — encryption status was NOT changed."
1289                    .to_string(),
1290            );
1291        }
1292    }
1293
1294    // Verify PIVX keys are raw (exactly 64 hex chars)
1295    let mut stmt = tx.prepare("SELECT id, length(privkey_encrypted) FROM pivx_promos")
1296        .map_err(|e| format!("Verification query failed: {}", e))?;
1297    let bad_keys: Vec<i64> = stmt
1298        .query_map([], |row| {
1299            let id: i64 = row.get(0)?;
1300            let len: i64 = row.get(1)?;
1301            Ok((id, len))
1302        })
1303        .map_err(|e| format!("Verification query failed: {}", e))?
1304        .filter_map(|r| r.ok())
1305        .filter(|(_, len)| *len > 64)
1306        .map(|(id, _)| id)
1307        .collect();
1308
1309    if !bad_keys.is_empty() {
1310        return Err(format!(
1311            "VERIFICATION FAILED: {} PIVX key(s) still encrypted (IDs: {:?}). \
1312             Aborting to protect your data — encryption status was NOT changed.",
1313            bad_keys.len(), bad_keys
1314        ));
1315    }
1316
1317    crate::log_info!("[Encryption] Verification passed: all data confirmed plaintext");
1318    Ok(())
1319}
1320
1321/// Verify all critical data is encrypted within a transaction.
1322/// Decrypts each value to confirm it round-trips back to valid plaintext.
1323fn verify_encrypted_state_in_tx(
1324    tx: &rusqlite::Transaction,
1325    key: &[u8; 32],
1326) -> Result<(), String> {
1327    // Verify pkey is encrypted and round-trips to nsec
1328    if let Ok(pkey) = tx.query_row::<String, _, _>(
1329        "SELECT value FROM settings WHERE key = 'pkey'", [], |row| row.get(0),
1330    ) {
1331        if pkey.starts_with("nsec") {
1332            return Err(
1333                "VERIFICATION FAILED: pkey is still plaintext after encryption. \
1334                 Aborting to protect your data — encryption status was NOT changed."
1335                    .to_string(),
1336            );
1337        }
1338        match decrypt_with_key(&pkey, key) {
1339            Ok(decrypted) if decrypted.starts_with("nsec") => {}
1340            Ok(decrypted) => {
1341                return Err(format!(
1342                    "VERIFICATION FAILED: pkey decrypts but not to nsec (len={}, prefix={}). \
1343                     Possible double-encryption. Aborting.",
1344                    decrypted.len(), &decrypted[..decrypted.len().min(6)]
1345                ));
1346            }
1347            Err(_) => {
1348                return Err(
1349                    "VERIFICATION FAILED: pkey cannot be decrypted with current key. Aborting."
1350                        .to_string(),
1351                );
1352            }
1353        }
1354    }
1355
1356    // Verify seed is encrypted and round-trips to BIP39
1357    if let Ok(seed) = tx.query_row::<String, _, _>(
1358        "SELECT value FROM settings WHERE key = 'seed'", [], |row| row.get(0),
1359    ) {
1360        if seed.contains(' ') {
1361            return Err(
1362                "VERIFICATION FAILED: seed is still plaintext after encryption. Aborting."
1363                    .to_string(),
1364            );
1365        }
1366        match decrypt_with_key(&seed, key) {
1367            Ok(decrypted) if decrypted.contains(' ') => {}
1368            Ok(_) => {
1369                return Err(
1370                    "VERIFICATION FAILED: seed decrypts but not to BIP39 mnemonic. \
1371                     Possible double-encryption. Aborting."
1372                        .to_string(),
1373                );
1374            }
1375            Err(_) => {
1376                return Err(
1377                    "VERIFICATION FAILED: seed cannot be decrypted with current key. Aborting."
1378                        .to_string(),
1379                );
1380            }
1381        }
1382    }
1383
1384    crate::log_info!("[Encryption] Verification passed: all data confirmed encrypted and round-trips correctly");
1385    Ok(())
1386}
1387
1388/// Does `key` provably decrypt this account's material? Checks whichever
1389/// anchor the account shape has: the pkey ciphertext (local/bunker) or the
1390/// canary (keyless NIP-55). No anchor (plaintext pkey, no canary) = nothing to
1391/// contradict, so accept — matching every other credential check in the app.
1392pub fn key_matches_account(key: &[u8; 32]) -> bool {
1393    let Ok(conn) = crate::db::get_db_connection_guard_static() else {
1394        return false;
1395    };
1396    let pkey: Option<String> = conn
1397        .query_row("SELECT value FROM settings WHERE key = 'pkey'", [], |r| r.get(0))
1398        .ok();
1399    if let Some(p) = pkey {
1400        if !p.starts_with("nsec") {
1401            return matches!(decrypt_with_key(&p, key), Ok(d) if d.starts_with("nsec"));
1402        }
1403    }
1404    let canary: Option<String> = conn
1405        .query_row("SELECT value FROM settings WHERE key = 'nip55_pin_check'", [], |r| r.get(0))
1406        .ok();
1407    if let Some(c) = canary {
1408        return matches!(
1409            decrypt_with_key(&c, key),
1410            Ok(d) if d == NIP55_PIN_CANARY
1411        );
1412    }
1413    true
1414}
1415
1416/// Perform the entire re-key operation inside a single SQLite transaction.
1417///
1418/// If ANY step fails (or the app crashes), the transaction auto-rolls back
1419/// and the database remains entirely on the old key. This prevents the
1420/// catastrophic "split-key" state where some data uses the old key and
1421/// some uses the new key (audit C1).
1422///
1423/// Memory-efficient: collects only event IDs upfront (small strings),
1424/// then processes one event at a time within the transaction.
1425pub fn rekey(
1426    old_key: &[u8; 32],
1427    new_key: &[u8; 32],
1428    new_kdf: &crate::crypto::Kdf,
1429    security_type: &str,
1430    biometric_wrap: Option<&str>,
1431    progress: &dyn Fn(MigrationProgress),
1432) -> Result<(), String> {
1433    let wrap = match biometric_wrap {
1434        Some(w) => Wrap::Set(w),
1435        None => Wrap::Drop,
1436    };
1437    rekey_with(old_key, new_key, new_kdf, Some(security_type), wrap, Upgrade::No, progress).map(|_| ())
1438}
1439
1440/// Move a legacy-salted account onto its own salt: the same transaction as [`rekey`], from the
1441/// key the unlock just proved, keeping the account's mode. The key must prove against something
1442/// the account holds, since a wrong one would be locked in under the new salt. The space the old
1443/// ciphertext freed is zeroed as it goes, the WAL is emptied after, and the next maintenance pass
1444/// vacuums the rest. `Ok(false)` when another unlock got there first.
1445pub fn upgrade_legacy_derivation(
1446    legacy_key: &[u8; 32],
1447    new_key: &[u8; 32],
1448    new_kdf: &crate::crypto::Kdf,
1449    progress: &dyn Fn(MigrationProgress),
1450) -> Result<bool, String> {
1451    if new_kdf.is_legacy() {
1452        return Err("an upgrade needs a salted derivation".to_string());
1453    }
1454    // Upgrades run only for typed credentials, so any wrap left here holds a key from an older
1455    // layout and goes with the legacy key.
1456    rekey_with(legacy_key, new_key, new_kdf, None, Wrap::Drop, Upgrade::Legacy, progress)
1457}
1458
1459/// What a re-key does with the biometric wrap: it always moves with the key it protects.
1460enum Wrap<'a> {
1461    /// The new key's wrap (switching TO biometric).
1462    Set(&'a str),
1463    /// No wrap (a credential change, switching AWAY from biometric, or an upgrade).
1464    Drop,
1465}
1466
1467/// Whether a re-key is the one-time move off the legacy salt, which proves its key positively,
1468/// re-checks under the key change that nothing moved the account first, and wipes as it goes.
1469#[derive(Clone, Copy, PartialEq)]
1470enum Upgrade {
1471    No,
1472    Legacy,
1473}
1474
1475fn rekey_with(
1476    old_key: &[u8; 32],
1477    new_key: &[u8; 32],
1478    new_kdf: &crate::crypto::Kdf,
1479    security_type: Option<&str>,
1480    wrap: Wrap<'_>,
1481    upgrade: Upgrade,
1482    progress: &dyn Fn(MigrationProgress),
1483) -> Result<bool, String> {
1484    if !same_key(old_key, new_key) && new_kdf.is_legacy() {
1485        return Err("A new key needs its own salt".to_string());
1486    }
1487    // Held from before the transaction until the vault and the flag show the result, so no
1488    // write sealed under the outgoing key can land after it.
1489    let _change = crate::crypto::gate::key_change()?;
1490    if !crate::db::writes_to_live_account() {
1491        return Err("The account changed before its key could".to_string());
1492    }
1493    if upgrade == Upgrade::Legacy {
1494        // A second unlock may have moved the account while this one derived.
1495        let vault_holds_legacy = crate::state::ENCRYPTION_KEY.with_key(|k| same_key(k, old_key)).unwrap_or(false);
1496        if !crate::crypto::Kdf::of_account()?.is_legacy() || !vault_holds_legacy {
1497            return Ok(false);
1498        }
1499    }
1500    let mut conn = crate::db::get_write_connection_guard_static()?;
1501    let wipe = upgrade == Upgrade::Legacy;
1502    let secure_delete_before: i64 = if wipe {
1503        let before = conn.query_row("PRAGMA secure_delete", [], |r| r.get(0)).map_err(|e| format!("secure_delete: {e}"))?;
1504        conn.execute_batch("PRAGMA secure_delete = ON;").map_err(|e| format!("secure_delete: {e}"))?;
1505        before
1506    } else {
1507        0
1508    };
1509    let result = rekey_tx(&mut conn, old_key, new_key, new_kdf, security_type, wrap, upgrade, progress);
1510    if wipe {
1511        // Best-effort: the commit is what matters, and the next VACUUM catches what this misses.
1512        let _ = conn.execute_batch(&format!("PRAGMA secure_delete = {secure_delete_before};"));
1513        let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");
1514    }
1515    result.map(|_| true)
1516}
1517
1518#[allow(clippy::too_many_arguments)]
1519fn rekey_tx(
1520    conn: &mut rusqlite::Connection,
1521    old_key: &[u8; 32],
1522    new_key: &[u8; 32],
1523    new_kdf: &crate::crypto::Kdf,
1524    security_type: Option<&str>,
1525    wrap: Wrap<'_>,
1526    upgrade: Upgrade,
1527    progress: &dyn Fn(MigrationProgress),
1528) -> Result<(), String> {
1529    let (require_anchor, wipe) = (upgrade == Upgrade::Legacy, upgrade == Upgrade::Legacy);
1530    // Begin transaction — auto-rolls back on drop if not committed
1531    let tx = conn.transaction()
1532        .map_err(|e| format!("Failed to begin transaction: {}", e))?;
1533
1534    // Set migration state inside the transaction — rolls back with everything else on crash
1535    tx.execute(
1536        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', 'rekeying')",
1537        [],
1538    ).map_err(|e| format!("Failed to set migration_state: {}", e))?;
1539
1540    prove_key_in_tx(&tx, old_key, require_anchor)?;
1541    // The same key on both sides changes only the mode rows: re-sealing a store to itself
1542    // gains nothing and would hold the transaction for a full sweep.
1543    if !same_key(old_key, new_key) {
1544        rekey_listed_in_tx(&tx, old_key, new_key, progress)?;
1545        sweep_residue_in_tx(&tx, old_key, Some(new_key))?;
1546        verify_encrypted_state_in_tx(&tx, new_key)?;
1547    }
1548
1549    // 5. Update metadata within the same transaction: the derivation lands with the data
1550    // sealed under it, so a crash can never leave one without the other.
1551    super::settings::write_kdf_in_tx(&tx, new_kdf.descriptor().as_deref())?;
1552    if let Some(security_type) = security_type {
1553        tx.execute(
1554            "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
1555            rusqlite::params![security_type],
1556        ).map_err(|e| format!("Failed to update security_type: {}", e))?;
1557    }
1558
1559    // The wrap always moves with the key it protects, inside this transaction, so a crash can
1560    // never leave a wrap that holds a key the store no longer uses.
1561    match wrap {
1562        Wrap::Set(w) => {
1563            tx.execute(
1564                "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
1565                rusqlite::params![w],
1566            ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
1567        }
1568        Wrap::Drop => {
1569            tx.execute(
1570                "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
1571                [],
1572            ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
1573        }
1574    }
1575    if wipe {
1576        // The free pages still hold the old ciphertext; the post-sync maintenance pass
1577        // vacuums once this mark is gone.
1578        tx.execute("DELETE FROM settings WHERE key = 'last_vacuum'", [])
1579            .map_err(|e| format!("Failed to schedule vacuum: {}", e))?;
1580    }
1581
1582    tx.execute(
1583        "INSERT OR REPLACE INTO settings (key, value) VALUES ('migration_state', '')",
1584        [],
1585    ).map_err(|e| format!("Failed to clear migration_state: {}", e))?;
1586
1587    // Other connections see the old rows until COMMIT and the new ones after, and a read can
1588    // straddle it. The vault takes the new key first and the old one stays openable a moment,
1589    // so every read opens whichever it got.
1590    let moving = !same_key(old_key, new_key);
1591    if moving {
1592        crate::crypto::hold_previous_key(old_key);
1593        crate::state::ENCRYPTION_KEY.set(*new_key, &[]);
1594    }
1595
1596    // 6. COMMIT — the atomic point. Everything succeeds or nothing does.
1597    if let Err(e) = tx.commit() {
1598        // A commit that reports failure may still have reached disk; the recorded derivation
1599        // says which key the store is under.
1600        let landed = crate::crypto::Kdf::of_account().is_ok_and(|k| k == *new_kdf) && !new_kdf.is_legacy();
1601        if moving && !landed {
1602            crate::state::ENCRYPTION_KEY.set(*old_key, &[]);
1603            crate::crypto::forget_previous_key();
1604        } else if moving {
1605            crate::crypto::forget_previous_key_later();
1606        }
1607        return Err(format!("Failed to commit re-key transaction: {}", e));
1608    }
1609    if moving {
1610        crate::crypto::forget_previous_key_later();
1611    }
1612    Ok(())
1613}
1614
1615/// After a verified unlock with `password`, whose legacy-salt key `legacy_key` just proved
1616/// itself, move the account onto its own salt. `Ok(false)` when there is nothing to move: an
1617/// account already salted, a plaintext store, a biometric one (its key never came from a typed
1618/// credential), one with nothing to prove the key against, or one whose last attempt failed less
1619/// than a day ago. Any failure leaves the account exactly as it was.
1620pub async fn upgrade_after_unlock(password: &str, legacy_key: &[u8; 32]) -> Result<bool, String> {
1621    const RETRY_AFTER_SECS: u64 = 24 * 60 * 60;
1622    if !crate::crypto::Kdf::of_account()?.is_legacy() || !crate::state::is_encryption_enabled_fast() {
1623        return Ok(false);
1624    }
1625    if crate::db::get_sql_setting("security_type".to_string())?.as_deref() == Some("biometric") {
1626        return Ok(false);
1627    }
1628    let now = crate::clock::now_secs();
1629    let last_try: u64 = crate::db::get_sql_setting("kdf_upgrade_attempt".to_string())?.and_then(|v| v.parse().ok()).unwrap_or(0);
1630    if now.saturating_sub(last_try) < RETRY_AFTER_SECS {
1631        return Ok(false);
1632    }
1633    // Checked before the slow derivation: a store with nothing to prove against never upgrades.
1634    if !key_proves_positively(legacy_key)? {
1635        return Ok(false);
1636    }
1637
1638    // The unlock screen says why this first unlock takes longer.
1639    crate::emit_event("encryption_upgrading", &MigrationProgress { total: 0, completed: 0, phase: "deriving".to_string() });
1640    let new_kdf = crate::crypto::Kdf::fresh();
1641    let new_key = zeroize::Zeroizing::new(crate::crypto::derive_key(password, &new_kdf).await);
1642    let progress = |p: MigrationProgress| crate::emit_event("encryption_upgrading", &p);
1643    match upgrade_legacy_derivation(legacy_key, &new_key, &new_kdf, &progress) {
1644        Ok(moved) => {
1645            if moved {
1646                crate::log_info!("[Encryption] Moved this account onto its own key derivation salt");
1647            }
1648            Ok(moved)
1649        }
1650        Err(e) => {
1651            let _ = crate::db::set_sql_setting("kdf_upgrade_attempt".to_string(), now.to_string());
1652            Err(e)
1653        }
1654    }
1655}
1656
1657/// Whether `key` opens a positive anchor in this store (the pkey, the canary, or sampled
1658/// ciphertext), read-only.
1659fn key_proves_positively(key: &[u8; 32]) -> Result<bool, String> {
1660    let mut conn = crate::db::get_db_connection_guard_static()?;
1661    let tx = conn.transaction().map_err(|e| format!("key proof: {e}"))?;
1662    Ok(prove_key_in_tx(&tx, key, true).is_ok())
1663}
1664
1665/// An encrypted account was asked for a gated action without the user's PIN or password.
1666pub const CREDENTIAL_REQUIRED: &str = "CREDENTIAL_REQUIRED";
1667/// The PIN or password typed does not open this account.
1668pub const CREDENTIAL_INCORRECT: &str = "CREDENTIAL_INCORRECT";
1669
1670/// Too many wrong credentials in a row: `CREDENTIAL_LOCKED:<seconds until the next try>`.
1671pub const CREDENTIAL_LOCKED: &str = "CREDENTIAL_LOCKED";
1672/// Wrong credentials allowed before each further miss doubles the wait.
1673const FREE_TRIES: u32 = 5;
1674/// The longest wait a miss can earn.
1675const MAX_WAIT_SECS: u64 = 15 * 60;
1676/// One proof at a time, so parallel guesses can't all pass the wait before any miss is counted.
1677static PROVING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
1678
1679/// The account's key, derived from what the user typed and proven against the store. Gated actions
1680/// run on this rather than the session's vault, so a caller holding only the session gets nothing.
1681/// Misses past the first few wait longer each time, across restarts, so a script that can call
1682/// this can't walk the PIN space.
1683pub async fn prove_credential(credential: &str) -> Result<zeroize::Zeroizing<[u8; 32]>, String> {
1684    let _one_at_a_time = PROVING.lock().await;
1685    let now = crate::clock::now_secs();
1686    let read = |key: &str| crate::db::get_sql_setting(key.to_string()).ok().flatten().and_then(|v| v.parse::<u64>().ok());
1687    if let Some(retry_at) = read("credential_retry_at").filter(|&t| t > now) {
1688        // A wait longer than any miss earns means the clock went back; count it from now instead.
1689        let wait = if retry_at - now > MAX_WAIT_SECS {
1690            let _ = crate::db::set_sql_setting("credential_retry_at".to_string(), (now + MAX_WAIT_SECS).to_string());
1691            MAX_WAIT_SECS
1692        } else {
1693            retry_at - now
1694        };
1695        return Err(format!("{CREDENTIAL_LOCKED}:{wait}"));
1696    }
1697    let kdf = crate::crypto::Kdf::of_account()?;
1698    let key = zeroize::Zeroizing::new(crate::crypto::derive_key(credential, &kdf).await);
1699    if let Err(e) = prove_key(&key) {
1700        if e == CREDENTIAL_INCORRECT {
1701            let failures = record_miss()?;
1702            if failures >= FREE_TRIES {
1703                let wait = (30u64 << (failures - FREE_TRIES).min(5)).min(MAX_WAIT_SECS);
1704                let _ = crate::db::set_sql_setting("credential_retry_at".to_string(), (now + wait).to_string());
1705            }
1706        }
1707        return Err(e);
1708    }
1709    if read("credential_failures").is_some() {
1710        let _ = crate::db::remove_setting("credential_failures");
1711        let _ = crate::db::remove_setting("credential_retry_at");
1712    }
1713    Ok(key)
1714}
1715
1716/// Count one miss in a single statement and return the running total.
1717fn record_miss() -> Result<u32, String> {
1718    let conn = crate::db::get_write_connection_guard_static()?;
1719    conn.query_row(
1720        "INSERT INTO settings (key, value) VALUES ('credential_failures', '1')
1721         ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)
1722         RETURNING CAST(value AS INTEGER)",
1723        [],
1724        |r| r.get::<_, i64>(0),
1725    )
1726    .map(|n| n.clamp(0, u32::MAX as i64) as u32)
1727    .map_err(|e| format!("count credential miss: {e}"))
1728}
1729
1730/// `Ok` only when `key` opens a positive anchor in this store.
1731pub fn prove_key(key: &[u8; 32]) -> Result<(), String> {
1732    if key_proves_positively(key)? { Ok(()) } else { Err(CREDENTIAL_INCORRECT.to_string()) }
1733}
1734
1735/// The identity key and seed phrase as stored, opened under `key`: a proven key for an encrypted
1736/// store, `None` for a plaintext one.
1737pub fn open_identity_secrets(
1738    key: Option<&[u8; 32]>,
1739) -> Result<(zeroize::Zeroizing<String>, Option<zeroize::Zeroizing<String>>), String> {
1740    use rusqlite::OptionalExtension;
1741    let conn = crate::db::get_db_connection_guard_static()?;
1742    let read = |name: &str| -> Result<Option<String>, String> {
1743        conn.query_row("SELECT value FROM settings WHERE key = ?1", [name], |r| r.get::<_, String>(0))
1744            .optional()
1745            .map_err(|e| format!("read {name}: {e}"))
1746    };
1747    let open = |stored: String| -> Result<zeroize::Zeroizing<String>, String> {
1748        let stored = zeroize::Zeroizing::new(stored);
1749        match key {
1750            Some(k) => decrypt_with_key(&stored, k).map(zeroize::Zeroizing::new).map_err(|_| CREDENTIAL_INCORRECT.to_string()),
1751            None => Ok(stored),
1752        }
1753    };
1754    let nsec = open(read("pkey")?.ok_or("No private key is stored for this account")?)?;
1755    if !nsec.starts_with("nsec1") {
1756        return Err("The stored private key is unreadable".to_string());
1757    }
1758    let seed = match (read("seed")?, key) {
1759        (None, _) => None,
1760        (Some(stored), None) => Some(zeroize::Zeroizing::new(stored)),
1761        (Some(stored), Some(k)) => match decrypt_with_key(&stored, k) {
1762            Ok(plain) => Some(zeroize::Zeroizing::new(plain)),
1763            // A seed written before encryption covered it is still a phrase; anything else
1764            // unreadable stays behind rather than failing the whole export.
1765            Err(_) if stored.contains(' ') => Some(zeroize::Zeroizing::new(stored)),
1766            Err(_) => {
1767                crate::log_warn!("[Encryption] The stored seed phrase doesn't open; leaving it out");
1768                None
1769            }
1770        },
1771    };
1772    Ok((nsec, seed))
1773}
1774
1775/// Rebuild the database file so nothing an upgrade replaced survives in its free pages. For hosts
1776/// with no maintenance pass of their own; slow on a large store.
1777pub fn vacuum_now() -> Result<(), String> {
1778    let conn = crate::db::get_write_connection_guard_static()?;
1779    conn.execute_batch("VACUUM; PRAGMA wal_checkpoint(TRUNCATE);").map_err(|e| format!("vacuum: {e}"))
1780}
1781
1782/// Everything [`rekey`] moves by list: message content, the sealed settings, PIVX keys and
1783/// every `SWEEP` column, from `old_key` to `new_key` inside the caller's transaction.
1784pub(crate) fn rekey_listed_in_tx(
1785    tx: &rusqlite::Transaction,
1786    old_key: &[u8; 32],
1787    new_key: &[u8; 32],
1788    progress: &dyn Fn(MigrationProgress),
1789) -> Result<(), String> {
1790    // 1. Collect all encrypted event IDs (memory-efficient: just ID strings)
1791    let all_ids: Vec<String> = {
1792        let mut stmt = tx.prepare(
1793            r#"SELECT id FROM events
1794               WHERE kind IN (?1, ?2, ?3, ?4)
1795               AND length(content) >= 56
1796               AND content NOT GLOB '*[^0-9a-f]*'"#,
1797        ).map_err(|e| format!("Failed to prepare ID query: {}", e))?;
1798
1799        let rows = stmt.query_map(
1800            rusqlite::params![
1801                event_kind::CHAT_MESSAGE as i32,
1802                event_kind::PRIVATE_DIRECT_MESSAGE as i32,
1803                event_kind::MESSAGE_EDIT as i32,
1804                event_kind::FILE_ATTACHMENT as i32,
1805            ],
1806            |row| row.get::<_, String>(0),
1807        ).map_err(|e| format!("Failed to query IDs: {}", e))?;
1808
1809        rows.filter_map(|r| r.ok()).collect()
1810    };
1811
1812    let total = all_ids.len();
1813    let mut completed = 0;
1814    let mut last_emitted_percent: i32 = -1;
1815
1816    // 2. Re-key each event (one at a time, memory-efficient)
1817    for id in &all_ids {
1818        let content: Option<String> = tx.query_row(
1819            "SELECT content FROM events WHERE id = ?1",
1820            rusqlite::params![id],
1821            |row| row.get(0),
1822        ).ok();
1823
1824        if let Some(content) = content {
1825            match decrypt_with_key(&content, old_key) {
1826                Ok(plaintext) => {
1827                    let re_encrypted = encrypt_with_key(&plaintext, new_key);
1828                    tx.execute(
1829                        "UPDATE events SET content = ?1 WHERE id = ?2",
1830                        rusqlite::params![re_encrypted, id],
1831                    ).map_err(|e| format!("Failed to update event: {}", e))?;
1832                }
1833                Err(_) => {
1834                    // Content looks encrypted but can't be decrypted — skip
1835                    crate::log_warn!("[Rekey] Skipping event {} - decrypt failed", id);
1836                }
1837            }
1838        }
1839
1840        completed += 1;
1841        let current_percent = if total > 0 {
1842            ((completed as f64 / total as f64) * 100.0) as i32
1843        } else {
1844            100
1845        };
1846
1847        if current_percent >= last_emitted_percent + 5 {
1848            last_emitted_percent = current_percent;
1849            progress(MigrationProgress {
1850                total,
1851                completed,
1852                phase: "rekeying".to_string(),
1853            });
1854        }
1855    }
1856
1857    // 3. Re-key settings within the same transaction
1858    progress(MigrationProgress {
1859        total,
1860        completed,
1861        phase: "finalizing".to_string(),
1862    });
1863
1864    rekey_setting_in_tx(tx, "pkey", old_key, new_key)?;
1865    rekey_setting_in_tx(tx, "seed", old_key, new_key)?;
1866    // A keyless (NIP-55) account has no pkey, so the canary is its ONLY
1867    // wrong-credential detector; a bunker account cannot log in without its
1868    // url. Both are key-derived, so both move with the key or the account is
1869    // locked out at the NEXT boot rather than at the failing operation.
1870    rekey_setting_in_tx(tx, "nip55_pin_check", old_key, new_key)?;
1871    rekey_setting_in_tx(tx, "bunker_url", old_key, new_key)?;
1872    rekey_pivx_in_tx(tx, old_key, new_key)?;
1873    rekey_columns_in_tx(tx, old_key, new_key)?;
1874
1875    Ok(())
1876}
1877
1878fn same_key(a: &[u8; 32], b: &[u8; 32]) -> bool {
1879    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
1880}
1881
1882/// Prove `key` opens this store before a sweep writes under it. The pkey or the canary decides
1883/// when present; otherwise the newest message ciphertexts and community key blobs must include
1884/// one that opens. `require_anchor` also refuses a store with nothing to prove against: an
1885/// enable-direction pass wraps plaintext under whatever key it is handed.
1886fn prove_key_in_tx(tx: &rusqlite::Transaction, key: &[u8; 32], require_anchor: bool) -> Result<(), String> {
1887    use rusqlite::OptionalExtension;
1888    const WRONG: &str = "This key does not open the account's encrypted data; nothing was changed";
1889    let setting = |name: &str| -> Result<Option<String>, String> {
1890        tx.query_row("SELECT value FROM settings WHERE key = ?1", [name], |r| r.get::<_, String>(0))
1891            .optional()
1892            .map_err(|e| format!("read {name}: {e}"))
1893    };
1894    if let Some(pkey) = setting("pkey")? {
1895        if !pkey.starts_with("nsec") {
1896            let opened = decrypt_with_key(&pkey, key).map(zeroize::Zeroizing::new);
1897            return match opened {
1898                Ok(nsec) if nsec.starts_with("nsec") => Ok(()),
1899                _ => Err(WRONG.to_string()),
1900            };
1901        }
1902    }
1903    if let Some(canary) = setting("nip55_pin_check")? {
1904        return match decrypt_with_key(&canary, key) {
1905            Ok(plain) if plain == NIP55_PIN_CANARY => Ok(()),
1906            _ => Err(WRONG.to_string()),
1907        };
1908    }
1909    let samples = [
1910        "SELECT content FROM events WHERE kind IN (?1, ?2, ?3, ?4) AND length(content) >= 56
1911           AND content NOT GLOB '*[^0-9a-f]*' ORDER BY created_at DESC LIMIT 256",
1912        "SELECT server_root_key FROM communities WHERE length(server_root_key) > 32 LIMIT 256",
1913        "SELECT channel_key FROM community_channels WHERE length(channel_key) > 32 LIMIT 256",
1914        "SELECT key FROM community_epoch_keys WHERE length(key) > 32 LIMIT 256",
1915    ];
1916    let kinds = [
1917        event_kind::CHAT_MESSAGE as i64,
1918        event_kind::PRIVATE_DIRECT_MESSAGE as i64,
1919        event_kind::MESSAGE_EDIT as i64,
1920        event_kind::FILE_ATTACHMENT as i64,
1921    ];
1922    let cipher = crate::crypto::chachapoly::ChaCha20Poly1305::new(key);
1923    let mut scratch = Vec::new();
1924    let mut seen = false;
1925    for sql in samples {
1926        let mut stmt = tx.prepare(sql).map_err(|e| format!("key proof: {e}"))?;
1927        let params: &[i64] = if sql.contains("?1") { &kinds } else { &[] };
1928        let mut rows = stmt.query(rusqlite::params_from_iter(params)).map_err(|e| format!("key proof: {e}"))?;
1929        while let Some(row) = rows.next().map_err(|e| format!("key proof: {e}"))? {
1930            seen = true;
1931            if opens_under(row.get_ref(0).map_err(|e| format!("key proof: {e}"))?, &cipher, &mut scratch) {
1932                return Ok(());
1933            }
1934        }
1935    }
1936    match (seen, require_anchor) {
1937        (true, _) => Err(WRONG.to_string()),
1938        (false, true) => Err("Nothing here can confirm the key, so the store was left as it is".to_string()),
1939        (false, false) => Ok(()),
1940    }
1941}
1942
1943/// Re-key a single settings value within a transaction.
1944fn rekey_setting_in_tx(
1945    tx: &rusqlite::Transaction,
1946    key: &str,
1947    old_key: &[u8; 32],
1948    new_key: &[u8; 32],
1949) -> Result<(), String> {
1950
1951    let val: Option<String> = tx.query_row(
1952        "SELECT value FROM settings WHERE key = ?1",
1953        rusqlite::params![key],
1954        |row| row.get(0),
1955    ).ok();
1956
1957    if let Some(encrypted_val) = val {
1958        // A row that isn't ciphertext under `old_key` and isn't hex at all was
1959        // written plaintext (e.g. bunker_url stored before encryption was
1960        // enabled) — wrap it under the new key rather than failing the rekey.
1961        let looks_encrypted = encrypted_val.len() >= 56
1962            && encrypted_val.bytes().all(|b| b.is_ascii_hexdigit());
1963        let plaintext = match decrypt_with_key(&encrypted_val, old_key) {
1964            Ok(p) => p,
1965            Err(_) if !looks_encrypted => encrypted_val.clone(),
1966            Err(_) => return Err(format!("Failed to decrypt setting '{}'", key)),
1967        };
1968
1969        let re_encrypted = encrypt_with_key(&plaintext, new_key);
1970
1971        tx.execute(
1972            "UPDATE settings SET value = ?1 WHERE key = ?2",
1973            rusqlite::params![re_encrypted, key],
1974        ).map_err(|e| format!("Failed to update setting '{}': {}", key, e))?;
1975    }
1976
1977    Ok(())
1978}
1979
1980/// Re-key all PIVX promo private keys within a transaction.
1981fn rekey_pivx_in_tx(
1982    tx: &rusqlite::Transaction,
1983    old_key: &[u8; 32],
1984    new_key: &[u8; 32],
1985) -> Result<(), String> {
1986
1987    let keys: Vec<(i64, String)> = {
1988        let mut stmt = tx.prepare("SELECT id, privkey_encrypted FROM pivx_promos")
1989            .map_err(|e| format!("Failed to prepare PIVX query: {}", e))?;
1990        let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)))
1991            .map_err(|e| format!("Failed to query PIVX promos: {}", e))?;
1992        rows.filter_map(|r| r.ok()).collect()
1993    };
1994
1995    for (id, key_val) in keys {
1996        // Only re-key if longer than a raw key (64 chars) — meaning it's encrypted
1997        if key_val.len() > 64 {
1998            let decrypted = decrypt_with_key(&key_val, old_key)
1999                .map_err(|_| format!("Failed to decrypt PIVX key {}", id))?;
2000            let re_encrypted = encrypt_with_key(&decrypted, new_key);
2001
2002            tx.execute(
2003                "UPDATE pivx_promos SET privkey_encrypted = ?1 WHERE id = ?2",
2004                rusqlite::params![re_encrypted, id],
2005            ).map_err(|e| format!("Failed to update PIVX key: {}", e))?;
2006        }
2007    }
2008
2009    Ok(())
2010}
2011
2012#[cfg(test)]
2013mod rekey_setting_tests {
2014    use super::*;
2015    const OLD: [u8; 32] = [3u8; 32];
2016    const NEW: [u8; 32] = [5u8; 32];
2017
2018    fn conn() -> rusqlite::Connection {
2019        let c = rusqlite::Connection::open_in_memory().unwrap();
2020        c.execute_batch("CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);").unwrap();
2021        c
2022    }
2023    fn put(c: &rusqlite::Connection, k: &str, v: &str) {
2024        c.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
2025            rusqlite::params![k, v]).unwrap();
2026    }
2027    fn get(c: &rusqlite::Connection, k: &str) -> String {
2028        c.query_row("SELECT value FROM settings WHERE key = ?1", rusqlite::params![k], |r| r.get(0)).unwrap()
2029    }
2030
2031    /// The bug that shipped: a keyless account's canary stayed under the dead
2032    /// key, so the NEXT cold boot rejected the correct credential.
2033    #[test]
2034    fn canary_survives_rekey() {
2035        let mut c = conn();
2036        put(&c, "nip55_pin_check", &encrypt_with_key(NIP55_PIN_CANARY, &OLD));
2037        let tx = c.transaction().unwrap();
2038        rekey_setting_in_tx(&tx, "nip55_pin_check", &OLD, &NEW).unwrap();
2039        tx.commit().unwrap();
2040        assert_eq!(
2041            decrypt_with_key(&get(&c, "nip55_pin_check"), &NEW).unwrap(),
2042            NIP55_PIN_CANARY
2043        );
2044    }
2045
2046    /// Same shape for bunker accounts: an un-rekeyed url = permanent login failure.
2047    #[test]
2048    fn bunker_url_survives_rekey() {
2049        let mut c = conn();
2050        let url = "bunker://abc?relay=wss://relay.example";
2051        put(&c, "bunker_url", &encrypt_with_key(url, &OLD));
2052        let tx = c.transaction().unwrap();
2053        rekey_setting_in_tx(&tx, "bunker_url", &OLD, &NEW).unwrap();
2054        tx.commit().unwrap();
2055        assert_eq!(decrypt_with_key(&get(&c, "bunker_url"), &NEW).unwrap(), url);
2056    }
2057
2058    /// A row written before encryption was enabled is plaintext: wrap it under
2059    /// the new key rather than failing the whole migration.
2060    #[test]
2061    fn plaintext_row_is_adopted_not_fatal() {
2062        let mut c = conn();
2063        let url = "bunker://plain?relay=wss://r.example";
2064        put(&c, "bunker_url", url);
2065        let tx = c.transaction().unwrap();
2066        rekey_setting_in_tx(&tx, "bunker_url", &OLD, &NEW).unwrap();
2067        tx.commit().unwrap();
2068        assert_eq!(decrypt_with_key(&get(&c, "bunker_url"), &NEW).unwrap(), url);
2069    }
2070
2071    /// Ciphertext that does NOT belong to `old_key` must abort the rekey — the
2072    /// alternative is committing a value nobody can ever decrypt.
2073    #[test]
2074    fn wrong_old_key_aborts() {
2075        let mut c = conn();
2076        put(&c, "pkey", &encrypt_with_key("nsec1example", &[9u8; 32]));
2077        let tx = c.transaction().unwrap();
2078        assert!(rekey_setting_in_tx(&tx, "pkey", &OLD, &NEW).is_err());
2079    }
2080
2081    /// Absent rows are a no-op (accounts legitimately lack pkey, seed, canary).
2082    #[test]
2083    fn missing_row_is_noop() {
2084        let mut c = conn();
2085        let tx = c.transaction().unwrap();
2086        rekey_setting_in_tx(&tx, "nip55_pin_check", &OLD, &NEW).unwrap();
2087        tx.commit().unwrap();
2088        assert_eq!(
2089            c.query_row("SELECT count(*) FROM settings", [], |r| r.get::<_, i64>(0)).unwrap(), 0
2090        );
2091    }
2092}