Add multiple identity keys with per-app binding
This commit is contained in:
14 files changed
+1632
-401
No files matched your search
@@ -11,6 +11,11 @@
|
||||
<summary>Window height</summary>
|
||||
<description>Height of the main window, in pixels.</description>
|
||||
</key>
|
||||
<key name="current-identity" type="s">
|
||||
<default>''</default>
|
||||
<summary>Current identity</summary>
|
||||
<description>The identity key selected in the UI, as hex. It scopes the Apps and Activity pages and is the default identity for new pairings. Empty means the first stored key.</description>
|
||||
</key>
|
||||
<key name="auto-approve-limit" type="i">
|
||||
<default>30</default>
|
||||
<summary>Auto-approval rate limit</summary>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
use gtk::gio;
|
||||
use gtk::prelude::*;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use crate::APP_ID;
|
||||
|
||||
@@ -25,6 +26,24 @@ impl Config {
|
||||
self.settings.int("window-height")
|
||||
}
|
||||
|
||||
/// The identity selected in the UI: it scopes the Apps/Activity pages and
|
||||
/// is the default for new pairings. `None` means "the first stored key".
|
||||
pub fn current_identity(&self) -> Option<PublicKey> {
|
||||
let hex = self.settings.string("current-identity");
|
||||
if hex.is_empty() {
|
||||
None
|
||||
} else {
|
||||
PublicKey::from_hex(hex.as_str()).ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_current_identity(&self, identity: Option<PublicKey>) {
|
||||
let value = identity.map(|key| key.to_hex()).unwrap_or_default();
|
||||
if let Err(error) = self.settings.set_string("current-identity", &value) {
|
||||
eprintln!("regent: could not save the selected identity: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// How many requests per minute a stored "always" permission may answer
|
||||
/// silently, per application, before Regent asks again.
|
||||
pub fn auto_approve_limit(&self) -> u32 {
|
||||
|
||||
+46
-13
@@ -8,10 +8,12 @@
|
||||
//! Deliberately not a `GtkApplication`: headless must work with no display, and
|
||||
//! nothing here needs GTK. It is a plain tokio program.
|
||||
|
||||
use std::collections::HashMap;
|
||||
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;
|
||||
@@ -22,9 +24,10 @@ use crate::store::audit::ActivityLog;
|
||||
use crate::store::keys::KeyStore;
|
||||
use crate::APP_ID;
|
||||
|
||||
/// Run headless. `pair` is a `nostrconnect://` URI when `--pair` was given.
|
||||
pub fn run(pair: Option<String>) -> glib::ExitCode {
|
||||
match runtime::block_on(serve(pair.as_deref())) {
|
||||
/// Run headless. `pair` is a `nostrconnect://` URI when `--pair` was given;
|
||||
/// `key` selects the identity that pairing is bound to.
|
||||
pub fn run(pair: Option<String>, key: Option<String>) -> glib::ExitCode {
|
||||
match runtime::block_on(serve(pair.as_deref(), key.as_deref())) {
|
||||
Ok(()) => glib::ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
eprintln!("regent: {error}");
|
||||
@@ -33,7 +36,7 @@ pub fn run(pair: Option<String>) -> glib::ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
async fn serve(pair: Option<&str>, key: Option<&str>) -> Result<(), String> {
|
||||
// Two signers on one device key would both answer and would overwrite each
|
||||
// other's apps.json. The GUI owns this name; refuse to run alongside it.
|
||||
if another_instance_running()? {
|
||||
@@ -49,17 +52,41 @@ async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
let store = KeyStore::connect()
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
if store
|
||||
.user_key()
|
||||
let stored = store
|
||||
.list_user_keys()
|
||||
.await
|
||||
.map_err(|error| error.to_string())?
|
||||
.is_none()
|
||||
{
|
||||
.map_err(|error| error.to_string())?;
|
||||
if stored.is_empty() {
|
||||
return Err(
|
||||
"no identity key is stored; create or import one in the GUI first".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let settings = Config::new();
|
||||
// `--key` picks the identity for `--pair`; otherwise the UI's selection, then
|
||||
// the first stored key.
|
||||
let identity = match key {
|
||||
Some(raw) => {
|
||||
let wanted = PublicKey::parse(raw.trim())
|
||||
.map_err(|error| format!("--key is not a valid public key: {error}"))?;
|
||||
if !stored.iter().any(|stored| stored.public_key == wanted) {
|
||||
return Err("--key: that identity key is not stored".to_string());
|
||||
}
|
||||
wanted
|
||||
}
|
||||
None => settings
|
||||
.current_identity()
|
||||
.filter(|wanted| stored.iter().any(|stored| stored.public_key == *wanted))
|
||||
.unwrap_or(stored[0].public_key),
|
||||
};
|
||||
|
||||
let names: HashMap<String, String> = stored
|
||||
.into_iter()
|
||||
.map(|stored| (stored.public_key.to_hex(), stored.name))
|
||||
.collect();
|
||||
let names = Arc::new(Mutex::new(names));
|
||||
let default_identity = Arc::new(Mutex::new(Some(identity)));
|
||||
|
||||
// No window: deny everything the user has not already allowed.
|
||||
let (approver, questions) = Approver::new();
|
||||
tokio::spawn(async move {
|
||||
@@ -68,20 +95,21 @@ async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
}
|
||||
});
|
||||
|
||||
let settings = Config::new();
|
||||
let registry = Arc::new(Mutex::new(AppRegistry::load()));
|
||||
let activity = ActivityLog::new();
|
||||
// Nobody drains this in headless mode; a full channel just coalesces.
|
||||
let (changes, _changes_rx) = async_channel::bounded(1);
|
||||
|
||||
let mut config = SignerConfig::from_store(
|
||||
&store,
|
||||
Arc::new(store),
|
||||
settings.relays(),
|
||||
approver,
|
||||
Arc::clone(®istry),
|
||||
settings.auto_approve_limit(),
|
||||
activity.clone(),
|
||||
changes.clone(),
|
||||
names,
|
||||
default_identity,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
@@ -104,7 +132,7 @@ async fn serve(pair: Option<&str>) -> Result<(), String> {
|
||||
);
|
||||
|
||||
if let Some(pairing) = &pairing {
|
||||
finish_pairing(&signer, ®istry, &activity, &changes, pairing).await?;
|
||||
finish_pairing(&signer, ®istry, &activity, &changes, pairing, identity).await?;
|
||||
}
|
||||
|
||||
wait_for_shutdown().await;
|
||||
@@ -120,8 +148,9 @@ async fn finish_pairing(
|
||||
activity: &ActivityLog,
|
||||
changes: &async_channel::Sender<()>,
|
||||
pairing: &ClientPairing,
|
||||
identity: PublicKey,
|
||||
) -> Result<(), String> {
|
||||
crate::signer::pair_client(signer, registry, activity, changes, pairing)
|
||||
crate::signer::pair_client(signer, registry, activity, changes, pairing, identity)
|
||||
.await
|
||||
.map_err(|error| format!("pairing failed: {error}"))?;
|
||||
|
||||
@@ -138,6 +167,10 @@ async fn finish_pairing(
|
||||
"regent: paired with {name} ({}){asked}",
|
||||
pairing.client.to_bech32().unwrap_or_default()
|
||||
);
|
||||
println!(
|
||||
"regent: signing as {}",
|
||||
identity.to_bech32().unwrap_or_default()
|
||||
);
|
||||
println!(
|
||||
"regent: headless mode denies anything not covered by a stored permission; \
|
||||
approve permissions in the GUI first"
|
||||
|
||||
+27
-11
@@ -22,7 +22,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const USAGE: &str = "\
|
||||
Regent — a Nostr remote signer (NIP-46) for GNOME
|
||||
|
||||
Usage: regent [--headless] [--pair <uri>]
|
||||
Usage: regent [--headless] [--pair <uri>] [--key <npub|hex>]
|
||||
regent --version
|
||||
regent --help
|
||||
|
||||
@@ -31,6 +31,8 @@ Options:
|
||||
with \"Allow always\" is denied, so pre-approve in the GUI first
|
||||
--pair <uri> pair with a client from its nostrconnect:// URI, then run
|
||||
headless
|
||||
--key <key> identity (npub or hex) that --pair binds the client to; the
|
||||
current identity is used when omitted
|
||||
--version, -V print the version and exit
|
||||
--help, -h print this help and exit
|
||||
|
||||
@@ -49,7 +51,7 @@ fn main() -> glib::ExitCode {
|
||||
return glib::ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
let (headless, pair) = match parse_args(&args) {
|
||||
let (headless, pair, key) = match parse_args(&args) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
eprintln!("regent: {error}");
|
||||
@@ -58,18 +60,20 @@ fn main() -> glib::ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
if headless || pair.is_some() {
|
||||
return headless::run(pair);
|
||||
if headless || pair.is_some() || key.is_some() {
|
||||
return headless::run(pair, key);
|
||||
}
|
||||
|
||||
register_resources();
|
||||
application::run()
|
||||
}
|
||||
|
||||
/// Parse the (few) arguments we accept: `--headless` and `--pair <uri>`.
|
||||
fn parse_args(args: &[String]) -> Result<(bool, Option<String>), String> {
|
||||
/// Parse the (few) arguments we accept: `--headless`, `--pair <uri>`,
|
||||
/// `--key <npub|hex>`.
|
||||
fn parse_args(args: &[String]) -> Result<(bool, Option<String>, Option<String>), String> {
|
||||
let mut headless = false;
|
||||
let mut pair = None;
|
||||
let mut key = None;
|
||||
let mut iter = args.iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
match arg.as_str() {
|
||||
@@ -84,13 +88,25 @@ fn parse_args(args: &[String]) -> Result<(bool, Option<String>), String> {
|
||||
}
|
||||
pair = Some(value);
|
||||
}
|
||||
_ => match arg.strip_prefix("--pair=") {
|
||||
Some(value) => pair = Some(value.to_string()),
|
||||
None => return Err(format!("unknown argument: {arg}")),
|
||||
},
|
||||
"--key" => {
|
||||
let value = iter.next().ok_or("--key needs an npub or hex key")?.clone();
|
||||
if value.starts_with('-') {
|
||||
return Err("--key needs an npub or hex key, not a flag".to_string());
|
||||
}
|
||||
key = Some(value);
|
||||
}
|
||||
_ => {
|
||||
if let Some(value) = arg.strip_prefix("--pair=") {
|
||||
pair = Some(value.to_string());
|
||||
} else if let Some(value) = arg.strip_prefix("--key=") {
|
||||
key = Some(value.to_string());
|
||||
} else {
|
||||
return Err(format!("unknown argument: {arg}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((headless, pair))
|
||||
Ok((headless, pair, key))
|
||||
}
|
||||
|
||||
/// Directories that may hold an installed copy of the GResource, in the order
|
||||
|
||||
+44
-28
@@ -25,6 +25,13 @@ pub struct ClientInfo {
|
||||
pub image: Option<String>,
|
||||
}
|
||||
|
||||
/// The identity key a request would act as.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SigningKey {
|
||||
pub public_key: PublicKey,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
/// What is being asked for.
|
||||
///
|
||||
/// Everything the dialog shows beyond the client identity is already reduced to
|
||||
@@ -39,7 +46,7 @@ pub enum Request {
|
||||
/// shown for context only; granting stays per-request.
|
||||
requested: Option<String>,
|
||||
},
|
||||
/// An event would be signed with the identity key.
|
||||
/// An event would be signed with an identity key.
|
||||
Sign {
|
||||
kind: u16,
|
||||
preview: String,
|
||||
@@ -77,10 +84,21 @@ pub enum Decision {
|
||||
Always,
|
||||
}
|
||||
|
||||
/// One question for the user, with the channel to answer on.
|
||||
pub struct ApprovalRequest {
|
||||
/// Everything the user is shown, and what the answer would apply to.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Question {
|
||||
pub client: ClientInfo,
|
||||
pub request: Request,
|
||||
/// The identity key this request would act as.
|
||||
pub identity: SigningKey,
|
||||
/// Set when a pairing would rebind an already-approved client to a different
|
||||
/// identity; its stored permissions are reset, and the dialog says so.
|
||||
pub rebind_from: Option<PublicKey>,
|
||||
}
|
||||
|
||||
/// One question for the user, with the channel to answer on.
|
||||
pub struct ApprovalRequest {
|
||||
pub question: Question,
|
||||
pub reply: Sender<Decision>,
|
||||
}
|
||||
|
||||
@@ -98,25 +116,16 @@ impl Approver {
|
||||
}
|
||||
|
||||
/// Ask, and treat a timeout or a missing UI as a denial.
|
||||
pub async fn ask(&self, client: ClientInfo, request: Request) -> Decision {
|
||||
self.ask_within(ASK_TIMEOUT, client, request).await
|
||||
pub async fn ask(&self, question: Question) -> Decision {
|
||||
self.ask_within(ASK_TIMEOUT, question).await
|
||||
}
|
||||
|
||||
/// The same, with an explicit deadline, so tests can exercise the timeout
|
||||
/// without waiting a minute.
|
||||
async fn ask_within(
|
||||
&self,
|
||||
within: Duration,
|
||||
client: ClientInfo,
|
||||
request: Request,
|
||||
) -> Decision {
|
||||
async fn ask_within(&self, within: Duration, question: Question) -> Decision {
|
||||
let (reply, answer) = bounded(1);
|
||||
let question = ApprovalRequest {
|
||||
client,
|
||||
request,
|
||||
reply,
|
||||
};
|
||||
if self.inbox.send(question).await.is_err() {
|
||||
let pending = ApprovalRequest { question, reply };
|
||||
if self.inbox.send(pending).await.is_err() {
|
||||
return Decision::Deny;
|
||||
}
|
||||
match tokio::time::timeout(within, answer.recv()).await {
|
||||
@@ -130,12 +139,22 @@ impl Approver {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn client() -> ClientInfo {
|
||||
ClientInfo {
|
||||
public_key: Keys::generate().public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
fn question(request: Request) -> Question {
|
||||
let client = Keys::generate();
|
||||
let identity = Keys::generate();
|
||||
Question {
|
||||
client: ClientInfo {
|
||||
public_key: client.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
},
|
||||
request,
|
||||
identity: SigningKey {
|
||||
public_key: identity.public_key(),
|
||||
name: None,
|
||||
},
|
||||
rebind_from: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,8 +172,7 @@ mod tests {
|
||||
let decision = approver
|
||||
.ask_within(
|
||||
Duration::from_millis(50),
|
||||
client(),
|
||||
Request::Pair { requested: None },
|
||||
question(Request::Pair { requested: None }),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(decision, Decision::Deny);
|
||||
@@ -167,9 +185,7 @@ mod tests {
|
||||
let (approver, questions) = Approver::new();
|
||||
let drain = tokio::spawn(async move { while questions.recv().await.is_ok() {} });
|
||||
assert_eq!(
|
||||
approver
|
||||
.ask(client(), Request::Pair { requested: None })
|
||||
.await,
|
||||
approver.ask(question(Request::Pair { requested: None })).await,
|
||||
Decision::Deny
|
||||
);
|
||||
drain.abort();
|
||||
|
||||
+442
-87
@@ -7,6 +7,7 @@
|
||||
//! Every sensitive request is put to the user (M4); "allow always" stores a
|
||||
//! per-app permission, and every answer is recorded in the activity log (M5).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
@@ -15,7 +16,7 @@ use nostr::nips::{nip04, nip44};
|
||||
use nostr::prelude::*;
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use self::approval::{Approver, ClientInfo, Decision, Request};
|
||||
use self::approval::{Approver, ClientInfo, Decision, Question, Request, SigningKey};
|
||||
use self::policy::RateLimiter;
|
||||
use crate::store::apps::{AppRegistry, Permission};
|
||||
use crate::store::audit::{self, ActivityLog, Entry};
|
||||
@@ -27,11 +28,80 @@ pub mod policy;
|
||||
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Where identity key secrets come from.
|
||||
///
|
||||
/// The store reads a key's secret **on demand**, only when a request actually
|
||||
/// needs it: keeping every identity's `nsec` in memory would widen the exposure
|
||||
/// window the split-key design exists to keep small.
|
||||
pub enum IdentityKeys {
|
||||
/// A single key, for tests.
|
||||
#[allow(dead_code)] // constructed by the test config only
|
||||
Fixed(Keys),
|
||||
/// Several in-memory keys, so tests can exercise per-app resolution.
|
||||
#[cfg(test)]
|
||||
Many(Vec<Keys>),
|
||||
Store(Arc<KeyStore>),
|
||||
}
|
||||
|
||||
impl IdentityKeys {
|
||||
pub async fn get(&self, public_key: &PublicKey) -> Result<Keys> {
|
||||
match self {
|
||||
Self::Fixed(keys) if keys.public_key() == *public_key => Ok(keys.clone()),
|
||||
Self::Fixed(_) => Err("that identity key is not available".into()),
|
||||
#[cfg(test)]
|
||||
Self::Many(keys) => keys
|
||||
.iter()
|
||||
.find(|keys| keys.public_key() == *public_key)
|
||||
.cloned()
|
||||
.ok_or_else(|| "that identity key is not available".into()),
|
||||
Self::Store(store) => store
|
||||
.user_key(public_key)
|
||||
.await?
|
||||
.ok_or_else(|| "that identity key is no longer stored".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The fallback identity when none is selected.
|
||||
pub async fn first(&self) -> Result<PublicKey> {
|
||||
match self {
|
||||
Self::Fixed(keys) => Ok(keys.public_key()),
|
||||
#[cfg(test)]
|
||||
Self::Many(keys) => keys
|
||||
.first()
|
||||
.map(Keys::public_key)
|
||||
.ok_or_else(|| "no identity key is stored".into()),
|
||||
Self::Store(store) => store
|
||||
.list_user_keys()
|
||||
.await?
|
||||
.first()
|
||||
.map(|key| key.public_key)
|
||||
.ok_or_else(|| "no identity key is stored".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn fixed_key(&self) -> Option<&Keys> {
|
||||
match self {
|
||||
Self::Fixed(keys) => Some(keys),
|
||||
#[cfg(test)]
|
||||
Self::Many(_) => None,
|
||||
Self::Store(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Everything the responder needs, so tests can supply keys directly instead of
|
||||
/// going through the keyring.
|
||||
pub struct SignerConfig {
|
||||
pub device_keys: Keys,
|
||||
pub user_keys: Keys,
|
||||
/// Identity keys, resolved per request.
|
||||
pub keys: IdentityKeys,
|
||||
/// Display names for the identity keys (hex → name), kept fresh by the UI.
|
||||
pub names: Arc<Mutex<HashMap<String, String>>>,
|
||||
/// The identity a **new** pairing is bound to. Shared with the UI; the
|
||||
/// responder only reads it in `connect`. It is never consulted for an
|
||||
/// existing app — that comes from the registry.
|
||||
pub default_identity: Arc<Mutex<Option<PublicKey>>>,
|
||||
pub relays: Vec<String>,
|
||||
/// The value a client must present in `connect`. Rotating it invalidates
|
||||
/// previously handed-out connection strings.
|
||||
@@ -53,21 +123,23 @@ pub struct SignerConfig {
|
||||
}
|
||||
|
||||
impl SignerConfig {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn from_store(
|
||||
store: &KeyStore,
|
||||
store: Arc<KeyStore>,
|
||||
relays: Vec<String>,
|
||||
approver: Approver,
|
||||
registry: Arc<Mutex<AppRegistry>>,
|
||||
auto_approve_limit: u32,
|
||||
activity: ActivityLog,
|
||||
changes: async_channel::Sender<()>,
|
||||
names: Arc<Mutex<HashMap<String, String>>>,
|
||||
default_identity: Arc<Mutex<Option<PublicKey>>>,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
device_keys: store.device_key().await?,
|
||||
user_keys: store
|
||||
.user_key()
|
||||
.await?
|
||||
.ok_or("no identity key is stored")?,
|
||||
keys: IdentityKeys::Store(store),
|
||||
names,
|
||||
default_identity,
|
||||
relays,
|
||||
secret: random_secret(),
|
||||
approver,
|
||||
@@ -87,6 +159,38 @@ impl SignerConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// The identity a new pairing is bound to: the UI's selection, else the first
|
||||
/// stored key.
|
||||
async fn pairing_identity(config: &SignerConfig) -> Result<PublicKey> {
|
||||
let selected = *config.default_identity.lock().unwrap();
|
||||
match selected {
|
||||
Some(identity) => Ok(identity),
|
||||
None => config.keys.first().await,
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`SigningKey`] for display, with the name if the UI has one.
|
||||
fn signing_key(config: &SignerConfig, public_key: PublicKey) -> SigningKey {
|
||||
let name = config
|
||||
.names
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&public_key.to_hex())
|
||||
.cloned();
|
||||
SigningKey { public_key, name }
|
||||
}
|
||||
|
||||
/// The identity a client is bound to. Read from the registry, never from the
|
||||
/// mutable default — that is what keeps `apps.json` the source of truth.
|
||||
fn app_identity(config: &SignerConfig, client: &PublicKey) -> std::result::Result<PublicKey, String> {
|
||||
config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.identity_for(client)
|
||||
.ok_or_else(|| "this application has no identity key".to_string())
|
||||
}
|
||||
|
||||
pub struct Signer {
|
||||
config: Arc<SignerConfig>,
|
||||
client: Client,
|
||||
@@ -384,19 +488,29 @@ pub async fn pair_client(
|
||||
activity: &ActivityLog,
|
||||
changes: &async_channel::Sender<()>,
|
||||
pairing: &ClientPairing,
|
||||
identity: PublicKey,
|
||||
) -> Result<()> {
|
||||
let was_approved = registry.lock().unwrap().contains(&pairing.client);
|
||||
registry.lock().unwrap().approve(&pairing.client_info())?;
|
||||
registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&pairing.client_info(), identity)?;
|
||||
|
||||
if let Err(error) = signer.complete_pairing(pairing).await {
|
||||
rollback_pairing(registry, &pairing.client, was_approved);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
eprintln!(
|
||||
"regent: paired {} as {}",
|
||||
pairing.client.to_bech32().unwrap_or_default(),
|
||||
identity.to_bech32().unwrap_or_default()
|
||||
);
|
||||
activity.record(&Entry {
|
||||
at: audit::now(),
|
||||
app: pairing.client.to_hex(),
|
||||
name: pairing.name.clone(),
|
||||
identity: Some(identity.to_hex()),
|
||||
method: "connect".to_string(),
|
||||
kind: None,
|
||||
outcome: audit::outcome::PAIRED.to_string(),
|
||||
@@ -527,33 +641,68 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
} else if presented != config.secret {
|
||||
Err("unauthorized".to_string())
|
||||
} else {
|
||||
let requested = requested_perms(¶ms);
|
||||
match config
|
||||
.approver
|
||||
.ask(client.clone(), Request::Pair { requested })
|
||||
.await
|
||||
{
|
||||
Decision::Deny => {
|
||||
record(config, &client, "connect", None, audit::outcome::DENIED);
|
||||
Err("the user declined the connection".to_string())
|
||||
}
|
||||
_ => {
|
||||
let result = config
|
||||
// Bind the new pairing to the current identity (or the first
|
||||
// stored key). The registry, never this default, is consulted
|
||||
// for requests afterwards.
|
||||
match pairing_identity(config).await {
|
||||
Err(error) => Err(error.to_string()),
|
||||
Ok(identity) => {
|
||||
let requested = requested_perms(¶ms);
|
||||
let rebind_from = config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&client)
|
||||
.map(|()| "ack".to_string())
|
||||
.map_err(|error| format!("could not record the approval: {error}"));
|
||||
if result.is_ok() {
|
||||
record(config, &client, "connect", None, audit::outcome::PAIRED);
|
||||
.identity_for(&event.pubkey)
|
||||
.filter(|previous| *previous != identity);
|
||||
let question = Question {
|
||||
client: client.clone(),
|
||||
request: Request::Pair { requested },
|
||||
identity: signing_key(config, identity),
|
||||
rebind_from,
|
||||
};
|
||||
match config.approver.ask(question).await {
|
||||
Decision::Deny => {
|
||||
record(
|
||||
config,
|
||||
&client,
|
||||
"connect",
|
||||
None,
|
||||
Some(&identity),
|
||||
audit::outcome::DENIED,
|
||||
);
|
||||
Err("the user declined the connection".to_string())
|
||||
}
|
||||
_ => {
|
||||
let result = config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&client, identity)
|
||||
.map(|()| "ack".to_string())
|
||||
.map_err(|error| {
|
||||
format!("could not record the approval: {error}")
|
||||
});
|
||||
if result.is_ok() {
|
||||
record(
|
||||
config,
|
||||
&client,
|
||||
"connect",
|
||||
None,
|
||||
Some(&identity),
|
||||
audit::outcome::PAIRED,
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"get_public_key" => Ok(config.user_keys.public_key().to_hex()),
|
||||
"get_public_key" => match app_identity(config, &event.pubkey) {
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => Ok(identity.to_hex()),
|
||||
},
|
||||
"get_relays" => {
|
||||
let relays: serde_json::Map<String, serde_json::Value> = config
|
||||
.relays
|
||||
@@ -580,6 +729,7 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
}
|
||||
// The client asks to be forgotten: drop the approval and its permissions.
|
||||
"logout" => {
|
||||
let identity = config.registry.lock().unwrap().identity_for(&event.pubkey);
|
||||
let result = config
|
||||
.registry
|
||||
.lock()
|
||||
@@ -589,61 +739,110 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
|
||||
.map_err(|error| error.to_string());
|
||||
// Only claim it in the log if it actually happened.
|
||||
if result.is_ok() {
|
||||
record(config, &client, "logout", None, audit::outcome::LOGGED_OUT);
|
||||
record(
|
||||
config,
|
||||
&client,
|
||||
"logout",
|
||||
None,
|
||||
identity.as_ref(),
|
||||
audit::outcome::LOGGED_OUT,
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
"sign_event" => match incoming(params.first()) {
|
||||
Err(error) => Err(error),
|
||||
Ok(incoming) => {
|
||||
let kind = incoming.kind.as_u16();
|
||||
let request = Request::Sign {
|
||||
kind,
|
||||
preview: preview(&incoming.content),
|
||||
tags: tag_summary(&incoming.tags),
|
||||
};
|
||||
let verdict = gate(config, &client, request, Some(Permission::Kind(kind))).await;
|
||||
record(config, &client, "sign_event", Some(kind), verdict.outcome());
|
||||
match verdict {
|
||||
Verdict::Deny => Err("the user declined to sign the event".to_string()),
|
||||
_ => sign(incoming, &config.user_keys),
|
||||
Ok(incoming) => match app_identity(config, &event.pubkey) {
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => {
|
||||
let kind = incoming.kind.as_u16();
|
||||
let request = Request::Sign {
|
||||
kind,
|
||||
preview: preview(&incoming.content),
|
||||
tags: tag_summary(&incoming.tags),
|
||||
};
|
||||
let verdict = gate(
|
||||
config,
|
||||
&client,
|
||||
identity,
|
||||
request,
|
||||
Some(Permission::Kind(kind)),
|
||||
)
|
||||
.await;
|
||||
record(
|
||||
config,
|
||||
&client,
|
||||
"sign_event",
|
||||
Some(kind),
|
||||
Some(&identity),
|
||||
verdict.outcome(),
|
||||
);
|
||||
match verdict {
|
||||
Verdict::Deny => Err("the user declined to sign the event".to_string()),
|
||||
_ => match config.keys.get(&identity).await {
|
||||
Err(error) => Err(error.to_string()),
|
||||
Ok(keys) => sign(incoming, &keys),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
m @ ("nip04_encrypt" | "nip44_encrypt") => match peer(¶ms) {
|
||||
Err(error) => Err(error),
|
||||
Ok(peer) => {
|
||||
let request = Request::Encrypt {
|
||||
method: nim_name(m),
|
||||
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
|
||||
preview: preview(payload(¶ms)),
|
||||
};
|
||||
let verdict =
|
||||
gate(config, &client, request, Some(Permission::Method(m.to_string()))).await;
|
||||
record(config, &client, m, None, verdict.outcome());
|
||||
match verdict {
|
||||
Verdict::Deny => Err("the user declined to encrypt the message".to_string()),
|
||||
_ => encrypt(m, config.user_keys.secret_key(), &peer, payload(¶ms)),
|
||||
Ok(peer) => match app_identity(config, &event.pubkey) {
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => {
|
||||
let request = Request::Encrypt {
|
||||
method: nim_name(m),
|
||||
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
|
||||
preview: preview(payload(¶ms)),
|
||||
};
|
||||
let verdict = gate(
|
||||
config,
|
||||
&client,
|
||||
identity,
|
||||
request,
|
||||
Some(Permission::Method(m.to_string())),
|
||||
)
|
||||
.await;
|
||||
record(config, &client, m, None, Some(&identity), verdict.outcome());
|
||||
match verdict {
|
||||
Verdict::Deny => {
|
||||
Err("the user declined to encrypt the message".to_string())
|
||||
}
|
||||
_ => match config.keys.get(&identity).await {
|
||||
Err(error) => Err(error.to_string()),
|
||||
Ok(keys) => encrypt(m, keys.secret_key(), &peer, payload(¶ms)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
m @ ("nip04_decrypt" | "nip44_decrypt") => match peer(¶ms) {
|
||||
Err(error) => Err(error),
|
||||
Ok(peer) => {
|
||||
// Decryption may never be answered without asking: no permission
|
||||
// is offered, so it always reaches the user.
|
||||
let request = Request::Decrypt {
|
||||
method: nim_name(m),
|
||||
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
|
||||
preview: preview(payload(¶ms)),
|
||||
};
|
||||
let verdict = gate(config, &client, request, None).await;
|
||||
record(config, &client, m, None, verdict.outcome());
|
||||
match verdict {
|
||||
Verdict::Deny => Err("the user declined to decrypt the message".to_string()),
|
||||
_ => decrypt(m, config.user_keys.secret_key(), &peer, payload(¶ms)),
|
||||
Ok(peer) => match app_identity(config, &event.pubkey) {
|
||||
Err(error) => Err(error),
|
||||
Ok(identity) => {
|
||||
// Decryption may never be answered without asking: no
|
||||
// permission is offered, so it always reaches the user.
|
||||
let request = Request::Decrypt {
|
||||
method: nim_name(m),
|
||||
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
|
||||
preview: preview(payload(¶ms)),
|
||||
};
|
||||
let verdict = gate(config, &client, identity, request, None).await;
|
||||
record(config, &client, m, None, Some(&identity), verdict.outcome());
|
||||
match verdict {
|
||||
Verdict::Deny => {
|
||||
Err("the user declined to decrypt the message".to_string())
|
||||
}
|
||||
_ => match config.keys.get(&identity).await {
|
||||
Err(error) => Err(error.to_string()),
|
||||
Ok(keys) => decrypt(m, keys.secret_key(), &peer, payload(¶ms)),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
other => Err(format!("unsupported method: {other}")),
|
||||
};
|
||||
@@ -679,6 +878,7 @@ impl Verdict {
|
||||
async fn gate(
|
||||
config: &SignerConfig,
|
||||
client: &ClientInfo,
|
||||
identity: PublicKey,
|
||||
request: Request,
|
||||
permission: Option<Permission>,
|
||||
) -> Verdict {
|
||||
@@ -693,7 +893,13 @@ async fn gate(
|
||||
}
|
||||
}
|
||||
|
||||
let decision = config.approver.ask(client.clone(), request).await;
|
||||
let question = Question {
|
||||
client: client.clone(),
|
||||
request,
|
||||
identity: signing_key(config, identity),
|
||||
rebind_from: None,
|
||||
};
|
||||
let decision = config.approver.ask(question).await;
|
||||
|
||||
// The user may have revoked the app while the dialog was open. Re-check
|
||||
// before acting, otherwise a revoked client still gets its answer.
|
||||
@@ -734,12 +940,14 @@ fn record(
|
||||
client: &ClientInfo,
|
||||
method: &str,
|
||||
kind: Option<u16>,
|
||||
identity: Option<&PublicKey>,
|
||||
outcome: &str,
|
||||
) {
|
||||
config.activity.record(&Entry {
|
||||
at: audit::now(),
|
||||
app: client.public_key.to_hex(),
|
||||
name: client.name.clone(),
|
||||
identity: identity.map(PublicKey::to_hex),
|
||||
method: method.to_string(),
|
||||
kind,
|
||||
outcome: outcome.to_string(),
|
||||
@@ -1060,8 +1268,8 @@ mod tests {
|
||||
let log = Arc::clone(&seen);
|
||||
let handle = tokio::spawn(async move {
|
||||
while let Ok(question) = questions.recv().await {
|
||||
let decision = decide(&question.request);
|
||||
log.lock().unwrap().push(question.request.clone());
|
||||
let decision = decide(&question.question.request);
|
||||
log.lock().unwrap().push(question.question.request.clone());
|
||||
let _ = question.reply.send(decision).await;
|
||||
}
|
||||
});
|
||||
@@ -1084,9 +1292,17 @@ mod tests {
|
||||
activity: ActivityLog,
|
||||
changes: async_channel::Sender<()>,
|
||||
) -> SignerConfig {
|
||||
let identity = Keys::generate();
|
||||
let identity_public = identity.public_key();
|
||||
let names = Arc::new(Mutex::new(HashMap::from([(
|
||||
identity_public.to_hex(),
|
||||
"Test identity".to_string(),
|
||||
)])));
|
||||
SignerConfig {
|
||||
device_keys: Keys::generate(),
|
||||
user_keys: Keys::generate(),
|
||||
keys: IdentityKeys::Fixed(identity),
|
||||
names,
|
||||
default_identity: Arc::new(Mutex::new(Some(identity_public))),
|
||||
relays: vec![relay.to_string()],
|
||||
secret: "test-secret".to_string(),
|
||||
approver,
|
||||
@@ -1098,6 +1314,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The single identity a test signer is configured with.
|
||||
fn user_public(config: &SignerConfig) -> PublicKey {
|
||||
config
|
||||
.keys
|
||||
.fixed_key()
|
||||
.expect("the test config has a fixed identity")
|
||||
.public_key()
|
||||
}
|
||||
|
||||
fn temp_log() -> (std::path::PathBuf, ActivityLog) {
|
||||
static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
@@ -1147,7 +1372,7 @@ mod tests {
|
||||
let mut relay = TestRelay::start().await;
|
||||
let (approver, approvals, seen) = recording_approver(|_| Decision::Always);
|
||||
let config = config(&relay.relay, approver);
|
||||
let expected = config.user_keys.public_key();
|
||||
let expected = user_public(&config);
|
||||
let signer = Signer::start(config).await.expect("start signer");
|
||||
|
||||
let output = nak_signs(signer.bunker_uri()).await;
|
||||
@@ -1450,7 +1675,7 @@ mod tests {
|
||||
let (approver, task, seen) = recording_approver(|_| Decision::Always);
|
||||
let config = config("ws://127.0.0.1:1", approver);
|
||||
let device = pair(&client, &config).await;
|
||||
let user = config.user_keys.public_key();
|
||||
let user = user_public(&config);
|
||||
let peer = client.public_key().to_hex();
|
||||
|
||||
// Encrypting twice: the first "always" stores the method, the second
|
||||
@@ -1831,12 +2056,15 @@ mod tests {
|
||||
let keys = Keys::generate();
|
||||
let mut registry = AppRegistry::default();
|
||||
registry
|
||||
.approve(&ClientInfo {
|
||||
public_key: keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.approve(
|
||||
&ClientInfo {
|
||||
public_key: keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
},
|
||||
keys.public_key(),
|
||||
)
|
||||
.unwrap();
|
||||
if let Some(kind) = kind {
|
||||
registry
|
||||
@@ -1879,7 +2107,7 @@ mod tests {
|
||||
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 expected = user_public(&config);
|
||||
|
||||
let client_keys = Keys::generate();
|
||||
// Approved, so `get_public_key` is answered rather than rejected.
|
||||
@@ -1887,12 +2115,15 @@ mod tests {
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(&ClientInfo {
|
||||
public_key: client_keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
})
|
||||
.approve(
|
||||
&ClientInfo {
|
||||
public_key: client_keys.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
},
|
||||
expected,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let signer = Signer::start(config).await.expect("start signer");
|
||||
@@ -1952,4 +2183,128 @@ mod tests {
|
||||
let answer = read_response(&response, &client_keys, &device);
|
||||
assert_eq!(answer["result"].as_str(), Some(expected.to_hex().as_str()));
|
||||
}
|
||||
|
||||
/// Two clients bound to different identities resolve to their own key.
|
||||
#[tokio::test]
|
||||
async fn clients_resolve_to_their_own_identity() {
|
||||
let (approver, task, _) = recording_approver(|_| Decision::Always);
|
||||
let identity_a = Keys::generate();
|
||||
let identity_b = Keys::generate();
|
||||
let (changes, _rx) = async_channel::unbounded();
|
||||
let mut config = config_with(
|
||||
"ws://127.0.0.1:1",
|
||||
approver,
|
||||
ActivityLog::at(std::path::PathBuf::new()),
|
||||
changes,
|
||||
);
|
||||
config.keys = IdentityKeys::Many(vec![identity_a.clone(), identity_b.clone()]);
|
||||
*config.default_identity.lock().unwrap() = Some(identity_a.public_key());
|
||||
let device = config.device_keys.public_key();
|
||||
|
||||
let client_a = Keys::generate();
|
||||
let client_b = Keys::generate();
|
||||
|
||||
// A pairs normally and is bound to the default identity (A).
|
||||
let request = client_request(
|
||||
&client_a,
|
||||
&device,
|
||||
"connect",
|
||||
serde_json::json!(["", config.secret, "", ""]),
|
||||
);
|
||||
handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
|
||||
// B is bound to the other identity.
|
||||
config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(
|
||||
&ClientInfo {
|
||||
public_key: client_b.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
},
|
||||
identity_b.public_key(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for (client, expected) in [
|
||||
(&client_a, identity_a.public_key()),
|
||||
(&client_b, identity_b.public_key()),
|
||||
] {
|
||||
let request =
|
||||
client_request(client, &device, "get_public_key", serde_json::json!([]));
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
let answer = read_response(&response, client, &device);
|
||||
assert_eq!(answer["result"].as_str(), Some(expected.to_hex().as_str()));
|
||||
}
|
||||
|
||||
// Signing uses the bound key, not the selected/default one.
|
||||
let request = client_request(&client_b, &device, "sign_event", sign_params(1, "hi"));
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
let answer = read_response(&response, &client_b, &device);
|
||||
let signed: serde_json::Value =
|
||||
serde_json::from_str(answer["result"].as_str().expect("a signature")).unwrap();
|
||||
task.abort();
|
||||
|
||||
assert_eq!(
|
||||
signed["pubkey"].as_str(),
|
||||
Some(identity_b.public_key().to_hex().as_str()),
|
||||
"the event must be signed by the identity this client is bound to"
|
||||
);
|
||||
}
|
||||
|
||||
/// A client bound to a key that is no longer available gets an error, never
|
||||
/// a signature from some other key.
|
||||
#[tokio::test]
|
||||
async fn a_missing_identity_key_is_an_error() {
|
||||
let (approver, task, _) = recording_approver(|_| Decision::Always);
|
||||
let present = Keys::generate();
|
||||
let missing = Keys::generate();
|
||||
let (changes, _rx) = async_channel::unbounded();
|
||||
let mut config = config_with(
|
||||
"ws://127.0.0.1:1",
|
||||
approver,
|
||||
ActivityLog::at(std::path::PathBuf::new()),
|
||||
changes,
|
||||
);
|
||||
config.keys = IdentityKeys::Many(vec![present]);
|
||||
let device = config.device_keys.public_key();
|
||||
let client = Keys::generate();
|
||||
config
|
||||
.registry
|
||||
.lock()
|
||||
.unwrap()
|
||||
.approve(
|
||||
&ClientInfo {
|
||||
public_key: client.public_key(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
},
|
||||
missing.public_key(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
|
||||
let response = handle_request(&request, &config)
|
||||
.await
|
||||
.expect("handle")
|
||||
.expect("an answer");
|
||||
let answer = read_response(&response, &client, &device);
|
||||
task.abort();
|
||||
|
||||
assert!(answer["error"].is_string(), "got {answer}");
|
||||
assert!(answer["result"].is_null());
|
||||
}
|
||||
}
|
||||
+148
-11
@@ -1,15 +1,20 @@
|
||||
//! Shared application state: the key store once it is connected, the
|
||||
//! application registry, the activity log, and a way for views to be told that
|
||||
//! something changed.
|
||||
//! application registry, the activity log, the selected identity, and a way for
|
||||
//! views to be told that something changed.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::runtime;
|
||||
use crate::store::apps::AppRegistry;
|
||||
use crate::store::audit::ActivityLog;
|
||||
use crate::store::keys::KeyStore;
|
||||
use crate::store::keys::{KeyRef, KeyStore};
|
||||
|
||||
type Listener = Rc<dyn Fn()>;
|
||||
|
||||
@@ -19,11 +24,15 @@ pub struct AppState {
|
||||
registry: Arc<Mutex<AppRegistry>>,
|
||||
/// Shared with the responder; cloning shares the file lock too.
|
||||
activity: ActivityLog,
|
||||
/// The identity selected in the UI. This is the default for **new**
|
||||
/// pairings only — an approved app keeps the identity stored in the
|
||||
/// registry.
|
||||
current: Arc<Mutex<Option<PublicKey>>>,
|
||||
/// Display names for the identity keys (hex → name), kept for dialogs.
|
||||
names: Arc<Mutex<HashMap<String, String>>>,
|
||||
listeners: RefCell<Vec<Listener>>,
|
||||
change_listeners: RefCell<Vec<Listener>>,
|
||||
/// The responder pings this after it changes the registry or the activity
|
||||
/// log. Bounded and coalescing: only the fact that something changed
|
||||
/// matters, and `try_send` never blocks a signature.
|
||||
/// The responder pings this after it changes the registry or the log.
|
||||
changes: async_channel::Sender<()>,
|
||||
}
|
||||
|
||||
@@ -35,6 +44,8 @@ impl AppState {
|
||||
store: RefCell::new(None),
|
||||
registry: Arc::new(Mutex::new(AppRegistry::load())),
|
||||
activity: ActivityLog::new(),
|
||||
current: Arc::new(Mutex::new(Config::new().current_identity())),
|
||||
names: Arc::new(Mutex::new(HashMap::new())),
|
||||
listeners: RefCell::new(Vec::new()),
|
||||
change_listeners: RefCell::new(Vec::new()),
|
||||
changes,
|
||||
@@ -52,8 +63,9 @@ impl AppState {
|
||||
let connecting = Rc::clone(&state);
|
||||
runtime::spawn(KeyStore::connect(), move |result| match result {
|
||||
Ok(store) => {
|
||||
*connecting.store.borrow_mut() = Some(Arc::new(store));
|
||||
connecting.notify();
|
||||
let store = Arc::new(store);
|
||||
*connecting.store.borrow_mut() = Some(Arc::clone(&store));
|
||||
connecting.refresh_identities();
|
||||
}
|
||||
Err(error) => eprintln!("regent: the keyring is unavailable: {error}"),
|
||||
});
|
||||
@@ -75,6 +87,76 @@ impl AppState {
|
||||
self.activity.clone()
|
||||
}
|
||||
|
||||
/// The currently selected identity (the default for new pairings).
|
||||
pub fn current_identity(&self) -> Option<PublicKey> {
|
||||
*self.current.lock().unwrap()
|
||||
}
|
||||
|
||||
/// The handle the responder reads to choose a pairing's identity.
|
||||
pub fn current_identity_handle(&self) -> Arc<Mutex<Option<PublicKey>>> {
|
||||
Arc::clone(&self.current)
|
||||
}
|
||||
|
||||
/// Key display names (hex → name), for approval dialogs.
|
||||
pub fn names(&self) -> Arc<Mutex<HashMap<String, String>>> {
|
||||
Arc::clone(&self.names)
|
||||
}
|
||||
|
||||
/// Select an identity: it scopes the UI and becomes the pairing default.
|
||||
pub fn set_current_identity(&self, identity: PublicKey) {
|
||||
*self.current.lock().unwrap() = Some(identity);
|
||||
Config::new().set_current_identity(Some(identity));
|
||||
eprintln!(
|
||||
"regent: selected identity {}",
|
||||
identity.to_bech32().unwrap_or_else(|_| identity.to_hex())
|
||||
);
|
||||
self.notify_changes();
|
||||
}
|
||||
|
||||
/// Re-read the identity list and selected key. Call after adding, renaming
|
||||
/// or removing a key, and when the store becomes available.
|
||||
pub fn refresh_identities(self: &Rc<Self>) {
|
||||
let Some(store) = self.store() else {
|
||||
return;
|
||||
};
|
||||
let configured = Config::new().current_identity();
|
||||
let state = Rc::clone(self);
|
||||
runtime::spawn(
|
||||
async move { store.list_user_keys().await },
|
||||
move |result| match result {
|
||||
Ok(keys) => {
|
||||
// The **live** selection wins over the setting snapshot: a
|
||||
// refresh started before the user picked a key must not
|
||||
// clobber that pick when it lands.
|
||||
let live = *state.current.lock().unwrap();
|
||||
let selected = resolve_selection(live, configured, &keys);
|
||||
let names = keys
|
||||
.iter()
|
||||
.map(|key| (key.public_key.to_hex(), key.name.clone()))
|
||||
.collect();
|
||||
*state.names.lock().unwrap() = names;
|
||||
*state.current.lock().unwrap() = selected;
|
||||
if selected != live {
|
||||
Config::new().set_current_identity(selected);
|
||||
}
|
||||
|
||||
// One-time migration: apps from before identities existed
|
||||
// are bound to the selected key, so nothing resolves against
|
||||
// a mutable default later.
|
||||
if let Some(identity) = selected {
|
||||
let registry = state.registry();
|
||||
if let Err(error) = registry.lock().unwrap().bind_legacy(identity) {
|
||||
eprintln!("regent: could not bind legacy applications: {error}");
|
||||
}
|
||||
}
|
||||
state.notify();
|
||||
state.notify_changes();
|
||||
}
|
||||
Err(error) => eprintln!("regent: could not read the identity keys: {error}"),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A sender the responder uses to announce registry or log changes.
|
||||
pub fn changes(&self) -> async_channel::Sender<()> {
|
||||
self.changes.clone()
|
||||
@@ -100,9 +182,7 @@ impl AppState {
|
||||
/// Register a listener for registry/activity changes. The registry is
|
||||
/// loaded at startup, so it always runs immediately.
|
||||
pub fn listen_changes(&self, listener: impl Fn() + 'static) {
|
||||
self.change_listeners
|
||||
.borrow_mut()
|
||||
.push(Rc::new(listener));
|
||||
self.change_listeners.borrow_mut().push(Rc::new(listener));
|
||||
self.notify_changes();
|
||||
}
|
||||
|
||||
@@ -113,3 +193,60 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which identity to keep selected after a refresh.
|
||||
///
|
||||
/// Prefer the **live** selection (a pick made while the refresh was in flight),
|
||||
/// then the persisted setting, then the first key. A key that no longer exists
|
||||
/// is skipped.
|
||||
fn resolve_selection(
|
||||
live: Option<PublicKey>,
|
||||
configured: Option<PublicKey>,
|
||||
keys: &[KeyRef],
|
||||
) -> Option<PublicKey> {
|
||||
let valid = |key: &PublicKey| keys.iter().any(|stored| stored.public_key == *key);
|
||||
live.filter(valid)
|
||||
.or_else(|| configured.filter(valid))
|
||||
.or_else(|| keys.first().map(|key| key.public_key))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use nostr::prelude::Keys;
|
||||
|
||||
fn key(name: &str) -> (KeyRef, PublicKey) {
|
||||
let public_key = Keys::generate().public_key();
|
||||
(
|
||||
KeyRef {
|
||||
public_key,
|
||||
name: name.to_string(),
|
||||
},
|
||||
public_key,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_selection_survives_a_refresh() {
|
||||
let (a, a_pk) = key("A");
|
||||
let (b, b_pk) = key("B");
|
||||
let keys = vec![a, b];
|
||||
// The user picked B while the refresh was in flight: it must win over
|
||||
// the stale setting snapshot.
|
||||
assert_eq!(
|
||||
resolve_selection(Some(b_pk), Some(a_pk), &keys),
|
||||
Some(b_pk)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_selection_falls_back_to_the_first_key() {
|
||||
let (a, a_pk) = key("A");
|
||||
let removed = Keys::generate().public_key();
|
||||
let keys = vec![a];
|
||||
assert_eq!(
|
||||
resolve_selection(Some(removed), Some(removed), &keys),
|
||||
Some(a_pk)
|
||||
);
|
||||
}
|
||||
}
|
||||
+122
-4
@@ -53,6 +53,10 @@ pub struct App {
|
||||
pub image: Option<String>,
|
||||
/// Unix timestamp of when it was approved.
|
||||
pub approved_at: i64,
|
||||
/// The identity key this client is bound to, hex. Empty in registries that
|
||||
/// predate multiple identities; migrated once on load.
|
||||
#[serde(default)]
|
||||
pub identity: String,
|
||||
/// Requests it may answer without asking. Empty until the user picks
|
||||
/// "Always"; older registries simply deserialize to the default.
|
||||
#[serde(default)]
|
||||
@@ -213,13 +217,32 @@ impl AppRegistry {
|
||||
self.save()
|
||||
}
|
||||
|
||||
/// Record an approval. Metadata is whatever the client declared.
|
||||
pub fn approve(&mut self, client: &ClientInfo) -> Result<()> {
|
||||
/// The identity key a client is bound to, if it is approved.
|
||||
pub fn identity_for(&self, public_key: &PublicKey) -> Option<PublicKey> {
|
||||
let hex = public_key.to_hex();
|
||||
self.apps
|
||||
.iter()
|
||||
.find(|app| app.public_key == hex)
|
||||
.and_then(|app| PublicKey::from_hex(&app.identity).ok())
|
||||
}
|
||||
|
||||
/// Record an approval bound to `identity`. Metadata is whatever the client
|
||||
/// declared.
|
||||
///
|
||||
/// Re-pairing the **same** client with a **different** identity clears its
|
||||
/// stored policy: a permission belongs to the app+identity relationship, so
|
||||
/// an "always" granted while signing as A must not silently carry over to
|
||||
/// B. (A client that reuses one keypair for two identities cannot be
|
||||
/// distinguished — requests carry no identity — so rebinding is the escape
|
||||
/// hatch.)
|
||||
pub fn approve(&mut self, client: &ClientInfo, identity: PublicKey) -> Result<()> {
|
||||
let public_key = client.public_key.to_hex();
|
||||
let identity = identity.to_hex();
|
||||
let policy = self
|
||||
.apps
|
||||
.iter()
|
||||
.find(|app| app.public_key == public_key)
|
||||
.filter(|app| app.identity == identity)
|
||||
.map(|app| app.policy.clone())
|
||||
.unwrap_or_default();
|
||||
self.apps.retain(|app| app.public_key != public_key);
|
||||
@@ -232,11 +255,47 @@ impl AppRegistry {
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|since| since.as_secs() as i64)
|
||||
.unwrap_or_default(),
|
||||
identity,
|
||||
policy,
|
||||
});
|
||||
self.save()
|
||||
}
|
||||
|
||||
/// Bind registries that predate multiple identities to the current key. Run
|
||||
/// once, after the key list is known: an app must never resolve against a
|
||||
/// mutable "current" identity at request time.
|
||||
pub fn bind_legacy(&mut self, identity: PublicKey) -> Result<()> {
|
||||
let identity = identity.to_hex();
|
||||
let mut changed = false;
|
||||
for app in &mut self.apps {
|
||||
if app.identity.is_empty() {
|
||||
app.identity = identity.clone();
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.save()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applications bound to one identity.
|
||||
pub fn list_for(&self, identity: PublicKey) -> Vec<App> {
|
||||
let identity = identity.to_hex();
|
||||
self.apps
|
||||
.iter()
|
||||
.filter(|app| app.identity == identity)
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Forget every application bound to one identity.
|
||||
pub fn clear_for(&mut self, identity: PublicKey) -> Result<()> {
|
||||
let identity = identity.to_hex();
|
||||
self.apps.retain(|app| app.identity != identity);
|
||||
self.save()
|
||||
}
|
||||
|
||||
/// Forget an approved application and everything it was allowed to do.
|
||||
pub fn revoke(&mut self, public_key: &PublicKey) -> Result<()> {
|
||||
let hex = public_key.to_hex();
|
||||
@@ -308,7 +367,9 @@ mod tests {
|
||||
let method = Permission::Method("nip44_encrypt".to_string());
|
||||
|
||||
let mut registry = AppRegistry::at(path.clone());
|
||||
registry.approve(&client(keys.public_key())).unwrap();
|
||||
registry
|
||||
.approve(&client(keys.public_key()), keys.public_key())
|
||||
.unwrap();
|
||||
registry.allow(&keys.public_key(), kind.clone()).unwrap();
|
||||
registry.allow(&keys.public_key(), method.clone()).unwrap();
|
||||
assert!(registry.permits(&keys.public_key(), &kind));
|
||||
@@ -340,7 +401,64 @@ mod tests {
|
||||
fn an_ephemeral_registry_never_writes() {
|
||||
let keys = Keys::generate();
|
||||
let mut registry = AppRegistry::default();
|
||||
registry.approve(&client(keys.public_key())).unwrap();
|
||||
registry
|
||||
.approve(&client(keys.public_key()), keys.public_key())
|
||||
.unwrap();
|
||||
assert!(registry.contains(&keys.public_key()));
|
||||
}
|
||||
|
||||
/// A permission granted while signing as one identity must not carry over
|
||||
/// when the same client is re-paired with another identity.
|
||||
#[test]
|
||||
fn rebinding_clears_the_policy() {
|
||||
let client_keys = Keys::generate();
|
||||
let first = Keys::generate().public_key();
|
||||
let second = Keys::generate().public_key();
|
||||
let mut registry = AppRegistry::default();
|
||||
|
||||
registry.approve(&client(client_keys.public_key()), first).unwrap();
|
||||
registry
|
||||
.allow(&client_keys.public_key(), Permission::Kind(1))
|
||||
.unwrap();
|
||||
assert!(registry.permits(&client_keys.public_key(), &Permission::Kind(1)));
|
||||
assert_eq!(registry.identity_for(&client_keys.public_key()), Some(first));
|
||||
|
||||
registry.approve(&client(client_keys.public_key()), second).unwrap();
|
||||
assert_eq!(registry.identity_for(&client_keys.public_key()), Some(second));
|
||||
assert!(
|
||||
!registry.permits(&client_keys.public_key(), &Permission::Kind(1)),
|
||||
"the old identity's permission must not survive the rebind"
|
||||
);
|
||||
|
||||
// Re-pairing the *same* identity keeps the policy.
|
||||
registry
|
||||
.allow(&client_keys.public_key(), Permission::Kind(1))
|
||||
.unwrap();
|
||||
registry.approve(&client(client_keys.public_key()), second).unwrap();
|
||||
assert!(registry.permits(&client_keys.public_key(), &Permission::Kind(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_apps_are_bound_once() {
|
||||
let identity = Keys::generate().public_key();
|
||||
let mut registry = AppRegistry::default();
|
||||
// An app from before identities existed.
|
||||
registry.apps.push(App {
|
||||
public_key: Keys::generate().public_key().to_hex(),
|
||||
name: None,
|
||||
url: None,
|
||||
image: None,
|
||||
approved_at: 0,
|
||||
identity: String::new(),
|
||||
policy: Policy::default(),
|
||||
});
|
||||
|
||||
registry.bind_legacy(identity).unwrap();
|
||||
|
||||
assert!(registry
|
||||
.list()
|
||||
.iter()
|
||||
.all(|app| app.identity == identity.to_hex()));
|
||||
assert_eq!(registry.list_for(identity).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,10 @@ pub struct Entry {
|
||||
/// Self-declared client name; a display hint, not a fact.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
/// The identity key the request was answered as, hex. Absent in logs written
|
||||
/// before multiple identities existed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub identity: Option<String>,
|
||||
/// The NIP-46 method, or `connect` for a pairing.
|
||||
pub method: String,
|
||||
/// The event kind, for `sign_event` only. Never content or tags.
|
||||
@@ -225,6 +229,7 @@ mod tests {
|
||||
at,
|
||||
app: app.to_string(),
|
||||
name: None,
|
||||
identity: None,
|
||||
method: "sign_event".to_string(),
|
||||
kind: Some(1),
|
||||
outcome: outcome::ALLOWED_ONCE.to_string(),
|
||||
|
||||
+249
-92
@@ -1,8 +1,12 @@
|
||||
//! Key storage.
|
||||
//!
|
||||
//! One Secret Service item per key, so the device key can be rotated without
|
||||
//! touching the user's identity key. The identity key is the `nsec` and lives
|
||||
//! only in the keyring: Regent never writes it to a file of its own.
|
||||
//! One Secret Service item per key: the device/transport key, plus **any number
|
||||
//! of identity keys**. The identity keys are `nsec`s and live only in the
|
||||
//! keyring: Regent never writes them to a file of its own.
|
||||
//!
|
||||
//! Identity items are addressed by `(application, kind=user, pubkey=<hex>)`, so
|
||||
//! the key list can be shown without reading a single secret. The secret is
|
||||
//! read on demand, only when a request actually needs to sign.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -15,6 +19,9 @@ use crate::APP_ID;
|
||||
pub const KIND_USER: &str = "user";
|
||||
pub const KIND_DEVICE: &str = "device";
|
||||
|
||||
/// Label used for a key whose label cannot be read (e.g. a locked collection).
|
||||
pub const UNNAMED: &str = "Identity key";
|
||||
|
||||
/// NIP-49 `log_n` for exported keys. 16 is what rust-nostr's tooling uses by
|
||||
/// default; higher values make the export slower to open on modest hardware.
|
||||
const EXPORT_LOG_N: u8 = 16;
|
||||
@@ -22,94 +29,76 @@ const EXPORT_LOG_N: u8 = 16;
|
||||
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// A stored identity key, without its secret.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct KeyRef {
|
||||
pub public_key: PublicKey,
|
||||
/// User-chosen label (the keyring item label).
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub struct KeyStore {
|
||||
keyring: Keyring,
|
||||
}
|
||||
|
||||
impl KeyStore {
|
||||
/// Connect to the Secret Service (or the portal-backed store when
|
||||
/// sandboxed — `Keyring::new` picks).
|
||||
/// sandboxed — `Keyring::new` picks) and migrate a legacy single-key item.
|
||||
pub async fn connect() -> Result<Self> {
|
||||
Ok(Self {
|
||||
let store = Self {
|
||||
keyring: Keyring::new().await?,
|
||||
})
|
||||
};
|
||||
store.migrate_user_keys().await?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
fn attributes(kind: &str) -> HashMap<String, String> {
|
||||
/// Attributes shared by every item of a kind.
|
||||
fn kind_attributes(kind: &str) -> HashMap<String, String> {
|
||||
HashMap::from([
|
||||
("application".to_string(), APP_ID.to_string()),
|
||||
("kind".to_string(), kind.to_string()),
|
||||
])
|
||||
}
|
||||
|
||||
/// The user's identity key, if one has been imported or created.
|
||||
pub async fn user_key(&self) -> Result<Option<Keys>> {
|
||||
self.load(KIND_USER).await
|
||||
/// Attributes that address one identity key.
|
||||
fn user_attributes(public_key: &PublicKey) -> HashMap<String, String> {
|
||||
let mut attributes = Self::kind_attributes(KIND_USER);
|
||||
attributes.insert("pubkey".to_string(), public_key.to_hex());
|
||||
attributes
|
||||
}
|
||||
|
||||
/// The NIP-46 transport key, generated on first use. Deliberately not the
|
||||
/// identity key: it is what relays and requesting apps see, and it can be
|
||||
/// rotated without the user's `nsec` changing.
|
||||
pub async fn device_key(&self) -> Result<Keys> {
|
||||
if let Some(keys) = self.load(KIND_DEVICE).await? {
|
||||
return Ok(keys);
|
||||
/// Every stored identity key: name and pubkey, **without reading a secret**.
|
||||
///
|
||||
/// A label we cannot read (locked collection) becomes [`UNNAMED`] instead of
|
||||
/// failing the whole list.
|
||||
pub async fn list_user_keys(&self) -> Result<Vec<KeyRef>> {
|
||||
let items = self
|
||||
.keyring
|
||||
.search_items(&Self::kind_attributes(KIND_USER))
|
||||
.await?;
|
||||
let mut keys = Vec::new();
|
||||
for item in items {
|
||||
let attributes = item.attributes().await?;
|
||||
let Some(hex) = attributes.get("pubkey") else {
|
||||
continue; // should have been migrated
|
||||
};
|
||||
let public_key = PublicKey::from_hex(hex)?;
|
||||
let name = item
|
||||
.label()
|
||||
.await
|
||||
.unwrap_or_else(|_| UNNAMED.to_string());
|
||||
keys.push(KeyRef { public_key, name });
|
||||
}
|
||||
let keys = Keys::generate();
|
||||
self.store(KIND_DEVICE, "Regent device key", &keys).await?;
|
||||
keys.sort_by_key(|key| key.name.to_lowercase());
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// Create a brand new identity key and store it.
|
||||
pub async fn generate_user_key(&self) -> Result<PublicKey> {
|
||||
let keys = Keys::generate();
|
||||
self.store(KIND_USER, "Regent identity key", &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Import an identity key from `nsec1…` or 64-character hex.
|
||||
pub async fn import_user_key(&self, secret: &str) -> Result<PublicKey> {
|
||||
let keys = Keys::parse(secret.trim())?;
|
||||
self.store(KIND_USER, "Regent identity key", &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Import an identity key from a NIP-49 `ncryptsec1…` string.
|
||||
pub async fn import_user_key_encrypted(
|
||||
&self,
|
||||
ncryptsec: &str,
|
||||
password: &str,
|
||||
) -> Result<PublicKey> {
|
||||
let encrypted = EncryptedSecretKey::from_bech32(ncryptsec.trim())?;
|
||||
let secret_key = encrypted.decrypt(password)?;
|
||||
let keys = Keys::new(secret_key);
|
||||
self.store(KIND_USER, "Regent identity key", &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Export the identity key as a NIP-49 `ncryptsec1…` string.
|
||||
pub async fn export_user_key_encrypted(&self, password: &str) -> Result<Zeroizing<String>> {
|
||||
let keys = self
|
||||
.user_key()
|
||||
.await?
|
||||
.ok_or("no identity key is stored")?;
|
||||
let encrypted = EncryptedSecretKey::new(
|
||||
keys.secret_key(),
|
||||
password,
|
||||
EXPORT_LOG_N,
|
||||
KeySecurity::Medium,
|
||||
)?;
|
||||
Ok(Zeroizing::new(encrypted.to_bech32()?))
|
||||
}
|
||||
|
||||
/// Forget the identity key. Wired to the UI together with key replacement.
|
||||
#[allow(dead_code)]
|
||||
pub async fn forget_user_key(&self) -> Result<()> {
|
||||
self.keyring.delete(&Self::attributes(KIND_USER)).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load(&self, kind: &str) -> Result<Option<Keys>> {
|
||||
let items = self.keyring.search_items(&Self::attributes(kind)).await?;
|
||||
/// Load one identity key's secret, on demand.
|
||||
pub async fn user_key(&self, public_key: &PublicKey) -> Result<Option<Keys>> {
|
||||
let items = self
|
||||
.keyring
|
||||
.search_items(&Self::user_attributes(public_key))
|
||||
.await?;
|
||||
let Some(item) = items.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -123,13 +112,157 @@ impl KeyStore {
|
||||
Ok(Some(Keys::parse(text.as_str())?))
|
||||
}
|
||||
|
||||
async fn store(&self, kind: &str, label: &str, keys: &Keys) -> Result<()> {
|
||||
// Stored as the `nsec` so the value is self-describing. `replace` is
|
||||
// true because the attributes are unique per kind.
|
||||
/// The NIP-46 transport key, generated on first use. Deliberately not an
|
||||
/// identity key: it is what relays and requesting apps see, and it can be
|
||||
/// rotated without any `nsec` changing.
|
||||
pub async fn device_key(&self) -> Result<Keys> {
|
||||
if let Some(keys) = self.load_device().await? {
|
||||
return Ok(keys);
|
||||
}
|
||||
let keys = Keys::generate();
|
||||
let nsec = Zeroizing::new(keys.secret_key().to_bech32()?);
|
||||
self.keyring
|
||||
.create_item(label, &Self::attributes(kind), Secret::text(nsec.as_str()), true)
|
||||
.create_item(
|
||||
"Regent device key",
|
||||
&Self::kind_attributes(KIND_DEVICE),
|
||||
Secret::text(nsec.as_str()),
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
Ok(keys)
|
||||
}
|
||||
|
||||
/// Create a brand new identity key and store it under `name`.
|
||||
pub async fn generate_user_key(&self, name: &str) -> Result<PublicKey> {
|
||||
let keys = Keys::generate();
|
||||
self.store_user(name, &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Import an identity key from `nsec1…` or 64-character hex.
|
||||
pub async fn import_user_key(&self, name: &str, secret: &str) -> Result<PublicKey> {
|
||||
let keys = Keys::parse(secret.trim())?;
|
||||
self.store_user(name, &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Import an identity key from a NIP-49 `ncryptsec1…` string.
|
||||
pub async fn import_user_key_encrypted(
|
||||
&self,
|
||||
name: &str,
|
||||
ncryptsec: &str,
|
||||
password: &str,
|
||||
) -> Result<PublicKey> {
|
||||
let encrypted = EncryptedSecretKey::from_bech32(ncryptsec.trim())?;
|
||||
let secret_key = encrypted.decrypt(password)?;
|
||||
let keys = Keys::new(secret_key);
|
||||
self.store_user(name, &keys).await?;
|
||||
Ok(keys.public_key())
|
||||
}
|
||||
|
||||
/// Rename an identity key (the keyring item label).
|
||||
pub async fn rename_user_key(&self, public_key: &PublicKey, name: &str) -> Result<()> {
|
||||
let items = self
|
||||
.keyring
|
||||
.search_items(&Self::user_attributes(public_key))
|
||||
.await?;
|
||||
let item = items.first().ok_or("no such identity key")?;
|
||||
item.set_label(name).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Export one identity key as a NIP-49 `ncryptsec1…` string.
|
||||
pub async fn export_user_key_encrypted(
|
||||
&self,
|
||||
public_key: &PublicKey,
|
||||
password: &str,
|
||||
) -> Result<Zeroizing<String>> {
|
||||
let keys = self
|
||||
.user_key(public_key)
|
||||
.await?
|
||||
.ok_or("no such identity key")?;
|
||||
let encrypted = EncryptedSecretKey::new(
|
||||
keys.secret_key(),
|
||||
password,
|
||||
EXPORT_LOG_N,
|
||||
KeySecurity::Medium,
|
||||
)?;
|
||||
Ok(Zeroizing::new(encrypted.to_bech32()?))
|
||||
}
|
||||
|
||||
/// Forget one identity key.
|
||||
pub async fn forget_user_key(&self, public_key: &PublicKey) -> Result<()> {
|
||||
self.keyring
|
||||
.delete(&Self::user_attributes(public_key))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_device(&self) -> Result<Option<Keys>> {
|
||||
let items = self
|
||||
.keyring
|
||||
.search_items(&Self::kind_attributes(KIND_DEVICE))
|
||||
.await?;
|
||||
let Some(item) = items.first() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let secret = item.secret().await?;
|
||||
let text = Zeroizing::new(
|
||||
secret
|
||||
.as_str()
|
||||
.ok_or("stored key is not valid UTF-8")?
|
||||
.to_string(),
|
||||
);
|
||||
Ok(Some(Keys::parse(text.as_str())?))
|
||||
}
|
||||
|
||||
async fn store_user(&self, name: &str, keys: &Keys) -> Result<()> {
|
||||
// Stored as the `nsec` so the value is self-describing. Replace is true
|
||||
// because the attributes are unique per pubkey.
|
||||
let nsec = Zeroizing::new(keys.secret_key().to_bech32()?);
|
||||
self.keyring
|
||||
.create_item(
|
||||
name,
|
||||
&Self::user_attributes(&keys.public_key()),
|
||||
Secret::text(nsec.as_str()),
|
||||
true,
|
||||
)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Add the `pubkey` attribute to a `kind=user` item created before multiple
|
||||
/// identities existed, so it can be listed and looked up without reading it
|
||||
/// again. The secret is read exactly once, here.
|
||||
async fn migrate_user_keys(&self) -> Result<()> {
|
||||
let items = self
|
||||
.keyring
|
||||
.search_items(&Self::kind_attributes(KIND_USER))
|
||||
.await?;
|
||||
for item in items {
|
||||
let attributes = item.attributes().await?;
|
||||
if attributes.contains_key("pubkey") {
|
||||
continue;
|
||||
}
|
||||
let secret = item.secret().await?;
|
||||
let text = Zeroizing::new(
|
||||
secret
|
||||
.as_str()
|
||||
.ok_or("stored key is not valid UTF-8")?
|
||||
.to_string(),
|
||||
);
|
||||
let keys = Keys::parse(text.as_str())?;
|
||||
item.set_attributes(&Self::user_attributes(&keys.public_key()))
|
||||
.await?;
|
||||
if item
|
||||
.label()
|
||||
.await
|
||||
.map(|label| label.trim().is_empty())
|
||||
.unwrap_or(true)
|
||||
{
|
||||
let _ = item.set_label(UNNAMED).await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -142,47 +275,71 @@ mod tests {
|
||||
///
|
||||
/// ```sh
|
||||
/// dbus-run-session -- bash -c '
|
||||
/// printf test | gnome-keyring-daemon --unlock --components=secrets --daemonize
|
||||
/// printf test | gnome-keyring-daemon --unlock --components=secrets
|
||||
/// CARGO_TARGET_DIR=_build/cargo-target cargo test --release -- --ignored --nocapture'
|
||||
/// ```
|
||||
#[tokio::test]
|
||||
#[ignore = "needs a live Secret Service"]
|
||||
async fn keyring_roundtrip() {
|
||||
let store = KeyStore::connect().await.expect("connect to the keyring");
|
||||
let _ = store.forget_user_key().await;
|
||||
|
||||
// Clean slate.
|
||||
for key in store.list_user_keys().await.expect("list") {
|
||||
let _ = store.forget_user_key(&key.public_key).await;
|
||||
}
|
||||
|
||||
// The device key is generated once, then stays the same.
|
||||
let device = store.device_key().await.expect("device key");
|
||||
let device_again = store.device_key().await.expect("device key (again)");
|
||||
assert_eq!(device.public_key(), device_again.public_key());
|
||||
|
||||
// A generated identity key survives being read back.
|
||||
let generated = store.generate_user_key().await.expect("generate");
|
||||
let loaded = store.user_key().await.expect("load").expect("a key");
|
||||
assert_eq!(generated, loaded.public_key());
|
||||
// Two identity keys coexist, each with its own label.
|
||||
let first = store.generate_user_key("Work").await.expect("generate A");
|
||||
let second = store.generate_user_key("Personal").await.expect("generate B");
|
||||
assert_ne!(first, second);
|
||||
|
||||
// NIP-49 export, then import into an emptied store.
|
||||
let mut listed = store.list_user_keys().await.expect("list");
|
||||
listed.sort_by_key(|key| key.name.clone());
|
||||
assert_eq!(listed.len(), 2);
|
||||
assert_eq!(listed[0].name, "Personal");
|
||||
assert_eq!(listed[1].name, "Work");
|
||||
|
||||
// The secret loads by pubkey, and only for that key.
|
||||
let loaded = store.user_key(&second).await.expect("load").expect("a key");
|
||||
assert_eq!(loaded.public_key(), second);
|
||||
assert_eq!(
|
||||
store.user_key(&first).await.expect("load").expect("a key").public_key(),
|
||||
first
|
||||
);
|
||||
|
||||
// Rename changes the visible name without touching the key.
|
||||
store.rename_user_key(&first, "Clients").await.expect("rename");
|
||||
let listed = store.list_user_keys().await.expect("list");
|
||||
assert!(listed.iter().any(|key| key.name == "Clients" && key.public_key == first));
|
||||
|
||||
// NIP-49 export/import round-trips for a specific key.
|
||||
let ncryptsec = store
|
||||
.export_user_key_encrypted("hunter2")
|
||||
.export_user_key_encrypted(&second, "hunter2")
|
||||
.await
|
||||
.expect("export");
|
||||
assert!(ncryptsec.starts_with("ncryptsec1"), "got {}", ncryptsec.as_str());
|
||||
|
||||
store.forget_user_key().await.expect("forget");
|
||||
assert!(store.user_key().await.expect("load").is_none());
|
||||
|
||||
assert!(ncryptsec.starts_with("ncryptsec1"));
|
||||
let imported = store
|
||||
.import_user_key_encrypted(&ncryptsec, "hunter2")
|
||||
.import_user_key_encrypted("Imported", &ncryptsec, "hunter2")
|
||||
.await
|
||||
.expect("import");
|
||||
assert_eq!(imported, generated);
|
||||
|
||||
// The wrong password must not import.
|
||||
assert_eq!(imported, second, "re-import replaces the same item");
|
||||
assert!(store
|
||||
.import_user_key_encrypted(&ncryptsec, "wrong")
|
||||
.import_user_key_encrypted("Imported", &ncryptsec, "wrong")
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
store.forget_user_key().await.expect("clean up");
|
||||
// Removing one key leaves the other alone.
|
||||
store.forget_user_key(&first).await.expect("forget A");
|
||||
let listed = store.list_user_keys().await.expect("list");
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert_eq!(listed[0].public_key, second);
|
||||
|
||||
store.forget_user_key(&second).await.expect("clean up");
|
||||
assert!(store.list_user_keys().await.expect("list").is_empty());
|
||||
}
|
||||
}
|
||||
+33
-10
@@ -12,16 +12,16 @@ use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
use crate::signer::approval::{ApprovalRequest, ClientInfo, Decision, Request};
|
||||
use crate::signer::approval::{ApprovalRequest, Decision, Question, Request};
|
||||
use crate::ui::{kind, plain};
|
||||
|
||||
/// 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_question(&widget, &question.client, &question.request).await;
|
||||
let _ = question.reply.send(decision).await;
|
||||
while let Ok(pending) = questions.recv().await {
|
||||
let decision = present_question(&widget, &pending.question).await;
|
||||
let _ = pending.reply.send(decision).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -43,9 +43,9 @@ enum Choices {
|
||||
/// 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,
|
||||
question: &Question,
|
||||
) -> Decision {
|
||||
let request = &question.request;
|
||||
let choices = match request {
|
||||
Request::Pair { .. } => Choices::Pair,
|
||||
request if !request.allows_always() => Choices::Once,
|
||||
@@ -59,7 +59,7 @@ pub async fn present_question(
|
||||
// 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(client, request))
|
||||
.extra_child(&details(question))
|
||||
.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.
|
||||
@@ -122,13 +122,16 @@ fn story(request: &Request) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// The selectable, plain-text detail block: who is asking and exactly what.
|
||||
fn details(client: &ClientInfo, request: &Request) -> gtk::Box {
|
||||
/// The selectable, plain-text detail block: who is asking, as which identity,
|
||||
/// and exactly what.
|
||||
fn details(question: &Question) -> gtk::Box {
|
||||
let client = &question.client;
|
||||
let content = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
.spacing(10)
|
||||
.build();
|
||||
|
||||
content.append(&field("Signing as", &describe_key(&question.identity)));
|
||||
content.append(&field(
|
||||
"Application",
|
||||
client.name.as_deref().unwrap_or("(unnamed)"),
|
||||
@@ -141,7 +144,7 @@ fn details(client: &ClientInfo, request: &Request) -> gtk::Box {
|
||||
&client.public_key.to_bech32().unwrap_or_default(),
|
||||
));
|
||||
|
||||
match request {
|
||||
match &question.request {
|
||||
Request::Pair { requested } => {
|
||||
if let Some(requested) = requested {
|
||||
content.append(&field("Asked for", requested));
|
||||
@@ -176,6 +179,14 @@ fn details(client: &ClientInfo, request: &Request) -> gtk::Box {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(previous) = &question.rebind_from {
|
||||
content.append(¬e(&format!(
|
||||
"This application is currently paired with {}. Pairing it again switches it \
|
||||
to this identity and resets its stored permissions.",
|
||||
previous.to_bech32().unwrap_or_else(|_| previous.to_hex())
|
||||
)));
|
||||
}
|
||||
|
||||
content.append(¬e(
|
||||
"The application's name and URL are supplied by the application itself and \
|
||||
cannot be trusted.",
|
||||
@@ -184,6 +195,18 @@ fn details(client: &ClientInfo, request: &Request) -> gtk::Box {
|
||||
content
|
||||
}
|
||||
|
||||
/// The identity a request would act as: its label and npub.
|
||||
fn describe_key(key: &crate::signer::approval::SigningKey) -> String {
|
||||
let npub = key
|
||||
.public_key
|
||||
.to_bech32()
|
||||
.unwrap_or_else(|_| key.public_key.to_hex());
|
||||
match &key.name {
|
||||
Some(name) if !name.trim().is_empty() => format!("{name} ({npub})"),
|
||||
_ => npub,
|
||||
}
|
||||
}
|
||||
|
||||
/// A label/value row. Both halves are plain and selectable.
|
||||
fn field(title: &str, value: &str) -> gtk::Box {
|
||||
let row = gtk::Box::builder()
|
||||
|
||||
@@ -142,6 +142,28 @@ impl Ui {
|
||||
let row = plain::expander(&name, &plain::shorten(&npub, 12, 6));
|
||||
row.add_row(&plain::row("Public key", &npub));
|
||||
|
||||
// Which identity this app signs as. This is the binding the responder
|
||||
// resolves per request.
|
||||
let bound = PublicKey::parse(&app.identity).ok();
|
||||
let signing_as = match bound {
|
||||
Some(identity) => {
|
||||
let key_npub = identity.to_bech32().unwrap_or_else(|_| identity.to_hex());
|
||||
let key_name = self
|
||||
.state
|
||||
.names()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&identity.to_hex())
|
||||
.cloned();
|
||||
match key_name {
|
||||
Some(name) if !name.trim().is_empty() => format!("{name} ({key_npub})"),
|
||||
_ => key_npub,
|
||||
}
|
||||
}
|
||||
None => "unknown (paired before identities existed)".to_string(),
|
||||
};
|
||||
row.add_row(&plain::row("Signing as", &signing_as));
|
||||
|
||||
if app.policy.kinds.is_empty() && app.policy.methods.is_empty() {
|
||||
row.add_row(&plain::row(
|
||||
"Permissions",
|
||||
|
||||
+371
-126
@@ -1,10 +1,15 @@
|
||||
//! The keys page: shows the identity and device keys, and lets you create or
|
||||
//! import the identity key.
|
||||
//! The keys page: the identity keys (named, several of them) and the device key.
|
||||
//!
|
||||
//! Creating, importing, renaming, exporting and removing a key all happen here;
|
||||
//! the selected identity (used for new pairings and by the header switcher in
|
||||
//! M7b) is chosen from the same list.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
@@ -19,10 +24,13 @@ use crate::ui::plain;
|
||||
#[derive(Clone)]
|
||||
struct Handles {
|
||||
stack: gtk::Stack,
|
||||
identity: adw::ActionRow,
|
||||
list: adw::PreferencesGroup,
|
||||
device: adw::ActionRow,
|
||||
}
|
||||
|
||||
/// The rows currently in the list, so a reload can remove exactly them.
|
||||
type Rows = Rc<RefCell<Vec<adw::ActionRow>>>;
|
||||
|
||||
/// The toplevel, resolved lazily: a view is not in a window when it is built.
|
||||
fn toplevel(handles: &Handles) -> Option<gtk::Window> {
|
||||
handles.stack.root().and_downcast::<gtk::Window>()
|
||||
@@ -34,22 +42,14 @@ pub struct KeysView {
|
||||
|
||||
impl KeysView {
|
||||
pub fn new(state: Rc<AppState>) -> Self {
|
||||
let handles = Handles {
|
||||
stack: gtk::Stack::builder().vexpand(true).build(),
|
||||
identity: plain::row("Identity key", "—"),
|
||||
device: plain::row("Device key", "—"),
|
||||
};
|
||||
let stack = gtk::Stack::builder().vexpand(true).build();
|
||||
|
||||
let loading = adw::StatusPage::builder()
|
||||
.title("Connecting to the keyring…")
|
||||
.child(&adw::Spinner::new())
|
||||
.build();
|
||||
handles.stack.add_named(&loading, Some("loading"));
|
||||
stack.add_named(&loading, Some("loading"));
|
||||
|
||||
let actions = gtk::Box::builder()
|
||||
.spacing(12)
|
||||
.halign(gtk::Align::Center)
|
||||
.build();
|
||||
let create = gtk::Button::builder()
|
||||
.label("Create a key")
|
||||
.css_classes(["pill", "suggested-action"])
|
||||
@@ -58,136 +58,126 @@ impl KeysView {
|
||||
.label("Import a key…")
|
||||
.css_classes(["pill"])
|
||||
.build();
|
||||
let actions = gtk::Box::builder()
|
||||
.spacing(12)
|
||||
.halign(gtk::Align::Center)
|
||||
.build();
|
||||
actions.append(&create);
|
||||
actions.append(&import);
|
||||
|
||||
let empty = adw::StatusPage::builder()
|
||||
.icon_name("security-high-symbolic")
|
||||
.title("No key yet")
|
||||
.description(
|
||||
"Create a Nostr key or import one you already have. It is kept in the \
|
||||
system keyring and never written to disk by Regent.",
|
||||
"Create a Nostr identity key or import one you already have. It is kept in \
|
||||
the system keyring and never written to disk by Regent.",
|
||||
)
|
||||
.child(&actions)
|
||||
.build();
|
||||
handles.stack.add_named(&empty, Some("empty"));
|
||||
stack.add_named(&empty, Some("empty"));
|
||||
|
||||
let copy_npub = gtk::Button::builder()
|
||||
.icon_name("edit-copy-symbolic")
|
||||
.tooltip_text("Copy public key")
|
||||
let list = adw::PreferencesGroup::builder()
|
||||
.title("Identity keys")
|
||||
.description(
|
||||
"New pairings sign as the selected key. Each approved application keeps \
|
||||
the key it was paired with.",
|
||||
)
|
||||
.build();
|
||||
let device = plain::row("Device key", "—");
|
||||
let device_group = adw::PreferencesGroup::builder()
|
||||
.title("Transport")
|
||||
.description(
|
||||
"Used for NIP-46 traffic only. Rotating it does not change any identity.",
|
||||
)
|
||||
.build();
|
||||
device_group.add(&device);
|
||||
let add_group = adw::PreferencesGroup::builder().title("Add a key").build();
|
||||
let create_row = plain::row("Create a new identity key", "Generate one in the keyring");
|
||||
let create_button = gtk::Button::builder()
|
||||
.label("Create")
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
handles.identity.add_suffix(©_npub);
|
||||
|
||||
let export = gtk::Button::builder()
|
||||
.label("Export…")
|
||||
create_row.add_suffix(&create_button);
|
||||
let import_row = plain::row("Import an identity key", "nsec, hex, or NIP-49 ncryptsec");
|
||||
let import_button = gtk::Button::builder()
|
||||
.label("Import…")
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
let export_row = plain::row("Export identity key", "Encrypted with a password (NIP-49)");
|
||||
export_row.add_suffix(&export);
|
||||
export_row.set_activatable_widget(Some(&export));
|
||||
|
||||
let group = adw::PreferencesGroup::builder().title("Keys").build();
|
||||
group.add(&handles.identity);
|
||||
group.add(&handles.device);
|
||||
group.add(&export_row);
|
||||
import_row.add_suffix(&import_button);
|
||||
add_group.add(&create_row);
|
||||
add_group.add(&import_row);
|
||||
|
||||
let page = adw::PreferencesPage::new();
|
||||
page.add(&group);
|
||||
handles.stack.add_named(&page, Some("loaded"));
|
||||
|
||||
handles.stack.set_visible_child_name("loading");
|
||||
page.add(&list);
|
||||
page.add(&add_group);
|
||||
page.add(&device_group);
|
||||
stack.add_named(&page, Some("loaded"));
|
||||
stack.set_visible_child_name("loading");
|
||||
|
||||
let handles = Handles {
|
||||
stack,
|
||||
list,
|
||||
device,
|
||||
};
|
||||
let rows: Rows = Rc::new(RefCell::new(Vec::new()));
|
||||
let widget: gtk::Widget = handles.stack.clone().upcast();
|
||||
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
create.connect_clicked(move |_| {
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
runtime::spawn(
|
||||
async move { store.generate_user_key().await },
|
||||
move |result| match result {
|
||||
Ok(_) => state.notify(),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
for button in [&create_button, &create] {
|
||||
let (state, handles) = (Rc::clone(&state), handles.clone());
|
||||
button.connect_clicked(move |_| present_create(handles.clone(), Rc::clone(&state)));
|
||||
}
|
||||
for button in [&import_button, &import] {
|
||||
let (state, handles) = (Rc::clone(&state), handles.clone());
|
||||
button.connect_clicked(move |_| present_import(handles.clone(), Rc::clone(&state)));
|
||||
}
|
||||
|
||||
// Reload on key changes and on a selection change.
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
import.connect_clicked(move |_| present_import_dialog(handles.clone(), Rc::clone(&state)));
|
||||
let (listener_state, handles, rows) =
|
||||
(Rc::clone(&state), handles.clone(), Rc::clone(&rows));
|
||||
state.listen(move || reload(&listener_state, &handles, &rows));
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
copy_npub.connect_clicked(move |_| {
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
async move { store.user_key().await },
|
||||
move |result| match result {
|
||||
Ok(Some(keys)) => {
|
||||
if let Some(window) = toplevel(&handles) {
|
||||
window
|
||||
.clipboard()
|
||||
.set_text(&keys.public_key().to_bech32().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
export.connect_clicked(move |_| present_export_dialog(handles.clone(), Rc::clone(&state)));
|
||||
}
|
||||
|
||||
// Reload whenever the store becomes available or the keys change.
|
||||
{
|
||||
let handles = handles.clone();
|
||||
let listener_state = Rc::clone(&state);
|
||||
state.listen(move || {
|
||||
let Some(store) = listener_state.store() else {
|
||||
return;
|
||||
};
|
||||
reload_identity(handles.clone(), Arc::clone(&store));
|
||||
reload_device(handles.clone(), Arc::clone(&store));
|
||||
});
|
||||
let (listener_state, handles, rows) =
|
||||
(Rc::clone(&state), handles.clone(), Rc::clone(&rows));
|
||||
state.listen_changes(move || reload(&listener_state, &handles, &rows));
|
||||
}
|
||||
|
||||
Self { widget }
|
||||
}
|
||||
}
|
||||
|
||||
fn reload_identity(handles: Handles, store: Arc<KeyStore>) {
|
||||
runtime::spawn(
|
||||
async move { store.user_key().await },
|
||||
move |result| match result {
|
||||
Ok(Some(keys)) => {
|
||||
set_public_key(&handles.identity, &keys.public_key());
|
||||
handles.stack.set_visible_child_name("loaded");
|
||||
}
|
||||
Ok(None) => handles.stack.set_visible_child_name("empty"),
|
||||
Err(error) => {
|
||||
handles.stack.set_visible_child_name("empty");
|
||||
report_error(&handles, &error);
|
||||
}
|
||||
},
|
||||
);
|
||||
/// Rebuild the identity list from the shared state (names + selected key).
|
||||
fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows) {
|
||||
for row in rows.borrow_mut().drain(..) {
|
||||
handles.list.remove(&row);
|
||||
}
|
||||
|
||||
let names = state.names();
|
||||
let names = names.lock().unwrap().clone();
|
||||
let current = state.current_identity().map(|key| key.to_hex());
|
||||
if names.is_empty() {
|
||||
handles.stack.set_visible_child_name("empty");
|
||||
return;
|
||||
}
|
||||
handles.stack.set_visible_child_name("loaded");
|
||||
|
||||
let mut listed: Vec<(String, String)> = names.into_iter().collect();
|
||||
listed.sort_by_key(|(_, name)| name.to_lowercase());
|
||||
for (hex, name) in listed {
|
||||
let row = key_row(state, handles, &hex, &name, current.as_deref() == Some(hex.as_str()));
|
||||
handles.list.add(&row);
|
||||
rows.borrow_mut().push(row);
|
||||
}
|
||||
|
||||
reload_device(handles.clone(), state.store());
|
||||
}
|
||||
|
||||
fn reload_device(handles: Handles, store: Arc<KeyStore>) {
|
||||
fn reload_device(handles: Handles, store: Option<Arc<KeyStore>>) {
|
||||
let Some(store) = store else {
|
||||
return;
|
||||
};
|
||||
runtime::spawn(
|
||||
async move { store.device_key().await },
|
||||
move |result| match result {
|
||||
@@ -200,11 +190,150 @@ fn reload_device(handles: Handles, store: Arc<KeyStore>) {
|
||||
);
|
||||
}
|
||||
|
||||
fn set_public_key(row: &adw::ActionRow, public_key: &nostr::key::PublicKey) {
|
||||
fn key_row(
|
||||
state: &Rc<AppState>,
|
||||
handles: &Handles,
|
||||
hex: &str,
|
||||
name: &str,
|
||||
current: bool,
|
||||
) -> adw::ActionRow {
|
||||
let public_key = PublicKey::from_hex(hex).ok();
|
||||
let npub = public_key
|
||||
.map(|key| key.to_bech32().unwrap_or_default())
|
||||
.unwrap_or_else(|| hex.to_string());
|
||||
let row = plain::row(name, &plain::shorten(&npub, 12, 6));
|
||||
|
||||
if current {
|
||||
let badge = gtk::Label::builder()
|
||||
.label("Selected")
|
||||
.css_classes(["dim-label"])
|
||||
.valign(gtk::Align::Center)
|
||||
.build();
|
||||
row.add_suffix(&badge);
|
||||
}
|
||||
|
||||
let menu = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
.spacing(2)
|
||||
.build();
|
||||
let popover = gtk::Popover::new();
|
||||
popover.set_child(Some(&menu));
|
||||
|
||||
if !current {
|
||||
if let Some(public_key) = public_key {
|
||||
let use_button = menu_button("Use for new pairings");
|
||||
let state = Rc::clone(state);
|
||||
use_button.connect_clicked(move |_| state.set_current_identity(public_key));
|
||||
menu.append(&use_button);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(public_key) = public_key {
|
||||
let rename = menu_button("Rename…");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
let name = name.to_string();
|
||||
rename.connect_clicked(move |_| {
|
||||
present_rename(handles.clone(), Rc::clone(&state), public_key, &name)
|
||||
});
|
||||
}
|
||||
menu.append(&rename);
|
||||
|
||||
let copy = menu_button("Copy public key");
|
||||
{
|
||||
let handles = handles.clone();
|
||||
let npub = npub.clone();
|
||||
copy.connect_clicked(move |_| {
|
||||
if let Some(window) = toplevel(&handles) {
|
||||
window.clipboard().set_text(&npub);
|
||||
}
|
||||
});
|
||||
}
|
||||
menu.append(©);
|
||||
|
||||
let export = menu_button("Export…");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
export.connect_clicked(move |_| present_export(handles.clone(), Rc::clone(&state), public_key));
|
||||
}
|
||||
menu.append(&export);
|
||||
|
||||
let remove = menu_button("Remove…");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
let name = name.to_string();
|
||||
remove.connect_clicked(move |_| {
|
||||
present_remove(handles.clone(), Rc::clone(&state), public_key, &name)
|
||||
});
|
||||
}
|
||||
menu.append(&remove);
|
||||
}
|
||||
|
||||
let button = gtk::MenuButton::builder()
|
||||
.icon_name("view-more-symbolic")
|
||||
.popover(&popover)
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
row.add_suffix(&button);
|
||||
row
|
||||
}
|
||||
|
||||
fn menu_button(label: &str) -> gtk::Button {
|
||||
gtk::Button::builder()
|
||||
.label(label)
|
||||
.halign(gtk::Align::Start)
|
||||
.css_classes(["flat"])
|
||||
.build()
|
||||
}
|
||||
|
||||
fn set_public_key(row: &adw::ActionRow, public_key: &PublicKey) {
|
||||
row.set_subtitle(&public_key.to_bech32().unwrap_or_default());
|
||||
}
|
||||
|
||||
fn present_import_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
fn present_create(handles: Handles, state: Rc<AppState>) {
|
||||
let count = state.names().lock().unwrap().len() + 1;
|
||||
let entry = gtk::Entry::builder()
|
||||
.text(format!("Identity {count}"))
|
||||
.build();
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Create an identity key")
|
||||
.body("The key is generated in the keyring and never written to disk by Regent.")
|
||||
.extra_child(&entry)
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("create", "Create");
|
||||
dialog.set_default_response(Some("create"));
|
||||
dialog.set_response_appearance("create", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let entry = entry.clone();
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "create" {
|
||||
return;
|
||||
}
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let name = defaulted_name(&entry);
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
async move { store.generate_user_key(&name).await },
|
||||
move |result| match result {
|
||||
Ok(_) => after.refresh_identities(),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn present_import(handles: Handles, state: Rc<AppState>) {
|
||||
let entry = adw::EntryRow::builder()
|
||||
.title("nsec, hex, or ncryptsec")
|
||||
.build();
|
||||
@@ -219,8 +348,8 @@ fn present_import_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
list.append(&password);
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Import a key")
|
||||
.body("This replaces the identity key Regent currently uses.")
|
||||
.heading("Import an identity key")
|
||||
.body("Leave this Regent's other identity keys untouched.")
|
||||
.extra_child(&list)
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
@@ -231,8 +360,8 @@ fn present_import_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let handles = handles.clone();
|
||||
let (entry, password) = (entry.clone(), password.clone());
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "import" {
|
||||
return;
|
||||
@@ -240,28 +369,73 @@ fn present_import_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let (text, password) = (entry.text().to_string(), password.text().to_string());
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
let text = entry.text().to_string();
|
||||
let password = password.text().to_string();
|
||||
let name = format!("Imported {count}", count = state.names().lock().unwrap().len() + 1);
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
async move {
|
||||
if text.starts_with("ncryptsec1") {
|
||||
store.import_user_key_encrypted(&text, &password).await
|
||||
store.import_user_key_encrypted(&name, &text, &password).await
|
||||
} else {
|
||||
store.import_user_key(&text).await
|
||||
store.import_user_key(&name, &text).await
|
||||
}
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(_) => state.notify(),
|
||||
Ok(_) => after.refresh_identities(),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn present_export_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
fn present_rename(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
public_key: PublicKey,
|
||||
current: &str,
|
||||
) {
|
||||
let entry = gtk::Entry::builder().text(current).build();
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Rename identity key")
|
||||
.extra_child(&entry)
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("rename", "Rename");
|
||||
dialog.set_default_response(Some("rename"));
|
||||
dialog.set_response_appearance("rename", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let entry = entry.clone();
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "rename" {
|
||||
return;
|
||||
}
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let name = defaulted_name(&entry);
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
async move { store.rename_user_key(&public_key, &name).await },
|
||||
move |result| match result {
|
||||
Ok(_) => after.refresh_identities(),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn present_export(handles: Handles, state: Rc<AppState>, public_key: PublicKey) {
|
||||
let password = adw::PasswordEntryRow::builder().title("Password").build();
|
||||
let list = gtk::ListBox::builder()
|
||||
.selection_mode(gtk::SelectionMode::None)
|
||||
@@ -270,7 +444,7 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
list.append(&password);
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Export identity key")
|
||||
.heading("Export identity key")
|
||||
.body(
|
||||
"The key is exported NIP-49 encrypted; you will need this password to import \
|
||||
it again.",
|
||||
@@ -294,9 +468,14 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let (password, handles, window) = (password.text().to_string(), handles.clone(), window.clone());
|
||||
let (password, handles, window) =
|
||||
(password.text().to_string(), handles.clone(), window.clone());
|
||||
runtime::spawn(
|
||||
async move { store.export_user_key_encrypted(&password).await },
|
||||
async move {
|
||||
store
|
||||
.export_user_key_encrypted(&public_key, &password)
|
||||
.await
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(ncryptsec) => {
|
||||
if let Some(window) = &window {
|
||||
@@ -309,7 +488,7 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
.css_classes(["monospace"])
|
||||
.build();
|
||||
let done = adw::AlertDialog::builder()
|
||||
.title("Exported")
|
||||
.heading("Exported")
|
||||
.body(
|
||||
"Copied to the clipboard. Store it somewhere safe — anyone \
|
||||
with this string and the password can sign as you.",
|
||||
@@ -326,10 +505,76 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>) {
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn present_remove(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
public_key: PublicKey,
|
||||
name: &str,
|
||||
) {
|
||||
let paired = state.registry().lock().unwrap().list_for(public_key);
|
||||
let body = if paired.is_empty() {
|
||||
format!("Remove “{name}” from the keyring? This cannot be undone.")
|
||||
} else {
|
||||
let apps: Vec<String> = paired
|
||||
.iter()
|
||||
.map(|app| app.name.clone().unwrap_or_else(|| "an unnamed application".to_string()))
|
||||
.collect();
|
||||
format!(
|
||||
"Remove “{name}”? These applications are paired with it and will be revoked: {}.",
|
||||
apps.join(", ")
|
||||
)
|
||||
};
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Remove identity key")
|
||||
.body(body)
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("remove", "Remove");
|
||||
dialog.set_response_appearance("remove", adw::ResponseAppearance::Destructive);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(&state));
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "remove" {
|
||||
return;
|
||||
}
|
||||
let Some(store) = state.store() else {
|
||||
return;
|
||||
};
|
||||
let registry = state.registry();
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
async move {
|
||||
registry.lock().unwrap().clear_for(public_key)?;
|
||||
store.forget_user_key(&public_key).await?;
|
||||
Ok::<(), crate::store::keys::Error>(())
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(()) => after.refresh_identities(),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn defaulted_name(entry: >k::Entry) -> String {
|
||||
let name = entry.text().to_string();
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
"Identity key".to_string()
|
||||
} else {
|
||||
name.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn report_error(handles: &Handles, message: &str) {
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Something went wrong")
|
||||
|
||||
+99
-19
@@ -4,9 +4,10 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::signer::approval::{Approver, Decision, Request};
|
||||
use crate::signer::approval::{Approver, Decision, Question, Request, SigningKey};
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::gdk;
|
||||
@@ -221,12 +222,10 @@ impl SignerView {
|
||||
);
|
||||
let approver = listener_approver.clone();
|
||||
runtime::spawn(
|
||||
async move { store.user_key().await },
|
||||
async move { store.list_user_keys().await },
|
||||
move |result| match result {
|
||||
Ok(Some(_)) => {
|
||||
start(handles, state, running, approver, Vec::new(), None)
|
||||
}
|
||||
Ok(None) => show_empty(&handles),
|
||||
Ok(keys) if keys.is_empty() => show_empty(&handles),
|
||||
Ok(_) => start(handles, state, running, approver, Vec::new(), None),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
@@ -253,7 +252,7 @@ fn start(
|
||||
running: Running,
|
||||
approver: Approver,
|
||||
extra_relays: Vec<String>,
|
||||
after: Option<ClientPairing>,
|
||||
after: Option<(ClientPairing, PublicKey)>,
|
||||
) {
|
||||
if !matches!(&*running.borrow(), State::Stopped) {
|
||||
return;
|
||||
@@ -272,17 +271,21 @@ fn start(
|
||||
let registry = state.registry();
|
||||
let activity = state.activity();
|
||||
let changes = state.changes();
|
||||
let names = state.names();
|
||||
let current = state.current_identity_handle();
|
||||
|
||||
runtime::spawn(
|
||||
async move {
|
||||
let mut config = SignerConfig::from_store(
|
||||
&store,
|
||||
store,
|
||||
relays,
|
||||
approver,
|
||||
registry,
|
||||
auto_approve_limit,
|
||||
activity,
|
||||
changes,
|
||||
names,
|
||||
current,
|
||||
)
|
||||
.await?;
|
||||
config.extra_relays = extra_relays;
|
||||
@@ -293,8 +296,8 @@ fn start(
|
||||
let started = Arc::new(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);
|
||||
if let Some((pairing, identity)) = after {
|
||||
pair_now(handles.clone(), state, &started, pairing, identity);
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -422,14 +425,47 @@ fn begin_pairing(
|
||||
}
|
||||
};
|
||||
|
||||
let client = pairing.client_info();
|
||||
let requested = pairing.requested.clone();
|
||||
// New pairings are bound to the currently selected identity.
|
||||
let Some(identity) = state.current_identity() else {
|
||||
report_error(
|
||||
handles,
|
||||
"Create an identity key on the Keys page first, then pair a client.",
|
||||
);
|
||||
return;
|
||||
};
|
||||
let name = state
|
||||
.names()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&identity.to_hex())
|
||||
.cloned();
|
||||
eprintln!(
|
||||
"regent: pairing as {}",
|
||||
identity.to_bech32().unwrap_or_else(|_| identity.to_hex())
|
||||
);
|
||||
let rebind_from = state
|
||||
.registry()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.identity_for(&pairing.client)
|
||||
.filter(|previous| *previous != identity);
|
||||
let question = Question {
|
||||
client: pairing.client_info(),
|
||||
request: Request::Pair {
|
||||
requested: pairing.requested.clone(),
|
||||
},
|
||||
identity: SigningKey {
|
||||
public_key: identity,
|
||||
name,
|
||||
},
|
||||
rebind_from,
|
||||
};
|
||||
|
||||
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;
|
||||
let decision = approval::present_question(&widget, &question).await;
|
||||
if decision == Decision::Deny {
|
||||
return;
|
||||
}
|
||||
@@ -446,7 +482,7 @@ fn begin_pairing(
|
||||
_ => None,
|
||||
};
|
||||
match signer {
|
||||
Some(signer) => pair_now(handles, state, &signer, pairing),
|
||||
Some(signer) => pair_now(handles, state, &signer, pairing, identity),
|
||||
None => {
|
||||
if state.store().is_none() {
|
||||
report_error(
|
||||
@@ -460,7 +496,14 @@ fn begin_pairing(
|
||||
.iter()
|
||||
.map(|relay| relay.to_string())
|
||||
.collect();
|
||||
start(handles, state, running, approver, extra, Some(pairing));
|
||||
start(
|
||||
handles,
|
||||
state,
|
||||
running,
|
||||
approver,
|
||||
extra,
|
||||
Some((pairing, identity)),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -469,25 +512,62 @@ fn begin_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) {
|
||||
fn pair_now(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
signer: &Arc<Signer>,
|
||||
pairing: ClientPairing,
|
||||
identity: PublicKey,
|
||||
) {
|
||||
let app_name = pairing
|
||||
.name
|
||||
.clone()
|
||||
.unwrap_or_else(|| "The application".to_string());
|
||||
let registry = state.registry();
|
||||
let activity = state.activity();
|
||||
let changes = state.changes();
|
||||
let signer = Arc::clone(signer);
|
||||
let refresh = Arc::clone(&signer);
|
||||
let ui_state = Rc::clone(&state);
|
||||
runtime::spawn(
|
||||
async move {
|
||||
signer.add_client_relays(&pairing.relays).await?;
|
||||
pair_client(&signer, ®istry, &activity, &changes, &pairing).await?;
|
||||
pair_client(&signer, ®istry, &activity, &changes, &pairing, identity).await?;
|
||||
Ok::<(), crate::signer::Error>(())
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(()) => show_running(&handles, &refresh),
|
||||
Ok(()) => {
|
||||
show_running(&handles, &refresh);
|
||||
present_paired(&handles, &app_name, &ui_state, identity);
|
||||
}
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Confirm which identity a freshly paired client was bound to.
|
||||
fn present_paired(handles: &Handles, app: &str, state: &Rc<AppState>, identity: PublicKey) {
|
||||
let name = state
|
||||
.names()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&identity.to_hex())
|
||||
.cloned();
|
||||
let npub = identity.to_bech32().unwrap_or_else(|_| identity.to_hex());
|
||||
let who = match name {
|
||||
Some(name) if !name.trim().is_empty() => format!("{name} ({npub})"),
|
||||
_ => npub,
|
||||
};
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Client paired")
|
||||
.body(format!("{app} now signs as {who}."))
|
||||
.build();
|
||||
plain::dialog(&dialog);
|
||||
dialog.add_response("close", "Close");
|
||||
dialog.set_default_response(Some("close"));
|
||||
dialog.present(toplevel(handles).as_ref());
|
||||
}
|
||||
|
||||
fn report_error(handles: &Handles, message: &str) {
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Something went wrong")
|
||||
|
||||
Reference in new issue
Block a user