Add M9: background notifications and a visible approval deadline

This commit is contained in:
raucao committed 2026-11-24 11:54:23 +04:00
1 parent 8a3e3f3481
commit de2cd21132
9 files changed
+551 -72

No files matched your search

+89 -7
View File
@@ -1,10 +1,12 @@
#!/bin/sh
# End-to-end acceptance for Regent.
#
# Covers three levels:
# Covers four levels:
# 1. the `nak` loopback test (an independent NIP-46 client against our responder)
# 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
#
# The GUI needs a D-Bus session, so wrap it:
#
@@ -26,7 +28,7 @@ export HOME=$TMP_HOME
export CARGO_HOME=${CARGO_HOME:-$ORIGINAL_HOME/.cargo}
cleanup() {
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} 2>/dev/null
kill ${APP:-} ${RELAY:-} ${BWAY:-} ${HEADLESS:-} ${SUBSCRIBER:-} ${NOTIFY_STUB:-} 2>/dev/null
wait 2>/dev/null
rm -rf "$TMP_HOME"
}
@@ -42,15 +44,29 @@ check() {
fi
}
for tool in cargo nak gtk4-broadwayd; do
for tool in cargo nak gtk4-broadwayd python3; do
command -v "$tool" >/dev/null || {
printf 'missing: %s\n' "$tool" >&2
exit 2
}
done
# The notification stub needs dbus-python; nothing else in the tree does.
python3 -c 'import dbus' 2>/dev/null || {
printf 'missing: the python dbus module (needed by build-aux/notify-stub.py)\n' >&2
exit 2
}
cd "$ROOT" || exit 2
# Stand in for the desktop's notification daemon: it records what Regent would
# put on screen and simulates a click on each notification.
NOTIFY_LOG="$TMP_HOME/notify.log"
: >"$NOTIFY_LOG"
NOTIFY_LOG="$NOTIFY_LOG" NOTIFY_ACTION_ID=1 \
python3 "$ROOT/build-aux/notify-stub.py" >"$TMP_HOME/notify-stub.log" 2>&1 &
NOTIFY_STUB=$!
sleep 1
printf '== responder tests ==\n'
CARGO_TARGET_DIR="$BUILD/cargo-target" cargo test --release -- --ignored >"$TMP_HOME/tests.log" 2>&1
grep -q 'test result: ok' "$TMP_HOME/tests.log"
@@ -88,6 +104,28 @@ PASSPHRASE_FILE="$TMP_HOME/passphrase"
printf '%s' "$PASSPHRASE" >"$PASSPHRASE_FILE"
chmod 600 "$PASSPHRASE_FILE"
# An already-approved client, so a request can reach a prompt without pairing:
# the pairing secret is deliberately never logged, and the in-app pairing flow
# would need a click. The client is bound to the seeded identity and has no
# 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")
APPS="$HOME/.config/$DATA_DIR/apps.json"
mkdir -p "$(dirname "$APPS")"
cat >"$APPS" <<EOF
{
"apps": [
{
"public_key": "$NOTIFY_CLIENT",
"name": "Notification Client",
"approved_at": 1,
"identity": "$PUBKEY",
"policy": { "methods": [], "kinds": [] }
}
]
}
EOF
printf '\n== the app, end to end ==\n'
nak serve --port "$PORT" >/dev/null 2>&1 &
RELAY=$!
@@ -99,6 +137,7 @@ GDK_BACKEND=broadway BROADWAY_DISPLAY=:11 \
GSETTINGS_SCHEMA_DIR="$ROOT/$BUILD/data" \
REGENT_GRESOURCE="$ROOT/$BUILD/data/resources/org.kosmos.raucao.Regent.gresource" \
REGENT_RELAYS="ws://127.0.0.1:$PORT" \
REGENT_NOTIFY_ALWAYS=1 \
"$ROOT/$BUILD/regent" >"$TMP_HOME/app.log" 2>&1 &
APP=$!
sleep 6
@@ -110,6 +149,39 @@ check $? "the app started the signer ($(grep -m1 'signer listening' "$TMP_HOME/a
grep -q '"device"' "$VAULT"
check $? "a device key was created in the vault"
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",
"params": [json.dumps({"kind": 1, "content": "hello from the acceptance test", "tags": []})],
}))')
CIPHERTEXT=$(nak encrypt --sec "$NOTIFY_CLIENT_SEC" -p "$DEVICE_HEX" "$ENVELOPE")
nak event --sec "$NOTIFY_CLIENT_SEC" -k 24133 -p "$DEVICE_HEX" -c "$CIPHERTEXT" \
"ws://127.0.0.1:$PORT" >/dev/null 2>&1
sleep 3
grep -qF 'summary=Regent' "$NOTIFY_LOG"
check $? "a waiting prompt raises a notification"
grep -qF 'body=An application is asking for a signature' "$NOTIFY_LOG"
check $? "the notification names the request and nothing about the client"
grep -qF 'hints=desktop-entry:org.kosmos.raucao.Regent' "$NOTIFY_LOG"
check $? "the notification is attributed to Regent"
grep -qF 'urgency:1' "$NOTIFY_LOG"
check $? "the notification is high priority"
grep -qF 'actions=default' "$NOTIFY_LOG"
check $? "clicking the notification has a default action"
grep -q 'regent: bringing the window to the front' "$TMP_HOME/app.log"
check $? "clicking the notification brings the window to the front"
# The GUI owns the D-Bus name; headless must not run alongside it, and we need
# it gone so the two do not race over apps.json.
kill "$APP" 2>/dev/null
@@ -139,12 +211,22 @@ check $? "headless signer started with no window"
grep -q 'paired with Acceptance Client' "$TMP_HOME/headless.log"
check $? "CLI paired from a nostrconnect:// URI"
grep -q '"name": "Acceptance Client"' "$HOME/.config/$DATA_DIR/apps.json"
# Read the *paired* client's entry: apps.json also holds the seeded client, so a
# loose grep would pass even if pairing recorded nothing or granted something.
python3 - "$APPS" "$CLIENT" <<'PY'
import json, sys
apps = {app["public_key"]: app for app in json.load(open(sys.argv[1]))["apps"]}
entry = apps[sys.argv[2]]
assert entry["name"] == "Acceptance Client", entry
PY
check $? "the paired application was recorded"
# Pairing must never auto-grant: the stored policy stays empty.
grep -q '"methods": \[\]' "$HOME/.config/$DATA_DIR/apps.json" &&
grep -q '"kinds": \[\]' "$HOME/.config/$DATA_DIR/apps.json"
python3 - "$APPS" "$CLIENT" <<'PY'
import json, sys
apps = {app["public_key"]: app for app in json.load(open(sys.argv[1]))["apps"]}
entry = apps[sys.argv[2]]
assert entry["policy"] == {"methods": [], "kinds": []}, entry
PY
check $? "the pairing auto-granted nothing"
grep -q "$CLIENT" "$TMP_HOME/subscriber.log"
+103
View File
@@ -0,0 +1,103 @@
#!/usr/bin/env python3
"""A stub `org.freedesktop.Notifications`, for the acceptance test only.
GLib's `GApplication::send_notification` talks the freedesktop interface
directly, so owning the name is enough to observe what Regent would put on
screen. Every call is appended to `$NOTIFY_LOG` as one `key=value` line, and
when `NOTIFY_ACTION_ID=1` a click is simulated by emitting `ActionInvoked`
shortly after each `Notify` — which is exactly what GNOME Shell does when the
body of a notification is clicked, and what makes GLib activate the app's
default action.
Not a Regent dependency: it exists so the notification path has a test.
"""
import os
import sys
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GLib
LOG = os.environ["NOTIFY_LOG"]
CLICK = os.environ.get("NOTIFY_ACTION_ID") == "1"
class Notifications(dbus.service.Object):
def __init__(self, bus):
super().__init__(bus, "/org/freedesktop/Notifications")
self.next_id = 1
def log(self, line):
with open(LOG, "a") as handle:
handle.write(line + "\n")
@staticmethod
def render(value):
# `str()` on a dbus.Byte is the raw character, which would put a control
# byte in the log; numbers should read as numbers.
if isinstance(value, int):
return str(int(value))
return str(value)
@dbus.service.method(
"org.freedesktop.Notifications",
in_signature="susssasa{sv}i",
out_signature="u",
)
def Notify(self, app_name, replaces_id, app_icon, summary, body, actions, hints, timeout):
notify_id = self.next_id
self.next_id += 1
hints = {str(key): self.render(value) for key, value in hints.items()}
self.log(
"Notify app={} summary={} body={} actions={} hints={}".format(
app_name,
summary,
body,
",".join(str(action) for action in actions if str(action)),
",".join("{}:{}".format(key, value) for key, value in sorted(hints.items())),
)
)
if CLICK:
GLib.timeout_add(700, self._click, notify_id)
return dbus.UInt32(notify_id)
def _click(self, notify_id):
self.ActionInvoked(dbus.UInt32(notify_id), "default")
return False
@dbus.service.signal("org.freedesktop.Notifications", signature="us")
def ActionInvoked(self, notify_id, action):
pass
@dbus.service.signal("org.freedesktop.Notifications", signature="uu")
def NotificationClosed(self, notify_id, reason):
pass
@dbus.service.method("org.freedesktop.Notifications", in_signature="u", out_signature="")
def CloseNotification(self, notify_id):
self.log("CloseNotification id={}".format(notify_id))
self.NotificationClosed(dbus.UInt32(notify_id), dbus.UInt32(3))
@dbus.service.method("org.freedesktop.Notifications", out_signature="as")
def GetCapabilities(self):
return ["body", "actions", "persistence"]
@dbus.service.method("org.freedesktop.Notifications", out_signature="ssss")
def GetServerInformation(self):
return ("regent-test", "regent", "1.0", "1.2")
def main():
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
loop = GLib.MainLoop()
# Keep both alive: dbus-python releases the name when the BusName object is
# collected, and unregisters the object when it is.
loop.bus_name = dbus.service.BusName("org.freedesktop.Notifications", bus)
loop.server = Notifications(bus)
loop.run()
if __name__ == "__main__":
sys.exit(main())
+37 -5
View File
@@ -26,8 +26,9 @@ pub fn run() -> glib::ExitCode {
// same registry and signer.
let state = AppState::new();
// Lock or unlock the key vault. Unlocking asks for the passphrase on the
// active window; a locked vault fails closed, so this never signs anything.
// Lock or unlock the key vault. Unlocking asks for the passphrase; a locked
// vault fails closed, so this never signs anything. The user is present (they
// just clicked), so the dialog has no deadline.
let lock = gio::SimpleAction::new("lock", None);
{
let app = app.clone();
@@ -42,11 +43,16 @@ pub fn run() -> glib::ExitCode {
state.notify();
return;
}
let widget = app.active_window().map(|window| window.upcast::<gtk::Widget>());
// `active_window()` is None when nothing is focused, which is also
// reachable through the accelerator, so fall back to the window.
let widget = app
.active_window()
.or_else(|| app.windows().first().cloned())
.map(|window| window.upcast::<gtk::Widget>());
let state = Rc::clone(&state);
glib::MainContext::default().spawn_local(async move {
let unlocked = match &widget {
Some(widget) => approval::present_unlock(widget, store).await,
Some(widget) => approval::present_unlock(widget, store, None).await,
None => false,
};
if unlocked {
@@ -58,8 +64,34 @@ pub fn run() -> glib::ExitCode {
app.add_action(&lock);
app.set_accels_for_action("app.lock", &["<primary>l"]);
// A notification body click lands here: GNOME Shell emits
// `ActionInvoked("default")` and GLib activates the notification's default
// action in-process (the `org.gtk.Notifications` path calls
// `ActivateAction("focus")` instead). Bring the window — and the dialog
// waiting on it — back to the front.
let focus = gio::SimpleAction::new("focus", None);
{
let app = app.clone();
focus.connect_activate(move |_, _| {
eprintln!("regent: bringing the window to the front");
for window in app.windows() {
window.present();
}
});
}
app.add_action(&focus);
app.connect_startup(|_| load_css());
app.connect_activate(move |app| Window::new(app, Rc::clone(&state)).present());
// Reuse the window: an activation can arrive while the app is already
// running (a notification click, or launching `regent` again), and a second
// window would share the state and show the same dialog twice.
app.connect_activate(move |app| {
if let Some(window) = app.windows().first() {
window.present();
return;
}
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.
+1 -1
View File
@@ -129,7 +129,7 @@ async fn serve(
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Deny).await;
}
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
+100 -12
View File
@@ -5,14 +5,21 @@
//! same way. **No answer means no** — the ask times out to `Deny`, never to a
//! silent yes.
use std::time::Duration;
use std::time::{Duration, Instant};
use async_channel::{Receiver, Sender, bounded};
use nostr::prelude::*;
/// How long the responder waits for the user before denying.
/// How long a prompt stays up. The **UI** enforces this: it closes the dialog,
/// answers `Deny` and lets the notification be withdrawn, so the user sees the
/// request expire instead of finding buttons that no longer do anything.
pub const ASK_TIMEOUT: Duration = Duration::from_secs(60);
/// The responder's own backstop, for a UI that never answers at all (broken, or
/// absent). Deliberately longer than [`ASK_TIMEOUT`] so the dialog is what the
/// user sees expire — and so the UI's answer always lands on a live receiver.
pub const ASK_BACKSTOP: Duration = Duration::from_secs(90);
/// Who is asking, as far as we can tell.
///
/// Name, URL and image come from the client's own `connect` metadata: they are
@@ -102,9 +109,21 @@ pub enum Prompt {
Approve {
question: Question,
reply: Sender<Decision>,
/// When the dialog must give up and answer `Deny`.
///
/// **Absolute, and fixed when the ask starts** — not a duration the UI
/// applies when the dialog opens. Prompts queue behind each other, and a
/// deadline re-armed at presentation time could outlive this side's
/// backstop, leaving the dialog with buttons that no longer do anything.
deadline: Instant,
},
/// Open the vault. `true` means it is now unlocked.
Unlock { reply: Sender<bool> },
Unlock {
reply: Sender<bool>,
/// The same absolute deadline, so the unlock dialog expires with the
/// request.
deadline: Instant,
},
}
/// The handle the responder uses to ask the user.
@@ -122,16 +141,27 @@ impl Approver {
/// Ask, and treat a timeout or a missing UI as a denial.
pub async fn ask(&self, question: Question) -> Decision {
self.ask_within(ASK_TIMEOUT, question).await
self.ask_within(ASK_TIMEOUT, ASK_BACKSTOP, question).await
}
/// The same, with an explicit deadline, so tests can exercise the timeout
/// without waiting a minute.
async fn ask_within(&self, within: Duration, question: Question) -> Decision {
/// The same, with explicit deadlines so tests can exercise both without
/// waiting a minute: `deadline` is what the UI is told, `within` is this
/// side's own backstop. Both are anchored **now**, so a prompt that waits in
/// the queue behind another one still expires before the backstop.
async fn ask_within(
&self,
deadline: Duration,
within: Duration,
question: Question,
) -> Decision {
let (reply, answer) = bounded(1);
if self
.inbox
.send(Prompt::Approve { question, reply })
.send(Prompt::Approve {
question,
reply,
deadline: Instant::now() + deadline,
})
.await
.is_err()
{
@@ -148,12 +178,20 @@ impl Approver {
/// A timeout, a missing UI or a refusal is `false`: no answer never means
/// "unlocked". A locked vault fails closed exactly like a declined request.
pub async fn ask_unlock(&self) -> bool {
self.ask_unlock_within(ASK_TIMEOUT).await
self.ask_unlock_within(ASK_TIMEOUT, ASK_BACKSTOP).await
}
async fn ask_unlock_within(&self, within: Duration) -> bool {
async fn ask_unlock_within(&self, deadline: Duration, within: Duration) -> bool {
let (reply, answer) = bounded(1);
if self.inbox.send(Prompt::Unlock { reply }).await.is_err() {
if self
.inbox
.send(Prompt::Unlock {
reply,
deadline: Instant::now() + deadline,
})
.await
.is_err()
{
return false;
}
match tokio::time::timeout(within, answer.recv()).await {
@@ -199,6 +237,7 @@ mod tests {
});
let decision = approver
.ask_within(
Duration::from_millis(50),
Duration::from_millis(50),
question(Request::Pair { requested: None }),
)
@@ -219,6 +258,55 @@ mod tests {
drain.abort();
}
/// The dialog deadline must stay below the responder's backstop, so an
/// answer the UI produces at its own deadline still lands on a live
/// receiver. If this flips, a prompt at the deadline would be denied twice
/// and the notification would be withdrawn for nothing.
#[test]
fn the_backstop_outlives_the_dialog_deadline() {
assert!(ASK_BACKSTOP > ASK_TIMEOUT);
}
/// A prompt can wait in the queue behind another one, so the deadline the
/// UI is handed has to be anchored **when the ask starts**, not when the
/// dialog finally opens: otherwise a queued prompt's dialog would outlive
/// 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 deadline = Duration::from_millis(200);
let backstop = Duration::from_millis(400);
let before = Instant::now();
// Nobody drains the queue, so both asks sit in it until the backstop.
let (first, second) = tokio::join!(
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None })),
approver.ask_within(deadline, backstop, question(Request::Pair { requested: None })),
);
assert_eq!(first, Decision::Deny);
assert_eq!(second, Decision::Deny);
let mut deadlines = Vec::new();
while let Ok(prompt) = prompts.try_recv() {
match prompt {
Prompt::Approve { deadline, .. } => deadlines.push(deadline),
_ => panic!("the asks were approvals"),
}
}
assert_eq!(deadlines.len(), 2, "both prompts are queued");
for deadline_at in deadlines {
assert!(deadline_at > before, "anchored at the ask, not before it");
assert!(
deadline_at <= before + deadline + Duration::from_millis(50),
"never re-armed later: {deadline_at:?}"
);
assert!(
deadline_at < before + backstop,
"the dialog deadline still precedes the backstop"
);
}
}
/// A UI that never answers must not unlock the vault either.
#[tokio::test]
async fn a_silent_ui_never_unlocks() {
@@ -231,7 +319,7 @@ mod tests {
});
assert!(
!approver
.ask_unlock_within(Duration::from_millis(50))
.ask_unlock_within(Duration::from_millis(50), Duration::from_millis(50))
.await,
"no answer is not an unlock"
);
+5 -5
View File
@@ -1300,7 +1300,7 @@ mod tests {
Prompt::Approve { reply, .. } => {
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
@@ -1326,12 +1326,12 @@ mod tests {
let handle = tokio::spawn(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { question, reply } => {
Prompt::Approve { question, reply, .. } => {
let decision = decide(&question.request);
log.lock().unwrap().push(question.request.clone());
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
@@ -1709,7 +1709,7 @@ mod tests {
Prompt::Approve { reply, .. } => {
let _ = reply.send(Decision::Once).await;
}
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, .. } => {
let opened = unlocking.unlock("hunter2").await.is_ok();
let _ = reply.send(opened).await;
}
@@ -1766,7 +1766,7 @@ mod tests {
let _ = reply.send(Decision::Once).await;
}
// The user closes the unlock dialog without opening it.
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, .. } => {
let _ = reply.send(false).await;
}
}
+214 -40
View File
@@ -6,12 +6,15 @@
//! Regent's own interface.
use std::sync::Arc;
use std::time::{Duration, Instant};
use async_channel::Receiver;
use nostr::nips::nip19::ToBech32;
use zeroize::Zeroizing;
use adw::prelude::*;
use gtk::gio;
use gtk::gio::prelude::ApplicationExt;
use gtk::prelude::*;
use libadwaita as adw;
@@ -20,6 +23,14 @@ use crate::signer::approval::{Decision, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{kind, plain};
use crate::APP_ID;
/// One notification id, so a second prompt replaces the first rather than
/// stacking. The drain is serialized, so only one prompt is ever open.
const NOTIFICATION_ID: &str = "approval";
/// What the desktop shows for the unlock prompt.
const UNLOCK_BODY: &str = "Regent needs your passphrase to continue";
/// Start draining prompts: each one becomes a dialog, and the answer goes back
/// to the responder. Anything unanswered is a denial — and an unanswered unlock
@@ -28,15 +39,38 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
glib::MainContext::default().spawn_local(async move {
while let Ok(prompt) = prompts.recv().await {
match prompt {
Prompt::Approve { question, reply } => {
let decision = present_question(&widget, &question).await;
Prompt::Approve {
question,
reply,
deadline,
} => {
// A prompt can wait here behind another one. If its deadline
// has already passed, answer without raising a notification
// or flashing a dialog for a request that is already gone.
if expired(deadline) {
let _ = reply.send(Decision::Deny).await;
continue;
}
let notified = notify_pending(&widget, notification_body(&question.request));
let decision = present_question(&widget, &question, Some(deadline)).await;
if notified {
withdraw_pending(&widget);
}
let _ = reply.send(decision).await;
}
Prompt::Unlock { reply } => {
Prompt::Unlock { reply, deadline } => {
if expired(deadline) {
let _ = reply.send(false).await;
continue;
}
let notified = notify_pending(&widget, UNLOCK_BODY);
let unlocked = match state.store() {
Some(store) => present_unlock(&widget, store).await,
Some(store) => present_unlock(&widget, store, Some(deadline)).await,
None => false,
};
if notified {
withdraw_pending(&widget);
}
if unlocked {
// Only `notify` reaches the header lock button and the
// keys page's vault rows; `notify_changes` does not.
@@ -49,6 +83,107 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
});
}
/// The one line the desktop shows.
///
/// Deliberately no client name, event kind or content: a notification body is
/// rendered on the lock screen, and the client's name is attacker-controlled
/// display data — the same rule the activity log follows.
fn notification_body(request: &Request) -> &'static str {
match request {
Request::Pair { .. } => "An application wants to connect",
Request::Sign { .. } => "An application is asking for a signature",
Request::Encrypt { .. } => "An application is asking to encrypt a message",
Request::Decrypt { .. } => "An application is asking to decrypt a message",
}
}
/// 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 {
let Some(window) = window_of(widget) else {
return false;
};
if !user_is_away(&window) {
return false;
}
let Some(app) = window.application() else {
return false;
};
let notification = gio::Notification::new("Regent");
notification.set_body(Some(body));
// High becomes urgency 1, so the banner is not treated as routine.
notification.set_priority(gio::NotificationPriority::High);
notification.set_icon(&gio::ThemedIcon::new(APP_ID));
// A body click: GNOME Shell emits `ActionInvoked("default")` and GLib then
// 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);
true
}
fn withdraw_pending(widget: &impl IsA<gtk::Widget>) {
if let Some(app) = window_of(widget).and_then(|window| window.application()) {
app.withdraw_notification(NOTIFICATION_ID);
}
}
fn window_of(widget: &impl IsA<gtk::Widget>) -> Option<gtk::Window> {
widget.root().and_downcast::<gtk::Window>()
}
/// Whether the user is looking somewhere else.
///
/// `REGENT_NOTIFY_ALWAYS` forces "away" so the acceptance test can exercise the
/// notification path: `gtk4-broadwayd` reports the window active even though
/// there is no window manager to focus anything. The same kind of documented
/// test override as `REGENT_RELAYS`.
fn user_is_away(window: &gtk::Window) -> bool {
std::env::var_os("REGENT_NOTIFY_ALWAYS").is_some() || !window.is_active()
}
/// How long is left before an absolute deadline.
///
/// `None` means no deadline at all; `Some(Duration::ZERO)` means it has already
/// passed.
fn remaining(deadline: Option<Instant>) -> Option<Duration> {
deadline.map(|deadline| {
deadline
.checked_duration_since(Instant::now())
.unwrap_or_default()
})
}
/// Whether there is nothing left before the deadline.
fn expired(deadline: Instant) -> bool {
remaining(Some(deadline)) == Some(Duration::ZERO)
}
/// Close a dialog once its deadline passes, answering first.
///
/// The dialog owns the deadline so the user sees the request expire — and the
/// notification is withdrawn — instead of finding buttons that no longer do
/// anything because the responder has given up. The deadline is absolute and
/// was fixed when the ask started, so this holds for a prompt that waited in
/// the queue behind another one too.
fn expire<T: Send + 'static>(
dialog: &adw::AlertDialog,
reply: &async_channel::Sender<T>,
expired_value: T,
deadline: Option<Instant>,
) {
let Some(left) = remaining(deadline) else {
return;
};
let dialog = dialog.clone();
let reply = reply.clone();
glib::timeout_add_local_once(left.max(Duration::from_millis(1)), move || {
let _ = reply.try_send(expired_value);
dialog.force_close();
});
}
/// Which buttons a question offers.
enum Choices {
/// Denying or connecting; a connect is always remembered (M3 pairing).
@@ -67,6 +202,7 @@ enum Choices {
pub async fn present_question(
widget: &impl IsA<gtk::Widget>,
question: &Question,
deadline: Option<Instant>,
) -> Decision {
let request = &question.request;
let choices = match request {
@@ -107,15 +243,19 @@ pub async fn present_question(
}
let (sender, answer) = async_channel::bounded(1);
dialog.connect_response(None, move |_, response| {
let decision = match response {
"always" => Decision::Always,
"once" | "allow" => Decision::Once,
_ => Decision::Deny,
};
let _ = sender.try_send(decision);
});
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
{
let sender = sender.clone();
dialog.connect_response(None, move |_, response| {
let decision = match response {
"always" => Decision::Always,
"once" | "allow" => Decision::Once,
_ => Decision::Deny,
};
let _ = sender.try_send(decision);
});
}
dialog.present(window_of(widget).as_ref());
expire(&dialog, &sender, Decision::Deny, deadline);
// Dropped without an answer (window closed, app gone) is a denial.
answer.recv().await.unwrap_or(Decision::Deny)
@@ -123,14 +263,27 @@ pub async fn present_question(
/// Ask for the vault passphrase and open it.
///
/// A locked vault fails closed: cancelling, closing the window or a missing
/// store leaves it locked, exactly like an unanswered approval question.
pub async fn present_unlock(widget: &impl IsA<gtk::Widget>, store: Arc<KeyStore>) -> bool {
/// A locked vault fails closed: cancelling, closing the window, a missing store
/// or an expired deadline all leave it locked, exactly like an unanswered
/// approval question.
pub async fn present_unlock(
widget: &impl IsA<gtk::Widget>,
store: Arc<KeyStore>,
deadline: Option<Instant>,
) -> bool {
if !store.is_locked() {
return true;
}
let mut problem: Option<&'static str> = None;
loop {
let Some(passphrase) = ask_passphrase(widget).await else {
// One deadline for the whole unlock, not one per passphrase attempt: a
// wrong passphrase must not buy the request more time.
if remaining(deadline) == Some(Duration::ZERO) {
return false;
}
let Some(passphrase) = ask_passphrase(widget, problem, deadline).await else {
return false;
};
let (sender, answer) = async_channel::bounded(1);
@@ -146,34 +299,26 @@ pub async fn present_unlock(widget: &impl IsA<gtk::Widget>, store: Arc<KeyStore>
match answer.recv().await {
Ok(Ok(())) => return true,
Ok(Err(error)) => {
// Wrong passphrase, or an unreadable vault: say so and ask again.
let dialog = adw::AlertDialog::builder()
.heading("Could not unlock")
.body(error)
.build();
plain::dialog(&dialog);
dialog.add_response("close", "Try again");
dialog.set_default_response(Some("close"));
let (sender, answer) = async_channel::bounded(1);
dialog.connect_response(None, move |_, _| {
let _ = sender.try_send(());
});
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
// Wait for the acknowledgement so the next prompt does not
// stack on top of it.
let _ = answer.recv().await;
// The raw error is a crypto failure ("invalid HMAC") that tells
// the user nothing, so log it and say it in our own words.
eprintln!("regent: could not open the key vault: {error}");
problem = Some("That passphrase does not open the key vault.");
}
Err(_) => return false,
}
}
}
/// One passphrase dialog. `None` when the user cancelled.
/// One passphrase dialog. `None` when the user cancelled or the deadline passed.
///
/// Unlike an approval question this *does* have a default response: the user is
/// typing the passphrase themselves, and an empty submit simply fails and asks
/// again. It never answers a client's request on the user's behalf.
async fn ask_passphrase(widget: &impl IsA<gtk::Widget>) -> Option<Zeroizing<String>> {
async fn ask_passphrase(
widget: &impl IsA<gtk::Widget>,
problem: Option<&str>,
deadline: Option<Instant>,
) -> Option<Zeroizing<String>> {
let entry = adw::PasswordEntryRow::builder().title("Passphrase").build();
let list = gtk::ListBox::builder()
.selection_mode(gtk::SelectionMode::None)
@@ -183,7 +328,11 @@ async fn ask_passphrase(widget: &impl IsA<gtk::Widget>) -> Option<Zeroizing<Stri
let dialog = adw::AlertDialog::builder()
.heading("Unlock the key vault")
.body("Your identity keys are stored encrypted with your passphrase.")
.body(
problem.unwrap_or(
"Your identity keys are stored encrypted with your passphrase.",
),
)
.extra_child(&list)
.build();
plain::dialog(&dialog);
@@ -194,10 +343,14 @@ async fn ask_passphrase(widget: &impl IsA<gtk::Widget>) -> Option<Zeroizing<Stri
dialog.set_close_response("cancel");
let (sender, answer) = async_channel::bounded(1);
dialog.connect_response(None, move |_, response| {
let _ = sender.try_send(response == "unlock");
});
dialog.present(widget.root().and_downcast::<gtk::Window>().as_ref());
{
let sender = sender.clone();
dialog.connect_response(None, move |_, response| {
let _ = sender.try_send(response == "unlock");
});
}
dialog.present(window_of(widget).as_ref());
expire(&dialog, &sender, false, deadline);
if answer.recv().await.unwrap_or(false) {
Some(Zeroizing::new(entry.text().to_string()))
@@ -387,3 +540,24 @@ fn plain(text: &str) -> gtk::Label {
.build()
}
#[cfg(test)]
mod tests {
use super::*;
/// A prompt can wait in the queue behind another one, so the drain decides
/// from an absolute deadline — and must treat "already passed" as its own
/// case rather than a zero-length wait.
#[test]
fn a_passed_deadline_has_nothing_left() {
assert_eq!(remaining(None), None);
assert_eq!(
remaining(Some(Instant::now() - Duration::from_secs(1))),
Some(Duration::ZERO)
);
assert!(remaining(Some(Instant::now() + Duration::from_secs(5))).unwrap() > Duration::ZERO);
assert!(expired(Instant::now() - Duration::from_millis(1)));
assert!(!expired(Instant::now() + Duration::from_secs(5)));
}
}
+1 -1
View File
@@ -621,7 +621,7 @@ fn with_unlocked<F: FnOnce() + 'static>(handles: &Handles, state: &Rc<AppState>,
let widget: gtk::Widget = handles.stack.clone().upcast();
let state = Rc::clone(state);
glib::MainContext::default().spawn_local(async move {
if approval::present_unlock(&widget, store).await {
if approval::present_unlock(&widget, store, None).await {
// The vault just opened: the header button and the vault rows only
// hear about it through `notify`.
state.notify();
+1 -1
View File
@@ -501,7 +501,7 @@ fn begin_pairing(
let widget: gtk::Widget = handles.stack.clone().upcast();
glib::MainContext::default().spawn_local(async move {
// The same dialog and the same rules as a responder-side question.
let decision = approval::present_question(&widget, &question).await;
let decision = approval::present_question(&widget, &question, None).await;
if decision == Decision::Deny {
return;
}