Notify the user when a client logs Regent out

A NIP-46 logout removes the application and its permissions, but nothing
told the user: the only trace was a row on the Apps page or the activity
log, and only if that page happened to be open. Raise a desktop
notification, the way an approval prompt does.

The responder sends a one-way Notice through a second channel on Approver,
drained by ui::approval::install_notices. It is separate from the prompt
channel so Prompt keeps meaning "needs an answer", and it uses its own
notification id so it neither replaces nor is withdrawn with a pending
prompt's. Unlike a prompt it is raised unconditionally — there is no dialog
on screen, so a focused window is no indication. Headless logs it to stderr.
This commit is contained in:
raucao committed 2026-11-25 16:15:57 +04:00
1 parent 0f1ab9039a
commit f52933c442
7 files changed
+184 -22

No files matched your search

+9
View File
@@ -117,6 +117,15 @@ data/ desktop, metainfo, gschema, icons, resources (ui/*.blp, sty
test override as `REGENT_RELAYS`.
- One id (`"approval"`) so a second prompt replaces the first; the drain is
serialized, so only one prompt is ever open. Withdrawn as soon as it resolves.
- **One-way notices use their own channel and their own id.** A NIP-46 `logout`
removes an application, and nothing else tells the user, so the responder sends
a `Notice` through `Approver`'s separate `notices` channel, drained by
`ui::approval::install_notices`. A second channel keeps `Prompt` meaning "needs
an answer" and a one-way notice out of a drain that blocks in
`present_question` until the dialog is answered; the notice id (`"notice"`)
keeps it from replacing, or being withdrawn with, a prompt's notification. It
is raised **unconditionally** — the `user_is_away` gate exists for prompts, and
a notice has no dialog on screen — and headless logs it to stderr instead.
- The body is **per category and never carries the client name, event kind or
content** — a notification body renders on the lock screen, and the client's
name is attacker-controlled display data, exactly like the activity log's rule.
+39 -3
View File
@@ -6,7 +6,8 @@
# 2. the vault itself (NIP-49 keys, mode 0600, no plaintext identity key)
# 3. the app: a seeded identity key makes the signer come up and listen
# 4. notifications: a prompt while the window is "away" reaches the desktop,
# and clicking it brings the window back
# clicking it brings the window back, and a client-initiated logout
# announces itself
#
# The GUI needs a D-Bus session, so wrap it:
#
@@ -144,6 +145,10 @@ rm -f "$APPS_DIR/$DATA_DIR.broken.desktop"
# stored permission, so its request must be put to the user.
NOTIFY_CLIENT_SEC=$(nak key generate)
NOTIFY_CLIENT=$(nak key public "$NOTIFY_CLIENT_SEC")
# A second approved client for the logout path: its notice must be raised before
# the sign prompt is answered, so it is not queued behind the open dialog.
LOGOUT_CLIENT_SEC=$(nak key generate)
LOGOUT_CLIENT=$(nak key public "$LOGOUT_CLIENT_SEC")
APPS="$HOME/.config/$DATA_DIR/apps.json"
mkdir -p "$(dirname "$APPS")"
cat >"$APPS" <<EOF
@@ -155,6 +160,13 @@ cat >"$APPS" <<EOF
"approved_at": 1,
"identity": "$PUBKEY",
"policy": { "methods": [], "kinds": [] }
},
{
"public_key": "$LOGOUT_CLIENT",
"name": "Logout Client",
"approved_at": 1,
"identity": "$PUBKEY",
"policy": { "methods": [], "kinds": [] }
}
]
}
@@ -192,11 +204,35 @@ check $? "a device key was created in the vault"
! grep -q 'cannot resolve' "$TMP_HOME/app.log"
check $? "the app does not warn that GNOME cannot find it"
# The device key the app advertises, used to address both requests below.
DEVICE_NPUB=$(grep -o 'npub1[a-z0-9]*' "$TMP_HOME/app.log" | head -1)
DEVICE_HEX=$(nak decode "$DEVICE_NPUB")
printf '\n== a client logging itself out ==\n'
# Nothing else tells the user an application deleted itself and its permissions,
# so a client-initiated logout must raise a notification. Send it before the
# sign request below: the responder answers requests one at a time, and the open
# sign prompt would otherwise hold the loop until its deadline.
LOGOUT_ENVELOPE=$(python3 -c 'import json; print(json.dumps({
"id": "acceptance-logout",
"method": "logout",
"params": [],
}))')
LOGOUT_CIPHERTEXT=$(nak encrypt --sec "$LOGOUT_CLIENT_SEC" -p "$DEVICE_HEX" "$LOGOUT_ENVELOPE")
nak event --sec "$LOGOUT_CLIENT_SEC" -k 24133 -p "$DEVICE_HEX" -c "$LOGOUT_CIPHERTEXT" \
"ws://127.0.0.1:$PORT" >/dev/null 2>&1
sleep 3
grep -qF 'id=notice' "$NOTIFY_LOG" &&
grep -qF 'body=An application was disconnected' "$NOTIFY_LOG"
check $? "a client-initiated logout raises a notification"
! grep -qF "$LOGOUT_CLIENT" "$APPS"
check $? "the logged-out application is gone from apps.json"
printf '\n== notifications ==\n'
# `REGENT_NOTIFY_ALWAYS` makes the app treat the window as away: Broadway has no
# window manager, so `is_active()` is true even when nothing is focused.
DEVICE_NPUB=$(grep -o 'npub1[a-z0-9]*' "$TMP_HOME/app.log" | head -1)
DEVICE_HEX=$(nak decode "$DEVICE_NPUB")
ENVELOPE=$(python3 -c 'import json; print(json.dumps({
"id": "acceptance",
"method": "sign_event",
+7 -1
View File
@@ -120,7 +120,7 @@ async fn serve(
// No window: deny everything the user has not already allowed, and never
// open the vault (an unattended `--passphrase-file` does that at startup).
let (approver, prompts) = Approver::new();
let (approver, prompts, notices) = Approver::new();
tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
@@ -133,6 +133,12 @@ async fn serve(
}
}
});
// No window, so a one-way notice is a line on stderr, not a notification.
tokio::spawn(async move {
while let Ok(notice) = notices.recv().await {
eprintln!("regent: {notice:?}");
}
});
let registry = Arc::new(Mutex::new(AppRegistry::load()));
let activity = ActivityLog::new();
+2 -1
View File
@@ -56,8 +56,9 @@ impl SignerRunner {
/// Create the process's runner and install the approval drain. Call this
/// once, from the main window, after the window has its application.
pub fn new(state: Rc<AppState>, widget: gtk::Widget) -> Rc<Self> {
let (approver, prompts) = Approver::new();
let (approver, prompts, notices) = Approver::new();
crate::ui::approval::install(prompts, widget.clone(), Rc::clone(&state));
crate::ui::approval::install_notices(notices, widget.clone());
let runner = Rc::new(Self {
state,
+31 -8
View File
@@ -126,17 +126,40 @@ pub enum Prompt {
},
}
/// The handle the responder uses to ask the user.
/// A one-way message to the UI.
///
/// No answer is expected: it exists so the responder can tell the user that
/// something happened without raising a dialog. Which text that becomes lives in
/// the UI, so no client-supplied string ever reaches the desktop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Notice {
/// A client asked to be forgotten (NIP-46 `logout`).
LoggedOut,
}
/// The handle the responder uses to ask the user — and to tell them something.
#[derive(Clone)]
pub struct Approver {
inbox: Sender<Prompt>,
/// Deliberately separate from `inbox`: `Prompt` means "needs an answer", and
/// its drain blocks in `present_question` until the dialog is answered. A
/// notice is one-way and must never be queued behind one.
notices: Sender<Notice>,
}
impl Approver {
/// Create an approver and the receiver the UI must drain.
pub fn new() -> (Self, Receiver<Prompt>) {
/// Create an approver, the receiver the UI must drain for prompts, and the
/// receiver it must drain for notices.
pub fn new() -> (Self, Receiver<Prompt>, Receiver<Notice>) {
let (inbox, questions) = async_channel::unbounded();
(Self { inbox }, questions)
let (notices, notices_rx) = async_channel::unbounded();
(Self { inbox, notices }, questions, notices_rx)
}
/// Raise a desktop notification. One-way: there is no answer, and the
/// responder never waits for one.
pub fn notice(&self, notice: Notice) {
let _ = self.notices.try_send(notice);
}
/// Ask, and treat a timeout or a missing UI as a denial.
@@ -227,7 +250,7 @@ mod tests {
/// A UI that receives the question but never answers must deny.
#[tokio::test]
async fn a_silent_ui_times_out_to_deny() {
let (approver, questions) = Approver::new();
let (approver, questions, _notices) = Approver::new();
let holding = tokio::spawn(async move {
// Keep the question (and its reply channel) alive, but silent.
while let Ok(question) = questions.recv().await {
@@ -249,7 +272,7 @@ mod tests {
/// With no UI at all the send fails or the answer never comes: deny.
#[tokio::test]
async fn a_missing_ui_is_a_denial() {
let (approver, questions) = Approver::new();
let (approver, questions, _notices) = Approver::new();
let drain = tokio::spawn(async move { while questions.recv().await.is_ok() {} });
assert_eq!(
approver.ask(question(Request::Pair { requested: None })).await,
@@ -273,7 +296,7 @@ mod tests {
/// this side's backstop and end up with buttons that do nothing.
#[tokio::test]
async fn a_queued_prompt_keeps_the_deadline_it_was_asked_with() {
let (approver, prompts) = Approver::new();
let (approver, prompts, _notices) = Approver::new();
let deadline = Duration::from_millis(200);
let backstop = Duration::from_millis(400);
@@ -310,7 +333,7 @@ mod tests {
/// A UI that never answers must not unlock the vault either.
#[tokio::test]
async fn a_silent_ui_never_unlocks() {
let (approver, questions) = Approver::new();
let (approver, questions, _notices) = Approver::new();
let holding = tokio::spawn(async move {
while let Ok(prompt) = questions.recv().await {
tokio::time::sleep(Duration::from_secs(30)).await;
+45 -5
View File
@@ -16,7 +16,7 @@ use nostr::nips::{nip04, nip44};
use nostr::prelude::*;
use nostr_sdk::prelude::*;
use self::approval::{Approver, ClientInfo, Decision, Question, Request, SigningKey};
use self::approval::{Approver, ClientInfo, Decision, Notice, Question, Request, SigningKey};
use self::policy::RateLimiter;
use crate::store::apps::{AppRegistry, Permission};
use crate::store::audit::{self, ActivityLog, Entry};
@@ -754,6 +754,9 @@ async fn handle_request(event: &Event, config: &SignerConfig) -> Result<Option<E
identity.as_ref(),
audit::outcome::LOGGED_OUT,
);
// Nothing else tells the user an application deleted itself and
// its permissions, so raise a desktop notification.
config.approver.notice(Notice::LoggedOut);
}
result
}
@@ -1293,7 +1296,7 @@ mod tests {
/// Answers every question the same way, standing in for the UI.
fn auto_approver(decision: Decision) -> (Approver, tokio::task::JoinHandle<()>) {
let (approver, prompts) = Approver::new();
let (approver, prompts, _notices) = Approver::new();
let handle = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
@@ -1320,7 +1323,7 @@ mod tests {
where
F: Fn(&Request) -> Decision + Send + 'static,
{
let (approver, prompts) = Approver::new();
let (approver, prompts, _notices) = Approver::new();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
let handle = tokio::spawn(async move {
@@ -1701,7 +1704,7 @@ mod tests {
let identity = store.list_user_keys()[0].public_key;
let client = Keys::generate();
let (approver, prompts) = Approver::new();
let (approver, prompts, _notices) = Approver::new();
let unlocking = Arc::clone(&store);
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
@@ -1758,7 +1761,7 @@ mod tests {
let identity = store.list_user_keys()[0].public_key;
let client = Keys::generate();
let (approver, prompts) = Approver::new();
let (approver, prompts, _notices) = Approver::new();
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
@@ -2134,6 +2137,43 @@ mod tests {
assert_eq!(pairs_after, pairs_before + 1, "reconnecting must ask again");
}
/// A client that logs itself out is announced to the user: nothing else
/// tells them an application deleted itself and its permissions.
#[tokio::test]
async fn logout_notifies_the_user() {
let client = Keys::generate();
let (approver, prompts, notices) = Approver::new();
let drain = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Once).await;
}
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
}
});
let config = config("ws://127.0.0.1:1", approver);
let device = pair(&client, &config).await;
assert!(notices.try_recv().is_err(), "pairing is not a notice");
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());
drain.abort();
assert_eq!(
notices.try_recv().expect("a notice"),
Notice::LoggedOut,
"the client-initiated logout is announced"
);
}
/// A client can see what it may do without asking.
#[tokio::test]
async fn stored_permissions_are_reported_to_the_client() {
+51 -4
View File
@@ -19,7 +19,7 @@ use gtk::prelude::*;
use libadwaita as adw;
use crate::runtime;
use crate::signer::approval::{Decision, Prompt, Question, Request};
use crate::signer::approval::{Decision, Notice, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{kind, plain};
@@ -29,6 +29,10 @@ use crate::APP_ID;
/// stacking. The drain is serialized, so only one prompt is ever open.
const NOTIFICATION_ID: &str = "approval";
/// A separate id for one-way notices, so a logout announcement neither replaces
/// a pending prompt's notification nor is withdrawn with it.
const NOTICE_ID: &str = "notice";
/// What the desktop shows for the unlock prompt.
const UNLOCK_BODY: &str = "Regent needs your passphrase to continue";
@@ -81,6 +85,18 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
});
}
/// Drain one-way notices and turn each into a desktop notification.
///
/// The notice channel is separate from the prompt channel so this can never be
/// stuck behind an open approval dialog.
pub fn install_notices(notices: Receiver<Notice>, widget: gtk::Widget) {
glib::MainContext::default().spawn_local(async move {
while let Ok(notice) = notices.recv().await {
notify_notice(&widget, notice_body(&notice));
}
});
}
/// The one line the desktop shows.
///
/// Deliberately no client name, event kind or content: a notification body is
@@ -95,6 +111,14 @@ fn notification_body(request: &Request) -> &'static str {
}
}
/// The one line the desktop shows for a one-way notice. Our own words, so the
/// lock-screen rule holds here too.
fn notice_body(notice: &Notice) -> &'static str {
match notice {
Notice::LoggedOut => "An application was disconnected",
}
}
/// Tell the desktop a prompt is waiting — but only when the user is not already
/// looking at the window. Returns whether a notification was sent.
fn notify_pending(widget: &impl IsA<gtk::Widget>, body: &str) -> bool {
@@ -104,7 +128,21 @@ fn notify_pending(widget: &impl IsA<gtk::Widget>, body: &str) -> bool {
if !user_is_away(&window) {
return false;
}
let Some(app) = window.application() else {
raise(widget, body, NOTIFICATION_ID)
}
/// Raise a desktop notification for a one-way notice.
///
/// Unlike a prompt this is **not** gated on the user being away: there is no
/// dialog on screen, so even a focused window may show no sign of the change.
/// It is not withdrawn afterwards — the user may read it later.
fn notify_notice(widget: &impl IsA<gtk::Widget>, body: &str) {
raise(widget, body, NOTICE_ID);
}
/// Build and send one notification under `id`, returning whether it went out.
fn raise(widget: &impl IsA<gtk::Widget>, body: &str, id: &str) -> bool {
let Some(app) = window_of(widget).and_then(|window| window.application()) else {
return false;
};
@@ -117,7 +155,7 @@ fn notify_pending(widget: &impl IsA<gtk::Widget>, body: &str) -> bool {
// activates this action **in-process**; the `org.gtk.Notifications` path
// would call `ActivateAction("focus")` on the app instead. Both land here.
notification.set_default_action("app.focus");
app.send_notification(Some(NOTIFICATION_ID), &notification);
app.send_notification(Some(id), &notification);
true
}
@@ -557,5 +595,14 @@ mod tests {
assert!(expired(Instant::now() - Duration::from_millis(1)));
assert!(!expired(Instant::now() + Duration::from_secs(5)));
}
}
/// A notice names a category, never a client: the body renders on the lock
/// screen, so it must stay our own words.
#[test]
fn a_notice_body_is_our_own_words() {
assert_eq!(
notice_body(&Notice::LoggedOut),
"An application was disconnected"
);
}
}