Skip to main content

vector_core/
deletion.rs

1//! Message deletion — Vector's "delete from network" capability.
2//!
3//! NIP-17 DMs are wrapped in kind-1059 gift-wrap events signed by an
4//! ephemeral key. The standard NIP-59 implementation discards that key
5//! after signing, making the wrap permanently un-deletable: privacy by
6//! obscurity, since the wrap continues to sit on inbox relays
7//! decryptable by anyone with the recipient key.
8//!
9//! Vector retains the ephemeral key (see `db::nip17_keys`) so that on
10//! user request we can publish an author-signed NIP-09 deletion against
11//! every wrap and have relays drop it. Privacy by control.
12//!
13//! Scope: this module deletes the user's **own** outbound messages. It
14//! does not (and cannot) delete messages sent by others — those wraps
15//! were signed by ephemeral keys we never held.
16
17use crate::event_ext::FinalizeUnsignedWithId;
18use nostr_sdk::prelude::*;
19
20use crate::inbox_relays::{get_publish_tracker, send_gift_wrap};
21use crate::state::{my_public_key, nostr_client};
22
23/// Cooperative-hide notice expiry: 30 days. After this window relays
24/// drop the gift-wrap (NIP-40) and clients that come online later won't
25/// see the deletion notice — but they also won't see the original wrap
26/// (it was nuked from relays in Layer 1), so there's nothing to delete
27/// on their side anyway. Recipients who already fetched and decrypted
28/// the original need the notice to drop their local copy; 30 days is
29/// generous coverage for "live" use.
30const COOPERATIVE_HIDE_EXPIRY_SECS: u64 = 60 * 60 * 24 * 30;
31
32/// Outcome of a delete-own-* operation.
33///
34/// Vector's deletion is layered and best-effort: any subset of the
35/// layers may be available depending on whether we hold retained
36/// ephemeral keys, whether the message has attachments, etc. The
37/// outcome reports what was attempted so the caller can show an
38/// honest post-action summary.
39#[derive(serde::Serialize, Debug, Clone, Default)]
40pub struct DeleteOutcome {
41    /// Number of retained wraps for which we dispatched a NIP-09
42    /// deletion task (Layer 1 — relay-level nuke). Zero when the
43    /// message predates retention or was sent from a different device.
44    pub wraps_dispatched: usize,
45    /// Total wraps we had keys for at delete time (= wraps_dispatched
46    /// for now; reserved for future "skipped due to error" reporting).
47    pub wraps_total: usize,
48    /// Whether we sent a cooperative-hide notice (Layer 2). Always true
49    /// for own deletions in groups/DMs that succeed; tells live Vector
50    /// clients to drop the row from local UI.
51    pub cooperative_hide_sent: bool,
52    /// Number of Blossom blobs we asked the upload server to delete.
53    /// Best-effort: actual server response is logged, not surfaced.
54    pub blobs_dispatched: usize,
55    /// True iff at least one of (wrap nuke, cooperative hide, blob
56    /// delete) was attempted. False means the only thing the operation
57    /// could do is a local-state drop — caller can use this to surface
58    /// "we couldn't actually remove this from the network" copy.
59    pub any_network_action: bool,
60}
61
62/// Delete an outbound DM from the network by publishing NIP-09
63/// deletions against every retained gift-wrap for `rumor_id`.
64///
65/// Per-relay event-driven dispatch: the publish/delete race is closed
66/// by listening to each wrap's `WrapPublishTracker` (registered at
67/// send time). NIP-09 fires at each relay only **after** that relay
68/// has confirmed receiving the wrap — relays that haven't received it
69/// yet wait until they do, relays that already have it get NIP-09
70/// immediately, relays where the publish failed get nothing (no event
71/// there to delete).
72///
73/// Each per-wrap deletion runs as a background tokio task so the API
74/// returns immediately. Local UI removal happens synchronously; the
75/// caller's UX never blocks on relay roundtrips.
76///
77/// Returns `Err` if no retained keys exist for the rumor (predates
78/// the retention feature, sent from a different device, etc).
79pub async fn delete_own_dm(rumor_id: &EventId) -> Result<DeleteOutcome, String> {
80    let client = nostr_client().ok_or("Not logged in")?;
81    // Session captured for the relay-nuke loop — without this, an
82    // account-A wrap-key purge could land in account B's nip17_keys.
83    let session = crate::state::SessionGuard::capture();
84    let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(rumor_id)
85        .unwrap_or_default();
86
87    // Snapshot the message + recipient BEFORE any state/DB cleanup.
88    // Attachment URLs feed Blossom DELETE; the attachments themselves
89    // feed local-cache file removal; recipient pubkey feeds the
90    // cooperative-hide gift wrap. We try to recover all three even when
91    // no retained keys exist (older messages, pre-retention sends).
92    //
93    // INVARIANT: `chat.id` for a DM is the counterpart's npub. The
94    // `find_message` lookup here is unscoped, but `delete_own_dm` is
95    // only ever called from the DM branch of the Tauri command — the
96    // group branch routes to `delete_own_group_message` instead.
97    // `from_bech32` silently yields `None` if the invariant ever
98    // breaks; that just disables Layer 2 cooperative-hide for the
99    // call. Layer 1 (retained-key relay nuke) and Layer 3 (Blossom)
100    // remain functional.
101    let (all_attachments, recipient_from_state) = {
102        let state = crate::state::STATE.lock().await;
103        match state.find_message(&rumor_id.to_hex()) {
104            Some((chat, msg)) => {
105                debug_assert!(
106                    matches!(chat.chat_type, crate::chat::ChatType::DirectMessage),
107                    "delete_own_dm called on non-DM chat — caller bug"
108                );
109                let recipient = nostr_sdk::prelude::PublicKey::from_bech32(&chat.id).ok();
110                (msg.attachments.clone(), recipient)
111            }
112            None => (Vec::new(), None),
113        }
114    };
115
116    // Refcount filter: drop attachments still referenced by sibling
117    // messages so we don't yank cached files / Blossom blobs from
118    // messages that still need them. Vector dedupes uploads by SHA-256:
119    // re-sending the same file produces multiple messages pointing at
120    // the same cached path AND the same Blossom blob. Deleting one
121    // shouldn't delete the underlying resources.
122    let unique_attachments = filter_unreferenced_attachments(
123        &rumor_id.to_hex(),
124        all_attachments,
125    ).await;
126
127    // Local cache nuke (canonicalize + managed-dir-only inside helper).
128    delete_cached_attachment_files(&unique_attachments);
129
130    // Blossom URLs derived from the filtered (refcount-aware) set — the
131    // primary plus every mirror (same hash, other origins).
132    let attachment_urls: Vec<String> = unique_attachments
133        .iter()
134        .flat_map(|a| a.all_urls().map(str::to_string))
135        .collect();
136
137    let wraps_total = keys.len();
138    let mut wraps_dispatched = 0usize;
139
140    // Layer 1 — relay-level nuke. Only possible when we still hold
141    // retained wrap keys for this rumor.
142    for stored in keys.iter() {
143        let client = client.clone();
144        let task_session = session;
145        let wrap_event_id = stored.wrap_event_id;
146        let secret = stored.secret.clone();
147        let relay_urls = stored.relay_urls.clone();
148        tokio::spawn(async move {
149            if !task_session.is_valid() { return; }
150            delete_wrap_per_relay(&client, wrap_event_id, secret, relay_urls).await;
151            if !task_session.is_valid() { return; }
152            if let Err(e) = crate::db::nip17_keys::purge_wrap_keys(&[wrap_event_id]) {
153                crate::log_warn!("[NIP-17 delete] failed to purge wrap key: {}", e);
154            }
155        });
156        wraps_dispatched += 1;
157    }
158
159    // Layer 2 — cooperative hide. Always send a notice if we know the
160    // recipient: tells live Vector clients to drop their local copy.
161    // Prefer the recipient pubkey from a retained wrap key if we have
162    // one (recipient role); fall back to the chat counterpart from
163    // STATE. The notice itself is signed by our main key, so this
164    // works even when retained wrap keys are missing.
165    let cooperative_recipient = keys
166        .iter()
167        .find(|k| {
168            k.role == crate::db::nip17_keys::WrapRole::Recipient
169                || k.role == crate::db::nip17_keys::WrapRole::Retry
170        })
171        .map(|k| k.recipient_pubkey)
172        .or(recipient_from_state);
173
174    let mut cooperative_hide_sent = false;
175    if let Some(recipient) = cooperative_recipient {
176        match publish_cooperative_hide(&client, rumor_id, &recipient, 14).await {
177            Ok(()) => cooperative_hide_sent = true,
178            Err(e) => crate::log_warn!("[NIP-17 delete] cooperative-hide notice failed: {}", e),
179        }
180    }
181
182    // Layer 3 — Blossom blob delete. Route through the active client
183    // signer so bunker accounts sign DELETE auth under the user's
184    // identity (Blossom enforces "uploader == authorized signer";
185    // signing with the NIP-46 client keypair returns 401).
186    let mut blobs_dispatched = 0usize;
187    if !attachment_urls.is_empty() {
188        if let Ok(signer) = crate::signer::active_signer() {
189            blobs_dispatched = attachment_urls.len();
190            crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
191        }
192    }
193
194    let any_network_action =
195        wraps_dispatched > 0 || cooperative_hide_sent || blobs_dispatched > 0;
196
197    Ok(DeleteOutcome {
198        wraps_total,
199        wraps_dispatched,
200        cooperative_hide_sent,
201        blobs_dispatched,
202        any_network_action,
203    })
204}
205
206/// Revoke one of OUR OWN DM reactions. Mirrors `delete_own_dm` but the
207/// target is a kind-7 reaction rumor: Layer 1 nukes each retained gift-wrap
208/// from its relays via the stored ephemeral key; Layer 2 sends a cooperative
209/// hide (k=7) to the counterpart + self so live clients drop the chip. No
210/// Blossom layer — reactions carry no attachments. `recipient` is the DM
211/// counterpart, used for the cooperative hide when no recipient-role wrap key
212/// is retained (e.g. only the self-wrap survived).
213pub async fn delete_own_reaction(
214    reaction_id: &EventId,
215    recipient: PublicKey,
216) -> Result<DeleteOutcome, String> {
217    let client = nostr_client().ok_or("Not logged in")?;
218    let session = crate::state::SessionGuard::capture();
219    let keys = crate::db::nip17_keys::get_wrap_keys_for_rumor(reaction_id)
220        .unwrap_or_default();
221
222    let wraps_total = keys.len();
223    let mut wraps_dispatched = 0usize;
224
225    // Layer 1 — relay-level nuke per retained wrap key.
226    for stored in keys.iter() {
227        let client = client.clone();
228        let task_session = session;
229        let wrap_event_id = stored.wrap_event_id;
230        let secret = stored.secret.clone();
231        let relay_urls = stored.relay_urls.clone();
232        tokio::spawn(async move {
233            if !task_session.is_valid() { return; }
234            delete_wrap_per_relay(&client, wrap_event_id, secret, relay_urls).await;
235            if !task_session.is_valid() { return; }
236            if let Err(e) = crate::db::nip17_keys::purge_wrap_keys(&[wrap_event_id]) {
237                crate::log_warn!("[reaction delete] failed to purge wrap key: {}", e);
238            }
239        });
240        wraps_dispatched += 1;
241    }
242
243    // Layer 2 — cooperative hide (k=7). Prefer a recipient pulled from a
244    // retained recipient/retry wrap key; fall back to the passed-in
245    // counterpart. The notice is signed by our main key, so it works even
246    // when no wrap keys survive (pre-retention reactions stay undeletable at
247    // the relay layer, but a live counterpart still drops the chip).
248    let cooperative_recipient = keys
249        .iter()
250        .find(|k| {
251            k.role == crate::db::nip17_keys::WrapRole::Recipient
252                || k.role == crate::db::nip17_keys::WrapRole::Retry
253        })
254        .map(|k| k.recipient_pubkey)
255        .unwrap_or(recipient);
256
257    let mut cooperative_hide_sent = false;
258    match publish_cooperative_hide(&client, reaction_id, &cooperative_recipient, 7).await {
259        Ok(()) => cooperative_hide_sent = true,
260        Err(e) => crate::log_warn!("[reaction delete] cooperative-hide failed: {}", e),
261    }
262
263    let any_network_action = wraps_dispatched > 0 || cooperative_hide_sent;
264    Ok(DeleteOutcome {
265        wraps_total,
266        wraps_dispatched,
267        cooperative_hide_sent,
268        blobs_dispatched: 0,
269        any_network_action,
270    })
271}
272
273/// Per-relay deletion for a single wrap. Subscribes to the wrap's
274/// publish tracker and fires NIP-09 to each relay as soon as that
275/// relay confirms receiving the wrap. Relays where the publish failed
276/// don't get NIP-09 (no event there to delete).
277///
278/// If no live tracker exists (cross-restart: the original publishes
279/// completed in a previous session), falls back to a best-effort
280/// broadcast against every targeted relay. Relays that don't have
281/// the wrap will no-op the deletion; that's safe.
282async fn delete_wrap_per_relay(
283    client: &Client,
284    wrap_event_id: EventId,
285    secret: SecretKey,
286    targeted_relays: Vec<String>,
287) {
288    let ephemeral_keys = Keys::new(secret);
289    let deletion = match EventBuilder::new(Kind::EventDeletion, "")
290        .tag(Tag::event(wrap_event_id))
291        .tag(Tag::custom("k", ["1059"]))
292        .finalize(&ephemeral_keys)
293    {
294        Ok(ev) => ev,
295        Err(e) => {
296            eprintln!(
297                "[NIP-17 delete] failed to sign deletion for wrap {}: {}",
298                wrap_event_id.to_hex(),
299                e
300            );
301            return;
302        }
303    };
304
305    if let Some(tracker) = get_publish_tracker(&wrap_event_id) {
306        // Live tracker: walk the success stream as relays settle.
307        let mut delivered = 0usize;
308        let mut cursor = 0usize;
309        while let Some(url) = tracker.next_success(&mut cursor).await {
310            if send_to_one_relay(client, &url, &deletion).await {
311                delivered += 1;
312            }
313        }
314        crate::log_info!(
315            "[NIP-17 delete] wrap {} — NIP-09 delivered to {} relay(s) via tracker",
316            wrap_event_id.to_hex(),
317            delivered
318        );
319    } else {
320        // No tracker (cross-restart or already-GC'd). Best-effort
321        // broadcast: fire NIP-09 at every targeted relay; relays
322        // that lack the wrap silently no-op.
323        let urls: Vec<RelayUrl> = targeted_relays
324            .iter()
325            .filter_map(|s| RelayUrl::parse(s).ok())
326            .collect();
327        let total = urls.len();
328        let mut delivered = 0usize;
329        for url in urls {
330            if send_to_one_relay(client, &url, &deletion).await {
331                delivered += 1;
332            }
333        }
334        crate::log_info!(
335            "[NIP-17 delete] wrap {} — fallback broadcast: NIP-09 delivered to {}/{} relay(s)",
336            wrap_event_id.to_hex(),
337            delivered,
338            total
339        );
340    }
341}
342
343/// Best-effort delete of every cached attachment file for a message.
344/// Only unlinks files that canonicalize to a path under Vector's
345/// managed download directory — files the user has moved or copied
346/// elsewhere are never touched. Symlink and `..` escape attempts are
347/// rejected by the canonicalize check.
348///
349/// Used by both sender-initiated deletes (so the user's own cached
350/// copy disappears alongside the network deletion) and cooperative-
351/// hide receivers (so the recipient's downloaded copy goes when the
352/// sender asks for the message to disappear). Mirrors the
353/// "delete-for-everyone" semantics of iMessage/Signal at the file
354/// layer, scoped to Vector's own cache.
355pub fn delete_cached_attachment_files_pub(attachments: &[crate::types::Attachment]) {
356    delete_cached_attachment_files(attachments);
357}
358
359/// Filter `attachments` down to those NOT referenced by any OTHER
360/// undeleted message in STATE.
361///
362/// Vector dedupes uploads by SHA-256 hash: re-sending the same file
363/// reuses the on-disk cache + the same Blossom URL across multiple
364/// messages. Without this filter, deleting one of those messages
365/// would unlink the cached file (or DELETE the Blossom blob) even
366/// though sibling messages still reference it — the user's other
367/// copies would 404 and lose their local preview.
368///
369/// `excluding_message_id` is the id of the message we're deleting,
370/// so it doesn't count as a "reference" to itself when determining
371/// whether the attachment is shared.
372pub async fn filter_unreferenced_attachments(
373    excluding_message_id: &str,
374    attachments: Vec<crate::types::Attachment>,
375) -> Vec<crate::types::Attachment> {
376    if attachments.is_empty() {
377        return attachments;
378    }
379    let state = crate::state::STATE.lock().await;
380    attachments
381        .into_iter()
382        .filter(|att| {
383            // Dedup key: the attachment's SHA-256 (Attachment.id).
384            // Empty id can't be matched, so treat as unique.
385            let hash = &*att.id;
386            if hash.is_empty() {
387                return true;
388            }
389            let referenced_elsewhere = state.chats.iter().any(|chat| {
390                chat.iter_compact().any(|m| {
391                    let msg_id_hex = m.id_hex();
392                    msg_id_hex != excluding_message_id
393                        && m.attachments.iter().any(|a| a.id_eq(hash))
394                })
395            });
396            !referenced_elsewhere
397        })
398        .collect()
399}
400
401fn delete_cached_attachment_files(attachments: &[crate::types::Attachment]) {
402    if attachments.is_empty() {
403        return;
404    }
405    let download_dir = match crate::db::get_download_dir().canonicalize() {
406        Ok(d) => d,
407        Err(_) => return,
408    };
409    for att in attachments {
410        if att.path.is_empty() {
411            continue;
412        }
413        let candidate = match std::path::PathBuf::from(&*att.path).canonicalize() {
414            Ok(p) => p,
415            // File already gone, or path unresolvable — nothing to do.
416            Err(_) => continue,
417        };
418        if !candidate.starts_with(&download_dir) {
419            // User-managed path (moved/copied out of Vector's cache);
420            // never touch.
421            continue;
422        }
423        if let Err(e) = std::fs::remove_file(&candidate) {
424            crate::log_warn!(
425                "[delete] failed to remove cached attachment {}: {}",
426                candidate.display(),
427                e
428            );
429        }
430    }
431}
432
433/// Direct publish to a single relay handle. Returns true if the relay
434/// acknowledged. Returns false if the relay isn't in our pool, the
435/// publish hit a non-rate-limit error, or rate-limit retries were
436/// exhausted.
437///
438/// Per-URL outcome is logged so the user can pinpoint which relay is
439/// keeping a wrap alive after deletion — relays that ACK a NIP-09 but
440/// don't actually drop the event are non-compliant; the
441/// `verify_relay_dropped` probe scheduled below is the receipt that
442/// identifies them.
443///
444/// Rate-limit handling: relays like damus.io will reject NIP-09s with
445/// "rate-limited: you are noting too much" when the user deletes a
446/// few messages in quick succession. The deletion isn't a real
447/// failure, just back-pressure — so we wait and retry up to
448/// `MAX_RATELIMIT_RETRIES` times (each retry sleeps 30s). The whole
449/// loop runs inside the per-relay deletion task (already spawned), so
450/// the user's UX is unaffected; the wrap stays on the relay only
451/// until we get through.
452///
453/// On successful ACK, schedules a verification probe (~2s later) that
454/// re-queries the relay for the original wrap event id and reports
455/// whether the relay actually honored the deletion. Catches relays
456/// that lie about NIP-09 compliance.
457async fn send_to_one_relay(client: &Client, url: &RelayUrl, event: &Event) -> bool {
458    /// Max attempts to push past a rate-limit. With 30s between
459    /// attempts that's a 10-minute window — generous for any sane
460    /// per-IP rate limit. If the relay is still rate-limiting us
461    /// after that, something else is wrong and we give up so the
462    /// task doesn't loop forever.
463    const MAX_RATELIMIT_RETRIES: u32 = 20;
464    /// Pause between rate-limit retries.
465    const RATELIMIT_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);
466
467    let pool = client;
468    let relays = pool.relays().await;
469    let relay = match relays.get(url) {
470        Some(r) => r.clone(),
471        None => {
472            crate::log_warn!("[delete] relay {} not in pool — NIP-09 not delivered", url);
473            return false;
474        }
475    };
476    drop(relays);
477
478    let mut retries = 0u32;
479    loop {
480        match relay.send_event(event).await {
481            Ok(_) => {
482                if retries == 0 {
483                    crate::log_info!("[delete] relay {} ACK'd NIP-09", url);
484                } else {
485                    crate::log_info!(
486                        "[delete] relay {} ACK'd NIP-09 (after {} retr{})",
487                        url,
488                        retries,
489                        if retries == 1 { "y" } else { "ies" }
490                    );
491                }
492                if let Some(wrap_id) = extract_target_event_id(event) {
493                    let url_clone = url.clone();
494                    let client_clone = client.clone();
495                    tokio::spawn(async move {
496                        verify_relay_dropped(&client_clone, &url_clone, &wrap_id).await;
497                    });
498                }
499                return true;
500            }
501            Err(e) => {
502                let err_str = e.to_string();
503                let lc = err_str.to_ascii_lowercase();
504                let is_rate_limit = lc.contains("rate-limit")
505                    || lc.contains("rate limit")
506                    || lc.contains("noting too much");
507                let is_transient = lc.contains("timeout")
508                    || lc.contains("timed out")
509                    || lc.contains("connection reset")
510                    || lc.contains("connection refused")
511                    || lc.contains("connection closed")
512                    || lc.contains("broken pipe")
513                    || lc.contains("not connected");
514                let retryable = is_rate_limit || is_transient;
515                if retryable && retries < MAX_RATELIMIT_RETRIES {
516                    retries += 1;
517                    let reason = if is_rate_limit { "rate-limited" } else { "transient error" };
518                    crate::log_warn!(
519                        "[delete] relay {} {} (attempt {}/{}; err: {}); waiting {}s",
520                        url,
521                        reason,
522                        retries,
523                        MAX_RATELIMIT_RETRIES,
524                        err_str,
525                        RATELIMIT_BACKOFF.as_secs()
526                    );
527                    tokio::time::sleep(RATELIMIT_BACKOFF).await;
528                    continue;
529                }
530                if retryable {
531                    crate::log_warn!(
532                        "[delete] relay {} still failing after {} retries ({}); scheduling verify probe in case it eventually accepted",
533                        url,
534                        retries,
535                        err_str
536                    );
537                    // Even though our publish never ACK'd, the relay may
538                    // have actually received and processed the event
539                    // (timeouts often mean "ACK lost on the way back").
540                    // Schedule a verify probe so we still log whether the
541                    // wrap is gone.
542                    if let Some(wrap_id) = extract_target_event_id(event) {
543                        let url_clone = url.clone();
544                        let client_clone = client.clone();
545                        tokio::spawn(async move {
546                            verify_relay_dropped(&client_clone, &url_clone, &wrap_id).await;
547                        });
548                    }
549                } else {
550                    crate::log_warn!("[delete] relay {} rejected NIP-09: {}", url, err_str);
551                }
552                return false;
553            }
554        }
555    }
556}
557
558/// Pull the target event id from a NIP-09 deletion event's first
559/// `["e", ...]` tag. Used by the verification probe to know which
560/// wrap to look for after asking the relay to delete it.
561fn extract_target_event_id(deletion: &Event) -> Option<EventId> {
562    deletion.tags.iter().find_map(|tag| {
563        let s = tag.as_slice();
564        if s.len() >= 2 && s[0] == "e" {
565            EventId::from_hex(&s[1]).ok()
566        } else {
567            None
568        }
569    })
570}
571
572/// 2s after a relay ACKs our NIP-09, ask it whether the target wrap
573/// is actually gone. Logs a clear "GONE" or "STILL PRESENT" so we can
574/// identify non-compliant relays without bisecting via external tools.
575async fn verify_relay_dropped(client: &Client, url: &RelayUrl, wrap_event_id: &EventId) {
576    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
577
578    let pool = client;
579    let relays = pool.relays().await;
580    let relay = match relays.get(url) {
581        Some(r) => r.clone(),
582        None => return,
583    };
584
585    let filter = Filter::new().id(*wrap_event_id);
586    match relay
587        .fetch_events(filter)
588        .timeout(std::time::Duration::from_secs(5))
589        .policy(ReqExitPolicy::ExitOnEOSE)
590        .await
591    {
592        Ok(events) => {
593            let still_present = events.into_iter().next().is_some();
594            if still_present {
595                crate::log_warn!(
596                    "[delete-verify] relay {} STILL HAS wrap {} (non-compliant — relay ACK'd NIP-09 but did not drop the event)",
597                    url,
598                    wrap_event_id.to_hex()
599                );
600            } else {
601                crate::log_info!(
602                    "[delete-verify] relay {} confirmed wrap {} is GONE",
603                    url,
604                    wrap_event_id.to_hex()
605                );
606            }
607        }
608        Err(e) => {
609            crate::log_warn!(
610                "[delete-verify] relay {} probe failed for wrap {}: {}",
611                url,
612                wrap_event_id.to_hex(),
613                e
614            );
615        }
616    }
617}
618
619/// Publish the Layer-2 cooperative-hide notice — a kind-5 NIP-09 rumor
620/// signed by the user's main key, gift-wrapped to the recipient and to
621/// self. Carries a NIP-40 expiration tag (30 days) so relays drop the
622/// wrap once the live-client window has passed.
623async fn publish_cooperative_hide(
624    client: &Client,
625    target_rumor_id: &EventId,
626    recipient: &PublicKey,
627    original_kind: u16,
628) -> Result<(), String> {
629    let my_pk = my_public_key().ok_or("Public key not set")?;
630    let now = std::time::SystemTime::now()
631        .duration_since(std::time::UNIX_EPOCH)
632        .map_err(|e| e.to_string())?
633        .as_secs();
634    let expiration_ts = now + COOPERATIVE_HIDE_EXPIRY_SECS;
635
636    // Build the kind-5 rumor (signed by our main key via the gift-wrap
637    // path's seal step). Reference the inner rumor id with `e`, hint at
638    // the original kind via `k` (14 = DM message, 7 = reaction), expire
639    // after 30 days. The `k` lets the receiver remove the right thing.
640    let rumor = EventBuilder::new(Kind::EventDeletion, "")
641        .tag(Tag::event(*target_rumor_id))
642        .tag(Tag::custom("k", [original_kind.to_string()]))
643        .tag(Tag::expiration(Timestamp::from(expiration_ts)))
644        .finalize_unsigned_with_id(my_pk);
645
646    // Wrap and send to recipient. Also wrap and send to self so other
647    // devices belonging to the user drop the message from their local
648    // view too. Best-effort, fire-and-forget.
649    let r1 = send_gift_wrap(client, recipient, rumor.clone(), []).await;
650    let r2 = send_gift_wrap(client, &my_pk, rumor, []).await;
651
652    if r1.is_err() && r2.is_err() {
653        return Err("both cooperative-hide deliveries failed".to_string());
654    }
655    Ok(())
656}