Skip to main content

vector_core/
nip55.rs

1//! NIP-55 "offline" signer — an on-device signer app (Amber) reached over
2//! local Android IPC instead of a relay.
3//!
4//! This is the third signer mode alongside `Local` (nsec in the `MY_SECRET_KEY`
5//! vault) and `Bunker` (NIP-46 over relays, see [`crate::signer`]). A NIP-55
6//! account holds **nothing secret on this device** — not even the client
7//! keypair a bunker account keeps. Every signing op is a local IPC hop to the
8//! signer app; no network, works offline.
9//!
10//! Layering:
11//! - [`Nip55Backend`] is a platform hook (mirrors [`crate::traits::EventEmitter`]):
12//!   the Android shell registers the concrete JNI/ContentResolver/Intent impl at
13//!   startup. vector-core stays Tauri- and Android-decoupled. When no backend is
14//!   registered (desktop, CLI, tests), every op returns a clean runtime error —
15//!   never a compile-time platform stub, so a stray shared-call-site reference
16//!   can't break the desktop build.
17//! - [`Nip55Signer`] implements `VectorSigner` on top of the hook, so every
18//!   existing `client.signer()` call site (DM seals, Blossom auth, Concord v2
19//!   identity ops) uses it agnostically with no changes.
20//!
21//! Wire-identity: NIP-55 `sign_event` / `nip44_*` produce byte-identical output
22//! to the local path (same NIP-01 id computation, same NIP-44 conversation key),
23//! which is why an Amber account and a local account share communities without
24//! forking. Fail-closed: a signer returning an event authored by the wrong
25//! identity is rejected here, not silently published.
26
27use std::sync::atomic::{AtomicU8, Ordering};
28use std::sync::{LazyLock, OnceLock};
29
30use nostr_sdk::prelude::*;
31
32use crate::signer::{BoxedFuture, SignerError};
33
34// ============================================================================
35// Nip55Error — hook failure taxonomy
36// ============================================================================
37
38/// Failure modes of a NIP-55 signing operation. The three variants map to
39/// distinct observable states so the UI can tell "reopen and re-grant" apart
40/// from "Amber is gone" apart from "transient hiccup".
41#[derive(Debug, Clone)]
42pub enum Nip55Error {
43    /// Not pre-authorized: the background ContentResolver query returned a
44    /// `rejected`/null result and no foreground Activity was available to
45    /// prompt. Surfaces as [`Nip55State::NeedsAuth`]. MUST NEVER be read as a
46    /// valid empty decrypt — a null cursor is an authorization signal, not data.
47    NotAuthorized,
48    /// No external signer resolvable — Amber uninstalled, or no backend
49    /// registered on this platform. Surfaces as [`Nip55State::Missing`].
50    Missing,
51    /// Any other IPC / parse / transport failure. Transient — does not flip the
52    /// observable state (the signer is presumed still paired).
53    Ipc(String),
54}
55
56impl std::fmt::Display for Nip55Error {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        match self {
59            Nip55Error::NotAuthorized => {
60                write!(f, "external signer is not authorized for this operation")
61            }
62            Nip55Error::Missing => write!(f, "no external signer available"),
63            Nip55Error::Ipc(msg) => write!(f, "external signer IPC error: {msg}"),
64        }
65    }
66}
67
68impl std::error::Error for Nip55Error {}
69
70// ============================================================================
71// Nip55Backend — the platform hook (registered by the Android shell)
72// ============================================================================
73
74/// The Android-side transport for a NIP-55 signer. Implemented in the Tauri
75/// shell (JNI + ContentResolver + Intent-for-result); registered once at
76/// startup via [`set_nip55_backend`].
77///
78/// All methods are blocking (JNI) — [`Nip55Signer`] wraps each in
79/// `spawn_blocking` behind a concurrency semaphore, so implementors may block
80/// freely (including parking on an Activity-result condvar for the foreground
81/// pairing/fallback path).
82///
83/// Hex strings are lowercase x-only pubkey hex. `current_user_hex` is always
84/// the paired identity; passing it on every op lets Amber route to the right
85/// account even if the user has several.
86pub trait Nip55Backend: Send + Sync + 'static {
87    /// Whether an external signer app is installed and resolvable. Cheap; the
88    /// login screen and boot path call it to avoid offering a dead button.
89    fn is_installed(&self) -> Result<bool, Nip55Error>;
90
91    /// Pairing handshake (foreground `get_public_key` Intent). The user picks
92    /// their identity and grants the remembered permission set. Returns
93    /// `(user_pubkey, signer_package)`; the package is pinned for every
94    /// subsequent op. Called ONCE at login — never again while signed in.
95    fn get_public_key_pairing(&self, perms_json: &str) -> Result<(String, String), Nip55Error>;
96
97    /// Fast, silent background ContentResolver op. `method` is the uppercase
98    /// content-authority suffix (`SIGN_EVENT`, `NIP44_DECRYPT`, ...); `data` is
99    /// the payload (event JSON / plaintext / ciphertext); `counterparty` is the
100    /// other party's pubkey hex (empty for `SIGN_EVENT`). Returns a TRI-STATE
101    /// the caller must not collapse (see [`Nip55ResolverOutcome`]).
102    fn resolver_op(
103        &self,
104        method: &str,
105        data: &str,
106        counterparty: &str,
107        current_user: &str,
108    ) -> Nip55ResolverOutcome;
109
110    /// Foreground Intent fallback (may block up to the sign timeout on user approval).
111    /// Returns `(result, event)` — `result` carries sig/ciphertext/plaintext,
112    /// `event` the signed event JSON for `sign_event`. Only invoked when
113    /// [`is_foreground`](Self::is_foreground) is true.
114    fn intent_op(
115        &self,
116        intent_type: &str,
117        data: &str,
118        counterparty: &str,
119        current_user: &str,
120    ) -> Result<(Option<String>, Option<String>), Nip55Error>;
121
122    /// Whether a foreground Activity exists to prompt the user. False in the
123    /// Activity-less background service, where an un-remembered op fails soft.
124    fn is_foreground(&self) -> bool;
125}
126
127/// Outcome of a background ContentResolver op — three distinct meanings the
128/// caller must keep apart. A null/empty cursor is NEVER a valid empty decrypt.
129pub enum Nip55ResolverOutcome {
130    /// Success. `result` = sig/ciphertext/plaintext; `event` = signed JSON.
131    Value {
132        result: Option<String>,
133        event: Option<String>,
134    },
135    /// Not remembered (null/empty cursor) — escalate to the foreground Intent.
136    RequiresApproval,
137    /// Remembered reject (a `rejected` column) — surface NeedsAuth, do NOT
138    /// relaunch the signer.
139    Rejected,
140    /// IPC / parse failure. Transient — does not flip observable state.
141    Error(String),
142}
143
144static NIP55_BACKEND: OnceLock<Box<dyn Nip55Backend>> = OnceLock::new();
145
146/// Register the platform NIP-55 backend. Call once during app startup on
147/// Android. No-op on desktop/CLI (nothing registers), so every op below returns
148/// [`Nip55Error::Missing`] there — the runtime stub.
149pub fn set_nip55_backend(backend: Box<dyn Nip55Backend>) {
150    let _ = NIP55_BACKEND.set(backend);
151}
152
153/// The registered backend, if any. `None` on platforms without an external
154/// signer.
155#[inline]
156pub fn nip55_backend() -> Option<&'static dyn Nip55Backend> {
157    NIP55_BACKEND.get().map(|b| b.as_ref())
158}
159
160// ----------------------------------------------------------------------------
161// Concurrency bound (review W4) — scoped to the fast path only (review W1)
162// ----------------------------------------------------------------------------
163//
164// A deep-sync backfill decrypts one gift wrap per inbound message — thousands
165// of ops. An unbounded `spawn_blocking` per op would park a large slice of
166// tokio's blocking pool, so the fast ContentResolver query is gated behind this
167// semaphore. The permit is released BEFORE the (rare, up-to-2-minute) foreground
168// Intent fallback runs, so a parked signer prompt can't head-of-line-block an
169// interactive send waiting for a permit. See `Nip55Signer::run`.
170
171const NIP55_MAX_CONCURRENT_OPS: usize = 4;
172
173static NIP55_SEMAPHORE: LazyLock<tokio::sync::Semaphore> =
174    LazyLock::new(|| tokio::sync::Semaphore::new(NIP55_MAX_CONCURRENT_OPS));
175
176/// Serializes the foreground-Intent fallback to ONE at a time. Amber shows a
177/// single approval dialog anyway, so without this a burst of un-remembered ops
178/// (e.g. a foreground backfill whose kinds weren't pre-granted) would each park
179/// up to the sign timeout AND stack `startActivityForResult` launches — a
180/// thundering herd. Size 1 turns that into an orderly queue.
181static NIP55_INTENT_SEMAPHORE: LazyLock<tokio::sync::Semaphore> =
182    LazyLock::new(|| tokio::sync::Semaphore::new(1));
183
184// ============================================================================
185// Permissions requested at pairing
186// ============================================================================
187
188/// Encryption/decryption permissions Vector requests at pairing. These are
189/// granted blanket (no `kind`) because Amber only drops a `kind`-less
190/// permission when its type is `sign_event`/`nip` — nip04/nip44 with a null
191/// kind are kept.
192pub const VECTOR_NIP55_ENCRYPT_TYPES: &[&str] = &[
193    "nip44_encrypt",
194    "nip44_decrypt",
195    "nip04_encrypt",
196    "nip04_decrypt",
197];
198
199/// Event kinds Vector signs, requested per-kind at pairing.
200///
201/// CRITICAL: Amber drops a bare `{"type":"sign_event"}` (kind-less) permission
202/// during pairing, so a blanket sign grant silently pre-authorizes NOTHING and
203/// every outbound op would need a foreground tap. We must enumerate every kind
204/// we sign. A kind missed here isn't a hard failure — the first sign of it
205/// prompts once and the user can "remember" — but a background sign of an
206/// un-remembered kind fails soft (no Activity to prompt). Keep this in sync
207/// with the kinds Vector actually signs.
208pub const VECTOR_NIP55_SIGN_KINDS: &[u16] = &[
209    0,     // profile metadata
210    3,     // contacts
211    5,     // deletion
212    7,     // reaction
213    13,    // NIP-17 seal (DM hot path)
214    14,    // NIP-17 chat rumor
215    1059,  // NIP-17 gift wrap
216    8,     // NIP-58 badge award
217    30008, // NIP-58 profile badges
218    30009, // NIP-58 badge definition
219    10030, // emoji pack list
220    10050, // NIP-17 DM relay list
221    10063, // blossom server list
222    22242, // NIP-42 relay auth
223    24242, // blossom auth
224    30078, // app-specific data (invite acceptance)
225    // Concord (`community::v2::kind`).
226    3302, 3303, 3306, 3308, 3309, 3310, 3312, 3313,
227];
228
229/// Render the pairing `permissions` JSON: blanket encrypt/decrypt plus one
230/// `{"type":"sign_event","kind":K}` per signed kind. Never includes
231/// `get_private_key` — same policy as [`crate::signer::VECTOR_NIP46_PERMS`];
232/// the whole point of an external signer is that the identity nsec never leaves
233/// it.
234pub fn nip55_perms_json() -> String {
235    let mut arr: Vec<serde_json::Value> = VECTOR_NIP55_ENCRYPT_TYPES
236        .iter()
237        .map(|t| serde_json::json!({ "type": t }))
238        .collect();
239    for &kind in VECTOR_NIP55_SIGN_KINDS {
240        arr.push(serde_json::json!({ "type": "sign_event", "kind": kind }));
241    }
242    serde_json::Value::Array(arr).to_string()
243}
244
245// ============================================================================
246// Nip55State — observable pairing lifecycle (mirror BunkerConnectionState)
247// ============================================================================
248
249/// Observable state of the NIP-55 pairing. Backed by an atomic for hot-path
250/// reads; transitions fan out to the frontend as `nip55_state` events.
251#[derive(Copy, Clone, Debug, Eq, PartialEq)]
252#[repr(u8)]
253pub enum Nip55State {
254    /// No active NIP-55 session (local/bunker account, or between login and
255    /// first op).
256    Idle = 0,
257    /// Signer reachable and pre-authorized; ops succeed silently.
258    Ready = 1,
259    /// A background op came back `rejected` — the user must reopen the signer
260    /// and re-grant. Inbound decryption defers to a foreground prompt.
261    NeedsAuth = 2,
262    /// The signer app is gone (uninstalled). The account can't sign until it's
263    /// reinstalled and re-paired.
264    Missing = 3,
265}
266
267impl Nip55State {
268    /// User-facing label, mirrored to the frontend in `nip55_state` events.
269    pub fn as_label(self) -> &'static str {
270        match self {
271            Nip55State::Idle => "idle",
272            Nip55State::Ready => "ready",
273            Nip55State::NeedsAuth => "needs_auth",
274            Nip55State::Missing => "missing",
275        }
276    }
277}
278
279static NIP55_STATE: AtomicU8 = AtomicU8::new(Nip55State::Idle as u8);
280
281/// Read the live NIP-55 pairing state. Backed by an atomic; cheap to call.
282#[inline]
283pub fn nip55_state() -> Nip55State {
284    match NIP55_STATE.load(Ordering::Acquire) {
285        1 => Nip55State::Ready,
286        2 => Nip55State::NeedsAuth,
287        3 => Nip55State::Missing,
288        _ => Nip55State::Idle,
289    }
290}
291
292/// Install a new state and fan out a `nip55_state` event. No-op if unchanged,
293/// so per-op confirmation of an already-known state doesn't spam the UI.
294pub fn set_nip55_state(new_state: Nip55State) {
295    let prev = NIP55_STATE.swap(new_state as u8, Ordering::AcqRel);
296    if prev == new_state as u8 {
297        return;
298    }
299    crate::traits::emit_event_json(
300        "nip55_state",
301        serde_json::json!({ "state": new_state.as_label() }),
302    );
303}
304
305/// Reset NIP-55 observable state to Idle. Called by `reset_session()` on swap
306/// so a stale state from the previous account doesn't leak onto the new one.
307/// (The Android shell separately cancels any stranded Intent waiters.)
308pub fn drain_nip55_state() {
309    set_nip55_state(Nip55State::Idle);
310}
311
312// ============================================================================
313// Nip55Signer — VectorSigner over the platform hook
314// ============================================================================
315
316/// A `VectorSigner` that routes every identity op to an external NIP-55 signer
317/// over the platform hook. Cheap to clone (just a pubkey + a session
318/// generation snapshot).
319///
320/// Captures a [`std::sync::Arc<crate::db::Session>`](std::sync::Arc<crate::db::Session>) at construction:
321/// state flips after an account swap are suppressed so an in-flight op
322/// resolving against the previous account can't leak `nip55_state` onto the new
323/// one. Wrong-key is impossible regardless — every op is bound to
324/// `user_pubkey` and passes it as `current_user`, so a stale op still signs as
325/// the correct (old) identity; it just must not narrate onto the new session.
326#[derive(Debug, Clone)]
327pub struct Nip55Signer {
328    user_pubkey: PublicKey,
329    session: std::sync::Arc<crate::db::Session>,
330}
331
332impl Nip55Signer {
333    /// Build a signer for the paired identity. Capture happens now so the guard
334    /// is bound to the session that installed this signer.
335    pub fn new(user_pubkey: PublicKey) -> Self {
336        Self {
337            user_pubkey,
338            session: crate::db::current_session(),
339        }
340    }
341
342    /// The paired identity pubkey.
343    #[inline]
344    pub fn user_pubkey(&self) -> PublicKey {
345        self.user_pubkey
346    }
347
348    /// Flip observable state only while the captured session is still active.
349    #[inline]
350    fn flip(&self, state: Nip55State) {
351        if self.session.is_live() {
352            set_nip55_state(state);
353        }
354    }
355
356    /// Resolver-first op with a foreground-Intent fallback. The semaphore bounds
357    /// ONLY the fast ContentResolver query; the permit is released before the
358    /// (rare, up-to-2-minute) Intent runs so a parked prompt can't head-of-line-block
359    /// interactive signing (review W1). Returns `(result, event)`.
360    async fn run(
361        &self,
362        method: &'static str,
363        intent_type: &'static str,
364        data: String,
365        counterparty: String,
366        current_user: String,
367    ) -> Result<(Option<String>, Option<String>), SignerError> {
368        let backend = match nip55_backend() {
369            Some(b) => b,
370            None => {
371                self.flip(Nip55State::Missing);
372                return Err(SignerError::backend(Nip55Error::Missing));
373            }
374        };
375
376        // Fast ContentResolver path, permit-bounded. Permit drops with this block.
377        let outcome = {
378            let _permit = NIP55_SEMAPHORE.acquire().await.map_err(|_| {
379                SignerError::backend(Nip55Error::Ipc("nip55 semaphore closed".to_string()))
380            })?;
381            let (d, cp, cu) = (data.clone(), counterparty.clone(), current_user.clone());
382            match crate::rt::spawn_blocking(move || backend.resolver_op(method, &d, &cp, &cu)).await {
383                Ok(o) => o,
384                Err(e) => {
385                    return Err(SignerError::backend(Nip55Error::Ipc(format!(
386                        "nip55 worker join error: {e}"
387                    ))))
388                }
389            }
390        };
391
392        match outcome {
393            Nip55ResolverOutcome::Value { result, event } => {
394                self.flip(Nip55State::Ready);
395                Ok((result, event))
396            }
397            Nip55ResolverOutcome::Rejected => {
398                self.flip(Nip55State::NeedsAuth);
399                Err(SignerError::backend(Nip55Error::NotAuthorized))
400            }
401            Nip55ResolverOutcome::Error(e) => Err(SignerError::backend(Nip55Error::Ipc(e))),
402            Nip55ResolverOutcome::RequiresApproval => {
403                // Not remembered — prompt only if the user is actually in the app.
404                if !backend.is_foreground() {
405                    self.flip(Nip55State::NeedsAuth);
406                    return Err(SignerError::backend(Nip55Error::NotAuthorized));
407                }
408                // Serialize to one live prompt (Amber shows one dialog anyway).
409                // Held across the intent, but NOT the fast-path permit, so it
410                // can't head-of-line-block silent signing.
411                let _intent_permit = NIP55_INTENT_SEMAPHORE.acquire().await.map_err(|_| {
412                    SignerError::backend(Nip55Error::Ipc("nip55 intent semaphore closed".to_string()))
413                })?;
414                let res = match crate::rt::spawn_blocking(move || {
415                    backend.intent_op(intent_type, &data, &counterparty, &current_user)
416                })
417                .await
418                {
419                    Ok(r) => r,
420                    Err(e) => {
421                        return Err(SignerError::backend(Nip55Error::Ipc(format!(
422                            "nip55 worker join error: {e}"
423                        ))))
424                    }
425                };
426                match res {
427                    Ok((result, event)) => {
428                        self.flip(Nip55State::Ready);
429                        Ok((result, event))
430                    }
431                    Err(e @ Nip55Error::NotAuthorized) => {
432                        self.flip(Nip55State::NeedsAuth);
433                        Err(SignerError::backend(e))
434                    }
435                    Err(e @ Nip55Error::Missing) => {
436                        self.flip(Nip55State::Missing);
437                        Err(SignerError::backend(e))
438                    }
439                    Err(e) => Err(SignerError::backend(e)),
440                }
441            }
442        }
443    }
444
445    /// Test-only view onto the captured guard so a test can assert the wrapper
446    /// is bound to the session generation at construction.
447    #[cfg(test)]
448    pub(crate) fn session_id_for_test(&self) -> u64 {
449        self.session.id()
450    }
451}
452
453impl AsyncGetPublicKey for Nip55Signer {
454    type Error = SignerError;
455
456    fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
457        // Cached (review W6): NIP-55 `get_public_key` is a pairing-time Intent,
458        // never a per-call hop. `my_pk` is resolved constantly on the hot path;
459        // an IPC round-trip here would be catastrophic.
460        Box::pin(async move { Ok(self.user_pubkey) })
461    }
462
463}
464
465impl AsyncSignEvent for Nip55Signer {
466    type Error = SignerError;
467
468    fn sign_event_async(&self, unsigned: UnsignedEvent) -> BoxedFuture<'_, Result<Event, Self::Error>> {
469        Box::pin(async move {
470            let event_json = unsigned.as_json();
471            let user_hex = self.user_pubkey.to_hex();
472            let (_result, signed) = self
473                .run("SIGN_EVENT", "sign_event", event_json, String::new(), user_hex)
474                .await?;
475            let signed_json = signed.ok_or_else(|| {
476                SignerError::backend(Nip55Error::Ipc("signer returned no signed event".to_string()))
477            })?;
478            let event = crate::event_json::event(&signed_json).map_err(SignerError::backend)?;
479            // Fail closed: the signer must return an event authored by OUR
480            // identity. A mismatch (wrong Amber account, corrupted IPC) would
481            // otherwise fork the wire under a foreign key.
482            if event.pubkey != self.user_pubkey {
483                return Err(SignerError::backend(Nip55Error::Ipc(format!(
484                    "signer returned event authored by {} (expected {})",
485                    event.pubkey.to_hex(),
486                    self.user_pubkey.to_hex()
487                ))));
488            }
489            event.verify().map_err(SignerError::backend)?;
490            Ok(event)
491        })
492    }
493
494}
495
496impl AsyncNip04 for Nip55Signer {
497    type Error = SignerError;
498
499    fn nip04_encrypt_async<'a>(
500        &'a self,
501        public_key: &'a PublicKey,
502        content: &'a str,
503    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
504        Box::pin(async move {
505            let (result, _event) = self
506                .run("NIP04_ENCRYPT", "nip04_encrypt", content.to_string(), public_key.to_hex(), self.user_pubkey.to_hex())
507                .await?;
508            result.ok_or_else(|| SignerError::backend(Nip55Error::Ipc("signer returned no result".to_string())))
509        })
510    }
511
512    fn nip04_decrypt_async<'a>(
513        &'a self,
514        public_key: &'a PublicKey,
515        content: &'a str,
516    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
517        Box::pin(async move {
518            let (result, _event) = self
519                .run("NIP04_DECRYPT", "nip04_decrypt", content.to_string(), public_key.to_hex(), self.user_pubkey.to_hex())
520                .await?;
521            result.ok_or_else(|| SignerError::backend(Nip55Error::Ipc("signer returned no result".to_string())))
522        })
523    }
524
525}
526
527impl AsyncNip44 for Nip55Signer {
528    type Error = SignerError;
529
530    fn nip44_encrypt_async<'a>(
531        &'a self,
532        public_key: &'a PublicKey,
533        content: &'a str,
534    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
535        Box::pin(async move {
536            let (result, _event) = self
537                .run("NIP44_ENCRYPT", "nip44_encrypt", content.to_string(), public_key.to_hex(), self.user_pubkey.to_hex())
538                .await?;
539            result.ok_or_else(|| SignerError::backend(Nip55Error::Ipc("signer returned no result".to_string())))
540        })
541    }
542
543    fn nip44_decrypt_async<'a>(
544        &'a self,
545        public_key: &'a PublicKey,
546        content: &'a str,
547    ) -> BoxedFuture<'a, Result<String, Self::Error>> {
548        Box::pin(async move {
549            let (result, _event) = self
550                .run("NIP44_DECRYPT", "nip44_decrypt", content.to_string(), public_key.to_hex(), self.user_pubkey.to_hex())
551                .await?;
552            result.ok_or_else(|| SignerError::backend(Nip55Error::Ipc("signer returned no result".to_string())))
553        })
554    }
555}
556
557// ============================================================================
558// Pairing + availability helpers (login-flow entry points)
559// ============================================================================
560
561/// Whether an external signer is installed. Returns `Ok(false)` on platforms
562/// without a registered backend (desktop) rather than erroring — the login
563/// screen treats "not installed" and "not supported" the same (hide the
564/// button).
565pub fn nip55_is_installed() -> Result<bool, String> {
566    match nip55_backend() {
567        Some(b) => b.is_installed().map_err(|e| e.to_string()),
568        None => Ok(false),
569    }
570}
571
572/// Run the pairing handshake: fire the `get_public_key` Intent with Vector's
573/// remembered permission set and return the discovered identity pubkey plus the
574/// signer's package name. Blocking (Activity round-trip) — wrapped in
575/// `spawn_blocking`.
576pub async fn nip55_pair() -> Result<(PublicKey, String), String> {
577    let perms = nip55_perms_json();
578    let backend = nip55_backend().ok_or("no external signer available on this platform")?;
579    let (pk_str, package) =
580        crate::rt::spawn_blocking(move || backend.get_public_key_pairing(&perms))
581            .await
582            .map_err(|e| format!("pairing worker join error: {e}"))?
583            .map_err(|e| e.to_string())?;
584    // Amber returns the identity as npub (bech32); `parse` also accepts hex.
585    let pk = PublicKey::parse(&pk_str)
586        .map_err(|e| format!("external signer returned an invalid pubkey: {e}"))?;
587    Ok((pk, package))
588}
589
590#[cfg(test)]
591mod tests {
592    use crate::event_ext::FinalizeUnsignedWithId;
593    use super::*;
594
595    #[test]
596    fn perms_exclude_private_key_and_enumerate_sign_kinds() {
597        let json = nip55_perms_json();
598        // The identity nsec must never leave the signer.
599        assert!(!json.contains("private_key"), "perms leaked private-key access: {json}");
600        // Blanket encrypt/decrypt (kind-less, which Amber keeps).
601        for t in VECTOR_NIP55_ENCRYPT_TYPES {
602            assert!(json.contains(t), "perms JSON missing '{t}': {json}");
603        }
604        // The DM-seal hot-path kind must be pre-granted.
605        assert!(json.contains("\"kind\":13"), "seal kind 13 must be pre-granted: {json}");
606
607        // EVERY sign_event permission must carry an explicit kind — Amber drops
608        // a bare (kind-less) sign_event at pairing, so a blanket grant would
609        // silently pre-authorize nothing.
610        let v: serde_json::Value = serde_json::from_str(&json).expect("perms json parses");
611        let mut saw_sign = false;
612        for entry in v.as_array().expect("perms is an array") {
613            if entry.get("type").and_then(|t| t.as_str()) == Some("sign_event") {
614                saw_sign = true;
615                assert!(
616                    entry.get("kind").and_then(|k| k.as_u64()).is_some(),
617                    "bare sign_event perm would be dropped by Amber: {entry}"
618                );
619            }
620        }
621        assert!(saw_sign, "perms must request sign_event for at least one kind: {json}");
622    }
623
624    #[test]
625    fn state_label_covers_all_variants() {
626        // A new Nip55State without a label would ship an unlabelled event to
627        // the frontend listener. Force the match here.
628        assert_eq!(Nip55State::Idle.as_label(), "idle");
629        assert_eq!(Nip55State::Ready.as_label(), "ready");
630        assert_eq!(Nip55State::NeedsAuth.as_label(), "needs_auth");
631        assert_eq!(Nip55State::Missing.as_label(), "missing");
632    }
633
634    #[tokio::test]
635    async fn get_public_key_is_cached_and_needs_no_backend() {
636        // No backend is registered in pure vector-core tests, yet get_public_key
637        // must still resolve — it returns the cached identity, never an IPC hop.
638        let keys = Keys::generate();
639        let signer = Nip55Signer::new(keys.public_key());
640        let pk = signer.get_public_key_async().await.expect("cached pubkey resolves");
641        assert_eq!(pk, keys.public_key());
642    }
643
644    // NIP55_STATE is process-wide. Cargo runs #[test]
645    // functions in parallel, so every mutation of NIP55_STATE is bundled into
646    // THIS single test to keep the sequence deterministic — mirrors
647    // `atomic_state_round_trips_and_drains` / `watched_signer_session_gate...`
648    // in signer.rs.
649    #[tokio::test]
650    #[allow(clippy::await_holding_lock)]
651    async fn global_state_session_gate_and_missing_backend() {
652        // It swaps the live session, which every transport test reads.
653        let _db = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
654
655        // Defensive reset (a prior panic could have left state dirty).
656        set_nip55_state(Nip55State::Idle);
657
658        // State roundtrip.
659        set_nip55_state(Nip55State::Ready);
660        assert_eq!(nip55_state(), Nip55State::Ready);
661        set_nip55_state(Nip55State::NeedsAuth);
662        assert_eq!(nip55_state(), Nip55State::NeedsAuth);
663        set_nip55_state(Nip55State::Missing);
664        assert_eq!(nip55_state(), Nip55State::Missing);
665        drain_nip55_state();
666        assert_eq!(nip55_state(), Nip55State::Idle);
667
668        // Session gate: a signer flips state only while its captured generation
669        // is live.
670        let keys = Keys::generate();
671        let gen_before = crate::db::current_session_id();
672        let signer = Nip55Signer::new(keys.public_key());
673        assert_eq!(
674            signer.session_id_for_test(),
675            gen_before,
676            "signer must capture the live session generation at construction"
677        );
678        // Valid session flips (tolerate a concurrent bump from a sibling test).
679        if signer.session_id_for_test() == crate::db::current_session_id() {
680            signer.flip(Nip55State::Ready);
681            assert_eq!(nip55_state(), Nip55State::Ready, "valid-session flip must apply");
682        }
683        // After a swap the guard is stale; flips are no-ops so a leftover op
684        // can't leak state onto the new account.
685        set_nip55_state(Nip55State::Ready);
686        crate::db::close_database();
687        signer.flip(Nip55State::Missing);
688        assert_eq!(nip55_state(), Nip55State::Ready, "stale-session flip must be a no-op");
689
690        // Missing backend: a FRESH signer (guard valid post-bump) signing with
691        // no registered backend fails `Missing` and flips the state.
692        set_nip55_state(Nip55State::Idle);
693        let fresh = Nip55Signer::new(keys.public_key());
694        let unsigned = EventBuilder::new(Kind::TextNote, "hi")
695            .finalize_unsigned_with_id(keys.public_key());
696        let err = fresh.sign_event_async(unsigned).await;
697        assert!(err.is_err(), "no backend registered => sign must fail");
698        assert_eq!(
699            nip55_state(),
700            Nip55State::Missing,
701            "missing-backend op must surface Missing state"
702        );
703
704        // nip55_is_installed with no backend registered is a clean false.
705        assert_eq!(nip55_is_installed().unwrap(), false);
706
707        // Cleanup for sibling tests / reruns.
708        drain_nip55_state();
709    }
710}