Add key storage and a keys page
KeyStore keeps one Secret Service item per key: the identity key (the nsec, used only for signing) and a generated device key used for NIP-46 transport, so the transport key can be rotated without touching the identity. Includes NIP-49 export/import, zeroizing of in-memory copies, the tokio/main-loop bridge that the relay work will reuse, and an ignored test that round-trips everything against a real Secret Service.
This commit is contained in:
12 files changed
+2424
-20
No files matched your search
@@ -21,13 +21,34 @@ The full plan lives at `~/.opencode/plan/regent.md`.
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/main.rs resource registration, entry point
|
||||
src/main.rs resource registration, entry point, --version
|
||||
src/application.rs AdwApplication, actions, CSS
|
||||
src/window.rs main window (GtkBuilder from the GResource)
|
||||
src/config.rs GSettings wrapper
|
||||
src/runtime.rs tokio runtime + the bridge back to the GTK main loop
|
||||
src/store/keys.rs key storage (Secret Service, one item per key)
|
||||
src/ui/keys_view.rs the keys page
|
||||
data/ desktop, metainfo, gschema, icons, resources (ui/*.blp, style.css)
|
||||
```
|
||||
|
||||
## Keys
|
||||
|
||||
- The **identity key** is the user's `nsec`. It lives in the system keyring and
|
||||
is used only to sign events and to do nip04/nip44 on the user's behalf.
|
||||
- The **device key** is generated on first use and used for NIP-46 transport
|
||||
(encrypting/decrypting requests, signing responses). It is what relays and
|
||||
requesting apps see, and it can be rotated without touching the identity key.
|
||||
- Both are individual keyring items with attributes
|
||||
`application=org.kosmos.raucao.Regent` and `kind=user|device`.
|
||||
- **Never write the `nsec` to a file**, log it, or put it in argv/env. In-memory
|
||||
copies are wrapped in `zeroize::Zeroizing`; note that `Keys`/`SecretKey`
|
||||
zeroize on drop only if secp256k1 was built with `zeroize` (verify before
|
||||
claiming it).
|
||||
- Everything async goes through `runtime::spawn`, which runs the future on tokio
|
||||
and applies the result on the main loop. GTK objects are not `Send`, so a
|
||||
closure passed to `MainContext::invoke` cannot capture widgets — that is why
|
||||
results come back over a channel instead.
|
||||
|
||||
UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
|
||||
`blueprint-compiler`, bundled into the GResource, and loaded with
|
||||
`gtk::Builder` + `builder.object::<T>("id")`.
|
||||
@@ -93,9 +114,19 @@ the UI is tested. `build-aux/deploy-dev.sh` runs on the build host,
|
||||
|
||||
## Testing
|
||||
|
||||
- Key store against a real (throwaway) Secret Service:
|
||||
```sh
|
||||
dbus-run-session -- bash -c '
|
||||
export HOME=$(mktemp -d) && mkdir -p "$HOME/.local/share/keyrings"
|
||||
eval "$(printf test | gnome-keyring-daemon --unlock --components=secrets 2>/dev/null)"
|
||||
CARGO_TARGET_DIR=_build/cargo-target cargo test --release -- --ignored --nocapture'
|
||||
```
|
||||
Note `--daemonize` breaks this: it starts a daemon without the password, and
|
||||
every write then fails with `IsLocked("Cannot create an item in a locked
|
||||
collection")`.
|
||||
- Loopback with no public relays and no display:
|
||||
- `nak serve --port 10547` = writable in-memory relay.
|
||||
- `nak --sec 'bunker://…' …` = independent NIP‑46 *client*.
|
||||
- `nak --sec 'bunker://…' …` = independent NIP-46 *client*.
|
||||
- Headless GUI: see the recipe in `README.md` (`gtk4-broadwayd` +
|
||||
`dbus-run-session`).
|
||||
- Do **not** test against the host's `strfry` — it is a read-only mirror by
|
||||
|
||||
Generated
+1771
-9
File diff suppressed because it is too large.
Load diff
@@ -13,6 +13,12 @@ gtk = { package = "gtk4", version = "0.11", features = ["v4_24"] }
|
||||
libadwaita = { version = "0.9", features = ["v1_10"] }
|
||||
glib = "0.22"
|
||||
|
||||
nostr = { version = "0.45", features = ["nip49", "os-rng"] }
|
||||
oo7 = { version = "0.7", features = ["tokio"] }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
|
||||
async-channel = "2"
|
||||
zeroize = "1"
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
lto = true
|
||||
@@ -6,16 +6,10 @@ Adw.ApplicationWindow window {
|
||||
default-width: 420;
|
||||
default-height: 640;
|
||||
|
||||
content: Adw.ToolbarView {
|
||||
content: Adw.ToolbarView toolbar_view {
|
||||
[top]
|
||||
Adw.HeaderBar {}
|
||||
|
||||
content: Adw.StatusPage {
|
||||
icon-name: "security-high-symbolic";
|
||||
title: "Regent";
|
||||
description: "Nostr remote signer — no key configured yet";
|
||||
};
|
||||
|
||||
[bottom]
|
||||
Adw.Banner {
|
||||
title: "The signer is not running";
|
||||
|
||||
+6
-1
@@ -24,8 +24,13 @@ cargo_build = custom_target(binary_name,
|
||||
'Cargo.toml',
|
||||
'src/main.rs',
|
||||
'src/application.rs',
|
||||
'src/window.rs',
|
||||
'src/config.rs',
|
||||
'src/runtime.rs',
|
||||
'src/store/mod.rs',
|
||||
'src/store/keys.rs',
|
||||
'src/ui/mod.rs',
|
||||
'src/ui/keys_view.rs',
|
||||
'src/window.rs',
|
||||
),
|
||||
command: [
|
||||
find_program('sh'), '-c',
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
mod application;
|
||||
mod config;
|
||||
mod runtime;
|
||||
mod store;
|
||||
mod ui;
|
||||
mod window;
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! A shared async runtime, plus the bridge back to the GTK main loop.
|
||||
//!
|
||||
//! GTK objects are not `Send` and `MainContext::invoke` needs a `Send` closure,
|
||||
//! so results come back over a channel and are applied by a task running on the
|
||||
//! main context, where capturing widgets is allowed.
|
||||
|
||||
use std::future::Future;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use async_channel::bounded;
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
use gtk::glib;
|
||||
|
||||
fn runtime() -> &'static Runtime {
|
||||
static RUNTIME: OnceLock<Runtime> = OnceLock::new();
|
||||
RUNTIME.get_or_init(|| Runtime::new().expect("failed to start the async runtime"))
|
||||
}
|
||||
|
||||
/// Run `future` on the async runtime and hand the result to `then` on the main
|
||||
/// loop. Errors arrive stringified — they only ever end up in a dialog.
|
||||
///
|
||||
/// `then` may capture GTK widgets.
|
||||
pub fn spawn<F, T, E, C>(future: F, then: C)
|
||||
where
|
||||
F: Future<Output = Result<T, E>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
E: std::fmt::Display + Send + 'static,
|
||||
C: FnOnce(Result<T, String>) + 'static,
|
||||
{
|
||||
let (sender, receiver) = bounded(1);
|
||||
|
||||
runtime().spawn(async move {
|
||||
let result = future.await.map_err(|error| error.to_string());
|
||||
let _ = sender.send(result).await;
|
||||
});
|
||||
|
||||
glib::MainContext::default().spawn_local(async move {
|
||||
if let Ok(result) = receiver.recv().await {
|
||||
then(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! 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.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use nostr::prelude::*;
|
||||
use oo7::{Keyring, Secret};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::APP_ID;
|
||||
|
||||
pub const KIND_USER: &str = "user";
|
||||
pub const KIND_DEVICE: &str = "device";
|
||||
|
||||
/// 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;
|
||||
|
||||
pub type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
pub struct KeyStore {
|
||||
keyring: Keyring,
|
||||
}
|
||||
|
||||
impl KeyStore {
|
||||
/// Connect to the Secret Service (or the portal-backed store when
|
||||
/// sandboxed — `Keyring::new` picks).
|
||||
pub async fn connect() -> Result<Self> {
|
||||
Ok(Self {
|
||||
keyring: Keyring::new().await?,
|
||||
})
|
||||
}
|
||||
|
||||
fn 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
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
let keys = Keys::generate();
|
||||
self.store(KIND_DEVICE, "Regent device key", &keys).await?;
|
||||
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?;
|
||||
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(&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.
|
||||
let nsec = Zeroizing::new(keys.secret_key().to_bech32()?);
|
||||
self.keyring
|
||||
.create_item(label, &Self::attributes(kind), Secret::text(nsec.as_str()), true)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Exercises the real Secret Service, so it is ignored by default:
|
||||
///
|
||||
/// ```sh
|
||||
/// dbus-run-session -- bash -c '
|
||||
/// printf test | gnome-keyring-daemon --unlock --components=secrets --daemonize
|
||||
/// 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;
|
||||
|
||||
// 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());
|
||||
|
||||
// NIP-49 export, then import into an emptied store.
|
||||
let ncryptsec = store
|
||||
.export_user_key_encrypted("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());
|
||||
|
||||
let imported = store
|
||||
.import_user_key_encrypted(&ncryptsec, "hunter2")
|
||||
.await
|
||||
.expect("import");
|
||||
assert_eq!(imported, generated);
|
||||
|
||||
// The wrong password must not import.
|
||||
assert!(store
|
||||
.import_user_key_encrypted(&ncryptsec, "wrong")
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
store.forget_user_key().await.expect("clean up");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
//! Persistent state: the keyring today, the application registry later.
|
||||
|
||||
pub mod keys;
|
||||
@@ -0,0 +1,358 @@
|
||||
//! The keys page: shows the identity and device keys, and lets you create or
|
||||
//! import the identity key.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nostr::key::Keys;
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
use crate::runtime;
|
||||
use crate::store::keys::KeyStore;
|
||||
|
||||
/// Shared handles a callback needs to render a state change.
|
||||
#[derive(Clone)]
|
||||
struct Handles {
|
||||
stack: gtk::Stack,
|
||||
identity: adw::ActionRow,
|
||||
device: adw::ActionRow,
|
||||
}
|
||||
|
||||
/// The store is only available once the keyring connection succeeded.
|
||||
type StoreCell = Rc<RefCell<Option<Arc<KeyStore>>>>;
|
||||
|
||||
pub struct KeysView {
|
||||
pub widget: gtk::Widget,
|
||||
}
|
||||
|
||||
impl KeysView {
|
||||
pub fn new() -> Self {
|
||||
let handles = Handles {
|
||||
stack: gtk::Stack::builder().vexpand(true).build(),
|
||||
identity: adw::ActionRow::builder()
|
||||
.title("Identity key")
|
||||
.subtitle("—")
|
||||
.build(),
|
||||
device: adw::ActionRow::builder()
|
||||
.title("Device key")
|
||||
.subtitle("—")
|
||||
.build(),
|
||||
};
|
||||
|
||||
let loading = adw::StatusPage::builder()
|
||||
.title("Connecting to the keyring…")
|
||||
.child(&adw::Spinner::new())
|
||||
.build();
|
||||
handles.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"])
|
||||
.build();
|
||||
let import = gtk::Button::builder()
|
||||
.label("Import a key…")
|
||||
.css_classes(["pill"])
|
||||
.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.",
|
||||
)
|
||||
.child(&actions)
|
||||
.build();
|
||||
handles.stack.add_named(&empty, Some("empty"));
|
||||
|
||||
let copy_npub = gtk::Button::builder()
|
||||
.icon_name("edit-copy-symbolic")
|
||||
.tooltip_text("Copy public key")
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
handles.identity.add_suffix(©_npub);
|
||||
|
||||
let export = gtk::Button::builder()
|
||||
.label("Export…")
|
||||
.valign(gtk::Align::Center)
|
||||
.css_classes(["flat"])
|
||||
.build();
|
||||
let export_row = adw::ActionRow::builder()
|
||||
.title("Export identity key")
|
||||
.subtitle("Encrypted with a password (NIP-49)")
|
||||
.build();
|
||||
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);
|
||||
|
||||
let page = adw::PreferencesPage::new();
|
||||
page.add(&group);
|
||||
handles.stack.add_named(&page, Some("loaded"));
|
||||
|
||||
handles.stack.set_visible_child_name("loading");
|
||||
|
||||
let store: StoreCell = Rc::new(RefCell::new(None));
|
||||
|
||||
{
|
||||
let (handles, store) = (handles.clone(), Rc::clone(&store));
|
||||
create.connect_clicked(move |_| {
|
||||
let Some(store) = store.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
{
|
||||
let store = Arc::clone(&store);
|
||||
async move { store.generate_user_key().await }
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(_) => reload_identity(handles, store),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, store) = (handles.clone(), Rc::clone(&store));
|
||||
import.connect_clicked(move |_| {
|
||||
let Some(store) = store.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
present_import_dialog(handles.clone(), store);
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, store) = (handles.clone(), Rc::clone(&store));
|
||||
copy_npub.connect_clicked(move |button| {
|
||||
let Some(store) = store.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
let window = button.root().and_downcast::<gtk::Window>();
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
{
|
||||
let store = Arc::clone(&store);
|
||||
async move { store.user_key().await }
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(Some(keys)) => {
|
||||
if let Some(window) = &window {
|
||||
window
|
||||
.clipboard()
|
||||
.set_text(&keys.public_key().to_bech32().unwrap_or_default());
|
||||
}
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let (handles, store) = (handles.clone(), Rc::clone(&store));
|
||||
export.connect_clicked(move |_| {
|
||||
let Some(store) = store.borrow().clone() else {
|
||||
return;
|
||||
};
|
||||
present_export_dialog(handles.clone(), store);
|
||||
});
|
||||
}
|
||||
|
||||
// Connect to the keyring, then load what is there.
|
||||
{
|
||||
let (handles, store) = (handles.clone(), Rc::clone(&store));
|
||||
runtime::spawn(KeyStore::connect(), move |result| match result {
|
||||
Ok(connected) => {
|
||||
let connected = Arc::new(connected);
|
||||
*store.borrow_mut() = Some(Arc::clone(&connected));
|
||||
reload_identity(handles.clone(), Arc::clone(&connected));
|
||||
reload_device(handles, connected);
|
||||
}
|
||||
Err(error) => report_error(&handles, &error),
|
||||
});
|
||||
}
|
||||
|
||||
Self {
|
||||
widget: handles.stack.clone().upcast(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
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);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn reload_device(handles: Handles, store: Arc<KeyStore>) {
|
||||
runtime::spawn(
|
||||
async move { store.device_key().await },
|
||||
move |result| match result {
|
||||
Ok(keys) => set_public_key(&handles.device, &keys),
|
||||
Err(error) => {
|
||||
handles.device.set_subtitle("unavailable");
|
||||
report_error(&handles, &error);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn set_public_key(row: &adw::ActionRow, keys: &Keys) {
|
||||
row.set_subtitle(&keys.public_key().to_bech32().unwrap_or_default());
|
||||
}
|
||||
|
||||
fn present_import_dialog(handles: Handles, store: Arc<KeyStore>) {
|
||||
let entry = adw::EntryRow::builder().title("nsec, hex, or ncryptsec").build();
|
||||
let password = adw::PasswordEntryRow::builder()
|
||||
.title("Password (ncryptsec only)")
|
||||
.build();
|
||||
let list = gtk::ListBox::builder()
|
||||
.selection_mode(gtk::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
list.append(&entry);
|
||||
list.append(&password);
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Import a key")
|
||||
.body("This replaces the identity key Regent currently uses.")
|
||||
.extra_child(&list)
|
||||
.build();
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("import", "Import");
|
||||
dialog.set_default_response(Some("import"));
|
||||
dialog.set_response_appearance("import", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let handles = handles.clone();
|
||||
let (entry, password) = (entry.clone(), password.clone());
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "import" {
|
||||
return;
|
||||
}
|
||||
let (text, password) = (entry.text().to_string(), password.text().to_string());
|
||||
let handles = handles.clone();
|
||||
let task_store = Arc::clone(&store);
|
||||
let reload_store = Arc::clone(&store);
|
||||
runtime::spawn(
|
||||
async move {
|
||||
if text.starts_with("ncryptsec1") {
|
||||
task_store.import_user_key_encrypted(&text, &password).await
|
||||
} else {
|
||||
task_store.import_user_key(&text).await
|
||||
}
|
||||
},
|
||||
move |result| match result {
|
||||
Ok(_) => reload_identity(handles, reload_store),
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
dialog.present(handles.stack.root().and_downcast::<gtk::Window>().as_ref());
|
||||
}
|
||||
|
||||
fn present_export_dialog(handles: Handles, store: Arc<KeyStore>) {
|
||||
let password = adw::PasswordEntryRow::builder()
|
||||
.title("Password")
|
||||
.build();
|
||||
let list = gtk::ListBox::builder()
|
||||
.selection_mode(gtk::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
list.append(&password);
|
||||
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Export identity key")
|
||||
.body("The key is exported NIP-49 encrypted; you will need this password to import it again.")
|
||||
.extra_child(&list)
|
||||
.build();
|
||||
dialog.add_response("cancel", "Cancel");
|
||||
dialog.add_response("export", "Export");
|
||||
dialog.set_default_response(Some("export"));
|
||||
dialog.set_response_appearance("export", adw::ResponseAppearance::Suggested);
|
||||
dialog.set_close_response("cancel");
|
||||
|
||||
{
|
||||
let handles = handles.clone();
|
||||
let window = handles.stack.root().and_downcast::<gtk::Window>();
|
||||
dialog.connect_response(None, move |_, response| {
|
||||
if response != "export" {
|
||||
return;
|
||||
}
|
||||
let password = password.text().to_string();
|
||||
let handles = handles.clone();
|
||||
let store = Arc::clone(&store);
|
||||
let window = window.clone();
|
||||
runtime::spawn(
|
||||
async move { store.export_user_key_encrypted(&password).await },
|
||||
move |result| match result {
|
||||
Ok(ncryptsec) => {
|
||||
if let Some(window) = &window {
|
||||
window.clipboard().set_text(&ncryptsec);
|
||||
}
|
||||
let label = gtk::Label::builder()
|
||||
.label(ncryptsec.as_str())
|
||||
.wrap(true)
|
||||
.selectable(true)
|
||||
.css_classes(["monospace"])
|
||||
.build();
|
||||
let done = adw::AlertDialog::builder()
|
||||
.title("Exported")
|
||||
.body("Copied to the clipboard. Store it somewhere safe — anyone with this string and the password can sign as you.")
|
||||
.extra_child(&label)
|
||||
.build();
|
||||
done.add_response("close", "Close");
|
||||
done.set_default_response(Some("close"));
|
||||
done.present(window.as_ref());
|
||||
}
|
||||
Err(error) => report_error(&handles, &error),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
dialog.present(handles.stack.root().and_downcast::<gtk::Window>().as_ref());
|
||||
}
|
||||
|
||||
fn report_error(handles: &Handles, message: &str) {
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.title("Something went wrong")
|
||||
.body(message)
|
||||
.build();
|
||||
dialog.add_response("close", "Close");
|
||||
dialog.set_default_response(Some("close"));
|
||||
dialog.present(handles.stack.root().and_downcast::<gtk::Window>().as_ref());
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
//! User interface.
|
||||
|
||||
pub mod keys_view;
|
||||
+9
-1
@@ -1,10 +1,12 @@
|
||||
//! The main window. Built from Blueprint via `GtkBuilder` (see `AGENTS.md` for
|
||||
//! why this is not a `CompositeTemplate` subclass yet).
|
||||
//! why this is not a `CompositeTemplate` subclass yet); the content is composed
|
||||
//! in Rust.
|
||||
|
||||
use gtk::prelude::*;
|
||||
use libadwaita as adw;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::ui::keys_view::KeysView;
|
||||
use crate::RESOURCE_PATH;
|
||||
|
||||
pub struct Window {
|
||||
@@ -19,6 +21,12 @@ impl Window {
|
||||
let window: adw::ApplicationWindow = builder
|
||||
.object("window")
|
||||
.expect("ui/window.blp must contain an object with id \"window\"");
|
||||
let toolbar_view: adw::ToolbarView = builder
|
||||
.object("toolbar_view")
|
||||
.expect("ui/window.blp must contain an object with id \"toolbar_view\"");
|
||||
|
||||
let keys_view = KeysView::new();
|
||||
toolbar_view.set_content(Some(&keys_view.widget));
|
||||
|
||||
window.set_application(Some(app));
|
||||
window.set_default_size(config.window_width(), config.window_height());
|
||||
|
||||
Reference in new issue
Block a user