Add in-app pairing from a nostrconnect:// string
This commit is contained in:
4 files changed
+485
-147
No files matched your search
+7
-87
@@ -12,14 +12,13 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
use glib::prelude::ToVariant;
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::runtime;
|
||||
use crate::signer::approval::{Approver, Decision};
|
||||
use crate::signer::{ClientPairing, Signer, SignerConfig, parse_client_uri};
|
||||
use crate::store::apps::AppRegistry;
|
||||
use crate::store::audit::{self, ActivityLog, Entry};
|
||||
use crate::store::audit::ActivityLog;
|
||||
use crate::store::keys::KeyStore;
|
||||
use crate::APP_ID;
|
||||
|
||||
@@ -82,7 +81,7 @@ async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
Arc::clone(®istry),
|
||||
settings.auto_approve_limit(),
|
||||
activity.clone(),
|
||||
changes,
|
||||
changes.clone(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
@@ -105,7 +104,7 @@ async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
);
|
||||
|
||||
if let Some(pairing) = &pairing {
|
||||
finish_pairing(&signer, ®istry, &activity, pairing).await?;
|
||||
finish_pairing(&signer, ®istry, &activity, &changes, pairing).await?;
|
||||
}
|
||||
|
||||
wait_for_shutdown().await;
|
||||
@@ -119,31 +118,12 @@ async fn finish_pairing(
|
||||
signer: &Signer,
|
||||
registry: &Arc<Mutex<AppRegistry>>,
|
||||
activity: &ActivityLog,
|
||||
changes: &async_channel::Sender<()>,
|
||||
pairing: &ClientPairing,
|
||||
) -> Result<(), String> {
|
||||
// A re-pair of an already-approved client must not lose its stored
|
||||
// permissions if the response cannot be delivered, so only roll back what
|
||||
// this run added.
|
||||
let was_approved = registry.lock().unwrap().contains(&pairing.client);
|
||||
registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&pairing.client_info())
|
||||
.map_err(|error| format!("could not record the pairing: {error}"))?;
|
||||
|
||||
if let Err(error) = signer.complete_pairing(pairing).await {
|
||||
rollback_pairing(registry, &pairing.client, was_approved);
|
||||
return Err(format!("pairing failed: {error}"));
|
||||
}
|
||||
|
||||
activity.record(&Entry {
|
||||
at: audit::now(),
|
||||
app: pairing.client.to_hex(),
|
||||
name: pairing.name.clone(),
|
||||
method: "connect".to_string(),
|
||||
kind: None,
|
||||
outcome: audit::outcome::PAIRED.to_string(),
|
||||
});
|
||||
crate::signer::pair_client(signer, registry, activity, changes, pairing)
|
||||
.await
|
||||
.map_err(|error| format!("pairing failed: {error}"))?;
|
||||
|
||||
let name = pairing
|
||||
.name
|
||||
@@ -165,16 +145,6 @@ async fn finish_pairing(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo a pairing whose response could not be delivered: revoke the client
|
||||
/// **only if this run is what approved it**, so a re-pair never destroys
|
||||
/// existing permissions on a network blip.
|
||||
fn rollback_pairing(registry: &Arc<Mutex<AppRegistry>>, client: &PublicKey, was_approved: bool) {
|
||||
if was_approved {
|
||||
return;
|
||||
}
|
||||
let _ = registry.lock().unwrap().revoke(client);
|
||||
}
|
||||
|
||||
/// True if another Regent (the GUI, or another headless run) owns the app's
|
||||
/// D-Bus name. The session bus is required for the keyring, so a missing one is
|
||||
/// an error rather than a silent "not running".
|
||||
@@ -201,56 +171,6 @@ fn another_instance_running() -> Result<bool, String> {
|
||||
Ok(owned)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::signer::approval::ClientInfo;
|
||||
use crate::store::apps::Permission;
|
||||
use nostr::prelude::Keys;
|
||||
|
||||
fn registry_with(kind: Option<u16>) -> (Arc<Mutex<AppRegistry>>, PublicKey) {
|
||||
let keys = Keys::generate();
|
||||
let mut registry = AppRegistry::default();
|
||||
registry
|
||||
.approve(&ClientInfo {
|
||||
public_key: keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.unwrap();
|
||||
if let Some(kind) = kind {
|
||||
registry
|
||||
.allow(&keys.public_key(), Permission::Kind(kind))
|
||||
.unwrap();
|
||||
}
|
||||
(Arc::new(Mutex::new(registry)), keys.public_key())
|
||||
}
|
||||
|
||||
/// A re-pair that cannot deliver its response must not delete an existing
|
||||
/// approval or its permissions.
|
||||
#[test]
|
||||
fn a_failed_repair_keeps_an_existing_permission() {
|
||||
let (registry, client) = registry_with(Some(1));
|
||||
|
||||
rollback_pairing(®istry, &client, true);
|
||||
|
||||
let guard = registry.lock().unwrap();
|
||||
assert!(guard.contains(&client), "the app must survive");
|
||||
assert!(guard.permits(&client, &Permission::Kind(1)));
|
||||
}
|
||||
|
||||
/// A first pairing that fails removes the client it had just added.
|
||||
#[test]
|
||||
fn a_failed_first_pairing_revokes_the_client() {
|
||||
let (registry, client) = registry_with(None);
|
||||
|
||||
rollback_pairing(®istry, &client, false);
|
||||
|
||||
assert!(!registry.lock().unwrap().contains(&client));
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_shutdown() {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
|
||||
|
||||
+252
-37
@@ -91,9 +91,10 @@ pub struct Signer {
|
||||
config: Arc<SignerConfig>,
|
||||
client: Client,
|
||||
running: Arc<AtomicBool>,
|
||||
/// Configured relays plus any the client asked for: where we listen and
|
||||
/// answer, as opposed to the advertised list in `config.relays`.
|
||||
relay_count: usize,
|
||||
/// Where responses are published: the configured relays plus any a paired
|
||||
/// client asked for. Grows at runtime via [`Signer::add_client_relays`];
|
||||
/// the responder task reads it under a short lock when it answers.
|
||||
response_targets: Arc<Mutex<Vec<RelayUrl>>>,
|
||||
uri: String,
|
||||
}
|
||||
|
||||
@@ -106,6 +107,7 @@ impl Signer {
|
||||
}
|
||||
urls.sort();
|
||||
urls.dedup();
|
||||
let response_targets = Arc::new(Mutex::new(urls.clone()));
|
||||
|
||||
let client = Client::new();
|
||||
for url in &urls {
|
||||
@@ -147,11 +149,11 @@ impl Signer {
|
||||
|
||||
let running = Arc::new(AtomicBool::new(true));
|
||||
{
|
||||
let (client, config, running, urls) = (
|
||||
let (client, config, running, response_targets) = (
|
||||
client.clone(),
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&running),
|
||||
urls.clone(),
|
||||
Arc::clone(&response_targets),
|
||||
);
|
||||
tokio::spawn(async move {
|
||||
while running.load(Ordering::SeqCst) {
|
||||
@@ -166,11 +168,12 @@ impl Signer {
|
||||
}
|
||||
match handle_request(&event, &config).await {
|
||||
Ok(Some(response)) => {
|
||||
// Clone the targets under a short lock; the lock is
|
||||
// never held across the publish below.
|
||||
let targets = response_targets.lock().unwrap().clone();
|
||||
// Responses go back to the relays the clients use,
|
||||
// again bypassing gossip routing.
|
||||
if let Err(error) =
|
||||
client.send_event(&response).to(urls.clone()).await
|
||||
{
|
||||
if let Err(error) = client.send_event(&response).to(targets).await {
|
||||
eprintln!("regent: could not answer a request: {error}");
|
||||
}
|
||||
}
|
||||
@@ -188,7 +191,7 @@ impl Signer {
|
||||
config,
|
||||
client,
|
||||
running,
|
||||
relay_count: urls.len(),
|
||||
response_targets,
|
||||
uri,
|
||||
})
|
||||
}
|
||||
@@ -202,10 +205,50 @@ impl Signer {
|
||||
self.config.device_keys.public_key()
|
||||
}
|
||||
|
||||
/// How many relays we actually listen on: the configured ones plus any the
|
||||
/// paired client asked us to use. The advertised list is `config.relays`.
|
||||
/// How many relays we listen on: the configured ones plus any a paired
|
||||
/// client asked for. The advertised list is `config.relays`.
|
||||
pub fn relay_count(&self) -> usize {
|
||||
self.relay_count
|
||||
self.response_targets.lock().unwrap().len()
|
||||
}
|
||||
|
||||
/// Add relays a client asked us to use and start listening there.
|
||||
///
|
||||
/// Mirrors `start`'s discipline, which matters: a subscription sent while a
|
||||
/// relay is still `Pending` is registered locally but never transmitted, so
|
||||
/// add with `verify_subscriptions`, wait until connected, and only then
|
||||
/// subscribe an explicit `(RelayUrl, Vec<Filter>)` target — never a bare
|
||||
/// `Filter`, which gossip would resolve to no relay for a `#p`-only filter.
|
||||
pub async fn add_client_relays(&self, relays: &[RelayUrl]) -> Result<()> {
|
||||
let mut fresh = Vec::new();
|
||||
for relay in relays {
|
||||
if self.response_targets.lock().unwrap().contains(relay) {
|
||||
continue;
|
||||
}
|
||||
self.client
|
||||
.add_relay(relay.clone())
|
||||
.verify_subscriptions(true)
|
||||
.await?;
|
||||
fresh.push(relay.clone());
|
||||
}
|
||||
if fresh.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.client.connect().and_wait(Duration::from_secs(15)).await;
|
||||
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::NostrConnect)
|
||||
.pubkey(self.config.device_keys.public_key())
|
||||
.limit(0);
|
||||
let targets: Vec<(RelayUrl, Vec<Filter>)> = fresh
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|relay| (relay, vec![filter.clone()]))
|
||||
.collect();
|
||||
self.client.subscribe(targets).await?;
|
||||
|
||||
self.response_targets.lock().unwrap().extend(fresh);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
@@ -329,6 +372,48 @@ fn bound(value: &str, limit: usize) -> String {
|
||||
value.chars().take(limit).collect()
|
||||
}
|
||||
|
||||
/// Register a client-initiated pairing and send it the `connect` response.
|
||||
///
|
||||
/// Approve **before** publishing: the client validates the secret and usually
|
||||
/// sends `connect` right away, which a new client cannot do without the bunker
|
||||
/// secret. On a failed publish, revoke only if this run is what approved the
|
||||
/// client, so a re-pair never destroys existing permissions on a network blip.
|
||||
pub async fn pair_client(
|
||||
signer: &Signer,
|
||||
registry: &Arc<Mutex<AppRegistry>>,
|
||||
activity: &ActivityLog,
|
||||
changes: &async_channel::Sender<()>,
|
||||
pairing: &ClientPairing,
|
||||
) -> Result<()> {
|
||||
let was_approved = registry.lock().unwrap().contains(&pairing.client);
|
||||
registry.lock().unwrap().approve(&pairing.client_info())?;
|
||||
|
||||
if let Err(error) = signer.complete_pairing(pairing).await {
|
||||
rollback_pairing(registry, &pairing.client, was_approved);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
activity.record(&Entry {
|
||||
at: audit::now(),
|
||||
app: pairing.client.to_hex(),
|
||||
name: pairing.name.clone(),
|
||||
method: "connect".to_string(),
|
||||
kind: None,
|
||||
outcome: audit::outcome::PAIRED.to_string(),
|
||||
});
|
||||
let _ = changes.try_send(());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Undo a pairing whose response could not be delivered: revoke only if this
|
||||
/// run is what approved the client.
|
||||
fn rollback_pairing(registry: &Arc<Mutex<AppRegistry>>, client: &PublicKey, was_approved: bool) {
|
||||
if was_approved {
|
||||
return;
|
||||
}
|
||||
let _ = registry.lock().unwrap().revoke(client);
|
||||
}
|
||||
|
||||
/// The event a client-initiated pairing expects back: the client's secret as
|
||||
/// the `result`, p-tagging the client and signed by the **device** key (the
|
||||
/// client learns the remote-signer pubkey from this event's author).
|
||||
@@ -907,32 +992,36 @@ mod tests {
|
||||
eprintln!("using the relay from REGENT_TEST_RELAY: {relay}");
|
||||
Self { relay, child: None }
|
||||
}
|
||||
None => {
|
||||
// The tests run in parallel, so each gets its own relay; a
|
||||
// shared port means the second `nak serve` fails to bind and
|
||||
// the tests then hang on a relay that never answers.
|
||||
static NEXT_PORT: std::sync::atomic::AtomicU16 =
|
||||
std::sync::atomic::AtomicU16::new(10566);
|
||||
let port = NEXT_PORT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let child = std::process::Command::new("nak")
|
||||
.args(["serve", "--port", &port.to_string()])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn nak serve");
|
||||
// Wait for it to actually accept connections rather than
|
||||
// guessing a sleep.
|
||||
for _ in 0..50 {
|
||||
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Self {
|
||||
relay: format!("ws://127.0.0.1:{port}"),
|
||||
child: Some(child),
|
||||
}
|
||||
None => Self::local().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// Always a fresh local `nak serve`, even when `REGENT_TEST_RELAY` is
|
||||
/// set. The added-relay test needs two *distinct* relays.
|
||||
async fn local() -> Self {
|
||||
// The tests run in parallel, so each gets its own relay; a shared
|
||||
// port means the second `nak serve` fails to bind and the tests then
|
||||
// hang on a relay that never answers.
|
||||
static NEXT_PORT: std::sync::atomic::AtomicU16 =
|
||||
std::sync::atomic::AtomicU16::new(10566);
|
||||
let port = NEXT_PORT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let child = std::process::Command::new("nak")
|
||||
.args(["serve", "--port", &port.to_string()])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
.expect("spawn nak serve");
|
||||
// Wait for it to actually accept connections rather than guessing a
|
||||
// sleep.
|
||||
for _ in 0..50 {
|
||||
if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Self {
|
||||
relay: format!("ws://127.0.0.1:{port}"),
|
||||
child: Some(child),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1737,4 +1826,130 @@ mod tests {
|
||||
"a signature announces a change"
|
||||
);
|
||||
}
|
||||
|
||||
fn registry_with(kind: Option<u16>) -> (Arc<Mutex<AppRegistry>>, PublicKey) {
|
||||
let keys = Keys::generate();
|
||||
let mut registry = AppRegistry::default();
|
||||
registry
|
||||
.approve(&ClientInfo {
|
||||
public_key: keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.unwrap();
|
||||
if let Some(kind) = kind {
|
||||
registry
|
||||
.allow(&keys.public_key(), Permission::Kind(kind))
|
||||
.unwrap();
|
||||
}
|
||||
(Arc::new(Mutex::new(registry)), keys.public_key())
|
||||
}
|
||||
|
||||
/// A re-pair that cannot deliver its response must not delete an existing
|
||||
/// approval or its permissions.
|
||||
#[test]
|
||||
fn a_failed_repair_keeps_an_existing_permission() {
|
||||
let (registry, client) = registry_with(Some(1));
|
||||
|
||||
rollback_pairing(®istry, &client, true);
|
||||
|
||||
let guard = registry.lock().unwrap();
|
||||
assert!(guard.contains(&client), "the app must survive");
|
||||
assert!(guard.permits(&client, &Permission::Kind(1)));
|
||||
}
|
||||
|
||||
/// A first pairing that fails removes the client it had just added.
|
||||
#[test]
|
||||
fn a_failed_first_pairing_revokes_the_client() {
|
||||
let (registry, client) = registry_with(None);
|
||||
|
||||
rollback_pairing(®istry, &client, false);
|
||||
|
||||
assert!(!registry.lock().unwrap().contains(&client));
|
||||
}
|
||||
|
||||
/// A relay added after start must carry both directions: the signer has to
|
||||
/// receive the request and publish the answer there.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
|
||||
async fn a_request_on_an_added_relay_is_answered_there() {
|
||||
let mut relay_a = TestRelay::start().await;
|
||||
let mut relay_b = TestRelay::local().await;
|
||||
let (approver, approvals) = auto_approver(Decision::Always);
|
||||
let config = config(&relay_a.relay, approver);
|
||||
let device = config.device_keys.public_key();
|
||||
let expected = config.user_keys.public_key();
|
||||
|
||||
let client_keys = Keys::generate();
|
||||
// Approved, so `get_public_key` is answered rather than rejected.
|
||||
config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&ClientInfo {
|
||||
public_key: client_keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let signer = Signer::start(config).await.expect("start signer");
|
||||
|
||||
let added = RelayUrl::parse(&relay_b.relay).expect("relay url");
|
||||
signer
|
||||
.add_client_relays(&[added.clone()])
|
||||
.await
|
||||
.expect("add the client relay");
|
||||
|
||||
// A client that only ever touches relay B.
|
||||
let client = Client::new();
|
||||
client.add_relay(added.clone()).await.expect("add relay");
|
||||
client.connect().await;
|
||||
client.connect().and_wait(Duration::from_secs(15)).await;
|
||||
let filter = Filter::new()
|
||||
.kind(Kind::NostrConnect)
|
||||
.pubkey(client_keys.public_key())
|
||||
.limit(0);
|
||||
let mut notifications = client.notifications();
|
||||
client
|
||||
.subscribe(vec![(added.clone(), vec![filter])])
|
||||
.await
|
||||
.expect("subscribe");
|
||||
|
||||
let request = client_request(
|
||||
&client_keys,
|
||||
&device,
|
||||
"get_public_key",
|
||||
serde_json::json!([]),
|
||||
);
|
||||
client
|
||||
.send_event(&request)
|
||||
.to(vec![added])
|
||||
.await
|
||||
.expect("publish the request");
|
||||
|
||||
let response = tokio::time::timeout(Duration::from_secs(10), async {
|
||||
while let Some(notification) = notifications.next().await {
|
||||
if let ClientNotification::Event { event, .. } = notification {
|
||||
if event.kind == Kind::NostrConnect && event.pubkey == device {
|
||||
return Some(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await
|
||||
.expect("the request should be answered")
|
||||
.expect("a response");
|
||||
|
||||
relay_a.stop();
|
||||
relay_b.stop();
|
||||
signer.stop().await;
|
||||
approvals.abort();
|
||||
|
||||
let answer = read_response(&response, &client_keys, &device);
|
||||
assert_eq!(answer["result"].as_str(), Some(expected.to_hex().as_str()));
|
||||
}
|
||||
}
|
||||
+18
-10
@@ -12,7 +12,7 @@ use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
use crate::signer::approval::{ApprovalRequest, Decision, Request};
|
||||
use crate::signer::approval::{ApprovalRequest, ClientInfo, Decision, Request};
|
||||
use crate::ui::{kind, plain};
|
||||
|
||||
/// Start draining questions: each one becomes a dialog, and the answer goes back
|
||||
@@ -20,7 +20,7 @@ use crate::ui::{kind, plain};
|
||||
pub fn install(questions: Receiver<ApprovalRequest>, widget: gtk::Widget) {
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
while let Ok(question) = questions.recv().await {
|
||||
let decision = present(&widget, &question).await;
|
||||
let decision = present_question(&widget, &question.client, &question.request).await;
|
||||
let _ = question.reply.send(decision).await;
|
||||
}
|
||||
});
|
||||
@@ -36,21 +36,30 @@ enum Choices {
|
||||
OnceAlways,
|
||||
}
|
||||
|
||||
async fn present(widget: >k::Widget, question: &ApprovalRequest) -> Decision {
|
||||
let choices = match &question.request {
|
||||
/// Show one approval question and return the user's answer.
|
||||
///
|
||||
/// Used by the responder's drain ([`install`]) and by user-initiated flows such
|
||||
/// as pasting a `nostrconnect://` string, so both go through exactly the same
|
||||
/// plain-text dialog and the same "no answer means no" rule.
|
||||
pub async fn present_question(
|
||||
widget: &impl IsA<gtk::Widget>,
|
||||
client: &ClientInfo,
|
||||
request: &Request,
|
||||
) -> Decision {
|
||||
let choices = match request {
|
||||
Request::Pair { .. } => Choices::Pair,
|
||||
request if !request.allows_always() => Choices::Once,
|
||||
_ => Choices::OnceAlways,
|
||||
};
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading(heading(&question.request))
|
||||
.body(story(&question.request))
|
||||
.heading(heading(request))
|
||||
.body(story(request))
|
||||
// Narrower than the 420px default window: a floating `AdwDialog` is
|
||||
// part of the window and is clipped by it, so it must be able to shrink
|
||||
// to fit rather than poke out of the sides.
|
||||
.content_width(360)
|
||||
.extra_child(&details(question))
|
||||
.extra_child(&details(client, request))
|
||||
.build();
|
||||
// Heading and body are plain text too: the heading carries no client data
|
||||
// today, but the extra child is where all of it belongs.
|
||||
@@ -114,8 +123,7 @@ fn story(request: &Request) -> &'static str {
|
||||
}
|
||||
|
||||
/// The selectable, plain-text detail block: who is asking and exactly what.
|
||||
fn details(question: &ApprovalRequest) -> gtk::Box {
|
||||
let client = &question.client;
|
||||
fn details(client: &ClientInfo, request: &Request) -> gtk::Box {
|
||||
let content = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
.spacing(10)
|
||||
@@ -133,7 +141,7 @@ fn details(question: &ApprovalRequest) -> gtk::Box {
|
||||
&client.public_key.to_bech32().unwrap_or_default(),
|
||||
));
|
||||
|
||||
match &question.request {
|
||||
match request {
|
||||
Request::Pair { requested } => {
|
||||
if let Some(requested) = requested {
|
||||
content.append(&field("Asked for", requested));
|
||||
|
||||
+208
-13
@@ -4,7 +4,7 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::signer::approval::Approver;
|
||||
use crate::signer::approval::{Approver, Decision, Request};
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
|
||||
@@ -15,8 +15,9 @@ use libadwaita as adw;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::runtime;
|
||||
use crate::signer::{Signer, SignerConfig};
|
||||
use crate::signer::{ClientPairing, Signer, SignerConfig, pair_client, parse_client_uri};
|
||||
use crate::state::AppState;
|
||||
use crate::ui::approval;
|
||||
use crate::ui::plain;
|
||||
use crate::ui::qr;
|
||||
|
||||
@@ -30,6 +31,7 @@ struct Handles {
|
||||
device: adw::ActionRow,
|
||||
picture: gtk::Picture,
|
||||
toggle: gtk::Button,
|
||||
pair: gtk::Button,
|
||||
}
|
||||
|
||||
/// The toplevel, resolved lazily: a view is not in a window when it is built.
|
||||
@@ -37,7 +39,16 @@ fn toplevel(handles: &Handles) -> Option<gtk::Window> {
|
||||
handles.stack.root().and_downcast::<gtk::Window>()
|
||||
}
|
||||
|
||||
type Running = Rc<RefCell<Option<Arc<Signer>>>>;
|
||||
/// The signer's lifecycle. `Starting` matters: a second start (the toggle, or a
|
||||
/// paste while the first start is still in flight) would put two responders on
|
||||
/// the same device key.
|
||||
enum State {
|
||||
Stopped,
|
||||
Starting,
|
||||
Running(Arc<Signer>),
|
||||
}
|
||||
|
||||
type Running = Rc<RefCell<State>>;
|
||||
|
||||
pub struct SignerView {
|
||||
pub widget: gtk::Widget,
|
||||
@@ -76,6 +87,20 @@ impl SignerView {
|
||||
group.add(&uri);
|
||||
group.add(&device);
|
||||
|
||||
// The client-initiated direction: the application shows a
|
||||
// `nostrconnect://` string and waits for the signer to answer it.
|
||||
let pair_row = plain::row(
|
||||
"Pair with a client",
|
||||
"Paste a nostrconnect:// string from an application that is waiting to connect",
|
||||
);
|
||||
let pair = gtk::Button::builder()
|
||||
.label("Pair…")
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
pair_row.add_suffix(&pair);
|
||||
group.add(&pair_row);
|
||||
|
||||
let picture = gtk::Picture::builder()
|
||||
.content_fit(gtk::ContentFit::Contain)
|
||||
.can_shrink(true)
|
||||
@@ -116,6 +141,7 @@ impl SignerView {
|
||||
device,
|
||||
picture,
|
||||
toggle,
|
||||
pair,
|
||||
};
|
||||
|
||||
let widget: gtk::Widget = handles.stack.clone().upcast();
|
||||
@@ -125,13 +151,14 @@ impl SignerView {
|
||||
let (approver, questions) = Approver::new();
|
||||
crate::ui::approval::install(questions, widget.clone());
|
||||
|
||||
let running: Running = Rc::new(RefCell::new(None));
|
||||
let running: Running = Rc::new(RefCell::new(State::Stopped));
|
||||
|
||||
{
|
||||
let (handles, running) = (handles.clone(), Rc::clone(&running));
|
||||
copy.connect_clicked(move |_| {
|
||||
let Some(signer) = running.borrow().clone() else {
|
||||
return;
|
||||
let signer = match &*running.borrow() {
|
||||
State::Running(signer) => Arc::clone(signer),
|
||||
_ => return,
|
||||
};
|
||||
if let Some(window) = toplevel(&handles) {
|
||||
window.clipboard().set_text(signer.bunker_uri());
|
||||
@@ -143,7 +170,10 @@ impl SignerView {
|
||||
let (handles, state, running) = (handles.clone(), Rc::clone(&state), Rc::clone(&running));
|
||||
let approver = approver.clone();
|
||||
handles.toggle.clone().connect_clicked(move |_| {
|
||||
if running.borrow().is_some() {
|
||||
if matches!(&*running.borrow(), State::Starting) {
|
||||
return;
|
||||
}
|
||||
if matches!(&*running.borrow(), State::Running(_)) {
|
||||
stop(handles.clone(), Rc::clone(&running));
|
||||
} else {
|
||||
start(
|
||||
@@ -151,11 +181,26 @@ impl SignerView {
|
||||
Rc::clone(&state),
|
||||
Rc::clone(&running),
|
||||
approver.clone(),
|
||||
Vec::new(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, state, running) = (handles.clone(), Rc::clone(&state), Rc::clone(&running));
|
||||
let approver = approver.clone();
|
||||
handles.pair.clone().connect_clicked(move |_| {
|
||||
present_paste_dialog(
|
||||
handles.clone(),
|
||||
Rc::clone(&state),
|
||||
Rc::clone(&running),
|
||||
approver.clone(),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// React to the keyring becoming available, and to keys being changed.
|
||||
{
|
||||
let handles = handles.clone();
|
||||
@@ -166,7 +211,7 @@ impl SignerView {
|
||||
let Some(store) = listener_state.store() else {
|
||||
return;
|
||||
};
|
||||
if signer_running.borrow().is_some() {
|
||||
if !matches!(&*signer_running.borrow(), State::Stopped) {
|
||||
return;
|
||||
}
|
||||
let (handles, state, running) = (
|
||||
@@ -178,7 +223,9 @@ impl SignerView {
|
||||
runtime::spawn(
|
||||
async move { store.user_key().await },
|
||||
move |result| match result {
|
||||
Ok(Some(_)) => start(handles, state, running, approver),
|
||||
Ok(Some(_)) => {
|
||||
start(handles, state, running, approver, Vec::new(), None)
|
||||
}
|
||||
Ok(None) => show_empty(&handles),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
@@ -205,10 +252,17 @@ fn start(
|
||||
state: Rc<AppState>,
|
||||
running: Running,
|
||||
approver: Approver,
|
||||
extra_relays: Vec<String>,
|
||||
after: Option<ClientPairing>,
|
||||
) {
|
||||
if !matches!(&*running.borrow(), State::Stopped) {
|
||||
return;
|
||||
}
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
*running.borrow_mut() = State::Starting;
|
||||
|
||||
let settings = Config::new();
|
||||
let relays = settings.relays();
|
||||
let auto_approve_limit = settings.auto_approve_limit();
|
||||
@@ -221,7 +275,7 @@ fn start(
|
||||
|
||||
runtime::spawn(
|
||||
async move {
|
||||
let config = SignerConfig::from_store(
|
||||
let mut config = SignerConfig::from_store(
|
||||
&store,
|
||||
relays,
|
||||
approver,
|
||||
@@ -231,15 +285,20 @@ fn start(
|
||||
changes,
|
||||
)
|
||||
.await?;
|
||||
config.extra_relays = extra_relays;
|
||||
Signer::start(config).await
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(started) => {
|
||||
let started = Arc::new(started);
|
||||
*running.borrow_mut() = Some(Arc::clone(&started));
|
||||
*running.borrow_mut() = State::Running(Arc::clone(&started));
|
||||
show_running(&handles, &started);
|
||||
if let Some(pairing) = after {
|
||||
pair_now(handles.clone(), state, &started, pairing);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
*running.borrow_mut() = State::Stopped;
|
||||
handles.status.set_subtitle("Could not start");
|
||||
handles.stack.set_visible_child_name("ready");
|
||||
report_error(&handles, &error);
|
||||
@@ -249,8 +308,9 @@ fn start(
|
||||
}
|
||||
|
||||
fn stop(handles: Handles, running: Running) {
|
||||
let Some(signer) = running.borrow_mut().take() else {
|
||||
return;
|
||||
let signer = match std::mem::replace(&mut *running.borrow_mut(), State::Stopped) {
|
||||
State::Running(signer) => signer,
|
||||
_ => return,
|
||||
};
|
||||
runtime::spawn_detached(async move { signer.stop().await });
|
||||
handles.picture.set_paintable(None::<&gdk::Paintable>);
|
||||
@@ -293,6 +353,141 @@ fn show_running(handles: &Handles, signer: &Signer) {
|
||||
handles.banner.set_revealed(true);
|
||||
}
|
||||
|
||||
/// Ask for the client's `nostrconnect://` string.
|
||||
fn present_paste_dialog(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
running: Running,
|
||||
approver: Approver,
|
||||
) {
|
||||
// A plain `gtk::Entry`: an `AdwEntryRow` renders its text as Pango markup.
|
||||
let entry = gtk::Entry::builder()
|
||||
.placeholder_text("nostrconnect://…")
|
||||
.hexpand(true)
|
||||
.build();
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Pair with a client")
|
||||
.body(
|
||||
"Paste the nostrconnect:// string the application is showing. It must be \
|
||||
waiting for Regent to connect.",
|
||||
)
|
||||
.extra_child(&entry)
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("pair", "Pair");
|
||||
dialog.set_default_response(Some("pair"));
|
||||
dialog.set_response_appearance("pair", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let entry = entry.clone();
|
||||
let handles = handles.clone();
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "pair" {
|
||||
return;
|
||||
}
|
||||
let uri = entry.text().to_string();
|
||||
if !uri.trim().is_empty() {
|
||||
begin_pairing(
|
||||
&handles,
|
||||
Rc::clone(&state),
|
||||
Rc::clone(&running),
|
||||
approver.clone(),
|
||||
uri,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
/// Parse the URI, ask for consent, then pair — starting the signer if it is
|
||||
/// stopped, so the button works from any state.
|
||||
fn begin_pairing(
|
||||
handles: &Handles,
|
||||
state: Rc<AppState>,
|
||||
running: Running,
|
||||
approver: Approver,
|
||||
uri: String,
|
||||
) {
|
||||
let pairing = match parse_client_uri(uri.trim()) {
|
||||
Ok(pairing) => pairing,
|
||||
Err(error) => {
|
||||
report_error(
|
||||
handles,
|
||||
&format!("That is not a usable nostrconnect:// string: {error}"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let client = pairing.client_info();
|
||||
let requested = pairing.requested.clone();
|
||||
let handles = handles.clone();
|
||||
let widget: gtk::Widget = handles.stack.clone().upcast();
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
// The same dialog and the same rules as a responder-side question.
|
||||
let decision =
|
||||
approval::present_question(&widget, &client, &Request::Pair { requested }).await;
|
||||
if decision == Decision::Deny {
|
||||
return;
|
||||
}
|
||||
|
||||
if matches!(&*running.borrow(), State::Starting) {
|
||||
report_error(
|
||||
&handles,
|
||||
"The signer is still starting; try again in a moment.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let signer = match &*running.borrow() {
|
||||
State::Running(signer) => Some(Arc::clone(signer)),
|
||||
_ => None,
|
||||
};
|
||||
match signer {
|
||||
Some(signer) => pair_now(handles, state, &signer, pairing),
|
||||
None => {
|
||||
if state.store().is_none() {
|
||||
report_error(
|
||||
&handles,
|
||||
"The keyring is not ready yet; try again in a moment.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
let extra = pairing
|
||||
.relays
|
||||
.iter()
|
||||
.map(|relay| relay.to_string())
|
||||
.collect();
|
||||
start(handles, state, running, approver, extra, Some(pairing));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Add the client's relays to the running signer and send it the connect
|
||||
/// response. The app is registered before the response goes out (the client
|
||||
/// validates the secret and immediately sends `connect`).
|
||||
fn pair_now(handles: Handles, state: Rc<AppState>, signer: &Arc<Signer>, pairing: ClientPairing) {
|
||||
let registry = state.registry();
|
||||
let activity = state.activity();
|
||||
let changes = state.changes();
|
||||
let signer = Arc::clone(signer);
|
||||
let refresh = Arc::clone(&signer);
|
||||
runtime::spawn(
|
||||
async move {
|
||||
signer.add_client_relays(&pairing.relays).await?;
|
||||
pair_client(&signer, ®istry, &activity, &changes, &pairing).await?;
|
||||
Ok::<(), crate::signer::Error>(())
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(()) => show_running(&handles, &refresh),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn report_error(handles: &Handles, message: &str) {
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Something went wrong")
|
||||
|
||||
Reference in new issue
Block a user