Files
buzz/mobile/lib/shared/profile/user_cache_provider.dart
Tom Brow 985de41f14 feat(mobile): show NIP-FI verified names (#8858)
Stacked on #8700. Review only the last commit until #8700 merges.

NIP-FI relays can publish a relay-signed verified name for each member
who signs in with an organization assertion (kind 30382, specified in
#8745 and implemented in the relay in #8774). Desktop shows these names
in block/buzz-app#2005. Mobile showed only self-declared kind 0 names,
so a verified Block name looked no different from one anyone could set.

This adds verified names to mobile, following the spec and the desktop
client's validation rules.

**What people see**

- A verified member's name is the issuer-verified display name wherever
mobile resolves names through identity names (message headers, threads,
DM titles, member lists).
- Message headers and the profile sheet show a verification mark. The
profile sheet also shows the full name when present, "Verified by
{issuer}", "Last verified {time ago}", and marks the record as cached
when it hasn't been reconciled with the relay on this connection.
Verification is described as historical, never as current access.
- Nothing changes on relays that don't advertise
`federated_identity.public_profile`, and marks never come from kind 0 or
NIP-05.

**How it works**

- NIP-11 discovery decides whether marks may show: a successful response
without `public_profile` hides them (cached records are kept), and a
failed or malformed response keeps the last state. Discovery refreshes
on connect and every 5 minutes while names are tracked.
- Subjects are tracked as the profile cache resolves them, and fetched
in batches of up to 128 with `{kinds:[30382], authors:[self],
#d:[...]}`. Live updates and retractions apply on the same subscription.
A full batch that omits subjects is not treated as proof they have no
record.
- Each event's id and signature are verified (in an isolate) before use,
and it must be authored by the community's NIP-11 `self` key with
exactly the specified tags (plus the optional `full_name` the relay
emits). Names follow the spec's NFC and character rules; `unorm_dart`
(MIT, pure Dart) is added for the NFC check because Dart has no built-in
normalizer.
- The cache is per community and is cleared when the relay's `self` key
changes.

**Not yet covered**

- Some surfaces still read the kind 0 name directly: the members sheet
initial, and search and inbox rows. The mark isn't shown in search rows,
inbox rows, or member tiles. (The mention picker now matches, ranks and
inserts by the verified name and shows the mark, and it also offers
cached verified people outside the channel whose kind 0 name differs.)
- NIP-FI says clients MUST show `issuer_label` beside every verified
name. Here it appears only in the mark's tooltip and accessibility label
and in the profile sheet, and verified names reaching DM titles and
member lists show no mark or issuer. Follow-up: show the issuer inline
wherever a verified name is shown.
- Live updates are coalesced to the newest per subject before signature
proof, ordered by unverified `created_at`/`id`. Only a misbehaving relay
could exploit this (the subscription is `authors:[self]`), and it could
already withhold events. Follow-up: prove first, then coalesce among
valid events.
- The verified `username` isn't shown beside the name in message headers
(the NIP-05 handle still is).
- Collision qualification relies on the existing name-disambiguation
policy rather than the spec's exact self-declared-name rule.

### Validation

Added tests:

- Validation: discovery enabled, disabled and malformed; wrong author;
mismatched or duplicate `d`/`p`; extra or duplicate tags; invalid
usernames; non-NFC and whitespace-padded names; `verified_at` after
`created_at`; bad signatures; retractions.
- Directory: discovery gating, batching, truncation, live retraction,
reconnect reconciliation, and disable hiding cached records.
- Directory failures: a pre-EOSE flood, failed proof retried on refresh,
oversized events (by total size, id or signature) dropped before proof,
live events coalesced, a retry before or after the first EOSE never
proving absence, a retry during proof not promoting records to checked,
and a newer signed malformed projection clearing the older one.
- Mention picker: a verified name finds, ranks and inserts the verified
person; the self-declared name still finds them; a verified person
outside the channel is found by verified name even when an impostor
copies that name into kind 0.
- Identity names: a verified name outranks the kind 0 name.
- UI: the mark in message headers and the profile sheet details, no mark
for a cached record, and a single accessible label.

Full `mobile-check` and `mobile-test` pass.

**Live relay (checked 2026-11-01):** not yet run end to end.

- Staging now advertises the feature: the bb-block staging relay's
NIP-11 (`buzz.block.builderlabstaging.xyz`) has
`federated_identity.public_profile` with `kind: 30382` and
`multiple_issuers: false`, bound to `self` `f7f4df94…dcf1`. So #8774 is
deployed and enabled there. The other staging relays
(`communities.public.builderlabstaging.xyz` and its `team.` host)
advertise no `federated_identity`, and the client shows nothing on them.
- I couldn't confirm that real 30382 events are served or render them.
The relay requires NIP-42 auth plus a client-attached NIP-FI assertion,
which needs an interactive Builderlab/Okta sign-in on a physical device.
SSO doesn't work in the iOS simulator. The remaining step is a device
run signed in to the staging Block community, with screenshots of a
verified name, its mark and its details.

**Shipping behind discovery gating:** this is safe. The client reads and
shows verified names only when a successful NIP-11 discovery advertises
`public_profile` bound to `self`. It accepts only kind 30382 events
signed by that key that pass id and signature verification and strict
shape checks. On every relay without the feature, which is every relay
but bb-block staging today, it shows nothing new and changes no names. A
failed or malformed discovery never turns the feature on, and it marks
cached records as unchecked, which hides their mark. The subscription
and reconciliation paths are covered by the tests above, and Carl's
review reran retry probes through the real `RelaySessionNotifier`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-01 15:51:25 -08:00

295 lines
10 KiB
Dart

import 'dart:async';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../relay/relay.dart';
import '../verified_profiles/verified_profile_directory.dart';
import 'user_profile.dart';
import 'profile_event_parser.dart';
/// In-memory cache of user profiles, fetched in batches from the relay.
///
/// Lookups requested via [get] or [preload] are coalesced into a single
/// kind:0 batch query (NIP-01 `authors` filter) every 50ms. Larger requests
/// drain sequentially in pages bounded by the relay response limit.
class UserCacheNotifier extends Notifier<Map<String, UserProfile>> {
// The relay clamps each history response to DEFAULT_MAX_PAGE_LIMIT (1000).
static const _maximumProfilesPerQuery = 1000;
final Set<String> _pending = {};
final Map<String, ({int createdAt, String eventId})> _profileEventOrders = {};
int _generation = 0;
bool _flushInFlight = false;
Future<void> _verificationQueue = Future.value();
Timer? _batchTimer;
Completer<bool>? _batchCompleter;
@override
Map<String, UserProfile> build() {
ref.watch(relayConfigProvider);
_generation++;
_profileEventOrders.clear();
ref.onDispose(() {
_generation++;
_pending.clear();
_batchTimer?.cancel();
_batchTimer = null;
_batchCompleter?.complete(false);
_batchCompleter = null;
});
return {};
}
/// Request a profile for [pubkey]. Returns immediately from cache if
/// available, otherwise schedules a batch fetch.
UserProfile? get(String pubkey) {
_trackVerified([pubkey]);
final cached = state[pubkey.toLowerCase()];
if (cached != null) return cached;
_scheduleFetch(pubkey.toLowerCase());
return null;
}
/// Stores a profile that was fetched or updated outside the batch loader.
void put(UserProfile profile) {
state = {...state, profile.pubkey.toLowerCase(): profile};
}
/// Resolves profiles through verified batch admission.
///
/// Unlike [preload], failures propagate to callers whose result requires
/// profile hydration. Set [refreshCached] for a full revalidation; otherwise
/// cached profiles remain reusable within this scope.
Future<Map<String, UserProfile>> resolve(
List<String> pubkeys, {
bool refreshCached = false,
}) async {
final requested = pubkeys.map((pubkey) => pubkey.toLowerCase()).toSet();
_trackVerified(requested);
final toFetch = requested
.where((pubkey) => refreshCached || !state.containsKey(pubkey))
.toList();
final generation = _generation;
final session = ref.read(relaySessionProvider.notifier);
for (final batch in _profileQueryBatches(toFetch)) {
if (!_isCurrent(generation)) {
throw StateError('Profile request belongs to a retired cache');
}
final events = await session.fetchHistory(
NostrFilters.profilesBatch(batch),
);
if (!await _verifyAndMerge(events, generation)) {
throw StateError('Profile request belongs to a retired cache');
}
}
if (!_isCurrent(generation)) {
throw StateError('Profile request belongs to a retired cache');
}
return {for (final pubkey in requested) pubkey: ?state[pubkey]};
}
/// Preload profiles for a list of pubkeys (e.g. channel members).
/// Returns whether the batch completed successfully.
Future<bool> preload(List<String> pubkeys) {
_trackVerified(pubkeys);
final normalized = pubkeys.map((pk) => pk.toLowerCase()).toSet();
final alreadyPending = normalized.any(_pending.contains);
final uncached = normalized
.map((pk) => pk.toLowerCase())
.where((pk) => !state.containsKey(pk) && !_pending.contains(pk))
.toList();
if (uncached.isEmpty && !alreadyPending) return Future.value(true);
_pending.addAll(uncached);
final completer = _batchCompleter ??= Completer<bool>();
_scheduleBatch();
return completer.future;
}
/// Force-refresh profiles for identity-sensitive gates.
///
/// Unlike [preload], this fetches cached pubkeys too so stale human profiles
/// cannot be trusted after a verified agent-owner profile was published.
Future<bool> refresh(List<String> pubkeys) async {
final normalized = pubkeys
.map((pubkey) => pubkey.toLowerCase())
.where((pubkey) => pubkey.isNotEmpty)
.toSet()
.toList();
if (normalized.isEmpty) return true;
_trackVerified(normalized);
final generation = _generation;
try {
final session = ref.read(relaySessionProvider.notifier);
for (final batch in _profileQueryBatches(normalized)) {
if (!_isCurrent(generation)) return false;
final events = await session.fetchHistory(
NostrFilters.profilesBatch(batch),
);
if (!_isCurrent(generation)) return false;
if (!await _verifyAndMerge(events, generation)) return false;
}
return true;
} catch (_) {
return false;
}
}
/// Applies a live kind:0 profile event to the cache.
///
/// Surfaces that keep a participant-scoped profile subscription can use this
/// to update names and avatars without discarding the rest of the cache.
void cacheProfileEvent(NostrEvent event) {
if (event.kind != 0) return;
final updated = Map<String, UserProfile>.from(state);
if (_cacheProfileEvent(event, updated)) state = updated;
}
/// Anyone whose name is needed may also have a NIP-FI verified name.
void _trackVerified(Iterable<String> pubkeys) =>
ref.read(verifiedProfilesProvider.notifier).track(pubkeys);
void _scheduleFetch(String pubkey) {
if (state.containsKey(pubkey) || _pending.contains(pubkey)) return;
_pending.add(pubkey);
_batchCompleter ??= Completer<bool>();
_scheduleBatch();
}
Future<void> _flushPending() async {
_batchTimer = null;
if (_pending.isEmpty) return;
final pubkeys = _pending.toList();
_pending.clear();
final completer = _batchCompleter;
_batchCompleter = null;
_flushInFlight = true;
final generation = _generation;
var succeeded = false;
try {
final session = ref.read(relaySessionProvider.notifier);
var remaining = pubkeys.length;
for (final batch in _profileQueryBatches(pubkeys)) {
if (!_isCurrent(generation)) return;
final events = await session.fetchHistory(
NostrFilters.profilesBatch(batch),
);
if (!_isCurrent(generation)) return;
if (!await _verifyAndMerge(events, generation)) return;
remaining -= batch.length;
if (remaining == 0) {
// All requested pages are ready.
succeeded = true;
completer?.complete(true);
}
}
} catch (_) {
// Silently fail — non-gating callers will just show pubkeys.
} finally {
if (completer != null && !completer.isCompleted) {
completer.complete(succeeded);
}
_flushInFlight = false;
if (ref.mounted && _pending.isNotEmpty) _scheduleBatch();
}
}
Iterable<List<String>> _profileQueryBatches(List<String> pubkeys) sync* {
for (
var start = 0;
start < pubkeys.length;
start += _maximumProfilesPerQuery
) {
final end = start + _maximumProfilesPerQuery;
yield pubkeys.sublist(start, end < pubkeys.length ? end : pubkeys.length);
}
}
void _scheduleBatch() {
if (_flushInFlight) return;
_batchTimer ??= Timer(const Duration(milliseconds: 50), _flushPending);
}
Future<bool> _verifyAndMerge(List<NostrEvent> events, int generation) {
// Both refresh and preload share one worker slot. Keep this queue across
// community changes so an old worker cannot overlap a new community's job.
final result = _verificationQueue.then((_) async {
if (!_isCurrent(generation)) return false;
// Match live-cache admission before parsing. In particular, a malformed
// stale profile must not fail a refresh that previously ignored it.
final pending = [
for (final event in events)
if (event.kind == 0 &&
_isNewer(event.pubkey.toLowerCase(), event.createdAt, event.id))
event,
];
if (pending.isEmpty) return true;
final profiles = await ref.read(profileEventBatchParserProvider)(pending);
if (!_isCurrent(generation)) return false;
_mergeParsedProfiles(profiles);
return true;
});
// Callers receive the original error; only the sequencing tail recovers so
// one rejected batch does not poison all future refreshes.
_verificationQueue = result.then<void>(
(_) {},
onError: (Object error, StackTrace stack) {},
);
return result;
}
bool _isCurrent(int generation) => ref.mounted && generation == _generation;
void _mergeParsedProfiles(List<ParsedProfileEvent> profiles) {
// Read the current state after the isolate completes: live events and other
// batches may have installed newer profiles while this batch was parsing.
final updated = Map<String, UserProfile>.from(state);
var changed = false;
for (final parsed in profiles) {
if (!_isNewer(parsed.profile.pubkey, parsed.createdAt, parsed.eventId)) {
continue;
}
updated[parsed.profile.pubkey] = parsed.profile;
_profileEventOrders[parsed.profile.pubkey] = (
createdAt: parsed.createdAt,
eventId: parsed.eventId,
);
changed = true;
}
if (changed) state = updated;
}
bool _isNewer(String pubkey, int createdAt, String eventId) {
final current = _profileEventOrders[pubkey];
return current == null ||
createdAt > current.createdAt ||
(createdAt == current.createdAt &&
eventId.compareTo(current.eventId) < 0);
}
bool _cacheProfileEvent(NostrEvent event, Map<String, UserProfile> profiles) {
if (event.kind != 0) return false;
final pubkey = event.pubkey.toLowerCase();
if (!_isNewer(pubkey, event.createdAt, event.id)) return false;
profiles[pubkey] = parseProfileEvent(event).profile;
_profileEventOrders[pubkey] = (
createdAt: event.createdAt,
eventId: event.id,
);
return true;
}
}
/// Profile history parser, isolated from provider state so batch completion can
/// be delayed independently of relay delivery.
final profileEventBatchParserProvider =
Provider<Future<List<ParsedProfileEvent>> Function(List<NostrEvent>)>(
(ref) => parseProfileEventBatch,
);
final userCacheProvider =
NotifierProvider<UserCacheNotifier, Map<String, UserProfile>>(
UserCacheNotifier.new,
);