Compare commits

..
3 Commits
Author SHA1 Message Date
reya 0c6d700395 refactor 2026-08-06 14:52:43 +07:00
reya 6d5d154486 update sidebar 2026-08-06 14:21:03 +07:00
reya 627abbdcaf add create new identity 2026-08-06 14:02:16 +07:00
12 changed files with 372 additions and 39 deletions
+29
View File
@@ -0,0 +1,29 @@
use nostr::prelude::*;
/// Build a NIP-34 user grasp list (kind `10317`).
pub fn grasp_list(grasp_servers: Vec<RelayUrl>) -> EventBuilder {
GitUserGraspList { grasp_servers }.into_event_builder()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grasp_list_tags() {
let servers = vec![
RelayUrl::parse("wss://gitnostr.com").unwrap(),
RelayUrl::parse("wss://relay.ngit.dev").unwrap(),
];
let builder = grasp_list(servers);
let urls: Vec<&str> = builder
.tags
.iter()
.filter_map(|t| t.content())
.collect();
assert_eq!(urls, vec!["wss://gitnostr.com", "wss://relay.ngit.dev"]);
}
}
+1
View File
@@ -1,4 +1,5 @@
pub mod addr; pub mod addr;
pub mod builders;
pub mod clone_url; pub mod clone_url;
pub mod filters; pub mod filters;
pub mod model; pub mod model;
-5
View File
@@ -104,13 +104,8 @@ impl NostrBackend {
/// event is immediately visible to [`NostrBackend::query`]. /// event is immediately visible to [`NostrBackend::query`].
pub async fn send(&self, builder: EventBuilder) -> Result<Event> { pub async fn send(&self, builder: EventBuilder) -> Result<Event> {
let event = builder.finalize_async(&self.signer).await?; let event = builder.finalize_async(&self.signer).await?;
let output = self.client.send_event(&event).await?; let output = self.client.send_event(&event).await?;
// Keep our own events in the local database; the notification pump
// only fires for events received from relays.
self.client.database().save_event(&event).await?;
if output.success.is_empty() && !output.failed.is_empty() { if output.success.is_empty() && !output.failed.is_empty() {
let reasons = output let reasons = output
.failed .failed
+2 -7
View File
@@ -7,7 +7,7 @@ use nostr_sdk::prelude::*;
pub struct Update { pub struct Update {
pub kind: Kind, pub kind: Kind,
/// First `a` tag value of the event, if any (e.g. the repository coordinate). /// First `a` tag value of the event, if any (e.g. the repository coordinate).
pub coordinate: Option<String>, pub coordinate: Option<Coordinate>,
pub author: PublicKey, pub author: PublicKey,
pub event_id: EventId, pub event_id: EventId,
} }
@@ -15,12 +15,7 @@ pub struct Update {
impl Update { impl Update {
/// Build an update from a received event. /// Build an update from a received event.
pub fn from_event(event: &Event) -> Self { pub fn from_event(event: &Event) -> Self {
let coordinate = event let coordinate = event.tags.coordinates().nth(0);
.tags
.iter()
.find(|t| t.kind() == "a")
.and_then(|t| t.content())
.map(str::to_owned);
Self { Self {
kind: event.kind, kind: event.kind,
+123 -3
View File
@@ -6,7 +6,7 @@ use gpui::{App, AppContext, Context, Entity, EventEmitter, Global, Task};
use nostr_connect::prelude::*; use nostr_connect::prelude::*;
use nostr_sdk::client::SyncSummary; use nostr_sdk::client::SyncSummary;
use nostr_sdk::prelude::*; use nostr_sdk::prelude::*;
use signed_core::filters; use signed_core::{builders, filters};
use signed_nostr::{NostrBackend, SignedAuthUrlHandler, UniversalSigner, Update}; use signed_nostr::{NostrBackend, SignedAuthUrlHandler, UniversalSigner, Update};
/// Keyring entry holding the user credential (`nsec1...` or `bunker://...` /// Keyring entry holding the user credential (`nsec1...` or `bunker://...`
@@ -199,6 +199,11 @@ impl Backend {
)?; )?;
signer.auth_url_handler(SignedAuthUrlHandler); signer.auth_url_handler(SignedAuthUrlHandler);
this.update(cx, |this, cx| this.set_signer(signer, cx))?; 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 { } else {
this.update(cx, |_, cx| cx.emit(BackendEvent::SignerRequired))?; 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 /// Login with an `nsec1...` key or a `bunker://...` URI, dispatching on
/// the credential's prefix. /// the credential's prefix.
pub fn login(&mut self, credential: &str, cx: &mut Context<Self>) { pub fn login(&mut self, credential: &str, cx: &mut Context<Self>) {
@@ -394,6 +508,11 @@ impl Backend {
self.current_user 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. /// Whether the relay bootstrap has completed.
pub fn is_connected(&self) -> bool { pub fn is_connected(&self) -> bool {
self.connected self.connected
@@ -602,7 +721,6 @@ impl Backend {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> flume::Receiver<Result<Event, Error>> { ) -> flume::Receiver<Result<Event, Error>> {
let (tx, rx) = flume::bounded(1); let (tx, rx) = flume::bounded(1);
let backend = self.inner.clone(); let backend = self.inner.clone();
let task = cx.background_spawn(async move { backend.send(builder).await }); let task = cx.background_spawn(async move { backend.send(builder).await });
@@ -616,7 +734,9 @@ impl Backend {
})?; })?;
} }
Err(e) => { 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()));
})?;
} }
} }
+16 -11
View File
@@ -9,7 +9,6 @@ use crate::backend::{Backend, BackendEvent};
/// their resolved statuses. Always derived from the local database. /// their resolved statuses. Always derived from the local database.
pub struct RepoStore { pub struct RepoStore {
addr: RepoAddr, addr: RepoAddr,
addr_string: String,
pub announcement: Option<Announcement>, pub announcement: Option<Announcement>,
/// `(refname, commit-id)` pairs from the latest state announcement. /// `(refname, commit-id)` pairs from the latest state announcement.
pub refs: Vec<(String, String)>, pub refs: Vec<(String, String)>,
@@ -29,20 +28,27 @@ pub struct RepoStore {
impl RepoStore { impl RepoStore {
pub fn new(addr: RepoAddr, cx: &mut Context<Self>) -> Self { pub fn new(addr: RepoAddr, cx: &mut Context<Self>) -> Self {
let addr_string = addr.to_string(); let backend = Backend::global(cx);
let subscription = cx.subscribe(&Backend::global(cx), |this, _backend, event, cx| { let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
let relevant = match event { let relevant = match event {
BackendEvent::NostrUpdate(update) => { BackendEvent::NostrUpdate(update) => {
update.coordinate.as_deref() == Some(this.addr_string.as_str()) let coordinate = update.coordinate.as_ref() == Some(&this.addr.coordinate());
|| (update.kind == Kind::GitRepoAnnouncement let author = update.author == this.addr.owner;
&& update.author == this.addr.owner) let kind = update.kind == Kind::GitRepoAnnouncement;
coordinate || (author && kind)
} }
BackendEvent::Published(event) => { BackendEvent::Published(event) => {
event.kind == Kind::GitRepoAnnouncement && event.pubkey == this.addr.owner let kind = event.kind == Kind::GitRepoAnnouncement;
|| event.tags.iter().any(|t| { let author = event.pubkey == this.addr.owner;
t.kind() == "a" && t.content() == Some(this.addr_string.as_str()) let coordinate = event
}) .tags
.coordinates()
.into_iter()
.any(|c| c == this.addr.coordinate());
coordinate || (kind && author)
} }
_ => false, _ => false,
}; };
@@ -54,7 +60,6 @@ impl RepoStore {
let mut store = Self { let mut store = Self {
addr, addr,
addr_string,
announcement: None, announcement: None,
refs: Vec::new(), refs: Vec::new(),
head: None, head: None,
+5 -4
View File
@@ -21,15 +21,16 @@ impl RepoListStore {
/// Create a store. If `author` is `None`, all announcements are listed. /// Create a store. If `author` is `None`, all announcements are listed.
pub fn new(author: Option<PublicKey>, cx: &mut Context<Self>) -> Self { pub fn new(author: Option<PublicKey>, cx: &mut Context<Self>) -> Self {
let backend = Backend::global(cx); let backend = Backend::global(cx);
let subscription = cx.subscribe(&backend, |this, _backend, event, cx| { let subscription = cx.subscribe(&backend, |this, _backend, event, cx| {
let git_kind = Kind::GitRepoAnnouncement;
let relevant = match event { let relevant = match event {
BackendEvent::NostrUpdate(update) => { BackendEvent::NostrUpdate(update) => {
update.kind == Kind::GitRepoAnnouncement update.kind == git_kind && this.author.is_none_or(|a| a == update.author)
&& this.author.is_none_or(|a| a == update.author)
} }
BackendEvent::Published(event) => { BackendEvent::Published(event) => {
event.kind == Kind::GitRepoAnnouncement event.kind == git_kind && this.author.is_none_or(|a| a == event.pubkey)
&& this.author.is_none_or(|a| a == event.pubkey)
} }
BackendEvent::Synced | BackendEvent::SyncProgress { .. } => true, BackendEvent::Synced | BackendEvent::SyncProgress { .. } => true,
_ => false, _ => false,
@@ -0,0 +1,11 @@
use gpui::{App, Window, px};
use gpui_component::WindowExt;
/// Open the Import Identity dialog.
///
/// Currently a placeholder — the dialog only shows a title for now.
pub fn open(window: &mut Window, cx: &mut App) {
window.open_dialog(cx, move |dialog, _window, _cx| {
dialog.title("Import identity").width(px(400.))
});
}
@@ -7,10 +7,16 @@ use gpui::{
}; };
use gpui_component::button::{Button, ButtonVariants}; use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dock::{DockArea, DockPlacement, Panel, PanelEvent}; use gpui_component::dock::{DockArea, DockPlacement, Panel, PanelEvent};
use gpui_component::input::InputState;
use gpui_component::{ActiveTheme, v_flex}; use gpui_component::{ActiveTheme, v_flex};
use signed_state::{Backend, BackendEvent}; use signed_state::{Backend, BackendEvent};
use crate::views::RepoListView; use super::RepoListView;
mod import_identity_dialog;
mod onboarding_dialog;
use self::onboarding_dialog::OnboardingState;
/// Left-dock panel with navigation entries. Entries open content panels in /// Left-dock panel with navigation entries. Entries open content panels in
/// the dock area. /// the dock area.
@@ -68,6 +74,29 @@ impl SidebarPanel {
dock_area.add_panel(Arc::new(panel), DockPlacement::Center, None, window, cx); dock_area.add_panel(Arc::new(panel), DockPlacement::Center, None, window, cx);
}); });
} }
/// Show the Onboarding dialog.
fn open_onboarding(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let name_input = cx.new(|cx| InputState::new(window, cx).placeholder("Enter desired name"));
let pass_input = cx.new(|cx| {
InputState::new(window, cx)
.placeholder("Passphrase to protect your keys")
.masked(true)
});
let repass_input = cx.new(|cx| {
InputState::new(window, cx)
.placeholder("Repeat passphrase")
.masked(true)
});
let state = cx.new(|_| OnboardingState::default());
onboarding_dialog::open(name_input, pass_input, repass_input, state, window, cx);
}
/// Show the Import Identity dialog.
fn open_import(&mut self, window: &mut Window, cx: &mut Context<Self>) {
import_identity_dialog::open(window, cx);
}
} }
impl Panel for SidebarPanel { impl Panel for SidebarPanel {
@@ -114,20 +143,27 @@ impl Render for SidebarPanel {
.gap_2() .gap_2()
.child( .child(
div() div()
.text_xs() .text_sm()
.text_color(cx.theme().muted_foreground) .text_color(cx.theme().muted_foreground)
.child("Sign in to continue"), .child("Sign in to continue"),
) )
.child( .child(
Button::new("get-started") Button::new("onboarding")
.label("Get started") .label("Join now")
.primary() .primary()
.w_full(), .w_full()
.on_click(
cx.listener(|this, _ev, window, cx| this.open_onboarding(window, cx)),
),
) )
.child( .child(
Button::new("import-identity") Button::new("import-identity")
.label("Import identity") .label("Import identity")
.w_full(), .secondary()
.w_full()
.on_click(
cx.listener(|this, _ev, window, cx| this.open_import(window, cx)),
),
) )
} }
} }
@@ -0,0 +1,138 @@
use gpui::prelude::*;
use gpui::{App, Entity, SharedString, Window, div, px};
use gpui_component::button::{Button, ButtonVariants};
use gpui_component::dialog::{DialogDescription, DialogFooter, DialogHeader, DialogTitle};
use gpui_component::form::{field, v_form};
use gpui_component::input::{Input, InputState};
use gpui_component::{ActiveTheme, Disableable, WindowExt};
use signed_state::Backend;
/// Shared state for the Onboarding dialog, so async results can be rendered.
#[derive(Default)]
pub struct OnboardingState {
pub busy: bool,
pub error: Option<SharedString>,
}
/// Open the Onboarding dialog for creating a new identity.
///
/// The caller is responsible for creating the input and state entities and
/// passing them in. This function only builds the dialog UI and wires up
/// the continue-button handler.
pub fn open(
name_input: Entity<InputState>,
pass_input: Entity<InputState>,
repass_input: Entity<InputState>,
state: Entity<OnboardingState>,
window: &mut Window,
cx: &mut App,
) {
window.open_dialog(cx, move |dialog, _window, _cx| {
let name_input = name_input.clone();
let pass_input = pass_input.clone();
let repass_input = repass_input.clone();
let state = state.clone();
dialog
.width(px(520.))
.margin_top(px(50.))
.content(move |content, _window, cx| {
let busy = state.read(cx).busy;
let error = state.read(cx).error.clone();
content
.child(
DialogHeader::new()
.child(DialogTitle::new().child("Create identity"))
.child(
DialogDescription::new()
.child("Set up your Signed identity to get started."),
),
)
.child(
v_form()
.child(
field()
.label("Name")
.description("Max 255 characters")
.required(true)
.child(Input::new(&name_input)),
)
.child(
field()
.label("Passphrase")
.required(true)
.child(Input::new(&pass_input)),
)
.child(field().required(true).child(Input::new(&repass_input))),
)
.children(error.map(|message| {
div().text_sm().text_color(cx.theme().danger).child(message)
}))
.child(
DialogFooter::new().justify_end().child(
Button::new("continue")
.primary()
.label("Create new identity")
.tooltip("Create identity")
.loading(busy)
.disabled(busy)
.on_click({
let name_input = name_input.clone();
let pass_input = pass_input.clone();
let repass_input = repass_input.clone();
let state = state.clone();
move |_ev, window, cx| {
let backend = Backend::global(cx);
let name = name_input.read(cx).value().to_string();
let pass = pass_input.read(cx).value().to_string();
let repass = repass_input.read(cx).value().to_string();
if pass != repass {
state.update(cx, |state, _| {
state.busy = false;
state.error =
Some("Passphrases do not match".into());
});
return;
}
state.update(cx, |state, _| {
state.busy = true;
state.error = None;
});
let rx = backend.update(cx, |backend, cx| {
backend.create_identity(&name, &pass, cx)
});
let handle = window.window_handle();
let state = state.clone();
cx.spawn(async move |cx| match rx.recv_async().await {
Ok(Ok(_)) => {
cx.update_window(handle, |_, window, cx| {
window.close_dialog(cx);
})
.ok();
}
Ok(Err(e)) => {
cx.update_window(handle, |_, _window, cx| {
state.update(cx, |state, _| {
state.busy = false;
state.error = Some(e.to_string().into());
});
})
.ok();
}
Err(_) => {}
})
.detach();
}
}),
),
)
})
});
}
+4 -2
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use gpui::prelude::*; use gpui::prelude::*;
use gpui::{Context, Entity, Render, SharedString, Subscription, Window, div, px}; use gpui::{Context, Entity, Render, SharedString, Subscription, Window, div, px};
use gpui_component::dock::{DockArea, DockItem}; use gpui_component::dock::{DockArea, DockItem};
@@ -23,8 +25,8 @@ impl Workspace {
dock.update(cx, |dock_area, cx| { dock.update(cx, |dock_area, cx| {
dock_area.set_left_dock( dock_area.set_left_dock(
DockItem::tab(sidebar.clone(), &weak_dock, window, cx), DockItem::panel(Arc::new(sidebar.clone())),
Some(px(240.)), Some(px(260.)),
true, true,
window, window,
cx, cx,
+1 -1
View File
@@ -17,7 +17,7 @@ fn main() {
signed_state::init(paths::nostr_dir(), cx); signed_state::init(paths::nostr_dir(), cx);
// Set up the window bounds // Set up the window bounds
let bounds = Bounds::centered(None, size(px(960.0), px(720.0)), cx); let bounds = Bounds::centered(None, size(px(980.0), px(740.0)), cx);
// Set up the window options // Set up the window options
let opts = WindowOptions { let opts = WindowOptions {