Skip to main content

vector_core/
signer.rs

1//! Polymorphic signer — local key vault, NIP-46 remote bunker, or an
2//! external signer (NIP-55 app, NIP-07 browser extension).
3//!
4//! Vector supports two signer modes per account:
5//!
6//! - **Local** — the user's nsec lives in `MY_SECRET_KEY` (GuardedKey vault)
7//!   on this device. Signing is local; the key materialises in plaintext only
8//!   for microseconds per operation.
9//! - **Bunker** — the user's nsec lives on a remote NIP-46 signer (Amber,
10//!   nsec.app, ...). Vector holds only a *client keypair* (in `MY_SECRET_KEY`)
11//!   used to RPC the bunker. Every signing request takes a round-trip; the
12//!   user's identity key never touches this device.
13//!
14//! The discriminator is persisted in the per-account settings DB
15//! (`signer_type` key) and materialised into the `SIGNER_KIND` atomic at
16//! login. Hot paths read the atomic; cold paths read the DB directly.
17//!
18//! Storage layout for bunker accounts (see `db::settings`):
19//! - `signer_type = "bunker"`
20//! - `bunker_url`  = the `bunker://<remote_pubkey>?relay=...&secret=...`
21//!   string, encrypted-at-rest if the account uses pin/pass encryption (same
22//!   path as `pkey`).
23//! - `bunker_remote_pubkey` = the signer's pubkey, plaintext (routing only).
24//! - `pkey` = the NIP-46 client keypair (encrypted-at-rest under the same
25//!   path as local accounts). Reusing the existing vault avoids a second
26//!   GuardedKey slot; see the "Client-keypair storage note" section below.
27
28use std::sync::atomic::{AtomicU8, Ordering};
29use std::sync::{LazyLock, RwLock};
30use std::time::Duration;
31
32use nostr_sdk::prelude::*;
33use nostr_connect::prelude::{AuthUrlHandler, NostrConnect, NostrConnectUri};
34
35// ============================================================================
36// SignerError + VectorSigner — the capability-trait bundle
37// ============================================================================
38
39/// Boxed future returned by every async signer capability.
40///
41/// nostr 0.45.0 inlined this shape into its trait signatures and stopped
42/// exporting an alias, so Vector owns the name.
43pub type BoxedFuture<'a, T> =
44    std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;
45
46/// Error from any signing backend.
47///
48/// nostr 0.45 deleted `NostrSigner` and split it into per-capability traits,
49/// each carrying its own associated `Error`. Vector normalises all four onto
50/// this one type so the polymorphic seam stays a single trait bound and callers
51/// keep one error to handle.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct SignerError(String);
54
55impl SignerError {
56    /// Wrap a backend error (bunker RPC, NIP-55 IPC, local crypto).
57    #[inline]
58    pub fn backend<E>(e: E) -> Self
59    where
60        E: core::fmt::Display,
61    {
62        Self(e.to_string())
63    }
64}
65
66impl core::fmt::Display for SignerError {
67    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
68        f.write_str(&self.0)
69    }
70}
71
72impl core::error::Error for SignerError {}
73
74impl From<&str> for SignerError {
75    #[inline]
76    fn from(s: &str) -> Self {
77        Self(s.to_string())
78    }
79}
80
81impl From<String> for SignerError {
82    #[inline]
83    fn from(s: String) -> Self {
84        Self(s)
85    }
86}
87
88/// Every capability Vector's polymorphic signing paths need, in one bound.
89///
90/// Pinning `Error = SignerError` is what makes the bundle usable as a single
91/// bound; it's viable because the concrete-`Keys` paths have their own
92/// non-generic overloads (`build_list_event` vs `build_list_event_signed`), so
93/// bare `Keys` is never passed here.
94pub trait VectorSigner:
95    AsyncGetPublicKey<Error = SignerError>
96    + AsyncSignEvent<Error = SignerError>
97    + AsyncNip04<Error = SignerError>
98    + AsyncNip44<Error = SignerError>
99{
100}
101
102impl<T> VectorSigner for T
103where
104    T: ?Sized
105        + AsyncGetPublicKey<Error = SignerError>
106        + AsyncSignEvent<Error = SignerError>
107        + AsyncNip04<Error = SignerError>
108        + AsyncNip44<Error = SignerError>,
109{
110}
111
112// ============================================================================
113// ActiveSigner — the session's signer, resolved on demand
114// ============================================================================
115
116/// The signer for the active session.
117///
118/// nostr 0.45 removed `ClientBuilder::signer` / `Client::signer`: events are
119/// built and signed outside the client now, so Vector owns this dispatch.
120///
121/// A concrete enum rather than `Arc<dyn ...>` on purpose. 0.45 ships no blanket
122/// capability impls for `Arc<T>`, and the orphan rule forbids adding them, so a
123/// trait object would force every call site to deref. This also keeps dispatch
124/// static.
125///
126/// Deliberately NOT cached in a static: [`active_signer`] rebuilds it per call
127/// from state that is already swap-managed (`SIGNER_KIND`, `BUNKER_SIGNER`,
128/// `MY_PUBLIC_KEY`). A cached signer would be one more per-account global to
129/// invalidate on `reset_session`, and a stale one signs the new account's events
130/// under the old identity.
131#[derive(Debug, Clone)]
132#[allow(clippy::large_enum_variant)] // boxing a public variant's payload is an API break
133pub enum ActiveSigner {
134    /// Local key from the GuardedKey vault.
135    Local(crate::crypto::GuardedSigner),
136    /// Remote NIP-46 bunker, with reachability reporting.
137    Bunker(WatchedBunkerSigner),
138    /// On-device NIP-55 signer app reached over Android IPC.
139    Nip55(crate::nip55::Nip55Signer),
140    /// NIP-07 browser extension in the page hosting a web build.
141    Nip07(crate::nip07::Nip07Signer),
142    /// Raw keys a caller holds itself (tests). The vault's own key always resolves to
143    /// `Local`, which reads it per operation.
144    Keys(Keys),
145}
146
147macro_rules! dispatch {
148    ($self:ident, $method:ident $(, $arg:expr)*) => {
149        match $self {
150            ActiveSigner::Local(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
151            ActiveSigner::Bunker(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
152            ActiveSigner::Nip55(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
153            ActiveSigner::Nip07(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
154            ActiveSigner::Keys(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
155        }
156    };
157}
158
159impl AsyncGetPublicKey for ActiveSigner {
160    type Error = SignerError;
161
162    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
163        Box::pin(async move { dispatch!(self, get_public_key_async) })
164    }
165}
166
167impl AsyncSignEvent for ActiveSigner {
168    type Error = SignerError;
169
170    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
171        // Before any backend sees it: a remote signer signs exactly what it is sent.
172        let unsigned = crate::clock::restamp(unsigned);
173        Box::pin(async move { dispatch!(self, sign_event_async, unsigned) })
174    }
175}
176
177impl AsyncNip04 for ActiveSigner {
178    type Error = SignerError;
179
180    fn nip04_encrypt_async<'a>(
181        &'a self,
182        public_key: &'a PublicKey,
183        content: &'a str,
184    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
185        Box::pin(async move { dispatch!(self, nip04_encrypt_async, public_key, content) })
186    }
187
188    fn nip04_decrypt_async<'a>(
189        &'a self,
190        public_key: &'a PublicKey,
191        encrypted_content: &'a str,
192    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
193        Box::pin(async move { dispatch!(self, nip04_decrypt_async, public_key, encrypted_content) })
194    }
195}
196
197impl AsyncNip44 for ActiveSigner {
198    type Error = SignerError;
199
200    fn nip44_encrypt_async<'a>(
201        &'a self,
202        public_key: &'a PublicKey,
203        content: &'a str,
204    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
205        Box::pin(async move { dispatch!(self, nip44_encrypt_async, public_key, content) })
206    }
207
208    fn nip44_decrypt_async<'a>(
209        &'a self,
210        public_key: &'a PublicKey,
211        payload: &'a str,
212    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
213        Box::pin(async move { dispatch!(self, nip44_decrypt_async, public_key, payload) })
214    }
215}
216
217/// Test-only signer override consulted by [`active_signer`].
218#[cfg(test)]
219static TEST_SIGNER: LazyLock<RwLock<Option<ActiveSigner>>> =
220    LazyLock::new(|| RwLock::new(None));
221
222/// Install (or clear) the test signer override.
223#[cfg(test)]
224pub(crate) fn set_test_signer(signer: Option<ActiveSigner>) {
225    if let Ok(mut g) = TEST_SIGNER.write() {
226        *g = signer;
227    }
228}
229
230/// Unwrap a NIP-59 gift wrap with the active session's signer. A local key opens it
231/// under one vault read; remote signers go through their round-trips.
232pub async fn unwrap_gift_wrap(gift_wrap: &Event) -> Result<UnwrappedGift, String> {
233    #[cfg(test)]
234    let overridden = TEST_SIGNER.read().is_ok_and(|g| g.is_some());
235    #[cfg(not(test))]
236    let overridden = false;
237    if !overridden && signer_kind() == SignerKind::Local {
238        return crate::crypto::GuardedSigner::unwrap_gift_wrap(gift_wrap).map_err(|e| e.to_string());
239    }
240    let signer = active_signer()?;
241    UnwrappedGift::from_gift_wrap_async(&signer, gift_wrap).await.map_err(|e| e.to_string())
242}
243
244/// Seal a rumor for `receiver` with the active session's signer. A local key seals under
245/// one vault read; remote signers go through their round-trips.
246pub async fn seal_rumor(rumor: UnsignedEvent, receiver: &PublicKey) -> Result<Event, String> {
247    #[cfg(test)]
248    let overridden = TEST_SIGNER.read().is_ok_and(|g| g.is_some());
249    #[cfg(not(test))]
250    let overridden = false;
251    if !overridden && signer_kind() == SignerKind::Local {
252        if let Some(identity) = crate::state::my_public_key() {
253            return crate::crypto::GuardedSigner::seal(&identity, rumor, receiver).map_err(|e| e.to_string());
254        }
255    }
256    let signer = active_signer()?;
257    GiftWrapSealBuilder::new(rumor, *receiver)
258        .finalize_async(&signer)
259        .await
260        .map_err(|e| e.to_string())
261}
262
263/// Seal and gift-wrap a rumor for `receiver` with the active session's signer. A local
264/// key does both under one vault read.
265pub async fn gift_wrap(
266    receiver: &PublicKey,
267    rumor: UnsignedEvent,
268    extra_tags: impl IntoIterator<Item = Tag>,
269) -> Result<Event, String> {
270    #[cfg(test)]
271    let overridden = TEST_SIGNER.read().is_ok_and(|g| g.is_some());
272    #[cfg(not(test))]
273    let overridden = false;
274    crate::event_size::check_rumor(&rumor)?;
275    let extra_tags: Vec<Tag> = extra_tags.into_iter().collect();
276    let local = if !overridden && signer_kind() == SignerKind::Local { crate::state::my_public_key() } else { None };
277    let wrap = match local {
278        Some(identity) => crate::crypto::GuardedSigner::gift_wrap(&identity, receiver, rumor, extra_tags).map_err(|e| e.to_string())?,
279        None => GiftWrapBuilder::new(*receiver, rumor)
280            .extra_tags(extra_tags)
281            .finalize_async(&active_signer()?)
282            .await
283            .map_err(|e| e.to_string())?,
284    };
285    crate::event_size::check(&wrap)?;
286    Ok(wrap)
287}
288
289/// [`unwrap_gift_wrap`] for many wraps, one result per wrap in order. A local key opens
290/// the whole batch under one vault read.
291pub async fn unwrap_gift_wraps(gift_wraps: &[&Event]) -> Vec<Result<UnwrappedGift, String>> {
292    #[cfg(test)]
293    let overridden = TEST_SIGNER.read().is_ok_and(|g| g.is_some());
294    #[cfg(not(test))]
295    let overridden = false;
296    if !overridden && signer_kind() == SignerKind::Local {
297        return crate::crypto::GuardedSigner::unwrap_batch(gift_wraps)
298            .into_iter()
299            .map(|r| r.map_err(|e| e.to_string()))
300            .collect();
301    }
302    let mut out = Vec::with_capacity(gift_wraps.len());
303    for wrap in gift_wraps {
304        out.push(unwrap_gift_wrap(wrap).await);
305    }
306    out
307}
308
309/// Who the local vault key belongs to, remembered against the vault's write count: resolving
310/// the signer checks it with an atomic load and an uncontended lock, and a set() or clear() of
311/// any vault key makes the next resolve derive it again. Holds a public key only.
312static LOCAL_KEY_OWNER: std::sync::Mutex<Option<(usize, PublicKey)>> = std::sync::Mutex::new(None);
313
314fn local_key_owner() -> Option<PublicKey> {
315    let count = crate::crypto::guarded_key::write_count();
316    let settled = count & 1 == 0;
317    if settled {
318        if let Some((at, pk)) = *LOCAL_KEY_OWNER.lock().unwrap_or_else(|e| e.into_inner()) {
319            if at == count {
320                return Some(pk);
321            }
322        }
323    }
324    let Some(pk) = crate::state::MY_SECRET_KEY.with_keys(|keys| keys.public_key()) else {
325        *LOCAL_KEY_OWNER.lock().unwrap_or_else(|e| e.into_inner()) = None;
326        return None;
327    };
328    // Kept only if no write landed while it was derived, so it is this count's key.
329    if settled && crate::crypto::guarded_key::write_count() == count {
330        *LOCAL_KEY_OWNER.lock().unwrap_or_else(|e| e.into_inner()) = Some((count, pk));
331    }
332    Some(pk)
333}
334
335/// Resolve the active session's signer.
336///
337/// Fails CLOSED on identity mismatch: a remote-signer account's vault holds its
338/// *client* keypair, whose pubkey is not the identity. Signing with it emits
339/// wrong-identity events that self-reject on every reader (AuthorMismatch). A
340/// local signer is checked here against the vault key's cached owner, which costs
341/// no vault read unless the key changed, and again at sign/encrypt time.
342pub fn active_signer() -> Result<ActiveSigner, String> {
343    // Tests model a remote-signer account (identity signable, local vault empty),
344    // which production resolves from `BUNKER_SIGNER`. There's no such handle to
345    // fabricate in-process, so tests inject the signer directly.
346    #[cfg(test)]
347    if let Some(s) = TEST_SIGNER.read().ok().and_then(|g| g.clone()) {
348        return Ok(s);
349    }
350    match signer_kind() {
351        SignerKind::Bunker => {
352            let inner = match bunker_signer() {
353                Some(b) => b,
354                None if bunker_suspended() => return Err("Your signer isn't connected yet.".into()),
355                None => return Err("bunker account has no live signer (not yet connected)".into()),
356            };
357            Ok(ActiveSigner::Bunker(WatchedBunkerSigner::new(inner)))
358        }
359        SignerKind::Nip55 => {
360            let pk = crate::state::my_public_key().ok_or("no active identity")?;
361            Ok(ActiveSigner::Nip55(crate::nip55::Nip55Signer::new(pk)))
362        }
363        SignerKind::Nip07 => {
364            let pk = crate::state::my_public_key().ok_or("no active identity")?;
365            Ok(ActiveSigner::Nip07(crate::nip07::Nip07Signer::new(pk)))
366        }
367        SignerKind::Local => {
368            if !crate::state::MY_SECRET_KEY.has_key() {
369                return Err("no signer available (no local key)".to_string());
370            }
371            if let Some(pk) = crate::state::my_public_key() {
372                // Refused here, before a caller starts work it can't finish; GuardedSigner
373                // checks again at use, on the key it actually signs with.
374                if local_key_owner() != Some(pk) {
375                    return Err("local key does not match the active identity (remote-signer account with no live signer)".to_string());
376                }
377                return Ok(ActiveSigner::Local(crate::crypto::GuardedSigner::new(pk)));
378            }
379            // No bound identity (headless/CLI consumers and tests): the vault key is the identity.
380            let pk = local_key_owner().ok_or("no signer available (no local key)")?;
381            Ok(ActiveSigner::Local(crate::crypto::GuardedSigner::new(pk)))
382        }
383    }
384}
385
386// ============================================================================
387// SignerKind — discriminator
388// ============================================================================
389
390/// Which signer backs the active account.
391#[derive(Copy, Clone, Debug, Eq, PartialEq)]
392#[repr(u8)]
393pub enum SignerKind {
394    /// The user's nsec lives in `MY_SECRET_KEY` on this device.
395    Local = 0,
396    /// The user's nsec lives on a remote NIP-46 signer; we only hold the
397    /// client keypair used to RPC it.
398    Bunker = 1,
399    /// The user's nsec lives in an on-device NIP-55 signer app (Amber) reached
400    /// over local Android IPC. Nothing secret is stored on this device at all
401    /// (not even a client keypair). Android-only.
402    Nip55 = 2,
403    /// The user's nsec lives in a NIP-07 browser extension. Web-only; keyless
404    /// like NIP-55.
405    Nip07 = 3,
406}
407
408impl SignerKind {
409    /// Persisted form used by the per-account settings KV.
410    #[inline]
411    pub fn as_setting_str(self) -> &'static str {
412        match self {
413            SignerKind::Local => "local",
414            SignerKind::Bunker => "bunker",
415            SignerKind::Nip55 => "nip55",
416            SignerKind::Nip07 => "nip07",
417        }
418    }
419
420    /// Parse from the on-disk setting string. Unknown values fall back to
421    /// `Local` so an upgrade path from pre-NIP-46 accounts (which have no
422    /// `signer_type` row) is the obvious default.
423    #[inline]
424    pub fn from_setting_str(s: &str) -> Self {
425        match s {
426            "bunker" => SignerKind::Bunker,
427            "nip55" => SignerKind::Nip55,
428            "nip07" => SignerKind::Nip07,
429            _ => SignerKind::Local,
430        }
431    }
432}
433
434static SIGNER_KIND: AtomicU8 = AtomicU8::new(SignerKind::Local as u8);
435
436/// The signer kind for the active session. Cheap to read; backed by an atomic.
437#[inline]
438pub fn signer_kind() -> SignerKind {
439    match SIGNER_KIND.load(Ordering::Acquire) {
440        1 => SignerKind::Bunker,
441        2 => SignerKind::Nip55,
442        3 => SignerKind::Nip07,
443        _ => SignerKind::Local,
444    }
445}
446
447/// Install the signer kind for the active session. Call at login after the
448/// settings row has been read, and on swap before any signing work runs.
449#[inline]
450pub fn set_signer_kind(kind: SignerKind) {
451    SIGNER_KIND.store(kind as u8, Ordering::Release);
452}
453
454/// `true` iff the active account signs via a remote NIP-46 bunker. Hot-path
455/// helper for code that needs to branch on signer mode (e.g. parallelising
456/// gift-wrap signing harder when each call pays a round-trip).
457///
458/// Reserve this for genuinely NIP-46-relay-specific logic. For "we don't hold
459/// the identity key on this device" gates (key export refusal, keyless-account
460/// feature availability) use `is_keyless()` instead — a NIP-55 account is
461/// keyless but not a bunker.
462#[inline]
463pub fn is_bunker() -> bool {
464    signer_kind() == SignerKind::Bunker
465}
466
467/// `true` iff the identity key is NOT held on this device — i.e. any remote /
468/// external signer (NIP-46 bunker or NIP-55 Amber). The local `MY_SECRET_KEY`
469/// vault does not hold the signing identity for these accounts, so anything
470/// that reads or exports the raw nsec must gate on this and route through
471/// `client.signer()` instead.
472#[inline]
473pub fn is_keyless() -> bool {
474    signer_kind() != SignerKind::Local
475}
476
477// ============================================================================
478// Client-keypair storage note
479// ============================================================================
480//
481// The NIP-46 client keypair (used to RPC the bunker — not the user's
482// identity) lives in the existing `MY_SECRET_KEY` vault for bunker accounts.
483// This is intentional: every existing call site that loads "the active
484// signing key" gets the client key, which is what the NIP-46 layer wants for
485// its RPC envelope. For events the *user* sends, the path goes through
486// `client.signer()` → NostrConnect, which tunnels to the bunker — so user
487// events are signed by the user's identity, RPC envelopes by the client key.
488//
489// This avoids needing a second GuardedKey vault and the slot-coordination
490// problem that comes with it. The trade-off: bunker accounts share the same
491// memory-protection footprint as local accounts (the user's identity isn't
492// on this device at all).
493
494// ============================================================================
495// BUNKER_SIGNER — live NostrConnect handle
496// ============================================================================
497
498/// Active `NostrConnect` handle. `None` for local-signer sessions.
499///
500/// `NostrConnect` is internally `Arc`-counted (relay pool, OnceCell-backed
501/// remote pubkey cache), so cloning it for per-call use is cheap. The lock is
502/// only held briefly to snapshot the inner value.
503pub static BUNKER_SIGNER: LazyLock<RwLock<Option<NostrConnect>>> =
504    LazyLock::new(|| RwLock::new(None));
505
506/// Snapshot the active bunker handle. Returns `None` for local-signer sessions.
507#[inline]
508pub fn bunker_signer() -> Option<NostrConnect> {
509    BUNKER_SIGNER.read().ok().and_then(|g| g.as_ref().cloned())
510}
511
512/// Install the bunker handle for the active session. Replaces any prior handle
513/// without shutting it down — callers swapping should `take_bunker_signer()`
514/// first and `.shutdown().await` the old one to drain its relay pool cleanly.
515#[inline]
516pub fn set_bunker_signer(signer: NostrConnect) {
517    if let Ok(mut g) = BUNKER_SIGNER.write() {
518        *g = Some(signer);
519    }
520}
521
522/// Atomically remove the bunker handle. Used by session teardown so the
523/// caller can `.shutdown()` it without racing readers.
524#[inline]
525pub fn take_bunker_signer() -> Option<NostrConnect> {
526    BUNKER_SIGNER.write().ok().and_then(|mut g| g.take())
527}
528
529// ============================================================================
530// Construction helpers
531// ============================================================================
532
533/// Parse a `bunker://` URL and return the relay URLs it lists. Used by the
534/// Settings UI to render `"Connected via <relay>"` without re-bootstrapping.
535/// Returns an empty Vec on any parse failure — the caller treats this as a
536/// display-only signal and renders a generic fallback instead of erroring.
537pub fn parse_bunker_relays(bunker_url: &str) -> Vec<String> {
538    match NostrConnectUri::parse(bunker_url) {
539        Ok(NostrConnectUri::Bunker { relays, .. }) => {
540            relays.into_iter().map(|r| r.to_string()).collect()
541        }
542        _ => Vec::new(),
543    }
544}
545
546/// Inspect a `bunker://` URL without bootstrapping: returns the remote
547/// signer's pubkey (hex). Used by login flows to check whether a re-submitted
548/// URL points at the same bunker as the active session (idempotent re-login)
549/// versus a different bunker (which requires logout first). Cheap — no
550/// network.
551pub fn parse_bunker_remote_pubkey(bunker_url: &str) -> Result<String, String> {
552    let uri = NostrConnectUri::parse(bunker_url)
553        .map_err(|e| format!("Invalid bunker URL: {}", e))?;
554    match uri {
555        NostrConnectUri::Bunker { remote_signer_public_key, .. } => {
556            // Force lowercase. `to_hex()` already returns lowercase per
557            // nostr-sdk, but normalising here lets callers compare hex
558            // forms with `==` without worrying about a future upstream
559            // shift to mixed-case.
560            Ok(remote_signer_public_key.to_hex().to_ascii_lowercase())
561        }
562        // Client-initiated URIs aren't supported as login entry points in v1;
563        // they're for the reverse direction (we hand a URL to the signer).
564        NostrConnectUri::Client { .. } => {
565            Err("Client-initiated URIs not supported here; use a bunker:// URL".into())
566        }
567    }
568}
569
570// ============================================================================
571// Vector app identity — surfaced to remote signers via NIP-46 metadata
572// ============================================================================
573
574/// Application name shown to the user by the remote signer when approving the
575/// connection (e.g. on Amber's pairing screen).
576pub const VECTOR_APP_NAME: &str = "Vector";
577
578/// Marketing site — surfaced as the signer's "More info" link.
579pub const VECTOR_APP_URL: &str = "https://vectorapp.io";
580
581/// Icon shown by the signer alongside the app name. PNG, served from the
582/// public GitHub mirror so the URL stays valid even if vectorapp.io changes
583/// its asset layout. Signers cache by URL, so a stable target avoids
584/// re-fetches on every pairing.
585pub const VECTOR_APP_ICON: &str = "https://raw.githubusercontent.com/VectorPrivacy/Vector/master/src-tauri/icons/icon.png";
586
587/// NIP-46 permission scope Vector requests on client-initiated pairings.
588///
589/// Sent as the `perms=` query parameter on `nostrconnect://` URIs. Signer apps
590/// that honour it (Amber, nsec.app) surface this list on their pairing screen
591/// and refuse RPC calls outside the granted scope. Vector intentionally never
592/// requests `get_private_key`: the whole point of a Remote Signer is that the
593/// identity nsec stays on the signer device, so allowing extraction would
594/// defeat the threat model. Adding a method here is an explicit policy
595/// decision; signer apps that don't enforce `perms` server-side still benefit
596/// from a smaller surface in their pairing UI.
597pub const VECTOR_NIP46_PERMS: &[&str] = &[
598    "get_public_key",
599    "sign_event",
600    "nip04_encrypt",
601    "nip04_decrypt",
602    "nip44_encrypt",
603    "nip44_decrypt",
604];
605
606/// Build the NIP-46 metadata payload Vector advertises in client-initiated
607/// `nostrconnect://` URIs. The signer reads this to render the approval
608/// prompt — name and icon are the bits the user actually sees.
609pub fn vector_metadata() -> NostrConnectMetadata {
610    let mut md = NostrConnectMetadata::new(VECTOR_APP_NAME);
611    if let Ok(url) = Url::parse(VECTOR_APP_URL) {
612        md = md.url(url);
613    }
614    if let Ok(icon) = Url::parse(VECTOR_APP_ICON) {
615        md = md.icons(vec![icon]);
616    }
617    md
618}
619
620/// Build a client-initiated `nostrconnect://` URI. The user copies this URL
621/// into their signer app (or scans the QR rendering of it); the signer
622/// initiates the connection back to the listed relays.
623///
624/// Multi-relay by design — single-relay connect URIs are a centralisation
625/// trap: if that one relay goes down, the user can't reconnect to their own
626/// account. Pass the live trusted-relay list from `state::TRUSTED_RELAYS`.
627pub fn build_nostrconnect_uri(
628    client_pubkey: PublicKey,
629    relays: Vec<RelayUrl>,
630) -> NostrConnectUri {
631    NostrConnectUri::Client {
632        public_key: client_pubkey,
633        relays,
634        metadata: vector_metadata(),
635        secret: random_connect_secret(),
636    }
637}
638
639/// Fresh NIP-46 pairing secret. The signer echoes it in the `connect` response;
640/// a mismatch means someone else answered, so it must be unguessable per session.
641fn random_connect_secret() -> String {
642    use ::rand::RngCore;
643    let mut bytes = [0u8; 16];
644    ::rand::rngs::OsRng.fill_bytes(&mut bytes);
645    bytes.iter().map(|b| format!("{b:02x}")).collect()
646}
647
648/// Build a `NostrConnect` for a client-initiated session — generates the
649/// `nostrconnect://` URI from the client keys + relays + Vector metadata,
650/// constructs the underlying `NostrConnect` with the Vector auth-URL handler
651/// already attached, and returns both for the caller to (a) display the URI
652/// to the user (QR + copy button) and (b) install the signer.
653///
654/// Note: doesn't bootstrap. The caller is expected to install the returned
655/// `NostrConnect` in `BUNKER_SIGNER` and await `get_public_key()` to wait
656/// for the signer's connect response.
657pub fn build_nostrconnect_session(
658    client_keys: Keys,
659    relays: Vec<RelayUrl>,
660    timeout: Duration,
661) -> Result<(NostrConnect, String), String> {
662    let uri = build_nostrconnect_uri(client_keys.public_key(), relays);
663    // Append the NIP-46 `perms=` scope. nostr-sdk's `Display` impl doesn't
664    // write it, so the SDK-built URI is fine to hand back to `NostrConnect`
665    // (which doesn't read perms locally), while the signer app on the other
666    // side parses the appended query param to render its pairing screen.
667    //
668    // The NIP-46 `secret` is always emitted: nostr-connect accepts only its echo
669    // here (a bare `"ack"` would let any relay participant pair as the signer).
670    let mut uri_string = uri.to_string();
671    let perms = VECTOR_NIP46_PERMS.join(",");
672    if !perms.is_empty() {
673        uri_string.push_str("&perms=");
674        uri_string.push_str(&perms);
675    }
676    let mut nc = NostrConnect::new(uri, client_keys, timeout, Some(crate::transport_relay_options()))
677        .map_err(|e| format!("Bunker init failed: {}", e))?;
678    nc.auth_url_handler(VectorAuthUrlHandler);
679    Ok((nc, uri_string))
680}
681
682/// Build a `NostrConnect` from a `bunker://` URL + client keypair. Doesn't
683/// connect yet — `NostrConnect` bootstraps lazily on the first signing call.
684/// Use `prewarm()` if you want the connection up before the user's first send.
685///
686/// `timeout` bounds each RPC round-trip. 60s is the upstream example; we
687/// expose it so chat-send paths can tighten this for snappier failure surfacing.
688pub fn build_bunker_signer(
689    bunker_url: &str,
690    client_keys: Keys,
691    timeout: Duration,
692) -> Result<NostrConnect, String> {
693    let uri = NostrConnectUri::parse(bunker_url)
694        .map_err(|e| format!("Invalid bunker URL: {}", e))?;
695    NostrConnect::new(uri, client_keys, timeout, Some(crate::transport_relay_options()))
696        .map_err(|e| format!("Bunker init failed: {}", e))
697}
698
699/// Force a bunker bootstrap and discover the user's identity pubkey.
700///
701/// The signer's *device* pubkey (returned by `bunker_uri()`) is NOT the user
702/// identity for signers like Amber — bypassing this RPC produces events
703/// signed under the wrong key. In Amber's "Manually approve each" mode this
704/// prompts the user once during initial pairing.
705pub async fn prewarm_bunker(signer: &NostrConnect) -> Result<PublicKey, String> {
706    signer
707        .get_public_key_async()
708        .await
709        .map_err(|e| format!("Bunker prewarm failed: {}", e))
710}
711
712// ============================================================================
713// BunkerConnectionState — observable connection lifecycle
714// ============================================================================
715
716/// Observable state of the bunker connection. The atomic backs hot-path reads
717/// (e.g. send paths checking "is it safe to issue a sign call?"); state changes
718/// also fan out to the frontend via `EventEmitter` so the UI can show a banner.
719#[derive(Copy, Clone, Debug, Eq, PartialEq)]
720#[repr(u8)]
721pub enum BunkerConnectionState {
722    /// No active bunker session. Either we're on a local account, or we're
723    /// between login and the first successful bootstrap.
724    Idle = 0,
725    /// Currently bootstrapping (relay connect + remote-pubkey discovery).
726    Connecting = 1,
727    /// Bunker is reachable; signing calls should succeed.
728    Online = 2,
729    /// Bunker is unreachable. Hot-path sends will fail fast; the next signing
730    /// call will retry the underlying NostrConnect path which may reconnect.
731    Offline = 3,
732}
733
734impl BunkerConnectionState {
735    /// User-facing label, mirrored to the frontend in `bunker_state` events.
736    pub fn as_label(self) -> &'static str {
737        match self {
738            BunkerConnectionState::Idle => "idle",
739            BunkerConnectionState::Connecting => "connecting",
740            BunkerConnectionState::Online => "online",
741            BunkerConnectionState::Offline => "offline",
742        }
743    }
744}
745
746static BUNKER_STATE: AtomicU8 = AtomicU8::new(BunkerConnectionState::Idle as u8);
747
748/// Read the live bunker connection state. Backed by an atomic; cheap to call.
749#[inline]
750pub fn bunker_state() -> BunkerConnectionState {
751    match BUNKER_STATE.load(Ordering::Acquire) {
752        1 => BunkerConnectionState::Connecting,
753        2 => BunkerConnectionState::Online,
754        3 => BunkerConnectionState::Offline,
755        _ => BunkerConnectionState::Idle,
756    }
757}
758
759/// Install a new bunker state and fan out a `bunker_state` event to the
760/// frontend. No-op if the state didn't change — avoids spamming the UI with
761/// duplicate transitions when a signing call confirms what's already known.
762pub fn set_bunker_state(new_state: BunkerConnectionState) {
763    let prev = BUNKER_STATE.swap(new_state as u8, Ordering::AcqRel);
764    if prev == new_state as u8 {
765        return;
766    }
767    crate::traits::emit_event_json(
768        "bunker_state",
769        serde_json::json!({ "state": new_state.as_label() }),
770    );
771}
772
773// ============================================================================
774// WatchedBunkerSigner — wrap NostrConnect with bunker_state observability
775// ============================================================================
776//
777// Every signing operation (sign_event, nip44_encrypt, nip04_*) flows through
778// this adapter when a bunker account is active. On success we flip
779// `BUNKER_STATE` to Online; on error we flip to Offline. The frontend's
780// `bunker_state` listener picks up the transition and surfaces a banner /
781// toast so the user knows when their signer becomes unreachable mid-session.
782//
783// State flips are deduplicated by `set_bunker_state` (same-value writes are
784// no-ops), so the per-call overhead is just one atomic load.
785
786/// `VectorSigner` wrapper that emits `BunkerConnectionState` transitions on
787/// every signing outcome. The inner `NostrConnect` is cheaply clonable
788/// (internally Arc'd), so this is also Clone.
789///
790/// Captures a `std::sync::Arc<crate::db::Session>` at construction; state flips after `reset_session`
791/// are no-ops to avoid leaking signer-state events across an account swap (an
792/// in-flight signing call resolving after the new account is installed would
793/// otherwise emit `bunker_state: offline` against a local-account session).
794#[derive(Debug, Clone)]
795pub struct WatchedBunkerSigner {
796    inner: NostrConnect,
797    session: std::sync::Arc<crate::db::Session>,
798}
799
800impl WatchedBunkerSigner {
801    pub fn new(inner: NostrConnect) -> Self {
802        Self { inner, session: crate::db::current_session() }
803    }
804
805    /// Flip state only when the captured session is still active.
806    #[inline]
807    fn flip(&self, state: BunkerConnectionState) {
808        if self.session.is_live() {
809            set_bunker_state(state);
810        }
811    }
812
813    /// Test-only view onto the captured guard so a test can assert the
814    /// wrapper is bound to the session generation at construction.
815    #[cfg(test)]
816    pub(crate) fn session_id_for_test(&self) -> u64 {
817        self.session.id()
818    }
819}
820
821impl WatchedBunkerSigner {
822    /// Record the reachability implied by an outcome and normalise the bunker's
823    /// error into `SignerError`.
824    #[inline]
825    fn watch<T, E>(&self, res: Result<T, E>) -> Result<T, SignerError>
826    where
827        E: core::fmt::Display,
828    {
829        match res {
830            Ok(v) => {
831                self.flip(BunkerConnectionState::Online);
832                Ok(v)
833            }
834            Err(e) => {
835                self.flip(BunkerConnectionState::Offline);
836                Err(SignerError::backend(e))
837            }
838        }
839    }
840}
841
842impl AsyncGetPublicKey for WatchedBunkerSigner {
843    type Error = SignerError;
844
845    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
846        Box::pin(async move { self.watch(self.inner.get_public_key_async().await) })
847    }
848}
849
850impl AsyncSignEvent for WatchedBunkerSigner {
851    type Error = SignerError;
852
853    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
854        Box::pin(async move { self.watch(self.inner.sign_event_async(unsigned).await) })
855    }
856}
857
858impl AsyncNip04 for WatchedBunkerSigner {
859    type Error = SignerError;
860
861    fn nip04_encrypt_async<'a>(
862        &'a self,
863        public_key: &'a PublicKey,
864        content: &'a str,
865    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
866        Box::pin(async move { self.watch(self.inner.nip04_encrypt_async(public_key, content).await) })
867    }
868
869    fn nip04_decrypt_async<'a>(
870        &'a self,
871        public_key: &'a PublicKey,
872        encrypted_content: &'a str,
873    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
874        Box::pin(async move {
875            self.watch(self.inner.nip04_decrypt_async(public_key, encrypted_content).await)
876        })
877    }
878}
879
880impl AsyncNip44 for WatchedBunkerSigner {
881    type Error = SignerError;
882
883    fn nip44_encrypt_async<'a>(
884        &'a self,
885        public_key: &'a PublicKey,
886        content: &'a str,
887    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
888        Box::pin(async move { self.watch(self.inner.nip44_encrypt_async(public_key, content).await) })
889    }
890
891    fn nip44_decrypt_async<'a>(
892        &'a self,
893        public_key: &'a PublicKey,
894        payload: &'a str,
895    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
896        Box::pin(async move { self.watch(self.inner.nip44_decrypt_async(public_key, payload).await) })
897    }
898}
899
900// ============================================================================
901// VectorAuthUrlHandler — bridge bunker permission prompts to the frontend
902// ============================================================================
903//
904// NIP-46 signers occasionally need user approval (e.g. signing an event kind
905// the user hasn't yet granted blanket permission for). Amber and nsec.app
906// respond with an `auth_url` the user must visit; on completion the signing
907// retry succeeds. This handler emits the URL to the frontend so the UI can
908// show a "Open signer" prompt — we deliberately don't auto-open a browser
909// from the core because (a) the core doesn't own the platform-specific
910// browser-open path, and (b) frontends may prefer in-app webview.
911
912/// Auth-URL handler that forwards bunker prompts to the frontend via the
913/// `EventEmitter` trait. The frontend receives a `bunker_auth_url` event and
914/// is responsible for opening the URL (in-app webview, system browser, ...).
915#[derive(Debug, Clone, Default)]
916pub struct VectorAuthUrlHandler;
917
918impl AuthUrlHandler for VectorAuthUrlHandler {
919    fn on_auth_url<'a>(&'a self, auth_url: Url) -> BoxedFuture<'a, std::result::Result<(), nostr_connect::error::Error>> {
920        Box::pin(async move {
921            crate::traits::emit_event_json(
922                "bunker_auth_url",
923                serde_json::json!({ "url": auth_url.to_string() }),
924            );
925            Ok(())
926        })
927    }
928}
929
930// ============================================================================
931// attempt_bunker_login — end-to-end: build → prewarm → install
932// ============================================================================
933
934/// Build a `NostrConnect`, attach the Vector auth-URL handler, bootstrap it,
935/// and install it as the active bunker signer. Returns the discovered remote
936/// signer pubkey on success.
937///
938/// Emits `bunker_state` transitions: Connecting → Online (on success) or
939/// Connecting → Offline (on failure). The caller is expected to update the
940/// account-level discriminator (`signer_kind`) separately — this helper deals
941/// only with the live connection.
942pub async fn attempt_bunker_login(
943    bunker_url: &str,
944    client_keys: Keys,
945    timeout: Duration,
946) -> Result<PublicKey, String> {
947    set_bunker_state(BunkerConnectionState::Connecting);
948
949    let mut nc = match build_bunker_signer(bunker_url, client_keys, timeout) {
950        Ok(nc) => nc,
951        Err(e) => {
952            set_bunker_state(BunkerConnectionState::Offline);
953            return Err(e);
954        }
955    };
956    nc.auth_url_handler(VectorAuthUrlHandler);
957    let pairing = track_pairing(&nc);
958
959    match prewarm_bunker(&nc).await {
960        Ok(remote_pk) => match pairing.install(nc) {
961            Ok(old) => {
962                // A prior NostrConnect (retry-after-blip path) drains in the background:
963                // repeated calls would otherwise leak relay pools fighting for slots.
964                if let Some(old) = old {
965                    // spawn-detached: drains the replaced signer's relay pool; it holds no
966                    // account state and must finish even if the account swaps meanwhile.
967                    crate::rt::spawn(async move { let _ = old.shutdown().await; });
968                }
969                set_bunker_state(BunkerConnectionState::Online);
970                Ok(remote_pk)
971            }
972            Err(PairingAborted) => {
973                set_bunker_state(BunkerConnectionState::Offline);
974                Err(NETWORK_CHANGED.into())
975            }
976        },
977        Err(e) => {
978            // The just-built `nc`'s Drop will release its half-opened relay
979            // connections asynchronously; we don't need a shutdown call here
980            // because we never installed it as the active signer.
981            set_bunker_state(BunkerConnectionState::Offline);
982            Err(if pairing.aborted() { NETWORK_CHANGED.into() } else { e })
983        }
984    }
985}
986
987// ============================================================================
988// Network switches
989// ============================================================================
990
991/// A bunker closed for a network switch: what rebuilds it once the new network is ready.
992struct Suspended {
993    uri: NostrConnectUri,
994    keys: Keys,
995    user: Option<PublicKey>,
996}
997
998static SUSPENDED: std::sync::Mutex<Option<Suspended>> = std::sync::Mutex::new(None);
999
1000/// What a pairing that a network switch cut off reports.
1001pub const NETWORK_CHANGED: &str = "The network changed. Try again.";
1002
1003// A NIP-46 client between its build and its install sits in no slot, yet its stock sockets
1004// answer to no network switch: every one is registered here until it is installed or dropped.
1005struct Pairing {
1006    id: u64,
1007    nc: NostrConnect,
1008    aborted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1009}
1010
1011static PAIRINGS: std::sync::Mutex<Vec<Pairing>> = std::sync::Mutex::new(Vec::new());
1012static PAIRING_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1013
1014/// A network switch cut the pairing off before it could be installed.
1015#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1016pub struct PairingAborted;
1017
1018/// Held while a NIP-46 client pairs outside the signer slot. A network switch shuts the client
1019/// down and marks the pairing aborted; dropping the guard forgets it.
1020#[must_use = "the pairing is forgotten when the guard drops"]
1021pub struct PairingGuard {
1022    id: u64,
1023    aborted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1024}
1025
1026impl PairingGuard {
1027    /// A network switch cut this pairing off: its sockets are closed and it must not be used.
1028    pub fn aborted(&self) -> bool {
1029        self.aborted.load(Ordering::Acquire)
1030    }
1031
1032    /// Install the paired client, returning the signer it replaces. Atomic against a switch: the
1033    /// switch either finds it in the slot or has already aborted (and shut down) the pairing.
1034    pub fn install(self, nc: NostrConnect) -> Result<Option<NostrConnect>, PairingAborted> {
1035        let mut pairings = PAIRINGS.lock().unwrap_or_else(|e| e.into_inner());
1036        if self.aborted() {
1037            return Err(PairingAborted);
1038        }
1039        pairings.retain(|p| p.id != self.id);
1040        let old = take_bunker_signer();
1041        set_bunker_signer(nc);
1042        // A freshly paired signer supersedes one a switch suspended.
1043        *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = None;
1044        Ok(old)
1045    }
1046}
1047
1048impl Drop for PairingGuard {
1049    fn drop(&mut self) {
1050        PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).retain(|p| p.id != self.id);
1051    }
1052}
1053
1054/// Register a NIP-46 client that is not in the signer slot yet.
1055pub fn track_pairing(nc: &NostrConnect) -> PairingGuard {
1056    let id = PAIRING_SEQ.fetch_add(1, Ordering::Relaxed);
1057    let aborted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1058    PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).push(Pairing { id, nc: nc.clone(), aborted: aborted.clone() });
1059    PairingGuard { id, aborted }
1060}
1061
1062fn abort_pairings() -> Vec<NostrConnect> {
1063    PAIRINGS
1064        .lock()
1065        .unwrap_or_else(|e| e.into_inner())
1066        .drain(..)
1067        .map(|p| {
1068            p.aborted.store(true, Ordering::Release);
1069            p.nc
1070        })
1071        .collect()
1072}
1073
1074/// What a suspended signer rebuilds from, secret stripped: the stored (or staged) URL first, since
1075/// asking a client that never bootstrapped for its URI would bootstrap it.
1076async fn rebuild_uri(nc: &NostrConnect) -> Option<NostrConnectUri> {
1077    use futures_util::FutureExt;
1078    let stored = match crate::db::get_bunker_url().await {
1079        Ok(Some(url)) => Some(url),
1080        _ => crate::state::pending_bunker_setup().map(|(url, _)| url),
1081    };
1082    if let Some(NostrConnectUri::Bunker { remote_signer_public_key, relays, .. }) =
1083        stored.and_then(|url| NostrConnectUri::parse(&url).ok())
1084    {
1085        return Some(NostrConnectUri::Bunker { remote_signer_public_key, relays, secret: None });
1086    }
1087    match nc.bunker_uri().now_or_never() {
1088        Some(Ok(uri)) => Some(uri),
1089        _ => None,
1090    }
1091}
1092
1093/// NIP-46 clients are stock nostr-sdk clients no switch can close: shut down every pairing in
1094/// flight and the installed signer (keeping what rebuilds it), unless it never opened a socket.
1095pub async fn suspend_bunker() {
1096    use futures_util::FutureExt;
1097    for nc in abort_pairings() {
1098        nc.shutdown().await;
1099    }
1100    let Some(nc) = bunker_signer() else { return };
1101    if nc.status().now_or_never().is_some_and(|relays| relays.is_empty()) {
1102        return;
1103    }
1104    let Some(nc) = take_bunker_signer() else { return };
1105    match rebuild_uri(&nc).await {
1106        Some(uri) => {
1107            let user = crate::state::my_public_key();
1108            *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = Some(Suspended { uri, keys: nc.local_keys().clone(), user });
1109            set_bunker_state(BunkerConnectionState::Connecting);
1110        }
1111        // A signer pairing still waiting for its approval: nothing to rebuild, it starts over.
1112        None => set_bunker_state(BunkerConnectionState::Offline),
1113    }
1114    nc.shutdown().await;
1115}
1116
1117static RESUMING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1118
1119/// Clears [`RESUMING`] however a resume ends, a cancelled task included.
1120struct Resuming;
1121
1122impl Drop for Resuming {
1123    fn drop(&mut self) {
1124        RESUMING.store(false, Ordering::Release);
1125    }
1126}
1127
1128/// Rebuild a suspended bunker on the network now in use, bootstrapped before it takes the slot so
1129/// a signing call's clone never connects to the signer again. A no-op unless one was suspended.
1130pub async fn resume_bunker() {
1131    if bunker_signer().is_some() || RESUMING.swap(true, Ordering::AcqRel) {
1132        return;
1133    }
1134    let resuming = Resuming;
1135    let Some((uri, keys, user)) = SUSPENDED
1136        .lock()
1137        .unwrap_or_else(|e| e.into_inner())
1138        .as_ref()
1139        .map(|s| (s.uri.clone(), s.keys.clone(), s.user))
1140    else {
1141        return;
1142    };
1143    let mut nc = match NostrConnect::new(uri, keys, Duration::from_secs(60), Some(crate::transport_relay_options())) {
1144        Ok(nc) => nc,
1145        Err(e) => {
1146            crate::log_warn!("[Transport] could not rebuild the signer connection: {e}");
1147            set_bunker_state(BunkerConnectionState::Offline);
1148            return;
1149        }
1150    };
1151    nc.auth_url_handler(VectorAuthUrlHandler);
1152    if let Some(pk) = user {
1153        let _ = nc.non_secure_set_user_public_key(pk);
1154    }
1155    let pairing = track_pairing(&nc);
1156    // Bound: the signer it installs is this account's, and a swap drains SUSPENDED meanwhile.
1157    crate::db::spawn_bound(async move {
1158        let _resuming = resuming;
1159        let bootstrapped = nc.bunker_uri().await.is_ok();
1160        if pairing.aborted() || !crate::db::session_is_live() || !bunker_suspended() {
1161            nc.shutdown().await;
1162            return;
1163        }
1164        // An unreachable signer still gets its client: each signing call then retries the
1165        // connection itself, as before the switch.
1166        if pairing.install(nc).is_ok() {
1167            set_bunker_state(if bootstrapped { BunkerConnectionState::Online } else { BunkerConnectionState::Offline });
1168        }
1169    });
1170}
1171
1172/// Whether a bunker is suspended until the network is ready.
1173pub fn bunker_suspended() -> bool {
1174    SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()).is_some()
1175}
1176
1177/// A signer pairing is still waiting for its approval, in the slot or outside it.
1178pub fn pairing_pending() -> bool {
1179    (bunker_signer().is_some() && bunker_state() == BunkerConnectionState::Connecting)
1180        || !PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
1181}
1182
1183// ============================================================================
1184// Teardown
1185// ============================================================================
1186
1187/// Clear all bunker-specific state. Called by `reset_session()` so a swap
1188/// from bunker → local (or between two bunker accounts) leaves no stale
1189/// keying material, relay-pool handles, or stale connection-state observed
1190/// by the frontend. The caller is responsible for `.shutdown().await`-ing
1191/// the returned signer outside the lock.
1192pub fn drain_bunker_state() -> Option<NostrConnect> {
1193    // Resets SIGNER_KIND for EVERY signer kind, not just bunker — `reset_session`
1194    // calls this unconditionally, so a NIP-55 (or any) → local swap lands the
1195    // discriminator back at Local before the next account's login re-reads its
1196    // own signer_type. Do NOT make this bunker-conditional or is_keyless() gets
1197    // stuck across swaps.
1198    set_signer_kind(SignerKind::Local);
1199    set_bunker_state(BunkerConnectionState::Idle);
1200    *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = None;
1201    take_bunker_signer()
1202}
1203
1204#[cfg(test)]
1205mod tests {
1206    use super::*;
1207
1208    /// A signer other than the vault (here the test stand-in for a remote one) seals and wraps
1209    /// through its own signing, never the vault's key.
1210    #[tokio::test]
1211    async fn a_signer_that_is_not_the_vault_seals_and_wraps_itself() {
1212        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1213        let (vault_key, remote, peer) = (Keys::generate(), Keys::generate(), Keys::generate());
1214        crate::state::MY_SECRET_KEY.store_from_keys(&vault_key, &[]);
1215        set_test_signer(Some(ActiveSigner::Keys(remote.clone())));
1216        let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "x").finalize_unsigned(remote.public_key());
1217        let seal = seal_rumor(rumor.clone(), &peer.public_key()).await;
1218        let wrap = gift_wrap(&peer.public_key(), rumor, []).await;
1219        set_test_signer(None);
1220        crate::state::MY_SECRET_KEY.clear(&[]);
1221        assert_eq!(seal.unwrap().pubkey, remote.public_key(), "sealed by the signer");
1222        let opened = UnwrappedGift::from_gift_wrap(&peer, &wrap.unwrap()).unwrap();
1223        assert_eq!(opened.sender, remote.public_key(), "wrapped by the signer");
1224    }
1225
1226    #[test]
1227    fn resolving_a_local_signer_refuses_a_vault_key_that_is_not_the_identity() {
1228        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1229        set_signer_kind(SignerKind::Local);
1230        let (me, other) = (Keys::generate(), Keys::generate());
1231        crate::state::set_my_public_key(me.public_key());
1232        crate::state::MY_SECRET_KEY.store_from_keys(&other, &[]);
1233        let refused = active_signer().is_err();
1234        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
1235        let accepted = matches!(active_signer(), Ok(ActiveSigner::Local(_)));
1236        crate::state::MY_SECRET_KEY.clear(&[]);
1237        crate::state::clear_my_public_key();
1238        assert!(refused, "a key that isn't the identity is refused before any work");
1239        assert!(accepted, "the identity's own key resolves");
1240    }
1241
1242    #[test]
1243    fn the_vault_keys_owner_follows_every_set_and_clear() {
1244        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1245        let (me, other) = (Keys::generate(), Keys::generate());
1246        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
1247        assert_eq!(local_key_owner(), Some(me.public_key()));
1248        assert_eq!(local_key_owner(), Some(me.public_key()), "answered again from the cache");
1249        crate::state::MY_SECRET_KEY.store_from_keys(&other, &[]);
1250        assert_eq!(local_key_owner(), Some(other.public_key()), "a set is never answered from a stale cache");
1251        // Another key's write moves the count too, and the owner is derived again, unchanged.
1252        crate::state::ENCRYPTION_KEY.set([7u8; 32], &[&crate::state::MY_SECRET_KEY]);
1253        assert_eq!(local_key_owner(), Some(other.public_key()));
1254        crate::state::ENCRYPTION_KEY.clear(&[&crate::state::MY_SECRET_KEY]);
1255        crate::state::MY_SECRET_KEY.clear(&[]);
1256        assert_eq!(local_key_owner(), None);
1257    }
1258
1259    #[test]
1260    fn setting_roundtrip() {
1261        assert_eq!(SignerKind::from_setting_str("local"), SignerKind::Local);
1262        assert_eq!(SignerKind::from_setting_str("bunker"), SignerKind::Bunker);
1263        assert_eq!(SignerKind::from_setting_str("nip55"), SignerKind::Nip55);
1264        assert_eq!(SignerKind::from_setting_str("nip07"), SignerKind::Nip07);
1265        assert_eq!(SignerKind::Nip07.as_setting_str(), "nip07");
1266        assert_eq!(SignerKind::Local.as_setting_str(), "local");
1267        assert_eq!(SignerKind::Bunker.as_setting_str(), "bunker");
1268        assert_eq!(SignerKind::Nip55.as_setting_str(), "nip55");
1269        // Unknown values fall back to Local — upgrade path for pre-NIP-46 rows.
1270        assert_eq!(SignerKind::from_setting_str(""), SignerKind::Local);
1271        assert_eq!(SignerKind::from_setting_str("garbage"), SignerKind::Local);
1272    }
1273
1274    // SIGNER_KIND + BUNKER_SIGNER + BUNKER_STATE are process-wide atomics /
1275    // locks. Cargo runs `#[test]` functions in parallel, so any pair of
1276    // tests that mutate the same global races and produces flaky failures.
1277    // Bundled into one test function so the sequence is deterministic —
1278    // mirrors `session_helpers_round_trip_and_clear` in state.rs which
1279    // does the same for `MY_PUBLIC_KEY` / `PENDING_INVITE`.
1280    #[test]
1281    fn atomic_state_round_trips_and_drains() {
1282        // Held so tests that resolve a Local signer never see the kind flipped mid-test.
1283        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1284        // Defensive cleanup: a previous test panic could have left a non-
1285        // default value behind.
1286        set_signer_kind(SignerKind::Local);
1287        set_bunker_state(BunkerConnectionState::Idle);
1288
1289        // atomic kind roundtrip
1290        set_signer_kind(SignerKind::Bunker);
1291        assert_eq!(signer_kind(), SignerKind::Bunker);
1292        assert!(is_bunker());
1293        assert!(is_keyless());
1294        set_signer_kind(SignerKind::Local);
1295        assert_eq!(signer_kind(), SignerKind::Local);
1296        assert!(!is_bunker());
1297        assert!(!is_keyless());
1298
1299        // NIP-55 is keyless but NOT a bunker — the two gates must not conflate.
1300        set_signer_kind(SignerKind::Nip55);
1301        assert_eq!(signer_kind(), SignerKind::Nip55);
1302        assert!(!is_bunker());
1303        assert!(is_keyless());
1304        set_signer_kind(SignerKind::Local);
1305
1306        // drain resets discriminator + state and returns the (absent) signer
1307        set_signer_kind(SignerKind::Bunker);
1308        set_bunker_state(BunkerConnectionState::Online);
1309        let drained = drain_bunker_state();
1310        assert!(drained.is_none());
1311        assert_eq!(signer_kind(), SignerKind::Local);
1312        assert_eq!(bunker_state(), BunkerConnectionState::Idle);
1313
1314        // drain is idempotent — running again on already-cleared state is
1315        // safe (no panic, no spurious event), and leaves things clean.
1316        let drained_again = drain_bunker_state();
1317        assert!(drained_again.is_none());
1318        assert_eq!(signer_kind(), SignerKind::Local);
1319        assert_eq!(bunker_state(), BunkerConnectionState::Idle);
1320    }
1321
1322    #[test]
1323    fn bunker_state_label_covers_all_variants() {
1324        // Whenever a new BunkerConnectionState is added, this test forces a
1325        // matching label so the frontend's `bunker_state` listener never sees
1326        // an unlabelled discriminant.
1327        assert_eq!(BunkerConnectionState::Idle.as_label(), "idle");
1328        assert_eq!(BunkerConnectionState::Connecting.as_label(), "connecting");
1329        assert_eq!(BunkerConnectionState::Online.as_label(), "online");
1330        assert_eq!(BunkerConnectionState::Offline.as_label(), "offline");
1331    }
1332
1333    #[test]
1334    fn parse_bunker_relays_returns_relays_from_bunker_uri() {
1335        let signer_keys = Keys::generate();
1336        let r1 = RelayUrl::parse("wss://relay1.example").unwrap();
1337        let r2 = RelayUrl::parse("wss://relay2.example").unwrap();
1338        let uri = NostrConnectUri::Bunker {
1339            remote_signer_public_key: signer_keys.public_key(),
1340            relays: vec![r1.clone(), r2.clone()],
1341            secret: None,
1342        };
1343        let relays = parse_bunker_relays(&uri.to_string());
1344        assert_eq!(relays.len(), 2);
1345        assert!(relays.iter().any(|r| r.contains("relay1.example")));
1346        assert!(relays.iter().any(|r| r.contains("relay2.example")));
1347    }
1348
1349    #[test]
1350    fn parse_bunker_relays_returns_empty_on_invalid_input() {
1351        // Display-only signal; never panics, never errors. Bad input collapses
1352        // to "no relays known" so the Security panel falls back to "unknown"
1353        // instead of crashing.
1354        assert!(parse_bunker_relays("").is_empty());
1355        assert!(parse_bunker_relays("not a url").is_empty());
1356        assert!(parse_bunker_relays("http://example.com").is_empty());
1357
1358        // Client-initiated URIs also return empty — they're not the bunker
1359        // form we want to surface relays for.
1360        let client_keys = Keys::generate();
1361        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1362        let client_uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
1363        assert!(parse_bunker_relays(&client_uri.to_string()).is_empty(),
1364            "client URI must not surface as a bunker relay list");
1365    }
1366
1367    #[test]
1368    fn parse_bunker_remote_pubkey_invalid_url() {
1369        assert!(parse_bunker_remote_pubkey("not a url").is_err());
1370        assert!(parse_bunker_remote_pubkey("").is_err());
1371        assert!(parse_bunker_remote_pubkey("http://example.com").is_err());
1372    }
1373
1374    #[test]
1375    fn parse_bunker_remote_pubkey_rejects_client_uri() {
1376        // A client-initiated `nostrconnect://` URI is not a login entry point;
1377        // accepting it would let a hostile clipboard string register an
1378        // attacker-controlled client pubkey as "the remote signer".
1379        let client_keys = Keys::generate();
1380        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1381        let uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
1382        let err = parse_bunker_remote_pubkey(&uri.to_string())
1383            .expect_err("client URI must be rejected");
1384        assert!(err.contains("Client-initiated"), "unexpected error: {}", err);
1385    }
1386
1387    #[test]
1388    fn parse_bunker_remote_pubkey_normalizes_lowercase() {
1389        // Build a valid bunker URI with a known pubkey and verify the parse
1390        // result is forced to lowercase regardless of upstream casing choice.
1391        let signer_keys = Keys::generate();
1392        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1393        let uri = NostrConnectUri::Bunker {
1394            remote_signer_public_key: signer_keys.public_key(),
1395            relays: vec![relay],
1396            secret: None,
1397        };
1398        let parsed = parse_bunker_remote_pubkey(&uri.to_string())
1399            .expect("valid bunker URI");
1400        assert_eq!(parsed, signer_keys.public_key().to_hex().to_ascii_lowercase());
1401        assert_eq!(parsed, parsed.to_ascii_lowercase(),
1402            "callers may compare with == — output must already be lowercase");
1403    }
1404
1405    #[test]
1406    fn vector_metadata_carries_app_name_and_icon() {
1407        let md = vector_metadata();
1408        let json = serde_json::to_string(&md).expect("metadata serializes");
1409        assert!(json.contains(VECTOR_APP_NAME),
1410            "metadata must include app name for the signer's approval prompt; got {}", json);
1411        assert!(json.contains("vectorapp.io"),
1412            "metadata must reference the app URL for the signer's 'More info' link");
1413    }
1414
1415    #[test]
1416    fn nip46_perms_list_excludes_get_private_key() {
1417        // The whole point of a Remote Signer is keeping the identity nsec on
1418        // the signer device. Adding `get_private_key` to the requested perms
1419        // would invite the signer to expose it back to Vector and defeat the
1420        // threat model. This test fails loudly if a future edit re-adds it.
1421        for perm in VECTOR_NIP46_PERMS {
1422            assert!(!perm.contains("get_private_key"),
1423                "VECTOR_NIP46_PERMS must never include get_private_key (found: {})", perm);
1424            assert!(!perm.contains("private_key"),
1425                "perm string looks dangerous: {}", perm);
1426        }
1427    }
1428
1429    #[test]
1430    fn build_nostrconnect_session_appends_perms_query_param() {
1431        let client_keys = Keys::generate();
1432        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1433        let (_nc, uri) = build_nostrconnect_session(
1434            client_keys,
1435            vec![relay],
1436            std::time::Duration::from_secs(1),
1437        ).expect("session builds");
1438        assert!(uri.contains("perms="),
1439            "URI must carry perms query param so signers can scope the pairing; got: {}", uri);
1440        // Every permission we DO ask for must appear in the URI.
1441        for perm in VECTOR_NIP46_PERMS {
1442            assert!(uri.contains(perm),
1443                "URI missing permission '{}': {}", perm, uri);
1444        }
1445        // And get_private_key must NOT.
1446        assert!(!uri.contains("get_private_key"),
1447            "URI must never request get_private_key: {}", uri);
1448    }
1449
1450    #[test]
1451    fn build_nostrconnect_session_rejects_empty_uri() {
1452        // `build_nostrconnect_session` is the QR-flow entry. Constructing one
1453        // with zero relays would produce a URI that no signer can connect
1454        // back to — caller-side check is in `start_nostrconnect_session`, but
1455        // this is a sanity test that NostrConnect itself does not silently
1456        // accept an empty relay list at the URI level.
1457        let client_keys = Keys::generate();
1458        let session = build_nostrconnect_session(
1459            client_keys,
1460            vec![],
1461            std::time::Duration::from_secs(1),
1462        );
1463        // We don't assert pass/fail — different upstream versions may treat
1464        // empty relays differently — only that we don't panic.
1465        let _ = session;
1466    }
1467
1468    // Combined into one #[test] to serialise mutation of process-wide globals
1469    // (BUNKER_STATE, BUNKER_SIGNER). See the rationale on
1470    // `atomic_state_round_trips_and_drains` above.
1471    #[test]
1472    fn watched_signer_session_gate_and_state_transitions() {
1473        // It swaps the live session, which every transport test reads.
1474        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1475
1476        // Build a real NostrConnect so we can wrap it. We never call any of
1477        // its async methods (those would require a relay) — only the inner
1478        // wrapper's session-guard semantics are under test.
1479        let client_keys = Keys::generate();
1480        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1481        let signer_keys = Keys::generate();
1482        let uri = NostrConnectUri::Bunker {
1483            remote_signer_public_key: signer_keys.public_key(),
1484            relays: vec![relay],
1485            secret: None,
1486        };
1487        let nc = NostrConnect::new(
1488            uri,
1489            client_keys,
1490            std::time::Duration::from_secs(1),
1491            None,
1492        ).expect("NostrConnect builds");
1493
1494        let gen_before = crate::db::current_session_id();
1495        let watched = WatchedBunkerSigner::new(nc);
1496        assert_eq!(watched.session_id_for_test(), gen_before,
1497            "WatchedBunkerSigner must capture the live session generation at construction");
1498
1499        // Pre-swap: flip emits because the captured guard matches.
1500        set_bunker_state(BunkerConnectionState::Idle);
1501        watched.flip(BunkerConnectionState::Online);
1502        assert_eq!(bunker_state(), BunkerConnectionState::Online,
1503            "flip with valid session must update bunker_state");
1504
1505        // Simulate a session swap (logout / account swap). The captured
1506        // guard goes stale; subsequent flips must be ignored so a leftover
1507        // in-flight signing call from the previous account can't leak
1508        // bunker_state changes into the new session.
1509        crate::db::close_database();
1510        set_bunker_state(BunkerConnectionState::Online);
1511        watched.flip(BunkerConnectionState::Offline);
1512        assert_eq!(bunker_state(), BunkerConnectionState::Online,
1513            "flip with stale session must be a no-op");
1514
1515        // Cleanup so subsequent test runs / siblings see a sane state.
1516        set_bunker_state(BunkerConnectionState::Idle);
1517    }
1518}