Skip to main content

vector_core/db/
nip17_keys.rs

1//! NIP-17 ephemeral wrap-key vault.
2//!
3//! NIP-59 gift-wraps each DM with a fresh ephemeral keypair whose secret
4//! is normally discarded immediately after signing. We retain it so the
5//! user can later publish an author-signed NIP-09 deletion against the
6//! kind-1059 wrap event — actually removing the message from inbox
7//! relays rather than relying on "throw the keys away and hope".
8//!
9//! Encryption-at-rest is handled by Vector's per-account database
10//! envelope: ChaCha20 if the account has a password, plaintext if it
11//! doesn't (passwordless accounts are unencrypted by design).
12
13use nostr_sdk::prelude::*;
14use rusqlite::{params, OptionalExtension};
15
16/// Role of a stored wrap key. Recorded so the deletion path can label
17/// audit logs and so a future feature could selectively retain/purge by
18/// role (e.g. "drop self-send keys after N days").
19#[repr(i64)]
20#[derive(Copy, Clone, Debug, PartialEq, Eq)]
21pub enum WrapRole {
22    /// First-attempt wrap delivered to the recipient.
23    Recipient = 0,
24    /// Wrap delivered to our own inbox for multi-device recovery.
25    SelfSend = 1,
26    /// Retry wrap (used when an earlier attempt produced a different wrap
27    /// event that may also be sitting on some relay).
28    Retry = 2,
29}
30
31impl WrapRole {
32    fn from_i64(v: i64) -> Self {
33        match v {
34            1 => Self::SelfSend,
35            2 => Self::Retry,
36            _ => Self::Recipient,
37        }
38    }
39}
40
41#[derive(Clone, Debug)]
42pub struct StoredWrapKey {
43    pub wrap_event_id: EventId,
44    pub rumor_id: EventId,
45    pub recipient_pubkey: PublicKey,
46    pub role: WrapRole,
47    pub secret: SecretKey,
48    /// Relay URLs we attempted at send time. Deletion publishes the
49    /// author-signed NIP-09 back to this same set.
50    pub relay_urls: Vec<String>,
51}
52
53/// Persist a retained ephemeral wrap secret. Idempotent on
54/// `wrap_event_id` so retries that land the same wrap won't duplicate.
55pub fn store_wrap_key(
56    wrap_event_id: &EventId,
57    rumor_id: &EventId,
58    recipient_pubkey: &PublicKey,
59    role: WrapRole,
60    secret: &SecretKey,
61    relay_urls: &[String],
62) -> Result<(), String> {
63    let conn = super::get_write_connection_guard_static()?;
64    let now = std::time::SystemTime::now()
65        .duration_since(std::time::UNIX_EPOCH)
66        .unwrap()
67        .as_secs() as i64;
68    let relays_json = serde_json::to_string(relay_urls)
69        .map_err(|e| format!("Failed to encode relay urls: {}", e))?;
70    conn.execute(
71        "INSERT OR REPLACE INTO nip17_wrap_keys
72            (wrap_event_id, rumor_id, recipient_pubkey, role, secret, relay_urls, created_at)
73         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
74        params![
75            wrap_event_id.to_hex(),
76            rumor_id.to_hex(),
77            recipient_pubkey.to_hex(),
78            role as i64,
79            secret.as_secret_bytes(),
80            relays_json,
81            now,
82        ],
83    )
84    .map_err(|e| format!("Failed to insert wrap key: {}", e))?;
85    crate::log_info!(
86        "[NIP-17 keys] stored {:?} key for rumor {} (wrap {})",
87        role,
88        rumor_id.to_hex(),
89        wrap_event_id.to_hex()
90    );
91    Ok(())
92}
93
94/// Fetch every retained wrap key (recipient + self + retry) for a given
95/// inner rumor id. Used at delete time to construct one NIP-09 per wrap.
96pub fn get_wrap_keys_for_rumor(rumor_id: &EventId) -> Result<Vec<StoredWrapKey>, String> {
97    let conn = super::get_db_connection_guard_static()?;
98    let mut stmt = conn
99        .prepare(
100            "SELECT wrap_event_id, rumor_id, recipient_pubkey, role, secret, relay_urls
101             FROM nip17_wrap_keys WHERE rumor_id = ?1",
102        )
103        .map_err(|e| format!("Failed to prepare query: {}", e))?;
104
105    let rows = stmt
106        .query_map(params![rumor_id.to_hex()], |row| {
107            let wrap_hex: String = row.get(0)?;
108            let rumor_hex: String = row.get(1)?;
109            let recipient_hex: String = row.get(2)?;
110            let role_i: i64 = row.get(3)?;
111            let secret_blob: Vec<u8> = row.get(4)?;
112            let relays_json: String = row.get(5)?;
113            Ok((wrap_hex, rumor_hex, recipient_hex, role_i, secret_blob, relays_json))
114        })
115        .map_err(|e| format!("Failed to query wrap keys: {}", e))?;
116
117    let mut out = Vec::new();
118    for row_res in rows {
119        let (wrap_hex, rumor_hex, recipient_hex, role_i, secret_blob, relays_json) =
120            row_res.map_err(|e| format!("Row read error: {}", e))?;
121        let wrap_event_id =
122            EventId::from_hex(&wrap_hex).map_err(|e| format!("Bad wrap id: {}", e))?;
123        let rumor_id_parsed =
124            EventId::from_hex(&rumor_hex).map_err(|e| format!("Bad rumor id: {}", e))?;
125        let recipient_pubkey =
126            PublicKey::from_hex(&recipient_hex).map_err(|e| format!("Bad pubkey: {}", e))?;
127        let secret =
128            SecretKey::from_slice(&secret_blob).map_err(|e| format!("Bad secret: {}", e))?;
129        let relay_urls: Vec<String> = serde_json::from_str(&relays_json)
130            .map_err(|e| format!("Bad relay urls: {}", e))?;
131        out.push(StoredWrapKey {
132            wrap_event_id,
133            rumor_id: rumor_id_parsed,
134            recipient_pubkey,
135            role: WrapRole::from_i64(role_i),
136            secret,
137            relay_urls,
138        });
139    }
140    Ok(out)
141}
142
143/// Cheap existence check: do we hold any retained wrap key for this
144/// rumor id? Used by the UI to gate the delete-message control so we
145/// don't tease users with a button we can't actually fulfil.
146pub fn has_wrap_keys_for_rumor(rumor_id: &EventId) -> Result<bool, String> {
147    let conn = super::get_db_connection_guard_static()?;
148    conn.query_row(
149        "SELECT EXISTS(SELECT 1 FROM nip17_wrap_keys WHERE rumor_id = ?1)",
150        params![rumor_id.to_hex()],
151        |row| row.get::<_, bool>(0),
152    )
153    .map_err(|e| format!("Failed to check wrap keys: {}", e))
154}
155
156/// Drop wrap-key rows after the corresponding NIP-09 deletions have
157/// been broadcast. Caller passes the wrap event ids it actually deleted
158/// so partial-success scenarios don't accidentally drop keys still
159/// useful for retry.
160pub fn purge_wrap_keys(wrap_event_ids: &[EventId]) -> Result<(), String> {
161    if wrap_event_ids.is_empty() {
162        return Ok(());
163    }
164    let conn = super::get_write_connection_guard_static()?;
165    let placeholders = std::iter::repeat("?")
166        .take(wrap_event_ids.len())
167        .collect::<Vec<_>>()
168        .join(",");
169    let sql = format!(
170        "DELETE FROM nip17_wrap_keys WHERE wrap_event_id IN ({})",
171        placeholders,
172    );
173    let hex_strings: Vec<String> = wrap_event_ids.iter().map(|id| id.to_hex()).collect();
174    let params_dyn: Vec<&dyn rusqlite::ToSql> = hex_strings
175        .iter()
176        .map(|s| s as &dyn rusqlite::ToSql)
177        .collect();
178    conn.execute(&sql, params_dyn.as_slice())
179        .map_err(|e| format!("Failed to purge wrap keys: {}", e))?;
180    Ok(())
181}
182
183// ============================================================================
184// Retained wrap body — idempotent manual retry
185// ============================================================================
186//
187// The recipient wrap's ephemeral key is retained above for NIP-09 delete. For
188// a byte-identical *resend* (so a relay no-ops the duplicate rather than
189// storing a second copy) we also retain the built wrap EVENT plus its rumor,
190// keyed by the local pending id so Retry can find them from the failed row.
191// A gift wrap can't be rebuilt identically (random ephemeral key + NIP-44
192// nonce + NIP-59 backdated created_at), so the exact bytes must be kept.
193// The body is transient: nulled the instant a relay confirms delivery.
194
195/// Everything needed to republish a failed DM's recipient wrap verbatim.
196pub struct ResendPayload {
197    /// The exact kind-1059 event to republish (same id → relay dedup).
198    pub wrap_event: Event,
199    /// The inner rumor, for finalize + the self-send copy on success.
200    pub rumor: UnsignedEvent,
201    /// The wrap's ephemeral secret (re-associated with the injected wrap;
202    /// republishing a pre-signed event never reads it, but the send path's
203    /// `BuiltGiftWrap` carries it).
204    pub secret: SecretKey,
205    pub recipient_pubkey: PublicKey,
206    /// Relay set attempted at first send (fallback targets).
207    pub relay_urls: Vec<String>,
208    pub rumor_id: EventId,
209}
210
211/// Attach the republishable body to an existing recipient wrap-key row.
212/// Called right after `store_wrap_key` on the first send attempt.
213pub fn stash_resend_payload(
214    wrap_event_id: &EventId,
215    pending_id: &str,
216    wrap_event: &Event,
217    rumor: &UnsignedEvent,
218) -> Result<(), String> {
219    let conn = super::get_write_connection_guard_static()?;
220    conn.execute(
221        "UPDATE nip17_wrap_keys SET wrap_json = ?1, rumor_json = ?2, pending_id = ?3
222         WHERE wrap_event_id = ?4",
223        params![
224            wrap_event.as_json(),
225            rumor.as_json(),
226            pending_id,
227            wrap_event_id.to_hex(),
228        ],
229    )
230    .map_err(|e| format!("Failed to stash resend payload: {}", e))?;
231    Ok(())
232}
233
234/// Load the republishable recipient wrap for a failed message (its id is the
235/// local pending id). `None` when nothing retained — the caller then falls
236/// back to a fresh send. Only rows with a body (still unconfirmed) match.
237pub fn get_resend_payload_by_pending(pending_id: &str) -> Result<Option<ResendPayload>, String> {
238    let conn = super::get_db_connection_guard_static()?;
239    // role 0 = Recipient — the only wrap a manual retry republishes.
240    let row = conn
241        .query_row(
242            "SELECT rumor_id, recipient_pubkey, secret, relay_urls, wrap_json, rumor_json
243             FROM nip17_wrap_keys
244             WHERE pending_id = ?1 AND role = 0
245               AND wrap_json IS NOT NULL AND rumor_json IS NOT NULL
246             LIMIT 1",
247            params![pending_id],
248            |row| {
249                let rumor_hex: String = row.get(0)?;
250                let recipient_hex: String = row.get(1)?;
251                let secret_blob: Vec<u8> = row.get(2)?;
252                let relays_json: String = row.get(3)?;
253                let wrap_json: String = row.get(4)?;
254                let rumor_json: String = row.get(5)?;
255                Ok((rumor_hex, recipient_hex, secret_blob, relays_json, wrap_json, rumor_json))
256            },
257        )
258        .optional()
259        .map_err(|e| format!("Failed to query resend payload: {}", e))?;
260
261    let Some((rumor_hex, recipient_hex, secret_blob, relays_json, wrap_json, rumor_json)) = row
262    else {
263        return Ok(None);
264    };
265    let rumor_id = EventId::from_hex(&rumor_hex).map_err(|e| format!("Bad rumor id: {}", e))?;
266    let recipient_pubkey =
267        PublicKey::from_hex(&recipient_hex).map_err(|e| format!("Bad pubkey: {}", e))?;
268    let secret = SecretKey::from_slice(&secret_blob).map_err(|e| format!("Bad secret: {}", e))?;
269    let relay_urls: Vec<String> =
270        serde_json::from_str(&relays_json).map_err(|e| format!("Bad relay urls: {}", e))?;
271    let wrap_event = Event::from_json(&wrap_json).map_err(|e| format!("Bad wrap json: {}", e))?;
272    let rumor = UnsignedEvent::from_json(&rumor_json).map_err(|e| format!("Bad rumor json: {}", e))?;
273    Ok(Some(ResendPayload {
274        wrap_event,
275        rumor,
276        secret,
277        recipient_pubkey,
278        relay_urls,
279        rumor_id,
280    }))
281}
282
283/// Drop the republishable body once delivery is confirmed (the key row stays
284/// for NIP-09 delete). Keyed by rumor id so both the recipient and any retry
285/// rows for the message are cleared together.
286pub fn clear_resend_payload(rumor_id: &EventId) -> Result<(), String> {
287    let conn = super::get_write_connection_guard_static()?;
288    conn.execute(
289        "UPDATE nip17_wrap_keys SET wrap_json = NULL, rumor_json = NULL WHERE rumor_id = ?1",
290        params![rumor_id.to_hex()],
291    )
292    .map_err(|e| format!("Failed to clear resend payload: {}", e))?;
293    Ok(())
294}
295
296/// Backstop: null retained bodies older than `max_age_secs` so a pile of
297/// never-retried reds can't grow unbounded. The key row (NIP-09) survives.
298/// Returns how many bodies were reaped.
299pub fn prune_stale_resend_payloads(max_age_secs: i64) -> Result<usize, String> {
300    let conn = super::get_write_connection_guard_static()?;
301    let now = std::time::SystemTime::now()
302        .duration_since(std::time::UNIX_EPOCH)
303        .unwrap()
304        .as_secs() as i64;
305    let cutoff = now - max_age_secs;
306    let n = conn
307        .execute(
308            "UPDATE nip17_wrap_keys SET wrap_json = NULL, rumor_json = NULL
309             WHERE wrap_json IS NOT NULL AND created_at < ?1",
310            params![cutoff],
311        )
312        .map_err(|e| format!("Failed to prune resend payloads: {}", e))?;
313    Ok(n)
314}
315
316#[cfg(test)]
317mod tests {
318    use crate::event_ext::FinalizeUnsignedWithId;
319    use super::*;
320
321    static TEST_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(81000);
322
323    fn make_test_npub(n: u32) -> String {
324        const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
325        let mut payload = vec![b'q'; 58];
326        let mut x = n as u64;
327        let mut i = 58;
328        while x > 0 && i > 0 {
329            i -= 1;
330            payload[i] = BECH32[(x as usize) % 32];
331            x /= 32;
332        }
333        format!("npub1{}", std::str::from_utf8(&payload).unwrap())
334    }
335
336    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
337        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
338        crate::db::close_database();
339        crate::db::clear_id_caches();
340        let tmp = tempfile::tempdir().unwrap();
341        let n = TEST_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
342        let account = make_test_npub(n);
343        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
344        crate::db::set_app_data_dir(tmp.path().to_path_buf());
345        crate::db::set_current_account(account.clone()).unwrap();
346        crate::db::init_database(&account).unwrap();
347        (tmp, guard)
348    }
349
350    fn sample() -> (Event, UnsignedEvent, Keys, PublicKey) {
351        let ephemeral = Keys::generate();
352        let sender = Keys::generate();
353        let recipient = Keys::generate();
354        // Stand-in wrap: any valid signed event — the id is what must survive.
355        let wrap = EventBuilder::new(Kind::TextNote, "wrap").finalize(&ephemeral).unwrap();
356        let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hello")
357            .tag(Tag::public_key(recipient.public_key()))
358            .finalize_unsigned_with_id(sender.public_key());
359        (wrap, rumor, ephemeral, recipient.public_key())
360    }
361
362    #[test]
363    fn resend_payload_round_trips_and_clears() {
364        let (_tmp, _guard) = init_test_db();
365        let (wrap, rumor, ephemeral, recipient) = sample();
366        let rumor_id = rumor.id.unwrap();
367        let relays = vec!["wss://relay.one".to_string(), "wss://relay.two".to_string()];
368
369        store_wrap_key(&wrap.id, &rumor_id, &recipient, WrapRole::Recipient,
370            ephemeral.secret_key(), &relays).unwrap();
371        stash_resend_payload(&wrap.id, "pending-42", &wrap, &rumor).unwrap();
372
373        let got = get_resend_payload_by_pending("pending-42").unwrap().expect("payload retained");
374        // The whole point: the wrap republishes byte-identical (same outer id).
375        assert_eq!(got.wrap_event.id, wrap.id);
376        assert_eq!(got.rumor.id, Some(rumor_id));
377        assert_eq!(got.rumor_id, rumor_id);
378        assert_eq!(got.recipient_pubkey, recipient);
379        assert_eq!(got.relay_urls, relays);
380
381        // Confirmed delivery drops the body but keeps the key row for NIP-09.
382        clear_resend_payload(&rumor_id).unwrap();
383        assert!(get_resend_payload_by_pending("pending-42").unwrap().is_none());
384        assert!(has_wrap_keys_for_rumor(&rumor_id).unwrap(), "key row survives NIP-09");
385    }
386
387    #[test]
388    fn no_payload_for_unknown_pending() {
389        let (_tmp, _guard) = init_test_db();
390        assert!(get_resend_payload_by_pending("pending-none").unwrap().is_none());
391    }
392
393    #[test]
394    fn prune_reaps_stale_bodies_but_keeps_keys() {
395        let (_tmp, _guard) = init_test_db();
396        let (wrap, rumor, ephemeral, recipient) = sample();
397        let rumor_id = rumor.id.unwrap();
398        let relays = vec!["wss://relay.one".to_string()];
399        store_wrap_key(&wrap.id, &rumor_id, &recipient, WrapRole::Recipient,
400            ephemeral.secret_key(), &relays).unwrap();
401        stash_resend_payload(&wrap.id, "pending-stale", &wrap, &rumor).unwrap();
402        assert!(get_resend_payload_by_pending("pending-stale").unwrap().is_some());
403
404        // Negative TTL → cutoff in the future → the fresh row's body is reaped.
405        assert_eq!(prune_stale_resend_payloads(-100).unwrap(), 1);
406        assert!(get_resend_payload_by_pending("pending-stale").unwrap().is_none());
407        assert!(has_wrap_keys_for_rumor(&rumor_id).unwrap(), "key row survives prune");
408    }
409}