Re-fetch a profile on demand, and let an equal kind-0 fill in new fields
An identity with a valid NIP-05 address never showed it, however often the
profile was re-fetched. `put_metadata` only stored a *strictly* newer kind-0, so
`nip05` — a field added to `Profile` after the cached entries were written — was
refused along with the very event that carries it. The same comparison meant
`fetched_at` never advanced for an unchanged profile, so `needs_refresh` stayed
true and every start re-fetched it again.
The writer now answers two questions separately. Do we *have* this version? A
newer or equal `created_at` says yes: the clock moves and the answer counts.
Whose *content* does the entry hold? A newer version replaces it; an equal one is
the same version re-fetched, which is what backfills a field added later. Two
versions in the same second are settled by the lower event id — NIP-01's rule for
replaceable events — in the merge map and in the cache (`kind0_id`), so a relay
serving only one of them cannot make what we hold flip; an entry written before
that id was kept adopts the next equal-`created_at` answer. An older version is
still refused, which is the point of the watermark. `put_relay_list` stays strict
deliberately: its attempt clock moves on every call, so nothing can be stranded
there — and if a kind-10002-derived field is ever added, it has to become `>=` at
the same time.
The NIP-05 parser takes the email-ish local part now (`. _ % + -`, any case), as
clients in the wild use; it only reaches a percent-encoded query parameter. The
domain half stays strict, because that is what becomes the outbound request.
On top of that, the identities list can re-fetch one profile on demand: "Re-fetch
profile" (`AppState::refetch_profile`) loosens the 7-day discovery TTL, the 1-day
directory-fallback backoff and the 1-day NIP-05 backoff for that key, and a
per-key claim (`profile_fetch_in_flight`, claimed by automatic refreshes too, held
with a self-healing bound and released by comparing the stamp this call wrote)
keeps repeated clicks from opening parallel rounds. It cannot make anything worse:
the cached name, picture, relay list and watermarks are untouched, a profile is
stored only when it is newer than `kind0_at`, and an address can only be
*un*-verified by a definitive non-match.
The fetch reports what it found — `FetchOutcome::{Updated,UpToDate,NotFound}`,
decided by comparing what the app shows before and after — and the menu answers
with it ("Profile updated" / "Profile is up to date" / "No profile found"),
dismissing the "checking" toast rather than outranking it: libadwaita shows one
toast at a time, and a high-priority one only pushes the previous toast back into
the queue, where it would return stale.
This commit is contained in:
5 files changed
+786
-90
No files matched your search
@@ -388,9 +388,31 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
- `AppState::refresh_identities` resolves the current identity (setting valid,
|
||||
else first key) and binds legacy apps (`bind_legacy`) at startup and after any
|
||||
key change. Pre-M8 this also migrated a keyring item; that is gone.
|
||||
- Identities window: list, **Add/Import**, per-key **Rename / Copy / Export /
|
||||
Remove**, and **Use for new pairings**. Removing a key clears it as current,
|
||||
revokes the apps bound to it (the dialog names them), and deletes the item.
|
||||
- Identities window: list, **Add/Import**, per-key **Re-fetch profile / Rename /
|
||||
Copy / Export / Remove**. (Which key is *current* is the header switcher's job,
|
||||
not this window's.) "Re-fetch profile" (`AppState::refetch_profile`) loosens all
|
||||
three automatic gates for that one key — the 7-day discovery TTL, the 1-day
|
||||
directory-fallback backoff and the 1-day NIP-05 check backoff
|
||||
(`Profiles::mark_profile_stale`), so the row updates now instead of at the next
|
||||
refresh. That includes a discovery query — the per-author request that tells the
|
||||
directory relays this machine holds the key — which is exactly why it is behind
|
||||
a deliberate click; a click while a fetch for that key is already running
|
||||
(`profile_fetch_in_flight`, which an automatic refresh claims too) does nothing
|
||||
and says so. When it lands, the menu answers with what the fetch found
|
||||
(`store::profiles::FetchOutcome`): "Profile updated", "Profile is up to date"
|
||||
(the relays had nothing newer — including the version already held) or "No
|
||||
profile found"; so the "checking" toast does not just hang (the outcome dismisses
|
||||
it — it is not outranked, because a high-priority toast only pushes the previous
|
||||
one back into the queue and it would come back stale). A moved clock, or an
|
||||
entry `put_relay_list` created only for its attempt clock, is *not* an update:
|
||||
"updated" means the name, picture or *declared* address changed — a NIP-05 verdict
|
||||
arrives later, from `ensure_nip05`'s own round trip, so a flip of that on its own
|
||||
is not an update. It cannot make anything worse either: the cached name, picture,
|
||||
relay list and every watermark are untouched, a profile is stored only when it is
|
||||
newer than `kind0_at`, and an address can only be *un*-verified by a definitive
|
||||
non-match — an unreachable domain leaves the confirmed one in place. Removing a
|
||||
key clears it as current, revokes the apps bound to it (the dialog names them),
|
||||
and deletes the item.
|
||||
- The identity is shown as **"Signing as {name}"** with the npub beneath it, not
|
||||
as `{name} ({npub})`: in the approval dialog it is a stacked field (optionally
|
||||
the npub alone when the key has no name), in the Connect dialog and the Apps
|
||||
@@ -484,14 +506,34 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
the future (`FUTURE_SLACK`) — that is what keeps a relay from pinning a
|
||||
watermark out of reach.
|
||||
- **`profiles.json` holds the outbox and its clocks**, written by three
|
||||
single-owner writers: `put_metadata` (kind-0, refuses a not-newer answer,
|
||||
sets `kind0_at`/`fetched_at`), `put_relay_list` (sets `write_relays` only from a
|
||||
newer kind-10002 — `created_at = 0` means "nothing found" and only moves the
|
||||
clock, so a transient miss cannot wipe a working outbox — and always sets
|
||||
`relays_checked_at`), and `note_recovery`. `RELAYS_TTL` is **7 days** on
|
||||
*attempts*, so an identity that publishes no 10002 is re-discovered weekly, not
|
||||
on every start; `RECOVERY_BACKOFF` is 1 day on the directory kind-0 fallback,
|
||||
which matters because a missing profile never advances `fetched_at`, so
|
||||
single-owner writers: `put_metadata` (kind-0, older refused — see below — sets
|
||||
`kind0_at`/`fetched_at`), `put_relay_list` (sets `write_relays` only from a
|
||||
*strictly* newer kind-10002 — `created_at = 0` means "nothing found" and only
|
||||
moves the clock, so a transient miss cannot wipe a working outbox — and always
|
||||
sets `relays_checked_at`), and `note_recovery`.
|
||||
- **`put_metadata` accepts an equal `created_at`, and both halves of that matter.**
|
||||
A newer version wins; an *equal* one is the same version re-fetched, so storing
|
||||
it is what lets a field added to `Profile` after the entry was written be filled
|
||||
in — `nip05` arrived exactly that way, and with a strict `>` every later fetch of
|
||||
the same kind-0 was refused, so an existing installation could never show its
|
||||
address no matter how often it re-fetched. It is also what advances
|
||||
`fetched_at` — for any same-or-newer answer, since "do we have this version?" and
|
||||
"whose content does the entry hold?" are separate questions: re-fetching the very
|
||||
same event is the steady state once an id is kept, and with a strict `>` an
|
||||
unchanged profile kept a stale `fetched_at`, so `needs_refresh` stayed true and
|
||||
the app re-fetched it on **every start**. An *older* version is still refused,
|
||||
which is the whole point of the watermark. Equal `created_at`s are settled by
|
||||
the **lower event id** (NIP-01's rule for replaceable events) — in the merge map
|
||||
*and* in the cache, which keeps `kind0_id` for it — so two same-second versions
|
||||
cannot flip with relay order, and a relay serving only one of them cannot change
|
||||
what the cache holds from fetch to fetch. An entry written before `kind0_id`
|
||||
existed adopts the next equal-`created_at` answer, which is also how a field added
|
||||
later gets filled in. `put_relay_list` deliberately stays strict: its
|
||||
attempt clock advances on every call anyway, so nothing can be stranded there.
|
||||
`RELAYS_TTL` is **7 days** on *attempts*, so an identity that publishes no 10002
|
||||
is re-discovered weekly, not on every start; `RECOVERY_BACKOFF` is 1 day on the
|
||||
directory kind-0 fallback, which matters because a missing profile never
|
||||
advances `fetched_at`, so
|
||||
`needs_refresh` stays true. (**Amber does none of this**: it re-queries the
|
||||
kind-10002 on every profile fetch, applies it only if newer, and always asks
|
||||
*indexers ∪ saved relays* — no TTL, no outbox-only path.) Disclosure, honestly:
|
||||
@@ -513,8 +555,14 @@ data/ desktop, metainfo, gschema (all `.in` templates), icons, re
|
||||
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`).
|
||||
dropped (`set_nip05` compares before storing); a *definitive* non-match keeps it
|
||||
unshown, while *no answer at all* (an unreachable domain) leaves a previously
|
||||
confirmed address in place — a blip is not evidence. The local part is email-ish
|
||||
(`a–z 0–9 . _ % + -`, any case) and only ever reaches a percent-encoded query
|
||||
parameter; the **domain** is the strict half (labels, no port/path/scheme), since
|
||||
that is what becomes the outbound request. Either way the attempt is
|
||||
recorded, so an unchanged address is asked again at most once a day
|
||||
(`nip05_checked_for` / `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
|
||||
@@ -1058,6 +1106,11 @@ 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 **manual re-fetch's outcomes** are pinned by the ignored
|
||||
`nak_the_outbox_relay_profile_wins`: `Updated` for a newer profile from the
|
||||
directory and from the identity's own relays, `UpToDate` when the relays answer
|
||||
with what is already held, and `NotFound` for a key nobody publishes. The three
|
||||
toast texts are a unit test in `ui::keys_view`.
|
||||
- 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
|
||||
|
||||
+136
-9
@@ -6,6 +6,7 @@ use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use nostr::nips::nip19::ToBech32;
|
||||
use nostr::prelude::PublicKey;
|
||||
@@ -18,10 +19,27 @@ use crate::store::apps::AppRegistry;
|
||||
use crate::store::audit::ActivityLog;
|
||||
use crate::store::icons::IconStore;
|
||||
use crate::store::keys::{Error as KeyError, KeyRef, KeyStore};
|
||||
use crate::store::profiles::Profiles;
|
||||
use crate::store::profiles::{FetchOutcome, Profiles};
|
||||
|
||||
type Listener = Rc<dyn Fn()>;
|
||||
|
||||
/// What a manual fetch reports back with: one outcome per identity it was asked
|
||||
/// about, handed to the view that asked (a `Box` because it crosses into the
|
||||
/// fetch's completion closure).
|
||||
type FetchReport = Box<dyn FnOnce(Vec<(PublicKey, FetchOutcome)>) + 'static>;
|
||||
|
||||
/// How long a profile-fetch claim is believed.
|
||||
///
|
||||
/// A self-healing bound rather than a measured worst case: it only has to outlast
|
||||
/// a *live* fetch, so that a claim left behind by a task that died — a panic
|
||||
/// inside `profiles::fetch` — does not refuse every later re-fetch for that
|
||||
/// identity until the process restarts. A batch of identities takes longer than
|
||||
/// this (waves are per identity), and that is fine: the release is a
|
||||
/// compare-and-remove of the stamp this call wrote, so a late completion can never
|
||||
/// clear a newer claim. The most it can cost is that a big batch overlaps a second
|
||||
/// fetch, which the watermarks make harmless.
|
||||
const PROFILE_FETCH_CLAIM: Duration = Duration::from_secs(60);
|
||||
|
||||
pub struct AppState {
|
||||
/// Open once per process. A file, so it is read synchronously — the launch
|
||||
/// decision needs the key list before any window exists.
|
||||
@@ -43,6 +61,10 @@ pub struct AppState {
|
||||
/// 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>>,
|
||||
/// Identities whose profile is being fetched right now, with when the claim was
|
||||
/// taken. An automatic refresh and a manual "re-fetch" must not double up, and
|
||||
/// neither should two clicks.
|
||||
profile_fetch_in_flight: RefCell<HashMap<PublicKey, Instant>>,
|
||||
listeners: RefCell<Vec<Listener>>,
|
||||
change_listeners: RefCell<Vec<Listener>>,
|
||||
/// The responder pings this after it changes the registry or the log.
|
||||
@@ -67,6 +89,7 @@ impl AppState {
|
||||
profiles: Profiles::new(),
|
||||
icons: Rc::new(IconStore::new()),
|
||||
nip05_in_flight: RefCell::new(HashSet::new()),
|
||||
profile_fetch_in_flight: RefCell::new(HashMap::new()),
|
||||
listeners: RefCell::new(Vec::new()),
|
||||
change_listeners: RefCell::new(Vec::new()),
|
||||
changes,
|
||||
@@ -291,8 +314,9 @@ impl AppState {
|
||||
///
|
||||
/// 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.
|
||||
/// identified. At most one check per address per day; a *definitive*
|
||||
/// non-match un-shows the address, while a failed check (an unreachable
|
||||
/// domain) only records the attempt and leaves a confirmed address alone.
|
||||
///
|
||||
/// 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
|
||||
@@ -317,11 +341,13 @@ impl AppState {
|
||||
runtime::spawn(
|
||||
async move { crate::store::nip05::verify(&checked, &hex).await },
|
||||
move |result| {
|
||||
// `None` is "no answer": it must not un-verify an address the
|
||||
// domain confirmed earlier, only a definitive non-match may.
|
||||
let verified = match result {
|
||||
Ok(verified) => verified,
|
||||
Ok(verified) => Some(verified),
|
||||
Err(error) => {
|
||||
eprintln!("regent: could not check a NIP-05 address: {error}");
|
||||
false
|
||||
None
|
||||
}
|
||||
};
|
||||
state.nip05_in_flight.borrow_mut().remove(&claim);
|
||||
@@ -442,23 +468,124 @@ impl AppState {
|
||||
.filter(|key| self.profiles.needs_refresh(&key.public_key))
|
||||
.map(|key| key.public_key)
|
||||
.collect(),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
/// Re-fetch one identity's profile now, and re-check its NIP-05 address.
|
||||
///
|
||||
/// The identities list's "Re-fetch profile" menu item, and the one place the
|
||||
/// automatic cadences are bypassed: `mark_profile_stale` clears the 7-day
|
||||
/// discovery TTL, the 1-day directory-fallback backoff and the 1-day NIP-05
|
||||
/// backoff for that one key. That means a discovery query — the per-author
|
||||
/// request that tells the directory relays this machine holds the key — which
|
||||
/// is exactly why it sits behind a deliberate click rather than a timer.
|
||||
///
|
||||
/// It cannot make anything worse: the cached name, picture, relay list and
|
||||
/// every watermark are untouched, so a profile is stored only when the relays
|
||||
/// have something newer than `kind0_at`, and an address is only *un*-verified
|
||||
/// by a definitive non-match. Returns `false` when a fetch for this key is
|
||||
/// already running (a click during one, or an automatic refresh in flight), so
|
||||
/// repeated clicks cannot each open a new round of requests. Such a click is
|
||||
/// *refused*, not queued: it is a seconds-long race, and the menu says so.
|
||||
///
|
||||
/// `done` is called on the main loop with what the fetch found, so the menu can
|
||||
/// say "Profile updated" rather than leaving the user guessing after the
|
||||
/// "checking" toast: the identities window is where it was clicked.
|
||||
pub fn refetch_profile(
|
||||
self: &Rc<Self>,
|
||||
key: PublicKey,
|
||||
done: impl FnOnce(FetchOutcome) + 'static,
|
||||
) -> bool {
|
||||
if self.profile_fetch_claimed(&key) {
|
||||
return false;
|
||||
}
|
||||
self.profiles.mark_profile_stale(&key);
|
||||
self.fetch_profiles(
|
||||
vec![key],
|
||||
Some(Box::new(move |outcomes| {
|
||||
let outcome = outcomes
|
||||
.into_iter()
|
||||
.find(|(fetched, _)| *fetched == key)
|
||||
.map(|(_, outcome)| outcome)
|
||||
// A fetch that could not start at all still has to say
|
||||
// something, and "nothing found" is what it did.
|
||||
.unwrap_or(FetchOutcome::NotFound);
|
||||
done(outcome);
|
||||
})),
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether a fetch for `key` is already running.
|
||||
fn profile_fetch_claimed(&self, key: &PublicKey) -> bool {
|
||||
match self.profile_fetch_in_flight.borrow().get(key) {
|
||||
Some(taken) => Instant::now().duration_since(*taken) < PROFILE_FETCH_CLAIM,
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Claim `keys` for a fetch, skipping the ones already claimed.
|
||||
///
|
||||
/// Returns each key with the stamp this call wrote for it, so the release can
|
||||
/// compare before removing — a completion that arrives after its claim expired
|
||||
/// must not clear a *newer* claim.
|
||||
fn claim_profile_fetches(&self, keys: &[PublicKey]) -> Vec<(PublicKey, Instant)> {
|
||||
let now = Instant::now();
|
||||
let mut claimed = Vec::new();
|
||||
let mut in_flight = self.profile_fetch_in_flight.borrow_mut();
|
||||
for key in keys {
|
||||
let mine = match in_flight.get(key) {
|
||||
Some(taken) => now.duration_since(*taken) >= PROFILE_FETCH_CLAIM,
|
||||
None => true,
|
||||
};
|
||||
if mine {
|
||||
in_flight.insert(*key, now);
|
||||
claimed.push((*key, now));
|
||||
}
|
||||
}
|
||||
claimed
|
||||
}
|
||||
|
||||
/// Fetch kind-0 profiles for keys that lack a fresh one. Best effort and
|
||||
/// safe to call often; the cached names arrive via a later notify.
|
||||
fn fetch_profiles(self: &Rc<Self>, keys: Vec<PublicKey>) {
|
||||
///
|
||||
/// The keys are claimed here (the ones already claimed are skipped, not
|
||||
/// fetched in parallel) and released when the fetch lands.
|
||||
fn fetch_profiles(self: &Rc<Self>, keys: Vec<PublicKey>, report: Option<FetchReport>) {
|
||||
if keys.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Only what this call actually claimed: a key already being fetched is
|
||||
// skipped rather than fetched in parallel, and its claim is not ours to
|
||||
// release.
|
||||
let claimed = self.claim_profile_fetches(&keys);
|
||||
if claimed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let directory = crate::store::profiles::profile_relays();
|
||||
let profiles = self.profiles.clone();
|
||||
let state = Rc::clone(self);
|
||||
let fetching: Vec<PublicKey> = claimed.iter().map(|(key, _)| *key).collect();
|
||||
runtime::spawn(
|
||||
async move { crate::store::profiles::fetch(directory, keys, profiles).await },
|
||||
async move { crate::store::profiles::fetch(directory, fetching, profiles).await },
|
||||
move |result| {
|
||||
if let Err(error) = result {
|
||||
eprintln!("regent: could not fetch profiles: {error}");
|
||||
for (key, stamp) in &claimed {
|
||||
let mut in_flight = state.profile_fetch_in_flight.borrow_mut();
|
||||
// Only ours: the claim may have expired and been taken over.
|
||||
if in_flight.get(key) == Some(stamp) {
|
||||
in_flight.remove(key);
|
||||
}
|
||||
}
|
||||
let outcomes = match result {
|
||||
Ok(outcomes) => outcomes,
|
||||
Err(error) => {
|
||||
eprintln!("regent: could not fetch profiles: {error}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
if let Some(report) = report {
|
||||
report(outcomes);
|
||||
}
|
||||
// A profile that just arrived may carry a picture or a NIP-05
|
||||
// address: hydrate what is cached, fetch the rest, and check the
|
||||
|
||||
+27
-5
@@ -21,11 +21,14 @@ pub struct Address {
|
||||
/// 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.
|
||||
/// Parse `local@domain`.
|
||||
///
|
||||
/// 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.
|
||||
/// One `@`, then a local part of the characters an email address uses (letters,
|
||||
/// digits, `.`, `_`, `%`, `+`, `-`, any case) — it only ever reaches a URL query,
|
||||
/// where it is percent-encoded. The domain has to be a plain hostname: at least two
|
||||
/// labels, none empty or hyphen-edged, no scheme, path, query, port or whitespace.
|
||||
/// **The domain is the half that becomes an outbound HTTPS request**, so that is
|
||||
/// where the strictness has to be: a sloppy parse there is an SSRF vector.
|
||||
pub fn parse(value: &str) -> Option<Address> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.chars().count() > MAX_LEN {
|
||||
@@ -37,7 +40,7 @@ pub fn parse(value: &str) -> Option<Address> {
|
||||
}
|
||||
if !local
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
|
||||
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '%' | '+'))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
@@ -134,6 +137,23 @@ mod tests {
|
||||
Some("raucao@kosmos.org")
|
||||
);
|
||||
|
||||
// The local part is email-ish: clients in the wild use all of these, and
|
||||
// it only ever reaches a percent-encoded query parameter.
|
||||
for accepted in [
|
||||
"user+tag@example.org",
|
||||
"user%40x@example.org",
|
||||
"some.name_with-stuff@example.org",
|
||||
"under_score@sub.domain.co.uk",
|
||||
"dash-last_name@example.org",
|
||||
"a@b.co",
|
||||
] {
|
||||
let address = parse(accepted).unwrap_or_else(|| panic!("{accepted:?} must parse"));
|
||||
assert!(
|
||||
url(&address).starts_with("https://"),
|
||||
"{accepted:?} must build an https URL"
|
||||
);
|
||||
}
|
||||
|
||||
for rejected in [
|
||||
"",
|
||||
" ",
|
||||
@@ -149,6 +169,8 @@ mod tests {
|
||||
"raucao@kosmos.org #x",
|
||||
"rau cao@kosmos.org",
|
||||
"raucao@kos mos.org",
|
||||
"raucao@kosmos.org\ttail",
|
||||
"rau*cao@kosmos.org",
|
||||
"raucao@-kosmos.org",
|
||||
"raucao@kosmos.org-",
|
||||
"raucao@.kosmos.org",
|
||||
|
||||
+502
-63
@@ -107,6 +107,12 @@ pub struct Profile {
|
||||
/// `created_at` of the cached kind-0. Its watermark.
|
||||
#[serde(default)]
|
||||
pub kind0_at: i64,
|
||||
/// Event id of the cached kind-0, so two versions in the same second are
|
||||
/// settled the way NIP-01 settles replaceable events — the lower id wins — in
|
||||
/// the cache as well as within one fetch. `None` in an entry written before
|
||||
/// this was kept, which makes the next equal-`created_at` answer ours to adopt.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub kind0_id: Option<String>,
|
||||
/// 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.
|
||||
@@ -201,16 +207,51 @@ impl Profiles {
|
||||
|| 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) {
|
||||
/// Loosen the three automatic gates for one identity, so the next fetch asks
|
||||
/// again *now*: the discovery TTL (`relays_checked_at`), the directory-fallback
|
||||
/// backoff (`relays_recovery_at`) and the NIP-05 check backoff
|
||||
/// (`nip05_checked_for`).
|
||||
///
|
||||
/// This is what a manual "re-fetch profile" does. The cached data itself —
|
||||
/// name, picture, relay list, every watermark — is untouched, so the fetch can
|
||||
/// only replace it with something newer. A key with no cache entry is left
|
||||
/// alone: there is nothing to loosen, and no empty entry is invented.
|
||||
pub fn mark_profile_stale(&self, key: &PublicKey) {
|
||||
let mut changed = false;
|
||||
{
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
if let Some(entry) = entries.get_mut(&key.to_hex())
|
||||
&& (entry.relays_checked_at != 0
|
||||
|| entry.relays_recovery_at != 0
|
||||
|| entry.nip05_checked_for.is_some())
|
||||
{
|
||||
entry.relays_checked_at = 0;
|
||||
entry.relays_recovery_at = 0;
|
||||
entry.nip05_checked_for = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.save();
|
||||
}
|
||||
}
|
||||
|
||||
/// Record what a check found: `Some(true)` the domain confirmed the address
|
||||
/// for this key, `Some(false)` it answered with somebody else's, `None` there
|
||||
/// was no answer at all (a network failure) — which leaves a previously
|
||||
/// confirmed address in place, because a relay or DNS blip is not evidence
|
||||
/// against the domain. 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: Option<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());
|
||||
if let Some(verified) = verified {
|
||||
entry.nip05_ok = verified.then(|| checked.to_string());
|
||||
}
|
||||
entry.nip05_checked_for = Some(checked.to_string());
|
||||
entry.nip05_checked_at = now;
|
||||
}
|
||||
@@ -225,12 +266,22 @@ impl Profiles {
|
||||
}
|
||||
}
|
||||
|
||||
/// Store a kind-0's fields, unless it is not newer than what is cached.
|
||||
/// Note a kind-0 answer for `key`, and report whether we now have that version.
|
||||
///
|
||||
/// Returns whether it was stored: refusing a not-newer (or equal) answer is
|
||||
/// what keeps one relay replaying an old, validly signed profile from walking
|
||||
/// the cached name and picture backwards. `fetched_at` moves only on a store,
|
||||
/// and the relay fields are left alone — every clock has exactly one writer.
|
||||
/// Two questions, deliberately separate:
|
||||
///
|
||||
/// - *Do we have this version?* A **newer or equal** `created_at` answers yes:
|
||||
/// `fetched_at` moves and `true` comes back, so an unchanged profile is not
|
||||
/// re-fetched on every start. Only an **older** answer is refused outright.
|
||||
/// - *Whose content does the entry hold?* A newer version replaces it; an equal
|
||||
/// one is the same version re-fetched, which is what lets a field added to
|
||||
/// `Profile` after the entry was written be filled in (`nip05` arrived exactly
|
||||
/// that way). Between two versions in the same second the **lower event id**
|
||||
/// wins — NIP-01's rule for replaceable events — so the winner does not depend
|
||||
/// on relay order, and an entry written before `kind0_id` existed adopts the
|
||||
/// next equal-`created_at` answer.
|
||||
///
|
||||
/// The relay fields are left alone: every clock has exactly one writer.
|
||||
pub fn put_metadata(
|
||||
&self,
|
||||
key: &PublicKey,
|
||||
@@ -238,18 +289,41 @@ impl Profiles {
|
||||
picture: Option<String>,
|
||||
nip05: Option<String>,
|
||||
created_at: i64,
|
||||
id: Option<EventId>,
|
||||
) -> bool {
|
||||
let mut stored = false;
|
||||
{
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
let entry = entries.entry(key.to_hex()).or_default();
|
||||
if created_at > entry.kind0_at {
|
||||
// Newest `created_at` wins; an equal one is settled by the lower event
|
||||
// id (`tie_ours`), and an entry that predates the id being kept takes
|
||||
// that answer — which is also what fills in a field added later.
|
||||
let tie_ours = match (&entry.kind0_id, &id) {
|
||||
(None, _) => true,
|
||||
(Some(_), None) => false,
|
||||
(Some(stored), Some(incoming)) => incoming.to_hex().as_str() < stored.as_str(),
|
||||
};
|
||||
let newer = created_at > entry.kind0_at;
|
||||
let same_version = created_at == entry.kind0_at;
|
||||
|
||||
// Two questions, deliberately separate. Do we *have* this version? Then
|
||||
// the freshness clock moves, so an unchanged profile is not re-fetched
|
||||
// on every start — including a re-fetch of the very same event, which is
|
||||
// the steady state once an id has been kept. Which *content* the entry
|
||||
// holds is the tie-break's business: a same-second sibling with a higher
|
||||
// id loses that, while the clock still moves.
|
||||
if newer || same_version {
|
||||
entry.fetched_at = audit::now();
|
||||
stored = true;
|
||||
}
|
||||
if newer || (same_version && tie_ours) {
|
||||
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;
|
||||
if let Some(id) = id {
|
||||
entry.kind0_id = Some(id.to_hex());
|
||||
}
|
||||
}
|
||||
}
|
||||
if stored {
|
||||
@@ -265,6 +339,12 @@ impl Profiles {
|
||||
/// names no write/unmarked relay — a genuine clear), while `created_at = 0`
|
||||
/// means "nothing was found" and only moves the clock, so a transient miss
|
||||
/// cannot wipe a working outbox.
|
||||
///
|
||||
/// Strictly newer here (unlike [`Profiles::put_metadata`]): the attempt clock
|
||||
/// advances on every call regardless, so refusing an equal version strands
|
||||
/// nothing *today*. If a field derived from the kind-10002 is ever added, this
|
||||
/// must become `>=` at the same time, or it would strand exactly the way
|
||||
/// `nip05` did on kind-0.
|
||||
pub fn put_relay_list(
|
||||
&self,
|
||||
key: &PublicKey,
|
||||
@@ -350,6 +430,18 @@ fn resolve_profile_relays(profile_env: Option<&str>, relays_env: Option<&str>) -
|
||||
})
|
||||
}
|
||||
|
||||
/// What a fetch did for one identity — what the view that asked for it reports.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum FetchOutcome {
|
||||
/// A profile arrived and changed what the cache holds.
|
||||
Updated,
|
||||
/// The cache already held what the relays answered with (or holds something
|
||||
/// newer than they served).
|
||||
UpToDate,
|
||||
/// No relay served a kind-0 for this identity.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// What one identity needs this call, decided from its cache before anything is
|
||||
/// written.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -443,16 +535,21 @@ pub async fn fetch(
|
||||
directory: Vec<String>,
|
||||
keys: Vec<PublicKey>,
|
||||
profiles: Profiles,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
) -> Result<Vec<(PublicKey, FetchOutcome)>, Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
if keys.is_empty() {
|
||||
return Ok(());
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let directory_urls: Vec<RelayUrl> = directory
|
||||
.iter()
|
||||
.filter_map(|relay| RelayUrl::parse(relay).ok())
|
||||
.collect();
|
||||
if directory_urls.is_empty() {
|
||||
return Ok(());
|
||||
// Nothing to ask. The honest answer for every identity is that nothing was
|
||||
// found, rather than a silent success.
|
||||
return Ok(keys
|
||||
.iter()
|
||||
.map(|key| (*key, FetchOutcome::NotFound))
|
||||
.collect());
|
||||
}
|
||||
|
||||
// Only these keys may end up in the cache: a relay cannot answer for somebody
|
||||
@@ -492,8 +589,33 @@ pub async fn fetch(
|
||||
}
|
||||
ensure_connected(&client, &cached_outbox, &mut added).await;
|
||||
|
||||
let mut newest: HashMap<PublicKey, (Timestamp, Profile)> = HashMap::new();
|
||||
let mut newest_lists: HashMap<PublicKey, (Timestamp, Event)> = HashMap::new();
|
||||
// What the cache shows for each identity *before* the waves, so the outcome can
|
||||
// say whether anything actually changed. Only the fields the user sees: a moved
|
||||
// clock, or `put_metadata` accepting the version we already had, is not an
|
||||
// update. The NIP-05 side is the *declared* address — its verdict arrives later,
|
||||
// from `ensure_nip05`'s own round trip, so a verification flip on its own is not
|
||||
// an update here.
|
||||
// A cache entry with no content at all (one `put_relay_list` created for the
|
||||
// attempt clock, say) compares equal to no entry: both mean "we know nothing
|
||||
// about this identity".
|
||||
type Shown = (Option<String>, Option<String>, Option<String>);
|
||||
let content = |profile: &Profile| -> Shown {
|
||||
(
|
||||
profile.display_name.clone(),
|
||||
profile.picture.clone(),
|
||||
profile.nip05.clone(),
|
||||
)
|
||||
};
|
||||
let shown = |profile: Option<Profile>| -> Shown {
|
||||
profile.map(|profile| content(&profile)).unwrap_or_default()
|
||||
};
|
||||
let before: HashMap<PublicKey, Shown> = keys
|
||||
.iter()
|
||||
.map(|key| (*key, shown(profiles.get(key))))
|
||||
.collect();
|
||||
|
||||
let mut newest: Newest<Profile> = Newest::new();
|
||||
let mut newest_lists: Newest<Event> = Newest::new();
|
||||
|
||||
// Wave 1 — discovery: the kind-10002, and a profile in case the identity
|
||||
// publishes nowhere of its own.
|
||||
@@ -515,7 +637,7 @@ pub async fn fetch(
|
||||
continue;
|
||||
}
|
||||
match newest_lists.get(key) {
|
||||
Some((at, event)) => profiles.put_relay_list(
|
||||
Some((at, _, event)) => profiles.put_relay_list(
|
||||
key,
|
||||
write_relays(event, &directory_set),
|
||||
at.as_secs() as i64,
|
||||
@@ -575,23 +697,36 @@ pub async fn fetch(
|
||||
}
|
||||
|
||||
let _ = client.disconnect().await;
|
||||
Ok(())
|
||||
Ok(keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
let now = shown(profiles.get(key));
|
||||
let updated = now != *before.get(key).expect("every key was snapshotted");
|
||||
let saw = newest.contains_key(key);
|
||||
let has_content = now.0.is_some() || now.1.is_some() || now.2.is_some();
|
||||
let outcome = if updated {
|
||||
FetchOutcome::Updated
|
||||
} else if saw || has_content {
|
||||
FetchOutcome::UpToDate
|
||||
} else {
|
||||
FetchOutcome::NotFound
|
||||
};
|
||||
(*key, outcome)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Store the newest kind-0 for `key` from the merge map; `false` when there is
|
||||
/// none, or when it is not newer than the cached one.
|
||||
fn store_metadata(
|
||||
profiles: &Profiles,
|
||||
key: &PublicKey,
|
||||
newest: &HashMap<PublicKey, (Timestamp, Profile)>,
|
||||
) -> bool {
|
||||
/// none, or when it is older than the cached one.
|
||||
fn store_metadata(profiles: &Profiles, key: &PublicKey, newest: &Newest<Profile>) -> bool {
|
||||
match newest.get(key) {
|
||||
Some((at, profile)) => profiles.put_metadata(
|
||||
Some((at, id, profile)) => profiles.put_metadata(
|
||||
key,
|
||||
profile.display_name.clone(),
|
||||
profile.picture.clone(),
|
||||
profile.nip05.clone(),
|
||||
at.as_secs() as i64,
|
||||
Some(*id),
|
||||
),
|
||||
None => false,
|
||||
}
|
||||
@@ -602,8 +737,8 @@ async fn collect(
|
||||
client: &Client,
|
||||
targets: Vec<(RelayUrl, Vec<Filter>)>,
|
||||
requested: &HashSet<PublicKey>,
|
||||
newest: &mut HashMap<PublicKey, (Timestamp, Profile)>,
|
||||
newest_lists: &mut HashMap<PublicKey, (Timestamp, Event)>,
|
||||
newest: &mut Newest<Profile>,
|
||||
newest_lists: &mut Newest<Event>,
|
||||
) {
|
||||
if targets.is_empty() {
|
||||
return;
|
||||
@@ -691,8 +826,8 @@ async fn ensure_connected(client: &Client, urls: &[RelayUrl], added: &mut HashSe
|
||||
fn consider(
|
||||
event: &Event,
|
||||
requested: &HashSet<PublicKey>,
|
||||
newest: &mut HashMap<PublicKey, (Timestamp, Profile)>,
|
||||
newest_lists: &mut HashMap<PublicKey, (Timestamp, Event)>,
|
||||
newest: &mut Newest<Profile>,
|
||||
newest_lists: &mut Newest<Event>,
|
||||
) {
|
||||
if !requested.contains(&event.pubkey) {
|
||||
return;
|
||||
@@ -712,13 +847,24 @@ fn consider(
|
||||
}
|
||||
}
|
||||
|
||||
/// The newest answer per author: its `created_at`, the event id that settled a
|
||||
/// tie, and the value derived from its content.
|
||||
type Newest<T> = HashMap<PublicKey, (Timestamp, EventId, T)>;
|
||||
|
||||
/// Keep the newest `value` for the event's author.
|
||||
fn keep_newest<T>(newest: &mut HashMap<PublicKey, (Timestamp, T)>, event: &Event, value: T) {
|
||||
match newest.get(&event.pubkey) {
|
||||
Some((at, _)) if *at >= event.created_at => {}
|
||||
_ => {
|
||||
newest.insert(event.pubkey, (event.created_at, value));
|
||||
}
|
||||
///
|
||||
/// Equal `created_at`s are settled the way NIP-01 settles replaceable events: the
|
||||
/// **lowest event id** wins. Without that, two same-second versions of a profile
|
||||
/// (an author editing twice in a second, or a relay replaying one of them) would
|
||||
/// be chosen by arrival order, so what the cache holds could differ from fetch to
|
||||
/// fetch — one of them, for instance, having no name in it.
|
||||
fn keep_newest<T>(newest: &mut Newest<T>, event: &Event, value: T) {
|
||||
let replace = match newest.get(&event.pubkey) {
|
||||
Some((at, id, _)) => event.created_at > *at || (event.created_at == *at && event.id < *id),
|
||||
None => true,
|
||||
};
|
||||
if replace {
|
||||
newest.insert(event.pubkey, (event.created_at, event.id, value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -803,6 +949,7 @@ mod tests {
|
||||
Some(" https://example.com/a.png ".to_string()),
|
||||
crate::store::nip05::normalise("Alice@Example.org"),
|
||||
Timestamp::now().as_secs() as i64,
|
||||
None,
|
||||
));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Alice"));
|
||||
assert_eq!(
|
||||
@@ -818,7 +965,7 @@ mod tests {
|
||||
123,
|
||||
);
|
||||
store.note_recovery(&key, 456);
|
||||
store.set_nip05(&key, "alice@example.org", true, 789);
|
||||
store.set_nip05(&key, "alice@example.org", Some(true), 789);
|
||||
|
||||
// Survives a reload, every field and all three clocks.
|
||||
let reloaded = Profiles::at(path);
|
||||
@@ -870,7 +1017,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, None, 10);
|
||||
store.put_metadata(&key, Some(" ".to_string()), None, None, 10, None);
|
||||
assert!(store.display_name(&key).is_none());
|
||||
}
|
||||
|
||||
@@ -894,7 +1041,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} ")), None, 10);
|
||||
store.put_metadata(&key, None, Some(format!(" {long} ")), None, 10, None);
|
||||
assert_eq!(
|
||||
store.picture(&key).unwrap().chars().count(),
|
||||
MAX_PICTURE_LEN
|
||||
@@ -1047,8 +1194,8 @@ mod tests {
|
||||
let requested: HashSet<PublicKey> = [keys.public_key()].into_iter().collect();
|
||||
let now = audit::now();
|
||||
|
||||
let mut newest: HashMap<PublicKey, (Timestamp, Profile)> = HashMap::new();
|
||||
let mut lists: HashMap<PublicKey, (Timestamp, Event)> = HashMap::new();
|
||||
let mut newest: Newest<Profile> = Newest::new();
|
||||
let mut lists: Newest<Event> = Newest::new();
|
||||
|
||||
let newer = signed(
|
||||
&keys,
|
||||
@@ -1067,16 +1214,16 @@ mod tests {
|
||||
consider(&newer, &requested, &mut newest, &mut lists);
|
||||
consider(&older, &requested, &mut newest, &mut lists);
|
||||
assert_eq!(
|
||||
newest[&keys.public_key()].1.display_name.as_deref(),
|
||||
newest[&keys.public_key()].2.display_name.as_deref(),
|
||||
Some("New")
|
||||
);
|
||||
|
||||
// Arriving first does not make an older event win either.
|
||||
let mut newest: HashMap<PublicKey, (Timestamp, Profile)> = HashMap::new();
|
||||
let mut newest: Newest<Profile> = Newest::new();
|
||||
consider(&older, &requested, &mut newest, &mut lists);
|
||||
consider(&newer, &requested, &mut newest, &mut lists);
|
||||
assert_eq!(
|
||||
newest[&keys.public_key()].1.display_name.as_deref(),
|
||||
newest[&keys.public_key()].2.display_name.as_deref(),
|
||||
Some("New")
|
||||
);
|
||||
|
||||
@@ -1095,28 +1242,34 @@ mod tests {
|
||||
);
|
||||
consider(&ahead, &requested, &mut newest, &mut lists);
|
||||
assert_eq!(
|
||||
newest[&keys.public_key()].1.display_name.as_deref(),
|
||||
newest[&keys.public_key()].2.display_name.as_deref(),
|
||||
Some("New")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metadata_is_stored_once_and_never_walked_backwards() {
|
||||
fn an_older_profile_never_walks_the_cache_backwards() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
|
||||
assert!(store.put_metadata(&key, Some("Alice".to_string()), None, None, 200));
|
||||
assert!(store.put_metadata(&key, Some("Alice".to_string()), None, None, 200, None));
|
||||
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, None, 200));
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, None, 100));
|
||||
// Older: refused — a relay replaying an old version changes nothing.
|
||||
assert!(!store.put_metadata(&key, Some("Mallory".to_string()), None, None, 100, None));
|
||||
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()), None, 300));
|
||||
// A genuinely newer one replaces both fields — including clearing them.
|
||||
assert!(store.put_metadata(
|
||||
&key,
|
||||
None,
|
||||
Some("https://x/i.png".to_string()),
|
||||
None,
|
||||
300,
|
||||
None
|
||||
));
|
||||
assert!(store.display_name(&key).is_none());
|
||||
assert_eq!(store.picture(&key).as_deref(), Some("https://x/i.png"));
|
||||
|
||||
@@ -1157,6 +1310,189 @@ mod tests {
|
||||
assert_eq!(stored(&store, &key).relays_recovery_at, 0);
|
||||
}
|
||||
|
||||
/// A cache entry written before a field existed must be able to learn it: the
|
||||
/// same event (an equal `created_at`) is the same version, not a stale one.
|
||||
#[test]
|
||||
fn an_equal_version_still_fills_in_a_new_field() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let key = key();
|
||||
|
||||
assert!(store.put_metadata(&key, Some("Alice".to_string()), None, None, 100, None));
|
||||
assert_eq!(store.declared_nip05(&key), None);
|
||||
|
||||
// The same event again, this time carrying the address the older release
|
||||
// had no field for.
|
||||
assert!(
|
||||
store.put_metadata(
|
||||
&key,
|
||||
Some("Alice".to_string()),
|
||||
None,
|
||||
crate::store::nip05::normalise("alice@example.org"),
|
||||
100,
|
||||
None
|
||||
),
|
||||
"an equal version is stored, not refused"
|
||||
);
|
||||
assert_eq!(
|
||||
store.declared_nip05(&key).as_deref(),
|
||||
Some("alice@example.org")
|
||||
);
|
||||
|
||||
// An *older* version still never wins.
|
||||
assert!(!store.put_metadata(
|
||||
&key,
|
||||
Some("Mallory".to_string()),
|
||||
None,
|
||||
crate::store::nip05::normalise("mallory@example.org"),
|
||||
99,
|
||||
None,
|
||||
));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Alice"));
|
||||
assert_eq!(
|
||||
store.declared_nip05(&key).as_deref(),
|
||||
Some("alice@example.org")
|
||||
);
|
||||
}
|
||||
|
||||
/// Two versions in the same second are settled by the lower event id — the way
|
||||
/// NIP-01 settles replaceable events — so the winner does not depend on which
|
||||
/// relay answered first.
|
||||
#[test]
|
||||
fn an_equal_timestamp_is_settled_by_the_lower_event_id() {
|
||||
let keys = Keys::generate();
|
||||
let requested: HashSet<PublicKey> = [keys.public_key()].into_iter().collect();
|
||||
let mine = signed(
|
||||
&keys,
|
||||
Kind::Metadata,
|
||||
Vec::new(),
|
||||
r#"{"display_name":"A"}"#,
|
||||
500,
|
||||
);
|
||||
let other = signed(
|
||||
&keys,
|
||||
Kind::Metadata,
|
||||
Vec::new(),
|
||||
r#"{"display_name":"B"}"#,
|
||||
500,
|
||||
);
|
||||
assert_ne!(mine.id, other.id);
|
||||
let (low, high) = if mine.id < other.id {
|
||||
(&mine, &other)
|
||||
} else {
|
||||
(&other, &mine)
|
||||
};
|
||||
|
||||
for (first, second) in [(low, high), (high, low)] {
|
||||
let mut newest: Newest<Profile> = Newest::new();
|
||||
let mut lists: Newest<Event> = Newest::new();
|
||||
consider(first, &requested, &mut newest, &mut lists);
|
||||
consider(second, &requested, &mut newest, &mut lists);
|
||||
assert_eq!(
|
||||
newest[&keys.public_key()].1,
|
||||
low.id,
|
||||
"the lower id wins, whichever order the two arrive in"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache settles an equal version by the lower id as well, so a relay that
|
||||
/// serves only one of two same-second versions cannot make it flip between
|
||||
/// fetches.
|
||||
#[test]
|
||||
fn the_cache_keeps_the_lower_id_for_an_equal_timestamp() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
let keys = Keys::generate();
|
||||
let key = keys.public_key();
|
||||
let one = signed(
|
||||
&keys,
|
||||
Kind::Metadata,
|
||||
Vec::new(),
|
||||
r#"{"display_name":"One"}"#,
|
||||
100,
|
||||
)
|
||||
.id;
|
||||
let two = signed(
|
||||
&keys,
|
||||
Kind::Metadata,
|
||||
Vec::new(),
|
||||
r#"{"display_name":"Two"}"#,
|
||||
100,
|
||||
)
|
||||
.id;
|
||||
let (low, high) = if one < two { (one, two) } else { (two, one) };
|
||||
|
||||
// The higher id first: the lower one still takes the entry.
|
||||
assert!(store.put_metadata(&key, Some("High".to_string()), None, None, 100, Some(high)));
|
||||
assert!(store.put_metadata(&key, Some("Low".to_string()), None, None, 100, Some(low)));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Low"));
|
||||
|
||||
// …and a higher id arriving later cannot take the content back. It is still
|
||||
// an *answer* — the clock moves — just not the winning one.
|
||||
assert!(store.put_metadata(
|
||||
&key,
|
||||
Some("High again".to_string()),
|
||||
None,
|
||||
None,
|
||||
100,
|
||||
Some(high)
|
||||
));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Low"));
|
||||
|
||||
// A genuinely newer version still wins.
|
||||
assert!(store.put_metadata(&key, Some("Newer".to_string()), None, None, 101, Some(high)));
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Newer"));
|
||||
}
|
||||
|
||||
/// Re-fetching the *same* event must still count as an answer: that is the
|
||||
/// steady state once an id is kept, and `fetched_at` is what stops
|
||||
/// `needs_refresh` from re-fetching an unchanged profile on every start.
|
||||
#[test]
|
||||
fn a_refetch_of_the_same_version_still_refreshes_the_clock() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("regent-profiles-stale-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("profiles.json");
|
||||
let keys = Keys::generate();
|
||||
let key = keys.public_key();
|
||||
let event = signed(
|
||||
&keys,
|
||||
Kind::Metadata,
|
||||
Vec::new(),
|
||||
r#"{"display_name":"Same"}"#,
|
||||
100,
|
||||
);
|
||||
|
||||
// A cache entry aged well past `REFRESH_AFTER`, holding exactly this event.
|
||||
std::fs::write(
|
||||
&path,
|
||||
format!(
|
||||
r#"{{"{}":{{"display_name":"Same","kind0_at":100,"kind0_id":"{}","fetched_at":1}}}}"#,
|
||||
key.to_hex(),
|
||||
event.id.to_hex()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let store = Profiles::at(path.clone());
|
||||
assert!(store.needs_refresh(&key), "aged out");
|
||||
|
||||
assert!(
|
||||
store.put_metadata(
|
||||
&key,
|
||||
Some("Same".to_string()),
|
||||
None,
|
||||
None,
|
||||
100,
|
||||
Some(event.id)
|
||||
),
|
||||
"the same version is still an answer"
|
||||
);
|
||||
assert!(!store.needs_refresh(&key), "and it refreshes the clock");
|
||||
assert_eq!(store.display_name(&key).as_deref(), Some("Same"));
|
||||
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nip05_address_is_shown_only_while_it_is_verified() {
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
@@ -1168,7 +1504,8 @@ mod tests {
|
||||
Some("Alice".to_string()),
|
||||
None,
|
||||
crate::store::nip05::normalise("Alice@Example.org"),
|
||||
100
|
||||
100,
|
||||
None,
|
||||
));
|
||||
assert_eq!(
|
||||
store.declared_nip05(&key).as_deref(),
|
||||
@@ -1179,15 +1516,27 @@ mod tests {
|
||||
|
||||
// The domain confirmed it, just now.
|
||||
let now = audit::now();
|
||||
store.set_nip05(&key, "alice@example.org", true, now);
|
||||
store.set_nip05(&key, "alice@example.org", Some(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);
|
||||
store.set_nip05(
|
||||
&key,
|
||||
"alice@example.org",
|
||||
Some(true),
|
||||
now - REFRESH_AFTER - 60,
|
||||
);
|
||||
assert_eq!(store.nip05(&key).as_deref(), Some("alice@example.org"));
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// No answer (the domain was unreachable) is not a denial: the confirmed
|
||||
// address stays, and the attempt is still recorded so it is not retried
|
||||
// on every start.
|
||||
store.set_nip05(&key, "alice@example.org", None, now);
|
||||
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,
|
||||
@@ -1195,24 +1544,63 @@ mod tests {
|
||||
None,
|
||||
crate::store::nip05::normalise("mallory@example.org"),
|
||||
300,
|
||||
None,
|
||||
);
|
||||
store.set_nip05(&key, "alice@example.org", true, 400);
|
||||
store.set_nip05(&key, "alice@example.org", Some(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.
|
||||
// A manual re-fetch loosens all three gates for that key on demand — and
|
||||
// invents no entry for a key that has none.
|
||||
let cold = Keys::generate().public_key();
|
||||
store.mark_profile_stale(&cold);
|
||||
assert!(store.get(&cold).is_none(), "no empty entry is written");
|
||||
|
||||
// Give the key both clocks and an outbox first: otherwise the assertions
|
||||
// below would hold even if `mark_profile_stale` did nothing.
|
||||
store.put_relay_list(&key, vec!["wss://outbox.example".to_string()], 1_000, 2_000);
|
||||
store.note_recovery(&key, 3_000);
|
||||
let settled = stored(&store, &key);
|
||||
assert_eq!(settled.relays_checked_at, 2_000);
|
||||
assert_eq!(settled.relays_recovery_at, 3_000);
|
||||
|
||||
// Settle the current (mallory) address so the NIP-05 assertion below
|
||||
// discriminates — otherwise it is already due and proves nothing.
|
||||
store.set_nip05(&key, "mallory@example.org", None, audit::now());
|
||||
assert!(!store.nip05_needs_check(&key), "settled first");
|
||||
|
||||
store.mark_profile_stale(&key);
|
||||
let stale = stored(&store, &key);
|
||||
assert_eq!(stale.relays_checked_at, 0, "discovery is due again");
|
||||
assert_eq!(stale.relays_recovery_at, 0, "the fallback is due again");
|
||||
assert!(
|
||||
store.nip05_needs_check(&key),
|
||||
"the NIP-05 check is due again"
|
||||
);
|
||||
assert_eq!(
|
||||
stale.write_relays,
|
||||
["wss://outbox.example"],
|
||||
"the cached outbox itself is untouched"
|
||||
);
|
||||
|
||||
// A definitive non-match 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);
|
||||
store.set_nip05(&key, "mallory@example.org", Some(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);
|
||||
store.set_nip05(
|
||||
&key,
|
||||
"mallory@example.org",
|
||||
Some(false),
|
||||
now - REFRESH_AFTER - 60,
|
||||
);
|
||||
assert!(store.nip05_needs_check(&key));
|
||||
|
||||
// An unparseable declaration never reaches the cache.
|
||||
@@ -1222,6 +1610,7 @@ mod tests {
|
||||
None,
|
||||
crate::store::nip05::normalise("not an address"),
|
||||
600,
|
||||
None,
|
||||
);
|
||||
assert!(store.declared_nip05(&key).is_none());
|
||||
assert!(!store.nip05_needs_check(&key));
|
||||
@@ -1346,13 +1735,21 @@ mod tests {
|
||||
}
|
||||
|
||||
let store = Profiles::at(PathBuf::new());
|
||||
fetch(
|
||||
let outcomes = fetch(
|
||||
vec![directory.url.clone()],
|
||||
vec![first.public_key(), second.public_key()],
|
||||
store.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
vec![
|
||||
(first.public_key(), FetchOutcome::Updated),
|
||||
(second.public_key(), FetchOutcome::Updated),
|
||||
],
|
||||
"both identities got a profile from the directory and their outbox"
|
||||
);
|
||||
|
||||
for (keys, name) in [(&first, "First"), (&second, "Second")] {
|
||||
assert_eq!(
|
||||
@@ -1392,13 +1789,19 @@ mod tests {
|
||||
&[],
|
||||
);
|
||||
}
|
||||
fetch(
|
||||
let outcomes = fetch(
|
||||
vec![directory.url.clone()],
|
||||
vec![first.public_key(), second.public_key()],
|
||||
store.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
outcomes
|
||||
.iter()
|
||||
.all(|(_, outcome)| *outcome == FetchOutcome::Updated),
|
||||
"the outbox's newer profile is an update"
|
||||
);
|
||||
for (keys, name) in [(&first, "First"), (&second, "Second")] {
|
||||
assert_eq!(
|
||||
store.display_name(&keys.public_key()).as_deref(),
|
||||
@@ -1407,6 +1810,36 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
// Nothing newer anywhere: the relays answer with the version we hold, and
|
||||
// the fetch says so rather than claiming an update.
|
||||
let outcomes = fetch(
|
||||
vec![directory.url.clone()],
|
||||
vec![first.public_key(), second.public_key()],
|
||||
store.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
outcomes
|
||||
.iter()
|
||||
.all(|(_, outcome)| *outcome == FetchOutcome::UpToDate),
|
||||
"an unchanged profile is up to date"
|
||||
);
|
||||
|
||||
// An identity nobody publishes: no answer at all.
|
||||
let stranger = Keys::generate();
|
||||
let outcomes = fetch(
|
||||
vec![own.url.clone()],
|
||||
vec![stranger.public_key()],
|
||||
store.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
vec![(stranger.public_key(), FetchOutcome::NotFound)]
|
||||
);
|
||||
|
||||
// Warm path, part 2 — the outbox can also serve a dead directory.
|
||||
for (keys, name) in [(&first, "First"), (&second, "Second")] {
|
||||
publish(
|
||||
@@ -1420,13 +1853,19 @@ mod tests {
|
||||
}
|
||||
drop(directory);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
fetch(
|
||||
let outcomes = fetch(
|
||||
vec!["ws://127.0.0.1:10590".to_string()],
|
||||
vec![first.public_key(), second.public_key()],
|
||||
store.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
outcomes
|
||||
.iter()
|
||||
.all(|(_, outcome)| *outcome == FetchOutcome::Updated),
|
||||
"the newest profile on the identity's own relay is an update"
|
||||
);
|
||||
for (keys, name) in [(&first, "First"), (&second, "Second")] {
|
||||
assert_eq!(
|
||||
store.display_name(&keys.public_key()).as_deref(),
|
||||
|
||||
@@ -23,6 +23,7 @@ use libadwaita as adw;
|
||||
|
||||
use crate::runtime;
|
||||
use crate::state::AppState;
|
||||
use crate::store::profiles::FetchOutcome;
|
||||
use crate::ui::{approval, plain};
|
||||
|
||||
/// Handles the callbacks need; cloned per closure.
|
||||
@@ -251,6 +252,39 @@ fn key_row(state: &Rc<AppState>, handles: &Handles, live: &LiveRows, hex: &str)
|
||||
popover.set_child(Some(&menu));
|
||||
|
||||
if let Some(public_key) = public_key {
|
||||
// First, because it is the one item that changes what the row shows: the
|
||||
// automatic fetch only picks up a profile older than a day.
|
||||
let refetch = plain::menu_button("Re-fetch profile");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
refetch.connect_clicked(move |_| {
|
||||
// The fetch reports back on the main loop, so the "checking" toast is
|
||||
// followed by what it actually found.
|
||||
//
|
||||
// The outcome *dismisses* the checking toast rather than outranking
|
||||
// it: libadwaita shows one toast at a time, and a high-priority one
|
||||
// only pushes the current toast back into the queue — the "checking"
|
||||
// message would return, stale, after the answer had been read.
|
||||
let overlay = handles.overlay.clone();
|
||||
let checking_toast = adw::Toast::new("Checking the relays for this profile…");
|
||||
let done_toast = checking_toast.clone();
|
||||
let checking = state.refetch_profile(public_key, move |outcome| {
|
||||
done_toast.dismiss();
|
||||
overlay.add_toast(adw::Toast::new(fetched_toast(outcome)));
|
||||
});
|
||||
if checking {
|
||||
handles.overlay.add_toast(checking_toast);
|
||||
} else {
|
||||
// A fetch for this key is already running (this profile, or the
|
||||
// automatic one) — asking again would only repeat it.
|
||||
handles.overlay.add_toast(adw::Toast::new(
|
||||
"Already checking the relays for this profile",
|
||||
));
|
||||
}
|
||||
});
|
||||
}
|
||||
menu.append(&refetch);
|
||||
|
||||
let rename = plain::menu_button("Rename…");
|
||||
{
|
||||
let (handles, state) = (handles.clone(), Rc::clone(state));
|
||||
@@ -720,6 +754,17 @@ fn present_remove(handles: Handles, state: Rc<AppState>, public_key: PublicKey,
|
||||
dialog.present(toplevel(&handles).as_ref());
|
||||
}
|
||||
|
||||
/// What a manual re-fetch says when it lands. Its own function so the three
|
||||
/// answers are one thing to read (and one thing to test) rather than strings
|
||||
/// scattered through the menu wiring.
|
||||
fn fetched_toast(outcome: FetchOutcome) -> &'static str {
|
||||
match outcome {
|
||||
FetchOutcome::Updated => "Profile updated",
|
||||
FetchOutcome::UpToDate => "Profile is up to date",
|
||||
FetchOutcome::NotFound => "No profile found",
|
||||
}
|
||||
}
|
||||
|
||||
/// 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).
|
||||
@@ -751,6 +796,16 @@ fn report_error(handles: &Handles, message: &str) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_manual_refetch_has_three_things_to_say() {
|
||||
assert_eq!(fetched_toast(FetchOutcome::Updated), "Profile updated");
|
||||
assert_eq!(
|
||||
fetched_toast(FetchOutcome::UpToDate),
|
||||
"Profile is up to date"
|
||||
);
|
||||
assert_eq!(fetched_toast(FetchOutcome::NotFound), "No profile found");
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
Reference in new issue
Block a user