add create new identity
This commit is contained in:
@@ -6,7 +6,7 @@ use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task};
|
||||
use nostr_connect::prelude::*;
|
||||
use nostr_sdk::client::SyncSummary;
|
||||
use nostr_sdk::prelude::*;
|
||||
use signed_core::filters;
|
||||
use signed_core::{builders, filters};
|
||||
use signed_nostr::{NostrBackend, SignedAuthUrlHandler, UniversalSigner, Update};
|
||||
|
||||
/// Keyring entry holding the user credential (`nsec1...` or `bunker://...`
|
||||
@@ -199,6 +199,11 @@ impl Backend {
|
||||
)?;
|
||||
signer.auth_url_handler(SignedAuthUrlHandler);
|
||||
this.update(cx, |this, cx| this.set_signer(signer, cx))?;
|
||||
} else if content.starts_with("ncryptsec1") {
|
||||
// Encrypted identity: a passphrase is required to
|
||||
// decrypt it, which is not implemented yet.
|
||||
log::warn!("stored identity is ncryptsec-encrypted; passphrase restore is not implemented");
|
||||
this.update(cx, |_, cx| cx.emit(BackendEvent::SignerRequired))?;
|
||||
} else {
|
||||
this.update(cx, |_, cx| cx.emit(BackendEvent::SignerRequired))?;
|
||||
}
|
||||
@@ -218,6 +223,115 @@ impl Backend {
|
||||
}));
|
||||
}
|
||||
|
||||
/// Create a new identity: generate keys, encrypt the secret key with the
|
||||
/// passphrase (NIP-49) and persist it in the keyring, then publish the
|
||||
/// user's NIP-65 relay list, metadata and grasp list.
|
||||
///
|
||||
/// The heavy encryption runs off the UI thread. The returned receiver
|
||||
/// yields the new public key on success, or the failure reason, so
|
||||
/// callers can render progress and inline errors.
|
||||
pub fn create_identity(
|
||||
&mut self,
|
||||
name: &str,
|
||||
password: &str,
|
||||
cx: &mut Context<Self>,
|
||||
) -> flume::Receiver<Result<PublicKey, Error>> {
|
||||
let (tx, rx) = flume::bounded(1);
|
||||
|
||||
let name = name.trim().to_owned();
|
||||
let password = password.to_owned();
|
||||
|
||||
let validation_error = if name.is_empty() || name.len() > 255 {
|
||||
Some("Name must be 1-255 characters")
|
||||
} else if password.is_empty() {
|
||||
Some("Passphrase must not be empty")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(message) = validation_error {
|
||||
tx.try_send(Err(anyhow!(message))).ok();
|
||||
return rx;
|
||||
}
|
||||
|
||||
let job = cx.background_spawn(async move {
|
||||
let keys = Keys::generate();
|
||||
let encrypted =
|
||||
EncryptedSecretKey::new(keys.secret_key(), &password, 16, KeySecurity::Medium)?;
|
||||
let ncryptsec = encrypted.to_bech32()?;
|
||||
Ok::<_, Error>((keys, ncryptsec))
|
||||
});
|
||||
|
||||
self.tasks.push(cx.spawn(async move |this, cx| {
|
||||
let result = async {
|
||||
let (keys, ncryptsec) = job.await?;
|
||||
let public_key = keys.public_key();
|
||||
|
||||
// Persist the encrypted credential.
|
||||
let write = cx.update(|cx| {
|
||||
cx.write_credentials(USER_KEYRING, &public_key.to_hex(), ncryptsec.as_bytes())
|
||||
});
|
||||
write.await?;
|
||||
|
||||
this.update(cx, |this, cx| {
|
||||
// Become the new identity, so the publishes below are
|
||||
// signed with the new keys.
|
||||
this.inner.signer().swap_inner(keys);
|
||||
this.current_user = Some(public_key);
|
||||
this.bootstrap_user(public_key, cx);
|
||||
cx.emit(BackendEvent::SignerChanged);
|
||||
cx.notify();
|
||||
|
||||
let relays: Vec<(RelayUrl, Option<RelayMetadata>)> = [
|
||||
(
|
||||
RelayUrl::parse("wss://relay.primal.net").unwrap(),
|
||||
Some(RelayMetadata::Read),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://relay.ditto.pub").unwrap(),
|
||||
Some(RelayMetadata::Read),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://relay.nostr.net").unwrap(),
|
||||
Some(RelayMetadata::Write),
|
||||
),
|
||||
(
|
||||
RelayUrl::parse("wss://nos.lol").unwrap(),
|
||||
Some(RelayMetadata::Write),
|
||||
),
|
||||
]
|
||||
.to_vec();
|
||||
|
||||
this.send(RelayList::new(relays).into_event_builder(), cx);
|
||||
|
||||
let metadata = Metadata::new()
|
||||
.name(&name)
|
||||
.display_name(&name)
|
||||
.into_event_builder();
|
||||
|
||||
this.send(metadata, cx);
|
||||
|
||||
let grasp_servers: Vec<RelayUrl> =
|
||||
["wss://gitnostr.com", "wss://relay.ngit.dev"]
|
||||
.into_iter()
|
||||
.map(|url| RelayUrl::parse(url).expect("valid relay URL"))
|
||||
.collect();
|
||||
|
||||
this.send(builders::grasp_list(grasp_servers), cx);
|
||||
})?;
|
||||
|
||||
Ok(public_key)
|
||||
}
|
||||
.await;
|
||||
|
||||
tx.send_async(result).await.ok();
|
||||
|
||||
Ok(())
|
||||
}));
|
||||
|
||||
rx
|
||||
}
|
||||
|
||||
/// Login with an `nsec1...` key or a `bunker://...` URI, dispatching on
|
||||
/// the credential's prefix.
|
||||
pub fn login(&mut self, credential: &str, cx: &mut Context<Self>) {
|
||||
@@ -394,6 +508,11 @@ impl Backend {
|
||||
self.current_user
|
||||
}
|
||||
|
||||
/// Surface an error message through [`BackendEvent::Error`].
|
||||
pub fn emit_error(&mut self, message: impl Into<String>, cx: &mut Context<Self>) {
|
||||
cx.emit(BackendEvent::error(message));
|
||||
}
|
||||
|
||||
/// Whether the relay bootstrap has completed.
|
||||
pub fn is_connected(&self) -> bool {
|
||||
self.connected
|
||||
@@ -602,7 +721,6 @@ impl Backend {
|
||||
cx: &mut Context<Self>,
|
||||
) -> flume::Receiver<Result<Event, Error>> {
|
||||
let (tx, rx) = flume::bounded(1);
|
||||
|
||||
let backend = self.inner.clone();
|
||||
let task = cx.background_spawn(async move { backend.send(builder).await });
|
||||
|
||||
@@ -616,7 +734,9 @@ impl Backend {
|
||||
})?;
|
||||
}
|
||||
Err(e) => {
|
||||
this.update(cx, |_this, cx| cx.emit(BackendEvent::error(e.to_string())))?;
|
||||
this.update(cx, |_this, cx| {
|
||||
cx.emit(BackendEvent::error(e.to_string()));
|
||||
})?;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user