nostr-sdk 0.45.0

A full-featured SDK for building high-performance and reliable nostr applications.
Documentation
//! A NIP-42 authenticator

use std::any::Any;
use std::fmt::Debug;

use nostr::prelude::*;

use crate::error::Error;
use crate::future::BoxedFuture;

/// Authenticator
pub trait Authenticator: Any + Debug + Send + Sync {
    /// Makes a NIP-42 event for authentication
    ///
    /// Must return a valid NIP-42 event.
    fn make_auth_event<'a>(
        &'a self,
        relay_url: &'a RelayUrl,
        challenge: &'a str,
    ) -> BoxedFuture<'a, Result<Event, Error>>;
}

/// An authenticator that uses a signer that implements [`AsyncGetPublicKey`] and [`AsyncSignEvent`] for creating NIP-42 events.
#[derive(Debug)]
pub struct SignerAuthenticator<T>
where
    T: AsyncGetPublicKey + AsyncSignEvent,
{
    signer: T,
}

impl<T> SignerAuthenticator<T>
where
    T: AsyncGetPublicKey + AsyncSignEvent,
{
    /// Constructs a new authenticator
    #[inline]
    pub fn new(signer: T) -> Self {
        Self { signer }
    }
}

impl<T> From<T> for SignerAuthenticator<T>
where
    T: AsyncGetPublicKey + AsyncSignEvent,
{
    /// Constructs a new authenticator from a signer
    #[inline]
    fn from(signer: T) -> Self {
        Self::new(signer)
    }
}

impl<T> Authenticator for SignerAuthenticator<T>
where
    T: AsyncGetPublicKey + AsyncSignEvent,
{
    fn make_auth_event<'a>(
        &'a self,
        relay_url: &'a RelayUrl,
        challenge: &'a str,
    ) -> BoxedFuture<'a, Result<Event, Error>> {
        Box::pin(async move {
            Ok(ClientAuthentication::new(challenge, relay_url.clone())
                .finalize_async(&self.signer)
                .await?)
        })
    }
}