1pub 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
14pub 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
24pub 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
34pub const SECRET_SETTINGS: &[&str] = &[
37 "pkey", "seed", "bunker_url", "nip55_pin_check", "biometric_wrapped_key",
38 crate::transport::prefs::KEY_I2P_CONFIG,
39];
40
41pub 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
51pub 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
66pub 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
74pub 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
84pub 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
94pub 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
104pub 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
114pub 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 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 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 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
201pub(crate) fn write_kdf_in_tx(tx: &rusqlite::Transaction, kdf: Option<&str>) -> Result<(), String> {
204 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
215pub 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
240pub 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
252pub 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
273pub 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
286pub 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
299pub 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
311pub 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 tx.execute("DELETE FROM settings WHERE key = 'seed'", [])
369 .map_err(|e| format!("Failed to clear stale seed: {}", e))?;
370 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
394pub 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
422pub 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
432pub 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
443pub 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
453pub 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
474pub 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 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 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 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}