Show identity keys in one style, and verify NIP-05 before showing it
Every key in the app is now the same kind of thing: `plain::key` / `.key-value` renders it in the monospace font at the size the label already has, as a fixed `head…tail` cut, so a column of them lines up. Deliberately not libadwaita's `.monospace`, which also switches to the code size and, on an `AdwActionRow`, takes the field name with it. The identities list shows the name over the key alone (it used to be "Profile · npub" on one line, where a long profile name ate the key's tail), and the switcher keeps its own shorter npub cut and renders it at `.caption`: a key is never body-sized there, and the row's bold *name* stays the loudest thing in it. The switcher's second line prefers a NIP-05 address — but only one the domain has confirmed for exactly this key, because a kind-0's `nip05` is self-declared and that line is where an identity is identified. `store::nip05` parses the address strictly (it becomes an HTTPS request, so a sloppy parse would be an SSRF), asks `https://<domain>/.well-known/nostr.json?name=<local>` through the icons' hardened fetch — now split into `fetch_https(url, Content)`, the app's single HTTP path — and shows the address only while `nip05_ok == nip05`. A re-declared or forged address is unverified again immediately, a slow answer for a changed one is dropped, and a failed check costs a day. Names are no longer invented: no "Identity 3" and no "Imported 1". The create dialog starts empty, import carries a Name field that is prefilled from a cached profile as soon as the pasted string decodes to a key, and an empty field stores no label at all. A discovered profile name trumps the label for display (`identity_label`), which is what happens for a key imported before its profile was known — the label itself is never overwritten.
This commit is contained in:
14 files changed
+913
-176
No files matched your search
@@ -39,6 +39,7 @@ src/store/audit.rs the activity log (metadata only, mode 0600)
|
||||
src/store/keys.rs the NIP-49 key vault (identity keys + the device key)
|
||||
src/store/profiles.rs cached kind-0 names and picture URLs (read-only)
|
||||
src/store/icons.rs app icons + identity avatars: hardened fetch, disk cache (M11)
|
||||
src/store/nip05.rs NIP-05 parse + the verified-address check (single HTTP path)
|
||||
src/ui/approval.rs approval dialogs
|
||||
src/ui/apps_view.rs the apps page (permission table + revoke)
|
||||
src/ui/activity_view.rs the activity page
|
||||
@@ -405,10 +406,33 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
pattern): a `GtkMenuButton` showing the current identity's avatar (the kind-0
|
||||
picture when one is cached, else initials),
|
||||
opening a popover with one row per key (avatar, `display_name` or key label,
|
||||
short npub, a check on the current), then "Manage identities…" (opens the
|
||||
identities window). Hidden when there are no keys; rebuilds on key and selection
|
||||
changes. Holds the `Windows` registry **weakly**: the main window owns the
|
||||
switcher, so a strong reference would be a cycle.
|
||||
then **one** short line, a check on the current), then "Manage identities…"
|
||||
(opens the identities window). Hidden when there are no keys; rebuilds on key
|
||||
and selection changes; both the header button's label and the rows are sorted
|
||||
by what they show. Holds the `Windows` registry **weakly**: the main window owns
|
||||
the switcher, so a strong reference would be a cycle.
|
||||
- **The switcher's second line** is a **verified** NIP-05 address when the domain
|
||||
confirmed it for this key (`Profile.nip05 == Profile.nip05_ok`): shown as
|
||||
published, because that address is what the user recognises, and the popover
|
||||
widens for a long one. Past `plain::key`'s 48-character natural-width cap it is
|
||||
end-ellipsized rather than clipped, so the popover cannot run off the screen.
|
||||
Without a verified address the line is the key:
|
||||
`plain::shorten(npub, 12, 7)` — 20 characters, shorter than
|
||||
`plain::shorten_npub`'s 31 because this popover also carries the avatar and a
|
||||
check mark inside a 420 px window. The tooltip always carries the full npub.
|
||||
- That line carries `.caption`: *about* the size a key renders at in every row
|
||||
subtitle (12.0 pt against a subtitle's 12.2 — the class is 82%, a subtitle's
|
||||
`smaller` is ~83%; the 20-character npub cut measures 145 px there against
|
||||
176 px at body size), so the switcher is not the one place a key is body-sized
|
||||
and the bold name above it stays the loudest thing in the row.
|
||||
- **In a switcher row the name is bold and the value is not.** The rows are
|
||||
`GtkButton`s and libadwaita bolds every button's text (`button { font-weight:
|
||||
bold }`, no `.flat` exemption), which is exactly what the identity's *name*
|
||||
should look like (700, measured with
|
||||
`get_pango_context().get_font_description()`). The npub/NIP-05 beneath it is a
|
||||
value and stays normal weight — `label.key-value` sets `font-family` **and**
|
||||
`font-weight: normal` for that (the class beats the theme's element selector).
|
||||
The avatar's initials are bold too, by libadwaita's own `avatar` rule.
|
||||
- **Pages are scoped to the selected identity:** Apps lists only that identity's
|
||||
approvals (the title names it) and its "Forget all" is scoped; Activity filters
|
||||
to the identity and "Clear this identity's activity" keeps the rest. Pre-M7
|
||||
@@ -477,10 +501,27 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
cadence. The ignored `nak_the_outbox_relay_profile_wins` test covers the
|
||||
cross-relay newest-wins rule, two identities and the warm path (dead directory,
|
||||
cached outbox) against two local `nak serve`s on ports 10590/10591.
|
||||
- Only `display_name` and `picture` are kept; nip05 is never shown as verified,
|
||||
since kind-0 is attacker-publishable. `picture` is bounded like
|
||||
`ClientInfo.image` (trimmed, ≤256 chars, blank ⇒ absent) and re-bounded on
|
||||
read, because `profiles.json` is on disk.
|
||||
- `display_name`, `picture` and a **well-formed** `nip05` are kept — nothing else.
|
||||
`picture` is bounded like `ClientInfo.image` (trimmed, ≤256 chars, blank ⇒
|
||||
absent) and re-bounded on read, because `profiles.json` is on disk; an `nip05`
|
||||
is stored normalised (`local@domain`, lowercase) and only if it parses, because
|
||||
an unparseable address could never be verified and so could never be shown.
|
||||
- **nip05 is shown only when verified** (`store::nip05`). A kind-0's `nip05` is
|
||||
self-declared, and the one place it would appear — the switcher's second line —
|
||||
is exactly where the identity is identified, so the domain must confirm it:
|
||||
`https://<domain>/.well-known/nostr.json?name=<local>` has to map that name back
|
||||
to *this* key. The rule is `Profile.nip05 == Profile.nip05_ok`, so re-declaring
|
||||
a different address (or a forged one) makes it unverified immediately and the
|
||||
npub comes back; a slow answer for an address that has meanwhile changed is
|
||||
dropped (`set_nip05` compares before storing); a failed check keeps it unshown
|
||||
and is retried at most once a day (`nip05_checked_at`).
|
||||
- That fetch goes through **the same single hardened HTTP path** as the icons —
|
||||
`store::icons::fetch_https(url, Content::Document)`, `Content::Image` being the
|
||||
icon side — so https-only, public-addresses-only (resolved and pinned), ≤3
|
||||
re-validated redirects, timeouts and a 1 MiB cap live in one place, and the
|
||||
domain (attacker-controlled text) cannot be turned into an SSRF. Disclosure, next
|
||||
to the picture-host note above: the identity's domain learns that this machine
|
||||
resolves that address, at most once a day.
|
||||
- **Identity avatars are fetched, cached and rendered** through the *same*
|
||||
hardened `IconStore` as app icons (https/inline `data:` only, pinned public
|
||||
addresses, ≤3 re-validated redirects, 1 MiB, magic-byte raster gate — see
|
||||
@@ -494,6 +535,42 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
a relay cannot link an identity to this signer.
|
||||
- `AppState::identity_label` is the single display rule: profile `display_name`
|
||||
first, else the user's key label.
|
||||
- **One key style, two cuts.** Every `npub`/hex/`bunker://` value is shown in the
|
||||
monospace font at the size the label already has, through our `.key-value`
|
||||
class (`plain::key` for labels we build, `plain::key_row` for a row whose
|
||||
*subtitle* is the key). Deliberately **not** libadwaita's `.monospace`: that one
|
||||
also switches to the code size and, on an `AdwActionRow`, takes the title with
|
||||
it — hence the two descendant selectors in `data/style.css` (one for
|
||||
`AdwActionRow`, one for `AdwExpanderRow`, whose header sits deeper), mirroring
|
||||
libadwaita's own `row.property.monospace`. Widths: the 31-character
|
||||
`shorten_npub` cut is 213 px in a row subtitle (228 monospace) and the full
|
||||
63-character npub is 513 (555) — too wide anywhere, so the cut stays. The
|
||||
switcher is the only other cut (19 characters, above); the activity view keeps
|
||||
its own 10/6 cut and stays out of this, because its subtitle mixes a name and a
|
||||
timestamp rather than showing a value.
|
||||
- **Names are never invented, and a discovered profile name wins.** The vault
|
||||
label is only ever what the user typed (an empty label — `UNNAMED`, "Identity
|
||||
key" — when they typed nothing): the create dialog has no `Identity 3` default
|
||||
and the import dialog has no `Imported 1`. Import carries a `Name` field that is
|
||||
**prefilled from the cached profile** as soon as the pasted string decodes to a
|
||||
key (`prefill_name`: `nsec`/hex; an `ncryptsec`'s key is unknown until it is
|
||||
decrypted). A bare 64-hex string is ambiguous and is read as a *secret*, the way
|
||||
the vault reads it — so pasting a public hex key prefills a name for a different
|
||||
key, and importing one actually *succeeds* as that other identity (the store
|
||||
cannot tell them apart either). The user's own words always win over the
|
||||
prefill. The label is **never overwritten** by a
|
||||
profile: `identity_label` prefers the profile at display time only, so a key
|
||||
imported before its profile was known simply gets its name when the fetch
|
||||
lands — `refresh_identities` fetches profiles for keys that need one right after
|
||||
any add/import/rename/remove.
|
||||
- **The identities list** shows the same name as everywhere else
|
||||
(`identity_label`) over **the key alone** — `shorten_npub`, monospace, with the
|
||||
full npub as the tooltip. It used to be `"Profile · npub"` on one line, where a
|
||||
long profile name ate the key's tail. A profile arriving goes through `notify`,
|
||||
which rebuilds the list (and re-sorts it by the new name); the `changes` pings —
|
||||
activity and registry traffic — only re-set each row's title, initials and
|
||||
picture in place (`refresh_live_rows`), because a reload there would close an
|
||||
open per-key menu for a reason the user cannot see.
|
||||
- Adding a key never switches the selection. A key refresh never clobbers a pick
|
||||
made while it was in flight (the live selection wins over the settings
|
||||
snapshot).
|
||||
@@ -659,6 +736,11 @@ UI lives in `data/resources/ui/*.blp` (Blueprint) and is compiled to `.ui` by
|
||||
parsed and persisted (`parse_client_uri`, `client_info`, `App.image`). M11 is
|
||||
the fetch → cache → decode → render, and it is mostly a **security** feature:
|
||||
the URL is attacker-controlled.
|
||||
- **`fetch_https(url, Content)` is the only HTTP fetch in the app** — the icon
|
||||
path (`Content::Image`, plus the raster magic-byte gate) and NIP-05 verification
|
||||
(`Content::Document`, JSON parsed by the caller) both go through it, so there is
|
||||
one place to audit for SSRF. `fetch` is the icon entry point and keeps the inline
|
||||
`data:` support.
|
||||
- `store::icons` (`IconStore`) owns the disk cache and the decoded textures. Files
|
||||
under `glib::user_cache_dir()/…/icons/`, keyed by the client pubkey (validated
|
||||
64-hex at the store boundary — `apps.json` is on disk and must never reach a
|
||||
@@ -976,6 +1058,16 @@ the UI is tested. `build-aux/deploy-dev.sh` runs on the build host,
|
||||
The audit has its own tests: a content canary never reaches the log,
|
||||
unapproved requests are not logged, names are bounded, and `record` trims an
|
||||
oversized file while keeping it 0600. All run on a plain `cargo test`.
|
||||
- The **NIP-05** logic is pure and covered offline: parse (every rejecting shape,
|
||||
including empty labels, ports, paths and schemes), the `.well-known` URL
|
||||
(percent-encoding), the document match (case-insensitive both ways, malformed
|
||||
and hostile JSON), the display rule (`nip05_ok == nip05`, cleared when the
|
||||
declared address changes, stale answers dropped), and that an unparseable
|
||||
address never reaches the network. Its network half is the ignored
|
||||
`nip05_of_a_real_domain_is_verified`: set `REGENT_TEST_NIP05=user@domain` and
|
||||
`REGENT_TEST_NIP05_KEY=<hex>` (written against `raucao@kosmos.org` and the key
|
||||
the About dialog links to) and run `cargo test -- --ignored`; it also asserts
|
||||
that somebody else's key does *not* verify for the same address.
|
||||
- The **vault** has its own fast tests (no Secret Service needed any more):
|
||||
add/list/unlock/lock, a wrong passphrase refused both for unlocking and for
|
||||
adding a key, rename/remove without a passphrase, `keys.json` is 0600 and holds
|
||||
|
||||
@@ -6,3 +6,31 @@
|
||||
.request-pending {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* A key is a value, not chrome: it reads better in the monospace font, and
|
||||
equal-length cuts then render at equal widths.
|
||||
|
||||
Deliberately not libadwaita's `.monospace`: that class also switches to the
|
||||
*code size* (`--monospace-font-size`), and on an `AdwActionRow` it applies to
|
||||
the whole row, so the field name ("Public key") would turn monospace too.
|
||||
These rules take the family and a value's normal weight, never the size.
|
||||
|
||||
`label.key-value` is for widgets we build ourselves; the two descendant
|
||||
selectors reach the subtitle of an `AdwActionRow` (`.key-value` on the row)
|
||||
and of an `AdwExpanderRow` (whose header sits one `box > list > row.header`
|
||||
deeper). Both mirror the selectors libadwaita itself uses for
|
||||
`row.property.monospace`.
|
||||
|
||||
`font-weight: normal` is for the one place a value sits inside a *button*: a
|
||||
switcher row's name is a button's text, so libadwaita bolds it (700) and that
|
||||
is wanted — the key or NIP-05 under it is a value and must not join in. */
|
||||
label.key-value {
|
||||
font-family: var(--monospace-font-family);
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.key-value > box.header > box.title > .subtitle,
|
||||
.key-value.expander > box > list > row.header > box.header > box.title > .subtitle {
|
||||
font-family: var(--monospace-font-family);
|
||||
font-weight: normal;
|
||||
}
|
||||
@@ -64,6 +64,7 @@ cargo_build = custom_target(binary_name,
|
||||
'src/store/icons.rs',
|
||||
'src/store/mod.rs',
|
||||
'src/store/keys.rs',
|
||||
'src/store/nip05.rs',
|
||||
'src/store/profiles.rs',
|
||||
'src/ui/about.rs',
|
||||
'src/ui/activity_view.rs',
|
||||
|
||||
+61
-7
@@ -3,7 +3,7 @@
|
||||
//! something changed.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
@@ -40,6 +40,9 @@ pub struct AppState {
|
||||
profiles: Profiles,
|
||||
/// Cached application icons and their decoded textures.
|
||||
icons: Rc<IconStore>,
|
||||
/// NIP-05 checks in flight (address + key), so a start that both loads the
|
||||
/// identities and finishes a profile fetch does not ask the same domain twice.
|
||||
nip05_in_flight: RefCell<HashSet<String>>,
|
||||
listeners: RefCell<Vec<Listener>>,
|
||||
change_listeners: RefCell<Vec<Listener>>,
|
||||
/// The responder pings this after it changes the registry or the log.
|
||||
@@ -63,6 +66,7 @@ impl AppState {
|
||||
names: Arc::new(Mutex::new(HashMap::new())),
|
||||
profiles: Profiles::new(),
|
||||
icons: Rc::new(IconStore::new()),
|
||||
nip05_in_flight: RefCell::new(HashSet::new()),
|
||||
listeners: RefCell::new(Vec::new()),
|
||||
change_listeners: RefCell::new(Vec::new()),
|
||||
changes,
|
||||
@@ -283,6 +287,56 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify the declared NIP-05 addresses of the stored identities.
|
||||
///
|
||||
/// Only a *verified* address is ever shown (the switcher's second line): a
|
||||
/// kind-0's `nip05` is self-declared, and that line is where an identity is
|
||||
/// identified. At most one check per address per day, and a failure simply
|
||||
/// leaves the address unshown.
|
||||
///
|
||||
/// A check in flight is claimed, like an icon fetch: `refresh_identities` and
|
||||
/// the profile fetch that follows it can both see a stale address in the same
|
||||
/// breath, and the once-a-day bound is meant to be literal.
|
||||
pub fn ensure_nip05(self: &Rc<Self>) {
|
||||
for key in self.store.list_user_keys() {
|
||||
let public_key = key.public_key;
|
||||
let Some(declared) = self.profiles.declared_nip05(&public_key) else {
|
||||
continue;
|
||||
};
|
||||
if !self.profiles.nip05_needs_check(&public_key) {
|
||||
continue;
|
||||
}
|
||||
let hex = public_key.to_hex();
|
||||
let claim = format!("{declared} {hex}");
|
||||
if !self.nip05_in_flight.borrow_mut().insert(claim.clone()) {
|
||||
continue;
|
||||
}
|
||||
let profiles = self.profiles.clone();
|
||||
let state = Rc::clone(self);
|
||||
let checked = declared.clone();
|
||||
runtime::spawn(
|
||||
async move { crate::store::nip05::verify(&checked, &hex).await },
|
||||
move |result| {
|
||||
let verified = match result {
|
||||
Ok(verified) => verified,
|
||||
Err(error) => {
|
||||
eprintln!("regent: could not check a NIP-05 address: {error}");
|
||||
false
|
||||
}
|
||||
};
|
||||
state.nip05_in_flight.borrow_mut().remove(&claim);
|
||||
profiles.set_nip05(
|
||||
&public_key,
|
||||
&declared,
|
||||
verified,
|
||||
crate::store::audit::now(),
|
||||
);
|
||||
state.notify_changes();
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every pubkey whose cached image must survive an icon gc: approved clients
|
||||
/// across all identities, plus every identity key in the vault.
|
||||
pub fn icon_live_keys(&self) -> Vec<String> {
|
||||
@@ -382,6 +436,7 @@ impl AppState {
|
||||
self.notify();
|
||||
self.notify_changes();
|
||||
self.ensure_avatars();
|
||||
self.ensure_nip05();
|
||||
self.fetch_profiles(
|
||||
keys.iter()
|
||||
.filter(|key| self.profiles.needs_refresh(&key.public_key))
|
||||
@@ -405,9 +460,11 @@ impl AppState {
|
||||
if let Err(error) = result {
|
||||
eprintln!("regent: could not fetch profiles: {error}");
|
||||
}
|
||||
// A profile that just arrived may carry a picture: hydrate what
|
||||
// is cached and fetch the rest. Safe to call on every fetch.
|
||||
// A profile that just arrived may carry a picture or a NIP-05
|
||||
// address: hydrate what is cached, fetch the rest, and check the
|
||||
// address the domain has to confirm. Safe on every fetch.
|
||||
state.ensure_avatars();
|
||||
state.ensure_nip05();
|
||||
state.notify();
|
||||
state.notify_changes();
|
||||
},
|
||||
@@ -501,10 +558,7 @@ mod tests {
|
||||
let keys = vec![a, b];
|
||||
// The user picked B while the refresh was in flight: it must win over
|
||||
// the stale setting snapshot.
|
||||
assert_eq!(
|
||||
resolve_selection(Some(b_pk), Some(a_pk), &keys),
|
||||
Some(b_pk)
|
||||
);
|
||||
assert_eq!(resolve_selection(Some(b_pk), Some(a_pk), &keys), Some(b_pk));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+59
-32
@@ -54,25 +54,46 @@ pub fn is_fetchable(url: &str) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetch the bytes for `url`.
|
||||
/// What a fetch expects to receive, checked before the body is read.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Content {
|
||||
/// An image: the response must declare `image/…` (the magic bytes below are
|
||||
/// still the real gate).
|
||||
Image,
|
||||
/// A document parsed by the caller (a `.well-known/nostr.json` for NIP-05).
|
||||
/// The parse is the gate, so a `Content-Type` is not required: some servers
|
||||
/// send `text/plain` for a JSON body.
|
||||
Document,
|
||||
}
|
||||
|
||||
/// Fetch the bytes for an image at `url`.
|
||||
///
|
||||
/// Runs on the async runtime. `data:image/…;base64,…` is decoded locally and
|
||||
/// never touches the network; an `https` URL is resolved, validated, pinned and
|
||||
/// fetched with a bounded body.
|
||||
/// never touches the network; an `https` URL goes through [`fetch_https`] and
|
||||
/// the raster magic-byte gate.
|
||||
pub async fn fetch(url: &str) -> Result<Vec<u8>> {
|
||||
if let Some(rest) = url.strip_prefix("data:") {
|
||||
return decode_data_url(rest);
|
||||
}
|
||||
let bytes = fetch_https(url, Content::Image).await?;
|
||||
sniff_raster(&bytes)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// Fetch bytes over `https`, hardened: public addresses only (resolved and then
|
||||
/// pinned into the per-fetch client), ≤3 redirects re-validated and re-pinned at
|
||||
/// every hop, a bounded body, no cookies/auth/proxy.
|
||||
///
|
||||
/// The **only** HTTP fetch path in the app: the icon fetcher and the NIP-05
|
||||
/// verifier (`store::nip05`) both go through here, so there is one place to
|
||||
/// audit for SSRF.
|
||||
pub async fn fetch_https(url: &str, expect: Content) -> Result<Vec<u8>> {
|
||||
let mut url = url::Url::parse(url).map_err(|error| format!("that is not a URL: {error}"))?;
|
||||
for _ in 0..=MAX_REDIRECTS {
|
||||
if url.scheme() != "https" {
|
||||
return Err(format!("refusing to fetch a {} URL", url.scheme()));
|
||||
}
|
||||
let host = url
|
||||
.host_str()
|
||||
.ok_or("the URL has no host")?
|
||||
.to_string();
|
||||
let host = url.host_str().ok_or("the URL has no host")?.to_string();
|
||||
let port = url.port_or_known_default().ok_or("the URL has no port")?;
|
||||
let addrs = resolve_public(&host, port).await?;
|
||||
|
||||
@@ -91,37 +112,36 @@ pub async fn fetch(url: &str) -> Result<Vec<u8>> {
|
||||
.get(url.clone())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| format!("could not fetch the icon: {error}"))?;
|
||||
.map_err(|error| format!("could not fetch the URL: {error}"))?;
|
||||
|
||||
if response.status().is_redirection() {
|
||||
let location = response
|
||||
.headers()
|
||||
.get(reqwest::header::LOCATION)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or("the icon redirect had no usable Location")?;
|
||||
.ok_or("the redirect had no usable Location")?;
|
||||
url = url
|
||||
.join(location)
|
||||
.map_err(|error| format!("the icon redirect was unusable: {error}"))?;
|
||||
.map_err(|error| format!("the redirect was unusable: {error}"))?;
|
||||
continue;
|
||||
}
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("the server answered {}", response.status()));
|
||||
}
|
||||
if let Some(content_type) = response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
if expect == Content::Image
|
||||
&& let Some(content_type) = response
|
||||
.headers()
|
||||
.get(reqwest::header::CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
{
|
||||
if !content_type.starts_with("image/") {
|
||||
return Err("the server did not send an image".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let bytes = read_capped(response).await?;
|
||||
sniff_raster(&bytes)?;
|
||||
return Ok(bytes);
|
||||
return read_capped(response).await;
|
||||
}
|
||||
Err("the icon redirected too many times".to_string())
|
||||
Err(format!("{url} redirected too many times"))
|
||||
}
|
||||
|
||||
/// Read at most [`MAX_BYTES`] from the response, aborting past it.
|
||||
@@ -130,10 +150,10 @@ async fn read_capped(mut response: reqwest::Response) -> Result<Vec<u8>> {
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.map_err(|error| format!("the icon download failed: {error}"))?
|
||||
.map_err(|error| format!("the download failed: {error}"))?
|
||||
{
|
||||
if out.len() + chunk.len() > MAX_BYTES {
|
||||
return Err("the icon is larger than 1 MiB".to_string());
|
||||
return Err("the body is larger than 1 MiB".to_string());
|
||||
}
|
||||
out.extend_from_slice(&chunk);
|
||||
}
|
||||
@@ -245,15 +265,13 @@ fn sniff_raster(bytes: &[u8]) -> Result<()> {
|
||||
if raster {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("the icon is not a PNG, JPEG, GIF or WebP image".to_string())
|
||||
Err("the body is not a PNG, JPEG, GIF or WebP image".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a `data:…` URL body (the part after `data:`).
|
||||
fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
|
||||
let (meta, payload) = rest
|
||||
.split_once(',')
|
||||
.ok_or("the data URL is malformed")?;
|
||||
let (meta, payload) = rest.split_once(',').ok_or("the data URL is malformed")?;
|
||||
if !meta.starts_with("image/") {
|
||||
return Err("the data URL is not an image".to_string());
|
||||
}
|
||||
@@ -265,7 +283,7 @@ fn decode_data_url(rest: &str) -> Result<Vec<u8>> {
|
||||
.decode(payload)
|
||||
.map_err(|_| "the data URL is not valid base64".to_string())?;
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return Err("the icon is larger than 1 MiB".to_string());
|
||||
return Err("the body is larger than 1 MiB".to_string());
|
||||
}
|
||||
sniff_raster(&bytes)?;
|
||||
Ok(bytes)
|
||||
@@ -413,9 +431,7 @@ impl IconStore {
|
||||
if !self.needs_fetch(&key, url) {
|
||||
return false;
|
||||
}
|
||||
self.in_flight
|
||||
.borrow_mut()
|
||||
.insert((key, url.to_string()))
|
||||
self.in_flight.borrow_mut().insert((key, url.to_string()))
|
||||
}
|
||||
|
||||
/// Claim a one-shot cache hydration for `(key, url)`. `false` when it was
|
||||
@@ -613,7 +629,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn data_urls_are_checked() {
|
||||
assert!(decode_data_url("image/png;base64,AAAA").is_err(), "AAAA is not raster");
|
||||
assert!(
|
||||
decode_data_url("image/png;base64,AAAA").is_err(),
|
||||
"AAAA is not raster"
|
||||
);
|
||||
assert!(decode_data_url("text/plain;base64,AAAA").is_err());
|
||||
assert!(decode_data_url("image/png,notbase64").is_err());
|
||||
assert!(decode_data_url("image/png;base64").is_err(), "no comma");
|
||||
@@ -650,14 +669,19 @@ mod tests {
|
||||
assert!(!store.needs_fetch(&key, url));
|
||||
assert_eq!(store.cached_bytes(&key, url).as_deref(), Some(&bytes[..]));
|
||||
assert!(
|
||||
store.cached_bytes(&key, "https://example.com/other.png").is_none(),
|
||||
store
|
||||
.cached_bytes(&key, "https://example.com/other.png")
|
||||
.is_none(),
|
||||
"a different URL must not serve these bytes"
|
||||
);
|
||||
|
||||
// A fresh store reads the sidecar from disk.
|
||||
let reloaded = IconStore::at(dir.clone());
|
||||
assert!(!reloaded.needs_fetch(&key, url));
|
||||
assert_eq!(reloaded.cached_bytes(&key, url).as_deref(), Some(&bytes[..]));
|
||||
assert_eq!(
|
||||
reloaded.cached_bytes(&key, url).as_deref(),
|
||||
Some(&bytes[..])
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -713,7 +737,10 @@ mod tests {
|
||||
!dir.join(format!("{dead}.url")).exists(),
|
||||
"the dead sidecar is gone"
|
||||
);
|
||||
assert!(store.needs_fetch(&dead, url), "the evicted key must refetch");
|
||||
assert!(
|
||||
store.needs_fetch(&dead, url),
|
||||
"the evicted key must refetch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -5,4 +5,5 @@ pub mod apps;
|
||||
pub mod audit;
|
||||
pub mod icons;
|
||||
pub mod keys;
|
||||
pub mod nip05;
|
||||
pub mod profiles;
|
||||
@@ -0,0 +1,246 @@
|
||||
//! NIP-05 addresses: parse, build the `.well-known` URL, and check it.
|
||||
//!
|
||||
//! A kind-0 may *declare* any `name@domain`; that is attacker-publishable text
|
||||
//! like the name itself, and the switcher's second line is exactly where an
|
||||
//! identity is identified. So an address is only ever shown after the domain's
|
||||
//! `/.well-known/nostr.json` maps that name back to the key we hold.
|
||||
//!
|
||||
//! The fetch goes through [`crate::store::icons::fetch_https`], the app's single
|
||||
//! hardened HTTP path (https only, public addresses only, pinned, bounded body),
|
||||
//! because the domain comes from that self-declared string.
|
||||
|
||||
use crate::store::icons;
|
||||
|
||||
/// A parsed NIP-05 address, `local@domain`, both lowercased.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Address {
|
||||
pub local: String,
|
||||
pub domain: String,
|
||||
}
|
||||
|
||||
/// The longest address we will even look at. It reaches a URL and `profiles.json`.
|
||||
pub const MAX_LEN: usize = 128;
|
||||
|
||||
/// Parse `local@domain`, strictly.
|
||||
///
|
||||
/// One `@`, a non-empty local part of NIP-05's alphabet, and a domain that is a
|
||||
/// plain hostname: no scheme, path, query, port or whitespace. The domain becomes
|
||||
/// an outbound HTTPS request, so a sloppy parse is an SSRF vector.
|
||||
pub fn parse(value: &str) -> Option<Address> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.chars().count() > MAX_LEN {
|
||||
return None;
|
||||
}
|
||||
let (local, domain) = value.split_once('@')?;
|
||||
if local.is_empty() || domain.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if !local
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let labels: Vec<&str> = domain.split('.').collect();
|
||||
if !domain
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if labels.len() < 2
|
||||
|| labels
|
||||
.iter()
|
||||
.any(|label| label.is_empty() || label.starts_with('-') || label.ends_with('-'))
|
||||
|| labels.iter().any(|label| label.len() > 63)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(Address {
|
||||
local: local.to_ascii_lowercase(),
|
||||
domain: domain.to_ascii_lowercase(),
|
||||
})
|
||||
}
|
||||
|
||||
/// The address as the cache stores it, so two spellings of the same address
|
||||
/// compare equal.
|
||||
pub fn normalise(value: &str) -> Option<String> {
|
||||
parse(value).map(|address| format!("{}@{}", address.local, address.domain))
|
||||
}
|
||||
|
||||
/// The `.well-known` URL to ask, with the local part percent-encoded.
|
||||
pub fn url(address: &Address) -> String {
|
||||
let local: String = url::form_urlencoded::byte_serialize(address.local.as_bytes()).collect();
|
||||
format!(
|
||||
"https://{}/.well-known/nostr.json?name={local}",
|
||||
address.domain
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether `body` (a `nostr.json`) points `address` at `hex`.
|
||||
///
|
||||
/// Anything unexpected — malformed JSON, no `names` object, the name missing, a
|
||||
/// name whose value is not a string — is `false`. The name is matched
|
||||
/// case-insensitively, as NIP-05 asks, and the hex comparison ignores case.
|
||||
pub fn matches(body: &str, address: &Address, hex: &str) -> bool {
|
||||
let Ok(document) = serde_json::from_str::<serde_json::Value>(body) else {
|
||||
return false;
|
||||
};
|
||||
let Some(names) = document.get("names").and_then(|names| names.as_object()) else {
|
||||
return false;
|
||||
};
|
||||
let found = names
|
||||
.get(&address.local)
|
||||
.or_else(|| {
|
||||
names
|
||||
.iter()
|
||||
.find(|(name, _)| name.eq_ignore_ascii_case(&address.local))
|
||||
.map(|(_, value)| value)
|
||||
})
|
||||
.and_then(|value| value.as_str());
|
||||
match found {
|
||||
Some(hex_in_document) => hex_in_document.eq_ignore_ascii_case(hex),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Verify `nip05` for the key `hex`.
|
||||
///
|
||||
/// Best effort: an unparseable address is `false` without touching the network,
|
||||
/// and a fetch that fails is an error the caller logs and drops (the address
|
||||
/// simply stays unshown).
|
||||
pub async fn verify(nip05: &str, hex: &str) -> Result<bool, String> {
|
||||
let Some(address) = parse(nip05) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let body = icons::fetch_https(&url(&address), icons::Content::Document).await?;
|
||||
let body = String::from_utf8(body).map_err(|_| "the answer was not UTF-8".to_string())?;
|
||||
Ok(matches(&body, &address, hex))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HEX: &str = "1f79058c77a224e5be226c8f024cacdad4d741855d75ed9f11473ba8eb86e1cb";
|
||||
|
||||
#[test]
|
||||
fn an_address_is_parsed_leniently_but_strictly_enough_to_be_a_url() {
|
||||
let address = parse(" RauCao@Kosmos.org ").unwrap();
|
||||
assert_eq!(address.local, "raucao");
|
||||
assert_eq!(address.domain, "kosmos.org");
|
||||
assert_eq!(
|
||||
normalise("RauCao@Kosmos.org").as_deref(),
|
||||
Some("raucao@kosmos.org")
|
||||
);
|
||||
|
||||
for rejected in [
|
||||
"",
|
||||
" ",
|
||||
"raucao",
|
||||
"raucao@",
|
||||
"@kosmos.org",
|
||||
"a@b@c.org",
|
||||
"raucao@kosmos",
|
||||
"raucao@https://kosmos.org",
|
||||
"raucao@kosmos.org/path",
|
||||
"raucao@kosmos.org:443",
|
||||
"raucao@kosmos.org?x=1",
|
||||
"raucao@kosmos.org #x",
|
||||
"rau cao@kosmos.org",
|
||||
"raucao@kos mos.org",
|
||||
"raucao@-kosmos.org",
|
||||
"raucao@kosmos.org-",
|
||||
"raucao@.kosmos.org",
|
||||
"raucao@kosmos..org",
|
||||
"raucao@kosmos.org.",
|
||||
"raucao@sub.-kosmos.org",
|
||||
"raucao@kösmi.org",
|
||||
"ra*cao@kosmos.org",
|
||||
] {
|
||||
assert!(parse(rejected).is_none(), "{rejected:?} must not parse");
|
||||
}
|
||||
|
||||
let long = format!("{}@kosmos.org", "a".repeat(MAX_LEN));
|
||||
assert!(parse(&long).is_none(), "an unbounded address is refused");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_well_known_url_encodes_the_local_part() {
|
||||
let plain = url(&parse("raucao@kosmos.org").unwrap());
|
||||
assert_eq!(
|
||||
plain,
|
||||
"https://kosmos.org/.well-known/nostr.json?name=raucao"
|
||||
);
|
||||
|
||||
// Characters a user could type are encoded rather than injected.
|
||||
let odd = Address {
|
||||
local: "a b+c".to_string(),
|
||||
domain: "kosmos.org".to_string(),
|
||||
};
|
||||
assert_eq!(
|
||||
url(&odd),
|
||||
"https://kosmos.org/.well-known/nostr.json?name=a+b%2Bc"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_declared_key_verifies() {
|
||||
let address = parse("raucao@kosmos.org").unwrap();
|
||||
let body = format!(r#"{{"names":{{"raucao":"{HEX}"}},"relays":{{}}}}"#);
|
||||
assert!(matches(&body, &address, HEX));
|
||||
assert!(matches(&body, &address, &HEX.to_uppercase()));
|
||||
|
||||
// The name may be spelled in any case in the document.
|
||||
let upper = format!(r#"{{"names":{{"RauCao":"{HEX}"}}}}"#);
|
||||
assert!(matches(&upper, &address, HEX));
|
||||
|
||||
// A different key, a different name, and every malformed shape.
|
||||
assert!(!matches(&body, &address, &"0".repeat(64)));
|
||||
assert!(!matches(&body, &parse("someone@kosmos.org").unwrap(), HEX));
|
||||
assert!(!matches("not json", &address, HEX));
|
||||
assert!(!matches("{}", &address, HEX));
|
||||
assert!(!matches(r#"{"names":[]}"#, &address, HEX));
|
||||
assert!(!matches(r#"{"names":{"raucao":42}}"#, &address, HEX));
|
||||
assert!(!matches(r#"{"names":{"raucao":null}}"#, &address, HEX));
|
||||
assert!(!matches("", &address, HEX));
|
||||
}
|
||||
|
||||
/// The network half, which no offline test can cover: a real domain's
|
||||
/// `/.well-known/nostr.json` has to confirm a real address for a real key.
|
||||
///
|
||||
/// `REGENT_TEST_NIP05=user@domain REGENT_TEST_NIP05_KEY=<hex>` plus
|
||||
/// `--ignored` runs it; it was written against `raucao@kosmos.org` and the key
|
||||
/// in `ui::about` (the same one the About dialog links to).
|
||||
#[tokio::test]
|
||||
#[ignore = "needs REGENT_TEST_NIP05 / REGENT_TEST_NIP05_KEY and the network"]
|
||||
async fn nip05_of_a_real_domain_is_verified() {
|
||||
let Ok(nip05) = std::env::var("REGENT_TEST_NIP05") else {
|
||||
eprintln!("set REGENT_TEST_NIP05 and REGENT_TEST_NIP05_KEY to run this");
|
||||
return;
|
||||
};
|
||||
let key = std::env::var("REGENT_TEST_NIP05_KEY").expect("REGENT_TEST_NIP05_KEY");
|
||||
let address = parse(&nip05).expect("a parseable address");
|
||||
|
||||
let body = icons::fetch_https(&url(&address), icons::Content::Document)
|
||||
.await
|
||||
.expect("the hardened fetch has to reach the domain");
|
||||
let body = String::from_utf8(body).expect("utf-8");
|
||||
assert!(
|
||||
matches(&body, &address, &key),
|
||||
"{nip05} must point at {key}"
|
||||
);
|
||||
assert!(verify(&nip05, &key).await.unwrap_or(false));
|
||||
|
||||
// Somebody else's key must not verify against the same address — that is
|
||||
// the impersonation this whole module exists to prevent.
|
||||
assert!(!verify(&nip05, &"0".repeat(64)).await.unwrap_or(false));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_unparseable_address_never_reaches_the_network() {
|
||||
for bad in ["", "raucao", "raucao@", "raucao@/etc/passwd"] {
|
||||
assert_eq!(verify(bad, HEX).await, Ok(false), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+155
-7
@@ -28,8 +28,8 @@ use nostr::prelude::*;
|
||||
use nostr_sdk::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::store::audit;
|
||||
use crate::APP_ID;
|
||||
use crate::store::audit;
|
||||
|
||||
/// A cached profile is refreshed after a day.
|
||||
const REFRESH_AFTER: i64 = 24 * 60 * 60;
|
||||
@@ -107,6 +107,21 @@ pub struct Profile {
|
||||
/// `created_at` of the cached kind-0. Its watermark.
|
||||
#[serde(default)]
|
||||
pub kind0_at: i64,
|
||||
/// The kind-0's declared NIP-05 address, normalised (`local@domain`), only
|
||||
/// when it parsed. Self-declared, so it is *never shown* unless
|
||||
/// [`Profile::nip05_ok`] says the domain confirmed it for this key.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub nip05: Option<String>,
|
||||
/// The address the domain's `/.well-known/nostr.json` confirmed for this key.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub nip05_ok: Option<String>,
|
||||
/// The address the last attempt was *for*, successful or not: a domain that
|
||||
/// never confirms must not be re-asked on every app start.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub nip05_checked_for: Option<String>,
|
||||
/// When that attempt happened, so an unchanged address is re-checked daily.
|
||||
#[serde(default)]
|
||||
pub nip05_checked_at: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -152,6 +167,56 @@ impl Profiles {
|
||||
bound_picture(Some(&picture))
|
||||
}
|
||||
|
||||
/// The identity's **verified** NIP-05 address, if it has one.
|
||||
///
|
||||
/// "Verified" means the currently declared address is the one a domain
|
||||
/// confirmed for this key. A re-declared (or changed) address is unverified
|
||||
/// again until it is checked, so a forged one can never be shown.
|
||||
pub fn nip05(&self, key: &PublicKey) -> Option<String> {
|
||||
let profile = self.get(key)?;
|
||||
let declared = profile.nip05?;
|
||||
(profile.nip05_ok.as_deref() == Some(declared.as_str())).then_some(declared)
|
||||
}
|
||||
|
||||
/// The declared address, verified or not — what the checker works from.
|
||||
pub fn declared_nip05(&self, key: &PublicKey) -> Option<String> {
|
||||
self.get(key)?.nip05
|
||||
}
|
||||
|
||||
/// Whether the declared address still needs a check.
|
||||
///
|
||||
/// True when it has never been attempted, when the declaration changed since
|
||||
/// the last attempt, or when that attempt is older than a day. A *failed*
|
||||
/// attempt therefore buys a day of quiet too — keyed on what was attempted
|
||||
/// (`nip05_checked_for`), not on whether it succeeded, so a domain that never
|
||||
/// confirms is not asked again on every start.
|
||||
pub fn nip05_needs_check(&self, key: &PublicKey) -> bool {
|
||||
let Some(profile) = self.get(key) else {
|
||||
return false;
|
||||
};
|
||||
let Some(declared) = profile.nip05 else {
|
||||
return false;
|
||||
};
|
||||
profile.nip05_checked_for.as_deref() != Some(declared.as_str())
|
||||
|| audit::now() - profile.nip05_checked_at > REFRESH_AFTER
|
||||
}
|
||||
|
||||
/// Record what a check found. A result for an address that has since changed
|
||||
/// is dropped, so a slow answer cannot vouch for a newer declaration.
|
||||
pub fn set_nip05(&self, key: &PublicKey, checked: &str, verified: bool, now: i64) {
|
||||
{
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
let entry = entries.entry(key.to_hex()).or_default();
|
||||
if entry.nip05.as_deref() != Some(checked) {
|
||||
return;
|
||||
}
|
||||
entry.nip05_ok = verified.then(|| checked.to_string());
|
||||
entry.nip05_checked_for = Some(checked.to_string());
|
||||
entry.nip05_checked_at = now;
|
||||
}
|
||||
self.save();
|
||||
}
|
||||
|
||||
/// Whether this key has no profile or an old one.
|
||||
pub fn needs_refresh(&self, key: &PublicKey) -> bool {
|
||||
match self.get(key) {
|
||||
@@ -171,6 +236,7 @@ impl Profiles {
|
||||
key: &PublicKey,
|
||||
display_name: Option<String>,
|
||||
picture: Option<String>,
|
||||
nip05: Option<String>,
|
||||
created_at: i64,
|
||||
) -> bool {
|
||||
let mut stored = false;
|
||||
@@ -180,6 +246,7 @@ impl Profiles {
|
||||
if created_at > entry.kind0_at {
|
||||
entry.display_name = bound_name(display_name);
|
||||
entry.picture = bound_picture(picture.as_deref());
|
||||
entry.nip05 = nip05;
|
||||
entry.kind0_at = created_at;
|
||||
entry.fetched_at = audit::now();
|
||||
stored = true;
|
||||
@@ -523,6 +590,7 @@ fn store_metadata(
|
||||
key,
|
||||
profile.display_name.clone(),
|
||||
profile.picture.clone(),
|
||||
profile.nip05.clone(),
|
||||
at.as_secs() as i64,
|
||||
),
|
||||
None => false,
|
||||
@@ -666,6 +734,12 @@ fn profile_from_metadata(metadata: &Metadata) -> Profile {
|
||||
// Kept even when it is not fetchable: the cache stores what the identity
|
||||
// published, and `ensure_avatars` decides whether to request it.
|
||||
picture: bound_picture(metadata.picture.as_deref()),
|
||||
// Only a well-formed address is kept: an unparseable one could never be
|
||||
// verified, so it could never be shown either.
|
||||
nip05: metadata
|
||||
.nip05
|
||||
.as_deref()
|
||||
.and_then(crate::store::nip05::normalise),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -727,6 +801,7 @@ mod tests {
|
||||
&key,
|
||||
Some(" Alice ".to_string()),
|
||||
Some(" https://example.com/a.png ".to_string()),
|
||||
crate::store::nip05::normalise("Alice@Example.org"),
|
||||
Timestamp::now().as_secs() as i64,
|
||||
));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Alice"));
|
||||
@@ -743,6 +818,7 @@ mod tests {
|
||||
123,
|
||||
);
|
||||
store.note_recovery(&key, 456);
|
||||
store.set_nip05(&key, "alice@example.org", true, 789);
|
||||
|
||||
// Survives a reload, every field and all three clocks.
|
||||
let reloaded = Profiles::at(path);
|
||||
@@ -755,6 +831,8 @@ mod tests {
|
||||
assert_eq!(profile.write_relays, ["wss://outbox.example"]);
|
||||
assert_eq!(profile.relays_checked_at, 123);
|
||||
assert_eq!(profile.relays_recovery_at, 456);
|
||||
assert_eq!(profile.nip05.as_deref(), Some("alice@example.org"));
|
||||
assert_eq!(reloaded.nip05(&key).as_deref(), Some("alice@example.org"));
|
||||
assert!(profile.kind0_at > 0 && profile.fetched_at > 0);
|
||||
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
@@ -792,7 +870,7 @@ mod tests {
|
||||
fn a_blank_display_name_is_ignored() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
store.put_metadata(&key, Some(" ".to_string()), None, 10);
|
||||
store.put_metadata(&key, Some(" ".to_string()), None, None, 10);
|
||||
assert!(store.display_name(&key).is_none());
|
||||
}
|
||||
|
||||
@@ -816,7 +894,7 @@ mod tests {
|
||||
// A hand-edited cache cannot smuggle an unbounded fetch input through.
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
store.put_metadata(&key, None, Some(format!(" {long} ")), 10);
|
||||
store.put_metadata(&key, None, Some(format!(" {long} ")), None, 10);
|
||||
assert_eq!(
|
||||
store.picture(&key).unwrap().chars().count(),
|
||||
MAX_PICTURE_LEN
|
||||
@@ -1027,18 +1105,18 @@ mod tests {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
|
||||
assert!(store.put_metadata(&key, Some("Alice".to_string()), None, 200));
|
||||
assert!(store.put_metadata(&key, Some("Alice".to_string()), None, None, 200));
|
||||
let fetched_at = stored(&store, &key).fetched_at;
|
||||
assert!(fetched_at > 0);
|
||||
|
||||
// Not newer: refused, and nothing moves.
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, 200));
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, 100));
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, None, 200));
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, None, 100));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Alice"));
|
||||
assert_eq!(stored(&store, &key).fetched_at, fetched_at);
|
||||
|
||||
// A genuine update replaces both fields — including clearing them.
|
||||
assert!(store.put_metadata(&key, None, Some("https://x/i.png".to_string()), 300));
|
||||
assert!(store.put_metadata(&key, None, Some("https://x/i.png".to_string()), None, 300));
|
||||
assert!(store.display_name(&key).is_none());
|
||||
assert_eq!(store.picture(&key).as_deref(), Some("https://x/i.png"));
|
||||
|
||||
@@ -1079,6 +1157,76 @@ mod tests {
|
||||
assert_eq!(stored(&store, &key).relays_recovery_at, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nip05_address_is_shown_only_while_it_is_verified() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
|
||||
// Declared, not yet checked: never shown.
|
||||
assert!(store.put_metadata(
|
||||
&key,
|
||||
Some("Alice".to_string()),
|
||||
None,
|
||||
crate::store::nip05::normalise("Alice@Example.org"),
|
||||
100
|
||||
));
|
||||
assert_eq!(
|
||||
store.declared_nip05(&key).as_deref(),
|
||||
Some("alice@example.org")
|
||||
);
|
||||
assert!(store.nip05(&key).is_none(), "a declaration is not proof");
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// The domain confirmed it, just now.
|
||||
let now = audit::now();
|
||||
store.set_nip05(&key, "alice@example.org", true, now);
|
||||
assert_eq!(store.nip05(&key).as_deref(), Some("alice@example.org"));
|
||||
assert!(!store.nip05_needs_check(&key));
|
||||
|
||||
// A day later it is checked again.
|
||||
store.set_nip05(&key, "alice@example.org", true, now - REFRESH_AFTER - 60);
|
||||
assert_eq!(store.nip05(&key).as_deref(), Some("alice@example.org"));
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// A result for an address that has since changed is dropped.
|
||||
store.put_metadata(
|
||||
&key,
|
||||
Some("Alice".to_string()),
|
||||
None,
|
||||
crate::store::nip05::normalise("mallory@example.org"),
|
||||
300,
|
||||
);
|
||||
store.set_nip05(&key, "alice@example.org", true, 400);
|
||||
assert!(
|
||||
store.nip05(&key).is_none(),
|
||||
"the old answer vouches for nothing"
|
||||
);
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// A failed check keeps it unshown — and buys a day of quiet, so a domain
|
||||
// that never confirms is not re-asked on every start.
|
||||
let now = audit::now();
|
||||
store.set_nip05(&key, "mallory@example.org", false, now);
|
||||
assert!(store.nip05(&key).is_none());
|
||||
assert_eq!(stored(&store, &key).nip05_checked_at, now);
|
||||
assert!(!store.nip05_needs_check(&key));
|
||||
|
||||
// …but a later attempt is due again a day on.
|
||||
store.set_nip05(&key, "mallory@example.org", false, now - REFRESH_AFTER - 60);
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// An unparseable declaration never reaches the cache.
|
||||
store.put_metadata(
|
||||
&key,
|
||||
None,
|
||||
None,
|
||||
crate::store::nip05::normalise("not an address"),
|
||||
600,
|
||||
);
|
||||
assert!(store.declared_nip05(&key).is_none());
|
||||
assert!(!store.nip05_needs_check(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_notes_set_only_their_own_clock() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
|
||||
+9
-5
@@ -593,6 +593,7 @@ fn more_details(question: &Question) -> gtk::ListBox {
|
||||
let row = plain::expander("Details", "Key and request metadata");
|
||||
let client_npub = client.public_key.to_bech32().unwrap_or_default();
|
||||
let client_key = plain::row("Client key", &plain::shorten_npub(&client_npub));
|
||||
plain::key_row(&client_key);
|
||||
client_key.set_subtitle_lines(1);
|
||||
client_key.set_tooltip_text(Some(&client_npub));
|
||||
row.add_row(&client_key);
|
||||
@@ -609,6 +610,7 @@ fn more_details(question: &Question) -> gtk::ListBox {
|
||||
Request::Encrypt { method, peer, .. } | Request::Decrypt { method, peer, .. } => {
|
||||
row.add_row(&plain::row("Method", method));
|
||||
let peer_row = plain::row("Peer", &plain::shorten_npub(peer));
|
||||
plain::key_row(&peer_row);
|
||||
peer_row.set_subtitle_lines(1);
|
||||
peer_row.set_tooltip_text(Some(peer));
|
||||
row.add_row(&peer_row);
|
||||
@@ -662,7 +664,7 @@ fn identity_field(state: &Rc<AppState>, identity: &crate::signer::approval::Sign
|
||||
// for a key that somehow does not.
|
||||
let value = match name {
|
||||
Some(name) => plain::label(name),
|
||||
None => plain::label(&plain::shorten_npub(&npub)),
|
||||
None => plain::key(&plain::shorten_npub(&npub)),
|
||||
};
|
||||
value.set_hexpand(true);
|
||||
value.set_tooltip_text(Some(&npub));
|
||||
@@ -704,10 +706,12 @@ fn application_field(state: &Rc<AppState>, client: &ClientInfo) -> gtk::Box {
|
||||
}
|
||||
}
|
||||
|
||||
let label_text = name
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| plain::shorten_npub(&npub));
|
||||
let label = plain::label(&label_text);
|
||||
let label = match name {
|
||||
Some(name) => plain::label(name),
|
||||
// An application that declared no name is identified by its key: same
|
||||
// treatment (and same width) as every other key in the app.
|
||||
None => plain::key(&plain::shorten_npub(&npub)),
|
||||
};
|
||||
label.set_hexpand(true);
|
||||
row.append(&avatar);
|
||||
row.append(&label);
|
||||
|
||||
+17
-19
@@ -267,9 +267,7 @@ impl Ui {
|
||||
// initials of a placeholder. The user's own label wins over what the
|
||||
// client declared.
|
||||
let name = app.display_name().map(str::to_string);
|
||||
let title = name
|
||||
.clone()
|
||||
.unwrap_or_else(|| plain::shorten_npub(&npub));
|
||||
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
|
||||
@@ -281,6 +279,10 @@ impl Ui {
|
||||
};
|
||||
let row = plain::expander(&title, &byline);
|
||||
row.set_subtitle_lines(1);
|
||||
if url.is_none() {
|
||||
// When the byline is the key (no declared URL), it is a value.
|
||||
plain::key_row(&row);
|
||||
}
|
||||
// The icon is decoration: the name above stays the identifier.
|
||||
let avatar = plain::avatar(
|
||||
32,
|
||||
@@ -293,6 +295,7 @@ impl Ui {
|
||||
row.set_tooltip_text(Some(&npub));
|
||||
}
|
||||
let public_key = plain::row("Public key", &plain::shorten_npub(&npub));
|
||||
plain::key_row(&public_key);
|
||||
public_key.set_subtitle_lines(1);
|
||||
public_key.set_tooltip_text(Some(&npub));
|
||||
row.add_row(&public_key);
|
||||
@@ -330,6 +333,7 @@ impl Ui {
|
||||
),
|
||||
};
|
||||
let signing_as_row = plain::row(&signing_as, &plain::shorten_npub(&signing_npub));
|
||||
plain::key_row(&signing_as_row);
|
||||
signing_as_row.set_subtitle_lines(1);
|
||||
signing_as_row.set_tooltip_text(Some(&signing_npub));
|
||||
row.add_row(&signing_as_row);
|
||||
@@ -341,24 +345,12 @@ impl Ui {
|
||||
));
|
||||
} 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,
|
||||
));
|
||||
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,
|
||||
));
|
||||
row.add_row(&self.permission_row(app, Permission::Method(method.clone()), &title));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -445,7 +437,13 @@ impl Ui {
|
||||
return;
|
||||
};
|
||||
let name = entry.text().to_string();
|
||||
if let Err(error) = ui.state.registry().lock().unwrap().rename(&key, Some(&name)) {
|
||||
if let Err(error) = ui
|
||||
.state
|
||||
.registry()
|
||||
.lock()
|
||||
.unwrap()
|
||||
.rename(&key, Some(&name))
|
||||
{
|
||||
eprintln!("regent: could not rename an application: {error}");
|
||||
}
|
||||
ui.state.notify_changes();
|
||||
|
||||
+19
-10
@@ -24,7 +24,7 @@ use nostr::prelude::PublicKey;
|
||||
use crate::runner::{SignerRunner, Status};
|
||||
use crate::runtime;
|
||||
use crate::signer::approval::{Decision, Question, Request, SigningKey};
|
||||
use crate::signer::{ClientPairing, Signer, pair_client, parse_client_uri};
|
||||
use crate::signer::{pair_client, parse_client_uri, ClientPairing, Signer};
|
||||
use crate::state::AppState;
|
||||
use crate::ui::{approval, plain, qr};
|
||||
use crate::window::Windows;
|
||||
@@ -61,7 +61,9 @@ impl ConnectDialog {
|
||||
.title("The app shows a code")
|
||||
.build();
|
||||
let signing_as = plain::row("Signing as", "");
|
||||
// The npub beneath is a long token: one line, ellipsized in the middle.
|
||||
// The npub beneath is a long token: one line, cut to `head…tail` and in
|
||||
// the monospace font.
|
||||
plain::key_row(&signing_as);
|
||||
signing_as.set_subtitle_lines(1);
|
||||
// Filled in by `refresh`, from the selected identity.
|
||||
let signing_avatar = plain::avatar(32, None, None);
|
||||
@@ -81,6 +83,9 @@ impl ConnectDialog {
|
||||
|
||||
// --- The signer-initiated direction: hidden until asked for. ---
|
||||
let uri = plain::row("Connection string", "—");
|
||||
// A `bunker://` string is a value like a key: monospace, and its own
|
||||
// `head…tail` cut.
|
||||
plain::key_row(&uri);
|
||||
// The connection string is long and stays on one line, cut to
|
||||
// `head…tail`: the head and the secret tail are what identify it. (Not
|
||||
// Pango's middle ellipsis — see `plain::shorten_uri`.) The full string
|
||||
@@ -251,7 +256,9 @@ impl ConnectDialog {
|
||||
// the snapshot the moment it closes.
|
||||
{
|
||||
let listener = Rc::clone(&connect);
|
||||
connect.dialog.connect_closed(move |_| listener.shown.set(None));
|
||||
connect
|
||||
.dialog
|
||||
.connect_closed(move |_| listener.shown.set(None));
|
||||
}
|
||||
|
||||
connect.refresh();
|
||||
@@ -325,7 +332,8 @@ impl ConnectDialog {
|
||||
.set_subtitle("The connection string embeds the pairing secret.");
|
||||
// Display only: the copy button and the QR code still use the
|
||||
// full string. The row shows the head and the secret tail.
|
||||
self.uri.set_subtitle(&plain::shorten_uri(signer.bunker_uri()));
|
||||
self.uri
|
||||
.set_subtitle(&plain::shorten_uri(signer.bunker_uri()));
|
||||
if self.reveal.is_expanded() {
|
||||
self.show_qr(signer.bunker_uri());
|
||||
}
|
||||
@@ -358,7 +366,9 @@ impl ConnectDialog {
|
||||
let pairing = match parse_client_uri(uri) {
|
||||
Ok(pairing) => pairing,
|
||||
Err(error) => {
|
||||
self.report_error(&format!("That is not a usable nostrconnect:// string: {error}"));
|
||||
self.report_error(&format!(
|
||||
"That is not a usable nostrconnect:// string: {error}"
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -402,8 +412,7 @@ impl ConnectDialog {
|
||||
// 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.
|
||||
let answer =
|
||||
approval::present_question(&parent, &question, None, &connect.state).await;
|
||||
let answer = approval::present_question(&parent, &question, None, &connect.state).await;
|
||||
if answer.decision == Decision::Deny {
|
||||
return;
|
||||
}
|
||||
@@ -412,9 +421,9 @@ impl ConnectDialog {
|
||||
|
||||
match connect.runner.status() {
|
||||
Status::Running(signer) => connect.pair_now(&signer, pairing, identity, name),
|
||||
Status::Starting => connect.report_error(
|
||||
"The signer is still starting. Try again in a moment.",
|
||||
),
|
||||
Status::Starting => {
|
||||
connect.report_error("The signer is still starting. Try again in a moment.")
|
||||
}
|
||||
Status::Stopped => {
|
||||
let extra = pairing
|
||||
.relays
|
||||
|
||||
+154
-75
@@ -15,7 +15,7 @@ use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
use nostr::prelude::{Keys, PublicKey};
|
||||
|
||||
use adw::prelude::*;
|
||||
use gtk::prelude::*;
|
||||
@@ -36,10 +36,16 @@ struct Handles {
|
||||
|
||||
/// The rows currently in the list, so a reload can remove exactly them.
|
||||
type Rows = Rc<RefCell<Vec<adw::ActionRow>>>;
|
||||
/// Each row's avatar and the key it belongs to, so a picture that lands later
|
||||
/// can be swapped in without rebuilding the list (a rebuild would close a row's
|
||||
/// open menu).
|
||||
type Avatars = Rc<RefCell<Vec<(String, adw::Avatar)>>>;
|
||||
/// The parts of a row that change when a profile lands — its picture and its
|
||||
/// name — kept as handles so a change ping can update them in place. A rebuild
|
||||
/// would close a row's open menu for a reason the user cannot see.
|
||||
struct LiveRow {
|
||||
hex: String,
|
||||
avatar: adw::Avatar,
|
||||
row: adw::ActionRow,
|
||||
}
|
||||
|
||||
type LiveRows = Rc<RefCell<Vec<LiveRow>>>;
|
||||
|
||||
/// The toplevel, resolved lazily: a view is not in a window when it is built.
|
||||
fn toplevel(handles: &Handles) -> Option<gtk::Window> {
|
||||
@@ -118,7 +124,7 @@ impl KeysView {
|
||||
overlay: overlay.clone(),
|
||||
};
|
||||
let rows: Rows = Rc::new(RefCell::new(Vec::new()));
|
||||
let avatars: Avatars = Rc::new(RefCell::new(Vec::new()));
|
||||
let live: LiveRows = Rc::new(RefCell::new(Vec::new()));
|
||||
let widget: gtk::Widget = overlay.upcast();
|
||||
|
||||
for button in [&create_button, &create] {
|
||||
@@ -135,17 +141,17 @@ impl KeysView {
|
||||
// nothing this window needs to hear about — but an avatar that lands
|
||||
// later does: `listen_changes` is what an icon/avatar fetch announces.
|
||||
{
|
||||
let (listener_state, handles, rows, avatars) = (
|
||||
let (listener_state, handles, rows, live) = (
|
||||
Rc::clone(&state),
|
||||
handles.clone(),
|
||||
Rc::clone(&rows),
|
||||
Rc::clone(&avatars),
|
||||
Rc::clone(&live),
|
||||
);
|
||||
state.listen(move || reload(&listener_state, &handles, &rows, &avatars));
|
||||
state.listen(move || reload(&listener_state, &handles, &rows, &live));
|
||||
}
|
||||
{
|
||||
let (listener_state, avatars) = (Rc::clone(&state), Rc::clone(&avatars));
|
||||
state.listen_changes(move || refresh_avatars(&listener_state, &avatars));
|
||||
let (listener_state, live) = (Rc::clone(&state), Rc::clone(&live));
|
||||
state.listen_changes(move || refresh_live_rows(&listener_state, &live));
|
||||
}
|
||||
|
||||
Self { widget }
|
||||
@@ -153,11 +159,11 @@ impl KeysView {
|
||||
}
|
||||
|
||||
/// Rebuild the identity list from the shared state.
|
||||
fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows, avatars: &Avatars) {
|
||||
fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows, live: &LiveRows) {
|
||||
for row in rows.borrow_mut().drain(..) {
|
||||
handles.list.remove(&row);
|
||||
}
|
||||
avatars.borrow_mut().clear();
|
||||
live.borrow_mut().clear();
|
||||
|
||||
let names = state.names();
|
||||
let names = names.lock().unwrap().clone();
|
||||
@@ -168,60 +174,74 @@ fn reload(state: &Rc<AppState>, handles: &Handles, rows: &Rows, avatars: &Avatar
|
||||
}
|
||||
handles.stack.set_visible_child_name("loaded");
|
||||
|
||||
let mut listed: Vec<(String, String)> = names.into_iter().collect();
|
||||
listed.sort_by_key(|(_, name)| name.to_lowercase());
|
||||
for (hex, name) in listed {
|
||||
let profile = PublicKey::from_hex(&hex)
|
||||
.ok()
|
||||
.and_then(|key| state.profiles().display_name(&key));
|
||||
let row = key_row(state, handles, avatars, &hex, &name, profile.as_deref());
|
||||
// Sorted by what the rows actually show: the profile name trumps the label,
|
||||
// so sorting by the label would look arbitrary.
|
||||
let mut listed: Vec<String> = names.into_keys().collect();
|
||||
listed.sort_by_key(|hex| {
|
||||
PublicKey::from_hex(hex)
|
||||
.map(|key| state.identity_label(&key).to_lowercase())
|
||||
.unwrap_or_else(|_| hex.to_lowercase())
|
||||
});
|
||||
for hex in listed {
|
||||
let row = key_row(state, handles, live, &hex);
|
||||
handles.list.add(&row);
|
||||
rows.borrow_mut().push(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the pictures that landed after the list was built onto the existing rows.
|
||||
/// Update the bits of a row that a later profile changes: the picture and the
|
||||
/// name.
|
||||
///
|
||||
/// Deliberately not a `reload`: a change ping also fires for activity and app
|
||||
/// registry changes, and rebuilding would close an open per-key menu for a
|
||||
/// reason the user cannot see.
|
||||
fn refresh_avatars(state: &Rc<AppState>, avatars: &Avatars) {
|
||||
for (hex, avatar) in avatars.borrow().iter() {
|
||||
let texture = state.icons().texture(hex);
|
||||
avatar.set_custom_image(texture.as_ref());
|
||||
/// reason the user cannot see. The title is re-set rather than rebuilt because
|
||||
/// the *discovered* profile name trumps the user's label — for a key that was
|
||||
/// imported before its profile was known, this is where the name finally lands.
|
||||
fn refresh_live_rows(state: &Rc<AppState>, live: &LiveRows) {
|
||||
for entry in live.borrow().iter() {
|
||||
entry
|
||||
.avatar
|
||||
.set_custom_image(state.icons().texture(&entry.hex).as_ref());
|
||||
if let Ok(key) = PublicKey::from_hex(&entry.hex) {
|
||||
let label = state.identity_label(&key);
|
||||
entry.row.set_title(&label);
|
||||
// The initials are a name too (the picture, if any, covers them).
|
||||
entry.avatar.set_text(Some(&label));
|
||||
entry.avatar.set_show_initials(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_row(
|
||||
state: &Rc<AppState>,
|
||||
handles: &Handles,
|
||||
avatars: &Avatars,
|
||||
hex: &str,
|
||||
name: &str,
|
||||
profile: Option<&str>,
|
||||
) -> adw::ActionRow {
|
||||
/// One identity: the name (profile first, else the user's label) over its key.
|
||||
///
|
||||
/// The key is alone on its line — `plain::shorten_npub`'s fixed cut, in the
|
||||
/// monospace font — so a long profile name cannot eat its tail the way the old
|
||||
/// `"Name · key"` subtitle did.
|
||||
fn key_row(state: &Rc<AppState>, handles: &Handles, live: &LiveRows, hex: &str) -> adw::ActionRow {
|
||||
let public_key = PublicKey::from_hex(hex).ok();
|
||||
let name = public_key
|
||||
.map(|key| state.identity_label(&key))
|
||||
.unwrap_or_else(|| hex.to_string());
|
||||
let npub = public_key
|
||||
.map(|key| key.to_bech32().unwrap_or_default())
|
||||
.unwrap_or_else(|| hex.to_string());
|
||||
let short_npub = plain::shorten_npub(&npub);
|
||||
let subtitle = match profile {
|
||||
Some(profile) => format!("{profile} · {short_npub}"),
|
||||
None => short_npub.clone(),
|
||||
};
|
||||
let row = plain::row(name, &subtitle);
|
||||
let row = plain::row(&name, &short_npub);
|
||||
// The subtitle is the key, so the style class belongs on the row: the
|
||||
// selector reaches the subtitle and leaves the name proportional.
|
||||
plain::key_row(&row);
|
||||
// One line, cut to `head…tail`; the full npub stays reachable as a tooltip.
|
||||
row.set_subtitle_lines(1);
|
||||
row.set_tooltip_text(Some(&npub));
|
||||
// The identity's own picture when one is cached, else initials. Decoration:
|
||||
// the name beside it stays the identifier.
|
||||
let avatar = plain::avatar(
|
||||
32,
|
||||
Some(profile.unwrap_or(name)),
|
||||
state.icons().texture(hex).as_ref(),
|
||||
);
|
||||
let avatar = plain::avatar(32, Some(&name), state.icons().texture(hex).as_ref());
|
||||
row.add_prefix(&avatar);
|
||||
avatars.borrow_mut().push((hex.to_string(), avatar));
|
||||
live.borrow_mut().push(LiveRow {
|
||||
hex: hex.to_string(),
|
||||
avatar,
|
||||
row: row.clone(),
|
||||
});
|
||||
|
||||
let menu = gtk::Box::builder()
|
||||
.orientation(gtk::Orientation::Vertical)
|
||||
@@ -259,7 +279,9 @@ fn key_row(
|
||||
let export = plain::menu_button("Export…");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
export.connect_clicked(move |_| present_export(handles.clone(), Rc::clone(&state), public_key));
|
||||
export.connect_clicked(move |_| {
|
||||
present_export(handles.clone(), Rc::clone(&state), public_key)
|
||||
});
|
||||
}
|
||||
menu.append(&export);
|
||||
|
||||
@@ -316,7 +338,10 @@ impl PassphraseFields {
|
||||
.title("Confirm passphrase")
|
||||
.build()
|
||||
});
|
||||
Self { passphrase, confirm }
|
||||
Self {
|
||||
passphrase,
|
||||
confirm,
|
||||
}
|
||||
}
|
||||
|
||||
fn append_to(&self, list: >k::ListBox) {
|
||||
@@ -349,12 +374,11 @@ const NEW_VAULT_NOTE: &str = "Choose a passphrase for the key vault. Every ident
|
||||
fn present_create(handles: Handles, state: Rc<AppState>) {
|
||||
let store = state.store();
|
||||
let first = !store.has_vault();
|
||||
let count = state.names().lock().unwrap().len() + 1;
|
||||
|
||||
let name = adw::EntryRow::builder()
|
||||
.title("Name")
|
||||
.text(format!("Identity {count}"))
|
||||
.build();
|
||||
// Deliberately empty: a freshly generated key has no profile yet, so there is
|
||||
// no name to prefill and no invented "Identity 3" to store. Empty means "no
|
||||
// label", which reads as *Identity key* until a profile is discovered.
|
||||
let name = adw::EntryRow::builder().title("Name").build();
|
||||
let fields = PassphraseFields::new(first);
|
||||
let list = gtk::ListBox::builder()
|
||||
.selection_mode(gtk::SelectionMode::None)
|
||||
@@ -389,7 +413,7 @@ fn present_create(handles: Handles, state: Rc<AppState>) {
|
||||
Ok(passphrase) => passphrase,
|
||||
Err(error) => return report_error(&handles, &error),
|
||||
};
|
||||
let name = defaulted_name(&name.text().to_string());
|
||||
let name = name.text().trim().to_string();
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
let store = Arc::clone(&store);
|
||||
@@ -412,15 +436,37 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
|
||||
let entry = adw::EntryRow::builder()
|
||||
.title("nsec, hex, or ncryptsec")
|
||||
.build();
|
||||
// Prefilled from the *discovered* profile once the pasted key can be decoded,
|
||||
// so an import of a key that already has a profile is named right away. An
|
||||
// empty field stores no label at all — the profile name wins for display
|
||||
// anyway, and a label is only for keys with no discoverable profile.
|
||||
let name = adw::EntryRow::builder().title("Name").build();
|
||||
let import_password = adw::PasswordEntryRow::builder()
|
||||
.title("Password (ncryptsec only)")
|
||||
.build();
|
||||
{
|
||||
let name = name.clone();
|
||||
let state = Rc::clone(&state);
|
||||
let prefilled = Rc::new(RefCell::new(String::new()));
|
||||
entry.connect_changed(move |entry| {
|
||||
let typed = name.text().to_string();
|
||||
if !typed.is_empty() && typed != *prefilled.borrow() {
|
||||
return; // the user's own words win
|
||||
}
|
||||
let found = prefill_name(&entry.text())
|
||||
.and_then(|key| state.profiles().display_name(&key))
|
||||
.unwrap_or_default();
|
||||
name.set_text(&found);
|
||||
*prefilled.borrow_mut() = found;
|
||||
});
|
||||
}
|
||||
let fields = PassphraseFields::new(first);
|
||||
let list = gtk::ListBox::builder()
|
||||
.selection_mode(gtk::SelectionMode::None)
|
||||
.css_classes(["boxed-list"])
|
||||
.build();
|
||||
list.append(&entry);
|
||||
list.append(&name);
|
||||
list.append(&import_password);
|
||||
fields.append_to(&list);
|
||||
|
||||
@@ -452,7 +498,9 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
|
||||
};
|
||||
let text = entry.text().to_string();
|
||||
let import_password = import_password.text().to_string();
|
||||
let name = format!("Imported {count}", count = state.names().lock().unwrap().len() + 1);
|
||||
// Empty means "no label": the discovered profile name is what the app
|
||||
// shows, and a label is only for keys with no profile.
|
||||
let label = name.text().trim().to_string();
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
let store = Arc::clone(&store);
|
||||
@@ -460,10 +508,10 @@ fn present_import(handles: Handles, state: Rc<AppState>) {
|
||||
async move {
|
||||
if text.starts_with("ncryptsec1") {
|
||||
store
|
||||
.import_user_key_encrypted(&name, &text, &import_password, &passphrase)
|
||||
.import_user_key_encrypted(&label, &text, &import_password, &passphrase)
|
||||
.await
|
||||
} else {
|
||||
store.import_user_key(&name, &text, &passphrase).await
|
||||
store.import_user_key(&label, &text, &passphrase).await
|
||||
}
|
||||
},
|
||||
move |result| match result {
|
||||
@@ -495,12 +543,7 @@ fn with_unlocked<F: FnOnce() + 'static>(handles: &Handles, state: &Rc<AppState>,
|
||||
});
|
||||
}
|
||||
|
||||
fn present_rename(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
public_key: PublicKey,
|
||||
current: &str,
|
||||
) {
|
||||
fn present_rename(handles: Handles, state: Rc<AppState>, public_key: PublicKey, current: &str) {
|
||||
let entry = gtk::Entry::builder().text(current).build();
|
||||
let dialog = adw::AlertDialog::builder()
|
||||
.heading("Rename identity key")
|
||||
@@ -521,7 +564,9 @@ fn present_rename(
|
||||
return;
|
||||
}
|
||||
let store = state.store();
|
||||
let name = defaulted_name(&entry.text().to_string());
|
||||
// Clearing the field means "no label": the discovered profile name (or
|
||||
// *Identity key*) is what the app shows then.
|
||||
let name = entry.text().trim().to_string();
|
||||
let after = Rc::clone(&state);
|
||||
let handles = handles.clone();
|
||||
runtime::spawn(
|
||||
@@ -615,12 +660,7 @@ fn present_export_dialog(handles: Handles, state: Rc<AppState>, public_key: Publ
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn present_remove(
|
||||
handles: Handles,
|
||||
state: Rc<AppState>,
|
||||
public_key: PublicKey,
|
||||
name: &str,
|
||||
) {
|
||||
fn present_remove(handles: Handles, state: Rc<AppState>, public_key: PublicKey, name: &str) {
|
||||
let paired = state.registry().lock().unwrap().list_for(public_key);
|
||||
let body = if paired.is_empty() {
|
||||
format!("Remove “{name}” from this computer? This cannot be undone.")
|
||||
@@ -680,13 +720,20 @@ fn present_remove(
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
fn defaulted_name(text: &str) -> String {
|
||||
let name = text.trim();
|
||||
if name.is_empty() {
|
||||
"Identity key".to_string()
|
||||
} else {
|
||||
name.to_string()
|
||||
/// The public key a pasted import string belongs to, for prefilling a name from
|
||||
/// the profile cache. `nsec` and hex parse; an `ncryptsec`'s key is unknown until
|
||||
/// it is decrypted, so it prefills nothing (and anything else is not an import).
|
||||
///
|
||||
/// A bare 64-character hex string is ambiguous and is read the way the vault
|
||||
/// reads it, as a *secret* key — so a pasted public hex key would prefill a name
|
||||
/// for some other key. Harmless: the name is only stored when the import
|
||||
/// succeeds, and the import of a public key fails.
|
||||
fn prefill_name(input: &str) -> Option<PublicKey> {
|
||||
let input = input.trim();
|
||||
if input.is_empty() || input.starts_with("ncryptsec1") {
|
||||
return None;
|
||||
}
|
||||
Keys::parse(input).ok().map(|keys| keys.public_key())
|
||||
}
|
||||
|
||||
fn report_error(handles: &Handles, message: &str) {
|
||||
@@ -699,3 +746,35 @@ fn report_error(handles: &Handles, message: &str) {
|
||||
dialog.set_default_response(Some("close"));
|
||||
dialog.present(toplevel(handles).as_ref());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Prefilling a name must only ever happen for a string that really is the
|
||||
/// secret half of a key: an `ncryptsec` cannot be decoded without the
|
||||
/// password, and a public key is not an import at all.
|
||||
#[test]
|
||||
fn a_pasted_import_only_prefills_from_a_decodable_secret() {
|
||||
let keys = Keys::generate();
|
||||
let public_key = keys.public_key();
|
||||
|
||||
let nsec = keys.secret_key().to_bech32().unwrap();
|
||||
assert_eq!(prefill_name(&nsec), Some(public_key));
|
||||
assert_eq!(
|
||||
prefill_name(&keys.secret_key().to_secret_hex()),
|
||||
Some(public_key)
|
||||
);
|
||||
// Surrounding whitespace is what a clipboard hands over.
|
||||
assert_eq!(prefill_name(&format!(" {nsec} ")), Some(public_key));
|
||||
|
||||
assert_eq!(prefill_name("ncryptsec1qyfkstqqqqq"), None);
|
||||
for bad in ["", " ", "hello"] {
|
||||
assert_eq!(prefill_name(bad), None, "{bad:?} is not a secret key");
|
||||
}
|
||||
// A bech32 *public* key is not an import; a bare hex one is ambiguous and
|
||||
// is read as a secret (see the doc comment above).
|
||||
assert_eq!(prefill_name(&public_key.to_bech32().unwrap()), None);
|
||||
assert_ne!(prefill_name(&public_key.to_hex()), Some(public_key));
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,31 @@ pub fn row(title: &str, subtitle: &str) -> adw::ActionRow {
|
||||
row
|
||||
}
|
||||
|
||||
/// A label for a **key or value** (an `npub`, a hex key, a `bunker://` string):
|
||||
/// plain text like [`label`], but in the monospace font.
|
||||
///
|
||||
/// The font comes from our `.key-value` class, not libadwaita's `.monospace`,
|
||||
/// because that one also switches to the code size — see `data/style.css`. Keys
|
||||
/// are shown as fixed `head…tail` cuts (`shorten_npub`, `shorten_uri`), so equal
|
||||
/// lengths and equal widths make a column of them look deliberate.
|
||||
pub fn key(text: &str) -> gtk::Label {
|
||||
let label = gtk::Label::builder()
|
||||
.label(text)
|
||||
.use_markup(false)
|
||||
.xalign(0.0)
|
||||
.max_width_chars(48)
|
||||
.build();
|
||||
label.add_css_class("key-value");
|
||||
label
|
||||
}
|
||||
|
||||
/// Mark an `AdwActionRow`/`AdwExpanderRow` whose **subtitle is a key**, so the
|
||||
/// style class reaches the subtitle's label and not the row's name. The
|
||||
/// selectors live in `data/style.css`.
|
||||
pub fn key_row(row: &impl IsA<gtk::Widget>) {
|
||||
row.add_css_class("key-value");
|
||||
}
|
||||
|
||||
/// A plain, word-char-wrapped label.
|
||||
///
|
||||
/// `WordChar` wrapping matters: the values include long tokens with no spaces
|
||||
|
||||
+38
-13
@@ -89,8 +89,13 @@ impl IdentitySwitcher {
|
||||
self.button
|
||||
.set_tooltip_text(Some(&format!("Identity: {current_label}")));
|
||||
|
||||
// Sorted by what the rows show (the profile name trumps the label).
|
||||
let mut listed: Vec<(String, String)> = names.into_iter().collect();
|
||||
listed.sort_by_key(|(_, name)| name.to_lowercase());
|
||||
listed.sort_by_key(|(hex, name)| {
|
||||
PublicKey::from_hex(hex)
|
||||
.map(|key| self.state.identity_label(&key).to_lowercase())
|
||||
.unwrap_or_else(|_| name.to_lowercase())
|
||||
});
|
||||
for (hex, name) in listed {
|
||||
let row = self.row(&hex, &name, current);
|
||||
self.content.append(&row);
|
||||
@@ -128,6 +133,9 @@ impl IdentitySwitcher {
|
||||
.map(|key| self.state.identity_label(&key))
|
||||
.unwrap_or_else(|| name.to_string());
|
||||
let row = gtk::Button::builder()
|
||||
// The name below is a button's text, so libadwaita renders it bold
|
||||
// (700) — wanted. The byline under it is a value: `plain::key` takes
|
||||
// the bold off (see `data/style.css`).
|
||||
.css_classes(["flat"])
|
||||
.halign(gtk::Align::Fill)
|
||||
.build();
|
||||
@@ -156,18 +164,35 @@ impl IdentitySwitcher {
|
||||
.build(),
|
||||
);
|
||||
if let Some(key) = key {
|
||||
texts.append(
|
||||
>k::Label::builder()
|
||||
.label(plain::shorten(
|
||||
&key.to_bech32().unwrap_or_else(|_| key.to_hex()),
|
||||
12,
|
||||
6,
|
||||
))
|
||||
.use_markup(false)
|
||||
.xalign(0.0)
|
||||
.css_classes(["dim-label"])
|
||||
.build(),
|
||||
);
|
||||
// The switcher gets a shorter line than the rest of the app: this
|
||||
// popover also carries the avatar and a check mark, and the window is
|
||||
// 420 px wide. `key-value` gives it the monospace font.
|
||||
//
|
||||
// A **verified** NIP-05 reads better than a key, so it wins when the
|
||||
// domain confirmed it for exactly this key and is shown **in full** —
|
||||
// however long the address is, that is the identity the user
|
||||
// recognises. Everything else falls back to the shortened npub (20
|
||||
// characters, `head…tail`), and the tooltip always carries the full
|
||||
// npub, the authoritative value.
|
||||
let npub = key.to_bech32().unwrap_or_else(|_| key.to_hex());
|
||||
let text = match self.state.profiles().nip05(&key) {
|
||||
Some(nip05) => nip05,
|
||||
None => plain::shorten(&npub, 12, 7),
|
||||
};
|
||||
// `.caption`: about the size a key has in a row subtitle (12.0 pt
|
||||
// against a subtitle's 12.2 — `caption` is 82%, a subtitle's
|
||||
// `smaller` is ~83%), so the switcher is not the one place a key
|
||||
// renders at body size and the bold name above it stays the loudest
|
||||
// thing in the row.
|
||||
let byline = plain::key(&text);
|
||||
byline.add_css_class("dim-label");
|
||||
byline.add_css_class("caption");
|
||||
// A published address can be long; `plain::key` caps a label's natural
|
||||
// width at 48 characters, so without this the tail would be clipped
|
||||
// rather than shown. (The npub cut is 20, so this never bites there.)
|
||||
byline.set_ellipsize(gtk::pango::EllipsizeMode::End);
|
||||
byline.set_tooltip_text(Some(&npub));
|
||||
texts.append(&byline);
|
||||
}
|
||||
line.append(&texts);
|
||||
|
||||
|
||||
Reference in new issue
Block a user