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