merged previous stuffs on master

This commit is contained in:
2026-02-20 19:48:03 +07:00
parent 014757cfc9
commit b88955e62c
176 changed files with 11152 additions and 11212 deletions

View File

@@ -9,11 +9,19 @@ common = { path = "../common" }
nostr-sdk.workspace = true
nostr-lmdb.workspace = true
nostr-connect.workspace = true
gpui.workspace = true
gpui_tokio.workspace = true
smol.workspace = true
reqwest.workspace = true
flume.workspace = true
log.workspace = true
anyhow.workspace = true
webbrowser.workspace = true
serde.workspace = true
serde_json.workspace = true
rustls = "0.23"
petname = "2.0.2"
whoami = "1.6.1"

View File

@@ -0,0 +1,59 @@
use std::sync::OnceLock;
/// Client name (Application name)
pub const CLIENT_NAME: &str = "Coop";
/// COOP's public key
pub const COOP_PUBKEY: &str = "npub126kl5fruqan90py77gf6pvfvygefl2mu2ukew6xdx5pc5uqscwgsnkgarv";
/// App ID
pub const APP_ID: &str = "su.reya.coop";
/// Keyring name
pub const KEYRING: &str = "Coop Safe Storage";
/// Default timeout for subscription
pub const TIMEOUT: u64 = 3;
/// Default delay for searching
pub const FIND_DELAY: u64 = 600;
/// Default limit for searching
pub const FIND_LIMIT: usize = 20;
/// Default timeout for Nostr Connect
pub const NOSTR_CONNECT_TIMEOUT: u64 = 200;
/// Default Nostr Connect relay
pub const NOSTR_CONNECT_RELAY: &str = "wss://relay.nsec.app";
/// Default subscription id for device gift wrap events
pub const DEVICE_GIFTWRAP: &str = "device-gift-wraps";
/// Default subscription id for user gift wrap events
pub const USER_GIFTWRAP: &str = "user-gift-wraps";
/// Default vertex relays
pub const WOT_RELAYS: [&str; 1] = ["wss://relay.vertexlab.io"];
/// Default search relays
pub const SEARCH_RELAYS: [&str; 1] = ["wss://antiprimal.net"];
/// Default bootstrap relays
pub const BOOTSTRAP_RELAYS: [&str; 3] = [
"wss://relay.damus.io",
"wss://relay.primal.net",
"wss://user.kindpag.es",
];
static APP_NAME: OnceLock<String> = OnceLock::new();
/// Get the app name
pub fn app_name() -> &'static String {
APP_NAME.get_or_init(|| {
let devicename = whoami::devicename();
let platform = whoami::platform();
format!("{CLIENT_NAME} on {platform} ({devicename})")
})
}

View File

@@ -1,62 +0,0 @@
use gpui::SharedString;
use nostr_sdk::prelude::*;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub enum DeviceState {
#[default]
Initial,
Requesting,
Set,
}
/// Announcement
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Announcement {
/// The public key of the device that created this announcement.
public_key: PublicKey,
/// The name of the device that created this announcement.
client_name: Option<String>,
}
impl From<&Event> for Announcement {
fn from(val: &Event) -> Self {
let public_key = val
.tags
.iter()
.find(|tag| tag.kind().as_str() == "n" || tag.kind().as_str() == "P")
.and_then(|tag| tag.content())
.and_then(|c| PublicKey::parse(c).ok())
.unwrap_or(val.pubkey);
let client_name = val
.tags
.find(TagKind::Client)
.and_then(|tag| tag.content())
.map(|c| c.to_string());
Self::new(public_key, client_name)
}
}
impl Announcement {
pub fn new(public_key: PublicKey, client_name: Option<String>) -> Self {
Self {
public_key,
client_name,
}
}
/// Returns the public key of the device that created this announcement.
pub fn public_key(&self) -> PublicKey {
self.public_key
}
/// Returns the client name of the device that created this announcement.
pub fn client_name(&self) -> SharedString {
self.client_name
.as_ref()
.map(SharedString::from)
.unwrap_or(SharedString::from("Unknown"))
}
}

View File

@@ -1,46 +0,0 @@
use std::collections::HashSet;
use std::sync::{Arc, OnceLock};
use nostr_sdk::prelude::*;
use smol::lock::RwLock;
static TRACKER: OnceLock<Arc<RwLock<EventTracker>>> = OnceLock::new();
pub fn tracker() -> &'static Arc<RwLock<EventTracker>> {
TRACKER.get_or_init(|| Arc::new(RwLock::new(EventTracker::default())))
}
/// Event tracker
#[derive(Debug, Clone, Default)]
pub struct EventTracker {
/// Tracking events sent by Coop in the current session
sent_ids: HashSet<EventId>,
/// Events that need to be resent later
pending_resend: HashSet<(EventId, RelayUrl)>,
}
impl EventTracker {
/// Check if an event was sent by Coop in the current session.
pub fn is_sent_by_coop(&self, id: &EventId) -> bool {
self.sent_ids.contains(id)
}
/// Mark an event as sent by Coop.
pub fn sent(&mut self, id: EventId) {
self.sent_ids.insert(id);
}
/// Get all events that need to be resent later for a specific relay.
pub fn pending_resend(&mut self, relay: &RelayUrl) -> Vec<EventId> {
self.pending_resend
.extract_if(|(_id, url)| url == relay)
.map(|(id, _url)| id)
.collect()
}
/// Add an event (id and relay url) to the pending resend set.
pub fn add_to_pending(&mut self, id: EventId, url: RelayUrl) {
self.pending_resend.insert((id, url));
}
}

View File

@@ -1,86 +0,0 @@
use nostr_sdk::prelude::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RelayState {
#[default]
Initial,
NotSet,
Set,
}
impl RelayState {
pub fn is_initial(&self) -> bool {
matches!(self, RelayState::Initial)
}
}
/// Identity
#[derive(Debug, Clone, Default)]
pub struct Identity {
/// The public key of the account
pub public_key: Option<PublicKey>,
/// Status of the current user NIP-65 relays
relay_list: RelayState,
/// Status of the current user NIP-17 relays
messaging_relays: RelayState,
}
impl AsRef<Identity> for Identity {
fn as_ref(&self) -> &Identity {
self
}
}
impl Identity {
pub fn new() -> Self {
Self {
public_key: None,
relay_list: RelayState::default(),
messaging_relays: RelayState::default(),
}
}
/// Sets the state of the NIP-65 relays.
pub fn set_relay_list_state(&mut self, state: RelayState) {
self.relay_list = state;
}
/// Returns the state of the NIP-65 relays.
pub fn relay_list_state(&self) -> RelayState {
self.relay_list
}
/// Sets the state of the NIP-17 relays.
pub fn set_messaging_relays_state(&mut self, state: RelayState) {
self.messaging_relays = state;
}
/// Returns the state of the NIP-17 relays.
pub fn messaging_relays_state(&self) -> RelayState {
self.messaging_relays
}
/// Force getting the public key of the identity.
///
/// Panics if the public key is not set.
pub fn public_key(&self) -> PublicKey {
self.public_key.unwrap()
}
/// Returns true if the identity has a public key.
pub fn has_public_key(&self) -> bool {
self.public_key.is_some()
}
/// Sets the public key of the identity.
pub fn set_public_key(&mut self, public_key: PublicKey) {
self.public_key = Some(public_key);
}
/// Unsets the public key of the identity.
pub fn unset_public_key(&mut self) {
self.public_key = None;
}
}

File diff suppressed because it is too large Load Diff

60
crates/state/src/nip05.rs Normal file
View File

@@ -0,0 +1,60 @@
use std::sync::Arc;
use anyhow::Error;
use gpui::http_client::{AsyncBody, HttpClient};
use nostr_sdk::prelude::*;
use smol::io::AsyncReadExt;
#[allow(async_fn_in_trait)]
pub trait NostrAddress {
/// Get the NIP-05 profile
async fn profile(&self, client: &Arc<dyn HttpClient>) -> Result<Nip05Profile, Error>;
/// Verify the NIP-05 address
async fn verify(
&self,
client: &Arc<dyn HttpClient>,
public_key: &PublicKey,
) -> Result<bool, Error>;
}
impl NostrAddress for Nip05Address {
async fn profile(&self, client: &Arc<dyn HttpClient>) -> Result<Nip05Profile, Error> {
let mut body = Vec::new();
let mut res = client
.get(self.url().as_str(), AsyncBody::default(), false)
.await?;
// Read the response body into a vector
res.body_mut().read_to_end(&mut body).await?;
// Parse the JSON response
let json: Value = serde_json::from_slice(&body)?;
let profile = Nip05Profile::from_json(self, &json)?;
Ok(profile)
}
async fn verify(
&self,
client: &Arc<dyn HttpClient>,
public_key: &PublicKey,
) -> Result<bool, Error> {
let mut body = Vec::new();
let mut res = client
.get(self.url().as_str(), AsyncBody::default(), false)
.await?;
// Read the response body into a vector
res.body_mut().read_to_end(&mut body).await?;
// Parse the JSON response
let json: Value = serde_json::from_slice(&body)?;
// Verify the NIP-05 address
let verified = nip05::verify_from_json(public_key, self, &json);
Ok(verified)
}
}

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

@@ -0,0 +1,146 @@
use std::borrow::Cow;
use std::result::Result;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use nostr_sdk::prelude::*;
use smol::lock::RwLock;
#[derive(Debug)]
pub struct CoopSigner {
/// User's signer
signer: RwLock<Arc<dyn NostrSigner>>,
/// User's signer public key
signer_pkey: RwLock<Option<PublicKey>>,
/// Specific signer for encryption purposes
encryption_signer: RwLock<Option<Arc<dyn NostrSigner>>>,
/// By default, Coop generates a new signer for new users.
///
/// This flag indicates whether the signer is user-owned or Coop-generated.
owned: AtomicBool,
}
impl CoopSigner {
pub fn new<T>(signer: T) -> Self
where
T: IntoNostrSigner,
{
Self {
signer: RwLock::new(signer.into_nostr_signer()),
signer_pkey: RwLock::new(None),
encryption_signer: RwLock::new(None),
owned: AtomicBool::new(false),
}
}
/// Get the current signer.
pub async fn get(&self) -> Arc<dyn NostrSigner> {
self.signer.read().await.clone()
}
/// Get the encryption signer.
pub async fn get_encryption_signer(&self) -> Option<Arc<dyn NostrSigner>> {
self.encryption_signer.read().await.clone()
}
/// Get public key
pub fn public_key(&self) -> Option<PublicKey> {
self.signer_pkey.read_blocking().to_owned()
}
/// Get the flag indicating whether the signer is user-owned.
pub fn owned(&self) -> bool {
self.owned.load(Ordering::SeqCst)
}
/// Switch the current signer to a new signer.
pub async fn switch<T>(&self, new: T, owned: bool)
where
T: IntoNostrSigner,
{
let new_signer = new.into_nostr_signer();
let public_key = new_signer.get_public_key().await.ok();
let mut signer = self.signer.write().await;
let mut signer_pkey = self.signer_pkey.write().await;
let mut encryption_signer = self.encryption_signer.write().await;
// Switch to the new signer
*signer = new_signer;
// Update the public key
*signer_pkey = public_key;
// Reset the encryption signer
*encryption_signer = None;
// Update the owned flag
self.owned.store(owned, Ordering::SeqCst);
}
/// Set the encryption signer.
pub async fn set_encryption_signer<T>(&self, new: T)
where
T: IntoNostrSigner,
{
let mut encryption_signer = self.encryption_signer.write().await;
*encryption_signer = Some(new.into_nostr_signer());
}
}
impl NostrSigner for CoopSigner {
#[allow(mismatched_lifetime_syntaxes)]
fn backend(&self) -> SignerBackend {
SignerBackend::Custom(Cow::Borrowed("custom"))
}
fn get_public_key<'a>(&'a self) -> BoxedFuture<'a, Result<PublicKey, SignerError>> {
Box::pin(async move { self.get().await.get_public_key().await })
}
fn sign_event<'a>(
&'a self,
unsigned: UnsignedEvent,
) -> BoxedFuture<'a, Result<Event, SignerError>> {
Box::pin(async move { self.get().await.sign_event(unsigned).await })
}
fn nip04_encrypt<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
Box::pin(async move { self.get().await.nip04_encrypt(public_key, content).await })
}
fn nip04_decrypt<'a>(
&'a self,
public_key: &'a PublicKey,
encrypted_content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
Box::pin(async move {
self.get()
.await
.nip04_decrypt(public_key, encrypted_content)
.await
})
}
fn nip44_encrypt<'a>(
&'a self,
public_key: &'a PublicKey,
content: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
Box::pin(async move { self.get().await.nip44_encrypt(public_key, content).await })
}
fn nip44_decrypt<'a>(
&'a self,
public_key: &'a PublicKey,
payload: &'a str,
) -> BoxedFuture<'a, Result<String, SignerError>> {
Box::pin(async move { self.get().await.nip44_decrypt(public_key, payload).await })
}
}