Ask the user before letting an application pair
Adds the approval bridge (responder asks over a channel, the dialog answers on the main loop, a timeout or a missing UI denies), the registry of approved applications stored in apps.json, and the pairing dialog showing the client's self-declared metadata as the untrusted hint it is. A client that has not been approved now gets no answer to anything except connect. Requests from approved clients are still answered without asking; the banner says so until M4. Covered by two tests against nak: approval lets it pair and sign, denial stops it pairing.
This commit is contained in:
10 files changed
+502
-61
No files matched your search
Generated
+1
@@ -1917,6 +1917,7 @@ dependencies = [
|
||||
"nostr-sdk",
|
||||
"oo7",
|
||||
"qrcode",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
"zeroize",
|
||||
|
||||
@@ -19,6 +19,7 @@ oo7 = { version = "0.7", features = ["tokio"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "process", "time"] }
|
||||
async-channel = "2"
|
||||
serde_json = "1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
zeroize = "1"
|
||||
qrcode = { version = "0.14", features = ["image"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
@@ -26,10 +26,13 @@ cargo_build = custom_target(binary_name,
|
||||
'src/application.rs',
|
||||
'src/config.rs',
|
||||
'src/runtime.rs',
|
||||
'src/signer/approval.rs',
|
||||
'src/signer/mod.rs',
|
||||
'src/state.rs',
|
||||
'src/store/apps.rs',
|
||||
'src/store/mod.rs',
|
||||
'src/store/keys.rs',
|
||||
'src/ui/approval.rs',
|
||||
'src/ui/keys_view.rs',
|
||||
'src/ui/mod.rs',
|
||||
'src/ui/qr.rs',
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Asking the user before answering a request.
|
||||
//!
|
||||
//! The responder runs on the async runtime while the dialogs live on the GTK
|
||||
//! main loop, so requests travel over a channel and the answer comes back the
|
||||
//! same way. **No answer means no** — the ask times out to `Deny`, never to a
|
||||
//! silent yes.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use async_channel::{Receiver, Sender, bounded};
|
||||
use nostr::prelude::*;
|
||||
|
||||
/// How long the responder waits for the user before denying.
|
||||
pub const ASK_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Who is asking, as far as we can tell.
|
||||
///
|
||||
/// Name, URL and image come from the client's own `connect` metadata: they are
|
||||
/// unauthenticated display hints and must never be used to decide anything.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ClientInfo {
|
||||
pub public_key: PublicKey,
|
||||
pub name: Option<String>,
|
||||
pub url: Option<String>,
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
/// What is being asked for.
|
||||
///
|
||||
/// `Sign`, `Encrypt` and `Decrypt` are used from M4, when every sensitive
|
||||
/// request is put to the user.
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Request {
|
||||
/// An application wants to connect for the first time.
|
||||
Pair,
|
||||
/// An event would be signed with the identity key.
|
||||
Sign { kind: u16, preview: String },
|
||||
/// A message would be encrypted to someone.
|
||||
Encrypt { peer: String },
|
||||
/// A message would be decrypted from someone.
|
||||
Decrypt { peer: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Decision {
|
||||
Deny,
|
||||
Once,
|
||||
Always,
|
||||
}
|
||||
|
||||
/// One question for the user, with the channel to answer on.
|
||||
pub struct ApprovalRequest {
|
||||
pub client: ClientInfo,
|
||||
pub request: Request,
|
||||
pub reply: Sender<Decision>,
|
||||
}
|
||||
|
||||
/// The handle the responder uses to ask the user.
|
||||
#[derive(Clone)]
|
||||
pub struct Approver {
|
||||
inbox: Sender<ApprovalRequest>,
|
||||
}
|
||||
|
||||
impl Approver {
|
||||
/// Create an approver and the receiver the UI must drain.
|
||||
pub fn new() -> (Self, Receiver<ApprovalRequest>) {
|
||||
let (inbox, questions) = async_channel::unbounded();
|
||||
(Self { inbox }, questions)
|
||||
}
|
||||
|
||||
/// Ask, and treat a timeout or a missing UI as a denial.
|
||||
pub async fn ask(&self, client: ClientInfo, request: Request) -> Decision {
|
||||
let (reply, answer) = bounded(1);
|
||||
let question = ApprovalRequest {
|
||||
client,
|
||||
request,
|
||||
reply,
|
||||
};
|
||||
if self.inbox.send(question).await.is_err() {
|
||||
return Decision::Deny;
|
||||
}
|
||||
match tokio::time::timeout(ASK_TIMEOUT, answer.recv()).await {
|
||||
Ok(Ok(decision)) => decision,
|
||||
_ => Decision::Deny,
|
||||
}
|
||||
}
|
||||
}
|
||||
+172
-53
@@ -8,7 +8,7 @@
|
||||
//! arrives in M3 and per-request approval in M4, so nothing here should be
|
||||
//! presented as a working signer yet.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -16,8 +16,12 @@ use nostr::nips::{nip04, nip44};
|
||||
use nostr::prelude::*;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use self::approval::{Approver, ClientInfo, Decision, Request};
|
||||
use crate::store::apps::AppRegistry;
|
||||
use crate::store::keys::KeyStore;
|
||||
|
||||
pub mod approval;
|
||||
|
||||
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
@@ -30,10 +34,19 @@ pub struct SignerConfig {
|
||||
/// The value a client must present in `connect`. Rotating it invalidates
|
||||
/// previously handed-out connection strings.
|
||||
pub secret: String,
|
||||
/// Asks the user; M4 will use it for every sensitive request.
|
||||
pub approver: Approver,
|
||||
/// Which applications have been approved.
|
||||
pub registry: Arc<Mutex<AppRegistry>>,
|
||||
}
|
||||
|
||||
impl SignerConfig {
|
||||
pub async fn from_store(store: &KeyStore, relays: Vec<String>) -> Result<Self> {
|
||||
pub async fn from_store(
|
||||
store: &KeyStore,
|
||||
relays: Vec<String>,
|
||||
approver: Approver,
|
||||
registry: Arc<Mutex<AppRegistry>>,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
device_keys: store.device_key().await?,
|
||||
user_keys: store
|
||||
@@ -42,6 +55,8 @@ impl SignerConfig {
|
||||
.ok_or("no identity key is stored")?,
|
||||
relays,
|
||||
secret: random_secret(),
|
||||
approver,
|
||||
registry,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -122,7 +137,7 @@ impl Signer {
|
||||
if event.kind != Kind::NostrConnect {
|
||||
continue;
|
||||
}
|
||||
match handle_request(&event, &config) {
|
||||
match handle_request(&event, &config).await {
|
||||
Ok(Some(response)) => {
|
||||
// Responses go back to the relays the clients use,
|
||||
// again bypassing gossip routing.
|
||||
@@ -201,8 +216,7 @@ fn random_secret() -> String {
|
||||
/// The envelope is parsed by hand: rust-nostr's typed NIP-46 request cannot
|
||||
/// represent a spec-shaped `sign_event` (it expects a full event with
|
||||
/// `pubkey`/`id`/`sig`, which is not what clients send).
|
||||
fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>> {
|
||||
let plain = match nip44::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)
|
||||
async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>> { let plain = match nip44::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)
|
||||
{
|
||||
Ok(plain) => plain,
|
||||
Err(_) => nip04::decrypt(config.device_keys.secret_key(), &event.pubkey, &event.content)?,
|
||||
@@ -223,13 +237,37 @@ fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>>
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
// Everything except pairing requires an application the user has approved;
|
||||
// bootstrapping happens through `connect`, which asks.
|
||||
let approved = config.registry.lock().unwrap().contains(&event.pubkey);
|
||||
if method != "connect" && !approved {
|
||||
return respond(
|
||||
config,
|
||||
event,
|
||||
&id,
|
||||
Err(format!("{method}: this application has not been approved")),
|
||||
);
|
||||
}
|
||||
|
||||
let result: std::result::Result<String, String> = match method {
|
||||
"connect" => {
|
||||
let presented = params.get(1).cloned().unwrap_or_default();
|
||||
if presented == config.secret {
|
||||
if presented != config.secret {
|
||||
Err("unauthorized".to_string())
|
||||
} else if approved {
|
||||
Ok("ack".to_string())
|
||||
} else {
|
||||
Err("unauthorized".to_string())
|
||||
let client = client_info(&event.pubkey, ¶ms);
|
||||
match config.approver.ask(client.clone(), Request::Pair).await {
|
||||
Decision::Deny => Err("the user declined the connection".to_string()),
|
||||
_ => config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&client)
|
||||
.map(|()| "ack".to_string())
|
||||
.map_err(|error| format!("could not record the approval: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
"get_public_key" => Ok(config.user_keys.public_key().to_hex()),
|
||||
@@ -277,13 +315,22 @@ fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>>
|
||||
other => Err(format!("unsupported method: {other}")),
|
||||
};
|
||||
|
||||
respond(config, event, &id, result)
|
||||
}
|
||||
|
||||
/// Build the answer: NIP-44 encrypted (what both go-nostr and rust-nostr
|
||||
/// expect), p-tagging the client, signed with the device key.
|
||||
fn respond(
|
||||
config: &SignerConfig,
|
||||
event: &Event,
|
||||
id: &str,
|
||||
result: std::result::Result<String, String>,
|
||||
) -> Result<Option<Event>> {
|
||||
let payload = match result {
|
||||
Ok(result) => serde_json::json!({ "id": id, "result": result }),
|
||||
Err(error) => serde_json::json!({ "id": id, "error": error }),
|
||||
};
|
||||
|
||||
// Responses are always NIP-44 (what both go-nostr and rust-nostr expect),
|
||||
// p-tag the client, and are signed with the device key.
|
||||
let content = nip44::encrypt(
|
||||
config.device_keys.secret_key(),
|
||||
&event.pubkey,
|
||||
@@ -300,6 +347,26 @@ fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<Event>>
|
||||
Ok(Some(config.device_keys.sign_event(unsigned)?))
|
||||
}
|
||||
|
||||
/// The client metadata from a `connect` request, if it sent any.
|
||||
///
|
||||
/// This is client-supplied and unauthenticated: display it, never trust it.
|
||||
fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
|
||||
let metadata: Option<serde_json::Value> =
|
||||
params.get(3).and_then(|raw| serde_json::from_str(raw).ok());
|
||||
let field = |name: &str| {
|
||||
metadata
|
||||
.as_ref()
|
||||
.and_then(|value| value[name].as_str())
|
||||
.map(str::to_string)
|
||||
};
|
||||
ClientInfo {
|
||||
public_key: *public_key,
|
||||
name: field("name"),
|
||||
url: field("url"),
|
||||
image: field("image"),
|
||||
}
|
||||
}
|
||||
|
||||
fn sign_event(
|
||||
raw: Option<&String>,
|
||||
user_keys: &Keys,
|
||||
@@ -345,66 +412,96 @@ fn payload(params: &[String]) -> &str {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The responder, driven by `nak` (an independent NIP-46 client) over either
|
||||
/// a local in-memory relay or, with `REGENT_TEST_RELAY=wss://…`, a real one.
|
||||
/// Ignored by default because it needs `nak` and network access:
|
||||
///
|
||||
/// ```sh
|
||||
/// CARGO_TARGET_DIR=_build/cargo-target cargo test --release -- --ignored --nocapture
|
||||
/// CARGO_TARGET_DIR=_build/cargo-target REGENT_TEST_RELAY=wss://nostr.kosmos.org \
|
||||
/// cargo test --release -- --ignored --nocapture
|
||||
/// ```
|
||||
#[tokio::test]
|
||||
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
|
||||
async fn nak_can_pair_and_sign() {
|
||||
const PORT: u16 = 10566;
|
||||
/// The relay to test against: `REGENT_TEST_RELAY`, or a local `nak serve`.
|
||||
struct TestRelay {
|
||||
relay: String,
|
||||
child: Option<std::process::Child>,
|
||||
}
|
||||
|
||||
let relay;
|
||||
let mut serving = None;
|
||||
match std::env::var("REGENT_TEST_RELAY").ok().filter(|url| !url.is_empty()) {
|
||||
Some(url) => {
|
||||
eprintln!("using the relay from REGENT_TEST_RELAY: {url}");
|
||||
relay = url;
|
||||
}
|
||||
None => {
|
||||
serving = Some(
|
||||
std::process::Command::new("nak")
|
||||
impl TestRelay {
|
||||
async fn start() -> Self {
|
||||
match std::env::var("REGENT_TEST_RELAY").ok().filter(|url| !url.is_empty()) {
|
||||
Some(relay) => {
|
||||
eprintln!("using the relay from REGENT_TEST_RELAY: {relay}");
|
||||
Self { relay, child: None }
|
||||
}
|
||||
None => {
|
||||
const PORT: u16 = 10566;
|
||||
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"),
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
|
||||
relay = format!("ws://127.0.0.1:{PORT}");
|
||||
.expect("spawn nak serve");
|
||||
tokio::time::sleep(Duration::from_millis(800)).await;
|
||||
Self {
|
||||
relay: format!("ws://127.0.0.1:{PORT}"),
|
||||
child: Some(child),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let config = SignerConfig {
|
||||
fn stop(&mut self) {
|
||||
if let Some(child) = &mut self.child {
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers every question the same way, standing in for the UI.
|
||||
fn auto_approver(decision: Decision) -> (Approver, tokio::task::JoinHandle<()>) {
|
||||
let (approver, questions) = Approver::new();
|
||||
let handle = tokio::spawn(async move {
|
||||
while let Ok(question) = questions.recv().await {
|
||||
let _ = question.reply.send(decision).await;
|
||||
}
|
||||
});
|
||||
(approver, handle)
|
||||
}
|
||||
|
||||
fn config(relay: &str, approver: Approver) -> SignerConfig {
|
||||
SignerConfig {
|
||||
device_keys: Keys::generate(),
|
||||
user_keys: Keys::generate(),
|
||||
relays: vec![relay],
|
||||
relays: vec![relay.to_string()],
|
||||
secret: "test-secret".to_string(),
|
||||
};
|
||||
approver,
|
||||
registry: Arc::new(Mutex::new(AppRegistry::default())),
|
||||
}
|
||||
}
|
||||
|
||||
async fn nak_signs(uri: &str) -> std::process::Output {
|
||||
tokio::process::Command::new("nak")
|
||||
.args(["event", "--sec", uri, "-c", "hello from nak through regent"])
|
||||
.output()
|
||||
.await
|
||||
.expect("run nak")
|
||||
}
|
||||
|
||||
/// The point of the responder: an independent NIP-46 client pairs, and the
|
||||
/// event comes back signed by the identity key rather than the device key.
|
||||
///
|
||||
/// Ignored by default because it needs `nak` and a relay:
|
||||
/// ```sh
|
||||
/// CARGO_TARGET_DIR=_build/cargo-target cargo test --release -- --ignored --nocapture
|
||||
/// CARGO_TARGET_DIR=_build/cargo-target REGENT_TEST_RELAY=wss://nostr.kosmos.org \
|
||||
/// cargo test --release -- --ignored --nocapture nak_can_pair_and_sign
|
||||
/// ```
|
||||
#[tokio::test]
|
||||
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
|
||||
async fn nak_can_pair_and_sign() {
|
||||
let mut relay = TestRelay::start().await;
|
||||
let (approver, approvals) = auto_approver(Decision::Always);
|
||||
let config = config(&relay.relay, approver);
|
||||
let expected = config.user_keys.public_key();
|
||||
let signer = Signer::start(config).await.expect("start signer");
|
||||
|
||||
let output = tokio::process::Command::new("nak")
|
||||
.args([
|
||||
"event",
|
||||
"--sec",
|
||||
signer.bunker_uri(),
|
||||
"-c",
|
||||
"hello from nak through regent",
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.expect("run nak");
|
||||
let output = nak_signs(signer.bunker_uri()).await;
|
||||
|
||||
if let Some(mut child) = serving {
|
||||
let _ = child.kill();
|
||||
}
|
||||
relay.stop();
|
||||
signer.stop().await;
|
||||
approvals.abort();
|
||||
|
||||
assert!(
|
||||
output.status.success(),
|
||||
@@ -419,4 +516,26 @@ mod tests {
|
||||
"the event must be signed by the identity key, not the device key"
|
||||
);
|
||||
}
|
||||
|
||||
/// Saying no has to mean no: the client must not be able to pair.
|
||||
#[tokio::test]
|
||||
#[ignore = "needs nak, and either a free port or REGENT_TEST_RELAY"]
|
||||
async fn pairing_is_refused_when_the_user_says_no() {
|
||||
let mut relay = TestRelay::start().await;
|
||||
let (approver, approvals) = auto_approver(Decision::Deny);
|
||||
let config = config(&relay.relay, approver);
|
||||
let signer = Signer::start(config).await.expect("start signer");
|
||||
|
||||
let output = nak_signs(signer.bunker_uri()).await;
|
||||
|
||||
relay.stop();
|
||||
signer.stop().await;
|
||||
approvals.abort();
|
||||
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"nak should not have been able to pair: {}",
|
||||
String::from_utf8_lossy(&output.stdout)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! The registry of applications the user has approved.
|
||||
//!
|
||||
//! Not secret, so it is a plain JSON file under the config directory — unlike
|
||||
//! the keys, which live in the keyring.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use nostr::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::signer::approval::ClientInfo;
|
||||
use crate::APP_ID;
|
||||
|
||||
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// An application that may ask this signer for things.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct App {
|
||||
/// Client public key, hex.
|
||||
pub public_key: String,
|
||||
/// Self-declared by the client; a hint, not a fact.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub image: Option<String>,
|
||||
/// Unix timestamp of when it was approved.
|
||||
pub approved_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
pub struct AppRegistry {
|
||||
#[serde(default)]
|
||||
pub apps: Vec<App>,
|
||||
}
|
||||
|
||||
impl AppRegistry {
|
||||
pub fn path() -> PathBuf {
|
||||
glib::user_config_dir().join(APP_ID).join("apps.json")
|
||||
}
|
||||
|
||||
/// Load from disk; a missing or unreadable file is simply an empty registry
|
||||
/// (denying everything is the safe failure).
|
||||
pub fn load() -> Self {
|
||||
let path = Self::path();
|
||||
match std::fs::read_to_string(&path) {
|
||||
Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|error| {
|
||||
eprintln!("regent: ignoring unreadable {}: {error}", path.display());
|
||||
Self::default()
|
||||
}),
|
||||
Err(_) => Self::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) -> Result<()> {
|
||||
let path = Self::path();
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
std::fs::write(&path, serde_json::to_string_pretty(self)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn contains(&self, public_key: &PublicKey) -> bool {
|
||||
let hex = public_key.to_hex();
|
||||
self.apps.iter().any(|app| app.public_key == hex)
|
||||
}
|
||||
|
||||
/// Record an approval. Metadata is whatever the client declared.
|
||||
pub fn approve(&mut self, client: &ClientInfo) -> Result<()> {
|
||||
let public_key = client.public_key.to_hex();
|
||||
self.apps.retain(|app| app.public_key != public_key);
|
||||
self.apps.push(App {
|
||||
public_key,
|
||||
name: client.name.clone(),
|
||||
url: client.url.clone(),
|
||||
image: client.image.clone(),
|
||||
approved_at: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|since| since.as_secs() as i64)
|
||||
.unwrap_or_default(),
|
||||
});
|
||||
self.save()
|
||||
}
|
||||
|
||||
/// Forget an approved application, and list what is approved. Both are
|
||||
/// wired up by the apps page in M5.
|
||||
#[allow(dead_code)]
|
||||
pub fn revoke(&mut self, public_key: &PublicKey) -> Result<()> {
|
||||
let hex = public_key.to_hex();
|
||||
self.apps.retain(|app| app.public_key != hex);
|
||||
self.save()
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn list(&self) -> &[App] {
|
||||
&self.apps
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
//! Persistent state: the keyring today, the application registry later.
|
||||
|
||||
pub mod apps;
|
||||
pub mod keys;
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Showing approval questions and turning the answer into a `Decision`.
|
||||
|
||||
use async_channel::Receiver;
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
use crate::signer::approval::{ApprovalRequest, Decision, Request};
|
||||
|
||||
/// Start draining questions: each one becomes a dialog, and the answer goes back
|
||||
/// to the responder. Anything unanswered is a denial.
|
||||
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 _ = question.reply.send(decision).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn present(widget: >k::Widget, question: &ApprovalRequest) -> Decision {
|
||||
let client = &question.client;
|
||||
let name = client
|
||||
.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| "An unnamed application".to_string());
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title(match &question.request {
|
||||
Request::Pair => format!("Connect {name}?"),
|
||||
Request::Sign { .. } => format!("Sign for {name}?"),
|
||||
Request::Encrypt { .. } => format!("Encrypt for {name}?"),
|
||||
Request::Decrypt { .. } => format!("Decrypt for {name}?"),
|
||||
})
|
||||
.body(describe(question))
|
||||
.build();
|
||||
|
||||
dialog.add_response("deny", "Deny");
|
||||
dialog.add_response("allow", "Allow");
|
||||
dialog.set_default_response(Some("allow"));
|
||||
dialog.set_response_appearance("allow", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("deny");
|
||||
|
||||
let (sender, answer) = async_channel::bounded(1);
|
||||
// For a pairing, "allow" means remember the application; for everything else
|
||||
// it is a one-off decision.
|
||||
let pairing = matches!(question.request, Request::Pair);
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
let decision = match response {
|
||||
"allow" if pairing => Decision::Always,
|
||||
"allow" => Decision::Once,
|
||||
_ => Decision::Deny,
|
||||
};
|
||||
let _ = sender.try_send(decision);
|
||||
});
|
||||
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
|
||||
|
||||
// Dropped without an answer (window closed, app gone) is a denial.
|
||||
answer.recv().await.unwrap_or(Decision::Deny)
|
||||
}
|
||||
|
||||
fn describe(question: &ApprovalRequest) -> String {
|
||||
let client = &question.client;
|
||||
let mut lines = Vec::new();
|
||||
|
||||
match &question.request {
|
||||
Request::Pair => lines.push(
|
||||
"It will be able to ask for signatures and to encrypt or decrypt messages in \
|
||||
your name."
|
||||
.to_string(),
|
||||
),
|
||||
Request::Sign { kind, preview } => {
|
||||
lines.push(format!("Kind {kind}"));
|
||||
if !preview.is_empty() {
|
||||
lines.push(preview.clone());
|
||||
}
|
||||
}
|
||||
Request::Encrypt { peer } => lines.push(format!("Encrypting to {peer}")),
|
||||
Request::Decrypt { peer } => lines.push(format!("Decrypting from {peer}")),
|
||||
}
|
||||
|
||||
lines.push(String::new());
|
||||
lines.push(format!(
|
||||
"Public key: {}",
|
||||
client.public_key.to_bech32().unwrap_or_default()
|
||||
));
|
||||
if let Some(url) = &client.url {
|
||||
lines.push(format!("Declared URL: {url}"));
|
||||
}
|
||||
lines.push(String::new());
|
||||
lines.push(
|
||||
"The name and URL above are supplied by the application itself and cannot be \
|
||||
trusted."
|
||||
.to_string(),
|
||||
);
|
||||
|
||||
lines.join("\n")
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! User interface.
|
||||
|
||||
pub mod approval;
|
||||
pub mod keys_view;
|
||||
pub mod qr;
|
||||
pub mod signer_view;
|
||||
+34
-8
@@ -2,7 +2,10 @@
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::signer::approval::Approver;
|
||||
use crate::store::apps::AppRegistry;
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
|
||||
@@ -126,6 +129,12 @@ impl SignerView {
|
||||
|
||||
let widget: gtk::Widget = handles.stack.clone().upcast();
|
||||
|
||||
// Approval questions are answered on the main loop; the responder waits
|
||||
// on the other end of this channel.
|
||||
let (approver, questions) = Approver::new();
|
||||
crate::ui::approval::install(questions, widget.clone());
|
||||
let registry = Arc::new(Mutex::new(AppRegistry::load()));
|
||||
|
||||
let running: Running = Rc::new(RefCell::new(None));
|
||||
|
||||
{
|
||||
@@ -142,11 +151,18 @@ impl SignerView {
|
||||
|
||||
{
|
||||
let (handles, state, running) = (handles.clone(), Rc::clone(&state), Rc::clone(&running));
|
||||
let (approver, registry) = (approver.clone(), Arc::clone(®istry));
|
||||
handles.toggle.clone().connect_clicked(move |_| {
|
||||
if running.borrow().is_some() {
|
||||
stop(handles.clone(), Rc::clone(&running));
|
||||
} else {
|
||||
start(handles.clone(), Rc::clone(&state), Rc::clone(&running));
|
||||
start(
|
||||
handles.clone(),
|
||||
Rc::clone(&state),
|
||||
Rc::clone(&running),
|
||||
approver.clone(),
|
||||
Arc::clone(®istry),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -156,6 +172,8 @@ impl SignerView {
|
||||
let handles = handles.clone();
|
||||
let signer_running = Rc::clone(&running);
|
||||
let listener_state = Rc::clone(&state);
|
||||
let listener_approver = approver.clone();
|
||||
let listener_registry = Arc::clone(®istry);
|
||||
state.listen(move || {
|
||||
let Some(store) = listener_state.store() else {
|
||||
return;
|
||||
@@ -168,10 +186,12 @@ impl SignerView {
|
||||
Rc::clone(&listener_state),
|
||||
Rc::clone(&signer_running),
|
||||
);
|
||||
let (approver, registry) =
|
||||
(listener_approver.clone(), Arc::clone(&listener_registry));
|
||||
runtime::spawn(
|
||||
async move { store.user_key().await },
|
||||
move |result| match result {
|
||||
Ok(Some(_)) => start(handles, state, running),
|
||||
Ok(Some(_)) => start(handles, state, running, approver, registry),
|
||||
Ok(None) => show_empty(&handles),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
@@ -193,7 +213,13 @@ fn show_empty(handles: &Handles) {
|
||||
handles.banner.set_revealed(true);
|
||||
}
|
||||
|
||||
fn start(handles: Handles, state: Rc<AppState>, running: Running) {
|
||||
fn start(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
running: Running,
|
||||
approver: Approver,
|
||||
registry: Arc<Mutex<AppRegistry>>,
|
||||
) {
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
@@ -201,7 +227,7 @@ fn start(handles: Handles, state: Rc<AppState>, running: Running) {
|
||||
|
||||
runtime::spawn(
|
||||
async move {
|
||||
let config = SignerConfig::from_store(&store, relays).await?;
|
||||
let config = SignerConfig::from_store(&store, relays, approver, registry).await?;
|
||||
Signer::start(config).await
|
||||
},
|
||||
move |result| match result {
|
||||
@@ -257,9 +283,9 @@ fn show_running(handles: &Handles, signer: &Signer) {
|
||||
}
|
||||
|
||||
// Loud on purpose: until M4 every request is answered without asking.
|
||||
handles
|
||||
.banner
|
||||
.set_title("Approval is not implemented yet — every request is currently allowed");
|
||||
handles.banner.set_title(
|
||||
"Approved applications can sign anything without asking yet — per-request approval arrives next",
|
||||
);
|
||||
handles.banner.set_revealed(true);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user