Label metadata-less clients by their key and preview icons at consent

Connecting noStrudel by pasting Regent's bunker:// code showed "(unnamed)" and
no icon. noStrudel (through applesauce-signers) only sends client metadata in
the client-initiated direction: fromBunkerURI is called without metadata, so its
connect request is [remote, secret, perms] and there is no metadata for Regent to
read. That direction cannot be fixed here, but it should not render as broken.

- The approval dialog and the Apps row fall back to the shortened npub and build
  the AdwAvatar with show_initials(false) instead of feeding the
  "(unnamed)"/"Unnamed application" placeholder into the initials, which showed
  as "(" / "U".
- parse_client_uri and client_info treat empty name/url/image (and perms) as
  absent. Clients that always emit name=&url=&image=&perms= used to store
  url: Some(""), which rendered an empty byline instead of the npub fallback.
- The approval dialog now fetches the client's declared icon before approval,
  but only when load-app-icons is on. AppState::preview_icon is memory-only: no
  disk cache is written for an unapproved app, so a denial leaves nothing behind.
  This turns M11's blanket no-fetch-before-consent rule into a user setting.

Adds tests for empty query and connect metadata values.
This commit is contained in:
raucao committed 2026-11-26 22:57:47 +04:00
1 parent 468d918bd3
commit eee77b9f76
7 files changed
+203 -47

No files matched your search

+17 -4
View File
@@ -526,10 +526,23 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
`Send`). A cached `.img` may be decoded synchronously on the first paint
(`AppState::hydrate_icon`), bounded by the byte cap; `IconStore` memoises the
sidecar URL and the one-shot hydration so the per-ping path does no disk I/O.
- **No fetch before consent.** The approval dialog shows the icon only when it is
already cached (an already-approved app); a first pairing shows initials.
Fetching an unknown app's URL at the moment trust is decided is a tracking ping
to that app's server — the same rule as M9's no-client-text notification bodies.
- **No fetch before consent — now a preference, not a rule.** For an
already-approved app the dialog shows the cached icon. For a first pairing it
shows the client's declared icon too, but **only when `load-app-icons` is on**,
fetched through `AppState::preview_icon`, which is **memory only**: no disk cache
is written for an unapproved app, so a denial leaves nothing behind. With the
preference off there is no request and the dialog shows the generic avatar and
the shortened npub. (M9's no-client-text *notification* bodies remain strict.)
- **A metadata-less client is labelled by its key.** When an app declares no usable
`name`, the approval dialog and the Apps row show `plain::shorten_npub` and build
the `AdwAvatar` with `show_initials(false)` (libadwaita's generic glyph) — never
the strings `"(unnamed)"`/`"Unnamed application"` as initials, which rendered as
`"("`/`"U"`. Empty `name`/`url`/`image` (and `perms`) are treated as **absent** in
`parse_client_uri` and `client_info`: some clients always emit
`name=&url=&image=&perms=`, and `url: Some("")` otherwise produced an empty byline
instead of the npub fallback. Note the **bunker direction often carries no
metadata at all** — noStrudel's `fromBunkerURI` sends none — so this is normal, not
a parse failure.
- **Render.** A 32 px `adw::Avatar` prefix on the Apps `AdwExpanderRow`, and beside
the plain-text "Application" field in the approval dialog. The icon is
**decoration, never the sole identifier**, and the name stays plain text — a
+61 -3
View File
@@ -471,12 +471,21 @@ pub fn parse_client_uri(uri: &str) -> Result<ClientPairing> {
relays,
secret,
// Bound client-supplied text: it reaches a dialog, the log and apps.json.
// An empty value is treated as absent — some clients always include
// `name=&url=&image=&perms=`, and a stored `Some("")` reads as "declared
// nothing" everywhere it is shown.
name: name
.filter(|name| !name.trim().is_empty())
.map(|name| bound(&name, 64)),
url: url.map(|url| bound(&url, 256)),
image: image.map(|image| bound(&image, 256)),
requested: requested.map(|perms| bound(&perms, 200)),
url: url
.filter(|url| !url.trim().is_empty())
.map(|url| bound(&url, 256)),
image: image
.filter(|image| !image.trim().is_empty())
.map(|image| bound(&image, 256)),
requested: requested
.filter(|perms| !perms.trim().is_empty())
.map(|perms| bound(&perms, 200)),
})
}
@@ -1095,6 +1104,7 @@ fn client_info(public_key: &PublicKey, params: &[String]) -> ClientInfo {
.as_ref()
.and_then(|value| value[name].as_str())
.map(str::to_string)
.filter(|value| !value.trim().is_empty())
};
ClientInfo {
public_key: *public_key,
@@ -2259,6 +2269,54 @@ mod tests {
assert!(parse_client_uri("https://example.com").is_err());
}
/// Clients that always emit the metadata keys (`name=&url=&image=&perms=`)
/// must not produce an empty name, an empty byline or a stored empty image.
#[test]
fn empty_metadata_query_values_are_absent() {
let keys = Keys::generate();
let uri = format!(
"nostrconnect://{}?relay=wss%3A%2F%2Frelay.example.com&secret=s\
&name=&url=&image=&perms=",
keys.public_key().to_hex()
);
let pairing = parse_client_uri(&uri).expect("parse");
assert_eq!(pairing.name, None);
assert_eq!(pairing.url, None);
assert_eq!(pairing.image, None);
assert_eq!(pairing.requested, None);
}
/// The `connect` metadata JSON: empty strings are the same as absent fields.
#[test]
fn empty_connect_metadata_fields_are_absent() {
let keys = Keys::generate();
let with_empty = vec![
keys.public_key().to_hex(),
String::new(),
String::new(),
r#"{"name":"","url":"","image":""}"#.to_string(),
];
let info = client_info(&keys.public_key(), &with_empty);
assert_eq!(info.name, None);
assert_eq!(info.url, None);
assert_eq!(info.image, None);
let real = vec![
keys.public_key().to_hex(),
String::new(),
String::new(),
r#"{"name":"noStrudel","url":"https://nostrudel.ninja","image":"https://nostrudel.ninja/apple-touch-icon.png"}"#
.to_string(),
];
let info = client_info(&keys.public_key(), &real);
assert_eq!(info.name.as_deref(), Some("noStrudel"));
assert_eq!(info.url.as_deref(), Some("https://nostrudel.ninja"));
assert_eq!(
info.image.as_deref(),
Some("https://nostrudel.ninja/apple-touch-icon.png")
);
}
/// The client learns the signer key from the response author and must get
/// its own secret back as the result.
#[test]
+44
View File
@@ -10,6 +10,8 @@ use std::sync::{Arc, Mutex};
use nostr::nips::nip19::ToBech32;
use nostr::prelude::PublicKey;
use gtk::gdk;
use crate::config::Config;
use crate::runtime;
use crate::store::apps::AppRegistry;
@@ -214,6 +216,48 @@ impl AppState {
);
}
/// Fetch a client's declared icon for an approval dialog, **before** it is
/// approved, and hand the texture to `apply` for display.
///
/// Only when icon loading is enabled — this is a request to a not-yet-trusted
/// server, so it is the user's setting to make. Memory only: nothing about an
/// unapproved application is written to disk. A denial therefore leaves no
/// trace, and an approval re-fetches once through [`AppState::load_icon`] to
/// cache it.
pub fn preview_icon(
self: &Rc<Self>,
key: &str,
url: &str,
apply: impl FnOnce(gdk::Texture) + 'static,
) {
if !Config::new().load_app_icons() || !crate::store::icons::is_fetchable(url) {
return;
}
let icons = self.icons();
if let Some(texture) = icons.texture(key) {
apply(texture);
return;
}
if !icons.begin_preview(key, url) {
return;
}
let key = key.to_string();
let url = url.to_string();
let fetch_url = url.clone();
runtime::spawn(
async move { crate::store::icons::fetch(&fetch_url).await },
move |result| {
icons.end_preview(&key, &url);
if let Ok(bytes) = result {
if let Ok(texture) = crate::store::icons::decode(&bytes) {
icons.set_texture(&key, texture.clone());
apply(texture);
}
}
},
);
}
/// What to call an identity: its kind-0 `display_name` if one was fetched,
/// else the user's label for the key.
pub fn identity_label(&self, key: &PublicKey) -> String {
+20
View File
@@ -301,6 +301,8 @@ pub struct IconStore {
urls: RefCell<HashMap<String, Option<String>>>,
textures: RefCell<HashMap<String, gdk::Texture>>,
in_flight: RefCell<HashSet<(String, String)>>,
/// Pre-consent preview fetches an approval dialog has started.
previews: RefCell<HashSet<(String, String)>>,
/// `(key, url)` pairs whose cache has already been looked at once.
hydrated: RefCell<HashSet<(String, String)>>,
}
@@ -317,6 +319,7 @@ impl IconStore {
urls: RefCell::new(HashMap::new()),
textures: RefCell::new(HashMap::new()),
in_flight: RefCell::new(HashSet::new()),
previews: RefCell::new(HashSet::new()),
hydrated: RefCell::new(HashSet::new()),
}
}
@@ -417,6 +420,23 @@ impl IconStore {
self.hydrated.borrow_mut().insert((key, url.to_string()))
}
/// Claim a pre-consent preview fetch for `(key, url)`. Separate from
/// [`IconStore::begin`] so it never blocks, or is blocked by, the cached
/// post-approval fetch. Memory only: a preview never writes to disk.
pub fn begin_preview(&self, key: &str, url: &str) -> bool {
let Some(key) = Self::valid_key(key) else {
return false;
};
self.previews.borrow_mut().insert((key, url.to_string()))
}
/// Release a claim taken by [`IconStore::begin_preview`].
pub fn end_preview(&self, key: &str, url: &str) {
if let Some(key) = Self::valid_key(key) {
self.previews.borrow_mut().remove(&(key, url.to_string()));
}
}
/// Release a claim taken by [`IconStore::begin`].
pub fn end(&self, key: &str, url: &str) {
if let Some(key) = Self::valid_key(key) {
+41 -25
View File
@@ -5,6 +5,7 @@
//! Pango markup — so an application cannot forge formatting that looks like
//! Regent's own interface.
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -13,14 +14,13 @@ use nostr::nips::nip19::ToBech32;
use zeroize::Zeroizing;
use adw::prelude::*;
use gtk::gdk;
use gtk::gio;
use gtk::gio::prelude::ApplicationExt;
use gtk::prelude::*;
use libadwaita as adw;
use crate::runtime;
use crate::signer::approval::{Decision, Notice, Prompt, Question, Request};
use crate::signer::approval::{ClientInfo, Decision, Notice, Prompt, Question, Request};
use crate::state::AppState;
use crate::store::keys::KeyStore;
use crate::ui::{content, kind, plain};
@@ -57,15 +57,8 @@ pub fn install(prompts: Receiver<Prompt>, widget: gtk::Widget, state: std::rc::R
continue;
}
let notified = notify_pending(&widget, notification_body(&question.request));
// The icon is shown only when it is already cached: a first
// pairing shows initials, because fetching an unknown app's
// URL before the user says yes is a tracking ping at the
// moment trust is being decided.
let icon = state
.icons()
.texture(&question.client.public_key.to_hex());
let decision =
present_question(&widget, &question, Some(deadline), icon.as_ref()).await;
present_question(&widget, &question, Some(deadline), &state).await;
if notified {
withdraw_pending(&widget);
}
@@ -248,7 +241,7 @@ pub async fn present_question(
widget: &impl IsA<gtk::Widget>,
question: &Question,
deadline: Option<Instant>,
icon: Option<&gdk::Texture>,
state: &Rc<AppState>,
) -> Decision {
let request = &question.request;
let choices = match request {
@@ -260,7 +253,7 @@ pub async fn present_question(
let dialog = adw::AlertDialog::builder()
.heading(heading(request))
.body(story(request))
.extra_child(&details(question, widget, deadline, icon))
.extra_child(&details(question, widget, deadline, state))
.build();
// Heading and body are plain text too: the heading carries no client data
// today, but the extra child is where all of it belongs.
@@ -448,7 +441,7 @@ fn details(
question: &Question,
widget: &impl IsA<gtk::Widget>,
deadline: Option<Instant>,
icon: Option<&gdk::Texture>,
state: &Rc<AppState>,
) -> gtk::Box {
let client = &question.client;
let content = gtk::Box::builder()
@@ -457,10 +450,7 @@ fn details(
.build();
content.append(&identity_field(&question.identity));
content.append(&application_field(
client.name.as_deref().unwrap_or("(unnamed)"),
icon,
));
content.append(&application_field(state, client));
// The kind is part of what is being signed, so it sits with the payload
// rather than collapsed under Details.
if let Request::Sign { kind, .. } = &question.request {
@@ -577,19 +567,45 @@ fn identity_field(identity: &crate::signer::approval::SigningKey) -> gtk::Box {
plain::field("Signing as", &value)
}
/// The application's name, with its icon when one is cached. The avatar draws
/// initials otherwise — an icon is decoration, never the identifier, and a client
/// must not be able to forge something that looks like Regent's own UI.
fn application_field(name: &str, icon: Option<&gdk::Texture>) -> gtk::Box {
/// The application's name (or its shortened key when it declares none), with its
/// icon. A cached icon is shown at once; otherwise, when icon loading is enabled,
/// the declared icon is fetched for the dialog and swapped in when it lands. The
/// avatar falls back to libadwaita's generic glyph rather than initials of a
/// placeholder — an icon is decoration, never the identifier, and a client must
/// not be able to forge something that looks like Regent's own UI.
fn application_field(state: &Rc<AppState>, client: &ClientInfo) -> gtk::Box {
let public_key = client.public_key.to_hex();
let npub = client
.public_key
.to_bech32()
.unwrap_or_else(|_| public_key.clone());
let name = client
.name
.as_deref()
.map(str::trim)
.filter(|name| !name.is_empty());
let row = gtk::Box::builder()
.orientation(gtk::Orientation::Horizontal)
.spacing(10)
.build();
let avatar = adw::Avatar::new(32, Some(name), true);
if let Some(texture) = icon {
avatar.set_custom_image(Some(texture));
let avatar = match name {
Some(name) => adw::Avatar::new(32, Some(name), true),
None => adw::Avatar::new(32, None, false),
};
if let Some(texture) = state.icons().texture(&public_key) {
avatar.set_custom_image(Some(&texture));
} else if let Some(image) = client.image.as_deref() {
let avatar = avatar.clone();
state.preview_icon(&public_key, image, move |texture| {
avatar.set_custom_image(Some(&texture));
});
}
let label = plain::label(name);
let label_text = name
.map(str::to_string)
.unwrap_or_else(|| plain::shorten_npub(&npub));
let label = plain::label(&label_text);
label.set_hexpand(true);
row.append(&avatar);
row.append(&label);
+17 -11
View File
@@ -257,39 +257,45 @@ impl Ui {
}
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());
// A client that declares no usable name is labelled by its key rather than
// a generic word, and the avatar shows libadwaita's glyph instead of
// initials of a placeholder.
let name = app.name.clone().filter(|name| !name.trim().is_empty());
let title = name
.clone()
.unwrap_or_else(|| plain::shorten_npub(&npub));
let url = app.url.as_deref().filter(|url| !url.trim().is_empty());
// The byline is the host the application declares, because a host is
// what a person can recognise; the public key stays in the details. A
// client-supplied URL is display data only — it proves nothing.
let byline = match app.url.as_deref() {
let byline = match url {
Some(url) => declared_host(url),
None => plain::shorten_npub(&npub),
};
let row = plain::expander(&name, &byline);
let row = plain::expander(&title, &byline);
row.set_subtitle_lines(1);
// The icon is decoration: the plain-text name above stays the identifier,
// and an application without a (fetchable) icon keeps its initials.
let avatar = adw::Avatar::new(32, Some(&name), true);
// The icon is decoration: the name above stays the identifier.
let avatar = match &name {
Some(name) => adw::Avatar::new(32, Some(name), true),
None => adw::Avatar::new(32, None, false),
};
if let Some(texture) = self.state.icons().texture(&app.public_key) {
avatar.set_custom_image(Some(&texture));
}
row.add_prefix(&avatar);
// When the byline is a shortened npub, keep the full key in a tooltip.
if app.url.is_none() {
if url.is_none() {
row.set_tooltip_text(Some(&npub));
}
let public_key = plain::row("Public key", &plain::shorten_npub(&npub));
public_key.set_subtitle_lines(1);
public_key.set_tooltip_text(Some(&npub));
row.add_row(&public_key);
if let Some(url) = &app.url {
if let Some(url) = url {
row.add_row(&plain::row("Declared URL", url));
}
+3 -4
View File
@@ -395,10 +395,9 @@ impl ConnectDialog {
glib::MainContext::default().spawn_local(async move {
// The same approval dialog as a responder question: the app is
// registered *before* the response goes out, and the user is the
// one who decides. A re-pairing may already have a cached icon; a
// first pairing shows initials (no fetch before consent).
let icon = connect.state.icons().texture(&pairing.client.to_hex());
let decision = approval::present_question(&parent, &question, None, icon.as_ref()).await;
// one who decides.
let decision =
approval::present_question(&parent, &question, None, &connect.state).await;
if decision == Decision::Deny {
return;
}