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 emitted now (0.45 requires it, and its response
669    // parser accepts both a spec-compliant secret echo and Amber's bare `"ack"`),
670    // so spoof detection costs nothing in interop.
671    let mut uri_string = uri.to_string();
672    let perms = VECTOR_NIP46_PERMS.join(",");
673    if !perms.is_empty() {
674        uri_string.push_str("&perms=");
675        uri_string.push_str(&perms);
676    }
677    let mut nc = NostrConnect::new(uri, client_keys, timeout, Some(crate::transport_relay_options()))
678        .map_err(|e| format!("Bunker init failed: {}", e))?;
679    nc.auth_url_handler(VectorAuthUrlHandler);
680    Ok((nc, uri_string))
681}
682
683/// Build a `NostrConnect` from a `bunker://` URL + client keypair. Doesn't
684/// connect yet — `NostrConnect` bootstraps lazily on the first signing call.
685/// Use `prewarm()` if you want the connection up before the user's first send.
686///
687/// `timeout` bounds each RPC round-trip. 60s is the upstream example; we
688/// expose it so chat-send paths can tighten this for snappier failure surfacing.
689pub fn build_bunker_signer(
690    bunker_url: &str,
691    client_keys: Keys,
692    timeout: Duration,
693) -> Result<NostrConnect, String> {
694    let uri = NostrConnectUri::parse(bunker_url)
695        .map_err(|e| format!("Invalid bunker URL: {}", e))?;
696    NostrConnect::new(uri, client_keys, timeout, Some(crate::transport_relay_options()))
697        .map_err(|e| format!("Bunker init failed: {}", e))
698}
699
700/// Force a bunker bootstrap and discover the user's identity pubkey.
701///
702/// The signer's *device* pubkey (returned by `bunker_uri()`) is NOT the user
703/// identity for signers like Amber — bypassing this RPC produces events
704/// signed under the wrong key. In Amber's "Manually approve each" mode this
705/// prompts the user once during initial pairing.
706pub async fn prewarm_bunker(signer: &NostrConnect) -> Result<PublicKey, String> {
707    signer
708        .get_public_key_async()
709        .await
710        .map_err(|e| format!("Bunker prewarm failed: {}", e))
711}
712
713// ============================================================================
714// BunkerConnectionState — observable connection lifecycle
715// ============================================================================
716
717/// Observable state of the bunker connection. The atomic backs hot-path reads
718/// (e.g. send paths checking "is it safe to issue a sign call?"); state changes
719/// also fan out to the frontend via `EventEmitter` so the UI can show a banner.
720#[derive(Copy, Clone, Debug, Eq, PartialEq)]
721#[repr(u8)]
722pub enum BunkerConnectionState {
723    /// No active bunker session. Either we're on a local account, or we're
724    /// between login and the first successful bootstrap.
725    Idle = 0,
726    /// Currently bootstrapping (relay connect + remote-pubkey discovery).
727    Connecting = 1,
728    /// Bunker is reachable; signing calls should succeed.
729    Online = 2,
730    /// Bunker is unreachable. Hot-path sends will fail fast; the next signing
731    /// call will retry the underlying NostrConnect path which may reconnect.
732    Offline = 3,
733}
734
735impl BunkerConnectionState {
736    /// User-facing label, mirrored to the frontend in `bunker_state` events.
737    pub fn as_label(self) -> &'static str {
738        match self {
739            BunkerConnectionState::Idle => "idle",
740            BunkerConnectionState::Connecting => "connecting",
741            BunkerConnectionState::Online => "online",
742            BunkerConnectionState::Offline => "offline",
743        }
744    }
745}
746
747static BUNKER_STATE: AtomicU8 = AtomicU8::new(BunkerConnectionState::Idle as u8);
748
749/// Read the live bunker connection state. Backed by an atomic; cheap to call.
750#[inline]
751pub fn bunker_state() -> BunkerConnectionState {
752    match BUNKER_STATE.load(Ordering::Acquire) {
753        1 => BunkerConnectionState::Connecting,
754        2 => BunkerConnectionState::Online,
755        3 => BunkerConnectionState::Offline,
756        _ => BunkerConnectionState::Idle,
757    }
758}
759
760/// Install a new bunker state and fan out a `bunker_state` event to the
761/// frontend. No-op if the state didn't change — avoids spamming the UI with
762/// duplicate transitions when a signing call confirms what's already known.
763pub fn set_bunker_state(new_state: BunkerConnectionState) {
764    let prev = BUNKER_STATE.swap(new_state as u8, Ordering::AcqRel);
765    if prev == new_state as u8 {
766        return;
767    }
768    crate::traits::emit_event_json(
769        "bunker_state",
770        serde_json::json!({ "state": new_state.as_label() }),
771    );
772}
773
774// ============================================================================
775// WatchedBunkerSigner — wrap NostrConnect with bunker_state observability
776// ============================================================================
777//
778// Every signing operation (sign_event, nip44_encrypt, nip04_*) flows through
779// this adapter when a bunker account is active. On success we flip
780// `BUNKER_STATE` to Online; on error we flip to Offline. The frontend's
781// `bunker_state` listener picks up the transition and surfaces a banner /
782// toast so the user knows when their signer becomes unreachable mid-session.
783//
784// State flips are deduplicated by `set_bunker_state` (same-value writes are
785// no-ops), so the per-call overhead is just one atomic load.
786
787/// `VectorSigner` wrapper that emits `BunkerConnectionState` transitions on
788/// every signing outcome. The inner `NostrConnect` is cheaply clonable
789/// (internally Arc'd), so this is also Clone.
790///
791/// Captures a `std::sync::Arc<crate::db::Session>` at construction; state flips after `reset_session`
792/// are no-ops to avoid leaking signer-state events across an account swap (an
793/// in-flight signing call resolving after the new account is installed would
794/// otherwise emit `bunker_state: offline` against a local-account session).
795#[derive(Debug, Clone)]
796pub struct WatchedBunkerSigner {
797    inner: NostrConnect,
798    session: std::sync::Arc<crate::db::Session>,
799}
800
801impl WatchedBunkerSigner {
802    pub fn new(inner: NostrConnect) -> Self {
803        Self { inner, session: crate::db::current_session() }
804    }
805
806    /// Flip state only when the captured session is still active.
807    #[inline]
808    fn flip(&self, state: BunkerConnectionState) {
809        if self.session.is_live() {
810            set_bunker_state(state);
811        }
812    }
813
814    /// Test-only view onto the captured guard so a test can assert the
815    /// wrapper is bound to the session generation at construction.
816    #[cfg(test)]
817    pub(crate) fn session_id_for_test(&self) -> u64 {
818        self.session.id()
819    }
820}
821
822impl WatchedBunkerSigner {
823    /// Record the reachability implied by an outcome and normalise the bunker's
824    /// error into `SignerError`.
825    #[inline]
826    fn watch<T, E>(&self, res: Result<T, E>) -> Result<T, SignerError>
827    where
828        E: core::fmt::Display,
829    {
830        match res {
831            Ok(v) => {
832                self.flip(BunkerConnectionState::Online);
833                Ok(v)
834            }
835            Err(e) => {
836                self.flip(BunkerConnectionState::Offline);
837                Err(SignerError::backend(e))
838            }
839        }
840    }
841}
842
843impl AsyncGetPublicKey for WatchedBunkerSigner {
844    type Error = SignerError;
845
846    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
847        Box::pin(async move { self.watch(self.inner.get_public_key_async().await) })
848    }
849}
850
851impl AsyncSignEvent for WatchedBunkerSigner {
852    type Error = SignerError;
853
854    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
855        Box::pin(async move { self.watch(self.inner.sign_event_async(unsigned).await) })
856    }
857}
858
859impl AsyncNip04 for WatchedBunkerSigner {
860    type Error = SignerError;
861
862    fn nip04_encrypt_async<'a>(
863        &'a self,
864        public_key: &'a PublicKey,
865        content: &'a str,
866    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
867        Box::pin(async move { self.watch(self.inner.nip04_encrypt_async(public_key, content).await) })
868    }
869
870    fn nip04_decrypt_async<'a>(
871        &'a self,
872        public_key: &'a PublicKey,
873        encrypted_content: &'a str,
874    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
875        Box::pin(async move {
876            self.watch(self.inner.nip04_decrypt_async(public_key, encrypted_content).await)
877        })
878    }
879}
880
881impl AsyncNip44 for WatchedBunkerSigner {
882    type Error = SignerError;
883
884    fn nip44_encrypt_async<'a>(
885        &'a self,
886        public_key: &'a PublicKey,
887        content: &'a str,
888    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
889        Box::pin(async move { self.watch(self.inner.nip44_encrypt_async(public_key, content).await) })
890    }
891
892    fn nip44_decrypt_async<'a>(
893        &'a self,
894        public_key: &'a PublicKey,
895        payload: &'a str,
896    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
897        Box::pin(async move { self.watch(self.inner.nip44_decrypt_async(public_key, payload).await) })
898    }
899}
900
901// ============================================================================
902// VectorAuthUrlHandler — bridge bunker permission prompts to the frontend
903// ============================================================================
904//
905// NIP-46 signers occasionally need user approval (e.g. signing an event kind
906// the user hasn't yet granted blanket permission for). Amber and nsec.app
907// respond with an `auth_url` the user must visit; on completion the signing
908// retry succeeds. This handler emits the URL to the frontend so the UI can
909// show a "Open signer" prompt — we deliberately don't auto-open a browser
910// from the core because (a) the core doesn't own the platform-specific
911// browser-open path, and (b) frontends may prefer in-app webview.
912
913/// Auth-URL handler that forwards bunker prompts to the frontend via the
914/// `EventEmitter` trait. The frontend receives a `bunker_auth_url` event and
915/// is responsible for opening the URL (in-app webview, system browser, ...).
916#[derive(Debug, Clone, Default)]
917pub struct VectorAuthUrlHandler;
918
919impl AuthUrlHandler for VectorAuthUrlHandler {
920    fn on_auth_url<'a>(&'a self, auth_url: Url) -> BoxedFuture<'a, std::result::Result<(), nostr_connect::error::Error>> {
921        Box::pin(async move {
922            crate::traits::emit_event_json(
923                "bunker_auth_url",
924                serde_json::json!({ "url": auth_url.to_string() }),
925            );
926            Ok(())
927        })
928    }
929}
930
931// ============================================================================
932// attempt_bunker_login — end-to-end: build → prewarm → install
933// ============================================================================
934
935/// Build a `NostrConnect`, attach the Vector auth-URL handler, bootstrap it,
936/// and install it as the active bunker signer. Returns the discovered remote
937/// signer pubkey on success.
938///
939/// Emits `bunker_state` transitions: Connecting → Online (on success) or
940/// Connecting → Offline (on failure). The caller is expected to update the
941/// account-level discriminator (`signer_kind`) separately — this helper deals
942/// only with the live connection.
943pub async fn attempt_bunker_login(
944    bunker_url: &str,
945    client_keys: Keys,
946    timeout: Duration,
947) -> Result<PublicKey, String> {
948    set_bunker_state(BunkerConnectionState::Connecting);
949
950    let mut nc = match build_bunker_signer(bunker_url, client_keys, timeout) {
951        Ok(nc) => nc,
952        Err(e) => {
953            set_bunker_state(BunkerConnectionState::Offline);
954            return Err(e);
955        }
956    };
957    nc.auth_url_handler(VectorAuthUrlHandler);
958    let pairing = track_pairing(&nc);
959
960    match prewarm_bunker(&nc).await {
961        Ok(remote_pk) => match pairing.install(nc) {
962            Ok(old) => {
963                // A prior NostrConnect (retry-after-blip path) drains in the background:
964                // repeated calls would otherwise leak relay pools fighting for slots.
965                if let Some(old) = old {
966                    // spawn-detached: drains the replaced signer's relay pool; it holds no
967                    // account state and must finish even if the account swaps meanwhile.
968                    crate::rt::spawn(async move { let _ = old.shutdown().await; });
969                }
970                set_bunker_state(BunkerConnectionState::Online);
971                Ok(remote_pk)
972            }
973            Err(PairingAborted) => {
974                set_bunker_state(BunkerConnectionState::Offline);
975                Err(NETWORK_CHANGED.into())
976            }
977        },
978        Err(e) => {
979            // The just-built `nc`'s Drop will release its half-opened relay
980            // connections asynchronously; we don't need a shutdown call here
981            // because we never installed it as the active signer.
982            set_bunker_state(BunkerConnectionState::Offline);
983            Err(if pairing.aborted() { NETWORK_CHANGED.into() } else { e })
984        }
985    }
986}
987
988// ============================================================================
989// Network switches
990// ============================================================================
991
992/// A bunker closed for a network switch: what rebuilds it once the new network is ready.
993struct Suspended {
994    uri: NostrConnectUri,
995    keys: Keys,
996    user: Option<PublicKey>,
997}
998
999static SUSPENDED: std::sync::Mutex<Option<Suspended>> = std::sync::Mutex::new(None);
1000
1001/// What a pairing that a network switch cut off reports.
1002pub const NETWORK_CHANGED: &str = "The network changed. Try again.";
1003
1004// A NIP-46 client between its build and its install sits in no slot, yet its stock sockets
1005// answer to no network switch: every one is registered here until it is installed or dropped.
1006struct Pairing {
1007    id: u64,
1008    nc: NostrConnect,
1009    aborted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1010}
1011
1012static PAIRINGS: std::sync::Mutex<Vec<Pairing>> = std::sync::Mutex::new(Vec::new());
1013static PAIRING_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
1014
1015/// A network switch cut the pairing off before it could be installed.
1016#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1017pub struct PairingAborted;
1018
1019/// Held while a NIP-46 client pairs outside the signer slot. A network switch shuts the client
1020/// down and marks the pairing aborted; dropping the guard forgets it.
1021#[must_use = "the pairing is forgotten when the guard drops"]
1022pub struct PairingGuard {
1023    id: u64,
1024    aborted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1025}
1026
1027impl PairingGuard {
1028    /// A network switch cut this pairing off: its sockets are closed and it must not be used.
1029    pub fn aborted(&self) -> bool {
1030        self.aborted.load(Ordering::Acquire)
1031    }
1032
1033    /// Install the paired client, returning the signer it replaces. Atomic against a switch: the
1034    /// switch either finds it in the slot or has already aborted (and shut down) the pairing.
1035    pub fn install(self, nc: NostrConnect) -> Result<Option<NostrConnect>, PairingAborted> {
1036        let mut pairings = PAIRINGS.lock().unwrap_or_else(|e| e.into_inner());
1037        if self.aborted() {
1038            return Err(PairingAborted);
1039        }
1040        pairings.retain(|p| p.id != self.id);
1041        let old = take_bunker_signer();
1042        set_bunker_signer(nc);
1043        // A freshly paired signer supersedes one a switch suspended.
1044        *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = None;
1045        Ok(old)
1046    }
1047}
1048
1049impl Drop for PairingGuard {
1050    fn drop(&mut self) {
1051        PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).retain(|p| p.id != self.id);
1052    }
1053}
1054
1055/// Register a NIP-46 client that is not in the signer slot yet.
1056pub fn track_pairing(nc: &NostrConnect) -> PairingGuard {
1057    let id = PAIRING_SEQ.fetch_add(1, Ordering::Relaxed);
1058    let aborted = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1059    PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).push(Pairing { id, nc: nc.clone(), aborted: aborted.clone() });
1060    PairingGuard { id, aborted }
1061}
1062
1063fn abort_pairings() -> Vec<NostrConnect> {
1064    PAIRINGS
1065        .lock()
1066        .unwrap_or_else(|e| e.into_inner())
1067        .drain(..)
1068        .map(|p| {
1069            p.aborted.store(true, Ordering::Release);
1070            p.nc
1071        })
1072        .collect()
1073}
1074
1075/// What a suspended signer rebuilds from, secret stripped: the stored (or staged) URL first, since
1076/// asking a client that never bootstrapped for its URI would bootstrap it.
1077async fn rebuild_uri(nc: &NostrConnect) -> Option<NostrConnectUri> {
1078    use futures_util::FutureExt;
1079    let stored = match crate::db::get_bunker_url().await {
1080        Ok(Some(url)) => Some(url),
1081        _ => crate::state::pending_bunker_setup().map(|(url, _)| url),
1082    };
1083    if let Some(NostrConnectUri::Bunker { remote_signer_public_key, relays, .. }) =
1084        stored.and_then(|url| NostrConnectUri::parse(&url).ok())
1085    {
1086        return Some(NostrConnectUri::Bunker { remote_signer_public_key, relays, secret: None });
1087    }
1088    match nc.bunker_uri().now_or_never() {
1089        Some(Ok(uri)) => Some(uri),
1090        _ => None,
1091    }
1092}
1093
1094/// NIP-46 clients are stock nostr-sdk clients no switch can close: shut down every pairing in
1095/// flight and the installed signer (keeping what rebuilds it), unless it never opened a socket.
1096pub async fn suspend_bunker() {
1097    use futures_util::FutureExt;
1098    for nc in abort_pairings() {
1099        nc.shutdown().await;
1100    }
1101    let Some(nc) = bunker_signer() else { return };
1102    if nc.status().now_or_never().is_some_and(|relays| relays.is_empty()) {
1103        return;
1104    }
1105    let Some(nc) = take_bunker_signer() else { return };
1106    match rebuild_uri(&nc).await {
1107        Some(uri) => {
1108            let user = crate::state::my_public_key();
1109            *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = Some(Suspended { uri, keys: nc.local_keys().clone(), user });
1110            set_bunker_state(BunkerConnectionState::Connecting);
1111        }
1112        // A signer pairing still waiting for its approval: nothing to rebuild, it starts over.
1113        None => set_bunker_state(BunkerConnectionState::Offline),
1114    }
1115    nc.shutdown().await;
1116}
1117
1118static RESUMING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1119
1120/// Clears [`RESUMING`] however a resume ends, a cancelled task included.
1121struct Resuming;
1122
1123impl Drop for Resuming {
1124    fn drop(&mut self) {
1125        RESUMING.store(false, Ordering::Release);
1126    }
1127}
1128
1129/// Rebuild a suspended bunker on the network now in use, bootstrapped before it takes the slot so
1130/// a signing call's clone never connects to the signer again. A no-op unless one was suspended.
1131pub async fn resume_bunker() {
1132    if bunker_signer().is_some() || RESUMING.swap(true, Ordering::AcqRel) {
1133        return;
1134    }
1135    let resuming = Resuming;
1136    let Some((uri, keys, user)) = SUSPENDED
1137        .lock()
1138        .unwrap_or_else(|e| e.into_inner())
1139        .as_ref()
1140        .map(|s| (s.uri.clone(), s.keys.clone(), s.user))
1141    else {
1142        return;
1143    };
1144    let mut nc = match NostrConnect::new(uri, keys, Duration::from_secs(60), Some(crate::transport_relay_options())) {
1145        Ok(nc) => nc,
1146        Err(e) => {
1147            crate::log_warn!("[Transport] could not rebuild the signer connection: {e}");
1148            set_bunker_state(BunkerConnectionState::Offline);
1149            return;
1150        }
1151    };
1152    nc.auth_url_handler(VectorAuthUrlHandler);
1153    if let Some(pk) = user {
1154        let _ = nc.non_secure_set_user_public_key(pk);
1155    }
1156    let pairing = track_pairing(&nc);
1157    // Bound: the signer it installs is this account's, and a swap drains SUSPENDED meanwhile.
1158    crate::db::spawn_bound(async move {
1159        let _resuming = resuming;
1160        let bootstrapped = nc.bunker_uri().await.is_ok();
1161        if pairing.aborted() || !crate::db::session_is_live() || !bunker_suspended() {
1162            nc.shutdown().await;
1163            return;
1164        }
1165        // An unreachable signer still gets its client: each signing call then retries the
1166        // connection itself, as before the switch.
1167        if pairing.install(nc).is_ok() {
1168            set_bunker_state(if bootstrapped { BunkerConnectionState::Online } else { BunkerConnectionState::Offline });
1169        }
1170    });
1171}
1172
1173/// Whether a bunker is suspended until the network is ready.
1174pub fn bunker_suspended() -> bool {
1175    SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()).is_some()
1176}
1177
1178/// A signer pairing is still waiting for its approval, in the slot or outside it.
1179pub fn pairing_pending() -> bool {
1180    (bunker_signer().is_some() && bunker_state() == BunkerConnectionState::Connecting)
1181        || !PAIRINGS.lock().unwrap_or_else(|e| e.into_inner()).is_empty()
1182}
1183
1184// ============================================================================
1185// Teardown
1186// ============================================================================
1187
1188/// Clear all bunker-specific state. Called by `reset_session()` so a swap
1189/// from bunker → local (or between two bunker accounts) leaves no stale
1190/// keying material, relay-pool handles, or stale connection-state observed
1191/// by the frontend. The caller is responsible for `.shutdown().await`-ing
1192/// the returned signer outside the lock.
1193pub fn drain_bunker_state() -> Option<NostrConnect> {
1194    // Resets SIGNER_KIND for EVERY signer kind, not just bunker — `reset_session`
1195    // calls this unconditionally, so a NIP-55 (or any) → local swap lands the
1196    // discriminator back at Local before the next account's login re-reads its
1197    // own signer_type. Do NOT make this bunker-conditional or is_keyless() gets
1198    // stuck across swaps.
1199    set_signer_kind(SignerKind::Local);
1200    set_bunker_state(BunkerConnectionState::Idle);
1201    *SUSPENDED.lock().unwrap_or_else(|e| e.into_inner()) = None;
1202    take_bunker_signer()
1203}
1204
1205#[cfg(test)]
1206mod tests {
1207    use super::*;
1208
1209    /// A signer other than the vault (here the test stand-in for a remote one) seals and wraps
1210    /// through its own signing, never the vault's key.
1211    #[tokio::test]
1212    async fn a_signer_that_is_not_the_vault_seals_and_wraps_itself() {
1213        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1214        let (vault_key, remote, peer) = (Keys::generate(), Keys::generate(), Keys::generate());
1215        crate::state::MY_SECRET_KEY.store_from_keys(&vault_key, &[]);
1216        set_test_signer(Some(ActiveSigner::Keys(remote.clone())));
1217        let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "x").finalize_unsigned(remote.public_key());
1218        let seal = seal_rumor(rumor.clone(), &peer.public_key()).await;
1219        let wrap = gift_wrap(&peer.public_key(), rumor, []).await;
1220        set_test_signer(None);
1221        crate::state::MY_SECRET_KEY.clear(&[]);
1222        assert_eq!(seal.unwrap().pubkey, remote.public_key(), "sealed by the signer");
1223        let opened = UnwrappedGift::from_gift_wrap(&peer, &wrap.unwrap()).unwrap();
1224        assert_eq!(opened.sender, remote.public_key(), "wrapped by the signer");
1225    }
1226
1227    #[test]
1228    fn resolving_a_local_signer_refuses_a_vault_key_that_is_not_the_identity() {
1229        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1230        set_signer_kind(SignerKind::Local);
1231        let (me, other) = (Keys::generate(), Keys::generate());
1232        crate::state::set_my_public_key(me.public_key());
1233        crate::state::MY_SECRET_KEY.store_from_keys(&other, &[]);
1234        let refused = active_signer().is_err();
1235        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
1236        let accepted = matches!(active_signer(), Ok(ActiveSigner::Local(_)));
1237        crate::state::MY_SECRET_KEY.clear(&[]);
1238        crate::state::clear_my_public_key();
1239        assert!(refused, "a key that isn't the identity is refused before any work");
1240        assert!(accepted, "the identity's own key resolves");
1241    }
1242
1243    #[test]
1244    fn the_vault_keys_owner_follows_every_set_and_clear() {
1245        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1246        let (me, other) = (Keys::generate(), Keys::generate());
1247        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
1248        assert_eq!(local_key_owner(), Some(me.public_key()));
1249        assert_eq!(local_key_owner(), Some(me.public_key()), "answered again from the cache");
1250        crate::state::MY_SECRET_KEY.store_from_keys(&other, &[]);
1251        assert_eq!(local_key_owner(), Some(other.public_key()), "a set is never answered from a stale cache");
1252        // Another key's write moves the count too, and the owner is derived again, unchanged.
1253        crate::state::ENCRYPTION_KEY.set([7u8; 32], &[&crate::state::MY_SECRET_KEY]);
1254        assert_eq!(local_key_owner(), Some(other.public_key()));
1255        crate::state::ENCRYPTION_KEY.clear(&[&crate::state::MY_SECRET_KEY]);
1256        crate::state::MY_SECRET_KEY.clear(&[]);
1257        assert_eq!(local_key_owner(), None);
1258    }
1259
1260    #[test]
1261    fn setting_roundtrip() {
1262        assert_eq!(SignerKind::from_setting_str("local"), SignerKind::Local);
1263        assert_eq!(SignerKind::from_setting_str("bunker"), SignerKind::Bunker);
1264        assert_eq!(SignerKind::from_setting_str("nip55"), SignerKind::Nip55);
1265        assert_eq!(SignerKind::from_setting_str("nip07"), SignerKind::Nip07);
1266        assert_eq!(SignerKind::Nip07.as_setting_str(), "nip07");
1267        assert_eq!(SignerKind::Local.as_setting_str(), "local");
1268        assert_eq!(SignerKind::Bunker.as_setting_str(), "bunker");
1269        assert_eq!(SignerKind::Nip55.as_setting_str(), "nip55");
1270        // Unknown values fall back to Local — upgrade path for pre-NIP-46 rows.
1271        assert_eq!(SignerKind::from_setting_str(""), SignerKind::Local);
1272        assert_eq!(SignerKind::from_setting_str("garbage"), SignerKind::Local);
1273    }
1274
1275    // SIGNER_KIND + BUNKER_SIGNER + BUNKER_STATE are process-wide atomics /
1276    // locks. Cargo runs `#[test]` functions in parallel, so any pair of
1277    // tests that mutate the same global races and produces flaky failures.
1278    // Bundled into one test function so the sequence is deterministic —
1279    // mirrors `session_helpers_round_trip_and_clear` in state.rs which
1280    // does the same for `MY_PUBLIC_KEY` / `PENDING_INVITE`.
1281    #[test]
1282    fn atomic_state_round_trips_and_drains() {
1283        // Held so tests that resolve a Local signer never see the kind flipped mid-test.
1284        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1285        // Defensive cleanup: a previous test panic could have left a non-
1286        // default value behind.
1287        set_signer_kind(SignerKind::Local);
1288        set_bunker_state(BunkerConnectionState::Idle);
1289
1290        // atomic kind roundtrip
1291        set_signer_kind(SignerKind::Bunker);
1292        assert_eq!(signer_kind(), SignerKind::Bunker);
1293        assert!(is_bunker());
1294        assert!(is_keyless());
1295        set_signer_kind(SignerKind::Local);
1296        assert_eq!(signer_kind(), SignerKind::Local);
1297        assert!(!is_bunker());
1298        assert!(!is_keyless());
1299
1300        // NIP-55 is keyless but NOT a bunker — the two gates must not conflate.
1301        set_signer_kind(SignerKind::Nip55);
1302        assert_eq!(signer_kind(), SignerKind::Nip55);
1303        assert!(!is_bunker());
1304        assert!(is_keyless());
1305        set_signer_kind(SignerKind::Local);
1306
1307        // drain resets discriminator + state and returns the (absent) signer
1308        set_signer_kind(SignerKind::Bunker);
1309        set_bunker_state(BunkerConnectionState::Online);
1310        let drained = drain_bunker_state();
1311        assert!(drained.is_none());
1312        assert_eq!(signer_kind(), SignerKind::Local);
1313        assert_eq!(bunker_state(), BunkerConnectionState::Idle);
1314
1315        // drain is idempotent — running again on already-cleared state is
1316        // safe (no panic, no spurious event), and leaves things clean.
1317        let drained_again = drain_bunker_state();
1318        assert!(drained_again.is_none());
1319        assert_eq!(signer_kind(), SignerKind::Local);
1320        assert_eq!(bunker_state(), BunkerConnectionState::Idle);
1321    }
1322
1323    #[test]
1324    fn bunker_state_label_covers_all_variants() {
1325        // Whenever a new BunkerConnectionState is added, this test forces a
1326        // matching label so the frontend's `bunker_state` listener never sees
1327        // an unlabelled discriminant.
1328        assert_eq!(BunkerConnectionState::Idle.as_label(), "idle");
1329        assert_eq!(BunkerConnectionState::Connecting.as_label(), "connecting");
1330        assert_eq!(BunkerConnectionState::Online.as_label(), "online");
1331        assert_eq!(BunkerConnectionState::Offline.as_label(), "offline");
1332    }
1333
1334    #[test]
1335    fn parse_bunker_relays_returns_relays_from_bunker_uri() {
1336        let signer_keys = Keys::generate();
1337        let r1 = RelayUrl::parse("wss://relay1.example").unwrap();
1338        let r2 = RelayUrl::parse("wss://relay2.example").unwrap();
1339        let uri = NostrConnectUri::Bunker {
1340            remote_signer_public_key: signer_keys.public_key(),
1341            relays: vec![r1.clone(), r2.clone()],
1342            secret: None,
1343        };
1344        let relays = parse_bunker_relays(&uri.to_string());
1345        assert_eq!(relays.len(), 2);
1346        assert!(relays.iter().any(|r| r.contains("relay1.example")));
1347        assert!(relays.iter().any(|r| r.contains("relay2.example")));
1348    }
1349
1350    #[test]
1351    fn parse_bunker_relays_returns_empty_on_invalid_input() {
1352        // Display-only signal; never panics, never errors. Bad input collapses
1353        // to "no relays known" so the Security panel falls back to "unknown"
1354        // instead of crashing.
1355        assert!(parse_bunker_relays("").is_empty());
1356        assert!(parse_bunker_relays("not a url").is_empty());
1357        assert!(parse_bunker_relays("http://example.com").is_empty());
1358
1359        // Client-initiated URIs also return empty — they're not the bunker
1360        // form we want to surface relays for.
1361        let client_keys = Keys::generate();
1362        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1363        let client_uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
1364        assert!(parse_bunker_relays(&client_uri.to_string()).is_empty(),
1365            "client URI must not surface as a bunker relay list");
1366    }
1367
1368    #[test]
1369    fn parse_bunker_remote_pubkey_invalid_url() {
1370        assert!(parse_bunker_remote_pubkey("not a url").is_err());
1371        assert!(parse_bunker_remote_pubkey("").is_err());
1372        assert!(parse_bunker_remote_pubkey("http://example.com").is_err());
1373    }
1374
1375    #[test]
1376    fn parse_bunker_remote_pubkey_rejects_client_uri() {
1377        // A client-initiated `nostrconnect://` URI is not a login entry point;
1378        // accepting it would let a hostile clipboard string register an
1379        // attacker-controlled client pubkey as "the remote signer".
1380        let client_keys = Keys::generate();
1381        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1382        let uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
1383        let err = parse_bunker_remote_pubkey(&uri.to_string())
1384            .expect_err("client URI must be rejected");
1385        assert!(err.contains("Client-initiated"), "unexpected error: {}", err);
1386    }
1387
1388    #[test]
1389    fn parse_bunker_remote_pubkey_normalizes_lowercase() {
1390        // Build a valid bunker URI with a known pubkey and verify the parse
1391        // result is forced to lowercase regardless of upstream casing choice.
1392        let signer_keys = Keys::generate();
1393        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1394        let uri = NostrConnectUri::Bunker {
1395            remote_signer_public_key: signer_keys.public_key(),
1396            relays: vec![relay],
1397            secret: None,
1398        };
1399        let parsed = parse_bunker_remote_pubkey(&uri.to_string())
1400            .expect("valid bunker URI");
1401        assert_eq!(parsed, signer_keys.public_key().to_hex().to_ascii_lowercase());
1402        assert_eq!(parsed, parsed.to_ascii_lowercase(),
1403            "callers may compare with == — output must already be lowercase");
1404    }
1405
1406    #[test]
1407    fn vector_metadata_carries_app_name_and_icon() {
1408        let md = vector_metadata();
1409        let json = serde_json::to_string(&md).expect("metadata serializes");
1410        assert!(json.contains(VECTOR_APP_NAME),
1411            "metadata must include app name for the signer's approval prompt; got {}", json);
1412        assert!(json.contains("vectorapp.io"),
1413            "metadata must reference the app URL for the signer's 'More info' link");
1414    }
1415
1416    #[test]
1417    fn nip46_perms_list_excludes_get_private_key() {
1418        // The whole point of a Remote Signer is keeping the identity nsec on
1419        // the signer device. Adding `get_private_key` to the requested perms
1420        // would invite the signer to expose it back to Vector and defeat the
1421        // threat model. This test fails loudly if a future edit re-adds it.
1422        for perm in VECTOR_NIP46_PERMS {
1423            assert!(!perm.contains("get_private_key"),
1424                "VECTOR_NIP46_PERMS must never include get_private_key (found: {})", perm);
1425            assert!(!perm.contains("private_key"),
1426                "perm string looks dangerous: {}", perm);
1427        }
1428    }
1429
1430    #[test]
1431    fn build_nostrconnect_session_appends_perms_query_param() {
1432        let client_keys = Keys::generate();
1433        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1434        let (_nc, uri) = build_nostrconnect_session(
1435            client_keys,
1436            vec![relay],
1437            std::time::Duration::from_secs(1),
1438        ).expect("session builds");
1439        assert!(uri.contains("perms="),
1440            "URI must carry perms query param so signers can scope the pairing; got: {}", uri);
1441        // Every permission we DO ask for must appear in the URI.
1442        for perm in VECTOR_NIP46_PERMS {
1443            assert!(uri.contains(perm),
1444                "URI missing permission '{}': {}", perm, uri);
1445        }
1446        // And get_private_key must NOT.
1447        assert!(!uri.contains("get_private_key"),
1448            "URI must never request get_private_key: {}", uri);
1449    }
1450
1451    #[test]
1452    fn build_nostrconnect_session_rejects_empty_uri() {
1453        // `build_nostrconnect_session` is the QR-flow entry. Constructing one
1454        // with zero relays would produce a URI that no signer can connect
1455        // back to — caller-side check is in `start_nostrconnect_session`, but
1456        // this is a sanity test that NostrConnect itself does not silently
1457        // accept an empty relay list at the URI level.
1458        let client_keys = Keys::generate();
1459        let session = build_nostrconnect_session(
1460            client_keys,
1461            vec![],
1462            std::time::Duration::from_secs(1),
1463        );
1464        // We don't assert pass/fail — different upstream versions may treat
1465        // empty relays differently — only that we don't panic.
1466        let _ = session;
1467    }
1468
1469    // Combined into one #[test] to serialise mutation of process-wide globals
1470    // (BUNKER_STATE, BUNKER_SIGNER). See the rationale on
1471    // `atomic_state_round_trips_and_drains` above.
1472    #[test]
1473    fn watched_signer_session_gate_and_state_transitions() {
1474        // It swaps the live session, which every transport test reads.
1475        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1476
1477        // Build a real NostrConnect so we can wrap it. We never call any of
1478        // its async methods (those would require a relay) — only the inner
1479        // wrapper's session-guard semantics are under test.
1480        let client_keys = Keys::generate();
1481        let relay = RelayUrl::parse("wss://relay.example").unwrap();
1482        let signer_keys = Keys::generate();
1483        let uri = NostrConnectUri::Bunker {
1484            remote_signer_public_key: signer_keys.public_key(),
1485            relays: vec![relay],
1486            secret: None,
1487        };
1488        let nc = NostrConnect::new(
1489            uri,
1490            client_keys,
1491            std::time::Duration::from_secs(1),
1492            None,
1493        ).expect("NostrConnect builds");
1494
1495        let gen_before = crate::db::current_session_id();
1496        let watched = WatchedBunkerSigner::new(nc);
1497        assert_eq!(watched.session_id_for_test(), gen_before,
1498            "WatchedBunkerSigner must capture the live session generation at construction");
1499
1500        // Pre-swap: flip emits because the captured guard matches.
1501        set_bunker_state(BunkerConnectionState::Idle);
1502        watched.flip(BunkerConnectionState::Online);
1503        assert_eq!(bunker_state(), BunkerConnectionState::Online,
1504            "flip with valid session must update bunker_state");
1505
1506        // Simulate a session swap (logout / account swap). The captured
1507        // guard goes stale; subsequent flips must be ignored so a leftover
1508        // in-flight signing call from the previous account can't leak
1509        // bunker_state changes into the new session.
1510        crate::db::close_database();
1511        set_bunker_state(BunkerConnectionState::Online);
1512        watched.flip(BunkerConnectionState::Offline);
1513        assert_eq!(bunker_state(), BunkerConnectionState::Online,
1514            "flip with stale session must be a no-op");
1515
1516        // Cleanup so subsequent test runs / siblings see a sane state.
1517        set_bunker_state(BunkerConnectionState::Idle);
1518    }
1519}