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