Skip to main content

cosmic_applet_avestruz/nostr/
account.rs

1// SPDX-License-Identifier: MIT
2
3//! The signed-in account: reading what someone signs in with, keeping what
4//! is secret where it belongs, signing, and encrypting what the account
5//! keeps to itself.
6//!
7//! Signing in takes one of three things:
8//!
9//! - an `nsec`, the account's secret key: full access, signed here;
10//! - an `npub`, its public key: read-only;
11//! - a `bunker://` address (NIP-46): full access, signed by a remote signer
12//!   that keeps the key.
13//!
14//! A remote signer knows this client by a key of the client's own. There is
15//! one for each signer, made the first time that signer is signed in with
16//! and the same ever after, signing out included: a signer that only answers
17//! clients it was told about (`nak bunker -k`) is told this key once. When a
18//! signer turns a sign-in down, the key's public half is what is shown, to
19//! be authorized there. Revoking it is done at the signer.
20//!
21//! What is secret goes to the system keyring (Secret Service: gnome-keyring,
22//! KWallet) and nowhere else: an account's `nsec` or its bunker address,
23//! and the client keys. None is ever written to the config, the event store
24//! or a log. The config only names the account by its `npub`.
25//!
26//! Signing with an `nsec` fetches it from the keyring, signs, and lets go of
27//! it: the applet runs for as long as the session does, and holds no secret
28//! key between one signature and the next. A remote signer is connected to
29//! when the first signature is asked for, and stays connected until the
30//! account signs out: connecting anew for every signature would have the
31//! signer greet this client each time.
32//!
33//! What an account keeps to itself, such as its private bookmarks, it
34//! encrypts to its own key (NIP-44), and only it can read back. That takes
35//! the secret key as signing does, and goes the same two ways: here, with
36//! the key from the keyring, or at the remote signer.
37//!
38//! ```mermaid
39//! flowchart LR
40//!     subgraph keyring["The system keyring, service cosmic-applet-avestruz"]
41//!         secret["Under the account's npub: its nsec, or its bunker address"]
42//!         client["Under bunker-client and a signer's key: this client's key for that signer"]
43//!     end
44//!     subgraph config["The config"]
45//!         npub["The account's npub, and nothing secret"]
46//!     end
47//!     signer["Signer"] -->|"an nsec: fetched for one signature, and let go of"| secret
48//!     signer -->|"a bunker: fetched once, and the connection kept"| secret
49//!     signer --> client
50//!     restore["At startup"] --> npub
51//!     restore -->|"is anything kept for it?"| secret
52//! ```
53//!
54//! The three ways in, step by step, and what a signature goes through,
55//! are in [`crate::guide::flows`].
56
57use std::future::Future;
58use std::pin::{Pin, pin};
59use std::sync::Arc;
60use std::time::Duration;
61
62use futures_util::future::{Either, select};
63use nostr_connect::prelude::{AsyncNip04, AsyncNip44, AuthUrlHandler, Nip04, Nip44, NostrConnect, NostrConnectUri};
64use nostr_sdk::prelude::{
65    AsyncGetPublicKey, Event, EventBuilder, FinalizeEvent, FinalizeEventAsync, Keys, PublicKey, ToBech32, Url,
66};
67use tokio::sync::{Mutex, Notify};
68
69use crate::links;
70
71/// The keyring service an account's secret is filed under; the entry's user
72/// name is the account's `npub`.
73const KEYRING_SERVICE: &str = "cosmic-applet-avestruz";
74
75/// What the keyring user name of a client key starts with; the signer's
76/// public key, in hex, follows.
77const CLIENT_KEY_PREFIX: &str = "bunker-client:";
78
79/// How bunker addresses start.
80const BUNKER_SCHEME: &str = "bunker://";
81
82/// How long a remote signer gets to answer one request. Someone may have to
83/// pick up a phone and approve it.
84const REMOTE_TIMEOUT: Duration = Duration::from_secs(60);
85
86/// What someone signed in with.
87pub enum Credential {
88    /// An `nsec`: the account can sign.
89    Secret(Keys),
90    /// An `npub`: the account can only read.
91    Public(PublicKey),
92    /// A `bunker://` address: the account signs through a remote signer.
93    Bunker(NostrConnectUri),
94}
95
96/// Why the text in the sign-in field can't be signed in with.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum CredentialError {
99    Empty,
100    /// Neither an `nsec`, an `npub` nor a bunker address.
101    NotAKey,
102    InvalidSecret,
103    InvalidPublic,
104    /// A bunker address that names no signer, or no relay to reach it by.
105    InvalidBunker,
106}
107
108/// Whether `input` is meant as a bunker address.
109fn is_bunker_address(input: &str) -> bool {
110    input.get(..BUNKER_SCHEME.len()).is_some_and(|scheme| scheme.eq_ignore_ascii_case(BUNKER_SCHEME))
111}
112
113/// Read what was typed or pasted into the sign-in field.
114///
115/// Keys are only taken in their bech32 forms. A bare hex key reads the same
116/// whether it is secret or public, and guessing wrong would either refuse a
117/// sign-in or treat a public key as a secret one.
118pub fn parse_credential(input: &str) -> Result<Credential, CredentialError> {
119    let input = input.trim();
120    if is_bunker_address(input) {
121        // A signer is reached through relays: an address without one leads
122        // nowhere.
123        return NostrConnectUri::parse(input)
124            .ok()
125            .filter(|uri| uri.is_bunker() && !uri.relays().is_empty())
126            .map(Credential::Bunker)
127            .ok_or(CredentialError::InvalidBunker);
128    }
129    let input = input.strip_prefix("nostr:").unwrap_or(input);
130    if input.is_empty() {
131        Err(CredentialError::Empty)
132    } else if input.starts_with("nsec1") {
133        Keys::parse(input).map(Credential::Secret).map_err(|_| CredentialError::InvalidSecret)
134    } else if input.starts_with("npub1") {
135        PublicKey::parse(input).map(Credential::Public).map_err(|_| CredentialError::InvalidPublic)
136    } else {
137        Err(CredentialError::NotAKey)
138    }
139}
140
141/// The account in use.
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Account {
144    pub public_key: PublicKey,
145    /// Whether the keyring holds what it signs with: its secret key, or the
146    /// way to its remote signer. Without it the account is read-only.
147    pub can_sign: bool,
148}
149
150impl Account {
151    /// The account's public key as an `npub`, the form the config stores.
152    pub fn npub(&self) -> String {
153        let Ok(npub) = self.public_key.to_bech32();
154        npub
155    }
156}
157
158/// Why nobody was signed in.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum SignInError {
161    /// Signing in was called off while the remote signer was being waited for.
162    Cancelled,
163    /// The keyring would not keep the secret.
164    Keyring(String),
165    /// The remote signer could not be reached, or said no.
166    Bunker {
167        /// What it said, or what went wrong.
168        reason: String,
169        /// The key it knows this client by, once there is one.
170        client: Option<PublicKey>,
171        /// The address had a secret in it, which may have been used up.
172        with_secret: bool,
173    },
174}
175
176/// Why an event was not signed, or something not encrypted or decrypted.
177#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum SignError {
179    /// What the account signs with could not be had from the keyring, or
180    /// would not sign.
181    Keyring(String),
182    /// The remote signer could not be reached, or would not do it.
183    Remote(String),
184    /// The account's key was there, and what it was given could not be
185    /// encrypted or decrypted with it: it was not encrypted to this
186    /// account, or is not whole.
187    Cipher(String),
188}
189
190/// Whether `payload` was encrypted the old way (NIP-04) rather than the
191/// new (NIP-44): it ends in `?iv=` and the 24 characters of an
192/// initialisation vector, which nothing encrypted the new way does. Lists
193/// written by older clients are.
194fn is_nip04(payload: &str) -> bool {
195    const IV_MARK: &[u8] = b"?iv=";
196    const IV_CHARS: usize = 24;
197    // Some client wrote this after the vector.
198    let bytes = payload.strip_suffix("-null").unwrap_or(payload).as_bytes();
199    let mark = bytes.len().checked_sub(IV_MARK.len() + IV_CHARS).and_then(|at| bytes.get(at..));
200    mark.is_some_and(|mark| mark.starts_with(IV_MARK))
201}
202
203/// What the keyring holds for an account: how it signs.
204enum StoredSigner {
205    /// With its own secret key.
206    Local(Keys),
207    /// Through a remote signer: its address, without the secret that only
208    /// serves the first connection.
209    Remote(NostrConnectUri),
210}
211
212impl StoredSigner {
213    /// As it is written to the keyring: an `nsec`, or a remote signer's
214    /// address.
215    fn to_secret(&self) -> String {
216        match self {
217            Self::Local(keys) => nsec(keys),
218            Self::Remote(bunker) => bunker.to_string(),
219        }
220    }
221
222    /// Read back what [`Self::to_secret`] wrote.
223    fn parse(secret: &str) -> Result<Self, String> {
224        let unreadable = || "what the keyring holds for this account can't be read".to_string();
225        let secret = secret.trim();
226        if is_bunker_address(secret) {
227            NostrConnectUri::parse(secret).ok().filter(NostrConnectUri::is_bunker).map(Self::Remote).ok_or_else(unreadable)
228        } else {
229            Keys::parse(secret).map(Self::Local).map_err(|_| unreadable())
230        }
231    }
232}
233
234/// `keys`' secret half as an `nsec`: the form the keyring keeps.
235fn nsec(keys: &Keys) -> String {
236    let Ok(nsec) = keys.secret_key().to_bech32();
237    nsec
238}
239
240/// The signer a bunker address names.
241fn remote_signer(bunker: &NostrConnectUri) -> Result<PublicKey, String> {
242    bunker.remote_signer_public_key().copied().ok_or_else(|| "not a bunker address".to_string())
243}
244
245/// Where the keyring keeps the key this client is known by to the signer
246/// `remote_signer`.
247fn client_keys_entry(remote_signer: &PublicKey) -> Result<keyring::Entry, String> {
248    keyring::Entry::new(KEYRING_SERVICE, &format!("{CLIENT_KEY_PREFIX}{}", remote_signer.to_hex())).map_err(|e| e.to_string())
249}
250
251/// The key this client is known by to the signer `remote_signer`: the one
252/// in the keyring, or, the first time, a new one that is put there.
253fn client_keys(remote_signer: &PublicKey) -> Result<Keys, String> {
254    let entry = client_keys_entry(remote_signer)?;
255    match entry.get_password() {
256        Ok(kept) => Keys::parse(kept.trim()).map_err(|_| "the client key in the keyring can't be read".to_string()),
257        Err(keyring::Error::NoEntry) => {
258            let keys = Keys::generate();
259            entry.set_password(&nsec(&keys)).map_err(|e| e.to_string())?;
260            Ok(keys)
261        }
262        Err(e) => Err(e.to_string()),
263    }
264}
265
266fn keyring_entry(public_key: &PublicKey) -> Result<keyring::Entry, String> {
267    let Ok(npub) = public_key.to_bech32();
268    keyring::Entry::new(KEYRING_SERVICE, &npub).map_err(|e| e.to_string())
269}
270
271/// Put what `public_key` signs with in the keyring, filed under its `npub`.
272fn store_signer(public_key: &PublicKey, signer: &StoredSigner) -> Result<(), String> {
273    keyring_entry(public_key)?.set_password(&signer.to_secret()).map_err(|e| e.to_string())
274}
275
276/// Whether the keyring holds what `public_key` signs with.
277fn has_signer(public_key: &PublicKey) -> Result<bool, String> {
278    match keyring_entry(public_key)?.get_password() {
279        Ok(_) => Ok(true),
280        Err(keyring::Error::NoEntry) => Ok(false),
281        Err(e) => Err(e.to_string()),
282    }
283}
284
285/// What `public_key` signs with, read from the keyring for the purpose.
286fn load_signer(public_key: &PublicKey) -> Result<StoredSigner, String> {
287    let secret = keyring_entry(public_key)?.get_password().map_err(|e| e.to_string())?;
288    let signer = StoredSigner::parse(&secret)?;
289    // An entry filed under one account and holding another's key would
290    // sign as somebody else.
291    match &signer {
292        StoredSigner::Local(keys) if keys.public_key() != *public_key => {
293            Err("the key in the keyring is not this account's".to_string())
294        }
295        _ => Ok(signer),
296    }
297}
298
299/// Take what `public_key` signs with out of the keyring, if it is there.
300fn delete_signer(public_key: &PublicKey) -> Result<(), String> {
301    match keyring_entry(public_key)?.delete_credential() {
302        Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
303        Err(e) => Err(e.to_string()),
304    }
305}
306
307/// Run a keyring call off the async executor: the Secret Service is reached
308/// over D-Bus with a blocking client, and may wait on an unlock prompt.
309async fn blocking<T: Send + 'static>(call: impl FnOnce() -> Result<T, String> + Send + 'static) -> Result<T, String> {
310    tokio::task::spawn_blocking(call).await.map_err(|e| e.to_string())?
311}
312
313/// Opens the page a remote signer asks to be approved on. Some signers
314/// answer a request with an address where the person says yes.
315#[derive(Debug)]
316struct ApproveInBrowser;
317
318impl AuthUrlHandler for ApproveInBrowser {
319    fn on_auth_url(&self, auth_url: Url) -> Pin<Box<dyn Future<Output = Result<(), nostr_connect::error::Error>> + Send + '_>> {
320        Box::pin(async move {
321            if let Err(e) = links::open_in_browser(auth_url.as_str()) {
322                tracing::warn!("the remote signer's approval page was not opened: {e:?}");
323            }
324            Ok(())
325        })
326    }
327}
328
329/// A connection to an account's remote signer.
330struct Session {
331    /// The account the signer signs as.
332    public_key: PublicKey,
333    connect: NostrConnect,
334}
335
336impl Session {
337    /// Connect to the signer at `bunker` as the client `client_keys`, and
338    /// ask whom it signs as. If that should be `expected` and isn't, there
339    /// is no session.
340    async fn open(bunker: NostrConnectUri, client_keys: Keys, expected: Option<PublicKey>) -> Result<Self, String> {
341        let mut connect = NostrConnect::new(bunker, client_keys, REMOTE_TIMEOUT, None).map_err(|e| e.to_string())?;
342        connect.auth_url_handler(ApproveInBrowser);
343        let public_key = match connect.get_public_key_async().await {
344            Ok(public_key) => public_key,
345            Err(e) => {
346                connect.shutdown().await;
347                return Err(e.to_string());
348            }
349        };
350        if expected.is_some_and(|expected| expected != public_key) {
351            connect.shutdown().await;
352            return Err("the remote signer now signs as another account".to_string());
353        }
354        Ok(Self { public_key, connect })
355    }
356
357    /// Have the signer sign `builder`'s event. What comes back is only
358    /// taken if it is signed, and by the account.
359    async fn sign(&self, builder: EventBuilder) -> Result<Event, String> {
360        let event = builder.finalize_async(&self.connect).await.map_err(|e| e.to_string())?;
361        if event.pubkey != self.public_key || event.verify().is_err() {
362            return Err("the remote signer did not sign as this account".to_string());
363        }
364        Ok(event)
365    }
366
367    /// Have the signer encrypt `text` to the account itself.
368    async fn encrypt(&self, text: &str) -> Result<String, String> {
369        self.connect.nip44_encrypt_async(&self.public_key, text).await.map_err(|e| e.to_string())
370    }
371
372    /// Have the signer decrypt `payload`, which the account encrypted to
373    /// itself, one way or the other.
374    async fn decrypt(&self, payload: &str) -> Result<String, String> {
375        let decrypted = if is_nip04(payload) {
376            self.connect.nip04_decrypt_async(&self.public_key, payload).await
377        } else {
378            self.connect.nip44_decrypt_async(&self.public_key, payload).await
379        };
380        decrypted.map_err(|e| e.to_string())
381    }
382
383    async fn close(self) {
384        self.connect.shutdown().await;
385    }
386}
387
388/// What signs for the account. Cheap to clone; clones share the connection
389/// to a remote signer, when there is one.
390#[derive(Clone, Default)]
391pub struct Signer {
392    /// The connection to the account's remote signer, once a signature was
393    /// asked of it. Held for as long as one request takes, so requests go
394    /// to the signer one at a time.
395    session: Arc<Mutex<Option<Session>>>,
396    /// Told when a sign-in that is waiting on a remote signer is called off.
397    cancelled: Arc<Notify>,
398}
399
400impl Signer {
401    /// Sign in with `credential`.
402    ///
403    /// A secret key is stored in the keyring first; if the keyring refuses,
404    /// nobody is signed in and the key is kept nowhere. A bunker address is
405    /// connected to first, as the client its signer knows or is about to,
406    /// which is where [`Self::cancel_sign_in`] can call it off; what is
407    /// then kept for the account is the address.
408    pub async fn sign_in(&self, credential: Credential) -> Result<Account, SignInError> {
409        // Whoever was signed in before is not any more.
410        let mut session = self.session.lock().await;
411        if let Some(previous) = session.take() {
412            previous.close().await;
413        }
414        match credential {
415            Credential::Public(public_key) => Ok(Account { public_key, can_sign: false }),
416            Credential::Secret(keys) => {
417                let public_key = keys.public_key();
418                blocking(move || store_signer(&public_key, &StoredSigner::Local(keys))).await.map_err(SignInError::Keyring)?;
419                Ok(Account { public_key, can_sign: true })
420            }
421            Credential::Bunker(bunker) => {
422                let with_secret = bunker.secret().is_some();
423                let signer =
424                    remote_signer(&bunker).map_err(|reason| SignInError::Bunker { reason, client: None, with_secret })?;
425                let client_keys = blocking(move || client_keys(&signer)).await.map_err(SignInError::Keyring)?;
426                let opened = self.connect(bunker, client_keys).await?;
427
428                let public_key = opened.public_key;
429                // Without the address's secret, which was for this once.
430                let stored = match opened.connect.bunker_uri().await {
431                    Ok(bunker) => StoredSigner::Remote(bunker),
432                    Err(e) => {
433                        opened.close().await;
434                        return Err(SignInError::Bunker { reason: e.to_string(), client: None, with_secret });
435                    }
436                };
437                if let Err(e) = blocking(move || store_signer(&public_key, &stored)).await {
438                    opened.close().await;
439                    return Err(SignInError::Keyring(e));
440                }
441                *session = Some(opened);
442                Ok(Account { public_key, can_sign: true })
443            }
444        }
445    }
446
447    /// Connect to the signer at `bunker` as the client `client_keys`, for
448    /// as long as it takes or until [`Self::cancel_sign_in`]. A signer that
449    /// says no is reported with the key it would have to know.
450    async fn connect(&self, bunker: NostrConnectUri, client_keys: Keys) -> Result<Session, SignInError> {
451        let client = Some(client_keys.public_key());
452        let with_secret = bunker.secret().is_some();
453        let cancelled = pin!(self.cancelled.notified());
454        let opening = pin!(Session::open(bunker, client_keys, None));
455        match select(opening, cancelled).await {
456            Either::Left((opened, _)) => opened.map_err(|reason| SignInError::Bunker { reason, client, with_secret }),
457            Either::Right(((), _)) => Err(SignInError::Cancelled),
458        }
459    }
460
461    /// Call off a sign-in that is waiting on a remote signer. One that is
462    /// past waiting, or isn't waiting on anyone, goes on as it was.
463    pub fn cancel_sign_in(&self) {
464        self.cancelled.notify_waiters();
465    }
466
467    /// What `public_key` signs with, ready for one use: its secret key, out
468    /// of the keyring, or its remote signer, which `session` is connected
469    /// to when this says `None`.
470    async fn keys_or_session(session: &mut Option<Session>, public_key: PublicKey) -> Result<Option<Keys>, SignError> {
471        if session.as_ref().is_some_and(|session| session.public_key == public_key) {
472            return Ok(None);
473        }
474        match blocking(move || load_signer(&public_key)).await.map_err(SignError::Keyring)? {
475            StoredSigner::Local(keys) => Ok(Some(keys)),
476            StoredSigner::Remote(bunker) => {
477                if let Some(previous) = session.take() {
478                    previous.close().await;
479                }
480                let signer = remote_signer(&bunker).map_err(SignError::Keyring)?;
481                let client_keys = blocking(move || client_keys(&signer)).await.map_err(SignError::Keyring)?;
482                let opened = Session::open(bunker, client_keys, Some(public_key)).await.map_err(SignError::Remote)?;
483                *session = Some(opened);
484                Ok(None)
485            }
486        }
487    }
488
489    /// The connection to the remote signer that `session` holds.
490    fn connected(session: &Option<Session>) -> Result<&Session, SignError> {
491        session.as_ref().ok_or_else(|| SignError::Remote("no connection to the remote signer".to_string()))
492    }
493
494    /// Sign the event `builder` describes as `public_key`: with its secret
495    /// key from the keyring, or through its remote signer.
496    pub async fn sign(&self, public_key: PublicKey, builder: EventBuilder) -> Result<Event, SignError> {
497        let mut session = self.session.lock().await;
498        match Self::keys_or_session(&mut session, public_key).await? {
499            Some(keys) => builder.finalize(&keys).map_err(|e| SignError::Keyring(e.to_string())),
500            None => Self::connected(&session)?.sign(builder).await.map_err(SignError::Remote),
501        }
502    }
503
504    /// Encrypt `text` so that only `public_key` can read it, as
505    /// `public_key`: what an account keeps to itself (NIP-44).
506    pub async fn encrypt_to_self(&self, public_key: PublicKey, text: &str) -> Result<String, SignError> {
507        let mut session = self.session.lock().await;
508        match Self::keys_or_session(&mut session, public_key).await? {
509            Some(keys) => keys.nip44_encrypt(&public_key, text).map_err(|e| SignError::Cipher(e.to_string())),
510            None => Self::connected(&session)?.encrypt(text).await.map_err(SignError::Remote),
511        }
512    }
513
514    /// Read `payload`, which `public_key` encrypted to itself: the new way
515    /// (NIP-44), or the old (NIP-04), which lists written by older clients
516    /// still are.
517    pub async fn decrypt_from_self(&self, public_key: PublicKey, payload: &str) -> Result<String, SignError> {
518        let mut session = self.session.lock().await;
519        match Self::keys_or_session(&mut session, public_key).await? {
520            Some(keys) => {
521                let decrypted = if is_nip04(payload) {
522                    keys.nip04_decrypt(&public_key, payload)
523                } else {
524                    keys.nip44_decrypt(&public_key, payload)
525                };
526                decrypted.map_err(|e| SignError::Cipher(e.to_string()))
527            }
528            None => Self::connected(&session)?.decrypt(payload).await.map_err(SignError::Remote),
529        }
530    }
531
532    /// Sign `public_key` out: what it signs with leaves the keyring, and its
533    /// remote signer is let go of. The key the signer knows this client by
534    /// stays, as the signer's knowing it does: signing in again is not a
535    /// new client to authorize. Forgetting this client is done at the signer.
536    pub async fn sign_out(&self, public_key: PublicKey) -> Result<(), String> {
537        if let Some(session) = self.session.lock().await.take() {
538            session.close().await;
539        }
540        blocking(move || delete_signer(&public_key)).await
541    }
542}
543
544/// The account the config names by `npub`, as it stands at startup: able to
545/// sign if the keyring holds what it signs with. A keyring that can't be
546/// asked leaves the account read-only rather than signed out.
547pub async fn restore(npub: String) -> Result<Account, String> {
548    let public_key = PublicKey::parse(&npub).map_err(|e| e.to_string())?;
549    let can_sign = blocking(move || has_signer(&public_key)).await.unwrap_or_else(|e| {
550        tracing::warn!("keyring unavailable, account is read-only for now: {e}");
551        false
552    });
553    Ok(Account { public_key, can_sign })
554}
555
556/// A remote signer in this process, for the tests here and for those of
557/// what signs or encrypts through one: no test can count on a keyring.
558#[cfg(test)]
559pub(crate) mod testing {
560    use super::{Session, Signer};
561    use nostr_connect::prelude::{
562        NostrConnectKeys, NostrConnectRemoteSigner, NostrConnectRequest, NostrConnectSignerActions, NostrConnectUri,
563    };
564    use nostr_sdk::prelude::{Keys, LocalRelay, PublicKey};
565    use std::future::Future;
566    use std::sync::Arc;
567    use std::time::Duration;
568    use tokio::sync::Mutex;
569
570    /// A remote signer that says yes to everything, or to everything but
571    /// signing, or but decrypting.
572    pub(crate) struct Approves {
573        pub signing: bool,
574        pub decrypting: bool,
575    }
576
577    impl NostrConnectSignerActions for Approves {
578        fn approve(&self, _client: &PublicKey, request: &NostrConnectRequest) -> bool {
579            match request {
580                NostrConnectRequest::SignEvent(_) => self.signing,
581                NostrConnectRequest::Nip04Decrypt { .. } | NostrConnectRequest::Nip44Decrypt { .. } => self.decrypting,
582                _ => true,
583            }
584        }
585    }
586
587    /// Run `test` with a remote signer that keeps the key `user_keys`,
588    /// listening on a relay in this process: its bunker address, with
589    /// `secret` if any. The relay keeps what it is sent, as any does.
590    pub(crate) fn with_remote_signer_for<F: Future<Output = ()>>(
591        user_keys: Keys,
592        secret: Option<&str>,
593        approves: Approves,
594        test: impl FnOnce(NostrConnectUri) -> F,
595    ) {
596        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
597        runtime.block_on(async {
598            let relay = LocalRelay::builder().build();
599            relay.run().await.unwrap();
600            let keys = NostrConnectKeys::new(Keys::generate(), user_keys);
601            let remote = NostrConnectRemoteSigner::new(keys, [relay.url().await], secret.map(String::from), None).unwrap();
602            let bunker = remote.bunker_uri();
603            let serving = tokio::spawn(async move { remote.serve(approves).await });
604            // Requests are not kept by the relay: the signer has to be
605            // listening before one is sent.
606            tokio::time::sleep(Duration::from_millis(500)).await;
607
608            tokio::time::timeout(Duration::from_secs(30), test(bunker)).await.unwrap();
609
610            serving.abort();
611            relay.shutdown();
612        });
613    }
614
615    impl Signer {
616        /// What signs for the account whose remote signer is at `bunker`,
617        /// connected to it already, as a client it has not seen before:
618        /// nothing is asked of a keyring.
619        pub(crate) async fn connected_to(bunker: NostrConnectUri) -> Self {
620            let session = Session::open(bunker, Keys::generate(), None).await.unwrap();
621            Self { session: Arc::new(Mutex::new(Some(session))), cancelled: Arc::default() }
622        }
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use super::testing::{Approves, with_remote_signer_for};
629    use super::{
630        Credential, CredentialError, KEYRING_SERVICE, Session, SignError, SignInError, Signer, StoredSigner, client_keys,
631        client_keys_entry, delete_signer, has_signer, is_nip04, keyring_entry, load_signer, parse_credential, remote_signer,
632        store_signer,
633    };
634    use nostr_connect::prelude::{Nip04, Nip44, NostrConnectUri};
635    use nostr_sdk::prelude::{EventBuilder, Keys, Kind, PublicKey, ToBech32};
636    use std::future::Future;
637    use std::time::Duration;
638
639    fn error(input: &str) -> Option<CredentialError> {
640        parse_credential(input).err()
641    }
642
643    fn note(text: &str) -> EventBuilder {
644        EventBuilder::new(Kind::TextNote, text)
645    }
646
647    /// Run `test` with a remote signer for a made-up account listening on a
648    /// relay in this process: its bunker address, with `secret` if any, and
649    /// the account it signs as.
650    fn with_remote_signer<F: Future<Output = ()>>(
651        secret: Option<&str>,
652        approves: Approves,
653        test: impl FnOnce(NostrConnectUri, PublicKey) -> F,
654    ) {
655        let user_keys = Keys::generate();
656        let user = user_keys.public_key();
657        with_remote_signer_for(user_keys, secret, approves, |bunker| test(bunker, user));
658    }
659
660    #[test]
661    fn what_was_encrypted_the_old_way_is_told_from_the_new() {
662        let keys = Keys::generate();
663        let me = keys.public_key();
664        let old = keys.nip04_encrypt(&me, "kept to myself").unwrap();
665        let new = keys.nip44_encrypt(&me, "kept to myself").unwrap();
666        assert!(is_nip04(&old), "{old}");
667        assert!(is_nip04(&format!("{old}-null")), "as one client left them");
668        assert!(!is_nip04(&new), "{new}");
669        for neither in ["", "?iv=", "?iv=tooshort", "héllo ?iv= wörld, not at the right place at all"] {
670            assert!(!is_nip04(neither), "{neither}");
671        }
672    }
673
674    #[test]
675    fn what_an_account_encrypts_to_itself_only_it_reads_back_here_or_at_its_remote_signer() {
676        let user_keys = Keys::generate();
677        let user = user_keys.public_key();
678        let approves = Approves { signing: true, decrypting: true };
679        with_remote_signer_for(user_keys.clone(), None, approves, async |bunker| {
680            let signer = Signer::connected_to(bunker).await;
681
682            // Encrypted there, read there and with the key itself.
683            let there = signer.encrypt_to_self(user, "kept to myself").await.unwrap();
684            assert!(!there.contains("kept"));
685            assert!(!is_nip04(&there), "the new way");
686            assert_eq!(signer.decrypt_from_self(user, &there).await.as_deref(), Ok("kept to myself"));
687            assert_eq!(user_keys.nip44_decrypt(&user, &there).as_deref().ok(), Some("kept to myself"));
688
689            // Encrypted with the key itself, either way, and read there.
690            let here = user_keys.nip44_encrypt(&user, "from another client").unwrap();
691            assert_eq!(signer.decrypt_from_self(user, &here).await.as_deref(), Ok("from another client"));
692            let old = user_keys.nip04_encrypt(&user, "from an old client").unwrap();
693            assert_eq!(signer.decrypt_from_self(user, &old).await.as_deref(), Ok("from an old client"));
694
695            // What somebody else encrypted to themselves is not read.
696            let stranger = Keys::generate();
697            let theirs = stranger.nip44_encrypt(&stranger.public_key(), "not yours").unwrap();
698            assert!(matches!(signer.decrypt_from_self(user, &theirs).await, Err(SignError::Remote(_))));
699        });
700    }
701
702    #[test]
703    fn a_remote_signer_that_will_not_decrypt_is_an_error() {
704        let user_keys = Keys::generate();
705        let user = user_keys.public_key();
706        let approves = Approves { signing: true, decrypting: false };
707        with_remote_signer_for(user_keys.clone(), None, approves, async |bunker| {
708            let signer = Signer::connected_to(bunker).await;
709            let kept = user_keys.nip44_encrypt(&user, "kept to myself").unwrap();
710            let refused = signer.decrypt_from_self(user, &kept).await;
711            assert!(matches!(&refused, Err(SignError::Remote(reason)) if reason.contains("Rejected")), "{refused:?}");
712        });
713    }
714
715    #[test]
716    fn a_remote_signer_signs_as_the_account_whose_key_it_keeps() {
717        with_remote_signer(Some("once"), Approves { signing: true, decrypting: true }, async |bunker, user| {
718            assert_eq!(bunker.secret(), Some("once"));
719            let session = Session::open(bunker, Keys::generate(), None).await.unwrap();
720            assert_eq!(session.public_key, user);
721
722            let signed = session.sign(note("signed far away")).await.unwrap();
723            assert_eq!(signed.pubkey, user);
724            assert_eq!(signed.content, "signed far away");
725            assert!(signed.verify().is_ok());
726
727            // What is kept for next time has not the secret, which was for
728            // this once.
729            assert_eq!(session.connect.bunker_uri().await.unwrap().secret(), None);
730            session.close().await;
731        });
732    }
733
734    #[test]
735    fn a_session_is_only_for_the_account_it_is_expected_to_sign_as() {
736        with_remote_signer(None, Approves { signing: true, decrypting: true }, async |bunker, user| {
737            let client_keys = Keys::generate();
738            // As at a later start: the same client, the address without a
739            // secret, and the account known.
740            let session = Session::open(bunker.clone(), client_keys.clone(), Some(user)).await.unwrap();
741            assert!(session.sign(note("again")).await.is_ok());
742            session.close().await;
743
744            let somebody_else = Keys::generate().public_key();
745            assert!(Session::open(bunker, client_keys, Some(somebody_else)).await.is_err());
746        });
747    }
748
749    #[test]
750    fn a_signature_the_remote_signer_refuses_is_an_error() {
751        with_remote_signer(None, Approves { signing: false, decrypting: true }, async |bunker, _user| {
752            let session = Session::open(bunker, Keys::generate(), None).await.unwrap();
753            let refused = session.sign(note("not this")).await;
754            assert!(refused.is_err_and(|reason| reason.contains("Rejected")));
755            session.close().await;
756        });
757    }
758
759    #[test]
760    fn a_signer_that_says_no_is_reported_with_the_key_it_would_have_to_know() {
761        // The signer wants a secret, and the address has another.
762        with_remote_signer(Some("right"), Approves { signing: true, decrypting: true }, async |bunker, _user| {
763            let NostrConnectUri::Bunker { remote_signer_public_key, relays, .. } = bunker else {
764                panic!("a bunker address");
765            };
766            let wrong = NostrConnectUri::Bunker { remote_signer_public_key, relays, secret: Some("wrong".into()) };
767            let client_keys = Keys::generate();
768
769            let refused = Signer::default().connect(wrong, client_keys.clone()).await;
770            match refused {
771                Err(SignInError::Bunker { reason, client, with_secret }) => {
772                    assert!(!reason.is_empty());
773                    assert_eq!(client, Some(client_keys.public_key()));
774                    assert!(with_secret);
775                }
776                _ => panic!("refused"),
777            }
778        });
779    }
780
781    #[test]
782    fn a_sign_in_waiting_on_a_remote_signer_can_be_called_off() {
783        with_remote_signer(None, Approves { signing: true, decrypting: true }, async |bunker, _user| {
784            // The same relay, and a signer nobody is: no answer will come.
785            let NostrConnectUri::Bunker { relays, .. } = bunker else {
786                panic!("a bunker address");
787            };
788            let nobody =
789                NostrConnectUri::Bunker { remote_signer_public_key: Keys::generate().public_key(), relays, secret: None };
790
791            let signer = Signer::default();
792            let waiting = signer.connect(nobody, Keys::generate());
793            let calling_off = async {
794                tokio::time::sleep(Duration::from_millis(500)).await;
795                signer.cancel_sign_in();
796            };
797            let (result, ()) = tokio::join!(waiting, calling_off);
798            assert!(matches!(result, Err(SignInError::Cancelled)));
799
800            // Calling off when nobody is signing in is not kept for later.
801            signer.cancel_sign_in();
802            let public_key = Keys::generate().public_key();
803            assert!(signer.sign_in(Credential::Public(public_key)).await.is_ok());
804        });
805    }
806
807    /// Whether a system keyring answers here. The tests of it run wherever
808    /// one does. Where none does there is nothing for them to hold to: a
809    /// machine with no session, which is not one Avestruz runs on.
810    fn keyring_answers() -> bool {
811        let asked =
812            keyring::Entry::new(KEYRING_SERVICE, "a-test-asking-whether-it-answers").and_then(|entry| entry.get_password());
813        matches!(asked, Ok(_) | Err(keyring::Error::NoEntry))
814    }
815
816    /// What a test put in the real keyring, taken out again when the test
817    /// is over, however it ended: one that fails half way leaves no
818    /// throwaway key behind.
819    struct TakenOutAfter(Vec<keyring::Entry>);
820
821    impl Drop for TakenOutAfter {
822        fn drop(&mut self) {
823            for entry in &self.0 {
824                let _ = entry.delete_credential();
825            }
826        }
827    }
828
829    /// Against the real system keyring, with a throwaway key that is removed
830    /// again.
831    #[test]
832    fn a_secret_key_is_kept_in_the_keyring_until_sign_out() {
833        if !keyring_answers() {
834            return;
835        }
836        let keys = Keys::generate();
837        let public_key = keys.public_key();
838        let _taken_out = TakenOutAfter(vec![keyring_entry(&public_key).unwrap()]);
839        assert_eq!(has_signer(&public_key), Ok(false));
840
841        store_signer(&public_key, &StoredSigner::Local(keys.clone())).unwrap();
842        assert_eq!(has_signer(&public_key), Ok(true));
843        assert!(matches!(load_signer(&public_key), Ok(StoredSigner::Local(_))));
844
845        // While it is there, the account signs with it, and as itself.
846        let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
847        let signer = Signer::default();
848        let signed = runtime.block_on(signer.sign(public_key, note("signed from the keyring"))).unwrap();
849        assert_eq!(signed.pubkey, public_key);
850        assert!(signed.verify().is_ok());
851
852        // And encrypts to itself, and reads it back, either way.
853        let kept = runtime.block_on(signer.encrypt_to_self(public_key, "kept to myself")).unwrap();
854        assert_eq!(keys.nip44_decrypt(&public_key, &kept).as_deref().ok(), Some("kept to myself"));
855        assert_eq!(runtime.block_on(signer.decrypt_from_self(public_key, &kept)).as_deref(), Ok("kept to myself"));
856        let old = keys.nip04_encrypt(&public_key, "from an old client").unwrap();
857        assert_eq!(runtime.block_on(signer.decrypt_from_self(public_key, &old)).as_deref(), Ok("from an old client"));
858        let stranger = Keys::generate();
859        let theirs = stranger.nip44_encrypt(&stranger.public_key(), "not yours").unwrap();
860        assert!(matches!(runtime.block_on(signer.decrypt_from_self(public_key, &theirs)), Err(SignError::Cipher(_))));
861
862        runtime.block_on(signer.sign_out(public_key)).unwrap();
863        assert_eq!(has_signer(&public_key), Ok(false));
864        // Signing out of an account whose key is already gone is not an error.
865        assert_eq!(delete_signer(&public_key), Ok(()));
866        assert!(matches!(runtime.block_on(signer.sign(public_key, note("no key"))), Err(SignError::Keyring(_))));
867    }
868
869    /// Against the real system keyring, as the test above.
870    #[test]
871    fn a_bunker_account_signs_through_what_the_keyring_keeps_until_sign_out() {
872        if !keyring_answers() {
873            return;
874        }
875        with_remote_signer(None, Approves { signing: true, decrypting: true }, async |bunker, user| {
876            let remote = remote_signer(&bunker).unwrap();
877            let _taken_out = TakenOutAfter(vec![keyring_entry(&user).unwrap(), client_keys_entry(&remote).unwrap()]);
878            let signer = Signer::default();
879            let account = signer.sign_in(Credential::Bunker(bunker.clone())).await.unwrap();
880            assert_eq!((account.public_key, account.can_sign), (user, true));
881            assert!(matches!(load_signer(&user), Ok(StoredSigner::Remote(_))));
882            assert_eq!(signer.sign(user, note("at once")).await.map(|event| event.pubkey), Ok(user));
883            let known_as = client_keys(&remote).unwrap().public_key();
884
885            // After a restart there is no connection, only the keyring.
886            let restarted = Signer::default();
887            assert_eq!(super::restore(account.npub()).await, Ok(account.clone()));
888            assert_eq!(restarted.sign(user, note("later")).await.map(|event| event.pubkey), Ok(user));
889
890            restarted.sign_out(user).await.unwrap();
891            assert_eq!(has_signer(&user), Ok(false));
892            assert!(matches!(restarted.sign(user, note("signed out")).await, Err(SignError::Keyring(_))));
893
894            // Signing in again is as the client the signer already knows.
895            assert_eq!(client_keys(&remote).unwrap().public_key(), known_as);
896            assert_eq!(restarted.sign_in(Credential::Bunker(bunker)).await, Ok(account));
897            restarted.sign_out(user).await.unwrap();
898            client_keys_entry(&remote).unwrap().delete_credential().unwrap();
899        });
900    }
901
902    #[test]
903    fn what_the_keyring_keeps_reads_back_as_it_was_written() {
904        let keys = Keys::generate();
905        let nsec = keys.secret_key().to_bech32().unwrap();
906
907        // A secret key is kept as its nsec and nothing else.
908        assert_eq!(StoredSigner::Local(keys.clone()).to_secret(), nsec);
909        assert!(matches!(StoredSigner::parse(&nsec), Ok(StoredSigner::Local(read)) if read == keys));
910
911        // A remote signer, as its address and nothing else.
912        let address = format!("bunker://{}?relay=wss://relay.example.com", Keys::generate().public_key().to_hex());
913        let bunker = NostrConnectUri::parse(&address).unwrap();
914        assert_eq!(StoredSigner::Remote(bunker.clone()).to_secret(), address);
915        assert!(matches!(StoredSigner::parse(&address), Ok(StoredSigner::Remote(read)) if read == bunker));
916
917        assert!(StoredSigner::parse("").is_err());
918        assert!(StoredSigner::parse("not a key").is_err());
919        assert!(StoredSigner::parse("bunker://not-a-signer").is_err());
920        assert!(StoredSigner::parse("https://example.com").is_err());
921    }
922
923    #[test]
924    fn an_nsec_signs_in_with_full_access_and_an_npub_read_only() {
925        let keys = Keys::generate();
926        let nsec = keys.secret_key().to_bech32().unwrap();
927        let npub = keys.public_key().to_bech32().unwrap();
928
929        match parse_credential(&nsec) {
930            Ok(Credential::Secret(parsed)) => assert_eq!(parsed.public_key(), keys.public_key()),
931            _ => panic!("an nsec is a secret key"),
932        }
933        match parse_credential(&npub) {
934            Ok(Credential::Public(parsed)) => assert_eq!(parsed, keys.public_key()),
935            _ => panic!("an npub is a public key"),
936        }
937    }
938
939    #[test]
940    fn a_bunker_address_signs_in_through_the_signer_and_relays_it_names() {
941        let remote = Keys::generate().public_key();
942        let address =
943            format!("bunker://{}?relay=wss://relay.example.com&relay=wss://other.example.com&secret=abc", remote.to_hex());
944
945        match parse_credential(&format!("  {address}\n")) {
946            Ok(Credential::Bunker(bunker)) => {
947                assert_eq!(bunker.remote_signer_public_key(), Some(&remote));
948                assert_eq!(bunker.relays().len(), 2);
949                assert_eq!(bunker.secret(), Some("abc"));
950            }
951            _ => panic!("a bunker address"),
952        }
953        assert!(matches!(parse_credential(&address.replace("bunker://", "BUNKER://")), Ok(Credential::Bunker(_))));
954
955        assert_eq!(error(&format!("bunker://{}", remote.to_hex())), Some(CredentialError::InvalidBunker), "no relay");
956        assert_eq!(error("bunker://not-a-key?relay=wss://relay.example.com"), Some(CredentialError::InvalidBunker));
957        assert_eq!(error("bunker://"), Some(CredentialError::InvalidBunker));
958        // The other kind of address is one a client shows, not one it is given.
959        let shown = format!("nostrconnect://{}?relay=wss://relay.example.com", remote.to_hex());
960        assert_eq!(error(&shown), Some(CredentialError::NotAKey));
961    }
962
963    #[test]
964    fn a_pasted_key_may_carry_spaces_or_the_nostr_scheme() {
965        let npub = Keys::generate().public_key().to_bech32().unwrap();
966        assert!(matches!(parse_credential(&format!("  {npub}\n")), Ok(Credential::Public(_))));
967        assert!(matches!(parse_credential(&format!("nostr:{npub}")), Ok(Credential::Public(_))));
968    }
969
970    #[test]
971    fn anything_else_is_refused_with_the_reason() {
972        assert_eq!(error("   "), Some(CredentialError::Empty));
973        assert_eq!(error("hello"), Some(CredentialError::NotAKey));
974        assert_eq!(error("nsec1notakey"), Some(CredentialError::InvalidSecret));
975        assert_eq!(error("npub1notakey"), Some(CredentialError::InvalidPublic));
976        // A hex key doesn't say which half it is.
977        let hex = Keys::generate().public_key().to_hex();
978        assert_eq!(error(&hex), Some(CredentialError::NotAKey));
979    }
980}