1use 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
71const KEYRING_SERVICE: &str = "cosmic-applet-avestruz";
74
75const CLIENT_KEY_PREFIX: &str = "bunker-client:";
78
79const BUNKER_SCHEME: &str = "bunker://";
81
82const REMOTE_TIMEOUT: Duration = Duration::from_secs(60);
85
86pub enum Credential {
88 Secret(Keys),
90 Public(PublicKey),
92 Bunker(NostrConnectUri),
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum CredentialError {
99 Empty,
100 NotAKey,
102 InvalidSecret,
103 InvalidPublic,
104 InvalidBunker,
106}
107
108fn 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
113pub fn parse_credential(input: &str) -> Result<Credential, CredentialError> {
119 let input = input.trim();
120 if is_bunker_address(input) {
121 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#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct Account {
144 pub public_key: PublicKey,
145 pub can_sign: bool,
148}
149
150impl Account {
151 pub fn npub(&self) -> String {
153 let Ok(npub) = self.public_key.to_bech32();
154 npub
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
160pub enum SignInError {
161 Cancelled,
163 Keyring(String),
165 Bunker {
167 reason: String,
169 client: Option<PublicKey>,
171 with_secret: bool,
173 },
174}
175
176#[derive(Debug, Clone, PartialEq, Eq)]
178pub enum SignError {
179 Keyring(String),
182 Remote(String),
184 Cipher(String),
188}
189
190fn is_nip04(payload: &str) -> bool {
195 const IV_MARK: &[u8] = b"?iv=";
196 const IV_CHARS: usize = 24;
197 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
203enum StoredSigner {
205 Local(Keys),
207 Remote(NostrConnectUri),
210}
211
212impl StoredSigner {
213 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 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
234fn nsec(keys: &Keys) -> String {
236 let Ok(nsec) = keys.secret_key().to_bech32();
237 nsec
238}
239
240fn 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
245fn 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
251fn 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
271fn 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
276fn 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
285fn 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 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
299fn 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
307async 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#[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
329struct Session {
331 public_key: PublicKey,
333 connect: NostrConnect,
334}
335
336impl Session {
337 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 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 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 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#[derive(Clone, Default)]
391pub struct Signer {
392 session: Arc<Mutex<Option<Session>>>,
396 cancelled: Arc<Notify>,
398}
399
400impl Signer {
401 pub async fn sign_in(&self, credential: Credential) -> Result<Account, SignInError> {
409 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 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 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 pub fn cancel_sign_in(&self) {
464 self.cancelled.notify_waiters();
465 }
466
467 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 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 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 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 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 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
544pub 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#[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 #[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 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 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 assert_eq!(StoredSigner::Local(keys.clone()).to_secret(), nsec);
909 assert!(matches!(StoredSigner::parse(&nsec), Ok(StoredSigner::Local(read)) if read == keys));
910
911 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 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 let hex = Keys::generate().public_key().to_hex();
978 assert_eq!(error(&hex), Some(CredentialError::NotAKey));
979 }
980}