Add M5: per-app permissions page and activity log

This commit is contained in:
raucao committed 2026-11-13 22:33:33 +04:00
1 parent 30ba603df7
commit 556201849d
17 files changed
+1505 -114

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@
<schemalist gettext-domain="regent">
<schema id="org.kosmos.raucao.Regent" path="/org/kosmos/raucao/Regent/">
<key name="window-width" type="i">
<default>420</default>
<default>480</default>
<summary>Window width</summary>
<description>Width of the main window, in pixels.</description>
</key>
+4
View File
@@ -31,9 +31,13 @@ cargo_build = custom_target(binary_name,
'src/signer/policy.rs',
'src/state.rs',
'src/store/apps.rs',
'src/store/audit.rs',
'src/store/mod.rs',
'src/store/keys.rs',
'src/ui/activity_view.rs',
'src/ui/apps_view.rs',
'src/ui/approval.rs',
'src/ui/kind.rs',
'src/ui/keys_view.rs',
'src/ui/mod.rs',
'src/ui/plain.rs',
+8 -1
View File
@@ -1,9 +1,12 @@
//! Application object, actions and global setup.
use std::rc::Rc;
use gtk::gio;
use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::window::Window;
use crate::{APP_ID, RESOURCE_PATH};
@@ -18,8 +21,12 @@ pub fn run() -> glib::ExitCode {
app.add_action(&quit);
app.set_accels_for_action("app.quit", &["<primary>q"]);
// One shared state per process, not per window: every window must see the
// same registry and signer.
let state = AppState::new();
app.connect_startup(|_| load_css());
app.connect_activate(|app| Window::new(app).present());
app.connect_activate(move |app| Window::new(app, Rc::clone(&state)).present());
// The resource file is passed through the environment, not argv, so that
// GApplication does not try to interpret it.
+17 -3
View File
@@ -33,7 +33,12 @@ pub struct ClientInfo {
#[derive(Debug, Clone)]
pub enum Request {
/// An application wants to connect for the first time.
Pair,
Pair {
/// Permissions the client asked for in `connect` (NIP-46 `params[2]`,
/// the same string as `nostrconnect://…&perms=`). Client-supplied and
/// shown for context only; granting stays per-request.
requested: Option<String>,
},
/// An event would be signed with the identity key.
Sign {
kind: u16,
@@ -146,7 +151,11 @@ mod tests {
}
});
let decision = approver
.ask_within(Duration::from_millis(50), client(), Request::Pair)
.ask_within(
Duration::from_millis(50),
client(),
Request::Pair { requested: None },
)
.await;
assert_eq!(decision, Decision::Deny);
holding.abort();
@@ -157,7 +166,12 @@ mod tests {
async fn a_missing_ui_is_a_denial() {
let (approver, questions) = Approver::new();
let drain = tokio::spawn(async move { while questions.recv().await.is_ok() {} });
assert_eq!(approver.ask(client(), Request::Pair).await, Decision::Deny);
assert_eq!(
approver
.ask(client(), Request::Pair { requested: None })
.await,
Decision::Deny
);
drain.abort();
}
}
+377 -35
View File
@@ -4,9 +4,8 @@
//! key, Regent answers, and the identity key only ever signs events or does
//! encryption on the user's behalf.
//!
//! **M2 state:** every request is answered without asking. Approving pairings
//! arrives in M3 and per-request approval in M4, so nothing here should be
//! presented as a working signer yet.
//! 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::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
@@ -19,6 +18,7 @@ use nostr_sdk::prelude::*;
use self::approval::{Approver, ClientInfo, Decision, Request};
use self::policy::RateLimiter;
use crate::store::apps::{AppRegistry, Permission};
use crate::store::audit::{self, ActivityLog, Entry};
use crate::store::keys::KeyStore;
pub mod approval;
@@ -42,6 +42,10 @@ pub struct SignerConfig {
pub registry: Arc<Mutex<AppRegistry>>,
/// Caps silent answers for each stored "always" permission.
pub rate: RateLimiter,
/// Where decisions are recorded.
pub activity: ActivityLog,
/// Wakes the apps/activity pages after a registry or log change.
pub changes: async_channel::Sender<()>,
}
impl SignerConfig {
@@ -51,6 +55,8 @@ impl SignerConfig {
approver: Approver,
registry: Arc<Mutex<AppRegistry>>,
auto_approve_limit: u32,
activity: ActivityLog,
changes: async_channel::Sender<()>,
) -> Result<Self> {
Ok(Self {
device_keys: store.device_key().await?,
@@ -63,6 +69,8 @@ impl SignerConfig {
approver,
registry,
rate: RateLimiter::new(auto_approve_limit),
activity,
changes,
})
}
@@ -277,15 +285,29 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
} else if approved {
Ok("ack".to_string())
} else {
match config.approver.ask(client.clone(), Request::Pair).await {
Decision::Deny => Err("the user declined the connection".to_string()),
_ => config
.registry
.lock()
.unwrap()
.approve(&client)
.map(|()| "ack".to_string())
.map_err(|error| format!("could not record the approval: {error}")),
let requested = requested_perms(&params);
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
.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);
}
result
}
}
}
}
@@ -305,6 +327,30 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
}
"switch_relays" => Ok(serde_json::json!(config.relays).to_string()),
"ping" => Ok("pong".to_string()),
// Regent extension, not part of NIP-46: let a client see what it may do.
"get_permissions" => {
let policy = config.registry.lock().unwrap().permissions(&event.pubkey);
Ok(serde_json::json!({
"methods": policy.methods,
"kinds": policy.kinds,
})
.to_string())
}
// The client asks to be forgotten: drop the approval and its permissions.
"logout" => {
let result = config
.registry
.lock()
.unwrap()
.revoke(&event.pubkey)
.map(|()| "ack".to_string())
.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);
}
result
}
"sign_event" => match incoming(params.first()) {
Err(error) => Err(error),
Ok(incoming) => {
@@ -314,9 +360,10 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
preview: preview(&incoming.content),
tags: tag_summary(&incoming.tags),
};
let permission = Permission::Kind(kind);
match gate(config, &client, request, Some(permission)).await {
Decision::Deny => Err("the user declined to sign the event".to_string()),
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),
}
}
@@ -329,9 +376,11 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
let permission = Permission::Method(m.to_string());
match gate(config, &client, request, Some(permission)).await {
Decision::Deny => Err("the user declined to encrypt the message".to_string()),
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(&params)),
}
}
@@ -346,8 +395,10 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
peer: peer.to_bech32().unwrap_or_else(|_| peer.to_hex()),
preview: preview(payload(&params)),
};
match gate(config, &client, request, None).await {
Decision::Deny => Err("the user declined to decrypt the message".to_string()),
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(&params)),
}
}
@@ -358,6 +409,27 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
respond(config, event, &id, result)
}
/// How a request was answered, in enough detail for the activity log to tell a
/// silent (permission-covered) answer from one the user actually gave.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Verdict {
Deny,
AllowOnce,
AllowAlways,
Silent,
}
impl Verdict {
fn outcome(self) -> &'static str {
match self {
Verdict::Deny => audit::outcome::DENIED,
Verdict::AllowOnce => audit::outcome::ALLOWED_ONCE,
Verdict::AllowAlways => audit::outcome::ALLOWED_ALWAYS,
Verdict::Silent => audit::outcome::SILENT,
}
}
}
/// Put a request to the user unless a stored permission covers it.
///
/// The policy check and the recording are both short, synchronous lock
@@ -367,7 +439,7 @@ async fn gate(
client: &ClientInfo,
request: Request,
permission: Option<Permission>,
) -> Decision {
) -> Verdict {
if let Some(permission) = &permission {
let covered = config
.registry
@@ -375,25 +447,69 @@ async fn gate(
.unwrap()
.permits(&client.public_key, permission);
if covered && config.rate.claim(&client.public_key.to_hex()) {
return Decision::Once;
return Verdict::Silent;
}
}
let decision = config.approver.ask(client.clone(), request).await;
if decision == Decision::Always {
if let Some(permission) = permission {
if let Err(error) = config
.registry
.lock()
.unwrap()
.allow(&client.public_key, permission)
{
eprintln!("regent: could not remember the permission: {error}");
// The user may have revoked the app while the dialog was open. Re-check
// before acting, otherwise a revoked client still gets its answer.
if decision != Decision::Deny && !config.registry.lock().unwrap().contains(&client.public_key)
{
return Verdict::Deny;
}
match decision {
Decision::Deny => Verdict::Deny,
Decision::Once => Verdict::AllowOnce,
Decision::Always => {
if let Some(permission) = permission {
if let Err(error) = config
.registry
.lock()
.unwrap()
.allow(&client.public_key, permission)
{
// The user allowed this once, but it could not be stored —
// record it honestly, because the next request will ask.
eprintln!("regent: could not remember the permission: {error}");
return Verdict::AllowOnce;
}
}
Verdict::AllowAlways
}
}
decision
}
/// Record a decision and wake the pages that display it.
///
/// Metadata only: the activity log must never contain event content, plaintext
/// or ciphertext. Unapproved requests are deliberately **not** recorded, so a
/// stranger who knows the device key cannot flush the history.
fn record(
config: &SignerConfig,
client: &ClientInfo,
method: &str,
kind: Option<u16>,
outcome: &str,
) {
config.activity.record(&Entry {
at: now_secs(),
app: client.public_key.to_hex(),
name: client.name.clone(),
method: method.to_string(),
kind,
outcome: outcome.to_string(),
});
let _ = config.changes.try_send(());
}
fn now_secs() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|since| since.as_secs() as i64)
.unwrap_or_default()
}
/// A client with no recorded metadata, for an approved key we cannot describe.
@@ -491,6 +607,19 @@ fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
}
}
/// The permissions a client asked for in `connect`, if any.
///
/// NIP-46 puts them in `params[2]` as `method[:params],…` — the same string as
/// `nostrconnect://…&perms=`. They are a request, not a grant: the dialog shows
/// them, but the user's per-request answers still decide what is allowed.
fn requested_perms(params: &[String]) -> Option<String> {
let raw = params.get(2)?.trim();
if raw.is_empty() {
return None;
}
Some(raw.chars().take(200).collect())
}
/// An event a client asked to have signed, still unsigned.
struct Incoming {
kind: Kind,
@@ -701,6 +830,21 @@ mod tests {
}
fn config(relay: &str, approver: Approver) -> SignerConfig {
let (changes, _receiver) = async_channel::unbounded();
config_with(
relay,
approver,
ActivityLog::at(std::path::PathBuf::new()),
changes,
)
}
fn config_with(
relay: &str,
approver: Approver,
activity: ActivityLog,
changes: async_channel::Sender<()>,
) -> SignerConfig {
SignerConfig {
device_keys: Keys::generate(),
user_keys: Keys::generate(),
@@ -709,9 +853,37 @@ mod tests {
approver,
registry: Arc::new(Mutex::new(AppRegistry::default())),
rate: RateLimiter::new(60),
activity,
changes,
}
}
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!(
"regent-signer-audit-{}-{}.jsonl",
std::process::id(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let _ = std::fs::remove_file(&path);
(path.clone(), ActivityLog::at(path))
}
/// Sign once and return the client-visible answer.
async fn sign_once(
client: &Keys,
device: &PublicKey,
config: &SignerConfig,
content: &str,
) -> serde_json::Value {
let request = client_request(client, device, "sign_event", sign_params(1, content));
let response = handle_request(&request, config)
.await
.expect("handle")
.expect("an answer");
read_response(&response, client, device)
}
async fn nak_signs(uri: &str) -> std::process::Output {
tokio::process::Command::new("nak")
.args(["event", "--sec", uri, "-c", "hello from nak through regent"])
@@ -780,7 +952,7 @@ mod tests {
async fn nak_signing_is_refused_when_the_user_says_no() {
let mut relay = TestRelay::start().await;
let (approver, approvals, _) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
Request::Pair { .. } => Decision::Always,
_ => Decision::Deny,
});
let config = config(&relay.relay, approver);
@@ -947,7 +1119,7 @@ mod tests {
async fn signing_asks_and_a_denial_reaches_the_client() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
Request::Pair { .. } => Decision::Always,
_ => Decision::Deny,
});
let config = config("ws://127.0.0.1:1", approver);
@@ -992,7 +1164,7 @@ mod tests {
async fn allow_always_skips_the_next_ask_for_that_kind() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|request| match request {
Request::Pair => Decision::Always,
Request::Pair { .. } => Decision::Always,
Request::Sign { kind: 7, .. } => Decision::Deny,
_ => Decision::Always,
});
@@ -1130,4 +1302,174 @@ mod tests {
);
}
/// The activity log is metadata only: event content must never appear in it.
#[tokio::test]
async fn event_content_never_reaches_the_log() {
const CANARY: &str = "CANARY-DO-NOT-LOG-12345";
let client = Keys::generate();
let (path, log) = temp_log();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let (changes, _changes_rx) = async_channel::unbounded();
let config = config_with("ws://127.0.0.1:1", approver, log.clone(), changes);
let device = pair(&client, &config).await;
let answer = sign_once(&client, &device, &config, CANARY).await;
task.abort();
assert!(answer["result"].is_string());
let entries = log.recent(10);
assert!(entries.iter().any(|entry| entry.method == "sign_event"));
assert!(entries.iter().any(|entry| entry.kind == Some(1)));
let raw = std::fs::read_to_string(&path).expect("read the log");
assert!(
!raw.contains(CANARY),
"event content must never reach the log"
);
let _ = std::fs::remove_file(&path);
}
/// Revoking a stored permission brings the prompt back immediately — this
/// is "the policy table drives behaviour".
#[tokio::test]
async fn revoking_a_permission_makes_the_next_request_ask() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert!(sign_once(&client, &device, &config, "one").await["result"].is_string());
assert!(sign_once(&client, &device, &config, "two").await["result"].is_string());
assert_eq!(sign_asks(&seen), 1, "the second request was silent");
config
.registry
.lock()
.unwrap()
.revoke_permission(&client.public_key(), &Permission::Kind(1))
.unwrap();
assert!(sign_once(&client, &device, &config, "three").await["result"].is_string());
task.abort();
assert_eq!(sign_asks(&seen), 2, "revoking must bring the prompt back");
}
/// A stranger cannot flush the history by spamming unapproved requests.
#[tokio::test]
async fn unapproved_requests_are_not_logged() {
let client = Keys::generate();
let (path, log) = temp_log();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let (changes, _changes_rx) = async_channel::unbounded();
let config = config_with("ws://127.0.0.1:1", approver, log.clone(), changes);
let device = config.device_keys.public_key();
for _ in 0..20 {
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["error"].is_string());
}
task.abort();
assert!(
log.recent(50).is_empty(),
"unapproved requests stay out of the log"
);
let _ = std::fs::remove_file(&path);
}
/// Logout forgets the application; connecting afterwards asks again.
#[tokio::test]
async fn logout_forgets_the_application() {
let client = Keys::generate();
let (approver, task, seen) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert!(config.registry.lock().unwrap().contains(&client.public_key()));
let request = client_request(&client, &device, "logout", serde_json::json!([]));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["result"].is_string());
assert!(!config.registry.lock().unwrap().contains(&client.public_key()));
// A request after logout is refused.
let request = client_request(&client, &device, "sign_event", sign_params(1, "hi"));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
assert!(read_response(&response, &client, &device)["error"].is_string());
let pairs_before = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Pair { .. }))
.count();
pair(&client, &config).await;
let pairs_after = seen
.lock()
.unwrap()
.iter()
.filter(|request| matches!(request, Request::Pair { .. }))
.count();
task.abort();
assert_eq!(pairs_after, pairs_before + 1, "reconnecting must ask again");
}
/// A client can see what it may do without asking.
#[tokio::test]
async fn stored_permissions_are_reported_to_the_client() {
let client = Keys::generate();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert!(sign_once(&client, &device, &config, "one").await["result"].is_string());
let request = client_request(&client, &device, "get_permissions", serde_json::json!([]));
let response = handle_request(&request, &config)
.await
.expect("handle")
.expect("an answer");
let answer = read_response(&response, &client, &device);
task.abort();
let policy: serde_json::Value =
serde_json::from_str(answer["result"].as_str().expect("a result")).unwrap();
assert_eq!(policy["kinds"], serde_json::json!([1]));
assert_eq!(policy["methods"], serde_json::json!([]));
}
/// Registry changes wake the Apps and Activity pages.
#[tokio::test]
async fn registry_changes_are_announced() {
let client = Keys::generate();
let (approver, task, _) = recording_approver(|_| Decision::Always);
let (changes, changes_rx) = async_channel::unbounded();
let config = config_with(
"ws://127.0.0.1:1",
approver,
ActivityLog::at(std::path::PathBuf::new()),
changes,
);
let device = pair(&client, &config).await;
assert!(
changes_rx.try_recv().is_ok(),
"pairing announces a change"
);
assert!(sign_once(&client, &device, &config, "one").await["result"].is_string());
task.abort();
assert!(
changes_rx.try_recv().is_ok(),
"a signature announces a change"
);
}
}
+71 -15
View File
@@ -1,27 +1,54 @@
//! Shared application state: the key store once it is connected, plus a way for
//! views to be told that something changed.
//! 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.
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::{Arc, Mutex};
use crate::runtime;
use crate::store::apps::AppRegistry;
use crate::store::audit::ActivityLog;
use crate::store::keys::KeyStore;
type Listener = Rc<dyn Fn()>;
pub struct AppState {
store: RefCell<Option<Arc<KeyStore>>>,
listeners: RefCell<Vec<Box<dyn Fn()>>>,
/// Shared with the responder, which runs on tokio.
registry: Arc<Mutex<AppRegistry>>,
/// Shared with the responder; cloning shares the file lock too.
activity: ActivityLog,
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.
changes: async_channel::Sender<()>,
}
impl AppState {
/// Connect to the keyring in the background; listeners are told when it is
/// ready.
/// Build the one shared state. Called once per process, not per window.
pub fn new() -> Rc<Self> {
let (changes, changes_rx) = async_channel::bounded(1);
let state = Rc::new(Self {
store: RefCell::new(None),
registry: Arc::new(Mutex::new(AppRegistry::load())),
activity: ActivityLog::new(),
listeners: RefCell::new(Vec::new()),
change_listeners: RefCell::new(Vec::new()),
changes,
});
{
let state = Rc::clone(&state);
glib::MainContext::default().spawn_local(async move {
while changes_rx.recv().await.is_ok() {
state.notify_changes();
}
});
}
let connecting = Rc::clone(&state);
runtime::spawn(KeyStore::connect(), move |result| match result {
Ok(store) => {
@@ -38,21 +65,50 @@ impl AppState {
self.store.borrow().clone()
}
/// Register a listener; it runs immediately if the store is already up.
/// The registry of approved applications, shared with the responder.
pub fn registry(&self) -> Arc<Mutex<AppRegistry>> {
Arc::clone(&self.registry)
}
/// The activity log, shared with the responder.
pub fn activity(&self) -> ActivityLog {
self.activity.clone()
}
/// A sender the responder uses to announce registry or log changes.
pub fn changes(&self) -> async_channel::Sender<()> {
self.changes.clone()
}
/// Register a listener for key/store changes; it runs immediately if the
/// store is already up.
pub fn listen(&self, listener: impl Fn() + 'static) {
let already_ready = self.store.borrow().is_some();
self.listeners.borrow_mut().push(Box::new(listener));
if already_ready {
let listeners = self.listeners.borrow();
if let Some(listener) = listeners.last() {
listener();
}
let listener: Listener = Rc::new(listener);
self.listeners.borrow_mut().push(Rc::clone(&listener));
if self.store.borrow().is_some() {
listener();
}
}
/// Announce that the keys (or the store) changed.
pub fn notify(&self) {
for listener in self.listeners.borrow().iter() {
for listener in self.listeners.borrow().clone() {
listener();
}
}
/// 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.notify_changes();
}
/// Announce that the registry or the activity log changed.
pub fn notify_changes(&self) {
for listener in self.change_listeners.borrow().clone() {
listener();
}
}
+184 -19
View File
@@ -29,7 +29,7 @@ pub enum Permission {
}
/// What an application may do without being asked.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Policy {
/// NIP method names approved wholesale.
#[serde(default)]
@@ -59,36 +59,77 @@ pub struct App {
pub policy: Policy,
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[derive(Debug, Serialize, Deserialize)]
pub struct AppRegistry {
/// Where this registry is saved. Empty means "ephemeral", which is what
/// tests use so they never touch the real `apps.json`.
#[serde(skip)]
path: PathBuf,
#[serde(default)]
pub apps: Vec<App>,
apps: Vec<App>,
}
impl Default for AppRegistry {
fn default() -> Self {
Self {
path: PathBuf::new(),
apps: Vec::new(),
}
}
}
impl AppRegistry {
pub fn path() -> PathBuf {
/// Where the real registry lives.
pub fn default_path() -> PathBuf {
glib::user_config_dir().join(APP_ID).join("apps.json")
}
/// Load from disk; a missing or unreadable file is simply an empty registry
/// (denying everything is the safe failure).
/// Load the real registry from disk; a missing or unreadable file is an
/// empty registry (denying everything is the safe failure).
pub fn load() -> Self {
let path = Self::path();
Self::at(Self::default_path())
}
/// Load a registry from an explicit path. Used by tests, and by `load`.
///
/// An unreadable file is moved aside rather than silently overwritten on
/// the next save, so a corrupt registry can still be recovered by hand.
pub fn at(path: PathBuf) -> Self {
match std::fs::read_to_string(&path) {
Ok(contents) => serde_json::from_str(&contents).unwrap_or_else(|error| {
eprintln!("regent: ignoring unreadable {}: {error}", path.display());
Self::default()
}),
Err(_) => Self::default(),
Ok(contents) => match serde_json::from_str::<Self>(&contents) {
Ok(mut registry) => {
registry.path = path;
registry
}
Err(error) => {
eprintln!("regent: moving unreadable {} aside: {error}", path.display());
let _ = std::fs::rename(&path, path.with_extension("json.corrupt"));
Self {
path,
apps: Vec::new(),
}
}
},
Err(_) => Self {
path,
apps: Vec::new(),
},
}
}
/// Write the registry out atomically: an approval must never leave a
/// truncated file behind. An ephemeral registry (no path) does nothing.
pub fn save(&self) -> Result<()> {
let path = Self::path();
if let Some(parent) = path.parent() {
if self.path.as_os_str().is_empty() {
return Ok(());
}
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, serde_json::to_string_pretty(self)?)?;
let contents = serde_json::to_string_pretty(self)?;
let temporary = self.path.with_extension("json.tmp");
write_private(&temporary, contents.as_bytes())?;
std::fs::rename(&temporary, &self.path)?;
Ok(())
}
@@ -123,6 +164,16 @@ impl AppRegistry {
}
}
/// The permissions stored for an application, empty if it has none.
pub fn permissions(&self, public_key: &PublicKey) -> Policy {
let hex = public_key.to_hex();
self.apps
.iter()
.find(|app| app.public_key == hex)
.map(|app| app.policy.clone())
.unwrap_or_default()
}
/// Remember an "always" answer. Unknown applications are ignored: there is
/// nothing to remember against.
pub fn allow(&mut self, public_key: &PublicKey, permission: Permission) -> Result<()> {
@@ -141,6 +192,27 @@ impl AppRegistry {
self.save()
}
/// Take back one stored permission without revoking the application.
pub fn revoke_permission(
&mut self,
public_key: &PublicKey,
permission: &Permission,
) -> Result<()> {
let hex = public_key.to_hex();
let Some(app) = self.apps.iter_mut().find(|app| app.public_key == hex) else {
return Ok(());
};
match permission {
Permission::Kind(kind) => {
app.policy.kinds.remove(kind);
}
Permission::Method(method) => {
app.policy.methods.remove(method);
}
}
self.save()
}
/// Record an approval. Metadata is whatever the client declared.
pub fn approve(&mut self, client: &ClientInfo) -> Result<()> {
let public_key = client.public_key.to_hex();
@@ -165,17 +237,110 @@ impl AppRegistry {
self.save()
}
/// Forget an approved application, and list what is approved. Both are
/// wired up by the apps page in M5.
#[allow(dead_code)]
/// 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();
self.apps.retain(|app| app.public_key != hex);
self.save()
}
#[allow(dead_code)]
/// Forget every application. Permissions go with them.
pub fn clear(&mut self) -> Result<()> {
self.apps.clear();
self.save()
}
pub fn list(&self) -> &[App] {
&self.apps
}
}
/// Write `bytes` to `path`, creating it mode 0600 on Unix.
fn write_private(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(bytes)?;
file.sync_all()?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
fn temp_path() -> PathBuf {
static NEXT: AtomicU32 = AtomicU32::new(0);
std::env::temp_dir().join(format!(
"regent-apps-{}-{}.json",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
))
}
fn client(public_key: PublicKey) -> ClientInfo {
ClientInfo {
public_key,
name: Some("Test".to_string()),
url: None,
image: None,
}
}
#[test]
fn permissions_are_added_revoked_and_persisted() {
let path = temp_path();
let keys = Keys::generate();
let kind = Permission::Kind(1);
let method = Permission::Method("nip44_encrypt".to_string());
let mut registry = AppRegistry::at(path.clone());
registry.approve(&client(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));
assert!(registry.permits(&keys.public_key(), &method));
// Survives a reload.
let reloaded = AppRegistry::at(path.clone());
assert!(reloaded.permits(&keys.public_key(), &kind));
assert_eq!(reloaded.permissions(&keys.public_key()).methods.len(), 1);
// One permission can go while the other stays.
registry
.revoke_permission(&keys.public_key(), &kind)
.unwrap();
assert!(!registry.permits(&keys.public_key(), &kind));
assert!(registry.permits(&keys.public_key(), &method));
let reloaded = AppRegistry::at(path.clone());
assert!(!reloaded.permits(&keys.public_key(), &kind));
assert!(reloaded.permits(&keys.public_key(), &method));
registry.clear().unwrap();
assert!(registry.list().is_empty());
assert!(AppRegistry::at(path.clone()).list().is_empty());
std::fs::remove_file(path).ok();
}
#[test]
fn an_ephemeral_registry_never_writes() {
let keys = Keys::generate();
let mut registry = AppRegistry::default();
registry.approve(&client(keys.public_key())).unwrap();
assert!(registry.contains(&keys.public_key()));
}
}
+308
View File
@@ -0,0 +1,308 @@
//! The activity log: what each application asked for and how it was answered.
//!
//! Append-only JSON Lines under the user data directory, mode 0600. It records
//! **metadata only**. `Entry` deliberately has a typed `kind: Option<u16>` and
//! no free-form detail field: a signer that kept a log of what was signed and
//! decrypted would be the very content oracle this project exists to replace.
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
use crate::APP_ID;
/// One answered request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Entry {
/// Unix timestamp, in seconds.
pub at: i64,
/// Client public key, hex.
pub app: String,
/// Self-declared client name; a display hint, not a fact.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: 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.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub kind: Option<u16>,
/// How it was answered: see [`outcome`].
pub outcome: String,
}
/// The vocabulary of outcomes, kept as plain strings so the log can be read
/// without this crate.
pub mod outcome {
pub const PAIRED: &str = "paired";
pub const DENIED: &str = "denied";
pub const ALLOWED_ONCE: &str = "allowed-once";
pub const ALLOWED_ALWAYS: &str = "allowed-always";
/// Answered from a stored permission, without asking.
pub const SILENT: &str = "allowed-silently";
pub const LOGGED_OUT: &str = "logged-out";
}
/// Records handled when the file grows without bound. Every line is bounded
/// (client names are truncated, the rest is fixed-size), so 500 lines fit well
/// under this.
const MAX_BYTES: u64 = 256 * 1024;
const KEEP_ENTRIES: usize = 500;
/// Client-declared names are attacker-controlled; keep them short and on one
/// line so a hostile client cannot bloat or forge log entries.
const MAX_NAME_CHARS: usize = 64;
fn bound(text: &str) -> String {
text.chars()
.filter(|c| !c.is_control())
.take(MAX_NAME_CHARS)
.collect()
}
/// A handle to the on-disk log.
///
/// Cloning shares both the path and the lock: the responder appends from tokio
/// while the activity page reads or clears from the main loop, and those must
/// not interleave (a trim rewrites the file).
#[derive(Clone)]
pub struct ActivityLog {
path: PathBuf,
lock: Arc<Mutex<()>>,
}
impl ActivityLog {
/// The log this installation writes to.
pub fn new() -> Self {
Self::at(glib::user_data_dir().join(APP_ID).join("activity.jsonl"))
}
/// A log at an explicit path, for tests.
pub fn at(path: PathBuf) -> Self {
Self {
path,
lock: Arc::new(Mutex::new(())),
}
}
/// Append one entry. Never fails the caller: an unwritable log must not
/// stop a signature. An empty path is an ephemeral, discard-only log.
pub fn record(&self, entry: &Entry) {
let _guard = self.lock.lock().unwrap();
if self.path.as_os_str().is_empty() {
return;
}
if let Some(parent) = self.path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if self.size() > MAX_BYTES {
self.trim_unlocked();
}
let mut entry = entry.clone();
if let Some(name) = &entry.name {
entry.name = Some(bound(name));
}
let Ok(mut line) = serde_json::to_string(&entry) else {
return;
};
line.push('\n');
let mut options = OpenOptions::new();
options.create(true).append(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(&self.path) {
// One `write_all` per entry, so an append is a single write.
Ok(mut file) => {
let _ = file.write_all(line.as_bytes());
}
Err(error) => eprintln!("regent: could not write the activity log: {error}"),
}
}
/// The most recent `limit` entries, newest first.
pub fn recent(&self, limit: usize) -> Vec<Entry> {
let _guard = self.lock.lock().unwrap();
let Ok(file) = File::open(&self.path) else {
return Vec::new();
};
let mut entries: Vec<Entry> = BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.filter_map(|line| serde_json::from_str(&line).ok())
.collect();
entries.reverse();
entries.truncate(limit);
entries
}
/// Forget everything recorded so far.
pub fn clear(&self) {
let _guard = self.lock.lock().unwrap();
let _ = std::fs::remove_file(&self.path);
}
fn size(&self) -> u64 {
std::fs::metadata(&self.path).map(|data| data.len()).unwrap_or(0)
}
/// Keep only the last [`KEEP_ENTRIES`] lines. Caller holds the lock.
fn trim_unlocked(&self) {
let Ok(file) = File::open(&self.path) else {
return;
};
let lines: Vec<String> = BufReader::new(file)
.lines()
.map_while(std::result::Result::ok)
.collect();
let keep = lines.len().saturating_sub(KEEP_ENTRIES);
let _ = rewrite(&self.path, lines[keep.min(lines.len())..].iter());
}
}
impl Default for ActivityLog {
fn default() -> Self {
Self::new()
}
}
/// Rewrite the log in place, keeping it private.
///
/// This must recreate the file with mode 0600: a plain `fs::write` would use
/// the umask, and the log would silently become world-readable after the first
/// trim.
fn rewrite<'a>(path: &Path, lines: impl Iterator<Item = &'a String>) -> std::io::Result<()> {
let mut contents = String::new();
for line in lines {
contents.push_str(line);
contents.push('\n');
}
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(path)?;
file.write_all(contents.as_bytes())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU32, Ordering};
fn scratch() -> (PathBuf, ActivityLog) {
static NEXT: AtomicU32 = AtomicU32::new(0);
let dir = std::env::temp_dir().join(format!(
"regent-audit-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = std::fs::remove_dir_all(&dir);
let log = ActivityLog::at(dir.join("activity.jsonl"));
(dir, log)
}
fn entry(at: i64, app: &str) -> Entry {
Entry {
at,
app: app.to_string(),
name: None,
method: "sign_event".to_string(),
kind: Some(1),
outcome: outcome::ALLOWED_ONCE.to_string(),
}
}
#[test]
fn entries_round_trip_newest_first() {
let (dir, log) = scratch();
assert!(log.recent(10).is_empty());
log.record(&entry(1, "aa"));
log.record(&entry(2, "bb"));
let recent = log.recent(10);
assert_eq!(recent.len(), 2);
assert_eq!(recent[0].app, "bb", "newest first");
assert_eq!(recent[1].app, "aa");
assert_eq!(log.recent(1).len(), 1);
log.clear();
assert!(log.recent(10).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn client_supplied_names_are_bounded() {
let (dir, log) = scratch();
let mut hostile = entry(1, "aa");
hostile.name = Some(format!("{}\n{}", "n".repeat(10_000), "evil"));
log.record(&hostile);
let entry = &log.recent(1)[0];
let name = entry.name.as_deref().unwrap();
assert_eq!(name.chars().count(), MAX_NAME_CHARS);
assert!(!name.contains('\n'), "control characters are stripped");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn trimming_keeps_the_newest_entries() {
let (dir, log) = scratch();
let total = KEEP_ENTRIES + 100;
for i in 0..total {
log.record(&entry(i as i64, "aa"));
}
log.trim_unlocked();
let recent = log.recent(total);
assert_eq!(recent.len(), KEEP_ENTRIES);
assert_eq!(
recent[0].at as usize,
total - 1,
"the newest entry survives the trim"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// `record` itself trims once the file is too big, and the rewrite must not
/// loosen the file mode.
#[test]
fn record_trims_an_oversized_log_and_keeps_it_private() {
let (dir, log) = scratch();
let mut i = 0i64;
while log.size() <= MAX_BYTES {
log.record(&entry(i, &"a".repeat(64)));
i += 1;
}
// This append crosses the limit, so it trims first.
log.record(&entry(i, "aa"));
assert!(log.size() <= MAX_BYTES, "the log is trimmed back down");
assert!(log.recent(KEEP_ENTRIES + 100).len() <= KEEP_ENTRIES + 1);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&log.path)
.unwrap()
.permissions()
.mode()
& 0o777;
assert_eq!(mode, 0o600, "the log stays private after a trim");
}
let _ = std::fs::remove_dir_all(&dir);
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
//! Persistent state: the keyring today, the application registry later.
//! Persistent state: the keyring, the application registry, and the activity log.
pub mod apps;
pub mod audit;
pub mod keys;
+171
View File
@@ -0,0 +1,171 @@
//! The activity page: a metadata-only record of requests and how they were
//! answered.
//!
//! This never shows (and the log never contains) event content, plaintext or
//! ciphertext — only which app asked for what, and the decision.
use std::rc::Rc;
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::store::audit::{self, ActivityLog, Entry};
use crate::ui::plain;
/// How many entries the page shows. The log keeps more.
const RECENT: usize = 100;
pub struct ActivityView {
pub widget: gtk::Widget,
}
struct Ui {
stack: gtk::Stack,
content: gtk::Box,
log: ActivityLog,
state: Rc<AppState>,
}
impl ActivityView {
pub fn new(state: Rc<AppState>) -> Self {
let stack = gtk::Stack::builder().vexpand(true).build();
let empty = adw::StatusPage::builder()
.icon_name("document-open-recent-symbolic")
.title("Nothing yet")
.description("Requests and their answers will show up here.")
.build();
stack.add_named(&empty, Some("empty"));
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(18)
.margin_top(18)
.margin_bottom(18)
.margin_start(12)
.margin_end(12)
.build();
let clamp = adw::Clamp::builder()
.child(&content)
.maximum_size(720)
.build();
let scrolled = gtk::ScrolledWindow::builder()
.child(&clamp)
.vexpand(true)
.build();
stack.add_named(&scrolled, Some("list"));
let ui = Rc::new(Ui {
stack,
content,
log: state.activity(),
state,
});
{
let listener_state = Rc::clone(&ui.state);
let view = Rc::clone(&ui);
listener_state.listen_changes(move || view.refresh());
}
ui.refresh();
Self {
widget: ui.stack.clone().upcast(),
}
}
}
impl Ui {
fn refresh(self: &Rc<Self>) {
let entries = self.log.recent(RECENT);
while let Some(child) = self.content.first_child() {
self.content.remove(&child);
}
if entries.is_empty() {
self.stack.set_visible_child_name("empty");
return;
}
self.stack.set_visible_child_name("list");
let group = adw::PreferencesGroup::builder()
.title("Recent activity")
.description("Metadata only — no message content is recorded.")
.build();
for entry in &entries {
group.add(&self.row(entry));
}
self.content.append(&group);
self.content.append(&self.clear_group());
}
fn row(&self, entry: &Entry) -> adw::ActionRow {
let title = format!(
"{} — {}",
method_label(&entry.method, entry.kind),
outcome_label(&entry.outcome)
);
let who = entry
.name
.clone()
.unwrap_or_else(|| plain::shorten(&entry.app, 10, 6));
let subtitle = format!("{who} · {}", when(entry.at));
plain::row(&title, &subtitle)
}
fn clear_group(self: &Rc<Self>) -> adw::PreferencesGroup {
let group = adw::PreferencesGroup::new();
let row = plain::row("Clear activity", "Forget everything recorded so far.");
let clear = gtk::Button::builder()
.label("Clear")
.valign(gtk::Align::Center)
.css_classes(["destructive-action"])
.build();
let ui = Rc::clone(self);
clear.connect_clicked(move |_| {
ui.log.clear();
ui.state.notify_changes();
});
row.add_suffix(&clear);
group.add(&row);
group
}
}
fn method_label(method: &str, kind: Option<u16>) -> String {
match method {
"connect" => "Pairing".to_string(),
"sign_event" => match kind {
Some(kind) => format!("Sign kind {kind}"),
None => "Sign event".to_string(),
},
"nip04_encrypt" => "Encrypt (NIP-04)".to_string(),
"nip44_encrypt" => "Encrypt (NIP-44)".to_string(),
"nip04_decrypt" => "Decrypt (NIP-04)".to_string(),
"nip44_decrypt" => "Decrypt (NIP-44)".to_string(),
"logout" => "Logout".to_string(),
other => other.to_string(),
}
}
fn outcome_label(outcome: &str) -> &'static str {
match outcome {
audit::outcome::PAIRED => "paired",
audit::outcome::DENIED => "denied",
audit::outcome::ALLOWED_ONCE => "allowed once",
audit::outcome::ALLOWED_ALWAYS => "allowed always",
audit::outcome::SILENT => "allowed silently",
audit::outcome::LOGGED_OUT => "logged out",
_ => "handled",
}
}
fn when(at: i64) -> String {
glib::DateTime::from_unix_local(at)
.and_then(|time| time.format("%Y-%m-%d %H:%M"))
.map(|formatted| formatted.to_string())
.unwrap_or_else(|_| at.to_string())
}
+10 -21
View File
@@ -13,7 +13,7 @@ use gtk::prelude::*;
use libadwaita as adw;
use crate::signer::approval::{ApprovalRequest, Decision, Request};
use crate::ui::plain;
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.
@@ -38,7 +38,7 @@ enum Choices {
async fn present(widget: &gtk::Widget, question: &ApprovalRequest) -> Decision {
let choices = match &question.request {
Request::Pair => Choices::Pair,
Request::Pair { .. } => Choices::Pair,
request if !request.allows_always() => Choices::Once,
_ => Choices::OnceAlways,
};
@@ -91,7 +91,7 @@ async fn present(widget: &gtk::Widget, question: &ApprovalRequest) -> Decision {
fn heading(request: &Request) -> String {
match request {
Request::Pair => "Connect an application?".to_string(),
Request::Pair { .. } => "Connect an application?".to_string(),
Request::Sign { .. } => "Sign an event?".to_string(),
Request::Encrypt { .. } => "Encrypt a message?".to_string(),
Request::Decrypt { .. } => "Decrypt a message?".to_string(),
@@ -101,7 +101,7 @@ fn heading(request: &Request) -> String {
/// Our own words about what the request means. No client data.
fn story(request: &Request) -> &'static str {
match request {
Request::Pair => {
Request::Pair { .. } => {
"It would be able to ask Regent for signatures and encryption. Every such \
request will still be shown to you."
}
@@ -134,13 +134,17 @@ fn details(question: &ApprovalRequest) -> gtk::Box {
));
match &question.request {
Request::Pair => {}
Request::Pair { requested } => {
if let Some(requested) = requested {
content.append(&field("Asked for", requested));
}
}
Request::Sign {
kind,
preview,
tags,
} => {
content.append(&field("Kind", &format!("{} ({})", kind, kind_name(*kind))));
content.append(&field("Kind", &format!("{} ({})", kind, kind::name(*kind))));
content.append(&block("Content", preview));
content.append(&field("Tags", tags));
}
@@ -244,18 +248,3 @@ fn plain(text: &str) -> gtk::Label {
.build()
}
/// A short, human name for the common kinds; the bare number otherwise.
fn kind_name(kind: u16) -> &'static str {
match kind {
0 => "profile metadata",
1 => "text note",
3 => "follow list",
4 => "encrypted direct message",
5 => "deletion",
6 => "repost",
7 => "reaction",
24133 => "NIP-46 message",
30023 => "long-form article",
_ => "event",
}
}
+256
View File
@@ -0,0 +1,256 @@
//! The apps page: who is approved, what they may do without asking, and how to
//! take that back.
//!
//! The table and the responder read the same registry, so revoking here changes
//! behaviour immediately. Client names are attacker-controlled and are rendered
//! as plain text only.
use std::cell::RefCell;
use std::rc::Rc;
use nostr::nips::nip19::ToBech32;
use nostr::prelude::*;
use adw::prelude::*;
use gtk::prelude::*;
use libadwaita as adw;
use crate::state::AppState;
use crate::store::apps::{App, Permission, Policy};
use crate::ui::{kind, plain};
/// What the page currently shows, so a log-only change does not rebuild it and
/// collapse the expanders.
type Shown = Vec<(String, Option<String>, Policy)>;
pub struct AppsView {
pub widget: gtk::Widget,
}
struct Ui {
stack: gtk::Stack,
/// Cleared and rebuilt when the registry changes; never populated while
/// holding the registry lock.
content: gtk::Box,
shown: RefCell<Option<Shown>>,
state: Rc<AppState>,
}
impl AppsView {
pub fn new(state: Rc<AppState>) -> Self {
let stack = gtk::Stack::builder().vexpand(true).build();
let empty = adw::StatusPage::builder()
.icon_name("applications-system-symbolic")
.title("No applications yet")
.description("Applications appear here once you approve them while pairing.")
.build();
stack.add_named(&empty, Some("empty"));
let content = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(18)
.margin_top(18)
.margin_bottom(18)
.margin_start(12)
.margin_end(12)
.build();
let clamp = adw::Clamp::builder()
.child(&content)
.maximum_size(720)
.build();
let scrolled = gtk::ScrolledWindow::builder()
.child(&clamp)
.vexpand(true)
.build();
stack.add_named(&scrolled, Some("apps"));
let ui = Rc::new(Ui {
stack,
content,
shown: RefCell::new(None),
state,
});
{
let listener_state = Rc::clone(&ui.state);
let view = Rc::clone(&ui);
listener_state.listen_changes(move || view.refresh());
}
ui.refresh();
Self {
widget: ui.stack.clone().upcast(),
}
}
}
impl Ui {
fn refresh(self: &Rc<Self>) {
// Snapshot under a short lock; build the UI after it is dropped.
let apps: Vec<App> = {
let registry = self.state.registry();
let guard = registry.lock().unwrap();
guard.list().to_vec()
};
// The shared change channel also fires for activity-log entries. Only
// rebuild when the apps themselves changed, or every answered request
// would collapse the expanders.
let signature: Shown = apps
.iter()
.map(|app| (app.public_key.clone(), app.name.clone(), app.policy.clone()))
.collect();
if self.shown.borrow().as_ref() == Some(&signature) {
return;
}
*self.shown.borrow_mut() = Some(signature);
while let Some(child) = self.content.first_child() {
self.content.remove(&child);
}
if apps.is_empty() {
self.stack.set_visible_child_name("empty");
return;
}
self.stack.set_visible_child_name("apps");
let group = adw::PreferencesGroup::builder()
.title("Approved applications")
.description(
"Each one can ask for signatures and encryption. It only skips the prompt \
for what you allowed with “Allow always”.",
)
.build();
for app in &apps {
group.add(&self.app_row(app));
}
self.content.append(&group);
self.content.append(&self.forget_all_group());
}
fn app_row(self: &Rc<Self>, app: &App) -> adw::ExpanderRow {
let name = app
.name
.clone()
.unwrap_or_else(|| "Unnamed application".to_string());
let npub = PublicKey::parse(&app.public_key)
.map(|key| key.to_bech32().unwrap_or_default())
.unwrap_or_else(|_| app.public_key.clone());
let row = plain::expander(&name, &plain::shorten(&npub, 12, 6));
row.add_row(&plain::row("Public key", &npub));
if app.policy.kinds.is_empty() && app.policy.methods.is_empty() {
row.add_row(&plain::row(
"Permissions",
"Always asks before signing, encrypting or decrypting",
));
} else {
for kind_number in &app.policy.kinds {
let title = format!(
"Sign kind {} ({})",
kind_number,
kind::name(*kind_number)
);
row.add_row(&self.permission_row(
app,
Permission::Kind(*kind_number),
&title,
));
}
for method in &app.policy.methods {
let title = encryption_label(method);
row.add_row(&self.permission_row(
app,
Permission::Method(method.clone()),
&title,
));
}
}
// Revoking the whole application stays visible while collapsed.
if let Ok(public_key) = PublicKey::parse(&app.public_key) {
let revoke = gtk::Button::builder()
.label("Revoke")
.valign(gtk::Align::Center)
.css_classes(["destructive-action"])
.build();
let ui = Rc::clone(self);
revoke.connect_clicked(move |_| {
let registry = ui.state.registry();
if let Err(error) = registry.lock().unwrap().revoke(&public_key) {
eprintln!("regent: could not revoke an application: {error}");
}
ui.state.notify_changes();
});
row.add_suffix(&revoke);
}
row
}
fn permission_row(
self: &Rc<Self>,
app: &App,
permission: Permission,
title: &str,
) -> adw::ActionRow {
let row = plain::row(title, "Allowed without asking");
if let Ok(public_key) = PublicKey::parse(&app.public_key) {
let remove = gtk::Button::builder()
.label("Remove")
.valign(gtk::Align::Center)
.css_classes(["flat"])
.build();
let ui = Rc::clone(self);
let permission = permission.clone();
remove.connect_clicked(move |_| {
let registry = ui.state.registry();
if let Err(error) = registry
.lock()
.unwrap()
.revoke_permission(&public_key, &permission)
{
eprintln!("regent: could not remove a permission: {error}");
}
ui.state.notify_changes();
});
row.add_suffix(&remove);
}
row
}
fn forget_all_group(self: &Rc<Self>) -> adw::PreferencesGroup {
let group = adw::PreferencesGroup::new();
let row = plain::row(
"Forget all applications",
"Remove every approval and everything it was allowed to do.",
);
let forget = gtk::Button::builder()
.label("Forget all")
.valign(gtk::Align::Center)
.css_classes(["destructive-action"])
.build();
let ui = Rc::clone(self);
forget.connect_clicked(move |_| {
let registry = ui.state.registry();
if let Err(error) = registry.lock().unwrap().clear() {
eprintln!("regent: could not forget applications: {error}");
}
ui.state.notify_changes();
});
row.add_suffix(&forget);
group.add(&row);
group
}
}
fn encryption_label(method: &str) -> String {
match method {
"nip04_encrypt" => "Encrypt (NIP-04)".to_string(),
"nip44_encrypt" => "Encrypt (NIP-44)".to_string(),
other => other.to_string(),
}
}
+18
View File
@@ -0,0 +1,18 @@
//! Human names for the common event kinds, shared by the dialogs and the
//! permission table.
/// A short, human name for the common kinds; a generic one otherwise.
pub fn name(kind: u16) -> &'static str {
match kind {
0 => "profile metadata",
1 => "text note",
3 => "follow list",
4 => "encrypted direct message",
5 => "deletion",
6 => "repost",
7 => "reaction",
24133 => "NIP-46 message",
30023 => "long-form article",
_ => "event",
}
}
+3
View File
@@ -1,6 +1,9 @@
//! User interface.
pub mod activity_view;
pub mod approval;
pub mod apps_view;
pub mod kind;
pub mod keys_view;
pub mod plain;
pub mod qr;
+33 -4
View File
@@ -14,12 +14,30 @@ use adw::prelude::*;
use libadwaita as adw;
/// An `ActionRow` whose title and subtitle are plain text.
///
/// Markup is turned off **before** the strings are set. A builder that sets
/// `title`/`subtitle` first parses them as markup while `use-markup` is still
/// true, so a subtitle containing `&` fails (and logs a warning) even though
/// `use_markup(false)` follows it.
pub fn row(title: &str, subtitle: &str) -> adw::ActionRow {
adw::ActionRow::builder()
.title(title)
.subtitle(subtitle)
let row = adw::ActionRow::builder().use_markup(false).build();
row.set_title(title);
row.set_subtitle(subtitle);
row
}
/// An `ExpanderRow` whose title and subtitle are plain text.
///
/// The enable switch is hidden: on an expander it only hides the child rows,
/// which reads as "disabled" while revoking nothing.
pub fn expander(title: &str, subtitle: &str) -> adw::ExpanderRow {
let row = adw::ExpanderRow::builder()
.use_markup(false)
.build()
.show_enable_switch(false)
.build();
row.set_title(title);
row.set_subtitle(subtitle);
row
}
/// Turn off markup on a banner, whose title defaults to markup.
@@ -27,6 +45,17 @@ pub fn banner(banner: &adw::Banner) {
banner.set_use_markup(false);
}
/// `value` shortened to `head…tail` characters, for one-line subtitles.
pub fn shorten(value: &str, head: usize, tail: usize) -> String {
let chars: Vec<char> = value.chars().collect();
if chars.len() <= head + tail + 1 {
return value.to_string();
}
let start: String = chars[..head].iter().collect();
let end: String = chars[chars.len() - tail..].iter().collect();
format!("{start}…{end}")
}
/// Turn off markup on an `AlertDialog`'s heading and body.
pub fn dialog(dialog: &adw::AlertDialog) {
dialog.set_heading_use_markup(false);
+12 -10
View File
@@ -2,10 +2,9 @@
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use crate::signer::approval::Approver;
use crate::store::apps::AppRegistry;
use nostr::nips::nip19::ToBech32;
@@ -125,7 +124,6 @@ impl SignerView {
// on the other end of this channel.
let (approver, questions) = Approver::new();
crate::ui::approval::install(questions, widget.clone());
let registry = Arc::new(Mutex::new(AppRegistry::load()));
let running: Running = Rc::new(RefCell::new(None));
@@ -143,7 +141,7 @@ impl SignerView {
{
let (handles, state, running) = (handles.clone(), Rc::clone(&state), Rc::clone(&running));
let (approver, registry) = (approver.clone(), Arc::clone(&registry));
let approver = approver.clone();
handles.toggle.clone().connect_clicked(move |_| {
if running.borrow().is_some() {
stop(handles.clone(), Rc::clone(&running));
@@ -153,7 +151,6 @@ impl SignerView {
Rc::clone(&state),
Rc::clone(&running),
approver.clone(),
Arc::clone(&registry),
);
}
});
@@ -165,7 +162,6 @@ impl SignerView {
let signer_running = Rc::clone(&running);
let listener_state = Rc::clone(&state);
let listener_approver = approver.clone();
let listener_registry = Arc::clone(&registry);
state.listen(move || {
let Some(store) = listener_state.store() else {
return;
@@ -178,12 +174,11 @@ impl SignerView {
Rc::clone(&listener_state),
Rc::clone(&signer_running),
);
let (approver, registry) =
(listener_approver.clone(), Arc::clone(&listener_registry));
let approver = listener_approver.clone();
runtime::spawn(
async move { store.user_key().await },
move |result| match result {
Ok(Some(_)) => start(handles, state, running, approver, registry),
Ok(Some(_)) => start(handles, state, running, approver),
Ok(None) => show_empty(&handles),
Err(error) => report_error(&handles, &error),
},
@@ -210,7 +205,6 @@ fn start(
state: Rc<AppState>,
running: Running,
approver: Approver,
registry: Arc<Mutex<AppRegistry>>,
) {
let Some(store) = state.store() else {
return;
@@ -219,6 +213,12 @@ fn start(
let relays = settings.relays();
let auto_approve_limit = settings.auto_approve_limit();
// Only `Send` handles go into the async task; the registry and log are the
// shared ones the pages read.
let registry = state.registry();
let activity = state.activity();
let changes = state.changes();
runtime::spawn(
async move {
let config = SignerConfig::from_store(
@@ -227,6 +227,8 @@ fn start(
approver,
registry,
auto_approve_limit,
activity,
changes,
)
.await?;
Signer::start(config).await
+30 -4
View File
@@ -10,6 +10,8 @@ use libadwaita as adw;
use crate::config::Config;
use crate::state::AppState;
use crate::ui::activity_view::ActivityView;
use crate::ui::apps_view::AppsView;
use crate::ui::keys_view::KeysView;
use crate::ui::plain;
use crate::ui::signer_view::SignerView;
@@ -20,7 +22,8 @@ pub struct Window {
}
impl Window {
pub fn new(app: &adw::Application) -> Self {
/// `state` is created once per process and shared by every window.
pub fn new(app: &adw::Application, state: Rc<AppState>) -> Self {
let config = Config::new();
let builder = gtk::Builder::from_resource(&format!("{RESOURCE_PATH}/ui/window.ui"));
@@ -38,13 +41,36 @@ impl Window {
.expect("ui/window.blp must contain an object with id \"banner\"");
plain::banner(&banner);
let state = AppState::new();
let keys_view = KeysView::new(Rc::clone(&state));
let signer_view = SignerView::new(Rc::clone(&state), banner);
let apps_view = AppsView::new(Rc::clone(&state));
let activity_view = ActivityView::new(Rc::clone(&state));
let stack = adw::ViewStack::new();
stack.add_titled(&keys_view.widget, Some("keys"), "Keys");
stack.add_titled(&signer_view.widget, Some("signer"), "Signer");
stack.add_titled_with_icon(
&keys_view.widget,
Some("keys"),
"Keys",
"dialog-password-symbolic",
);
stack.add_titled_with_icon(
&signer_view.widget,
Some("signer"),
"Signer",
"network-transmit-receive-symbolic",
);
stack.add_titled_with_icon(
&apps_view.widget,
Some("apps"),
"Apps",
"applications-system-symbolic",
);
stack.add_titled_with_icon(
&activity_view.widget,
Some("activity"),
"Activity",
"document-open-recent-symbolic",
);
let switcher = adw::ViewSwitcher::builder()
.stack(&stack)