feat: add initial support web via wasm (#35)

Reviewed-on: #35
This commit was merged in pull request #35.
This commit is contained in:
2026-07-25 03:43:51 +00:00
parent 4b57a1d2a6
commit b518c729f6
57 changed files with 1550 additions and 1463 deletions

View File

@@ -9,22 +9,25 @@ common = { path = "../common" }
nostr.workspace = true
nostr-sdk.workspace = true
nostr-lmdb.workspace = true
nostr-gossip-memory.workspace = true
nostr-connect.workspace = true
nostr-blossom.workspace = true
nostr-connect.workspace = true
gpui.workspace = true
gpui_tokio.workspace = true
smol.workspace = true
flume.workspace = true
futures.workspace = true
log.workspace = true
anyhow.workspace = true
webbrowser.workspace = true
serde.workspace = true
serde_json.workspace = true
rustls = "0.23"
petname = "2.0.2"
whoami = "1.6.1"
mime_guess = "2.0.4"
[target.'cfg(target_arch = "wasm32")'.dependencies]
nostr-memory.workspace = true
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
nostr-lmdb.workspace = true
smol.workspace = true
gpui_tokio.workspace = true
rustls = "0.23"

View File

@@ -1,12 +1,14 @@
use std::path::PathBuf;
use anyhow::{anyhow, Error};
use anyhow::{Error, anyhow};
use gpui::AsyncApp;
#[cfg(not(target_arch = "wasm32"))]
use gpui_tokio::Tokio;
use mime_guess::from_path;
use nostr_blossom::prelude::*;
use nostr_sdk::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
pub async fn upload(server: Url, path: PathBuf, cx: &AsyncApp) -> Result<Url, Error> {
let content_type = from_path(&path).first_or_octet_stream().to_string();
let data = smol::fs::read(path).await?;
@@ -25,3 +27,8 @@ pub async fn upload(server: Url, path: PathBuf, cx: &AsyncApp) -> Result<Url, Er
.await
.map_err(|e| anyhow!("Upload error: {e}"))?
}
#[cfg(target_arch = "wasm32")]
pub async fn upload(_server: Url, _path: PathBuf, _cx: &AsyncApp) -> Result<Url, Error> {
Err(anyhow!("File upload not supported on web"))
}

View File

@@ -8,7 +8,8 @@ pub const COOP_PUBKEY: &str = "npub1j3rz3ndl902lya6ywxvy5c983lxs8mpukqnx4pa4lt5w
pub const APP_ID: &str = "su.reya.coop";
/// Keyring name
pub const KEYRING: &str = "Coop Safe Storage";
pub const MASTER_KEYRING: &str = "Coop Master Key";
pub const USER_KEYRING: &str = "Coop User Credential";
/// Default timeout for subscription
pub const TIMEOUT: u64 = 2;
@@ -45,7 +46,7 @@ pub const SEARCH_RELAYS: [&str; 2] = ["wss://antiprimal.net", "wss://search.nos.
/// Default bootstrap relays
pub const BOOTSTRAP_RELAYS: [&str; 3] = [
"wss://relay.damus.io",
"wss://relay.ditto.pub",
"wss://relay.primal.net",
"wss://user.kindpag.es",
];

View File

@@ -3,31 +3,38 @@ use std::time::Duration;
use anyhow::{Error, anyhow};
use common::config_dir;
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString, Task, Window};
use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task, Window};
use nostr_connect::prelude::*;
use nostr_gossip_memory::prelude::*;
#[cfg(not(target_arch = "wasm32"))]
use nostr_lmdb::prelude::*;
#[cfg(target_arch = "wasm32")]
use nostr_memory::prelude::*;
use nostr_sdk::prelude::*;
mod blossom;
mod constants;
mod nip05;
mod nip4e;
mod signer;
pub use blossom::*;
pub use constants::*;
pub use nip4e::*;
pub use nip05::*;
pub use signer::{CoopAuthUrlHandler, UniversalSigner};
pub fn init(window: &mut Window, cx: &mut App) {
// rustls uses the `aws_lc_rs` provider by default
// This only errors if the default provider has already
// been installed. We can ignore this `Result`.
#[cfg(not(target_arch = "wasm32"))]
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.ok();
// Initialize the tokio runtime
#[cfg(not(target_arch = "wasm32"))]
gpui_tokio::init(cx);
NostrRegistry::set_global(cx.new(|cx| NostrRegistry::new(window, cx)), cx);
@@ -40,21 +47,27 @@ impl Global for GlobalNostrRegistry {}
/// Signer event.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StateEvent {
/// Connecting to the bootstrapping relay
Connecting,
/// Connected to the bootstrapping relay
Connected,
/// The state is busy
Busy,
/// User has no signer
NoSigner,
/// The signer has changed
SignerChanged,
/// An error occurred
Error(SharedString),
Error(String),
}
impl StateEvent {
pub fn error<T>(error: T) -> Self
where
T: Into<SharedString>,
T: Into<String>,
{
Self::Error(error.into())
}
pub fn signer_changed(&self) -> bool {
matches!(self, StateEvent::SignerChanged)
}
}
/// Nostr Registry
@@ -63,8 +76,11 @@ pub struct NostrRegistry {
/// Nostr client
client: Client,
/// Currently active signer
pub signer: Entity<Option<Keys>>,
/// Universal signer
signer: UniversalSigner,
/// Current user's public key
current_user: Option<PublicKey>,
/// Tasks for asynchronous operations
tasks: Vec<Task<Result<(), Error>>>,
@@ -85,18 +101,24 @@ impl NostrRegistry {
/// Create a new nostr instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let signer = cx.new(|_| None);
let signer = UniversalSigner::new(Keys::generate());
let authenticator = SignerAuthenticator::new(signer.clone());
// Construct the nostr lmdb instance
let lmdb = cx.foreground_executor().block_on(async move {
#[cfg(not(target_arch = "wasm32"))]
let database = cx.foreground_executor().block_on(async move {
NostrLmdb::open(config_dir().join("nostr"))
.await
.expect("Failed to initialize database")
});
#[cfg(target_arch = "wasm32")]
let database = MemoryDatabase::unbounded();
// Construct the nostr client
let client = ClientBuilder::default()
.database(lmdb)
.database(database)
.authenticator(authenticator)
.gossip(NostrGossipMemory::unbounded())
.gossip_config(GossipConfig::default().no_background_refresh())
.connect_timeout(Duration::from_secs(10))
@@ -105,14 +127,16 @@ impl NostrRegistry {
})
.build();
// Run at the end of current cycle
// Connect to bootstrap relays after the window is ready
cx.defer_in(window, |this, _window, cx| {
this.connect(cx);
this.connect_bootstrap_relays(cx);
this.get_user_credential(cx);
});
Self {
client,
signer,
current_user: None,
tasks: vec![],
}
}
@@ -122,26 +146,48 @@ impl NostrRegistry {
self.client.clone()
}
/// Get the signer
pub fn signer(&self, cx: &App) -> Option<Keys> {
self.signer.read(cx).clone()
/// Get the current signer
pub fn signer(&self) -> UniversalSigner {
self.signer.clone()
}
/// Get the public key of the signer
pub fn signer_pubkey(&self, cx: &App) -> Option<PublicKey> {
self.signer.read(cx).as_ref().map(|s| s.public_key())
/// Get the current user's public key
pub fn current_user(&self) -> Option<PublicKey> {
self.current_user
}
/// Set the signer to the given keys
pub fn set_signer(&mut self, new_keys: Keys, cx: &mut Context<Self>) {
self.signer.update(cx, |this, cx| {
*this = Some(new_keys);
cx.notify();
});
/// Update the signer
pub fn set_signer<T>(&mut self, new_signer: T, cx: &mut Context<Self>)
where
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
<T as AsyncGetPublicKey>::Error: std::error::Error + Send + Sync + 'static,
<T as AsyncSignEvent>::Error: std::error::Error + Send + Sync + 'static,
<T as AsyncNip44>::Error: std::error::Error + Send + Sync + 'static,
{
cx.spawn(async move |this, cx| {
match new_signer.get_public_key_async().await {
Ok(public_key) => {
this.update(cx, |this, cx| {
this.signer.swap_inner(new_signer);
this.current_user = Some(public_key);
cx.emit(StateEvent::SignerChanged);
cx.notify();
})?;
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string()));
})?;
}
};
Ok::<(), anyhow::Error>(())
})
.detach();
}
/// Connect to the bootstrapping relays
fn connect(&mut self, cx: &mut Context<Self>) {
fn connect_bootstrap_relays(&mut self, cx: &mut Context<Self>) {
let client = self.client();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
@@ -164,24 +210,90 @@ impl NostrRegistry {
Ok(())
});
// Emit connecting event
cx.emit(StateEvent::Connecting);
self.tasks.push(cx.spawn(async move |this, cx| {
if let Err(e) = task.await {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string()));
})?;
} else {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::Connected);
})?;
}
Ok(())
}));
}
/// Check the user's credential and set the signer if valid
fn get_user_credential(&mut self, cx: &mut Context<Self>) {
let user_keyring = cx.read_credentials(USER_KEYRING);
let master_keyring = self.get_master_key(cx);
self.tasks.push(cx.spawn(async move |this, cx| {
match user_keyring.await {
Ok(Some((_username, secret))) => {
let content = String::from_utf8(secret)?;
if content.starts_with("nsec1") {
let secret_key = SecretKey::parse(&content)?;
let keys = Keys::new(secret_key);
this.update(cx, |this, cx| {
this.set_signer(keys, cx);
cx.notify();
})?;
} else if content.starts_with("bunker://") {
let keys = master_keyring.await;
let timeout = Duration::from_secs(30);
let uri = NostrConnectUri::parse(content)?;
// Construct the nostr connect signer
let mut signer = NostrConnect::new(uri, keys, timeout, None)?;
// Handle auth url with the default browser
signer.auth_url_handler(CoopAuthUrlHandler);
this.update(cx, |this, cx| {
this.set_signer(signer, cx);
cx.notify();
})?;
}
}
_ => {
this.update(cx, |_, cx| {
cx.emit(StateEvent::NoSigner);
})?;
}
}
Ok(())
}));
}
/// Get the master key that used for Nostr Connect
pub fn get_master_key(&self, cx: &App) -> Task<Keys> {
let task = cx.read_credentials(MASTER_KEYRING);
cx.spawn(async move |cx| {
let (keys, new_key) = match task.await {
Ok(Some((_user, secret))) => match SecretKey::from_slice(&secret) {
Ok(secret_key) => (Keys::new(secret_key), false),
_ => (Keys::generate(), true),
},
_ => (Keys::generate(), true),
};
if new_key {
let keys_clone = keys.clone();
let username = keys_clone.public_key().to_hex();
let password = keys_clone.secret_key().to_secret_bytes();
cx.update(|cx| {
let task = cx.write_credentials(MASTER_KEYRING, &username, &password);
cx.background_spawn(async move { task.await.ok() }).detach();
});
}
keys
})
}
/// Get the public key of a NIP-05 address
pub fn query_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
let client = self.client();
@@ -291,10 +403,7 @@ impl NostrRegistry {
pub fn wot_search(&self, query: &str, cx: &App) -> Task<Result<Vec<PublicKey>, Error>> {
let client = self.client();
let query = query.to_string();
let Some(signer) = self.signer.read(cx).clone() else {
return Task::ready(Err(anyhow!("Signer is required")));
};
let signer = self.signer.clone();
cx.background_spawn(async move {
// Construct a vertex request event

View File

@@ -1,9 +1,9 @@
use std::sync::Arc;
use anyhow::Error;
use futures::io::AsyncReadExt;
use gpui::http_client::{AsyncBody, HttpClient};
use nostr_sdk::prelude::*;
use smol::io::AsyncReadExt;
#[allow(async_fn_in_trait)]
pub trait NostrAddress {

196
crates/state/src/signer.rs Normal file
View File

@@ -0,0 +1,196 @@
use std::error::Error;
use std::fmt;
use std::sync::{Arc, RwLock};
use nostr_connect::client::AuthUrlHandler;
use nostr_sdk::prelude::*;
#[derive(Debug)]
pub struct UniversalSignerError(Box<dyn Error + Send + Sync + 'static>);
impl fmt::Display for UniversalSignerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Error for UniversalSignerError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.0)
}
}
impl UniversalSignerError {
pub fn new<E>(err: E) -> Self
where
E: Error + Send + Sync + 'static,
{
UniversalSignerError(Box::new(err))
}
}
#[derive(Clone, Debug)]
pub struct UniversalSigner {
inner: Arc<RwLock<Arc<dyn InnerSigner>>>,
}
impl UniversalSigner {
pub fn new<T>(signer: T) -> Self
where
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
{
Self {
inner: Arc::new(RwLock::new(Arc::new(InnerSignerImpl(signer)))),
}
}
/// Swap the inner signer in-place. All clones see the new signer.
pub fn swap_inner<T>(&self, new_signer: T)
where
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + 'static,
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
{
*self.inner.write().expect("RwLock poisoned") = Arc::new(InnerSignerImpl(new_signer));
}
}
trait InnerSigner: fmt::Debug + Send + Sync + 'static {
fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, UniversalSignerError>>;
fn sign_event_async(
&self,
unsigned: UnsignedEvent,
) -> BoxedFuture<'_, Result<Event, UniversalSignerError>>;
fn nip44_encrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, UniversalSignerError>>;
fn nip44_decrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> BoxedFuture<'a, Result<String, UniversalSignerError>>;
}
#[derive(Debug)]
struct InnerSignerImpl<T>(T);
impl<T> InnerSigner for InnerSignerImpl<T>
where
T: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Send + Sync + 'static,
<T as AsyncGetPublicKey>::Error: Error + Send + Sync + 'static,
<T as AsyncSignEvent>::Error: Error + Send + Sync + 'static,
<T as AsyncNip44>::Error: Error + Send + Sync + 'static,
{
fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, UniversalSignerError>> {
Box::pin(async move {
AsyncGetPublicKey::get_public_key_async(&self.0)
.await
.map_err(UniversalSignerError::new)
})
}
fn sign_event_async(
&self,
unsigned: UnsignedEvent,
) -> BoxedFuture<'_, Result<Event, UniversalSignerError>> {
Box::pin(async move {
AsyncSignEvent::sign_event_async(&self.0, unsigned)
.await
.map_err(UniversalSignerError::new)
})
}
fn nip44_encrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, UniversalSignerError>> {
Box::pin(async move {
AsyncNip44::nip44_encrypt_async(&self.0, public_key, content)
.await
.map_err(UniversalSignerError::new)
})
}
fn nip44_decrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> BoxedFuture<'a, Result<String, UniversalSignerError>> {
Box::pin(async move {
AsyncNip44::nip44_decrypt_async(&self.0, public_key, payload)
.await
.map_err(UniversalSignerError::new)
})
}
}
impl UniversalSigner {
#[allow(dead_code)]
fn with_inner<R>(&self, f: impl FnOnce(&dyn InnerSigner) -> R) -> R {
let guard = self.inner.read().expect("RwLock poisoned");
f(&**guard)
}
}
impl AsyncGetPublicKey for UniversalSigner {
type Error = UniversalSignerError;
fn get_public_key_async(&self) -> BoxedFuture<'_, Result<PublicKey, Self::Error>> {
let inner = self.inner.read().expect("RwLock poisoned").clone();
Box::pin(async move { inner.get_public_key_async().await })
}
}
impl AsyncSignEvent for UniversalSigner {
type Error = UniversalSignerError;
fn sign_event_async(
&self,
unsigned: UnsignedEvent,
) -> BoxedFuture<'_, Result<Event, Self::Error>> {
let inner = self.inner.read().expect("RwLock poisoned").clone();
Box::pin(async move { inner.sign_event_async(unsigned).await })
}
}
impl AsyncNip44 for UniversalSigner {
type Error = UniversalSignerError;
fn nip44_encrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, Self::Error>> {
let inner = self.inner.read().expect("RwLock poisoned").clone();
Box::pin(async move { inner.nip44_encrypt_async(public_key, content).await })
}
fn nip44_decrypt_async<'a>(
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> BoxedFuture<'a, Result<String, Self::Error>> {
let inner = self.inner.read().expect("RwLock poisoned").clone();
Box::pin(async move { inner.nip44_decrypt_async(public_key, payload).await })
}
}
#[derive(Debug, Clone)]
pub struct CoopAuthUrlHandler;
impl AuthUrlHandler for CoopAuthUrlHandler {
#[allow(mismatched_lifetime_syntaxes)]
fn on_auth_url(&self, auth_url: Url) -> BoxedFuture<Result<(), nostr_connect::error::Error>> {
Box::pin(async move {
webbrowser::open(auth_url.as_str()).unwrap();
Ok(())
})
}
}