Skip to main content

vector_core/
deletion.rs

1//! Message deletion: Vector's "delete from network" for DMs.
2//!
3//! A NIP-17 DM travels as kind-1059 gift wraps, each signed by a single-use key and `p`-tagged
4//! to the one person who can open it. A relay honours a deletion of a wrap only from that
5//! `p`-tagged owner (NIP-59; CORD-01 §Deletions). A Concord plane shares one wrap key among all
6//! its members, so a deletion signed by a wrap's author would let any of them wipe the plane:
7//! Vector's relay refuses those, as every relay serving Concord should. A relay also refuses a
8//! vanish request (NIP-62) from a key that has written wraps, for the same reason.
9//!
10//! So each side deletes the copies addressed to itself:
11//! - The sender deletes its own self-copies with its own key, at once.
12//! - Either side deletes a message it received the same way: its copy by its own key, and a
13//!   hide request to itself for its other devices.
14//! - A hide request (a kind-5 rumor gift-wrapped to the recipient and to self, its wrap
15//!   expiring after 30 days) asks every other device to drop the message and delete the copy
16//!   it was sent the same way. A client that ignores it keeps the message.
17//! - A device that later meets any other wrap of a deleted message deletes that one too, and
18//!   one whose hide request came before the message holds it until the message arrives.
19//!
20//! Every wrap whose single-use key we kept (`db::nip17_keys`) also gets an author-signed
21//! deletion, best-effort: a relay still honouring those drops the recipient's copy even when
22//! their client never will, and our own on a relay that ignores the owner. On a relay that
23//! follows the spec it changes nothing.
24
25use crate::event_ext::FinalizeUnsignedWithId;
26use crate::event_ext::FinalizeOnClock;
27use nostr_sdk::prelude::*;
28
29use crate::inbox_relays::{get_publish_tracker, resolve_gift_wrap_targets, send_gift_wrap, teardown_gift_wrap_targets};
30use crate::state::{my_public_key, nostr_client};
31
32/// Hide-request expiry: 30 days, on the rumor and on its wrap, so relays drop it. A device
33/// first online after that no longer holds the message: every wrap it could fetch is gone.
34pub(crate) const COOPERATIVE_HIDE_EXPIRY_SECS: u64 = 60 * 60 * 24 * 30;
35
36/// Wrap-deletion expiry: the deletion outlives any honest re-broadcast of what it deletes,
37/// then leaves rather than sit on relays forever.
38const WRAP_DELETION_EXPIRY_SECS: u64 = 60 * 60 * 24 * 90;
39
40/// The most wraps one deletion names.
41pub(crate) const WRAPS_PER_DELETION: usize = 100;
42
43/// Outcome of a delete-own-* operation.
44///
45/// Vector's deletion is layered and best-effort: any subset of the
46/// layers may be available depending on whether we hold retained
47/// ephemeral keys, whether the message has attachments, etc. The
48/// outcome reports what was attempted so the caller can show an
49/// honest post-action summary.
50#[derive(serde::Serialize, Debug, Clone, Default)]
51pub struct DeleteOutcome {
52    /// Wrap deletions dispatched: our own copies signed by our key, and best-effort ones
53    /// signed by each retained single-use key.
54    pub wraps_dispatched: usize,
55    /// Wraps of the message this device knows of.
56    pub wraps_total: usize,
57    /// Whether the hide request went out: live Vector clients drop the message and delete
58    /// their own copies of it.
59    pub cooperative_hide_sent: bool,
60    /// Number of Blossom blobs we asked the upload server to delete.
61    /// Best-effort: actual server response is logged, not surfaced.
62    pub blobs_dispatched: usize,
63    /// True iff at least one of (wrap nuke, cooperative hide, blob
64    /// delete) was attempted. False means the only thing the operation
65    /// could do is a local-state drop — caller can use this to surface
66    /// "we couldn't actually remove this from the network" copy.
67    pub any_network_action: bool,
68}
69
70/// Delete an outbound DM from the network: our own copies of it with our key, the hide
71/// request for the recipient's, its attachments from Blossom. Every relay round trip runs
72/// in the background; the call returns once the local state is gone.
73pub async fn delete_own_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
74    let client = nostr_client().ok_or("Not logged in")?;
75    // Durable tombstone FIRST: a wrap some relay keeps re-serves after a restart, and without
76    // it the message would re-ingest and resurrect.
77    let rumor_hex = rumor_id.to_hex();
78    if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
79        crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
80    }
81    crate::state::note_message_deleted(&rumor_hex);
82    let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(rumor_id)
83        .unwrap_or_default();
84    let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
85
86    // Snapshot the message + recipient BEFORE any state/DB cleanup.
87    // Attachment URLs feed Blossom DELETE; the attachments themselves
88    // feed local-cache file removal; recipient pubkey feeds the
89    // hide request. We try to recover all three even when no retained
90    // keys exist (older messages, pre-retention sends).
91    //
92    // INVARIANT: `chat.id` for a DM is the counterpart's npub. The
93    // `find_message` lookup here is unscoped, but `delete_own_dm` is
94    // only ever called from the DM branch of the Tauri command.
95    // `from_bech32` silently yields `None` if the invariant ever
96    // breaks; that just disables the hide request for the call.
97    let (all_attachments, recipient_from_state) = {
98        let state = crate::state::STATE.lock().await;
99        match state.find_message(&rumor_id.to_hex()) {
100            Some((chat, msg)) => {
101                debug_assert!(
102                    matches!(chat.chat_type, crate::chat::ChatType::DirectMessage),
103                    "delete_own_dm called on non-DM chat — caller bug"
104                );
105                let recipient = nostr_sdk::prelude::PublicKey::from_bech32(&chat.id).ok();
106                (msg.attachments.clone(), recipient)
107            }
108            None => (Vec::new(), None),
109        }
110    };
111
112    // Refcount filter: drop attachments still referenced by sibling
113    // messages so we don't yank cached files / Blossom blobs from
114    // messages that still need them. Vector dedupes uploads by SHA-256:
115    // re-sending the same file produces multiple messages pointing at
116    // the same cached path AND the same Blossom blob. Deleting one
117    // shouldn't delete the underlying resources.
118    let unique_attachments = filter_unreferenced_attachments(
119        &rumor_id.to_hex(),
120        all_attachments,
121    ).await;
122
123    // Local cache nuke (canonicalize + managed-dir-only inside helper).
124    delete_cached_attachment_files(&unique_attachments);
125
126    // Blossom URLs derived from the filtered (refcount-aware) set — the
127    // primary plus every mirror (same hash, other origins) — then gated
128    // against the DB ledger: a smart-forwarded blob backs OTHER messages too.
129    let attachment_urls: Vec<String> = scrub_safe_urls(&unique_attachments, &rumor_id.to_hex());
130
131    let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
132
133    // The hide request, when we know the recipient: their live clients drop the message and
134    // delete their own copies. Signed by our main key, so it needs no retained wrap key.
135    let cooperative_recipient = keys
136        .iter()
137        .find(|k| {
138            k.role == crate::db::nip17_keys::WrapRole::Recipient
139                || k.role == crate::db::nip17_keys::WrapRole::Retry
140        })
141        .map(|k| k.recipient_pubkey)
142        .or(recipient_from_state);
143
144    let mut cooperative_hide_sent = false;
145    if let Some(recipient) = cooperative_recipient {
146        match publish_cooperative_hide(&client, rumor_id, Some(&recipient), 14).await {
147            Ok(()) => cooperative_hide_sent = true,
148            Err(e) => crate::log_warn!("[NIP-17 delete] cooperative-hide notice failed: {}", e),
149        }
150    }
151
152    // Layer 3 — Blossom blob delete. Route through the active client
153    // signer so bunker accounts sign DELETE auth under the user's
154    // identity (Blossom enforces "uploader == authorized signer";
155    // signing with the NIP-46 client keypair returns 401).
156    let mut blobs_dispatched = 0usize;
157    if !attachment_urls.is_empty() {
158        if let Ok(signer) = crate::signer::active_signer() {
159            blobs_dispatched = attachment_urls.len();
160            crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
161        }
162    }
163
164    let any_network_action =
165        wraps_dispatched > 0 || cooperative_hide_sent || blobs_dispatched > 0;
166
167    Ok(DeleteOutcome {
168        wraps_total,
169        wraps_dispatched,
170        cooperative_hide_sent,
171        blobs_dispatched,
172        any_network_action,
173    })
174}
175
176/// Revoke one of OUR OWN DM reactions, as [`delete_own_dm`] deletes a message: our copies
177/// with our key, a hide request (k=7) so the counterpart's clients drop the chip and delete
178/// theirs. `recipient` is the DM counterpart, for when no recipient-role wrap key is retained.
179pub async fn delete_own_reaction(
180    reaction_id: &EventId,
181    recipient: PublicKey,
182) -> Result<DeleteOutcome, String> {
183    let client = nostr_client().ok_or("Not logged in")?;
184    // Durable tombstone first, as for messages: a surviving self-wrap re-served later
185    // would otherwise bring the reaction back.
186    let reaction_hex = reaction_id.to_hex();
187    if let Err(e) = crate::db::events::add_message_tombstone(&reaction_hex) {
188        crate::log_warn!("[reaction delete] tombstone write failed: {}", e);
189    }
190    crate::state::note_message_deleted(&reaction_hex);
191    let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(reaction_id)
192        .unwrap_or_default();
193    let received = crate::db::events::wrapper_event_id_of(&reaction_hex);
194    let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &keys, received).await;
195
196    // The hide request (k=7), to a recipient from a retained recipient/retry wrap key or the
197    // passed-in counterpart. Signed by our main key, so it needs no retained wrap key.
198    let cooperative_recipient = keys
199        .iter()
200        .find(|k| {
201            k.role == crate::db::nip17_keys::WrapRole::Recipient
202                || k.role == crate::db::nip17_keys::WrapRole::Retry
203        })
204        .map(|k| k.recipient_pubkey)
205        .unwrap_or(recipient);
206
207    let mut cooperative_hide_sent = false;
208    match publish_cooperative_hide(&client, reaction_id, Some(&cooperative_recipient), 7).await {
209        Ok(()) => cooperative_hide_sent = true,
210        Err(e) => crate::log_warn!("[reaction delete] cooperative-hide failed: {}", e),
211    }
212
213    let any_network_action = wraps_dispatched > 0 || cooperative_hide_sent;
214    Ok(DeleteOutcome {
215        wraps_total,
216        wraps_dispatched,
217        cooperative_hide_sent,
218        blobs_dispatched: 0,
219        any_network_action,
220    })
221}
222
223/// Delete a DM someone sent us. Its gift wrap is addressed to us, so our key deletes our copy
224/// from relays (NIP-59), and a hide request to ourselves takes it off our other devices. The
225/// sender's copies are theirs to delete.
226pub async fn delete_received_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
227    let client = nostr_client().ok_or("Not logged in")?;
228    let rumor_hex = rumor_id.to_hex();
229    // Tombstone first, as for our own: another wrap of it re-served later must not bring it back.
230    if let Err(e) = crate::db::events::add_message_tombstone(&rumor_hex) {
231        crate::log_warn!("[NIP-17 delete] tombstone write failed: {}", e);
232    }
233    crate::state::note_message_deleted(&rumor_hex);
234    let received = crate::db::events::wrapper_event_id_of(&rumor_hex);
235
236    // A downloaded file goes with it; the sender's upload is theirs, so Blossom is left alone.
237    let attachments = {
238        let state = crate::state::STATE.lock().await;
239        state.find_message(&rumor_hex).map(|(_, msg)| msg.attachments.clone()).unwrap_or_default()
240    };
241    delete_cached_attachment_files(&filter_unreferenced_attachments(&rumor_hex, attachments).await);
242
243    let (wraps_dispatched, wraps_total) = dispatch_wrap_deletions(&client, &[], received).await;
244    let cooperative_hide_sent = match publish_cooperative_hide(&client, rumor_id, None, 14).await {
245        Ok(()) => true,
246        Err(e) => {
247            crate::log_warn!("[NIP-17 delete] hide request to our devices failed: {}", e);
248            false
249        }
250    };
251    Ok(DeleteOutcome {
252        wraps_total,
253        wraps_dispatched,
254        cooperative_hide_sent,
255        blobs_dispatched: 0,
256        any_network_action: wraps_dispatched > 0 || cooperative_hide_sent,
257    })
258}
259
260/// A deletion of gift wraps: `k` names their kind, and it expires once nothing could
261/// still re-broadcast them.
262pub(crate) fn wrap_deletion(wrap_ids: &[EventId]) -> EventBuilder {
263    let expires = crate::clock::timestamp().as_secs().saturating_add(WRAP_DELETION_EXPIRY_SECS);
264    wrap_ids
265        .iter()
266        .fold(EventBuilder::new(Kind::EventDeletion, ""), |b, id| b.tag(Tag::event(*id)))
267        .tag(Tag::custom("k", ["1059"]))
268        .tag(Tag::expiration(Timestamp::from(expires)))
269}
270
271/// [`wrap_deletion`] signed by our own key, the `p`-tagged owner of the wraps it names: the
272/// one signer every relay honours. Refused when the session's identity moved meanwhile.
273async fn owner_deletion(wrap_ids: &[EventId], owner: &PublicKey) -> Result<Event, String> {
274    let deletion = crate::sign_builder(wrap_deletion(wrap_ids)).await?;
275    if deletion.pubkey != *owner {
276        return Err("the account changed before the deletion was signed".to_string());
277    }
278    Ok(deletion)
279}
280
281/// Take a message's wraps off the relays: our own copies with our own key, and every wrap whose
282/// single-use key we kept with that key too, best-effort, for relays still honouring an author's
283/// deletion. Returns (dispatched, known).
284async fn dispatch_wrap_deletions(
285    client: &Client,
286    keys: &[crate::db::nip17_keys::StoredWrapKey],
287    received: Option<EventId>,
288) -> (usize, usize) {
289    let Some(me) = my_public_key() else { return (0, keys.len()) };
290    let own = own_wraps(keys, received);
291    let known = own.len() + keys.iter().filter(|k| !own.contains(&k.wrap_event_id)).count();
292    let mut dispatched = 0usize;
293    for wrap_id in own {
294        // Signed now, while the account it belongs to is the one in use.
295        match owner_deletion(&[wrap_id], &me).await {
296            Ok(deletion) => {
297                let client = client.clone();
298                crate::db::spawn_bound(async move {
299                    delete_wrap_per_relay(&client, wrap_id, &deletion, &me, true).await;
300                });
301                dispatched += 1;
302            }
303            Err(e) => crate::log_warn!("[NIP-17 delete] our own copy {} stays: {}", wrap_id.to_hex(), e),
304        }
305    }
306    for stored in keys {
307        let deletion = match wrap_deletion(&[stored.wrap_event_id]).finalize_on_clock(&Keys::new(stored.secret.clone())) {
308            Ok(ev) => ev,
309            Err(e) => {
310                crate::log_warn!("[NIP-17 delete] failed to sign deletion for wrap {}: {}", stored.wrap_event_id.to_hex(), e);
311                continue;
312            }
313        };
314        let (client, wrap_id, owner) = (client.clone(), stored.wrap_event_id, stored.recipient_pubkey);
315        crate::db::spawn_bound(async move {
316            delete_wrap_per_relay(&client, wrap_id, &deletion, &owner, false).await;
317        });
318        dispatched += 1;
319    }
320    let wraps: Vec<EventId> = keys.iter().map(|k| k.wrap_event_id).collect();
321    if let Err(e) = crate::db::nip17_keys::purge_wrap_keys(&wraps) {
322        crate::log_warn!("[NIP-17 delete] failed to purge wrap keys: {}", e);
323    }
324    (dispatched, known)
325}
326
327/// A message's wraps addressed to us, which our own key deletes: our self-copies, and the one
328/// that brought it to this device, when one did.
329fn own_wraps(keys: &[crate::db::nip17_keys::StoredWrapKey], received: Option<EventId>) -> Vec<EventId> {
330    use crate::db::nip17_keys::WrapRole;
331    let mut own: Vec<EventId> = keys.iter().filter(|k| k.role == WrapRole::SelfSend).map(|k| k.wrap_event_id).collect();
332    if let Some(w) = received.filter(|w| !own.contains(w)) {
333        own.push(w);
334    }
335    own
336}
337
338/// Pending deletions of wraps addressed to us, gathered so a sync that meets many deleted
339/// messages signs one deletion, not one per wrap (a remote signer asks for each).
340struct ReceivedWrapDeletions;
341
342fn received_wrap_deletions() -> std::sync::Arc<std::sync::Mutex<Vec<EventId>>> {
343    crate::db::current_session().scoped::<ReceivedWrapDeletions, _>()
344}
345
346#[cfg(test)]
347pub(crate) fn queued_received_wrap_deletions() -> Vec<EventId> {
348    received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
349}
350
351/// Delete a wrap addressed to us that carried a message since deleted, with our own key: the
352/// copy a hide request asks us to take down, or one more copy of a message already gone.
353pub(crate) fn delete_received_wrap(wrap_id: EventId) {
354    let pending = received_wrap_deletions();
355    let first = {
356        let mut q = pending.lock().unwrap_or_else(|e| e.into_inner());
357        if q.contains(&wrap_id) {
358            return;
359        }
360        q.push(wrap_id);
361        q.len() == 1
362    };
363    if !first {
364        return;
365    }
366    crate::db::spawn_bound(async move {
367        crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
368        let wraps = std::mem::take(&mut *pending.lock().unwrap_or_else(|e| e.into_inner()));
369        let (Some(client), Some(me)) = (nostr_client(), my_public_key()) else { return };
370        for batch in wraps.chunks(WRAPS_PER_DELETION) {
371            match owner_deletion(batch, &me).await {
372                Ok(deletion) => publish_to_inbox(&client, &me, &deletion, true).await,
373                Err(e) => crate::log_warn!("[NIP-17 delete] {} received wrap(s) stay: {}", batch.len(), e),
374            }
375        }
376    });
377}
378
379/// Send `deletion` for `wrap_event_id` to each relay that holds it. A wrap published this
380/// session gets it from each relay as that relay confirms the wrap, so it never outruns the
381/// wrap; any other goes to `owner`'s inbox relays, where wraps addressed to them sit.
382/// `verify` asks each relay that acknowledges whether the wrap is really gone.
383async fn delete_wrap_per_relay(client: &Client, wrap_event_id: EventId, deletion: &Event, owner: &PublicKey, verify: bool) {
384    let Some(tracker) = get_publish_tracker(&wrap_event_id) else {
385        publish_to_inbox(client, owner, deletion, verify).await;
386        return;
387    };
388    let mut delivered = 0usize;
389    let mut cursor = 0usize;
390    while let Some(url) = tracker.next_success(&mut cursor).await {
391        let relay = client.relays().await.get(&url).cloned();
392        match relay {
393            Some(relay) if send_to_one_relay(client, &url, &relay, deletion, verify).await => delivered += 1,
394            Some(_) => {}
395            None => crate::log_warn!("[delete] relay {} not in pool — deletion not delivered", url),
396        }
397    }
398    crate::log_info!("[NIP-17 delete] wrap {} — deletion delivered to {} relay(s) via tracker", wrap_event_id.to_hex(), delivered);
399}
400
401/// Send `deletion` to every inbox relay of `owner`, connecting any not pooled for the call.
402async fn publish_to_inbox(client: &Client, owner: &PublicKey, deletion: &Event, verify: bool) {
403    let targets = resolve_gift_wrap_targets(client, owner).await;
404    let total = targets.resolved.len();
405    let mut delivered = 0usize;
406    for (url, relay) in &targets.resolved {
407        if send_to_one_relay(client, url, relay, deletion, verify).await {
408            delivered += 1;
409        }
410    }
411    teardown_gift_wrap_targets(client, &targets).await;
412    crate::log_info!("[NIP-17 delete] deletion {} delivered to {}/{} inbox relay(s)", deletion.id.to_hex(), delivered, total);
413}
414
415/// Best-effort delete of every cached attachment file for a message.
416/// Only unlinks files that canonicalize to a path under Vector's
417/// managed download directory — files the user has moved or copied
418/// elsewhere are never touched. Symlink and `..` escape attempts are
419/// rejected by the canonicalize check.
420///
421/// Used by both sender-initiated deletes (so the user's own cached
422/// copy disappears alongside the network deletion) and cooperative-
423/// hide receivers (so the recipient's downloaded copy goes when the
424/// sender asks for the message to disappear). Mirrors the
425/// "delete-for-everyone" semantics of iMessage/Signal at the file
426/// layer, scoped to Vector's own cache.
427pub fn delete_cached_attachment_files_pub(attachments: &[crate::types::Attachment]) {
428    delete_cached_attachment_files(attachments);
429}
430
431/// Filter `attachments` down to those NOT referenced by any OTHER
432/// undeleted message in STATE.
433///
434/// Vector dedupes uploads by SHA-256 hash: re-sending the same file
435/// reuses the on-disk cache + the same Blossom URL across multiple
436/// messages. Without this filter, deleting one of those messages
437/// would unlink the cached file (or DELETE the Blossom blob) even
438/// though sibling messages still reference it — the user's other
439/// copies would 404 and lose their local preview.
440///
441/// `excluding_message_id` is the id of the message we're deleting,
442/// so it doesn't count as a "reference" to itself when determining
443/// whether the attachment is shared.
444pub async fn filter_unreferenced_attachments(
445    excluding_message_id: &str,
446    attachments: Vec<crate::types::Attachment>,
447) -> Vec<crate::types::Attachment> {
448    if attachments.is_empty() {
449        return attachments;
450    }
451    // STATE pass first, lock released before any DB read (lock-order hygiene).
452    let state_referenced: Vec<bool> = {
453        let state = crate::state::STATE.lock().await;
454        attachments
455            .iter()
456            .map(|att| {
457                // Dedup key: the attachment's SHA-256 (Attachment.id).
458                // Empty id can't be matched, so treat as unique.
459                let hash = &*att.id;
460                if hash.is_empty() {
461                    return false;
462                }
463                state.chats.iter().any(|chat| {
464                    chat.iter_compact().any(|m| {
465                        let msg_id_hex = m.id_hex();
466                        msg_id_hex != excluding_message_id
467                            && m.attachments.iter().any(|a| a.id_eq(hash))
468                    })
469                })
470            })
471            .collect()
472    };
473    // DB pass second: STATE windows to recent messages, so a reference in an
474    // older message is invisible there — the ledger is the authority. A read
475    // failure counts as referenced: deleting less is recoverable, deleting a
476    // still-shared file is not.
477    attachments
478        .into_iter()
479        .zip(state_referenced)
480        .filter(|(att, in_state)| {
481            if *in_state {
482                return false;
483            }
484            let hash = &*att.id;
485            if hash.is_empty() {
486                return true;
487            }
488            !crate::db::attachments::hash_referenced_elsewhere(hash, excluding_message_id).unwrap_or(true)
489        })
490        .map(|(att, _)| att)
491        .collect()
492}
493
494/// Of these attachments' remote urls, the ones no OTHER event still references
495/// — the only ones a delete may scrub from Blossom. One blob backs many
496/// messages under smart-forward, and the shared copy must outlive every send
497/// but the last. A ledger read failure scrubs nothing, same reasoning as above.
498pub fn scrub_safe_urls(attachments: &[crate::types::Attachment], excluding_event_id: &str) -> Vec<String> {
499    let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
500    if urls.is_empty() {
501        return urls;
502    }
503    crate::db::attachments::urls_unreferenced_elsewhere(&urls, excluding_event_id).unwrap_or_default()
504}
505
506fn delete_cached_attachment_files(attachments: &[crate::types::Attachment]) {
507    if attachments.is_empty() {
508        return;
509    }
510    let hashes: Vec<[u8; 32]> = attachments.iter().filter_map(|a| crate::simd::hex::hex_to_bytes_32_checked(&a.id)).collect();
511    for hash in &hashes {
512        crate::media::pending::forget(hash);
513        #[cfg(not(target_arch = "wasm32"))]
514        crate::media::store::forget(hash);
515        #[cfg(target_arch = "wasm32")]
516        {
517            let hash = *hash;
518            crate::media::store::stop_holding(&hash);
519            crate::db::spawn_bound(async move { crate::media::store::forget(&hash).await });
520        }
521    }
522    #[cfg(target_arch = "wasm32")]
523    {
524        let dir = crate::db::get_download_dir();
525        let paths: Vec<std::path::PathBuf> = attachments
526            .iter()
527            .map(|a| std::path::PathBuf::from(&*a.path))
528            .filter(|p| p.starts_with(&dir) && !p.components().any(|c| c == std::path::Component::ParentDir))
529            .collect();
530        crate::db::spawn_bound(async move {
531            for p in paths {
532                crate::webfiles::remove(&p).await;
533            }
534        });
535    }
536    #[cfg(not(target_arch = "wasm32"))]
537    delete_cached_attachment_files_native(attachments);
538    // Last, after every other place it could be read from: a copy or a read finishing meanwhile
539    // finds its picture gone and leaves it so.
540    let ram = crate::media::ram::cache();
541    for hash in &hashes {
542        ram.remove(hash);
543    }
544}
545
546#[cfg(not(target_arch = "wasm32"))]
547fn delete_cached_attachment_files_native(attachments: &[crate::types::Attachment]) {
548    let roots: Vec<std::path::PathBuf> = crate::db::download_roots().iter().filter_map(|r| r.canonicalize().ok()).collect();
549    if roots.is_empty() {
550        return;
551    }
552    for att in attachments {
553        if att.path.is_empty() {
554            continue;
555        }
556        let candidate = match std::path::PathBuf::from(&*att.path).canonicalize() {
557            Ok(p) => p,
558            // File already gone, or path unresolvable — nothing to do.
559            Err(_) => continue,
560        };
561        if !roots.iter().any(|root| candidate.starts_with(root)) {
562            // User-managed path (moved/copied out of Vector's cache);
563            // never touch.
564            continue;
565        }
566        if crate::db::saved::is_saved(&candidate.to_string_lossy()).unwrap_or(true) {
567            continue;
568        }
569        if let Err(e) = std::fs::remove_file(&candidate) {
570            crate::log_warn!(
571                "[delete] failed to remove cached attachment {}: {}",
572                candidate.display(),
573                e
574            );
575        }
576    }
577}
578
579/// Direct publish to a single relay handle. Returns true if the relay
580/// acknowledged. Returns false if the publish hit a non-rate-limit
581/// error, or rate-limit retries were exhausted.
582///
583/// Per-URL outcome is logged so the user can pinpoint which relay is
584/// keeping a wrap alive after deletion — relays that ACK a NIP-09 but
585/// don't actually drop the event are non-compliant; the
586/// `verify_relay_dropped` probe scheduled below is the receipt that
587/// identifies them.
588///
589/// Rate-limit handling: relays like damus.io will reject NIP-09s with
590/// "rate-limited: you are noting too much" when the user deletes a
591/// few messages in quick succession. The deletion isn't a real
592/// failure, just back-pressure — so we wait and retry up to
593/// `MAX_RATELIMIT_RETRIES` times (each retry sleeps 30s). The whole
594/// loop runs inside the per-relay deletion task (already spawned), so
595/// the user's UX is unaffected; the wrap stays on the relay only
596/// until we get through.
597///
598/// With `verify`, an ACK schedules a probe (~2s later) asking the relay whether the wraps
599/// are really gone. Off for a best-effort author deletion, which a relay that follows the
600/// spec acknowledges and ignores.
601async fn send_to_one_relay(client: &Client, url: &RelayUrl, relay: &Relay, event: &Event, verify: bool) -> bool {
602    /// Max attempts to push past a rate-limit. With 30s between
603    /// attempts that's a 10-minute window — generous for any sane
604    /// per-IP rate limit. If the relay is still rate-limiting us
605    /// after that, something else is wrong and we give up so the
606    /// task doesn't loop forever.
607    const MAX_RATELIMIT_RETRIES: u32 = 20;
608    /// Pause between rate-limit retries.
609    const RATELIMIT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);
610
611    let mut retries = 0u32;
612    let wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
613    loop {
614        match relay.send_event(event).ok_timeout(wait).authentication_timeout(wait).await {
615            Ok(_) => {
616                if retries == 0 {
617                    crate::log_info!("[delete] relay {} ACK'd NIP-09", url);
618                } else {
619                    crate::log_info!(
620                        "[delete] relay {} ACK'd NIP-09 (after {} retr{})",
621                        url,
622                        retries,
623                        if retries == 1 { "y" } else { "ies" }
624                    );
625                }
626                schedule_verify(client, url, event, verify);
627                return true;
628            }
629            Err(e) => {
630                let err_str = e.to_string();
631                let lc = err_str.to_ascii_lowercase();
632                let is_rate_limit = lc.contains("rate-limit")
633                    || lc.contains("rate limit")
634                    || lc.contains("noting too much");
635                let is_transient = lc.contains("timeout")
636                    || lc.contains("timed out")
637                    || lc.contains("connection reset")
638                    || lc.contains("connection refused")
639                    || lc.contains("connection closed")
640                    || lc.contains("broken pipe")
641                    || lc.contains("not connected");
642                let retryable = is_rate_limit || is_transient;
643                if retryable && retries < MAX_RATELIMIT_RETRIES {
644                    retries += 1;
645                    let reason = if is_rate_limit { "rate-limited" } else { "transient error" };
646                    crate::log_warn!(
647                        "[delete] relay {} {} (attempt {}/{}; err: {}); waiting {}s",
648                        url,
649                        reason,
650                        retries,
651                        MAX_RATELIMIT_RETRIES,
652                        err_str,
653                        RATELIMIT_BACKOFF.as_secs()
654                    );
655                    crate::rt::time::sleep(RATELIMIT_BACKOFF).await;
656                    continue;
657                }
658                if retryable {
659                    crate::log_warn!(
660                        "[delete] relay {} still failing after {} retries ({}); scheduling verify probe in case it eventually accepted",
661                        url,
662                        retries,
663                        err_str
664                    );
665                    // Even though our publish never ACK'd, the relay may
666                    // have actually received and processed the event
667                    // (timeouts often mean "ACK lost on the way back").
668                    // Schedule a verify probe so we still log whether the
669                    // wrap is gone.
670                    schedule_verify(client, url, event, verify);
671                } else {
672                    crate::log_warn!("[delete] relay {} rejected NIP-09: {}", url, err_str);
673                }
674                return false;
675            }
676        }
677    }
678}
679
680/// The wraps a deletion names, from its `e` tags.
681fn deletion_targets(deletion: &Event) -> Vec<EventId> {
682    deletion
683        .tags
684        .iter()
685        .filter_map(|tag| {
686            let s = tag.as_slice();
687            (s.len() >= 2 && s[0] == "e").then(|| EventId::from_hex(&s[1]).ok()).flatten()
688        })
689        .collect()
690}
691
692fn schedule_verify(client: &Client, url: &RelayUrl, deletion: &Event, verify: bool) {
693    let wraps = deletion_targets(deletion);
694    if !verify || wraps.is_empty() {
695        return;
696    }
697    let (client, url) = (client.clone(), url.clone());
698    crate::db::spawn_bound(async move {
699        verify_relay_dropped(&client, &url, &wraps).await;
700    });
701}
702
703/// 2s after a relay ACKs a deletion, ask it whether the wraps are actually gone. Logs a clear
704/// "GONE" or "STILL PRESENT" so a relay that acknowledges and keeps them is easy to name.
705async fn verify_relay_dropped(client: &Client, url: &RelayUrl, wraps: &[EventId]) {
706    crate::rt::time::sleep(std::time::Duration::from_secs(2)).await;
707    let Some(relay) = client.relays().await.get(url).cloned() else { return };
708    let filter = Filter::new().ids(wraps.iter().copied());
709    match relay
710        .fetch_events(filter)
711        .timeout(std::time::Duration::from_secs(5))
712        .policy(ReqExitPolicy::ExitOnEOSE)
713        .await
714    {
715        Ok(events) => {
716            let kept = events.len();
717            if kept > 0 {
718                crate::log_warn!("[delete-verify] relay {} STILL HAS {}/{} wrap(s) after acknowledging their deletion", url, kept, wraps.len());
719            } else {
720                crate::log_info!("[delete-verify] relay {} confirmed {} wrap(s) GONE", url, wraps.len());
721            }
722        }
723        Err(e) => crate::log_warn!("[delete-verify] relay {} probe failed: {}", url, e),
724    }
725}
726
727/// Publish the hide request: a kind-5 rumor signed by the user's main key, gift-wrapped to
728/// the recipient and to self. Rumor and wrap both expire after 30 days, so relays drop it.
729async fn publish_cooperative_hide(
730    client: &Client,
731    target_rumor_id: &EventId,
732    recipient: Option<&PublicKey>,
733    original_kind: u16,
734) -> Result<(), String> {
735    let my_pk = my_public_key().ok_or("Public key not set")?;
736    let now = crate::clock::now_secs();
737    let expiration_ts = now + COOPERATIVE_HIDE_EXPIRY_SECS;
738
739    // Build the kind-5 rumor (signed by our main key via the gift-wrap
740    // path's seal step). Reference the inner rumor id with `e`, hint at
741    // the original kind via `k` (14 = DM message, 7 = reaction), expire
742    // after 30 days. The `k` lets the receiver remove the right thing.
743    let rumor = EventBuilder::new(Kind::EventDeletion, "")
744        .tag(Tag::event(*target_rumor_id))
745        .tag(Tag::custom("k", [original_kind.to_string()]))
746        .tag(Tag::expiration(Timestamp::from(expiration_ts)))
747        .finalize_unsigned_with_id(my_pk);
748
749    // Wrap and send to the recipient, when there is one, and to self so the user's other
750    // devices drop it too. Best-effort.
751    let expires = || [Tag::expiration(Timestamp::from(expiration_ts))];
752    let to_them = match recipient {
753        Some(recipient) => send_gift_wrap(client, recipient, rumor.clone(), expires()).await.is_ok(),
754        None => false,
755    };
756    let to_me = send_gift_wrap(client, &my_pk, rumor, expires()).await.is_ok();
757    if !to_them && !to_me {
758        return Err("no cooperative-hide delivery went out".to_string());
759    }
760    Ok(())
761}
762
763#[cfg(test)]
764pub(crate) fn pending_received_wrap_deletions() -> Vec<EventId> {
765    received_wrap_deletions().lock().unwrap_or_else(|e| e.into_inner()).clone()
766}
767
768#[cfg(test)]
769mod tests {
770    use super::*;
771    use crate::db::nip17_keys::{StoredWrapKey, WrapRole};
772
773    fn stored(role: WrapRole) -> StoredWrapKey {
774        let k = Keys::generate();
775        StoredWrapKey {
776            wrap_event_id: EventBuilder::new(Kind::GiftWrap, "").finalize(&k).unwrap().id,
777            rumor_id: EventId::from_byte_array([0; 32]),
778            recipient_pubkey: Keys::generate().public_key(),
779            role,
780            secret: k.secret_key().clone(),
781            relay_urls: Vec::new(),
782        }
783    }
784
785    #[test]
786    fn a_wrap_deletion_names_its_wraps_and_expires() {
787        let wraps = [EventId::from_byte_array([0; 32]), EventId::from_byte_array([7; 32])];
788        let ev = wrap_deletion(&wraps).finalize(&Keys::generate()).unwrap();
789        assert_eq!(ev.kind, Kind::EventDeletion);
790        let tag = |name: &str| ev.tags.iter().filter(|t| t.as_slice()[0] == name).map(|t| t.as_slice()[1].clone()).collect::<Vec<_>>();
791        assert_eq!(tag("e"), wraps.iter().map(|w| w.to_hex()).collect::<Vec<_>>());
792        assert_eq!(tag("k"), vec!["1059".to_string()]);
793        let expires: u64 = tag("expiration")[0].parse().unwrap();
794        let now = Timestamp::now().as_secs();
795        assert!(expires > now + WRAP_DELETION_EXPIRY_SECS - 60 && expires <= now + WRAP_DELETION_EXPIRY_SECS, "it leaves the relays in time");
796    }
797
798    #[test]
799    fn our_own_key_deletes_the_copies_addressed_to_us() {
800        let (mine, theirs, retry) = (stored(WrapRole::SelfSend), stored(WrapRole::Recipient), stored(WrapRole::Retry));
801        let keys = [mine.clone(), theirs, retry];
802        let received = EventId::from_byte_array([9; 32]);
803        assert_eq!(own_wraps(&keys, Some(received)), vec![mine.wrap_event_id, received], "our self-copy and the wrap that reached us");
804        assert_eq!(own_wraps(&keys, Some(mine.wrap_event_id)), vec![mine.wrap_event_id], "named once");
805        assert_eq!(own_wraps(&keys, None), vec![mine.wrap_event_id]);
806    }
807
808    #[tokio::test]
809    async fn an_owner_deletion_is_signed_by_us_and_never_for_someone_else() {
810        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
811        let me = Keys::generate();
812        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
813        crate::state::set_my_public_key(me.public_key());
814        let wraps = [EventId::from_byte_array([3; 32])];
815        let deletion = owner_deletion(&wraps, &me.public_key()).await.unwrap();
816        assert_eq!(deletion.pubkey, me.public_key());
817        assert!(deletion.verify().is_ok());
818        assert!(owner_deletion(&wraps, &Keys::generate().public_key()).await.is_err(), "a swapped account signs nothing for the last one");
819    }
820}