Skip to main content

vector_core/
badges.rs

1//! Profile badges — fetch, validate, and cache.
2//!
3//! Badges are not loaded during the critical boot path. The cache is filled
4//! once after initial sync (see `refresh_own_badges`) so badge-gated perks
5//! (e.g. raised emoji-pack limits) resolve without an on-demand network
6//! round-trip. `has_vector_badge` is the cheap synchronous reader used by
7//! those gates.
8
9use nostr_sdk::prelude::*;
10use std::collections::HashSet;
11use std::sync::LazyLock;
12
13// Guy Fawkes Day 2025 — V for Vector badge claim window.
14const FAWKES_DAY_START: u64 = 1762300800; // 2025-11-05 00:00:00 UTC
15const FAWKES_DAY_END: u64 = 1762387200; // 2025-11-06 00:00:00 UTC
16
17/// Per-account settings key: "true" once we've confirmed the Vector badge.
18const BADGE_VECTOR_KEY: &str = "badge_vector";
19/// Per-account settings key: unix-secs of the last unsuccessful resolve pass.
20/// Throttles re-checking for accounts that don't (yet) hold the badge.
21const BADGE_CHECK_TS_KEY: &str = "badge_check_ts";
22/// Don't re-run the full retry loop more than this often for an account we've
23/// already checked without success. The claim window is permanently closed, so
24/// a non-holder can never become a holder — frequent restarts shouldn't each
25/// trigger a fresh relay sweep.
26const RECHECK_COOLDOWN_SECS: u64 = 6 * 3600;
27
28fn unix_now() -> u64 {
29    std::time::SystemTime::now()
30        .duration_since(std::time::UNIX_EPOCH)
31        .map(|d| d.as_secs())
32        .unwrap_or(0)
33}
34
35/// Whether a kind-30078 event is a valid Fawkes badge claim: right content and
36/// a timestamp inside the (half-open) event window. Pure so it's unit-testable.
37fn is_valid_fawkes_claim(content: &str, created_at: u64) -> bool {
38    content == "fawkes_badge_claimed"
39        && created_at >= FAWKES_DAY_START
40        && created_at < FAWKES_DAY_END
41}
42
43/// Fetch + validate whether `pubkey` holds the V for Vector (Guy Fawkes 2025)
44/// badge: a kind-30078 `d=fawkes_2025` claim published within the event window.
45///
46/// Queries the full relay pool rather than only the trusted relays: the claim
47/// was published during the event to whatever relays the holder used, and any
48/// single relay (including a trusted one) can be transiently down. Broadest
49/// net gives the best chance of locating the permanent claim.
50pub async fn has_fawkes_badge(pubkey: &PublicKey) -> Result<bool, String> {
51    let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
52    let filter = Filter::new()
53        .author(*pubkey)
54        .kind(Kind::ApplicationSpecificData)
55        .custom_tag(SingleLetterTag::LOWERCASE_D, "fawkes_2025")
56        // > 1 to tolerate relays serving superseded copies of the replaceable
57        // event alongside the current one.
58        .limit(10);
59    let mut events = client
60        .stream_events(filter)
61        .timeout(std::time::Duration::from_secs(10))
62        .await
63        .map_err(|e| e.to_string())?;
64    // 0.45 streams (relay, Result<Event>) so callers can attribute per-relay failures.
65    while let Some((_relay, res)) = events.next().await {
66        let Ok(event) = res else { continue };
67        if is_valid_fawkes_claim(&event.content, event.created_at.as_secs()) {
68            return Ok(true);
69        }
70    }
71    Ok(false)
72}
73
74/// Cached flag for whether we hold the Vector badge. Cheap + synchronous, so
75/// safe to call from limit checks. Defaults to false when unset — badge perks
76/// stay off until the cache is filled post-sync.
77pub fn has_vector_badge() -> bool {
78    crate::db::get_sql_setting(BADGE_VECTOR_KEY.to_string())
79        .ok()
80        .flatten()
81        .map(|v| v == "true")
82        .unwrap_or(false)
83}
84
85/// Per-account settings key: cached Bug Hunter NIP-58 tier (0-3). Filled by the
86/// award fetch; downgraded only on a seen issuer revocation, never on absence.
87const BADGE_BUG_HUNTER_TIER_KEY: &str = "badge_bug_hunter_tier";
88
89/// Per-account settings key: comma-separated hex ids of the award events backing
90/// the cached tier, so a revocation still resolves after the relays purge the award.
91const BADGE_BUG_HUNTER_AWARD_IDS_KEY: &str = "badge_bug_hunter_award_ids";
92
93/// Cached Bug Hunter tier (0-3) for the current account. Cheap + synchronous;
94/// 0 until the award fetch fills it.
95pub fn bug_hunter_tier() -> u8 {
96    crate::db::get_sql_setting(BADGE_BUG_HUNTER_TIER_KEY.to_string())
97        .ok()
98        .flatten()
99        .and_then(|v| v.parse::<u8>().ok())
100        .map(|t| t.min(3))
101        .unwrap_or(0)
102}
103
104/// The account's effective premium tier (0-3): the higher of the Bug Hunter tier
105/// and the V for Vector badge (full premium = tier 3). Per-account perks (emoji
106/// limits) read this.
107pub fn effective_tier() -> u8 {
108    bug_hunter_tier().max(if has_vector_badge() { 3 } else { 0 })
109}
110
111/// The highest effective tier across ALL accounts on this install. The
112/// multi-account cap is device-level (adding a profile spans accounts), so it
113/// must not drop when you switch to an un-badged account — unlike the per-account
114/// perks. Reads each account's badge state straight from its vector.db.
115pub fn max_account_tier() -> u8 {
116    let mut max = effective_tier();
117    if let Ok(accounts) = crate::db::get_accounts() {
118        for npub in accounts {
119            max = max.max(read_account_tier(&npub).unwrap_or(0));
120        }
121    }
122    max
123}
124
125/// A (possibly non-active) account's effective tier, read read-only from its
126/// vector.db settings (plaintext KV). None if the DB/keys are absent or locked.
127fn read_account_tier(npub: &str) -> Option<u8> {
128    let path = crate::db::account_dir(npub).ok()?.join("vector.db");
129    let conn = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY).ok()?;
130    let get = |key: &str| -> Option<String> {
131        conn.query_row("SELECT value FROM settings WHERE key = ?1", rusqlite::params![key], |r| r.get(0)).ok()
132    };
133    let bug = get(BADGE_BUG_HUNTER_TIER_KEY).and_then(|v| v.parse::<u8>().ok()).map(|t| t.min(3)).unwrap_or(0);
134    let vector = get(BADGE_VECTOR_KEY).map(|v| v == "true").unwrap_or(false);
135    Some(bug.max(if vector { 3 } else { 0 }))
136}
137
138/// Record the result of an on-demand badge check. When the checked key is our
139/// own and the badge is present, persist it (sticky) and emit `badges_updated`
140/// so badge-gated perks (raised emoji-pack limits) turn on immediately — this is
141/// the safety net for a post-sync `refresh_own_badges` that missed the claim
142/// (the holding relay is often flaky during the saturated sync window) and is now
143/// sitting in its multi-hour re-check cooldown. An on-demand check runs at a
144/// quiet moment, so it lands where the sync-time sweep didn't.
145///
146/// No-op for other users, a negative result, or an account swap mid-check (the
147/// own-key comparison re-reads the *current* account, so a stale key never
148/// writes the wrong DB). No awaits, so the read + write stay on one account.
149pub fn note_own_badge_confirmed(pubkey: &PublicKey, has_badge: bool) {
150    if !has_badge || has_vector_badge() {
151        return;
152    }
153    if crate::state::my_public_key().as_ref() != Some(pubkey) {
154        return;
155    }
156    let _ = crate::db::set_sql_setting(BADGE_VECTOR_KEY.to_string(), "true".to_string());
157    crate::log_info!("[Badges] vector badge confirmed via on-demand check");
158    crate::traits::emit_event_json(
159        "badges_updated",
160        serde_json::json!({ "vector": true, "tier": effective_tier(), "bug_hunter": bug_hunter_tier() }),
161    );
162}
163
164/// Fetch our own badges and persist to the per-account cache. Called once
165/// after initial sync. The SessionGuard straddles the network fetch so a
166/// mid-fetch account swap can't write account A's badge into account B's DB.
167pub async fn refresh_own_badges() {
168    let session = crate::state::SessionGuard::capture();
169    let Some(pk) = crate::state::my_public_key() else {
170        crate::log_warn!("[Badges] refresh skipped — no public key");
171        return;
172    };
173
174    // Sticky: the badge is a permanent achievement, so once confirmed we never
175    // re-query (avoids a flaky relay later flipping it off) and never downgrade.
176    if has_vector_badge() {
177        crate::log_info!("[Badges] vector badge already cached — skipping refresh");
178        return;
179    }
180
181    // Throttle: skip the relay sweep if we already checked recently without
182    // success. The window is closed, so a miss now will still be a miss in an
183    // hour — no need to re-sweep on every restart.
184    let now = unix_now();
185    if let Some(last) = crate::db::get_sql_setting(BADGE_CHECK_TS_KEY.to_string())
186        .ok()
187        .flatten()
188        .and_then(|v| v.parse::<u64>().ok())
189    {
190        if now.saturating_sub(last) < RECHECK_COOLDOWN_SECS {
191            return;
192        }
193    }
194
195    crate::log_info!(
196        "[Badges] resolving own badges for {}…",
197        pk.to_bech32().unwrap_or_default()
198    );
199
200    // The holding relay (often the user's own) is flaky/overloaded during the
201    // heavy sync window, so retry a few times to catch it during a quiet
202    // moment. A miss leaves the badge cache untouched (records only the check
203    // time for the cooldown); the next boot past the cooldown tries again until
204    // it lands once (then sticky-cached forever).
205    const ATTEMPTS: u8 = 3;
206    for attempt in 1..=ATTEMPTS {
207        match has_fawkes_badge(&pk).await {
208            Ok(true) => {
209                if !session.is_valid() {
210                    return;
211                }
212                crate::log_info!("[Badges] vector badge confirmed (attempt {})", attempt);
213                let _ = crate::db::set_sql_setting(BADGE_VECTOR_KEY.to_string(), "true".to_string());
214                return;
215            }
216            Ok(false) => {
217                crate::log_info!("[Badges] vector badge not found (attempt {}/{})", attempt, ATTEMPTS);
218            }
219            Err(e) => {
220                crate::log_warn!("[Badges] refresh attempt {}/{} failed: {}", attempt, ATTEMPTS, e);
221            }
222        }
223        if !session.is_valid() {
224            return;
225        }
226        if attempt < ATTEMPTS {
227            tokio::time::sleep(std::time::Duration::from_secs(20)).await;
228        }
229    }
230    // Record the unsuccessful pass so the cooldown applies before re-sweeping.
231    if session.is_valid() {
232        let _ = crate::db::set_sql_setting(BADGE_CHECK_TS_KEY.to_string(), now.to_string());
233    }
234    crate::log_info!("[Badges] vector badge not resolved this boot — will retry after cooldown");
235}
236
237// ── Bug Hunter (NIP-58 tiered, team-awarded) ───────────────────────────────
238
239/// The Vector Team issuer key — the NIP-58 trust root for Bug Hunter badges.
240/// Only awards (kind 8) and revocations (kind 5) signed by this key are honored,
241/// so a forged award from any other key grants nothing.
242const BUG_HUNTER_ISSUER_NPUB: &str =
243    "npub1hrujuc08r4zcdtn0u6ts7u7apldcjqgftz0z7stmaaz9hwaf9jxs66f3yh";
244
245static BUG_HUNTER_ISSUER: LazyLock<PublicKey> = LazyLock::new(|| {
246    PublicKey::from_bech32(BUG_HUNTER_ISSUER_NPUB)
247        .expect("hardcoded Bug Hunter issuer npub must be valid")
248});
249
250/// Map a badge-definition `d` identifier to its tier. The display `name` can
251/// change freely; the `d` slug is the permanent identity.
252fn tier_from_slug(d: &str) -> Option<u8> {
253    match d {
254        "bug-hunter-tier-1" => Some(1),
255        "bug-hunter-tier-2" => Some(2),
256        "bug-hunter-tier-3" => Some(3),
257        _ => None,
258    }
259}
260
261/// Parse a NIP-58 `a`-tag coordinate (`30009:<issuer-hex>:<d>`) into a tier, but
262/// only when the kind is 30009 AND the author is our trusted issuer — an award
263/// pointing at a definition minted under any other key is ignored.
264fn tier_from_coord(coord: &str, issuer_hex: &str) -> Option<u8> {
265    let mut parts = coord.splitn(3, ':');
266    let kind = parts.next()?;
267    let author = parts.next()?;
268    let d = parts.next()?;
269    if kind != "30009" || author != issuer_hex {
270        return None;
271    }
272    tier_from_slug(d)
273}
274
275/// Fold awards (event id + tier) and the set of revoked award ids into the tier
276/// seen this fetch, plus whether a revocation actually applied to one of our
277/// awards. Pure so it's unit-testable. `saw_revocation` is the positive signal
278/// that justifies a downgrade (vs. a flaky-relay absence, which must not).
279fn fold_bug_hunter(awards: &[(EventId, u8)], revoked: &HashSet<EventId>) -> (u8, bool) {
280    let mut seen_tier = 0u8;
281    let mut saw_revocation = false;
282    for (id, tier) in awards {
283        if revoked.contains(id) {
284            saw_revocation = true;
285        } else {
286            seen_tier = seen_tier.max(*tier);
287        }
288    }
289    (seen_tier, saw_revocation)
290}
291
292/// Fetch `pubkey`'s raw Bug Hunter standing from the issuer: the seen kind-8
293/// awards (id + tier) whose `a` points at one of our tier definitions, plus the
294/// set of award ids the issuer has revoked (kind-5). Queries the full pool.
295async fn fetch_bug_hunter_raw(pubkey: &PublicKey) -> Result<(Vec<(EventId, u8)>, HashSet<EventId>), String> {
296    let client = crate::state::nostr_client().ok_or("Nostr client not initialized")?;
297    let issuer = *BUG_HUNTER_ISSUER;
298    let issuer_hex = issuer.to_hex();
299
300    // Awards: kind 8 signed by the issuer, p-tagging this user.
301    let award_filter = Filter::new()
302        .author(issuer)
303        .kind(Kind::Custom(8))
304        .custom_tag(SingleLetterTag::LOWERCASE_P, pubkey.to_hex())
305        .limit(64);
306    let mut awards: Vec<(EventId, u8)> = Vec::new();
307    let mut stream = client
308        .stream_events(award_filter)
309        .timeout(std::time::Duration::from_secs(10))
310        .await
311        .map_err(|e| e.to_string())?;
312    while let Some((_relay, res)) = stream.next().await {
313        let Ok(ev) = res else { continue };
314        let coord = ev.tags.iter().find_map(|t| {
315            let s = t.as_slice();
316            if s.first().map(|k| k == "a").unwrap_or(false) {
317                s.get(1).cloned()
318            } else {
319                None
320            }
321        });
322        if let Some(c) = coord {
323            if let Some(tier) = tier_from_coord(&c, &issuer_hex) {
324                awards.push((ev.id, tier));
325            }
326        }
327    }
328
329    // Revocations: kind 5 from the issuer (NIP-09); each `e` tag names a revoked award.
330    let revoke_filter = Filter::new()
331        .author(issuer)
332        .kind(Kind::Custom(5))
333        .limit(256);
334    let mut revoked: HashSet<EventId> = HashSet::new();
335    let mut rstream = client
336        .stream_events(revoke_filter)
337        .timeout(std::time::Duration::from_secs(10))
338        .await
339        .map_err(|e| e.to_string())?;
340    while let Some((_relay, res)) = rstream.next().await {
341        let Ok(ev) = res else { continue };
342        for t in ev.tags.iter() {
343            let s = t.as_slice();
344            if s.first().map(|k| k == "e").unwrap_or(false) {
345                if let Some(id) = s.get(1).and_then(|h| EventId::from_hex(h).ok()) {
346                    revoked.insert(id);
347                }
348            }
349        }
350    }
351
352    Ok((awards, revoked))
353}
354
355/// Highest non-revoked tier + whether a seen award was revoked, for displaying
356/// another user's badge. Our own status goes through `refresh_own_bug_hunter`,
357/// which also catches revocation of a since-purged award.
358pub async fn fetch_bug_hunter_tier(pubkey: &PublicKey) -> Result<(u8, bool), String> {
359    let (awards, revoked) = fetch_bug_hunter_raw(pubkey).await?;
360    Ok(fold_bug_hunter(&awards, &revoked))
361}
362
363fn read_cached_award_ids() -> Vec<EventId> {
364    crate::db::get_sql_setting(BADGE_BUG_HUNTER_AWARD_IDS_KEY.to_string())
365        .ok()
366        .flatten()
367        .map(|s| s.split(',').filter_map(|h| EventId::from_hex(h.trim()).ok()).collect())
368        .unwrap_or_default()
369}
370
371fn write_cached_award_ids(ids: &[EventId]) {
372    let csv = ids.iter().map(|id| id.to_hex()).collect::<Vec<_>>().join(",");
373    let _ = crate::db::set_sql_setting(BADGE_BUG_HUNTER_AWARD_IDS_KEY.to_string(), csv);
374}
375
376/// Resolve + persist our own Bug Hunter tier (called post-sync). Sticky cache:
377/// upgrades apply immediately; a downgrade is honored ONLY on a seen revocation,
378/// never a mere absent award (flaky relay). The ids of the awards backing the
379/// current tier are cached so a revocation still resolves after the relays purge
380/// the award itself (NIP-09 deletion). SessionGuard straddles the fetch so a
381/// mid-fetch account swap can't write account A's tier into account B.
382pub async fn refresh_own_bug_hunter() {
383    let session = crate::state::SessionGuard::capture();
384    let Some(pk) = crate::state::my_public_key() else {
385        return;
386    };
387
388    let (awards, revoked) = match fetch_bug_hunter_raw(&pk).await {
389        Ok(r) => r,
390        Err(e) => {
391            crate::log_warn!("[Badges] bug hunter fetch failed: {}", e);
392            return;
393        }
394    };
395    if !session.is_valid() {
396        return;
397    }
398
399    // Highest non-revoked seen tier + the award ids backing it.
400    let mut seen_tier = 0u8;
401    let mut active_ids: Vec<EventId> = Vec::new();
402    let mut seen_revoked = false;
403    for (id, tier) in &awards {
404        if revoked.contains(id) {
405            seen_revoked = true;
406        } else {
407            seen_tier = seen_tier.max(*tier);
408            active_ids.push(*id);
409        }
410    }
411    // Also honor a revocation of an award we previously cached but that the relays
412    // have since purged (so it's no longer in `awards` to match directly).
413    let cached_revoked = read_cached_award_ids().iter().any(|id| revoked.contains(id));
414    let saw_revocation = seen_revoked || cached_revoked;
415
416    // Re-read the current account before any write: never persist A's state into B.
417    if crate::state::my_public_key().as_ref() != Some(&pk) {
418        return;
419    }
420
421    let cached = bug_hunter_tier();
422    let new_tier = if seen_tier > cached {
423        seen_tier
424    } else if seen_tier < cached && saw_revocation {
425        seen_tier
426    } else {
427        cached
428    };
429
430    // Remember the awards behind the current tier — but only when we actually saw
431    // awards, so a flaky empty fetch never wipes the memory we need for revocation.
432    if !awards.is_empty() {
433        write_cached_award_ids(&active_ids);
434    }
435    if new_tier == cached {
436        return;
437    }
438    let _ = crate::db::set_sql_setting(
439        BADGE_BUG_HUNTER_TIER_KEY.to_string(),
440        new_tier.to_string(),
441    );
442    crate::log_info!("[Badges] bug hunter tier {} -> {}", cached, new_tier);
443    crate::traits::emit_event_json(
444        "badges_updated",
445        serde_json::json!({ "vector": has_vector_badge(), "tier": effective_tier(), "bug_hunter": bug_hunter_tier() }),
446    );
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    #[test]
454    fn fawkes_claim_window_boundaries() {
455        // Correct content, inside the window.
456        assert!(is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_START));
457        assert!(is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_END - 1));
458        // End is exclusive.
459        assert!(!is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_END));
460        // Before the window.
461        assert!(!is_valid_fawkes_claim("fawkes_badge_claimed", FAWKES_DAY_START - 1));
462        // Wrong / empty content, even inside the window.
463        assert!(!is_valid_fawkes_claim("", FAWKES_DAY_START));
464        assert!(!is_valid_fawkes_claim("something_else", FAWKES_DAY_START));
465    }
466
467    #[test]
468    fn bug_hunter_issuer_npub_is_valid() {
469        // A malformed hardcoded issuer would panic when the LazyLock forces.
470        let _ = *BUG_HUNTER_ISSUER;
471        assert!(PublicKey::from_bech32(BUG_HUNTER_ISSUER_NPUB).is_ok());
472    }
473
474    #[test]
475    fn tier_from_coord_trusts_only_issuer_kind_and_slug() {
476        let issuer = "abc123";
477        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-1", issuer), Some(1));
478        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-2", issuer), Some(2));
479        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-3", issuer), Some(3));
480        // Forged: a definition minted under another key.
481        assert_eq!(tier_from_coord("30009:evil:bug-hunter-tier-3", issuer), None);
482        // Wrong kind.
483        assert_eq!(tier_from_coord("30008:abc123:bug-hunter-tier-3", issuer), None);
484        // Unknown slug.
485        assert_eq!(tier_from_coord("30009:abc123:bug-hunter-tier-9", issuer), None);
486    }
487
488    #[test]
489    fn fold_bug_hunter_highest_non_revoked_with_revocation_flag() {
490        let id = |b: u8| EventId::from_hex(&format!("{:02x}", b).repeat(32)).unwrap();
491        // No revocations: highest tier, flag clear.
492        assert_eq!(fold_bug_hunter(&[(id(1), 1), (id(3), 3), (id(2), 2)], &HashSet::new()), (3, false));
493        // Revoke the tier-3 award: tier drops to 2, flag set.
494        let revoked: HashSet<EventId> = [id(3)].into_iter().collect();
495        assert_eq!(fold_bug_hunter(&[(id(1), 1), (id(3), 3), (id(2), 2)], &revoked), (2, true));
496        // No awards: tier 0, no revocation.
497        assert_eq!(fold_bug_hunter(&[], &HashSet::new()), (0, false));
498    }
499}