vector-core 0.6.0

Core library for Vector — the single source of truth for all Vector clients, SDKs, and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
//! Polymorphic signer — local key vault vs. NIP-46 remote bunker.
//!
//! Vector supports two signer modes per account:
//!
//! - **Local** — the user's nsec lives in `MY_SECRET_KEY` (GuardedKey vault)
//!   on this device. Signing is local; the key materialises in plaintext only
//!   for microseconds per operation.
//! - **Bunker** — the user's nsec lives on a remote NIP-46 signer (Amber,
//!   nsec.app, ...). Vector holds only a *client keypair* (in `MY_SECRET_KEY`)
//!   used to RPC the bunker. Every signing request takes a round-trip; the
//!   user's identity key never touches this device.
//!
//! The discriminator is persisted in the per-account settings DB
//! (`signer_type` key) and materialised into the `SIGNER_KIND` atomic at
//! login. Hot paths read the atomic; cold paths read the DB directly.
//!
//! Storage layout for bunker accounts (see `db::settings`):
//! - `signer_type = "bunker"`
//! - `bunker_url`  = the `bunker://<remote_pubkey>?relay=...&secret=...`
//!   string, encrypted-at-rest if the account uses pin/pass encryption (same
//!   path as `pkey`).
//! - `bunker_remote_pubkey` = the signer's pubkey, plaintext (routing only).
//! - `pkey` = the NIP-46 client keypair (encrypted-at-rest under the same
//!   path as local accounts). Reusing the existing vault avoids a second
//!   GuardedKey slot; see the "Client-keypair storage note" section below.

use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::{LazyLock, RwLock};
use std::time::Duration;

use nostr_sdk::prelude::*;
use nostr_connect::prelude::{AuthUrlHandler, NostrConnect, NostrConnectUri};

// ============================================================================
// SignerError + VectorSigner — the capability-trait bundle
// ============================================================================

/// Boxed future returned by every async signer capability.
///
/// nostr 0.45.0 inlined this shape into its trait signatures and stopped
/// exporting an alias, so Vector owns the name.
pub type BoxedFuture<'a, T> =
    std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;

/// Error from any signing backend.
///
/// nostr 0.45 deleted `NostrSigner` and split it into per-capability traits,
/// each carrying its own associated `Error`. Vector normalises all four onto
/// this one type so the polymorphic seam stays a single trait bound and callers
/// keep one error to handle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignerError(String);

impl SignerError {
    /// Wrap a backend error (bunker RPC, NIP-55 IPC, local crypto).
    #[inline]
    pub fn backend<E>(e: E) -> Self
    where
        E: core::fmt::Display,
    {
        Self(e.to_string())
    }
}

impl core::fmt::Display for SignerError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(&self.0)
    }
}

impl core::error::Error for SignerError {}

impl From<&str> for SignerError {
    #[inline]
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl From<String> for SignerError {
    #[inline]
    fn from(s: String) -> Self {
        Self(s)
    }
}

/// Every capability Vector's polymorphic signing paths need, in one bound.
///
/// Pinning `Error = SignerError` is what makes the bundle usable as a single
/// bound; it's viable because the concrete-`Keys` paths have their own
/// non-generic overloads (`build_list_event` vs `build_list_event_signed`), so
/// bare `Keys` is never passed here.
pub trait VectorSigner:
    AsyncGetPublicKey<Error = SignerError>
    + AsyncSignEvent<Error = SignerError>
    + AsyncNip04<Error = SignerError>
    + AsyncNip44<Error = SignerError>
{
}

impl<T> VectorSigner for T
where
    T: ?Sized
        + AsyncGetPublicKey<Error = SignerError>
        + AsyncSignEvent<Error = SignerError>
        + AsyncNip04<Error = SignerError>
        + AsyncNip44<Error = SignerError>,
{
}

// ============================================================================
// ActiveSigner — the session's signer, resolved on demand
// ============================================================================

/// The signer for the active session.
///
/// nostr 0.45 removed `ClientBuilder::signer` / `Client::signer`: events are
/// built and signed outside the client now, so Vector owns this dispatch.
///
/// A concrete enum rather than `Arc<dyn ...>` on purpose. 0.45 ships no blanket
/// capability impls for `Arc<T>`, and the orphan rule forbids adding them, so a
/// trait object would force every call site to deref. This also keeps dispatch
/// static.
///
/// Deliberately NOT cached in a static: [`active_signer`] rebuilds it per call
/// from state that is already swap-managed (`SIGNER_KIND`, `BUNKER_SIGNER`,
/// `MY_PUBLIC_KEY`). A cached signer would be one more per-account global to
/// invalidate on `reset_session`, and a stale one signs the new account's events
/// under the old identity.
#[derive(Debug, Clone)]
pub enum ActiveSigner {
    /// Local key from the GuardedKey vault.
    Local(crate::crypto::GuardedSigner),
    /// Remote NIP-46 bunker, with reachability reporting.
    Bunker(WatchedBunkerSigner),
    /// On-device NIP-55 signer app reached over Android IPC.
    Nip55(crate::nip55::Nip55Signer),
    /// Raw keys — headless/CLI consumers and tests, which have a vault key but
    /// no notion of signer modes.
    Keys(Keys),
}

macro_rules! dispatch {
    ($self:ident, $method:ident $(, $arg:expr)*) => {
        match $self {
            ActiveSigner::Local(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
            ActiveSigner::Bunker(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
            ActiveSigner::Nip55(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
            ActiveSigner::Keys(s) => s.$method($($arg),*).await.map_err(SignerError::backend),
        }
    };
}

impl AsyncGetPublicKey for ActiveSigner {
    type Error = SignerError;

    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
        Box::pin(async move { dispatch!(self, get_public_key_async) })
    }
}

impl AsyncSignEvent for ActiveSigner {
    type Error = SignerError;

    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
        Box::pin(async move { dispatch!(self, sign_event_async, unsigned) })
    }
}

impl AsyncNip04 for ActiveSigner {
    type Error = SignerError;

    fn nip04_encrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { dispatch!(self, nip04_encrypt_async, public_key, content) })
    }

    fn nip04_decrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        encrypted_content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { dispatch!(self, nip04_decrypt_async, public_key, encrypted_content) })
    }
}

impl AsyncNip44 for ActiveSigner {
    type Error = SignerError;

    fn nip44_encrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { dispatch!(self, nip44_encrypt_async, public_key, content) })
    }

    fn nip44_decrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        payload: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { dispatch!(self, nip44_decrypt_async, public_key, payload) })
    }
}

/// Test-only signer override consulted by [`active_signer`].
#[cfg(test)]
static TEST_SIGNER: LazyLock<RwLock<Option<ActiveSigner>>> =
    LazyLock::new(|| RwLock::new(None));

/// Install (or clear) the test signer override.
#[cfg(test)]
pub(crate) fn set_test_signer(signer: Option<ActiveSigner>) {
    if let Ok(mut g) = TEST_SIGNER.write() {
        *g = signer;
    }
}

/// Resolve the active session's signer.
///
/// Fails CLOSED on identity mismatch: a remote-signer account's vault holds its
/// *client* keypair, whose pubkey is not the identity. Signing with it emits
/// wrong-identity events that self-reject on every reader (AuthorMismatch), so
/// erroring here surfaces the misconfiguration instead of a silently
/// undeliverable send.
pub fn active_signer() -> Result<ActiveSigner, String> {
    // Tests model a remote-signer account (identity signable, local vault empty),
    // which production resolves from `BUNKER_SIGNER`. There's no such handle to
    // fabricate in-process, so tests inject the signer directly.
    #[cfg(test)]
    if let Some(s) = TEST_SIGNER.read().ok().and_then(|g| g.clone()) {
        return Ok(s);
    }
    match signer_kind() {
        SignerKind::Bunker => {
            let inner = bunker_signer()
                .ok_or("bunker account has no live signer (not yet connected)")?;
            Ok(ActiveSigner::Bunker(WatchedBunkerSigner::new(inner)))
        }
        SignerKind::Nip55 => {
            let pk = crate::state::my_public_key().ok_or("no active identity")?;
            Ok(ActiveSigner::Nip55(crate::nip55::Nip55Signer::new(pk)))
        }
        SignerKind::Local => {
            let keys = crate::state::MY_SECRET_KEY
                .to_keys()
                .ok_or("no signer available (no local key)")?;
            if let Some(pk) = crate::state::my_public_key() {
                if keys.public_key() != pk {
                    return Err("local key does not match the active identity (remote-signer account with no live signer)".to_string());
                }
                return Ok(ActiveSigner::Local(crate::crypto::GuardedSigner::new(pk)));
            }
            // No bound identity: headless/CLI consumers and tests.
            Ok(ActiveSigner::Keys(keys))
        }
    }
}

// ============================================================================
// SignerKind — discriminator
// ============================================================================

/// Which signer backs the active account.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum SignerKind {
    /// The user's nsec lives in `MY_SECRET_KEY` on this device.
    Local = 0,
    /// The user's nsec lives on a remote NIP-46 signer; we only hold the
    /// client keypair used to RPC it.
    Bunker = 1,
    /// The user's nsec lives in an on-device NIP-55 signer app (Amber) reached
    /// over local Android IPC. Nothing secret is stored on this device at all
    /// (not even a client keypair). Android-only.
    Nip55 = 2,
}

impl SignerKind {
    /// Persisted form used by the per-account settings KV.
    #[inline]
    pub fn as_setting_str(self) -> &'static str {
        match self {
            SignerKind::Local => "local",
            SignerKind::Bunker => "bunker",
            SignerKind::Nip55 => "nip55",
        }
    }

    /// Parse from the on-disk setting string. Unknown values fall back to
    /// `Local` so an upgrade path from pre-NIP-46 accounts (which have no
    /// `signer_type` row) is the obvious default.
    #[inline]
    pub fn from_setting_str(s: &str) -> Self {
        match s {
            "bunker" => SignerKind::Bunker,
            "nip55" => SignerKind::Nip55,
            _ => SignerKind::Local,
        }
    }
}

static SIGNER_KIND: AtomicU8 = AtomicU8::new(SignerKind::Local as u8);

/// The signer kind for the active session. Cheap to read; backed by an atomic.
#[inline]
pub fn signer_kind() -> SignerKind {
    match SIGNER_KIND.load(Ordering::Acquire) {
        1 => SignerKind::Bunker,
        2 => SignerKind::Nip55,
        _ => SignerKind::Local,
    }
}

/// Install the signer kind for the active session. Call at login after the
/// settings row has been read, and on swap before any signing work runs.
#[inline]
pub fn set_signer_kind(kind: SignerKind) {
    SIGNER_KIND.store(kind as u8, Ordering::Release);
}

/// `true` iff the active account signs via a remote NIP-46 bunker. Hot-path
/// helper for code that needs to branch on signer mode (e.g. parallelising
/// gift-wrap signing harder when each call pays a round-trip).
///
/// Reserve this for genuinely NIP-46-relay-specific logic. For "we don't hold
/// the identity key on this device" gates (key export refusal, keyless-account
/// feature availability) use `is_keyless()` instead — a NIP-55 account is
/// keyless but not a bunker.
#[inline]
pub fn is_bunker() -> bool {
    signer_kind() == SignerKind::Bunker
}

/// `true` iff the identity key is NOT held on this device — i.e. any remote /
/// external signer (NIP-46 bunker or NIP-55 Amber). The local `MY_SECRET_KEY`
/// vault does not hold the signing identity for these accounts, so anything
/// that reads or exports the raw nsec must gate on this and route through
/// `client.signer()` instead.
#[inline]
pub fn is_keyless() -> bool {
    signer_kind() != SignerKind::Local
}

// ============================================================================
// Client-keypair storage note
// ============================================================================
//
// The NIP-46 client keypair (used to RPC the bunker — not the user's
// identity) lives in the existing `MY_SECRET_KEY` vault for bunker accounts.
// This is intentional: every existing call site that loads "the active
// signing key" gets the client key, which is what the NIP-46 layer wants for
// its RPC envelope. For events the *user* sends, the path goes through
// `client.signer()` → NostrConnect, which tunnels to the bunker — so user
// events are signed by the user's identity, RPC envelopes by the client key.
//
// This avoids needing a second GuardedKey vault and the slot-coordination
// problem that comes with it. The trade-off: bunker accounts share the same
// memory-protection footprint as local accounts (the user's identity isn't
// on this device at all).

// ============================================================================
// BUNKER_SIGNER — live NostrConnect handle
// ============================================================================

/// Active `NostrConnect` handle. `None` for local-signer sessions.
///
/// `NostrConnect` is internally `Arc`-counted (relay pool, OnceCell-backed
/// remote pubkey cache), so cloning it for per-call use is cheap. The lock is
/// only held briefly to snapshot the inner value.
pub static BUNKER_SIGNER: LazyLock<RwLock<Option<NostrConnect>>> =
    LazyLock::new(|| RwLock::new(None));

/// Snapshot the active bunker handle. Returns `None` for local-signer sessions.
#[inline]
pub fn bunker_signer() -> Option<NostrConnect> {
    BUNKER_SIGNER.read().ok().and_then(|g| g.as_ref().cloned())
}

/// Install the bunker handle for the active session. Replaces any prior handle
/// without shutting it down — callers swapping should `take_bunker_signer()`
/// first and `.shutdown().await` the old one to drain its relay pool cleanly.
#[inline]
pub fn set_bunker_signer(signer: NostrConnect) {
    if let Ok(mut g) = BUNKER_SIGNER.write() {
        *g = Some(signer);
    }
}

/// Atomically remove the bunker handle. Used by session teardown so the
/// caller can `.shutdown()` it without racing readers.
#[inline]
pub fn take_bunker_signer() -> Option<NostrConnect> {
    BUNKER_SIGNER.write().ok().and_then(|mut g| g.take())
}

// ============================================================================
// Construction helpers
// ============================================================================

/// Parse a `bunker://` URL and return the relay URLs it lists. Used by the
/// Settings UI to render "Connected via <relay>" without re-bootstrapping.
/// Returns an empty Vec on any parse failure — the caller treats this as a
/// display-only signal and renders a generic fallback instead of erroring.
pub fn parse_bunker_relays(bunker_url: &str) -> Vec<String> {
    match NostrConnectUri::parse(bunker_url) {
        Ok(NostrConnectUri::Bunker { relays, .. }) => {
            relays.into_iter().map(|r| r.to_string()).collect()
        }
        _ => Vec::new(),
    }
}

/// Inspect a `bunker://` URL without bootstrapping: returns the remote
/// signer's pubkey (hex). Used by login flows to check whether a re-submitted
/// URL points at the same bunker as the active session (idempotent re-login)
/// versus a different bunker (which requires logout first). Cheap — no
/// network.
pub fn parse_bunker_remote_pubkey(bunker_url: &str) -> Result<String, String> {
    let uri = NostrConnectUri::parse(bunker_url)
        .map_err(|e| format!("Invalid bunker URL: {}", e))?;
    match uri {
        NostrConnectUri::Bunker { remote_signer_public_key, .. } => {
            // Force lowercase. `to_hex()` already returns lowercase per
            // nostr-sdk, but normalising here lets callers compare hex
            // forms with `==` without worrying about a future upstream
            // shift to mixed-case.
            Ok(remote_signer_public_key.to_hex().to_ascii_lowercase())
        }
        // Client-initiated URIs aren't supported as login entry points in v1;
        // they're for the reverse direction (we hand a URL to the signer).
        NostrConnectUri::Client { .. } => {
            Err("Client-initiated URIs not supported here; use a bunker:// URL".into())
        }
    }
}

// ============================================================================
// Vector app identity — surfaced to remote signers via NIP-46 metadata
// ============================================================================

/// Application name shown to the user by the remote signer when approving the
/// connection (e.g. on Amber's pairing screen).
pub const VECTOR_APP_NAME: &str = "Vector";

/// Marketing site — surfaced as the signer's "More info" link.
pub const VECTOR_APP_URL: &str = "https://vectorapp.io";

/// Icon shown by the signer alongside the app name. PNG, served from the
/// public GitHub mirror so the URL stays valid even if vectorapp.io changes
/// its asset layout. Signers cache by URL, so a stable target avoids
/// re-fetches on every pairing.
pub const VECTOR_APP_ICON: &str = "https://raw.githubusercontent.com/VectorPrivacy/Vector/master/src-tauri/icons/icon.png";

/// NIP-46 permission scope Vector requests on client-initiated pairings.
///
/// Sent as the `perms=` query parameter on `nostrconnect://` URIs. Signer apps
/// that honour it (Amber, nsec.app) surface this list on their pairing screen
/// and refuse RPC calls outside the granted scope. Vector intentionally never
/// requests `get_private_key`: the whole point of a Remote Signer is that the
/// identity nsec stays on the signer device, so allowing extraction would
/// defeat the threat model. Adding a method here is an explicit policy
/// decision; signer apps that don't enforce `perms` server-side still benefit
/// from a smaller surface in their pairing UI.
pub const VECTOR_NIP46_PERMS: &[&str] = &[
    "get_public_key",
    "sign_event",
    "nip04_encrypt",
    "nip04_decrypt",
    "nip44_encrypt",
    "nip44_decrypt",
];

/// Build the NIP-46 metadata payload Vector advertises in client-initiated
/// `nostrconnect://` URIs. The signer reads this to render the approval
/// prompt — name and icon are the bits the user actually sees.
pub fn vector_metadata() -> NostrConnectMetadata {
    let mut md = NostrConnectMetadata::new(VECTOR_APP_NAME);
    if let Ok(url) = Url::parse(VECTOR_APP_URL) {
        md = md.url(url);
    }
    if let Ok(icon) = Url::parse(VECTOR_APP_ICON) {
        md = md.icons(vec![icon]);
    }
    md
}

/// Build a client-initiated `nostrconnect://` URI. The user copies this URL
/// into their signer app (or scans the QR rendering of it); the signer
/// initiates the connection back to the listed relays.
///
/// Multi-relay by design — single-relay connect URIs are a centralisation
/// trap: if that one relay goes down, the user can't reconnect to their own
/// account. Pass the live trusted-relay list from `state::TRUSTED_RELAYS`.
pub fn build_nostrconnect_uri(
    client_pubkey: PublicKey,
    relays: Vec<RelayUrl>,
) -> NostrConnectUri {
    NostrConnectUri::Client {
        public_key: client_pubkey,
        relays,
        metadata: vector_metadata(),
        secret: random_connect_secret(),
    }
}

/// Fresh NIP-46 pairing secret. The signer echoes it in the `connect` response;
/// a mismatch means someone else answered, so it must be unguessable per session.
fn random_connect_secret() -> String {
    use ::rand::RngCore;
    let mut bytes = [0u8; 16];
    ::rand::rngs::OsRng.fill_bytes(&mut bytes);
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Build a `NostrConnect` for a client-initiated session — generates the
/// `nostrconnect://` URI from the client keys + relays + Vector metadata,
/// constructs the underlying `NostrConnect` with the Vector auth-URL handler
/// already attached, and returns both for the caller to (a) display the URI
/// to the user (QR + copy button) and (b) install the signer.
///
/// Note: doesn't bootstrap. The caller is expected to install the returned
/// `NostrConnect` in `BUNKER_SIGNER` and await `get_public_key()` to wait
/// for the signer's connect response.
pub fn build_nostrconnect_session(
    client_keys: Keys,
    relays: Vec<RelayUrl>,
    timeout: Duration,
) -> Result<(NostrConnect, String), String> {
    let uri = build_nostrconnect_uri(client_keys.public_key(), relays);
    // Append the NIP-46 `perms=` scope. nostr-sdk's `Display` impl doesn't
    // write it, so the SDK-built URI is fine to hand back to `NostrConnect`
    // (which doesn't read perms locally), while the signer app on the other
    // side parses the appended query param to render its pairing screen.
    //
    // The NIP-46 `secret` IS emitted now (0.45 requires it, and its response
    // parser accepts both a spec-compliant secret echo and Amber's bare `"ack"`),
    // so spoof detection costs nothing in interop.
    let mut uri_string = uri.to_string();
    let perms = VECTOR_NIP46_PERMS.join(",");
    if !perms.is_empty() {
        uri_string.push_str("&perms=");
        uri_string.push_str(&perms);
    }
    let mut nc = NostrConnect::new(uri, client_keys, timeout, None)
        .map_err(|e| format!("Bunker init failed: {}", e))?;
    nc.auth_url_handler(VectorAuthUrlHandler);
    Ok((nc, uri_string))
}

/// Build a `NostrConnect` from a `bunker://` URL + client keypair. Doesn't
/// connect yet — `NostrConnect` bootstraps lazily on the first signing call.
/// Use `prewarm()` if you want the connection up before the user's first send.
///
/// `timeout` bounds each RPC round-trip. 60s is the upstream example; we
/// expose it so chat-send paths can tighten this for snappier failure surfacing.
pub fn build_bunker_signer(
    bunker_url: &str,
    client_keys: Keys,
    timeout: Duration,
) -> Result<NostrConnect, String> {
    let uri = NostrConnectUri::parse(bunker_url)
        .map_err(|e| format!("Invalid bunker URL: {}", e))?;
    NostrConnect::new(uri, client_keys, timeout, None)
        .map_err(|e| format!("Bunker init failed: {}", e))
}

/// Force a bunker bootstrap and discover the user's identity pubkey.
///
/// The signer's *device* pubkey (returned by `bunker_uri()`) is NOT the user
/// identity for signers like Amber — bypassing this RPC produces events
/// signed under the wrong key. In Amber's "Manually approve each" mode this
/// prompts the user once during initial pairing.
pub async fn prewarm_bunker(signer: &NostrConnect) -> Result<PublicKey, String> {
    signer
        .get_public_key_async()
        .await
        .map_err(|e| format!("Bunker prewarm failed: {}", e))
}

// ============================================================================
// BunkerConnectionState — observable connection lifecycle
// ============================================================================

/// Observable state of the bunker connection. The atomic backs hot-path reads
/// (e.g. send paths checking "is it safe to issue a sign call?"); state changes
/// also fan out to the frontend via `EventEmitter` so the UI can show a banner.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum BunkerConnectionState {
    /// No active bunker session. Either we're on a local account, or we're
    /// between login and the first successful bootstrap.
    Idle = 0,
    /// Currently bootstrapping (relay connect + remote-pubkey discovery).
    Connecting = 1,
    /// Bunker is reachable; signing calls should succeed.
    Online = 2,
    /// Bunker is unreachable. Hot-path sends will fail fast; the next signing
    /// call will retry the underlying NostrConnect path which may reconnect.
    Offline = 3,
}

impl BunkerConnectionState {
    /// User-facing label, mirrored to the frontend in `bunker_state` events.
    pub fn as_label(self) -> &'static str {
        match self {
            BunkerConnectionState::Idle => "idle",
            BunkerConnectionState::Connecting => "connecting",
            BunkerConnectionState::Online => "online",
            BunkerConnectionState::Offline => "offline",
        }
    }
}

static BUNKER_STATE: AtomicU8 = AtomicU8::new(BunkerConnectionState::Idle as u8);

/// Read the live bunker connection state. Backed by an atomic; cheap to call.
#[inline]
pub fn bunker_state() -> BunkerConnectionState {
    match BUNKER_STATE.load(Ordering::Acquire) {
        1 => BunkerConnectionState::Connecting,
        2 => BunkerConnectionState::Online,
        3 => BunkerConnectionState::Offline,
        _ => BunkerConnectionState::Idle,
    }
}

/// Install a new bunker state and fan out a `bunker_state` event to the
/// frontend. No-op if the state didn't change — avoids spamming the UI with
/// duplicate transitions when a signing call confirms what's already known.
pub fn set_bunker_state(new_state: BunkerConnectionState) {
    let prev = BUNKER_STATE.swap(new_state as u8, Ordering::AcqRel);
    if prev == new_state as u8 {
        return;
    }
    crate::traits::emit_event_json(
        "bunker_state",
        serde_json::json!({ "state": new_state.as_label() }),
    );
}

// ============================================================================
// WatchedBunkerSigner — wrap NostrConnect with bunker_state observability
// ============================================================================
//
// Every signing operation (sign_event, nip44_encrypt, nip04_*) flows through
// this adapter when a bunker account is active. On success we flip
// `BUNKER_STATE` to Online; on error we flip to Offline. The frontend's
// `bunker_state` listener picks up the transition and surfaces a banner /
// toast so the user knows when their signer becomes unreachable mid-session.
//
// State flips are deduplicated by `set_bunker_state` (same-value writes are
// no-ops), so the per-call overhead is just one atomic load.

/// `VectorSigner` wrapper that emits `BunkerConnectionState` transitions on
/// every signing outcome. The inner `NostrConnect` is cheaply clonable
/// (internally Arc'd), so this is also Clone.
///
/// Captures a `SessionGuard` at construction; state flips after `reset_session`
/// are no-ops to avoid leaking signer-state events across an account swap (an
/// in-flight signing call resolving after the new account is installed would
/// otherwise emit `bunker_state: offline` against a local-account session).
#[derive(Debug, Clone)]
pub struct WatchedBunkerSigner {
    inner: NostrConnect,
    session: crate::state::SessionGuard,
}

impl WatchedBunkerSigner {
    pub fn new(inner: NostrConnect) -> Self {
        Self { inner, session: crate::state::SessionGuard::capture() }
    }

    /// Flip state only when the captured session is still active.
    #[inline]
    fn flip(&self, state: BunkerConnectionState) {
        if self.session.is_valid() {
            set_bunker_state(state);
        }
    }

    /// Test-only view onto the captured guard so a test can assert the
    /// wrapper is bound to the session generation at construction.
    #[cfg(test)]
    pub(crate) fn session_generation_for_test(&self) -> u64 {
        self.session.generation()
    }
}

impl WatchedBunkerSigner {
    /// Record the reachability implied by an outcome and normalise the bunker's
    /// error into `SignerError`.
    #[inline]
    fn watch<T, E>(&self, res: Result<T, E>) -> Result<T, SignerError>
    where
        E: core::fmt::Display,
    {
        match res {
            Ok(v) => {
                self.flip(BunkerConnectionState::Online);
                Ok(v)
            }
            Err(e) => {
                self.flip(BunkerConnectionState::Offline);
                Err(SignerError::backend(e))
            }
        }
    }
}

impl AsyncGetPublicKey for WatchedBunkerSigner {
    type Error = SignerError;

    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
        Box::pin(async move { self.watch(self.inner.get_public_key_async().await) })
    }
}

impl AsyncSignEvent for WatchedBunkerSigner {
    type Error = SignerError;

    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
        Box::pin(async move { self.watch(self.inner.sign_event_async(unsigned).await) })
    }
}

impl AsyncNip04 for WatchedBunkerSigner {
    type Error = SignerError;

    fn nip04_encrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { self.watch(self.inner.nip04_encrypt_async(public_key, content).await) })
    }

    fn nip04_decrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        encrypted_content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move {
            self.watch(self.inner.nip04_decrypt_async(public_key, encrypted_content).await)
        })
    }
}

impl AsyncNip44 for WatchedBunkerSigner {
    type Error = SignerError;

    fn nip44_encrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        content: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { self.watch(self.inner.nip44_encrypt_async(public_key, content).await) })
    }

    fn nip44_decrypt_async<'a>(
        &'a self,
        public_key: &'a PublicKey,
        payload: &'a str,
    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
        Box::pin(async move { self.watch(self.inner.nip44_decrypt_async(public_key, payload).await) })
    }
}

// ============================================================================
// VectorAuthUrlHandler — bridge bunker permission prompts to the frontend
// ============================================================================
//
// NIP-46 signers occasionally need user approval (e.g. signing an event kind
// the user hasn't yet granted blanket permission for). Amber and nsec.app
// respond with an `auth_url` the user must visit; on completion the signing
// retry succeeds. This handler emits the URL to the frontend so the UI can
// show a "Open signer" prompt — we deliberately don't auto-open a browser
// from the core because (a) the core doesn't own the platform-specific
// browser-open path, and (b) frontends may prefer in-app webview.

/// Auth-URL handler that forwards bunker prompts to the frontend via the
/// `EventEmitter` trait. The frontend receives a `bunker_auth_url` event and
/// is responsible for opening the URL (in-app webview, system browser, ...).
#[derive(Debug, Clone, Default)]
pub struct VectorAuthUrlHandler;

impl AuthUrlHandler for VectorAuthUrlHandler {
    fn on_auth_url<'a>(&'a self, auth_url: Url) -> BoxedFuture<'a, std::result::Result<(), nostr_connect::error::Error>> {
        Box::pin(async move {
            crate::traits::emit_event_json(
                "bunker_auth_url",
                serde_json::json!({ "url": auth_url.to_string() }),
            );
            Ok(())
        })
    }
}

// ============================================================================
// attempt_bunker_login — end-to-end: build → prewarm → install
// ============================================================================

/// Build a `NostrConnect`, attach the Vector auth-URL handler, bootstrap it,
/// and install it as the active bunker signer. Returns the discovered remote
/// signer pubkey on success.
///
/// Emits `bunker_state` transitions: Connecting → Online (on success) or
/// Connecting → Offline (on failure). The caller is expected to update the
/// account-level discriminator (`signer_kind`) separately — this helper deals
/// only with the live connection.
pub async fn attempt_bunker_login(
    bunker_url: &str,
    client_keys: Keys,
    timeout: Duration,
) -> Result<PublicKey, String> {
    set_bunker_state(BunkerConnectionState::Connecting);

    let mut nc = match build_bunker_signer(bunker_url, client_keys, timeout) {
        Ok(nc) => nc,
        Err(e) => {
            set_bunker_state(BunkerConnectionState::Offline);
            return Err(e);
        }
    };
    nc.auth_url_handler(VectorAuthUrlHandler);

    match prewarm_bunker(&nc).await {
        Ok(remote_pk) => {
            // If a prior NostrConnect is already installed (retry-after-blip
            // path), take it out and shut it down on a background task so
            // its relay pool drains cleanly. Without this, repeated calls
            // leak Arc'd RelayPool handles fighting for connection slots.
            //
            if let Some(old) = take_bunker_signer() {
                tokio::spawn(async move { let _ = old.shutdown().await; });
            }
            set_bunker_signer(nc);
            set_bunker_state(BunkerConnectionState::Online);
            Ok(remote_pk)
        }
        Err(e) => {
            // The just-built `nc`'s Drop will release its half-opened relay
            // connections asynchronously; we don't need a shutdown call here
            // because we never installed it as the active signer.
            set_bunker_state(BunkerConnectionState::Offline);
            Err(e)
        }
    }
}

// ============================================================================
// Teardown
// ============================================================================

/// Clear all bunker-specific state. Called by `reset_session()` so a swap
/// from bunker → local (or between two bunker accounts) leaves no stale
/// keying material, relay-pool handles, or stale connection-state observed
/// by the frontend. The caller is responsible for `.shutdown().await`-ing
/// the returned signer outside the lock.
pub fn drain_bunker_state() -> Option<NostrConnect> {
    // Resets SIGNER_KIND for EVERY signer kind, not just bunker — `reset_session`
    // calls this unconditionally, so a NIP-55 (or any) → local swap lands the
    // discriminator back at Local before the next account's login re-reads its
    // own signer_type. Do NOT make this bunker-conditional or is_keyless() gets
    // stuck across swaps.
    set_signer_kind(SignerKind::Local);
    set_bunker_state(BunkerConnectionState::Idle);
    take_bunker_signer()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn setting_roundtrip() {
        assert_eq!(SignerKind::from_setting_str("local"), SignerKind::Local);
        assert_eq!(SignerKind::from_setting_str("bunker"), SignerKind::Bunker);
        assert_eq!(SignerKind::from_setting_str("nip55"), SignerKind::Nip55);
        assert_eq!(SignerKind::Local.as_setting_str(), "local");
        assert_eq!(SignerKind::Bunker.as_setting_str(), "bunker");
        assert_eq!(SignerKind::Nip55.as_setting_str(), "nip55");
        // Unknown values fall back to Local — upgrade path for pre-NIP-46 rows.
        assert_eq!(SignerKind::from_setting_str(""), SignerKind::Local);
        assert_eq!(SignerKind::from_setting_str("garbage"), SignerKind::Local);
    }

    // SIGNER_KIND + BUNKER_SIGNER + BUNKER_STATE are process-wide atomics /
    // locks. Cargo runs `#[test]` functions in parallel, so any pair of
    // tests that mutate the same global races and produces flaky failures.
    // Bundled into one test function so the sequence is deterministic —
    // mirrors `session_helpers_round_trip_and_clear` in state.rs which
    // does the same for `MY_PUBLIC_KEY` / `PENDING_INVITE`.
    #[test]
    fn atomic_state_round_trips_and_drains() {
        // Defensive cleanup: a previous test panic could have left a non-
        // default value behind.
        set_signer_kind(SignerKind::Local);
        set_bunker_state(BunkerConnectionState::Idle);

        // atomic kind roundtrip
        set_signer_kind(SignerKind::Bunker);
        assert_eq!(signer_kind(), SignerKind::Bunker);
        assert!(is_bunker());
        assert!(is_keyless());
        set_signer_kind(SignerKind::Local);
        assert_eq!(signer_kind(), SignerKind::Local);
        assert!(!is_bunker());
        assert!(!is_keyless());

        // NIP-55 is keyless but NOT a bunker — the two gates must not conflate.
        set_signer_kind(SignerKind::Nip55);
        assert_eq!(signer_kind(), SignerKind::Nip55);
        assert!(!is_bunker());
        assert!(is_keyless());
        set_signer_kind(SignerKind::Local);

        // drain resets discriminator + state and returns the (absent) signer
        set_signer_kind(SignerKind::Bunker);
        set_bunker_state(BunkerConnectionState::Online);
        let drained = drain_bunker_state();
        assert!(drained.is_none());
        assert_eq!(signer_kind(), SignerKind::Local);
        assert_eq!(bunker_state(), BunkerConnectionState::Idle);

        // drain is idempotent — running again on already-cleared state is
        // safe (no panic, no spurious event), and leaves things clean.
        let drained_again = drain_bunker_state();
        assert!(drained_again.is_none());
        assert_eq!(signer_kind(), SignerKind::Local);
        assert_eq!(bunker_state(), BunkerConnectionState::Idle);
    }

    #[test]
    fn bunker_state_label_covers_all_variants() {
        // Whenever a new BunkerConnectionState is added, this test forces a
        // matching label so the frontend's `bunker_state` listener never sees
        // an unlabelled discriminant.
        assert_eq!(BunkerConnectionState::Idle.as_label(), "idle");
        assert_eq!(BunkerConnectionState::Connecting.as_label(), "connecting");
        assert_eq!(BunkerConnectionState::Online.as_label(), "online");
        assert_eq!(BunkerConnectionState::Offline.as_label(), "offline");
    }

    #[test]
    fn parse_bunker_relays_returns_relays_from_bunker_uri() {
        let signer_keys = Keys::generate();
        let r1 = RelayUrl::parse("wss://relay1.example").unwrap();
        let r2 = RelayUrl::parse("wss://relay2.example").unwrap();
        let uri = NostrConnectUri::Bunker {
            remote_signer_public_key: signer_keys.public_key(),
            relays: vec![r1.clone(), r2.clone()],
            secret: None,
        };
        let relays = parse_bunker_relays(&uri.to_string());
        assert_eq!(relays.len(), 2);
        assert!(relays.iter().any(|r| r.contains("relay1.example")));
        assert!(relays.iter().any(|r| r.contains("relay2.example")));
    }

    #[test]
    fn parse_bunker_relays_returns_empty_on_invalid_input() {
        // Display-only signal; never panics, never errors. Bad input collapses
        // to "no relays known" so the Security panel falls back to "unknown"
        // instead of crashing.
        assert!(parse_bunker_relays("").is_empty());
        assert!(parse_bunker_relays("not a url").is_empty());
        assert!(parse_bunker_relays("http://example.com").is_empty());

        // Client-initiated URIs also return empty — they're not the bunker
        // form we want to surface relays for.
        let client_keys = Keys::generate();
        let relay = RelayUrl::parse("wss://relay.example").unwrap();
        let client_uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
        assert!(parse_bunker_relays(&client_uri.to_string()).is_empty(),
            "client URI must not surface as a bunker relay list");
    }

    #[test]
    fn parse_bunker_remote_pubkey_invalid_url() {
        assert!(parse_bunker_remote_pubkey("not a url").is_err());
        assert!(parse_bunker_remote_pubkey("").is_err());
        assert!(parse_bunker_remote_pubkey("http://example.com").is_err());
    }

    #[test]
    fn parse_bunker_remote_pubkey_rejects_client_uri() {
        // A client-initiated `nostrconnect://` URI is not a login entry point;
        // accepting it would let a hostile clipboard string register an
        // attacker-controlled client pubkey as "the remote signer".
        let client_keys = Keys::generate();
        let relay = RelayUrl::parse("wss://relay.example").unwrap();
        let uri = build_nostrconnect_uri(client_keys.public_key(), vec![relay]);
        let err = parse_bunker_remote_pubkey(&uri.to_string())
            .expect_err("client URI must be rejected");
        assert!(err.contains("Client-initiated"), "unexpected error: {}", err);
    }

    #[test]
    fn parse_bunker_remote_pubkey_normalizes_lowercase() {
        // Build a valid bunker URI with a known pubkey and verify the parse
        // result is forced to lowercase regardless of upstream casing choice.
        let signer_keys = Keys::generate();
        let relay = RelayUrl::parse("wss://relay.example").unwrap();
        let uri = NostrConnectUri::Bunker {
            remote_signer_public_key: signer_keys.public_key(),
            relays: vec![relay],
            secret: None,
        };
        let parsed = parse_bunker_remote_pubkey(&uri.to_string())
            .expect("valid bunker URI");
        assert_eq!(parsed, signer_keys.public_key().to_hex().to_ascii_lowercase());
        assert_eq!(parsed, parsed.to_ascii_lowercase(),
            "callers may compare with == — output must already be lowercase");
    }

    #[test]
    fn vector_metadata_carries_app_name_and_icon() {
        let md = vector_metadata();
        let json = serde_json::to_string(&md).expect("metadata serializes");
        assert!(json.contains(VECTOR_APP_NAME),
            "metadata must include app name for the signer's approval prompt; got {}", json);
        assert!(json.contains("vectorapp.io"),
            "metadata must reference the app URL for the signer's 'More info' link");
    }

    #[test]
    fn nip46_perms_list_excludes_get_private_key() {
        // The whole point of a Remote Signer is keeping the identity nsec on
        // the signer device. Adding `get_private_key` to the requested perms
        // would invite the signer to expose it back to Vector and defeat the
        // threat model. This test fails loudly if a future edit re-adds it.
        for perm in VECTOR_NIP46_PERMS {
            assert!(!perm.contains("get_private_key"),
                "VECTOR_NIP46_PERMS must never include get_private_key (found: {})", perm);
            assert!(!perm.contains("private_key"),
                "perm string looks dangerous: {}", perm);
        }
    }

    #[test]
    fn build_nostrconnect_session_appends_perms_query_param() {
        let client_keys = Keys::generate();
        let relay = RelayUrl::parse("wss://relay.example").unwrap();
        let (_nc, uri) = build_nostrconnect_session(
            client_keys,
            vec![relay],
            std::time::Duration::from_secs(1),
        ).expect("session builds");
        assert!(uri.contains("perms="),
            "URI must carry perms query param so signers can scope the pairing; got: {}", uri);
        // Every permission we DO ask for must appear in the URI.
        for perm in VECTOR_NIP46_PERMS {
            assert!(uri.contains(perm),
                "URI missing permission '{}': {}", perm, uri);
        }
        // And get_private_key must NOT.
        assert!(!uri.contains("get_private_key"),
            "URI must never request get_private_key: {}", uri);
    }

    #[test]
    fn build_nostrconnect_session_rejects_empty_uri() {
        // `build_nostrconnect_session` is the QR-flow entry. Constructing one
        // with zero relays would produce a URI that no signer can connect
        // back to — caller-side check is in `start_nostrconnect_session`, but
        // this is a sanity test that NostrConnect itself does not silently
        // accept an empty relay list at the URI level.
        let client_keys = Keys::generate();
        let session = build_nostrconnect_session(
            client_keys,
            vec![],
            std::time::Duration::from_secs(1),
        );
        // We don't assert pass/fail — different upstream versions may treat
        // empty relays differently — only that we don't panic.
        let _ = session;
    }

    // Combined into one #[test] to serialise mutation of process-wide globals
    // (SESSION_GENERATION, BUNKER_STATE, BUNKER_SIGNER). See the rationale on
    // `atomic_state_round_trips_and_drains` above.
    #[test]
    fn watched_signer_session_gate_and_state_transitions() {
        use crate::state::{bump_session_generation, current_session_generation};

        // Build a real NostrConnect so we can wrap it. We never call any of
        // its async methods (those would require a relay) — only the inner
        // wrapper's session-guard semantics are under test.
        let client_keys = Keys::generate();
        let relay = RelayUrl::parse("wss://relay.example").unwrap();
        let signer_keys = Keys::generate();
        let uri = NostrConnectUri::Bunker {
            remote_signer_public_key: signer_keys.public_key(),
            relays: vec![relay],
            secret: None,
        };
        let nc = NostrConnect::new(
            uri,
            client_keys,
            std::time::Duration::from_secs(1),
            None,
        ).expect("NostrConnect builds");

        let gen_before = current_session_generation();
        let watched = WatchedBunkerSigner::new(nc);
        assert_eq!(watched.session_generation_for_test(), gen_before,
            "WatchedBunkerSigner must capture the live session generation at construction");

        // Pre-swap: flip emits because the captured guard matches.
        set_bunker_state(BunkerConnectionState::Idle);
        watched.flip(BunkerConnectionState::Online);
        assert_eq!(bunker_state(), BunkerConnectionState::Online,
            "flip with valid session must update bunker_state");

        // Simulate a session swap (logout / account swap). The captured
        // guard goes stale; subsequent flips must be ignored so a leftover
        // in-flight signing call from the previous account can't leak
        // bunker_state changes into the new session.
        bump_session_generation();
        set_bunker_state(BunkerConnectionState::Online);
        watched.flip(BunkerConnectionState::Offline);
        assert_eq!(bunker_state(), BunkerConnectionState::Online,
            "flip with stale session must be a no-op");

        // Cleanup so subsequent test runs / siblings see a sane state.
        set_bunker_state(BunkerConnectionState::Idle);
    }
}