4 Commits

Author SHA1 Message Date
Ren Amamiya
6fef2ae1c6 chore: release version 1.0.0-beta3 2026-04-06 06:53:05 +07:00
Ren Amamiya
c2a723faa8 chore: prepare mobile(android/ios) target 2026-04-04 09:32:41 +07:00
reya
6b872527ad chore: simplify codebase and prepare for multi-platforms (#28)
Reviewed-on: #28
2026-04-04 02:22:08 +00:00
Ren Amamiya
d9b16aea9a feat: add tracking for which signer encrypted the message (#27)
Reviewed-on: #27
Co-authored-by: Ren Amamiya <reya@lume.nu>
Co-committed-by: Ren Amamiya <reya@lume.nu>
2026-04-01 02:53:49 +00:00
26 changed files with 1257 additions and 1055 deletions

895
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@ members = ["crates/*"]
default-members = ["crates/coop"] default-members = ["crates/coop"]
[workspace.package] [workspace.package]
version = "1.0.0-beta2" version = "1.0.0-beta3"
edition = "2024" edition = "2024"
publish = false publish = false
@@ -15,13 +15,11 @@ gpui_platform = { git = "https://github.com/zed-industries/zed", features = ["fo
gpui_linux = { git = "https://github.com/zed-industries/zed" } gpui_linux = { git = "https://github.com/zed-industries/zed" }
gpui_windows = { git = "https://github.com/zed-industries/zed" } gpui_windows = { git = "https://github.com/zed-industries/zed" }
gpui_macos = { git = "https://github.com/zed-industries/zed" } gpui_macos = { git = "https://github.com/zed-industries/zed" }
gpui_web = { git = "https://github.com/zed-industries/zed" }
gpui_tokio = { git = "https://github.com/zed-industries/zed" } gpui_tokio = { git = "https://github.com/zed-industries/zed" }
reqwest_client = { git = "https://github.com/zed-industries/zed" } reqwest_client = { git = "https://github.com/zed-industries/zed" }
# Nostr # Nostr
nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" } nostr-lmdb = { git = "https://github.com/rust-nostr/nostr" }
nostr-memory = { git = "https://github.com/rust-nostr/nostr" }
nostr-connect = { git = "https://github.com/rust-nostr/nostr" } nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
nostr-blossom = { git = "https://github.com/rust-nostr/nostr" } nostr-blossom = { git = "https://github.com/rust-nostr/nostr" }
nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" } nostr-gossip-memory = { git = "https://github.com/rust-nostr/nostr" }
@@ -44,6 +42,7 @@ smallvec = "1.14.0"
smol = "2" smol = "2"
tracing = "0.1.40" tracing = "0.1.40"
webbrowser = "1.0.4" webbrowser = "1.0.4"
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
[profile.release] [profile.release]
strip = true strip = true

View File

@@ -6,7 +6,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration; use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error, anyhow}; use anyhow::{Context as AnyhowContext, Error, anyhow};
use common::EventUtils; use common::EventExt;
use device::{DeviceEvent, DeviceRegistry};
use fuzzy_matcher::FuzzyMatcher; use fuzzy_matcher::FuzzyMatcher;
use fuzzy_matcher::skim::SkimMatcherV2; use fuzzy_matcher::skim::SkimMatcherV2;
use gpui::{ use gpui::{
@@ -41,8 +42,6 @@ pub enum ChatEvent {
CloseRoom(u64), CloseRoom(u64),
/// An event to notify UI about a new chat request /// An event to notify UI about a new chat request
Ping, Ping,
/// An event to notify UI that the chat registry has subscribed to messaging relays
Subscribed,
/// An error occurred /// An error occurred
Error(SharedString), Error(SharedString),
} }
@@ -75,9 +74,15 @@ impl Signal {
} }
} }
type Dekey = bool;
type GiftWrapId = EventId;
/// Chat Registry /// Chat Registry
#[derive(Debug)] #[derive(Debug)]
pub struct ChatRegistry { pub struct ChatRegistry {
/// Whether the chat registry is currently initializing.
pub initializing: bool,
/// Chat rooms /// Chat rooms
rooms: Vec<Entity<Room>>, rooms: Vec<Entity<Room>>,
@@ -88,7 +93,7 @@ pub struct ChatRegistry {
seens: Arc<RwLock<HashMap<EventId, HashSet<RelayUrl>>>>, seens: Arc<RwLock<HashMap<EventId, HashSet<RelayUrl>>>>,
/// Mapping of unwrapped event ids to their gift wrap event ids /// Mapping of unwrapped event ids to their gift wrap event ids
event_map: Arc<RwLock<HashMap<EventId, EventId>>>, event_map: Arc<RwLock<HashMap<EventId, (GiftWrapId, Dekey)>>>,
/// Tracking the status of unwrapping gift wrap events. /// Tracking the status of unwrapping gift wrap events.
tracking_flag: Arc<AtomicBool>, tracking_flag: Arc<AtomicBool>,
@@ -103,7 +108,7 @@ pub struct ChatRegistry {
tasks: SmallVec<[Task<Result<(), Error>>; 2]>, tasks: SmallVec<[Task<Result<(), Error>>; 2]>,
/// Subscriptions /// Subscriptions
_subscriptions: SmallVec<[Subscription; 1]>, _subscriptions: SmallVec<[Subscription; 2]>,
} }
impl EventEmitter<ChatEvent> for ChatRegistry {} impl EventEmitter<ChatEvent> for ChatRegistry {}
@@ -122,22 +127,48 @@ impl ChatRegistry {
/// Create a new chat registry instance /// Create a new chat registry instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let device = DeviceRegistry::global(cx);
let (tx, rx) = flume::unbounded::<Signal>(); let (tx, rx) = flume::unbounded::<Signal>();
let mut subscriptions = smallvec![]; let mut subscriptions = smallvec![];
subscriptions.push( subscriptions.push(
// Subscribe to the signer event // Subscribe to the signer event
cx.subscribe(&nostr, |this, _state, event, cx| { cx.subscribe_in(&nostr, window, |this, state, event, window, cx| {
match event { if event == &StateEvent::SignerSet {
StateEvent::SignerSet => { this.reset(cx);
this.reset(cx); this.get_contact_list(cx);
this.get_rooms(cx); this.get_rooms(cx);
}
StateEvent::RelayConnected => { let signer = state.read(cx).signer();
this.get_contact_list(cx); cx.spawn_in(window, async move |this, cx| {
this.get_messages(cx) let user_signer = signer.get().await;
} this.update(cx, |this, cx| {
_ => {} this.get_messages(user_signer, cx);
})
.ok();
})
.detach();
};
}),
);
subscriptions.push(
// Subscribe to the device event
cx.subscribe_in(&device, window, |_this, _s, event, window, cx| {
if event == &DeviceEvent::Set {
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
cx.spawn_in(window, async move |this, cx| {
if let Some(device_signer) = signer.get_encryption_signer().await {
this.update(cx, |this, cx| {
this.get_messages(device_signer, cx);
})
.ok();
}
})
.detach();
}; };
}), }),
); );
@@ -150,6 +181,7 @@ impl ChatRegistry {
}); });
Self { Self {
initializing: true,
rooms: vec![], rooms: vec![],
trashes: cx.new(|_| BTreeSet::default()), trashes: cx.new(|_| BTreeSet::default()),
seens: Arc::new(RwLock::new(HashMap::default())), seens: Arc::new(RwLock::new(HashMap::default())),
@@ -191,7 +223,10 @@ impl ChatRegistry {
}; };
match *message { match *message {
RelayMessage::Event { event, .. } => { RelayMessage::Event {
event,
subscription_id,
} => {
// Keep track of which relays have seen this event // Keep track of which relays have seen this event
{ {
let mut seens = seens.write().await; let mut seens = seens.write().await;
@@ -214,7 +249,8 @@ impl ChatRegistry {
// Map the rumor id to the gift wrap event id for later lookup // Map the rumor id to the gift wrap event id for later lookup
{ {
let mut event_map = event_map.write().await; let mut event_map = event_map.write().await;
event_map.insert(rumor.id.unwrap(), event.id); let dekey = subscription_id.as_ref() == &sub_id1;
event_map.insert(rumor.id.unwrap(), (event.id, dekey));
} }
// Check if the rumor has a recipient // Check if the rumor has a recipient
@@ -222,8 +258,6 @@ impl ChatRegistry {
let signal = let signal =
Signal::error(event.as_ref(), "Recipient is missing"); Signal::error(event.as_ref(), "Recipient is missing");
tx.send_async(signal).await?; tx.send_async(signal).await?;
continue;
} }
// Check if the rumor was created after the chat was initialized (for detecting new messages) // Check if the rumor was created after the chat was initialized (for detecting new messages)
@@ -231,6 +265,7 @@ impl ChatRegistry {
let signal = Signal::message(event.id, rumor); let signal = Signal::message(event.id, rumor);
tx.send_async(signal).await?; tx.send_async(signal).await?;
} else { } else {
// Mark the chat still processing new messages
status.store(true, Ordering::Release); status.store(true, Ordering::Release);
} }
} }
@@ -300,7 +335,7 @@ impl ChatRegistry {
} }
/// Get contact list from relays /// Get contact list from relays
pub fn get_contact_list(&mut self, cx: &mut Context<Self>) { fn get_contact_list(&mut self, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
@@ -330,15 +365,18 @@ impl ChatRegistry {
self.tasks.push(task); self.tasks.push(task);
} }
/// Get all messages for current user /// Get all messages for the provided signer
pub fn get_messages(&mut self, cx: &mut Context<Self>) { fn get_messages<T>(&mut self, signer: T, cx: &mut Context<Self>)
let task = self.subscribe(cx); where
T: NostrSigner + 'static,
{
let task = self.subscribe_gift_wrap_events(signer, cx);
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(_) => { Ok(_) => {
this.update(cx, |_this, cx| { this.update(cx, |this, cx| {
cx.emit(ChatEvent::Subscribed); this.set_initializing(false, cx);
})?; })?;
} }
Err(e) => { Err(e) => {
@@ -359,6 +397,7 @@ impl ChatRegistry {
cx.background_spawn(async move { cx.background_spawn(async move {
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
let id = SubscriptionId::new("inbox-relay");
// Construct filter for inbox relays // Construct filter for inbox relays
let filter = Filter::new() let filter = Filter::new()
@@ -369,12 +408,12 @@ impl ChatRegistry {
// Stream events from user's write relays // Stream events from user's write relays
let mut stream = client let mut stream = client
.stream_events(filter) .stream_events(filter)
.with_id(id)
.timeout(Duration::from_secs(TIMEOUT)) .timeout(Duration::from_secs(TIMEOUT))
.await?; .await?;
while let Some((_url, res)) = stream.next().await { while let Some((_url, res)) = stream.next().await {
if let Ok(event) = res { if let Ok(event) = res {
log::debug!("Got event: {:?}", event);
let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect(); let urls: Vec<RelayUrl> = nip17::extract_owned_relay_list(event).collect();
return Ok(urls); return Ok(urls);
} }
@@ -384,18 +423,20 @@ impl ChatRegistry {
}) })
} }
/// Continuously get gift wrap events for the current user in their messaging relays /// Continuously get gift wrap events for the signer
fn subscribe(&self, cx: &App) -> Task<Result<(), Error>> { fn subscribe_gift_wrap_events<T>(&self, signer: T, cx: &App) -> Task<Result<(), Error>>
where
T: NostrSigner + 'static,
{
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client(); let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let urls = self.get_messaging_relays(cx); let urls = self.get_messaging_relays(cx);
cx.background_spawn(async move { cx.background_spawn(async move {
let urls = urls.await?; let urls = urls.await?;
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key); let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let id = SubscriptionId::new(USER_GIFTWRAP); let id = SubscriptionId::new(format!("{}-msg", public_key.to_hex()));
// Ensure relay connections // Ensure relay connections
for url in urls.iter() { for url in urls.iter() {
@@ -419,6 +460,37 @@ impl ChatRegistry {
}) })
} }
/// Refresh the chat registry, fetching messages and contact list from relays.
pub fn refresh(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reset(cx);
self.get_contact_list(cx);
self.get_rooms(cx);
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
cx.spawn_in(window, async move |this, cx| {
let user_signer = signer.get().await;
let device_signer = signer.get_encryption_signer().await;
this.update(cx, |this, cx| {
this.get_messages(user_signer, cx);
if let Some(device_signer) = device_signer {
this.get_messages(device_signer, cx);
}
})
.ok();
})
.detach();
}
/// Set the initializing status of the chat registry
fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
self.initializing = initializing;
cx.notify();
}
/// Get the loading status of the chat registry /// Get the loading status of the chat registry
pub fn loading(&self) -> bool { pub fn loading(&self) -> bool {
self.tracking_flag.load(Ordering::Acquire) self.tracking_flag.load(Ordering::Acquire)
@@ -473,7 +545,7 @@ impl ChatRegistry {
self.event_map self.event_map
.read_blocking() .read_blocking()
.get(id) .get(id)
.map(|id| self.seen_on(id)) .map(|(id, _dekey)| self.seen_on(id))
} }
/// Get the relays that have seen a given gift wrap id. /// Get the relays that have seen a given gift wrap id.
@@ -485,6 +557,15 @@ impl ChatRegistry {
.unwrap_or_default() .unwrap_or_default()
} }
/// Check if a given rumor was encrypted by the dekey.
pub fn encrypted_by_dekey(&self, id: &EventId) -> bool {
self.event_map
.read_blocking()
.get(id)
.map(|(_, dekey)| *dekey)
.unwrap_or(false)
}
/// Add a new room to the start of list. /// Add a new room to the start of list.
pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>) pub fn add_room<I>(&mut self, room: I, cx: &mut Context<Self>)
where where
@@ -562,7 +643,12 @@ impl ChatRegistry {
/// Reset the registry. /// Reset the registry.
pub fn reset(&mut self, cx: &mut Context<Self>) { pub fn reset(&mut self, cx: &mut Context<Self>) {
self.initializing = true;
self.rooms.clear(); self.rooms.clear();
self.trashes.update(cx, |this, cx| {
this.clear();
cx.notify();
});
cx.notify(); cx.notify();
} }

View File

@@ -1,7 +1,7 @@
use std::hash::Hash; use std::hash::Hash;
use std::ops::Range; use std::ops::Range;
use common::{EventUtils, NostrParser}; use common::{EventExt, NostrParser};
use gpui::SharedString; use gpui::SharedString;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;

View File

@@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher};
use std::time::Duration; use std::time::Duration;
use anyhow::{Error, anyhow}; use anyhow::{Error, anyhow};
use common::EventUtils; use common::EventExt;
use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task}; use gpui::{App, AppContext, Context, EventEmitter, SharedString, Task};
use itertools::Itertools; use itertools::Itertools;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;

View File

@@ -4,7 +4,7 @@ use std::sync::Arc;
pub use actions::*; pub use actions::*;
use anyhow::{Context as AnyhowContext, Error}; use anyhow::{Context as AnyhowContext, Error};
use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus}; use chat::{ChatRegistry, Message, RenderedMessage, Room, RoomEvent, SendReport, SendStatus};
use common::RenderedTimestamp; use common::TimestampExt;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, AnyElement, App, AppContext, ClipboardItem, Context, Entity, EventEmitter, FocusHandle,
@@ -471,6 +471,12 @@ impl ChatPanel {
self.reports_by_id.read(cx).get(id).is_some() self.reports_by_id.read(cx).get(id).is_some()
} }
/// Check if a message was encrypted by the dekey
fn encrypted_by_dekey(&self, id: &EventId, cx: &App) -> bool {
let chat = ChatRegistry::global(cx);
chat.read(cx).encrypted_by_dekey(id)
}
/// Get all sent reports for a message by its ID /// Get all sent reports for a message by its ID
fn sent_reports(&self, id: &EventId, cx: &App) -> Option<Vec<SendReport>> { fn sent_reports(&self, id: &EventId, cx: &App) -> Option<Vec<SendReport>> {
self.reports_by_id.read(cx).get(id).cloned() self.reports_by_id.read(cx).get(id).cloned()
@@ -843,6 +849,7 @@ impl ChatPanel {
let replies = message.replies_to.as_slice(); let replies = message.replies_to.as_slice();
let has_replies = !replies.is_empty(); let has_replies = !replies.is_empty();
let has_reports = self.has_reports(&id, cx); let has_reports = self.has_reports(&id, cx);
let encrypted_by_dekey = self.encrypted_by_dekey(&id, cx);
// Hide avatar setting // Hide avatar setting
let hide_avatar = AppSettings::get_hide_avatar(cx); let hide_avatar = AppSettings::get_hide_avatar(cx);
@@ -888,6 +895,17 @@ impl ChatPanel {
.text_color(cx.theme().text) .text_color(cx.theme().text)
.child(author.name()), .child(author.name()),
) )
.when(encrypted_by_dekey, |this| {
this.child(
Button::new(format!("dekey-{ix}"))
.icon(IconName::Shield)
.ghost()
.xsmall()
.px_4()
.tooltip("Encrypted by Dekey")
.disabled(true),
)
})
.child(message.created_at.to_human_time()) .child(message.created_at.to_human_time())
.when(has_reports, |this| { .when(has_reports, |this| {
this.child(deferred(self.render_sent_reports(&id, cx))) this.child(deferred(self.render_sent_reports(&id, cx)))

View File

@@ -1,11 +1,10 @@
use std::sync::Arc; use std::sync::Arc;
use anyhow::{Error, anyhow};
use chrono::{Local, TimeZone}; use chrono::{Local, TimeZone};
use gpui::{Image, ImageFormat, SharedString}; use gpui::{Image, ImageFormat, SharedString};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use qrcode::render::svg;
use qrcode::QrCode; use qrcode::QrCode;
use qrcode::render::svg;
const NOW: &str = "now"; const NOW: &str = "now";
const SECONDS_IN_MINUTE: i64 = 60; const SECONDS_IN_MINUTE: i64 = 60;
@@ -13,12 +12,12 @@ const MINUTES_IN_HOUR: i64 = 60;
const HOURS_IN_DAY: i64 = 24; const HOURS_IN_DAY: i64 = 24;
const DAYS_IN_MONTH: i64 = 30; const DAYS_IN_MONTH: i64 = 30;
pub trait RenderedTimestamp { pub trait TimestampExt {
fn to_human_time(&self) -> SharedString; fn to_human_time(&self) -> SharedString;
fn to_ago(&self) -> SharedString; fn to_ago(&self) -> SharedString;
} }
impl RenderedTimestamp for Timestamp { impl TimestampExt for Timestamp {
fn to_human_time(&self) -> SharedString { fn to_human_time(&self) -> SharedString {
let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) { let input_time = match Local.timestamp_opt(self.as_secs() as i64, 0) {
chrono::LocalResult::Single(time) => time, chrono::LocalResult::Single(time) => time,
@@ -61,23 +60,11 @@ impl RenderedTimestamp for Timestamp {
} }
} }
pub trait TextUtils { pub trait StringExt {
fn to_public_key(&self) -> Result<PublicKey, Error>;
fn to_qr(&self) -> Option<Arc<Image>>; fn to_qr(&self) -> Option<Arc<Image>>;
} }
impl<T: AsRef<str>> TextUtils for T { impl<T: AsRef<str>> StringExt for T {
fn to_public_key(&self) -> Result<PublicKey, Error> {
let s = self.as_ref();
if s.starts_with("nprofile1") {
Ok(Nip19Profile::from_bech32(s)?.public_key)
} else if s.starts_with("npub1") {
Ok(PublicKey::parse(s)?)
} else {
Err(anyhow!("Invalid public key"))
}
}
fn to_qr(&self) -> Option<Arc<Image>> { fn to_qr(&self) -> Option<Arc<Image>> {
let s = self.as_ref(); let s = self.as_ref();
let code = QrCode::new(s).unwrap(); let code = QrCode::new(s).unwrap();

View File

@@ -3,12 +3,12 @@ use std::hash::{DefaultHasher, Hash, Hasher};
use itertools::Itertools; use itertools::Itertools;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
pub trait EventUtils { pub trait EventExt {
fn uniq_id(&self) -> u64; fn uniq_id(&self) -> u64;
fn extract_public_keys(&self) -> Vec<PublicKey>; fn extract_public_keys(&self) -> Vec<PublicKey>;
} }
impl EventUtils for Event { impl EventExt for Event {
fn uniq_id(&self) -> u64 { fn uniq_id(&self) -> u64 {
let mut hasher = DefaultHasher::new(); let mut hasher = DefaultHasher::new();
let mut pubkeys: Vec<PublicKey> = self.extract_public_keys(); let mut pubkeys: Vec<PublicKey> = self.extract_public_keys();
@@ -25,7 +25,7 @@ impl EventUtils for Event {
} }
} }
impl EventUtils for UnsignedEvent { impl EventExt for UnsignedEvent {
fn uniq_id(&self) -> u64 { fn uniq_id(&self) -> u64 {
let mut hasher = DefaultHasher::new(); let mut hasher = DefaultHasher::new();
let mut pubkeys: Vec<PublicKey> = vec![]; let mut pubkeys: Vec<PublicKey> = vec![];

View File

@@ -14,7 +14,7 @@ product-name = "Coop"
description = "Chat Freely, Stay Private on Nostr" description = "Chat Freely, Stay Private on Nostr"
identifier = "su.reya.coop" identifier = "su.reya.coop"
category = "SocialNetworking" category = "SocialNetworking"
version = "1.0.0-beta2" version = "1.0.0-beta3"
out-dir = "../../dist" out-dir = "../../dist"
before-packaging-command = "cargo build --release" before-packaging-command = "cargo build --release"
resources = ["Cargo.toml", "src"] resources = ["Cargo.toml", "src"]
@@ -62,9 +62,9 @@ smol.workspace = true
futures.workspace = true futures.workspace = true
oneshot.workspace = true oneshot.workspace = true
webbrowser.workspace = true webbrowser.workspace = true
tracing-subscriber.workspace = true
indexset = "0.12.3" indexset = "0.12.3"
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
[target.'cfg(target_os = "macos")'.dependencies] [target.'cfg(target_os = "macos")'.dependencies]
# Temporary workaround https://github.com/zed-industries/zed/issues/47168 # Temporary workaround https://github.com/zed-industries/zed/issues/47168

View File

@@ -91,7 +91,7 @@ impl AccountSelector {
fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) { fn login(&mut self, public_key: PublicKey, window: &mut Window, cx: &mut Context<Self>) {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let task = nostr.read(cx).get_signer(&public_key, cx); let task = nostr.read(cx).get_secret(public_key, cx);
// Mark the public key as being logged in // Mark the public key as being logged in
self.set_logging_in(public_key, cx); self.set_logging_in(public_key, cx);
@@ -117,7 +117,7 @@ impl AccountSelector {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
nostr.update(cx, |this, cx| { nostr.update(cx, |this, cx| {
this.remove_signer(&public_key, cx); this.remove_secret(&public_key, cx);
}); });
} }

View File

@@ -1,7 +1,7 @@
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use common::TextUtils; use common::StringExt;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled, AppContext, Context, Entity, Image, IntoElement, ParentElement, Render, SharedString, Styled,

View File

@@ -2,21 +2,21 @@ use std::collections::HashMap;
use std::time::Duration; use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error}; use anyhow::{Context as AnyhowContext, Error};
use common::RenderedTimestamp; use common::TimestampExt;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{
div, px, relative, uniform_list, App, AppContext, Context, Div, Entity, InteractiveElement, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, ParentElement, Render,
IntoElement, ParentElement, Render, SharedString, Styled, Subscription, Task, Window, SharedString, Styled, Subscription, Task, Window, div, px, relative, uniform_list,
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::{shorten_pubkey, Person, PersonRegistry}; use person::{Person, PersonRegistry, shorten_pubkey};
use smallvec::{smallvec, SmallVec}; use smallvec::{SmallVec, smallvec};
use state::{NostrAddress, NostrRegistry, BOOTSTRAP_RELAYS, TIMEOUT}; use state::{BOOTSTRAP_RELAYS, NostrAddress, NostrRegistry, TIMEOUT};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants}; use ui::button::{Button, ButtonVariants};
use ui::indicator::Indicator; use ui::indicator::Indicator;
use ui::{h_flex, v_flex, Icon, IconName, Sizable, StyledExt, WindowExtension}; use ui::{Icon, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> { pub fn init(public_key: PublicKey, window: &mut Window, cx: &mut App) -> Entity<Screening> {
cx.new(|cx| Screening::new(public_key, window, cx)) cx.new(|cx| Screening::new(public_key, window, cx))

View File

@@ -92,14 +92,14 @@ fn main() {
// Initialize relay auth registry // Initialize relay auth registry
relay_auth::init(window, cx); relay_auth::init(window, cx);
// Initialize app registry
chat::init(window, cx);
// Initialize device signer // Initialize device signer
// //
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md // NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
device::init(window, cx); device::init(window, cx);
// Initialize app registry
chat::init(window, cx);
// Initialize auto update // Initialize auto update
auto_update::init(window, cx); auto_update::init(window, cx);

View File

@@ -4,7 +4,7 @@ use std::time::Duration;
use anyhow::{Context as AnyhowContext, Error}; use anyhow::{Context as AnyhowContext, Error};
use chat::{ChatEvent, ChatRegistry, Room, RoomKind}; use chat::{ChatEvent, ChatRegistry, Room, RoomKind};
use common::{DebouncedDelay, RenderedTimestamp}; use common::{DebouncedDelay, TimestampExt};
use entry::RoomEntry; use entry::RoomEntry;
use gpui::prelude::FluentBuilder; use gpui::prelude::FluentBuilder;
use gpui::{ use gpui::{

View File

@@ -1,5 +1,3 @@
use std::cell::Cell;
use std::rc::Rc;
use std::sync::Arc; use std::sync::Arc;
use ::settings::AppSettings; use ::settings::AppSettings;
@@ -13,7 +11,7 @@ use gpui::{
relative, relative,
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::{PersonRegistry, shorten_pubkey};
use serde::Deserialize; use serde::Deserialize;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use state::{NostrRegistry, StateEvent}; use state::{NostrRegistry, StateEvent};
@@ -24,7 +22,7 @@ use ui::button::{Button, ButtonVariants};
use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView}; use ui::dock::{ClosePanel, DockArea, DockItem, DockPlacement, PanelView};
use ui::menu::{DropdownMenu, PopupMenuItem}; use ui::menu::{DropdownMenu, PopupMenuItem};
use ui::notification::{Notification, NotificationKind}; use ui::notification::{Notification, NotificationKind};
use ui::{Disableable, Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex}; use ui::{Icon, IconName, Root, Sizable, WindowExtension, h_flex, v_flex};
use crate::dialogs::restore::RestoreEncryption; use crate::dialogs::restore::RestoreEncryption;
use crate::dialogs::{accounts, settings}; use crate::dialogs::{accounts, settings};
@@ -51,7 +49,6 @@ enum Command {
ToggleTheme, ToggleTheme,
ToggleAccount, ToggleAccount,
RefreshRelayList,
RefreshMessagingRelays, RefreshMessagingRelays,
BackupEncryption, BackupEncryption,
ImportEncryption, ImportEncryption,
@@ -73,14 +70,8 @@ pub struct Workspace {
/// App's Dock Area /// App's Dock Area
dock: Entity<DockArea>, dock: Entity<DockArea>,
/// Whether a user's relay list is connected
relay_connected: bool,
/// Whether the inbox is connected
inbox_connected: bool,
/// Event subscriptions /// Event subscriptions
_subscriptions: SmallVec<[Subscription; 6]>, _subscriptions: SmallVec<[Subscription; 5]>,
} }
impl Workspace { impl Workspace {
@@ -88,7 +79,6 @@ impl Workspace {
let chat = ChatRegistry::global(cx); let chat = ChatRegistry::global(cx);
let device = DeviceRegistry::global(cx); let device = DeviceRegistry::global(cx);
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let npubs = nostr.read(cx).npubs();
let titlebar = cx.new(|_| TitleBar::new()); let titlebar = cx.new(|_| TitleBar::new());
let dock = cx.new(|cx| DockArea::new(window, cx)); let dock = cx.new(|cx| DockArea::new(window, cx));
@@ -102,15 +92,6 @@ impl Workspace {
}), }),
); );
subscriptions.push(
// Observe the npubs entity
cx.observe_in(&npubs, window, move |this, npubs, window, cx| {
if !npubs.read(cx).is_empty() {
this.account_selector(window, cx);
}
}),
);
subscriptions.push( subscriptions.push(
// Subscribe to the signer events // Subscribe to the signer events
cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| { cx.subscribe_in(&nostr, window, move |this, _state, event, window, cx| {
@@ -141,28 +122,14 @@ impl Workspace {
window.push_notification(note, cx); window.push_notification(note, cx);
} }
StateEvent::FetchingRelayList => {
let note = Notification::new()
.id::<RelayNotifcation>()
.message("Getting relay list...")
.with_kind(NotificationKind::Info);
window.push_notification(note, cx);
}
StateEvent::RelayNotConfigured => {
this.relay_warning(window, cx);
}
StateEvent::RelayConnected => {
window.clear_notification::<RelayNotifcation>(cx);
this.set_relay_connected(true, cx);
}
StateEvent::SignerSet => { StateEvent::SignerSet => {
this.set_center_layout(window, cx); this.set_center_layout(window, cx);
this.set_relay_connected(false, cx);
this.set_inbox_connected(false, cx);
// Clear the signer notification // Clear the signer notification
window.clear_notification::<SignerNotifcation>(cx); window.clear_notification::<SignerNotifcation>(cx);
} }
StateEvent::Show => {
this.account_selector(window, cx);
}
_ => {} _ => {}
}; };
}), }),
@@ -174,10 +141,11 @@ impl Workspace {
match event { match event {
DeviceEvent::Requesting => { DeviceEvent::Requesting => {
const MSG: &str = const MSG: &str =
"Please open the other client and approve the encryption key request"; "Coop has sent a request for an encryption key. Please open the other client then approve the request.";
let note = Notification::new() let note = Notification::new()
.id::<DeviceNotifcation>() .id::<DeviceNotifcation>()
.autohide(false)
.title("Wait for approval") .title("Wait for approval")
.message(MSG) .message(MSG)
.with_kind(NotificationKind::Info); .with_kind(NotificationKind::Info);
@@ -187,6 +155,7 @@ impl Workspace {
DeviceEvent::Creating => { DeviceEvent::Creating => {
let note = Notification::new() let note = Notification::new()
.id::<DeviceNotifcation>() .id::<DeviceNotifcation>()
.autohide(false)
.message("Creating encryption key") .message("Creating encryption key")
.with_kind(NotificationKind::Info); .with_kind(NotificationKind::Info);
@@ -200,26 +169,6 @@ impl Workspace {
window.push_notification(note, cx); window.push_notification(note, cx);
} }
DeviceEvent::NotSet { reason } => {
let note = Notification::new()
.id::<DeviceNotifcation>()
.title("Cannot setup the encryption key")
.message(reason)
.autohide(false)
.with_kind(NotificationKind::Error);
window.push_notification(note, cx);
}
DeviceEvent::NotSubscribe { reason } => {
let note = Notification::new()
.id::<DeviceNotifcation>()
.title("Cannot getting messages")
.message(reason)
.autohide(false)
.with_kind(NotificationKind::Error);
window.push_notification(note, cx);
}
DeviceEvent::Error(error) => { DeviceEvent::Error(error) => {
window.push_notification(Notification::error(error).autohide(false), cx); window.push_notification(Notification::error(error).autohide(false), cx);
} }
@@ -255,9 +204,6 @@ impl Workspace {
}); });
}); });
} }
ChatEvent::Subscribed => {
this.set_inbox_connected(true, cx);
}
ChatEvent::Error(error) => { ChatEvent::Error(error) => {
window.push_notification(Notification::error(error).autohide(false), cx); window.push_notification(Notification::error(error).autohide(false), cx);
} }
@@ -285,8 +231,6 @@ impl Workspace {
Self { Self {
titlebar, titlebar,
dock, dock,
relay_connected: false,
inbox_connected: false,
_subscriptions: subscriptions, _subscriptions: subscriptions,
} }
} }
@@ -318,18 +262,6 @@ impl Workspace {
.collect() .collect()
} }
/// Set whether the relay list is connected
fn set_relay_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
self.relay_connected = connected;
cx.notify();
}
/// Set whether the inbox is connected
fn set_inbox_connected(&mut self, connected: bool, cx: &mut Context<Self>) {
self.inbox_connected = connected;
cx.notify();
}
/// Set the dock layout /// Set the dock layout
fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn set_layout(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let left = DockItem::panel(Arc::new(sidebar::init(window, cx))); let left = DockItem::panel(Arc::new(sidebar::init(window, cx)));
@@ -414,8 +346,9 @@ impl Workspace {
} }
Command::RefreshMessagingRelays => { Command::RefreshMessagingRelays => {
let chat = ChatRegistry::global(cx); let chat = ChatRegistry::global(cx);
// Trigger a refresh of the chat registry
chat.update(cx, |this, cx| { chat.update(cx, |this, cx| {
this.get_messages(cx); this.refresh(window, cx);
}); });
} }
Command::ShowRelayList => { Command::ShowRelayList => {
@@ -428,16 +361,6 @@ impl Workspace {
); );
}); });
} }
Command::RefreshRelayList => {
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
if let Some(public_key) = signer.public_key() {
nostr.update(cx, |this, cx| {
this.ensure_relay_list(&public_key, cx);
});
}
}
Command::RefreshEncryption => { Command::RefreshEncryption => {
let device = DeviceRegistry::global(cx); let device = DeviceRegistry::global(cx);
device.update(cx, |this, cx| { device.update(cx, |this, cx| {
@@ -630,55 +553,6 @@ impl Workspace {
}); });
} }
fn relay_warning(&mut self, window: &mut Window, cx: &mut Context<Self>) {
const BODY: &str = "Coop cannot found your gossip relay list. \
Maybe you haven't set it yet or relay not responsed";
let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer();
let Some(public_key) = signer.public_key() else {
return;
};
let entity = nostr.downgrade();
let loading = Rc::new(Cell::new(false));
let note = Notification::new()
.autohide(false)
.id::<RelayNotifcation>()
.icon(IconName::Relay)
.title("Gossip Relays are required")
.message(BODY)
.action(move |_this, _window, _cx| {
let entity = entity.clone();
let public_key = public_key.to_owned();
Button::new("retry")
.label("Retry")
.small()
.primary()
.loading(loading.get())
.disabled(loading.get())
.on_click({
let loading = Rc::clone(&loading);
move |_ev, _window, cx| {
// Set loading state to true
loading.set(true);
// Retry
entity
.update(cx, |this, cx| {
this.ensure_relay_list(&public_key, cx);
})
.ok();
}
})
});
window.push_notification(note, cx);
}
fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement { fn titlebar_left(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
@@ -759,19 +633,24 @@ impl Workspace {
} }
fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement { fn titlebar_right(&mut self, cx: &mut Context<Self>) -> impl IntoElement {
let relay_connected = self.relay_connected; let chat = ChatRegistry::global(cx);
let inbox_connected = self.inbox_connected; let initializing = chat.read(cx).initializing;
let trash_messages = chat.read(cx).count_trash_messages(cx);
let device = DeviceRegistry::global(cx);
let device_initializing = device.read(cx).initializing;
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
let signer = nostr.read(cx).signer(); let signer = nostr.read(cx).signer();
let trashes = ChatRegistry::global(cx);
let trash_messages = trashes.read(cx).count_trash_messages(cx);
let Some(public_key) = signer.public_key() else { let Some(public_key) = signer.public_key() else {
return div(); return div();
}; };
let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&public_key, cx);
let announcement = profile.announcement();
h_flex() h_flex()
.when(!cx.theme().platform.is_mac(), |this| this.pr_2()) .when(!cx.theme().platform.is_mac(), |this| this.pr_2())
.gap_2() .gap_2()
@@ -813,53 +692,42 @@ impl Workspace {
.tooltip("Decoupled encryption key") .tooltip("Decoupled encryption key")
.small() .small()
.ghost() .ghost()
.dropdown_menu(move |this, _window, cx| { .loading(device_initializing)
let device = DeviceRegistry::global(cx); .when(device_initializing, |this| {
let subscribing = device.read(cx).subscribing; this.label("Dekey")
let requesting = device.read(cx).requesting; .xsmall()
.tooltip("Loading decoupled encryption key...")
})
.dropdown_menu(move |this, _window, _cx| {
this.min_w(px(260.)) this.min_w(px(260.))
.label("Encryption Key") .label("Encryption Key")
.when(requesting, |this| { .when_some(announcement.as_ref(), |this, announcement| {
let name = announcement.client_name();
let pkey = shorten_pubkey(announcement.public_key(), 8);
this.item(PopupMenuItem::element(move |_window, cx| { this.item(PopupMenuItem::element(move |_window, cx| {
h_flex() h_flex()
.px_1() .gap_1()
.w_full()
.gap_2()
.text_sm() .text_sm()
.child( .child(
div() Icon::new(IconName::Device)
.size_1p5() .small()
.rounded_full() .text_color(cx.theme().icon_muted),
.bg(cx.theme().icon_accent),
) )
.child(SharedString::from("Waiting for approval...")) .child(name.clone())
}))
.item(PopupMenuItem::element(move |_window, cx| {
h_flex()
.gap_1()
.text_sm()
.child(
Icon::new(IconName::UserKey)
.small()
.text_color(cx.theme().icon_muted),
)
.child(SharedString::from(pkey.clone()))
})) }))
}) })
.item(PopupMenuItem::element(move |_window, cx| {
h_flex()
.px_1()
.w_full()
.gap_2()
.text_sm()
.when(!subscribing, |this| {
this.text_color(cx.theme().text_muted)
})
.child(div().size_1p5().rounded_full().map(|this| {
if subscribing {
this.bg(cx.theme().icon_accent)
} else {
this.bg(cx.theme().icon_muted)
}
}))
.map(|this| {
if subscribing {
this.child("Listening for messages")
} else {
this.child("Idle")
}
})
}))
.separator() .separator()
.menu_with_icon( .menu_with_icon(
"Backup", "Backup",
@@ -889,17 +757,13 @@ impl Workspace {
.icon(IconName::Inbox) .icon(IconName::Inbox)
.small() .small()
.ghost() .ghost()
.loading(!inbox_connected) .loading(initializing)
.disabled(!inbox_connected) .when(initializing, |this| {
.when(!inbox_connected, |this| { this.label("Inbox")
this.tooltip("Connecting to the user's messaging relays...") .xsmall()
.tooltip("Getting inbox messages...")
}) })
.when(inbox_connected, |this| this.indicator())
.dropdown_menu(move |this, _window, cx| { .dropdown_menu(move |this, _window, cx| {
let chat = ChatRegistry::global(cx);
let persons = PersonRegistry::global(cx);
let profile = persons.read(cx).get(&public_key, cx);
let urls: Vec<(SharedString, SharedString)> = profile let urls: Vec<(SharedString, SharedString)> = profile
.messaging_relays() .messaging_relays()
.iter() .iter()
@@ -950,38 +814,17 @@ impl Workspace {
Box::new(Command::RefreshMessagingRelays), Box::new(Command::RefreshMessagingRelays),
) )
.menu_with_icon( .menu_with_icon(
"Update relays", "Manage gossip relays",
IconName::Relay,
Box::new(Command::ShowRelayList),
)
.menu_with_icon(
"Manage messaging relays",
IconName::Settings, IconName::Settings,
Box::new(Command::ShowMessaging), Box::new(Command::ShowMessaging),
) )
}), }),
) )
.child(
Button::new("relay-list")
.icon(IconName::Relay)
.small()
.ghost()
.loading(!relay_connected)
.disabled(!relay_connected)
.when(!relay_connected, |this| {
this.tooltip("Connecting to the user's relay list...")
})
.when(relay_connected, |this| this.indicator())
.dropdown_menu(move |this, _window, _cx| {
this.label("User's Relay List")
.separator()
.menu_with_icon(
"Reload",
IconName::Refresh,
Box::new(Command::RefreshRelayList),
)
.menu_with_icon(
"Update",
IconName::Settings,
Box::new(Command::ShowRelayList),
)
}),
)
} }
} }

View File

@@ -0,0 +1,36 @@
[package]
name = "coop_mobile"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
assets = { path = "../assets" }
ui = { path = "../ui" }
theme = { path = "../theme" }
common = { path = "../common" }
state = { path = "../state" }
device = { path = "../device" }
chat = { path = "../chat" }
settings = { path = "../settings" }
person = { path = "../person" }
relay_auth = { path = "../relay_auth" }
gpui.workspace = true
gpui_platform.workspace = true
gpui_tokio.workspace = true
gpui-mobile = { git = "https://github.com/itsbalamurali/gpui-mobile" }
nostr-connect.workspace = true
nostr-sdk.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
itertools.workspace = true
log.workspace = true
smallvec.workspace = true
smol.workspace = true
futures.workspace = true
oneshot.workspace = true
tracing-subscriber.workspace = true

View File

View File

@@ -12,15 +12,14 @@ common = { path = "../common" }
state = { path = "../state" } state = { path = "../state" }
device = { path = "../device" } device = { path = "../device" }
chat = { path = "../chat" } chat = { path = "../chat" }
chat_ui = { path = "../chat_ui" }
settings = { path = "../settings" } settings = { path = "../settings" }
person = { path = "../person" } person = { path = "../person" }
relay_auth = { path = "../relay_auth" } relay_auth = { path = "../relay_auth" }
gpui.workspace = true gpui.workspace = true
gpui_web.workspace = true
gpui_platform.workspace = true gpui_platform.workspace = true
gpui_tokio.workspace = true gpui_tokio.workspace = true
gpui_web = { git = "https://github.com/zed-industries/zed" }
nostr-connect.workspace = true nostr-connect.workspace = true
nostr-sdk.workspace = true nostr-sdk.workspace = true
@@ -35,8 +34,8 @@ smol.workspace = true
futures.workspace = true futures.workspace = true
oneshot.workspace = true oneshot.workspace = true
webbrowser.workspace = true webbrowser.workspace = true
tracing-subscriber.workspace = true
tracing-subscriber = { version = "0.3.18", features = ["fmt", "env-filter"] }
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
tracing-wasm = "0.2" tracing-wasm = "0.2"
console_log = "1.0" console_log = "1.0"

View File

@@ -1,5 +1,5 @@
use std::cell::Cell; use std::cell::Cell;
use std::collections::{HashMap, HashSet}; use std::collections::HashSet;
use std::path::PathBuf; use std::path::PathBuf;
use std::rc::Rc; use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
@@ -11,12 +11,12 @@ use gpui::{
}; };
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use person::PersonRegistry; use person::PersonRegistry;
use state::{Announcement, DEVICE_GIFTWRAP, NostrRegistry, StateEvent, TIMEOUT, app_name}; use state::{Announcement, NostrRegistry, StateEvent, TIMEOUT, app_name};
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::avatar::Avatar; use ui::avatar::Avatar;
use ui::button::{Button, ButtonVariants}; use ui::button::Button;
use ui::notification::Notification; use ui::notification::{Notification, NotificationKind};
use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, h_flex, v_flex}; use ui::{Disableable, Sizable, StyledExt, WindowExtension, h_flex, v_flex};
const IDENTIFIER: &str = "coop:device"; const IDENTIFIER: &str = "coop:device";
const MSG: &str = "You've requested an encryption key from another device. \ const MSG: &str = "You've requested an encryption key from another device. \
@@ -39,10 +39,6 @@ pub enum DeviceEvent {
Requesting, Requesting,
/// The device is creating a new encryption key /// The device is creating a new encryption key
Creating, Creating,
/// Encryption key is not set
NotSet { reason: SharedString },
/// An event to notify that Coop isn't subscribed to gift wrap events
NotSubscribe { reason: SharedString },
/// An error occurred /// An error occurred
Error(SharedString), Error(SharedString),
} }
@@ -54,24 +50,6 @@ impl DeviceEvent {
{ {
Self::Error(error.into()) Self::Error(error.into())
} }
pub fn not_subscribe<T>(reason: T) -> Self
where
T: Into<SharedString>,
{
Self::NotSubscribe {
reason: reason.into(),
}
}
pub fn not_set<T>(reason: T) -> Self
where
T: Into<SharedString>,
{
Self::NotSet {
reason: reason.into(),
}
}
} }
/// Device Registry /// Device Registry
@@ -79,14 +57,11 @@ impl DeviceEvent {
/// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md /// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
#[derive(Debug)] #[derive(Debug)]
pub struct DeviceRegistry { pub struct DeviceRegistry {
/// Whether the registry is currently subscribing to gift wrap events /// Whether the registry is currently initializing
pub subscribing: bool, pub initializing: bool,
/// Whether the registry is waiting for encryption key approval from other devices
pub requesting: bool,
/// Whether there is a pending request for encryption key approval /// Whether there is a pending request for encryption key approval
pub has_pending_request: bool, pub pending_request: bool,
/// Async tasks /// Async tasks
tasks: Vec<Task<Result<(), Error>>>, tasks: Vec<Task<Result<(), Error>>>,
@@ -112,17 +87,11 @@ impl DeviceRegistry {
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
// Get announcement when signer is set // Subscribe to nostr state events
let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| { let subscription = cx.subscribe_in(&nostr, window, |this, _e, event, _window, cx| {
match event { if event == &StateEvent::SignerSet {
StateEvent::SignerSet => { this.set_initializing(true, cx);
this.set_subscribing(false, cx); this.get_announcement(cx);
this.set_requesting(false, cx);
}
StateEvent::RelayConnected => {
this.get_announcement(cx);
}
_ => {}
}; };
}); });
@@ -131,9 +100,8 @@ impl DeviceRegistry {
}); });
Self { Self {
subscribing: false, initializing: true,
requesting: false, pending_request: false,
has_pending_request: false,
tasks: vec![], tasks: vec![],
_subscription: Some(subscription), _subscription: Some(subscription),
} }
@@ -198,21 +166,15 @@ impl DeviceRegistry {
})); }));
} }
/// Set whether the registry is currently subscribing to gift wrap events /// Set whether the registry is currently initializing
fn set_subscribing(&mut self, subscribing: bool, cx: &mut Context<Self>) { fn set_initializing(&mut self, initializing: bool, cx: &mut Context<Self>) {
self.subscribing = subscribing; self.initializing = initializing;
cx.notify();
}
/// Set whether the registry is waiting for encryption key approval from other devices
fn set_requesting(&mut self, requesting: bool, cx: &mut Context<Self>) {
self.requesting = requesting;
cx.notify(); cx.notify();
} }
/// Set whether there is a pending request for encryption key approval /// Set whether there is a pending request for encryption key approval
fn set_has_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) { fn set_pending_request(&mut self, pending: bool, cx: &mut Context<Self>) {
self.has_pending_request = pending; self.pending_request = pending;
cx.notify(); cx.notify();
} }
@@ -229,76 +191,14 @@ impl DeviceRegistry {
// Update state // Update state
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_initializing(false, cx);
cx.emit(DeviceEvent::Set); cx.emit(DeviceEvent::Set);
this.get_messages(cx);
})?; })?;
Ok(()) Ok(())
})); }));
} }
/// Get all messages for encryption keys
fn get_messages(&mut self, cx: &mut Context<Self>) {
let task = self.subscribe_to_giftwrap_events(cx);
self.tasks.push(cx.spawn(async move |this, cx| {
if let Err(e) = task.await {
this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::not_subscribe(e.to_string()));
})?;
} else {
this.update(cx, |this, cx| {
this.set_subscribing(true, cx);
})?;
}
Ok(())
}));
}
/// Continuously get gift wrap events for the current user in their messaging relays
fn subscribe_to_giftwrap_events(&self, cx: &App) -> Task<Result<(), Error>> {
let persons = PersonRegistry::global(cx);
let nostr = NostrRegistry::global(cx);
let client = nostr.read(cx).client();
let signer = nostr.read(cx).signer();
let Some(user) = signer.public_key() else {
return Task::ready(Err(anyhow!("User not found")));
};
let profile = persons.read(cx).get(&user, cx);
let relays = profile.messaging_relays().clone();
cx.background_spawn(async move {
let encryption = signer.get_encryption_signer().await.context("not found")?;
let public_key = encryption.get_public_key().await?;
let filter = Filter::new().kind(Kind::GiftWrap).pubkey(public_key);
let id = SubscriptionId::new(DEVICE_GIFTWRAP);
// Ensure user has relays configured
if relays.is_empty() {
return Err(anyhow!("No messaging relays found"));
}
// Ensure relays are connected
for url in relays.iter() {
client.add_relay(url).and_connect().await?;
}
// Construct target for subscription
let target: HashMap<RelayUrl, Filter> = relays
.into_iter()
.map(|relay| (relay, filter.clone()))
.collect();
// Subscribe
client.subscribe(target).with_id(id).await?;
Ok(())
})
}
/// Backup the encryption's secret key to a file /// Backup the encryption's secret key to a file
pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> { pub fn backup(&self, path: PathBuf, cx: &App) -> Task<Result<(), Error>> {
let nostr = NostrRegistry::global(cx); let nostr = NostrRegistry::global(cx);
@@ -431,30 +331,27 @@ impl DeviceRegistry {
// Get encryption key from the database and compare with the announcement // Get encryption key from the database and compare with the announcement
let task: Task<Result<Keys, Error>> = cx.background_spawn(async move { let task: Task<Result<Keys, Error>> = cx.background_spawn(async move {
if let Ok(keys) = get_keys(&client).await { let keys = get_keys(&client).await?;
if keys.public_key() != device_pubkey {
return Err(anyhow!("Encryption Key doesn't match the announcement")); // Compare the public key from the announcement with the one from the database
}; if keys.public_key() != device_pubkey {
Ok(keys) return Err(anyhow!("Encryption Key doesn't match the announcement"));
} else { };
Err(anyhow!("Encryption Key not found. Please create a new key"))
} Ok(keys)
}); });
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { if let Ok(keys) = task.await {
Ok(keys) => { this.update(cx, |this, cx| {
this.update(cx, |this, cx| { this.set_signer(keys, cx);
this.set_signer(keys, cx); this.wait_for_request(cx);
this.wait_for_request(cx); })?;
})?; } else {
} this.update(cx, |this, cx| {
Err(e) => { this.request(cx);
this.update(cx, |_this, cx| { })?;
cx.emit(DeviceEvent::not_set(e.to_string())); }
})?;
}
};
Ok(()) Ok(())
})); }));
} }
@@ -467,21 +364,16 @@ impl DeviceRegistry {
self.tasks.push(cx.background_spawn(async move { self.tasks.push(cx.background_spawn(async move {
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
let id = SubscriptionId::new("dekey-requests");
// Construct a filter for encryption key requests // Construct a filter for encryption key requests
let now = Filter::new() let filter = Filter::new()
.kind(Kind::Custom(4454)) .kind(Kind::Custom(4454))
.author(public_key) .author(public_key)
.since(Timestamp::now()); .since(Timestamp::now());
// Construct a filter for the last encryption key request
let last = Filter::new()
.kind(Kind::Custom(4454))
.author(public_key)
.limit(1);
// Subscribe to the device key requests on user's write relays // Subscribe to the device key requests on user's write relays
client.subscribe(vec![now, last]).await?; client.subscribe(vec![filter]).with_id(id).await?;
Ok(()) Ok(())
})); }));
@@ -537,7 +429,7 @@ impl DeviceRegistry {
} }
Ok(None) => { Ok(None) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_requesting(true, cx); this.set_initializing(false, cx);
this.wait_for_approval(cx); this.wait_for_approval(cx);
cx.emit(DeviceEvent::Requesting); cx.emit(DeviceEvent::Requesting);
@@ -602,12 +494,11 @@ impl DeviceRegistry {
Ok(keys) => { Ok(keys) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.set_signer(keys, cx);
this.set_requesting(false, cx);
})?; })?;
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(DeviceEvent::not_set(e.to_string())); cx.emit(DeviceEvent::error(e.to_string()));
})?; })?;
} }
} }
@@ -683,10 +574,10 @@ impl DeviceRegistry {
/// Handle encryption request /// Handle encryption request
fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) { fn ask_for_approval(&mut self, event: Event, window: &mut Window, cx: &mut Context<Self>) {
// Ignore if there is already a pending request // Ignore if there is already a pending request
if self.has_pending_request { if self.pending_request {
return; return;
} }
self.set_has_pending_request(true, cx); self.set_pending_request(true, cx);
// Show notification // Show notification
let notification = self.notification(event, cx); let notification = self.notification(event, cx);
@@ -706,8 +597,8 @@ impl DeviceRegistry {
Notification::new() Notification::new()
.type_id::<DeviceNotification>(key) .type_id::<DeviceNotification>(key)
.autohide(false) .autohide(false)
.icon(IconName::UserKey) .with_kind(NotificationKind::Info)
.title(SharedString::from("New request")) .title("Encryption Key Request")
.content(move |_this, _window, cx| { .content(move |_this, _window, cx| {
v_flex() v_flex()
.gap_2() .gap_2()
@@ -730,7 +621,7 @@ impl DeviceRegistry {
.font_semibold() .font_semibold()
.text_xs() .text_xs()
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(SharedString::from("Requester:")), .child(SharedString::from("From:")),
) )
.child( .child(
div() div()
@@ -777,8 +668,6 @@ impl DeviceRegistry {
Button::new("approve") Button::new("approve")
.label("Approve") .label("Approve")
.small()
.primary()
.loading(loading.get()) .loading(loading.get())
.disabled(loading.get()) .disabled(loading.get())
.on_click({ .on_click({

View File

@@ -4,7 +4,7 @@ use std::rc::Rc;
use std::time::Duration; use std::time::Duration;
use anyhow::{Error, anyhow}; use anyhow::{Error, anyhow};
use common::EventUtils; use common::EventExt;
use gpui::{App, AppContext, Context, Entity, Global, Task, Window}; use gpui::{App, AppContext, Context, Entity, Global, Task, Window};
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};

View File

@@ -15,9 +15,9 @@ use settings::{AppSettings, AuthMode};
use smallvec::{SmallVec, smallvec}; use smallvec::{SmallVec, smallvec};
use state::NostrRegistry; use state::NostrRegistry;
use theme::ActiveTheme; use theme::ActiveTheme;
use ui::button::{Button, ButtonVariants}; use ui::button::Button;
use ui::notification::Notification; use ui::notification::{Notification, NotificationKind};
use ui::{Disableable, IconName, Sizable, StyledExt, WindowExtension, v_flex}; use ui::{Disableable, WindowExtension, v_flex};
const AUTH_MESSAGE: &str = const AUTH_MESSAGE: &str =
"Approve the authentication request to allow Coop to continue sending or receiving events."; "Approve the authentication request to allow Coop to continue sending or receiving events.";
@@ -327,8 +327,8 @@ impl RelayAuth {
Notification::new() Notification::new()
.type_id::<AuthNotification>(challenge) .type_id::<AuthNotification>(challenge)
.autohide(false) .autohide(false)
.icon(IconName::Warning) .with_kind(NotificationKind::Info)
.title(SharedString::from("Authentication Required")) .title("Authentication Required")
.content(move |_this, _window, cx| { .content(move |_this, _window, cx| {
v_flex() v_flex()
.gap_2() .gap_2()
@@ -344,7 +344,6 @@ impl RelayAuth {
.px_1p5() .px_1p5()
.rounded_sm() .rounded_sm()
.text_xs() .text_xs()
.font_semibold()
.bg(cx.theme().elevated_surface_background) .bg(cx.theme().elevated_surface_background)
.text_color(cx.theme().text) .text_color(cx.theme().text)
.child(url.clone()), .child(url.clone()),
@@ -357,8 +356,6 @@ impl RelayAuth {
Button::new("approve") Button::new("approve")
.label("Approve") .label("Approve")
.small()
.primary()
.loading(loading.get()) .loading(loading.get())
.disabled(loading.get()) .disabled(loading.get())
.on_click({ .on_click({

View File

@@ -10,7 +10,6 @@ common = { path = "../common" }
nostr.workspace = true nostr.workspace = true
nostr-sdk.workspace = true nostr-sdk.workspace = true
nostr-lmdb.workspace = true nostr-lmdb.workspace = true
nostr-memory.workspace = true
nostr-gossip-memory.workspace = true nostr-gossip-memory.workspace = true
nostr-connect.workspace = true nostr-connect.workspace = true
nostr-blossom.workspace = true nostr-blossom.workspace = true

View File

@@ -1,4 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -8,7 +9,6 @@ use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, SharedString,
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
use nostr_gossip_memory::prelude::*; use nostr_gossip_memory::prelude::*;
use nostr_lmdb::prelude::*; use nostr_lmdb::prelude::*;
use nostr_memory::prelude::*;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
mod blossom; mod blossom;
@@ -44,18 +44,14 @@ impl Global for GlobalNostrRegistry {}
/// Signer event. /// Signer event.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum StateEvent { pub enum StateEvent {
/// Creating the signer
Creating,
/// Connecting to the bootstrapping relay /// Connecting to the bootstrapping relay
Connecting, Connecting,
/// Connected to the bootstrapping relay /// Connected to the bootstrapping relay
Connected, Connected,
/// Fetching the relay list /// Creating the signer
FetchingRelayList, Creating,
/// User has not set up NIP-65 relays /// Show the identity dialog
RelayNotConfigured, Show,
/// Connected to NIP-65 relays
RelayConnected,
/// A new signer has been set /// A new signer has been set
SignerSet, SignerSet,
/// An error occurred /// An error occurred
@@ -80,16 +76,19 @@ pub struct NostrRegistry {
/// Nostr signer /// Nostr signer
signer: Arc<CoopSigner>, signer: Arc<CoopSigner>,
/// Local public keys /// All local stored identities
npubs: Entity<Vec<PublicKey>>, npubs: Entity<Vec<PublicKey>>,
/// App keys /// Keys directory
key_dir: PathBuf,
/// Master app keys used for various operations.
/// ///
/// Used for Nostr Connect and NIP-4e operations /// Example: Nostr Connect and NIP-4e operations
app_keys: Keys, app_keys: Keys,
/// Tasks for asynchronous operations /// Tasks for asynchronous operations
tasks: Vec<Task<()>>, tasks: Vec<Task<Result<(), Error>>>,
} }
impl EventEmitter<StateEvent> for NostrRegistry {} impl EventEmitter<StateEvent> for NostrRegistry {}
@@ -107,55 +106,57 @@ impl NostrRegistry {
/// Create a new nostr instance /// Create a new nostr instance
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let key_dir = config_dir().join("keys");
let app_keys = get_or_init_app_keys(cx).unwrap_or(Keys::generate());
// Construct the nostr signer // Construct the nostr signer
let app_keys = get_or_init_app_keys().unwrap_or(Keys::generate());
let signer = Arc::new(CoopSigner::new(app_keys.clone())); let signer = Arc::new(CoopSigner::new(app_keys.clone()));
// Construct the nostr npubs entity // Get all local stored npubs
let npubs = cx.new(|_| vec![]); let npubs = cx.new(|_| match Self::discover(&key_dir) {
Ok(npubs) => npubs,
Err(e) => {
log::error!("Failed to discover npubs: {e}");
vec![]
}
});
// Construct the nostr client builder // Construct the nostr lmdb instance
let mut builder = ClientBuilder::default() let lmdb = cx.foreground_executor().block_on(async move {
NostrLmdb::open(config_dir().join("nostr"))
.await
.expect("Failed to initialize database")
});
// Construct the nostr client
let client = ClientBuilder::default()
.signer(signer.clone()) .signer(signer.clone())
.database(lmdb)
.gossip(NostrGossipMemory::unbounded()) .gossip(NostrGossipMemory::unbounded())
.gossip_config(
GossipConfig::default()
.no_background_refresh()
.sync_idle_timeout(Duration::from_secs(TIMEOUT))
.sync_initial_timeout(Duration::from_millis(600)),
)
.automatic_authentication(false) .automatic_authentication(false)
.verify_subscriptions(false)
.connect_timeout(Duration::from_secs(10)) .connect_timeout(Duration::from_secs(10))
.sleep_when_idle(SleepWhenIdle::Enabled { .sleep_when_idle(SleepWhenIdle::Enabled {
timeout: Duration::from_secs(600), timeout: Duration::from_secs(600),
}); })
.build();
// Add database if not in debug mode
if !cfg!(debug_assertions) {
// Construct the nostr lmdb instance
let lmdb = cx.foreground_executor().block_on(async move {
NostrLmdb::open(config_dir().join("nostr"))
.await
.expect("Failed to initialize database")
});
builder = builder.database(lmdb);
} else {
builder = builder.database(MemoryDatabase::unbounded())
}
// Build the nostr client
let client = builder.build();
// Run at the end of current cycle // Run at the end of current cycle
cx.defer_in(window, |this, _window, cx| { cx.defer_in(window, |this, _window, cx| {
this.connect(cx); this.connect(cx);
// Create an identity if none exists
if this.npubs.read(cx).is_empty() {
this.create_identity(cx);
} else {
// Show the identity dialog
cx.emit(StateEvent::Show);
}
}); });
Self { Self {
client, client,
signer, signer,
npubs, npubs,
key_dir,
app_keys, app_keys,
tasks: vec![], tasks: vec![],
} }
@@ -181,6 +182,33 @@ impl NostrRegistry {
self.app_keys.clone() self.app_keys.clone()
} }
/// Discover all npubs in the keys directory
fn discover(dir: &PathBuf) -> Result<Vec<PublicKey>, Error> {
// Ensure keys directory exists
std::fs::create_dir_all(dir)?;
let files = std::fs::read_dir(dir)?;
let mut entries = Vec::new();
let mut npubs: Vec<PublicKey> = Vec::new();
for file in files.flatten() {
let metadata = file.metadata()?;
let modified_time = metadata.modified()?;
let name = file.file_name().into_string().unwrap().replace(".npub", "");
entries.push((modified_time, name));
}
// Sort by modification time (most recent first)
entries.sort_by(|a, b| b.0.cmp(&a.0));
for (_, name) in entries {
let public_key = PublicKey::parse(&name)?;
npubs.push(public_key);
}
Ok(npubs)
}
/// Connect to the bootstrapping relays /// Connect to the bootstrapping relays
fn connect(&mut self, cx: &mut Context<Self>) { fn connect(&mut self, cx: &mut Context<Self>) {
let client = self.client(); let client = self.client();
@@ -219,105 +247,143 @@ impl NostrRegistry {
// Emit connecting event // Emit connecting event
cx.emit(StateEvent::Connecting); cx.emit(StateEvent::Connecting);
self.tasks
.push(cx.spawn(async move |this, cx| match task.await {
Ok(_) => {
this.update(cx, |this, cx| {
cx.emit(StateEvent::Connected);
this.get_npubs(cx);
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
}));
}
/// Get all used npubs
fn get_npubs(&mut self, cx: &mut Context<Self>) {
let npubs = self.npubs.downgrade();
let task: Task<Result<Vec<PublicKey>, Error>> = cx.background_spawn(async move {
let dir = config_dir().join("keys");
// Ensure keys directory exists
smol::fs::create_dir_all(&dir).await?;
let mut files = smol::fs::read_dir(&dir).await?;
let mut entries = Vec::new();
while let Some(Ok(entry)) = files.next().await {
let metadata = entry.metadata().await?;
let modified_time = metadata.modified()?;
let name = entry
.file_name()
.into_string()
.unwrap()
.replace(".npub", "");
entries.push((modified_time, name));
}
// Sort by modification time (most recent first)
entries.sort_by(|a, b| b.0.cmp(&a.0));
let mut npubs = Vec::new();
for (_, name) in entries {
let public_key = PublicKey::parse(&name)?;
npubs.push(public_key);
}
Ok(npubs)
});
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { if let Err(e) = task.await {
Ok(public_keys) => match public_keys.is_empty() { this.update(cx, |_this, cx| {
true => { cx.emit(StateEvent::error(e.to_string()));
this.update(cx, |this, cx| { })?;
this.create_identity(cx); } else {
}) this.update(cx, |_this, cx| {
.ok(); cx.emit(StateEvent::Connected);
} })?;
false => {
// TODO: auto login
npubs
.update(cx, |this, cx| {
this.extend(public_keys);
cx.notify();
})
.ok();
}
},
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
} }
Ok(())
})); }));
} }
/// Get the secret for a given npub.
pub fn get_secret(
&self,
public_key: PublicKey,
cx: &App,
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
let npub = public_key.to_bech32().unwrap();
let key_path = self.key_dir.join(format!("{}.npub", npub));
let app_keys = self.app_keys.clone();
if let Ok(payload) = std::fs::read_to_string(key_path) {
if !payload.is_empty() {
cx.background_spawn(async move {
let decrypted = app_keys.nip44_decrypt(&public_key, &payload).await?;
let secret = SecretKey::parse(&decrypted)?;
let keys = Keys::new(secret);
Ok(keys.into_nostr_signer())
})
} else {
self.get_secret_keyring(&npub, cx)
}
} else {
self.get_secret_keyring(&npub, cx)
}
}
/// Get the secret for a given npub in the OS credentials store.
#[deprecated = "Use get_secret instead"]
fn get_secret_keyring(
&self,
user: &str,
cx: &App,
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
let read = cx.read_credentials(user);
let app_keys = self.app_keys.clone();
cx.background_spawn(async move {
let (_, secret) = read
.await
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
// Try to parse as a direct secret key first
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
return Ok(Keys::new(secret_key).into_nostr_signer());
}
// Convert the secret into string
let sec = String::from_utf8(secret)
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
// Try to parse as a NIP-46 URI
let uri =
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
// Set the auth URL handler
nip46.auth_url_handler(CoopAuthUrlHandler);
Ok(nip46.into_nostr_signer())
})
}
/// Add a new npub to the keys directory
fn write_secret(
&self,
public_key: PublicKey,
secret: String,
cx: &App,
) -> Task<Result<(), Error>> {
let npub = public_key.to_bech32().unwrap();
let key_path = self.key_dir.join(format!("{}.npub", npub));
let app_keys = self.app_keys.clone();
cx.background_spawn(async move {
// If the secret starts with "bunker://" (nostr connect), use it directly; otherwise, encrypt it
let content = if secret.starts_with("bunker://") {
secret
} else {
app_keys.nip44_encrypt(&public_key, &secret).await?
};
// Write the encrypted secret to the keys directory
smol::fs::write(key_path, &content).await?;
Ok(())
})
}
/// Remove a secret
pub fn remove_secret(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
let public_key = public_key.to_owned();
let npub = public_key.to_bech32().unwrap();
let keys_dir = config_dir().join("keys");
let key_path = keys_dir.join(format!("{}.npub", npub));
// Remove the secret file from the keys directory
std::fs::remove_file(key_path).ok();
self.npubs.update(cx, |this, cx| {
this.retain(|k| k != &public_key);
cx.notify();
});
}
/// Create a new identity /// Create a new identity
fn create_identity(&mut self, cx: &mut Context<Self>) { pub fn create_identity(&mut self, cx: &mut Context<Self>) {
let client = self.client(); let client = self.client();
let keys = Keys::generate(); let keys = Keys::generate();
let async_keys = keys.clone(); let async_keys = keys.clone();
let username = keys.public_key().to_bech32().unwrap();
let secret = keys.secret_key().to_secret_bytes();
// Create a write credential task
let write_credential = cx.write_credentials(&username, &username, &secret);
// Emit creating event // Emit creating event
cx.emit(StateEvent::Creating); cx.emit(StateEvent::Creating);
// Create the write secret task
let write_secret =
self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
// Run async tasks in background // Run async tasks in background
let task: Task<Result<(), Error>> = cx.background_spawn(async move { let task: Task<Result<(), Error>> = cx.background_spawn(async move {
let signer = async_keys.into_nostr_signer(); let signer = async_keys.into_nostr_signer();
@@ -362,14 +428,10 @@ impl NostrRegistry {
let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?; let event = EventBuilder::nip17_relay_list(relays).sign(&signer).await?;
// Publish messaging relay list event // Publish messaging relay list event
client client.send_event(&event).to_nip65().await?;
.send_event(&event)
.to_nip65()
.ack_policy(AckPolicy::none())
.await?;
// Write user's credentials to the system keyring // Write user's credentials to the system keyring
write_credential.await?; write_secret.await?;
Ok(()) Ok(())
}); });
@@ -379,58 +441,19 @@ impl NostrRegistry {
Ok(_) => { Ok(_) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.set_signer(keys, cx);
}) })?;
.ok();
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string())); cx.emit(StateEvent::error(e.to_string()));
}) })?;
.ok();
} }
}; };
Ok(())
})); }));
} }
/// Get the signer in keyring by username
pub fn get_signer(
&self,
public_key: &PublicKey,
cx: &App,
) -> Task<Result<Arc<dyn NostrSigner>, Error>> {
let username = public_key.to_bech32().unwrap();
let app_keys = self.app_keys.clone();
let read_credential = cx.read_credentials(&username);
cx.spawn(async move |_cx| {
let (_, secret) = read_credential
.await
.map_err(|_| anyhow!("Failed to get signer. Please re-import the secret key"))?
.ok_or_else(|| anyhow!("Failed to get signer. Please re-import the secret key"))?;
// Try to parse as a direct secret key first
if let Ok(secret_key) = SecretKey::from_slice(&secret) {
return Ok(Keys::new(secret_key).into_nostr_signer());
}
// Convert the secret into string
let sec = String::from_utf8(secret)
.map_err(|_| anyhow!("Failed to parse secret as UTF-8"))?;
// Try to parse as a NIP-46 URI
let uri =
NostrConnectUri::parse(&sec).map_err(|_| anyhow!("Failed to parse NIP-46 URI"))?;
let timeout = Duration::from_secs(NOSTR_CONNECT_TIMEOUT);
let mut nip46 = NostrConnect::new(uri, app_keys, timeout, None)?;
// Set the auth URL handler
nip46.auth_url_handler(CoopAuthUrlHandler);
Ok(nip46.into_nostr_signer())
})
}
/// Set the signer for the nostr client and verify the public key /// Set the signer for the nostr client and verify the public key
pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>) pub fn set_signer<T>(&mut self, new: T, cx: &mut Context<Self>)
where where
@@ -449,15 +472,6 @@ impl NostrRegistry {
let signer = client.signer().context("Signer not found")?; let signer = client.signer().context("Signer not found")?;
let public_key = signer.get_public_key().await?; let public_key = signer.get_public_key().await?;
let npub = public_key.to_bech32().unwrap();
let keys_dir = config_dir().join("keys");
// Ensure keys directory exists
smol::fs::create_dir_all(&keys_dir).await?;
let key_path = keys_dir.join(format!("{}.npub", npub));
smol::fs::write(key_path, "").await?;
log::info!("Signer's public key: {}", public_key); log::info!("Signer's public key: {}", public_key);
Ok(public_key) Ok(public_key)
}); });
@@ -465,9 +479,7 @@ impl NostrRegistry {
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok(public_key) => { Ok(public_key) => {
// Update states
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.ensure_relay_list(&public_key, cx);
// Add public key to npubs if not already present // Add public key to npubs if not already present
this.npubs.update(cx, |this, cx| { this.npubs.update(cx, |this, cx| {
if !this.contains(&public_key) { if !this.contains(&public_key) {
@@ -475,65 +487,43 @@ impl NostrRegistry {
cx.notify(); cx.notify();
} }
}); });
// Emit signer changed event // Emit signer changed event
cx.emit(StateEvent::SignerSet); cx.emit(StateEvent::SignerSet);
}) })?;
.ok();
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string())); cx.emit(StateEvent::error(e.to_string()));
}) })?;
.ok();
} }
}; };
}));
}
/// Remove a signer from the keyring Ok(())
pub fn remove_signer(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
let public_key = public_key.to_owned();
let npub = public_key.to_bech32().unwrap();
let keys_dir = config_dir().join("keys");
self.tasks.push(cx.spawn(async move |this, cx| {
let key_path = keys_dir.join(format!("{}.npub", npub));
smol::fs::remove_file(key_path).await.ok();
this.update(cx, |this, cx| {
this.npubs().update(cx, |this, cx| {
this.retain(|k| k != &public_key);
cx.notify();
});
})
.ok();
})); }));
} }
/// Add a key signer to keyring /// Add a key signer to keyring
pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) { pub fn add_key_signer(&mut self, keys: &Keys, cx: &mut Context<Self>) {
let keys = keys.clone(); let keys = keys.clone();
let username = keys.public_key().to_bech32().unwrap(); let write_secret =
let secret = keys.secret_key().to_secret_bytes(); self.write_secret(keys.public_key(), keys.secret_key().to_secret_hex(), cx);
// Write the credential to the keyring
let write_credential = cx.write_credentials(&username, "keys", &secret);
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match write_credential.await { match write_secret.await {
Ok(_) => { Ok(_) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(keys, cx); this.set_signer(keys, cx);
}) })?;
.ok();
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string())); cx.emit(StateEvent::error(e.to_string()));
}) })?;
.ok();
} }
}; };
Ok(())
})); }));
} }
@@ -554,154 +544,35 @@ impl NostrRegistry {
self.tasks.push(cx.spawn(async move |this, cx| { self.tasks.push(cx.spawn(async move |this, cx| {
match task.await { match task.await {
Ok((public_key, uri)) => { Ok((public_key, uri)) => {
let username = public_key.to_bech32().unwrap(); // Create the write secret task
let write_credential = this let write_secret = this.read_with(cx, |this, cx| {
.read_with(cx, |_this, cx| { this.write_secret(public_key, uri.to_string(), cx)
cx.write_credentials( })?;
&username,
"nostrconnect",
uri.to_string().as_bytes(),
)
})
.unwrap();
match write_credential.await { match write_secret.await {
Ok(_) => { Ok(_) => {
this.update(cx, |this, cx| { this.update(cx, |this, cx| {
this.set_signer(nip46, cx); this.set_signer(nip46, cx);
}) })?;
.ok();
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string())); cx.emit(StateEvent::error(e.to_string()));
}) })?;
.ok();
} }
} }
} }
Err(e) => { Err(e) => {
this.update(cx, |_this, cx| { this.update(cx, |_this, cx| {
cx.emit(StateEvent::error(e.to_string())); cx.emit(StateEvent::error(e.to_string()));
}) })?;
.ok();
} }
}; };
}));
}
/// Ensure the relay list is fetched for the given public key
pub fn ensure_relay_list(&mut self, public_key: &PublicKey, cx: &mut Context<Self>) {
let task = self.get_event(public_key, Kind::RelayList, cx);
// Emit a fetching event before starting the task
cx.emit(StateEvent::FetchingRelayList);
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(event) => {
this.update(cx, |this, cx| {
this.ensure_connection(&event, cx);
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
};
}));
}
/// Ensure that the user is connected to the relay specified in the NIP-65 event.
pub fn ensure_connection(&mut self, event: &Event, cx: &mut Context<Self>) {
let client = self.client();
// Extract the relay list from the event
let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = nip65::extract_relay_list(event)
.map(|(url, metadata)| (url.to_owned(), metadata.to_owned()))
.collect();
let task: Task<Result<(), Error>> = cx.background_spawn(async move {
for (url, metadata) in relays.into_iter() {
match metadata {
Some(RelayMetadata::Read) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::READ)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
Some(RelayMetadata::Write) => {
client
.add_relay(url)
.capabilities(RelayCapabilities::WRITE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
None => {
client
.add_relay(url)
.capabilities(RelayCapabilities::NONE)
.connect_timeout(Duration::from_secs(TIMEOUT))
.and_connect()
.await?;
}
}
}
Ok(()) Ok(())
});
self.tasks.push(cx.spawn(async move |this, cx| {
match task.await {
Ok(_) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayConnected);
})
.ok();
}
Err(e) => {
this.update(cx, |_this, cx| {
cx.emit(StateEvent::RelayNotConfigured);
cx.emit(StateEvent::error(e.to_string()));
})
.ok();
}
};
})); }));
} }
/// Get an event with the given author and kind.
pub fn get_event(
&self,
author: &PublicKey,
kind: Kind,
cx: &App,
) -> Task<Result<Event, Error>> {
let client = self.client();
let public_key = *author;
cx.background_spawn(async move {
let filter = Filter::new().kind(kind).author(public_key).limit(1);
let mut stream = client
.stream_events(filter)
.timeout(Duration::from_millis(800))
.await?;
while let Some((_url, res)) = stream.next().await {
if let Ok(event) = res {
return Ok(event);
}
}
Err(anyhow!("No event found"))
})
}
/// Get the public key of a NIP-05 address /// Get the public key of a NIP-05 address
pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> { pub fn get_address(&self, addr: Nip05Address, cx: &App) -> Task<Result<PublicKey, Error>> {
let client = self.client(); let client = self.client();
@@ -857,29 +728,33 @@ impl NostrRegistry {
} }
} }
/// Get or create a new app keys /// Get or create new app keys
fn get_or_init_app_keys() -> Result<Keys, Error> { fn get_or_init_app_keys(cx: &App) -> Result<Keys, Error> {
let dir = config_dir().join(".app_keys"); let read = cx.read_credentials(CLIENT_NAME);
let stored_keys: Option<Keys> = cx.foreground_executor().block_on(async move {
let content = match std::fs::read(&dir) { if let Ok(Some((_, secret))) = read.await {
Ok(content) => content, SecretKey::from_slice(&secret).map(Keys::new).ok()
Err(_) => { } else {
// Generate new keys if file doesn't exist None
let keys = Keys::generate();
let secret_key = keys.secret_key();
// Create directory and write secret key
std::fs::create_dir_all(dir.parent().unwrap())?;
std::fs::write(&dir, secret_key.to_secret_bytes())?;
return Ok(keys);
} }
}; });
let secret_key = SecretKey::from_slice(&content)?; if let Some(keys) = stored_keys {
let keys = Keys::new(secret_key); Ok(keys)
} else {
let keys = Keys::generate();
let user = keys.public_key().to_hex();
let secret = keys.secret_key().to_secret_bytes();
let write = cx.write_credentials(CLIENT_NAME, &user, &secret);
Ok(keys) cx.foreground_executor().block_on(async move {
if let Err(e) = write.await {
log::error!("Keyring not available or panic: {e}")
}
});
Ok(keys)
}
} }
fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> { fn default_relay_list() -> Vec<(RelayUrl, Option<RelayMetadata>)> {
@@ -911,7 +786,7 @@ fn default_messaging_relays() -> Vec<RelayUrl> {
vec![ vec![
RelayUrl::parse("wss://nos.lol").unwrap(), RelayUrl::parse("wss://nos.lol").unwrap(),
RelayUrl::parse("wss://nip17.com").unwrap(), RelayUrl::parse("wss://nip17.com").unwrap(),
RelayUrl::parse("wss://relay.0xchat.com").unwrap(), RelayUrl::parse("wss://auth.nostr1.com").unwrap(),
] ]
} }

View File

@@ -42,7 +42,7 @@ impl CoopSigner {
/// Get public key /// Get public key
/// ///
/// Ensure to call this method after the signer has been initialized. /// Ensure to call this method after the signer has been initialized.
/// Otherwise, this method will panic. /// Otherwise, it will panic.
pub fn public_key(&self) -> Option<PublicKey> { pub fn public_key(&self) -> Option<PublicKey> {
*self.signer_pkey.read_blocking() *self.signer_pkey.read_blocking()
} }

View File

@@ -295,10 +295,13 @@ impl Render for Notification {
.clone() .clone()
.map(|builder| builder(self, window, cx)); .map(|builder| builder(self, window, cx));
let action = self let action = self.action_builder.clone().map(|builder| {
.action_builder builder(self, window, cx)
.clone() .xsmall()
.map(|builder| builder(self, window, cx).small().mr_3p5()); .primary()
.px_3()
.font_semibold()
});
let icon = match self.kind { let icon = match self.kind {
None => self.icon.clone(), None => self.icon.clone(),
@@ -360,14 +363,8 @@ impl Render for Notification {
}) })
.when_some(content, |this, content| this.child(content)) .when_some(content, |this, content| this.child(content))
.when_some(action, |this, action| { .when_some(action, |this, action| {
this.child( this.gap_2()
h_flex() .child(h_flex().w_full().flex_1().justify_end().child(action))
.w_full()
.flex_1()
.gap_1()
.justify_end()
.child(action),
)
}), }),
) )
.child( .child(

View File

@@ -8,5 +8,7 @@ targets = [
"x86_64-unknown-linux-gnu", "x86_64-unknown-linux-gnu",
"x86_64-pc-windows-msvc", "x86_64-pc-windows-msvc",
"aarch64-pc-windows-msvc", "aarch64-pc-windows-msvc",
"aarch64-apple-ios",
"aarch64-linux-android",
"wasm32-unknown-unknown" "wasm32-unknown-unknown"
] ]