Continue redesign for the v1 stable release (#5)
Some checks failed
Rust / build (ubuntu-latest, stable) (push) Failing after 1m32s

Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
2026-02-12 08:32:17 +00:00
parent 32201554ec
commit ecd7f6aa9b
43 changed files with 2794 additions and 3409 deletions

View File

@@ -3,8 +3,9 @@ use std::cell::Cell;
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use std::sync::Arc;
use anyhow::{anyhow, Error};
use anyhow::{anyhow, Context as AnyhowContext, Error};
use gpui::{
App, AppContext, Context, Entity, Global, IntoElement, ParentElement, SharedString, Styled,
Subscription, Task, Window,
@@ -28,8 +29,8 @@ pub fn init(window: &mut Window, cx: &mut App) {
/// Authentication request
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct AuthRequest {
pub url: RelayUrl,
pub challenge: String,
url: RelayUrl,
challenge: String,
}
impl Hash for AuthRequest {
@@ -45,6 +46,14 @@ impl AuthRequest {
url,
}
}
pub fn url(&self) -> &RelayUrl {
&self.url
}
pub fn challenge(&self) -> &str {
&self.challenge
}
}
struct GlobalRelayAuth(Entity<RelayAuth>);
@@ -55,7 +64,7 @@ impl Global for GlobalRelayAuth {}
#[derive(Debug)]
pub struct RelayAuth {
/// Entity for managing auth requests
requests: HashSet<AuthRequest>,
requests: HashSet<Arc<AuthRequest>>,
/// Event subscriptions
_subscriptions: SmallVec<[Subscription; 1]>,
@@ -91,14 +100,14 @@ impl RelayAuth {
subscriptions.push(
// Observe the current state
cx.observe_in(&entity, window, |this, _, window, cx| {
cx.observe_in(&entity, window, |this, _state, window, cx| {
let settings = AppSettings::global(cx);
let mode = AppSettings::get_auth_mode(cx);
for req in this.requests.clone().into_iter() {
let is_trusted_relay = settings.read(cx).is_trusted_relay(&req.url, cx);
for req in this.requests.iter() {
let trusted_relay = settings.read(cx).trusted_relay(req.url(), cx);
if is_trusted_relay && mode == AuthMode::Auto {
if trusted_relay && mode == AuthMode::Auto {
// Automatically authenticate if the relay is authenticated before
this.response(req, window, cx);
} else {
@@ -111,7 +120,9 @@ impl RelayAuth {
tasks.push(
// Handle nostr notifications
cx.background_spawn(async move { Self::handle_notifications(&client, &tx).await }),
cx.background_spawn(async move {
Self::handle_notifications(&client, &tx).await;
}),
);
tasks.push(
@@ -136,25 +147,45 @@ impl RelayAuth {
// Handle nostr notifications
async fn handle_notifications(client: &Client, tx: &flume::Sender<AuthRequest>) {
let mut notifications = client.notifications();
let mut challenges: HashSet<Cow<'_, str>> = HashSet::default();
while let Ok(notification) = notifications.recv().await {
if let RelayPoolNotification::Message {
message: RelayMessage::Auth { challenge },
relay_url,
} = notification
{
let request = AuthRequest::new(challenge, relay_url);
while let Some(notification) = notifications.next().await {
match notification {
ClientNotification::Message { relay_url, message } => {
match message {
RelayMessage::Auth { challenge } => {
if challenges.insert(challenge.clone()) {
let request = AuthRequest::new(challenge, relay_url);
tx.send_async(request).await.ok();
}
}
RelayMessage::Ok {
event_id, message, ..
} => {
let msg = MachineReadablePrefix::parse(&message);
let mut tracker = tracker().write().await;
if let Err(e) = tx.send_async(request).await {
log::error!("Failed to send auth request: {}", e);
// Handle authentication messages
if let Some(MachineReadablePrefix::AuthRequired) = msg {
// Keep track of events that need to be resent after authentication
tracker.add_to_pending(event_id, relay_url);
} else {
// Keep track of events sent by Coop
tracker.sent(event_id)
}
}
_ => {}
}
}
ClientNotification::Shutdown => break,
_ => {}
}
}
}
/// Add a new authentication request.
fn add_request(&mut self, request: AuthRequest, cx: &mut Context<Self>) {
self.requests.insert(request);
self.requests.insert(Arc::new(request));
cx.notify();
}
@@ -165,57 +196,55 @@ impl RelayAuth {
/// Reask for approval for all pending requests.
pub fn re_ask(&mut self, window: &mut Window, cx: &mut Context<Self>) {
for request in self.requests.clone().into_iter() {
for request in self.requests.iter() {
self.ask_for_approval(request, window, cx);
}
}
/// Respond to an authentication request.
fn response(&mut self, req: AuthRequest, window: &mut Window, cx: &mut Context<Self>) {
fn response(&self, req: &Arc<AuthRequest>, window: &Window, cx: &Context<Self>) {
let settings = AppSettings::global(cx);
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let challenge = req.challenge.to_owned();
let url = req.url.to_owned();
let challenge_clone = challenge.clone();
let url_clone = url.clone();
let req = req.clone();
let challenge = req.challenge().to_string();
let async_req = req.clone();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = client.signer().await?;
// Construct event
let event: Event = EventBuilder::auth(challenge_clone, url_clone.clone())
.sign(&signer)
.await?;
let builder = EventBuilder::auth(async_req.challenge(), async_req.url().clone());
let event = client.sign_event_builder(builder).await?;
// Get the event ID
let id = event.id;
// Get the relay
let relay = client.pool().relay(url_clone).await?;
let relay_url = relay.url();
let relay = client
.relay(async_req.url())
.await?
.context("Relay not found")?;
// Subscribe to notifications
let mut notifications = relay.notifications();
// Send the AUTH message
relay.send_msg(ClientMessage::Auth(Cow::Borrowed(&event)))?;
relay
.send_msg(ClientMessage::Auth(Cow::Borrowed(&event)))
.await?;
while let Ok(notification) = notifications.recv().await {
while let Some(notification) = notifications.next().await {
match notification {
RelayNotification::Message {
message: RelayMessage::Ok { event_id, .. },
} => {
if id == event_id {
// Re-subscribe to previous subscription
relay.resubscribe().await?;
// relay.resubscribe().await?;
// Get all pending events that need to be resent
let mut tracker = tracker().write().await;
let ids: Vec<EventId> = tracker.pending_resend(relay_url);
let ids: Vec<EventId> = tracker.pending_resend(relay.url());
for id in ids.into_iter() {
if let Some(event) = client.database().event_by_id(&id).await? {
@@ -228,7 +257,6 @@ impl RelayAuth {
}
}
RelayNotification::AuthenticationFailed => break,
RelayNotification::Shutdown => break,
_ => {}
}
}
@@ -236,47 +264,56 @@ impl RelayAuth {
Err(anyhow!("Authentication failed"))
});
self._tasks.push(
// Handle response in the background
cx.spawn_in(window, async move |this, cx| {
match task.await {
cx.spawn_in(window, async move |this, cx| {
let result = task.await;
let url = req.url();
this.update_in(cx, |this, window, cx| {
match result {
Ok(_) => {
this.update_in(cx, |this, window, cx| {
// Clear the current notification
window.clear_notification(challenge, cx);
window.clear_notification(challenge, cx);
window.push_notification(format!("{} has been authenticated", url), cx);
// Push a new notification
window.push_notification(format!("{url} has been authenticated"), cx);
// Save the authenticated relay to automatically authenticate future requests
settings.update(cx, |this, cx| {
this.add_trusted_relay(url, cx);
});
// Save the authenticated relay to automatically authenticate future requests
settings.update(cx, |this, cx| {
this.add_trusted_relay(url, cx);
});
// Remove the challenge from the list of pending authentications
this.requests.remove(&req);
cx.notify();
})
.expect("Entity has been released");
// Remove the challenge from the list of pending authentications
this.requests.remove(&req);
cx.notify();
}
Err(e) => {
this.update_in(cx, |_, window, cx| {
window.push_notification(Notification::error(e.to_string()), cx);
})
.expect("Entity has been released");
window.push_notification(Notification::error(e.to_string()), cx);
}
};
}),
);
}
})
.ok();
})
.detach();
}
/// Push a popup to approve the authentication request.
fn ask_for_approval(&mut self, req: AuthRequest, window: &mut Window, cx: &mut Context<Self>) {
let url = SharedString::from(req.url.clone().to_string());
fn ask_for_approval(&self, req: &Arc<AuthRequest>, window: &Window, cx: &Context<Self>) {
let notification = self.notification(req, cx);
cx.spawn_in(window, async move |_this, cx| {
cx.update(|window, cx| {
window.push_notification(notification, cx);
})
.ok();
})
.detach();
}
/// Build a notification for the authentication request.
fn notification(&self, req: &Arc<AuthRequest>, cx: &Context<Self>) -> Notification {
let req = req.clone();
let url = SharedString::from(req.url().to_string());
let entity = cx.entity().downgrade();
let loading = Rc::new(Cell::new(false));
let note = Notification::new()
Notification::new()
.custom_id(SharedString::from(&req.challenge))
.autohide(false)
.icon(IconName::Info)
@@ -299,7 +336,7 @@ impl RelayAuth {
.into_any_element()
})
.action(move |_window, _cx| {
let entity = entity.clone();
let view = entity.clone();
let req = req.clone();
Button::new("approve")
@@ -310,24 +347,18 @@ impl RelayAuth {
.disabled(loading.get())
.on_click({
let loading = Rc::clone(&loading);
move |_ev, window, cx| {
// Set loading state to true
loading.set(true);
// Process to approve the request
entity
.update(cx, |this, cx| {
this.response(req.clone(), window, cx);
})
.ok();
view.update(cx, |this, cx| {
this.response(&req, window, cx);
})
.ok();
}
})
});
// Push the notification to the current window
window.push_notification(note, cx);
// Bring the window to the front
cx.activate(true);
})
}
}