Skip to main content

vector_core/db/
settings.rs

1//! Settings key-value store operations.
2
3/// Get a SQL setting by key.
4pub fn get_sql_setting(key: String) -> Result<Option<String>, String> {
5    let conn = super::get_db_connection_guard_static()?;
6    let result: Option<String> = conn.query_row(
7        "SELECT value FROM settings WHERE key = ?1",
8        rusqlite::params![key],
9        |row| row.get(0),
10    ).ok();
11    Ok(result)
12}
13
14/// A setting where a failed read is an error, not an absent row: for rows whose absence means
15/// something, like the key derivation's.
16pub fn get_sql_setting_strict(key: &str) -> Result<Option<String>, String> {
17    use rusqlite::OptionalExtension;
18    let conn = super::get_db_connection_guard_static()?;
19    conn.query_row("SELECT value FROM settings WHERE key = ?1", rusqlite::params![key], |row| row.get(0))
20        .optional()
21        .map_err(|e| format!("read {key}: {e}"))
22}
23
24/// Rows only the key and migration code may change: a write or delete through the generic
25/// settings commands could lock an account out of its own data.
26pub const PROTECTED_SETTINGS: &[&str] = &[
27    "pkey", "seed", "bunker_url", "nip55_pin_check", "biometric_wrapped_key", "kdf",
28    "encryption_enabled", "security_type", "signer_type", "migration_state", "community_at_rest_encrypted",
29    "credential_failures", "credential_retry_at",
30    crate::transport::prefs::KEY_TRANSPORT, crate::transport::prefs::KEY_LEGACY_TOR,
31    crate::transport::prefs::KEY_I2P_CONFIG, crate::transport::prefs::KEY_ALIASES,
32];
33
34/// Rows the generic settings commands never hand out: sealed secrets and their checks. The I2P
35/// config can hold a SAM password.
36pub const SECRET_SETTINGS: &[&str] = &[
37    "pkey", "seed", "bunker_url", "nip55_pin_check", "biometric_wrapped_key",
38    crate::transport::prefs::KEY_I2P_CONFIG,
39];
40
41/// Set a SQL setting key-value pair.
42pub fn set_sql_setting(key: String, value: String) -> Result<(), String> {
43    let conn = super::get_write_connection_guard_static()?;
44    conn.execute(
45        "INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)",
46        rusqlite::params![key, value],
47    ).map_err(|e| format!("Failed to set setting: {}", e))?;
48    Ok(())
49}
50
51/// Monotonically advance a numeric setting in ONE statement — the stored
52/// value only ever grows. For reconcile cursors and similar floors, where a
53/// read-modify-write window would let a stale or concurrent writer regress
54/// the value.
55pub fn advance_u64_setting(key: String, value: u64) -> Result<(), String> {
56    let conn = super::get_write_connection_guard_static()?;
57    conn.execute(
58        "INSERT INTO settings (key, value) VALUES (?1, ?2)
59         ON CONFLICT(key) DO UPDATE SET value = excluded.value
60         WHERE CAST(excluded.value AS INTEGER) > CAST(value AS INTEGER)",
61        rusqlite::params![key, value.to_string()],
62    ).map_err(|e| format!("Failed to advance setting: {}", e))?;
63    Ok(())
64}
65
66/// Remove a setting by key.
67pub fn remove_setting(key: &str) -> Result<(), String> {
68    let conn = super::get_write_connection_guard_static()?;
69    conn.execute("DELETE FROM settings WHERE key = ?1", rusqlite::params![key])
70        .map_err(|e| format!("Failed to remove setting: {}", e))?;
71    Ok(())
72}
73
74/// Get the stored private key (bech32 nsec).
75pub fn get_pkey() -> Result<Option<String>, String> {
76    let conn = super::get_db_connection_guard_static()?;
77    Ok(conn.query_row(
78        "SELECT value FROM settings WHERE key = 'pkey'",
79        [],
80        |row| row.get(0),
81    ).ok())
82}
83
84/// Set the stored private key.
85pub fn set_pkey(pkey: &str) -> Result<(), String> {
86    let conn = super::get_write_connection_guard_static()?;
87    conn.execute(
88        "INSERT OR REPLACE INTO settings (key, value) VALUES ('pkey', ?1)",
89        rusqlite::params![pkey],
90    ).map_err(|e| format!("Failed to set pkey: {}", e))?;
91    Ok(())
92}
93
94/// Get the stored seed phrase (may be encrypted).
95pub fn get_seed() -> Result<Option<String>, String> {
96    let conn = super::get_db_connection_guard_static()?;
97    Ok(conn.query_row(
98        "SELECT value FROM settings WHERE key = 'seed'",
99        [],
100        |row| row.get(0),
101    ).ok())
102}
103
104/// Set the seed phrase (should be encrypted before calling).
105pub fn set_seed(seed: &str) -> Result<(), String> {
106    let conn = super::get_write_connection_guard_static()?;
107    conn.execute(
108        "INSERT OR REPLACE INTO settings (key, value) VALUES ('seed', ?1)",
109        rusqlite::params![seed],
110    ).map_err(|e| format!("Failed to set seed: {}", e))?;
111    Ok(())
112}
113
114/// Atomically commit the four settings written during new-account setup:
115/// the (possibly-encrypted) pkey, the `encryption_enabled` flag, the
116/// `security_type` (only when encrypted), and the (already-encrypted) seed
117/// phrase. Wrapping these in a single transaction makes the new-account
118/// flow crash-safe: either all four land or none do. The previous design
119/// wrote them through four separate `set_sql_setting` calls, which left a
120/// window where pkey was persisted but `encryption_enabled` was not — the
121/// next boot would then mis-interpret the encrypted blob as plaintext nsec
122/// and brick the account.
123///
124/// `security_type` is `Some(_)` for encrypted accounts and `None` for
125/// skip-encryption flows (passing `Some("")` would write an empty string,
126/// which `resolve_encryption_enabled` treats as encrypted — not what we
127/// want for the skip path).
128pub fn commit_account_setup(
129    pkey: &str,
130    encryption_enabled: bool,
131    security_type: Option<&str>,
132    encrypted_seed: Option<&str>,
133    biometric_wrap: Option<&str>,
134    kdf: Option<&str>,
135) -> Result<(), String> {
136    if encryption_enabled && kdf.is_none() {
137        return Err("An encrypted account needs its key derivation recorded".to_string());
138    }
139    let mut conn = super::get_write_connection_guard_static()?;
140    let tx = conn.transaction()
141        .map_err(|e| format!("Failed to begin tx: {}", e))?;
142    tx.execute(
143        "INSERT OR REPLACE INTO settings (key, value) VALUES ('pkey', ?1)",
144        rusqlite::params![pkey],
145    ).map_err(|e| format!("Failed to set pkey: {}", e))?;
146    tx.execute(
147        "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', ?1)",
148        rusqlite::params![if encryption_enabled { "true" } else { "false" }],
149    ).map_err(|e| format!("Failed to set encryption_enabled: {}", e))?;
150    if let Some(st) = security_type {
151        tx.execute(
152            "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
153            rusqlite::params![st],
154        ).map_err(|e| format!("Failed to set security_type: {}", e))?;
155    } else {
156        // Skip path: ensure no stale security_type from a previous setup
157        // attempt lingers (would mis-route `resolve_encryption_enabled`).
158        tx.execute(
159            "DELETE FROM settings WHERE key = 'security_type'",
160            [],
161        ).map_err(|e| format!("Failed to clear security_type: {}", e))?;
162    }
163    if let Some(seed) = encrypted_seed {
164        tx.execute(
165            "INSERT OR REPLACE INTO settings (key, value) VALUES ('seed', ?1)",
166            rusqlite::params![seed],
167        ).map_err(|e| format!("Failed to set seed: {}", e))?;
168    }
169    // Write an explicit signer_type='local' row so the post-migration
170    // invariant "every account has a discriminator on disk" holds for
171    // freshly-created local accounts too (the migration only backfills
172    // pre-existing rows).
173    tx.execute(
174        "INSERT OR REPLACE INTO settings (key, value) VALUES ('signer_type', 'local')",
175        [],
176    ).map_err(|e| format!("Failed to set signer_type: {}", e))?;
177    // Biometric-only mode: the wrapped vault key is the account's SOLE
178    // credential, so it must land in the SAME transaction that locks the
179    // store to it — a crash between commit and a separate write would leave
180    // the account permanently unrecoverable. None purges any stale wrap.
181    match biometric_wrap {
182        Some(w) => {
183            tx.execute(
184                "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
185                rusqlite::params![w],
186            ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
187        }
188        None => {
189            tx.execute(
190                "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
191                [],
192            ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
193        }
194    }
195
196    write_kdf_in_tx(&tx, kdf)?;
197    tx.commit().map_err(|e| format!("Failed to commit tx: {}", e))?;
198    Ok(())
199}
200
201/// Record how the key everything in this transaction is sealed under was derived. `None` (no
202/// encryption) leaves no row; a missing row on an encrypted account means the legacy salt.
203pub(crate) fn write_kdf_in_tx(tx: &rusqlite::Transaction, kdf: Option<&str>) -> Result<(), String> {
204    // A new credential, or none, starts with fresh tries.
205    tx.execute("DELETE FROM settings WHERE key IN ('credential_failures', 'credential_retry_at')", [])
206        .map_err(|e| format!("Failed to reset credential tries: {e}"))?;
207    match kdf {
208        Some(k) => tx.execute("INSERT OR REPLACE INTO settings (key, value) VALUES ('kdf', ?1)", rusqlite::params![k]),
209        None => tx.execute("DELETE FROM settings WHERE key = 'kdf'", []),
210    }
211    .map(|_| ())
212    .map_err(|e| format!("Failed to record key derivation: {e}"))
213}
214
215// ============================================================================
216// NIP-46 remote-signer settings (added in migration 27)
217// ============================================================================
218//
219// Three keys back the bunker login flow:
220//   - `signer_type`         — "local" | "bunker"
221//   - `bunker_url`          — `bunker://...` URI, encrypted-at-rest when the
222//                             account uses pin/pass encryption (same path as
223//                             pkey). Contains the connection secret.
224//   - `bunker_remote_pubkey`— signer pubkey, plaintext (routing info only).
225//
226// The `bunker_url` getter/setter keep their `async` signatures; both seal and
227// open against the vault without awaiting.
228
229/// Read the active signer kind from settings. Missing rows pre-date migration
230/// 27 and are treated as `"local"` so pre-NIP-46 accounts behave unchanged.
231pub fn get_signer_type() -> Result<String, String> {
232    let conn = super::get_db_connection_guard_static()?;
233    Ok(conn.query_row(
234        "SELECT value FROM settings WHERE key = 'signer_type'",
235        [],
236        |row| row.get::<_, String>(0),
237    ).unwrap_or_else(|_| "local".to_string()))
238}
239
240/// Persist the signer kind. Accepts the discriminator's `as_setting_str()`
241/// form ("local" or "bunker"); other values are accepted but `get_signer_type`
242/// will treat them as `local` downstream.
243pub fn set_signer_type(value: &str) -> Result<(), String> {
244    let conn = super::get_write_connection_guard_static()?;
245    conn.execute(
246        "INSERT OR REPLACE INTO settings (key, value) VALUES ('signer_type', ?1)",
247        rusqlite::params![value],
248    ).map_err(|e| format!("Failed to set signer_type: {}", e))?;
249    Ok(())
250}
251
252/// Read the `bunker://` URL, decrypting it if the account uses encryption.
253/// Returns `Ok(None)` for local accounts (no row), or when decryption fails
254/// against an obviously-encrypted blob (likely the user hasn't unlocked yet).
255pub async fn get_bunker_url() -> Result<Option<String>, String> {
256    let raw: Option<String> = {
257        let conn = super::get_db_connection_guard_static()?;
258        conn.query_row(
259            "SELECT value FROM settings WHERE key = 'bunker_url'",
260            [],
261            |row| row.get::<_, String>(0),
262        ).ok()
263    };
264    match raw {
265        Some(s) => match crate::crypto::maybe_decrypt(s).await {
266            Ok(plain) => Ok(Some(plain)),
267            Err(_) => Err("bunker_url decryption failed (account locked?)".into()),
268        },
269        None => Ok(None),
270    }
271}
272
273/// Persist the `bunker://` URL, encrypting if the account uses encryption.
274/// The plaintext form is never written to disk for encrypted accounts.
275pub async fn set_bunker_url(url: &str) -> Result<(), String> {
276    let _seal = crate::crypto::gate::sealing();
277    let stored = crate::crypto::maybe_encrypt_text(url)?;
278    let conn = super::get_write_connection_guard_static()?;
279    conn.execute(
280        "INSERT OR REPLACE INTO settings (key, value) VALUES ('bunker_url', ?1)",
281        rusqlite::params![stored],
282    ).map_err(|e| format!("Failed to set bunker_url: {}", e))?;
283    Ok(())
284}
285
286/// Read the cached remote signer pubkey (hex). Plaintext on disk — it's
287/// public-key material with no secrecy implications, and keeping it readable
288/// before unlock lets the UI display `"Connected to <pubkey>"` on the locked
289/// account picker without prompting for a password.
290pub fn get_bunker_remote_pubkey() -> Result<Option<String>, String> {
291    let conn = super::get_db_connection_guard_static()?;
292    Ok(conn.query_row(
293        "SELECT value FROM settings WHERE key = 'bunker_remote_pubkey'",
294        [],
295        |row| row.get::<_, String>(0),
296    ).ok())
297}
298
299/// Persist the cached remote signer pubkey (hex form). Updated after each
300/// successful bunker bootstrap — the bootstrap response carries the canonical
301/// pubkey, which may differ from any user-supplied form.
302pub fn set_bunker_remote_pubkey(pubkey_hex: &str) -> Result<(), String> {
303    let conn = super::get_write_connection_guard_static()?;
304    conn.execute(
305        "INSERT OR REPLACE INTO settings (key, value) VALUES ('bunker_remote_pubkey', ?1)",
306        rusqlite::params![pubkey_hex],
307    ).map_err(|e| format!("Failed to set bunker_remote_pubkey: {}", e))?;
308    Ok(())
309}
310
311/// Atomically commit the four settings written during *bunker* new-account
312/// setup: the (possibly-encrypted) client keypair pkey, `encryption_enabled`,
313/// `security_type`, plus `signer_type='bunker'`, the (possibly-encrypted)
314/// `bunker_url`, and the plaintext `bunker_remote_pubkey`. Wraps the whole
315/// commit in a transaction for the same reason as `commit_account_setup` —
316/// a half-written bunker account would brick login.
317///
318/// The seed is intentionally absent: bunker accounts have no local mnemonic
319/// (the user's nsec lives on the remote signer; we only hold a client keypair
320/// with no recovery phrase).
321pub fn commit_bunker_account_setup(
322    pkey: &str,
323    encryption_enabled: bool,
324    security_type: Option<&str>,
325    bunker_url_stored: &str,
326    bunker_remote_pubkey_hex: &str,
327    biometric_wrap: Option<&str>,
328    kdf: Option<&str>,
329) -> Result<(), String> {
330    if encryption_enabled && kdf.is_none() {
331        return Err("An encrypted account needs its key derivation recorded".to_string());
332    }
333    let mut conn = super::get_write_connection_guard_static()?;
334    let tx = conn.transaction()
335        .map_err(|e| format!("Failed to begin tx: {}", e))?;
336    tx.execute(
337        "INSERT OR REPLACE INTO settings (key, value) VALUES ('pkey', ?1)",
338        rusqlite::params![pkey],
339    ).map_err(|e| format!("Failed to set pkey: {}", e))?;
340    tx.execute(
341        "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', ?1)",
342        rusqlite::params![if encryption_enabled { "true" } else { "false" }],
343    ).map_err(|e| format!("Failed to set encryption_enabled: {}", e))?;
344    if let Some(st) = security_type {
345        tx.execute(
346            "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
347            rusqlite::params![st],
348        ).map_err(|e| format!("Failed to set security_type: {}", e))?;
349    } else {
350        tx.execute(
351            "DELETE FROM settings WHERE key = 'security_type'",
352            [],
353        ).map_err(|e| format!("Failed to clear security_type: {}", e))?;
354    }
355    tx.execute(
356        "INSERT OR REPLACE INTO settings (key, value) VALUES ('signer_type', 'bunker')",
357        [],
358    ).map_err(|e| format!("Failed to set signer_type: {}", e))?;
359    tx.execute(
360        "INSERT OR REPLACE INTO settings (key, value) VALUES ('bunker_url', ?1)",
361        rusqlite::params![bunker_url_stored],
362    ).map_err(|e| format!("Failed to set bunker_url: {}", e))?;
363    tx.execute(
364        "INSERT OR REPLACE INTO settings (key, value) VALUES ('bunker_remote_pubkey', ?1)",
365        rusqlite::params![bunker_remote_pubkey_hex],
366    ).map_err(|e| format!("Failed to set bunker_remote_pubkey: {}", e))?;
367    // Drop any stale seed from a previous local-account setup on this DB.
368    tx.execute("DELETE FROM settings WHERE key = 'seed'", [])
369        .map_err(|e| format!("Failed to clear stale seed: {}", e))?;
370    // Biometric-only mode: the wrapped vault key is the account's SOLE
371    // credential, so it must land in the SAME transaction that locks the
372    // store to it — a crash between commit and a separate write would leave
373    // the account permanently unrecoverable. None purges any stale wrap.
374    match biometric_wrap {
375        Some(w) => {
376            tx.execute(
377                "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
378                rusqlite::params![w],
379            ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
380        }
381        None => {
382            tx.execute(
383                "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
384                [],
385            ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
386        }
387    }
388
389    write_kdf_in_tx(&tx, kdf)?;
390    tx.commit().map_err(|e| format!("Failed to commit tx: {}", e))?;
391    Ok(())
392}
393
394// ============================================================================
395// NIP-55 offline-signer settings
396// ============================================================================
397//
398// A NIP-55 (Amber) account keeps NOTHING secret on this device — not even the
399// client keypair a bunker account holds. So there is no `pkey` row at all; the
400// only account-identifying material is public:
401//   - `signer_type`         — "nip55"
402//   - `nip55_user_pubkey`   — identity pubkey hex, plaintext (public material;
403//                             lets the locked account picker render the npub
404//                             pre-unlock, same as `bunker_remote_pubkey`).
405//   - `nip55_signer_package`— the signer app's Android package name, plaintext.
406//
407// `encryption_enabled`/`security_type` still apply, but they gate ONLY the
408// local at-rest DB encryption (messages Vector stores) — orthogonal to signing,
409// which never touches this device's storage.
410
411/// Read the cached NIP-55 identity pubkey (hex). Plaintext on disk (public-key
412/// material); readable before unlock so the account picker can show the npub.
413pub fn get_nip55_user_pubkey() -> Result<Option<String>, String> {
414    let conn = super::get_db_connection_guard_static()?;
415    Ok(conn.query_row(
416        "SELECT value FROM settings WHERE key = 'nip55_user_pubkey'",
417        [],
418        |row| row.get::<_, String>(0),
419    ).ok())
420}
421
422/// Persist the NIP-55 identity pubkey (hex).
423pub fn set_nip55_user_pubkey(pubkey_hex: &str) -> Result<(), String> {
424    let conn = super::get_write_connection_guard_static()?;
425    conn.execute(
426        "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_user_pubkey', ?1)",
427        rusqlite::params![pubkey_hex],
428    ).map_err(|e| format!("Failed to set nip55_user_pubkey: {}", e))?;
429    Ok(())
430}
431
432/// Read the paired signer app's Android package name. Pinned on every intent +
433/// as the ContentResolver authority so a second signer app can't intercept.
434pub fn get_nip55_signer_package() -> Result<Option<String>, String> {
435    let conn = super::get_db_connection_guard_static()?;
436    Ok(conn.query_row(
437        "SELECT value FROM settings WHERE key = 'nip55_signer_package'",
438        [],
439        |row| row.get::<_, String>(0),
440    ).ok())
441}
442
443/// Persist the paired signer app's package name. Updated on re-pair.
444pub fn set_nip55_signer_package(package: &str) -> Result<(), String> {
445    let conn = super::get_write_connection_guard_static()?;
446    conn.execute(
447        "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_signer_package', ?1)",
448        rusqlite::params![package],
449    ).map_err(|e| format!("Failed to set nip55_signer_package: {}", e))?;
450    Ok(())
451}
452
453/// Atomically commit NIP-55 new-account setup: `encryption_enabled`,
454/// `security_type`, `signer_type='nip55'`, and the two plaintext public fields.
455/// No `pkey` is written (nothing secret exists), and any stale key material
456/// from a prior local/bunker setup on this DB is scrubbed so login can't
457/// mis-route through a leftover pkey/bunker row. Transactional for the same
458/// reason as the sibling commits — a half-written account bricks login.
459pub fn commit_nip55_account_setup(
460    user_pubkey_hex: &str,
461    signer_package: &str,
462    encryption_enabled: bool,
463    security_type: Option<&str>,
464    biometric_wrap: Option<&str>,
465    pin_canary: Option<&str>,
466    kdf: Option<&str>,
467) -> Result<(), String> {
468    commit_external_signer_setup(
469        crate::SignerKind::Nip55, user_pubkey_hex, signer_package,
470        encryption_enabled, security_type, biometric_wrap, pin_canary, kdf,
471    )
472}
473
474/// [`commit_nip55_account_setup`] for any keyless signer kind. NIP-07 accounts
475/// share the NIP-55 rows: the identity in `nip55_user_pubkey`, the signer's
476/// name in `nip55_signer_package`, the PIN canary in `nip55_pin_check`.
477pub fn commit_external_signer_setup(
478    kind: crate::SignerKind,
479    user_pubkey_hex: &str,
480    signer_package: &str,
481    encryption_enabled: bool,
482    security_type: Option<&str>,
483    biometric_wrap: Option<&str>,
484    pin_canary: Option<&str>,
485    kdf: Option<&str>,
486) -> Result<(), String> {
487    if encryption_enabled && kdf.is_none() {
488        return Err("An encrypted account needs its key derivation recorded".to_string());
489    }
490    if kind == crate::SignerKind::Local || kind == crate::SignerKind::Bunker {
491        return Err("not a keyless signer kind".into());
492    }
493    let mut conn = super::get_write_connection_guard_static()?;
494    let tx = conn.transaction()
495        .map_err(|e| format!("Failed to begin tx: {}", e))?;
496    tx.execute(
497        "INSERT OR REPLACE INTO settings (key, value) VALUES ('encryption_enabled', ?1)",
498        rusqlite::params![if encryption_enabled { "true" } else { "false" }],
499    ).map_err(|e| format!("Failed to set encryption_enabled: {}", e))?;
500    if let Some(st) = security_type {
501        tx.execute(
502            "INSERT OR REPLACE INTO settings (key, value) VALUES ('security_type', ?1)",
503            rusqlite::params![st],
504        ).map_err(|e| format!("Failed to set security_type: {}", e))?;
505    } else {
506        tx.execute(
507            "DELETE FROM settings WHERE key = 'security_type'",
508            [],
509        ).map_err(|e| format!("Failed to clear security_type: {}", e))?;
510    }
511    tx.execute(
512        "INSERT OR REPLACE INTO settings (key, value) VALUES ('signer_type', ?1)",
513        rusqlite::params![kind.as_setting_str()],
514    ).map_err(|e| format!("Failed to set signer_type: {}", e))?;
515    tx.execute(
516        "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_user_pubkey', ?1)",
517        rusqlite::params![user_pubkey_hex],
518    ).map_err(|e| format!("Failed to set nip55_user_pubkey: {}", e))?;
519    tx.execute(
520        "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_signer_package', ?1)",
521        rusqlite::params![signer_package],
522    ).map_err(|e| format!("Failed to set nip55_signer_package: {}", e))?;
523    // Scrub any secret/bunker material a prior setup on this DB may have left —
524    // a NIP-55 account must never fall back to a stale key at boot.
525    for stale in ["pkey", "seed", "bunker_url", "bunker_remote_pubkey"] {
526        tx.execute(
527            "DELETE FROM settings WHERE key = ?1",
528            rusqlite::params![stale],
529        ).map_err(|e| format!("Failed to clear stale {}: {}", stale, e))?;
530    }
531    // Biometric-only mode: the wrapped vault key is the account's SOLE
532    // credential, so it must land in the SAME transaction that locks the
533    // store to it — a crash between commit and a separate write would leave
534    // the account permanently unrecoverable. None purges any stale wrap.
535    match biometric_wrap {
536        Some(w) => {
537            tx.execute(
538                "INSERT OR REPLACE INTO settings (key, value) VALUES ('biometric_wrapped_key', ?1)",
539                rusqlite::params![w],
540            ).map_err(|e| format!("Failed to set biometric wrap: {}", e))?;
541        }
542        None => {
543            tx.execute(
544                "DELETE FROM settings WHERE key = 'biometric_wrapped_key'",
545                [],
546            ).map_err(|e| format!("Failed to clear biometric wrap: {}", e))?;
547        }
548    }
549
550    // The canary is a keyless account's ONLY wrong-PIN detector at boot —
551    // same atomicity rule as the biometric wrap: it lands with the commit or
552    // not at all. None scrubs any stale canary from a prior setup.
553    match pin_canary {
554        Some(c) => {
555            tx.execute(
556                "INSERT OR REPLACE INTO settings (key, value) VALUES ('nip55_pin_check', ?1)",
557                rusqlite::params![c],
558            ).map_err(|e| format!("Failed to set pin canary: {}", e))?;
559        }
560        None => {
561            tx.execute(
562                "DELETE FROM settings WHERE key = 'nip55_pin_check'",
563                [],
564            ).map_err(|e| format!("Failed to clear pin canary: {}", e))?;
565        }
566    }
567
568    write_kdf_in_tx(&tx, kdf)?;
569    tx.commit().map_err(|e| format!("Failed to commit tx: {}", e))?;
570    Ok(())
571}