refactor auth
Some checks failed
Rust / build (ubuntu-latest, stable) (push) Failing after 1m48s

This commit is contained in:
2026-02-13 18:31:29 +07:00
parent 7e4d42b967
commit 911b841918
2 changed files with 95 additions and 142 deletions

View File

@@ -63,14 +63,11 @@ impl Global for GlobalRelayAuth {}
// Relay authentication
#[derive(Debug)]
pub struct RelayAuth {
/// Entity for managing auth requests
requests: HashSet<Arc<AuthRequest>>,
/// Tasks for asynchronous operations
tasks: SmallVec<[Task<()>; 2]>,
/// Event subscriptions
_subscriptions: SmallVec<[Subscription; 1]>,
/// Tasks for asynchronous operations
_tasks: SmallVec<[Task<()>; 1]>,
}
impl RelayAuth {
@@ -87,50 +84,27 @@ impl RelayAuth {
/// Create a new relay auth instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
// Get the current entity
let entity = cx.entity();
// Channel for communication between nostr and gpui
let (tx, rx) = flume::bounded::<AuthRequest>(100);
let (tx, rx) = flume::bounded::<Arc<AuthRequest>>(100);
let mut subscriptions = smallvec![];
let mut tasks = smallvec![];
subscriptions.push(
// Observe the current state
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.iter() {
let trusted_relay = settings.read(cx).trusted_relay(req.url(), cx);
if trusted_relay && mode == AuthMode::Auto {
// Automatically authenticate if the relay is authenticated before
this.response(req, window, cx);
} else {
// Otherwise open the auth request popup
this.ask_for_approval(req, window, cx);
}
cx.observe(&nostr, move |this, state, cx| {
if state.read(cx).connected() {
this.handle_notifications(tx.clone(), cx)
}
}),
);
tasks.push(
// Handle nostr notifications
cx.background_spawn(async move {
Self::handle_notifications(&client, &tx).await;
}),
);
tasks.push(
// Update GPUI states
cx.spawn(async move |this, cx| {
while let Ok(request) = rx.recv_async().await {
this.update(cx, |this, cx| {
this.add_request(request, cx);
cx.spawn_in(window, async move |this, cx| {
while let Ok(req) = rx.recv_async().await {
this.update_in(cx, |this, window, cx| {
this.handle_auth(&req, window, cx);
})
.ok();
}
@@ -138,66 +112,72 @@ impl RelayAuth {
);
Self {
requests: HashSet::new(),
tasks,
_subscriptions: subscriptions,
_tasks: tasks,
}
}
// 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();
fn handle_notifications(
&mut self,
tx: flume::Sender<Arc<AuthRequest>>,
cx: &mut Context<Self>,
) {
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
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;
let task = cx.background_spawn(async move {
let mut notifications = client.notifications();
let mut challenges: HashSet<Cow<'_, str>> = HashSet::default();
// 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)
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(Arc::new(request)).await.ok();
}
}
RelayMessage::Ok {
event_id, message, ..
} => {
let msg = MachineReadablePrefix::parse(&message);
let mut tracker = tracker().write().await;
// 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,
_ => {}
}
ClientNotification::Shutdown => break,
_ => {}
}
}
});
self.tasks.push(task);
}
/// Add a new authentication request.
fn add_request(&mut self, request: AuthRequest, cx: &mut Context<Self>) {
self.requests.insert(Arc::new(request));
cx.notify();
}
fn handle_auth(&mut self, req: &Arc<AuthRequest>, window: &mut Window, cx: &mut Context<Self>) {
let settings = AppSettings::global(cx);
let trusted_relay = settings.read(cx).trusted_relay(req.url(), cx);
let mode = AppSettings::get_auth_mode(cx);
/// Get the number of pending requests.
pub fn pending_requests(&self, _cx: &App) -> usize {
self.requests.len()
}
/// 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.iter() {
self.ask_for_approval(request, window, cx);
if trusted_relay && mode == AuthMode::Auto {
// Automatically authenticate if the relay is authenticated before
self.response(req, window, cx);
} else {
// Otherwise open the auth request popup
self.ask_for_approval(req, window, cx);
}
}
@@ -268,20 +248,17 @@ impl RelayAuth {
let result = task.await;
let url = req.url();
this.update_in(cx, |this, window, cx| {
this.update_in(cx, |_this, window, cx| {
window.clear_notification(challenge, cx);
match result {
Ok(_) => {
window.clear_notification(challenge, cx);
window.push_notification(format!("{} has been authenticated", 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();
window.push_notification(format!("{} has been authenticated", url), cx);
}
Err(e) => {
window.push_notification(Notification::error(e.to_string()), cx);