Files
buzz/mobile/lib/features/profile/user_profile_sheet.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

656 lines
25 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import '../../shared/widgets/profile_action_chip.dart';
import '../../shared/widgets/app_list_card.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:hooks_riverpod/misc.dart' show ProviderListenable;
import 'package:buzz/shared/theme/buzz_icons.dart';
import '../../shared/animated_avatar.dart';
import '../../shared/widgets/buzz_toast.dart';
import '../../shared/identity_names/identity_names.dart';
import '../../shared/identity_names/identity_names_provider.dart';
import '../../shared/relay/relay.dart';
import '../../shared/theme/theme.dart';
import '../../shared/utils/string_utils.dart';
import '../../shared/widgets/avatar_shape.dart';
import '../../shared/widgets/avatar_image.dart';
import '../../shared/widgets/agent_artwork_panel.dart';
import '../../shared/widgets/buzz_sheet_header.dart';
import '../../shared/widgets/verified_mark.dart';
import '../../shared/widgets/verified_profile_details.dart';
import '../../shared/widgets/buzz_action_tile.dart';
import '../../shared/widgets/modal_presentation.dart';
import '../../shared/widgets/progressive_animated_avatar.dart';
import '../channels/channel.dart';
import '../channels/channel_detail_page.dart';
import '../channels/channel_management_provider.dart';
import '../channels/message_content.dart';
import 'presence_cache_provider.dart';
import '../../shared/profile/user_cache_provider.dart';
import 'user_status_cache_provider.dart';
/// Show a user profile bottom sheet for the given [pubkey].
///
/// The sheet names [pubkey] as the opening surface did: within the live
/// comparison context [names] (for example a channel's members). Without it,
/// the identity is compared only with itself.
void showUserProfileSheet(
BuildContext context,
String pubkey, {
ProviderListenable<IdentityNames>? names,
WidgetBuilder? contextualActions,
}) {
showBuzzModalBottomSheet<Channel>(
context: context,
isScrollControlled: true,
showDragHandle: false,
builder: (_) => UserProfileSheet(
pubkey: pubkey,
names: names,
contextualActions: contextualActions,
),
).then((channel) {
if (channel == null || !context.mounted) return;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => ChannelDetailPage(
channel: channel,
placement: ChannelRoutePlacement.ordinary,
),
),
);
});
}
class UserProfileSheet extends HookConsumerWidget {
final String pubkey;
/// Agent artwork treatment within the profile sheet.
final bool agentPresentation;
final String? agentSubtitle;
final Widget? agentSubtitleIcon;
/// The opening surface's comparison context. The sheet watches it, so its
/// title follows profile and context changes while it is open. The caller
/// owns the context, so this sheet depends on no other feature's state.
final ProviderListenable<IdentityNames>? names;
/// Optional actions supplied by the opening surface, below the profile tiles.
final WidgetBuilder? contextualActions;
/// Optional action opposite the sheet close control.
final Widget? headerLeading;
/// Agent-specific content supplied by the owning surface.
final WidgetBuilder? agentIdentity;
final WidgetBuilder? agentSettings;
/// Space before the primary profile actions.
final double primaryActionsSpacing;
/// Space between primary actions and caller-supplied actions.
final double contextualActionsSpacing;
const UserProfileSheet({
super.key,
required this.pubkey,
this.agentPresentation = false,
this.agentSubtitle,
this.agentSubtitleIcon,
this.names,
this.contextualActions,
this.headerLeading,
this.agentIdentity,
this.agentSettings,
this.primaryActionsSpacing = Grid.xs + Grid.half,
this.contextualActionsSpacing = Grid.xs,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final pk = pubkey.toLowerCase();
final currentPubkey = ref.watch(currentPubkeyProvider);
// Watch cached profile, presence, and user status.
final profile =
ref.watch(userCacheProvider.select((cache) => cache[pk])) ??
ref.read(userCacheProvider.notifier).get(pk);
final presenceMap = ref.watch(presentedPresenceProvider);
final presence = presenceMap[pk];
final statusCache = ref.watch(userStatusCacheProvider);
final userStatus = statusCache[pk];
// Fetch about from the user's kind:0 profile event.
final aboutFuture = useMemoized(
() => ref
.read(relaySessionProvider.notifier)
.fetchHistory(NostrFilters.profile(pk))
.then((events) {
if (events.isEmpty) return '';
return ProfileData.fromEvent(events.first).about ?? '';
})
.catchError((_) => ''),
[pk],
);
final aboutSnapshot = useFuture(aboutFuture);
final about = aboutSnapshot.data ?? profile?.about ?? '';
// Ensure presence and status are tracked.
useEffect(() {
ref.read(presenceCacheProvider.notifier).track([pk]);
ref.read(userStatusCacheProvider.notifier).track([pk]);
ref.read(userCacheProvider.notifier).preload([pk]);
return null;
}, [pk]);
final copied = useState(false);
final isOpeningDirectMessage = useState(false);
// Canonical npub for the copy action; null when [pubkey] is not a valid
// identity, in which case the copy tile is disabled — an invalid key is
// never placed on the clipboard.
final npub = fullNpub(pubkey);
// Keep the opening surface's comparison context and qualified identity.
final opener = names;
final displayName =
(opener != null ? ref.watch(opener) : watchIdentityNames(ref, {pk}))
.labelFor(pk);
final avatarUrl = profile?.avatarUrl;
final nip05 = profile?.nip05Handle;
final initial =
profile?.initial ?? (pubkey.isNotEmpty ? pubkey[0].toUpperCase() : '?');
final copyGeneration = useRef(0);
Future<void> copyPublicKey() async {
if (npub == null) return;
await Clipboard.setData(ClipboardData(text: npub));
if (!context.mounted) return;
final generation = ++copyGeneration.value;
copied.value = true;
showBuzzToast(context, 'Public key copied', kind: ToastKind.success);
unawaited(
Future<void>.delayed(const Duration(seconds: 2), () {
if (context.mounted && copyGeneration.value == generation) {
copied.value = false;
}
}),
);
}
Future<void> openDirectMessage() async {
if (isOpeningDirectMessage.value) return;
isOpeningDirectMessage.value = true;
try {
final channel = await ref
.read(channelActionsProvider)
.openDm(pubkeys: [pk], waitForChannelList: false);
if (!context.mounted) return;
Navigator.of(context).pop(channel);
} catch (_) {
// Silently fail — user tapped but DM open failed.
if (context.mounted) isOpeningDirectMessage.value = false;
}
}
final content = ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.7,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Flexible(
child: Padding(
padding: EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
MediaQuery.viewInsetsOf(context).bottom,
),
child: SingleChildScrollView(
padding: const EdgeInsets.only(bottom: Grid.xs),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Center the presence chip on the avatar's lower edge.
Padding(
padding: EdgeInsets.only(
bottom: agentPresentation ? 0 : Grid.xl / 2,
),
child: Stack(
clipBehavior: Clip.none,
children: [
Align(
alignment: Alignment.center,
child: agentPresentation
? SizedBox(
width: Grid.xxl * 2,
child: _ProfileAvatar(
avatarUrl: avatarUrl,
initial: initial,
isAgent: true,
),
)
: FractionallySizedBox(
widthFactor: 0.5,
child: _ProfileAvatar(
avatarUrl: avatarUrl,
initial: initial,
isAgent: profile?.isAgent == true,
),
),
),
if (!agentPresentation)
Positioned(
left: 0,
right: 0,
bottom: -(Grid.xl / 2),
child: _ProfilePresenceChip(presence: presence),
),
],
),
),
SizedBox(height: agentPresentation ? Grid.xs : Grid.half),
// Display name — centered, large
Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(
displayName,
style: agentPresentation
? context.textTheme.bodyLarge?.copyWith(
fontSize: 20,
height: 1.4,
letterSpacing: -0.2,
)
: context.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w700,
),
textAlign: TextAlign.center,
),
),
VerifiedMark(pubkey: pk, size: 20),
],
),
),
VerifiedProfileDetails(pubkey: pk),
if (!agentPresentation && agentSubtitle != null) ...[
const SizedBox(height: Grid.xxs),
Center(
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: Grid.half,
children: [
if (agentSubtitleIcon != null)
ExcludeSemantics(
child: IconTheme(
data: IconThemeData(
color: context.colors.onSurfaceVariant,
),
child: agentSubtitleIcon!,
),
),
Text(
agentSubtitle!,
style: context.textTheme.bodySmall?.copyWith(
color: context.colors.onSurfaceVariant,
),
),
],
),
),
],
if (about.trim().isNotEmpty) ...[
const SizedBox(height: Grid.xxs),
SizedBox(
width: double.infinity,
child: Text(
about,
textAlign: TextAlign.center,
style: context.textTheme.bodyMedium?.copyWith(
color: context.colors.onSurfaceVariant,
),
),
),
],
// Keep the current status centered beneath the profile identity.
if (userStatus != null && !userStatus.isEmpty)
SizedBox(
width: double.infinity,
child: Padding(
padding: const EdgeInsets.only(
top: Grid.xxs,
left: Grid.gutter,
right: Grid.gutter,
bottom: Grid.xxs,
),
child: MessageContent(
content: userStatus.text.isNotEmpty
? '${userStatus.emoji.isNotEmpty ? '${userStatus.emoji} ' : ''}${userStatus.text}'
: userStatus.emoji,
baseStyle: context.textTheme.bodySmall?.copyWith(
color: context.colors.onSurfaceVariant,
),
textAlign: TextAlign.center,
maxLines: 2,
),
),
),
// NIP-05 handle — centered, secondary
if (nip05 != null && nip05.isNotEmpty) ...[
const SizedBox(height: Grid.half),
Center(
child: Text(
nip05,
style: context.textTheme.bodyMedium?.copyWith(
color: context.colors.onSurfaceVariant,
),
),
),
],
// The 48-point target adds 8 points above the 32-point capsule.
SizedBox(
height: agentPresentation
? Grid.xxs
: primaryActionsSpacing,
),
if (agentPresentation) ...[
Center(
child: Wrap(
alignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: Grid.xxs,
runSpacing: Grid.xxs,
children: [
if (pk != currentPubkey)
ProfileActionChip(
onPressed: isOpeningDirectMessage.value
? null
: openDirectMessage,
label: isOpeningDirectMessage.value
? 'Opening…'
: 'Message',
),
if (contextualActions != null)
Builder(builder: contextualActions!),
],
),
),
const SizedBox(height: Grid.sm),
if (agentIdentity != null)
Builder(builder: agentIdentity!),
AppListCard(
label: 'Public key',
horizontalPadding: 0,
children: [
Semantics(
button: true,
enabled: npub != null,
label: copied.value
? 'Copied public key'
: 'Copy public key',
value: npub,
liveRegion: true,
child: Tooltip(
message: 'Copy public key',
excludeFromSemantics: true,
child: InkWell(
onTap: npub == null ? null : copyPublicKey,
child: Padding(
padding: const EdgeInsets.all(Grid.xs),
child: ExcludeSemantics(
child: Row(
children: [
Expanded(
child: Text(
npub ?? 'Public key unavailable',
style: context.textTheme.bodySmall,
),
),
const SizedBox(width: Grid.xs),
AnimatedSwitcher(
duration:
MediaQuery.disableAnimationsOf(
context,
)
? Duration.zero
: const Duration(
milliseconds: 180,
),
switchInCurve: Curves.easeOutCubic,
switchOutCurve: Curves.easeInCubic,
transitionBuilder:
(child, animation) =>
ScaleTransition(
scale: animation,
child: child,
),
child: Icon(
copied.value
? BuzzIcons.check
: BuzzIcons.copy,
key: ValueKey(copied.value),
size: 18,
),
),
],
),
),
),
),
),
),
],
),
if (agentSettings != null)
Builder(builder: agentSettings!),
] else ...[
Row(
children: [
if (pk != currentPubkey) ...[
Expanded(
child: BuzzActionTile(
icon: isOpeningDirectMessage.value
? null
: BuzzIcons.messageSquare,
label: isOpeningDirectMessage.value
? 'Opening…'
: 'Message',
isLoading: isOpeningDirectMessage.value,
loadingSemanticLabel: 'Opening direct message',
onTap: openDirectMessage,
),
),
const SizedBox(width: Grid.twelve),
],
Expanded(
child: BuzzActionTile(
icon: copied.value
? BuzzIcons.check
: BuzzIcons.key,
label: copied.value
? 'Copied'
: 'Copy public key',
isEnabled: npub != null,
onTap: copyPublicKey,
),
),
],
),
SizedBox(height: contextualActionsSpacing),
if (contextualActions != null)
Builder(builder: contextualActions!),
],
],
),
),
),
),
],
),
);
if (!agentPresentation) return content;
return AgentArtworkPanel(
imageUrl: avatarUrl,
borderRadius: BorderRadius.zero,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
BuzzSheetHeader(leading: headerLeading),
Flexible(child: SafeArea(top: false, child: content)),
],
),
);
}
}
/// The read-only version of the presence control in Settings. A viewed profile
/// reflects its owner's availability but does not allow another user to change
/// it.
class _ProfilePresenceChip extends StatelessWidget {
const _ProfilePresenceChip({required this.presence});
final String? presence;
@override
Widget build(BuildContext context) {
final effectivePresence = switch (presence) {
'online' || 'away' || 'offline' => presence,
_ => null,
};
final backgroundColor = switch (effectivePresence) {
'online' => context.appColors.success,
'away' => context.appColors.warning,
_ => context.colors.onSurfaceVariant,
};
final label = switch (effectivePresence) {
'online' => 'Online',
'away' => 'Away',
'offline' => 'Offline',
_ => 'Unknown',
};
return Semantics(
label: 'Presence: $label',
excludeSemantics: true,
child: SizedBox(
height: Grid.xl,
child: Center(
child: Material(
color: backgroundColor,
borderRadius: BorderRadius.circular(Radii.full),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: Grid.xs,
vertical: Grid.xxs,
),
child: Text(
label,
style: filterChipTextStyle.copyWith(
color: context.colors.onPrimary,
fontWeight: FontWeight.w500,
),
),
),
),
),
),
);
}
}
class _ProfileAvatar extends HookWidget {
final String? avatarUrl;
final String initial;
final bool isAgent;
const _ProfileAvatar({
required this.avatarUrl,
required this.initial,
required this.isAgent,
});
@override
Widget build(BuildContext context) {
final animatedAvatar = parseAnimatedAvatarUrl(avatarUrl);
final stoppedAnimationUrl = useState<String?>(null);
final isPlaying =
animatedAvatar != null &&
stoppedAnimationUrl.value != animatedAvatar.animationUrl;
return AspectRatio(
aspectRatio: 1,
child: GestureDetector(
key: const ValueKey('selected-profile-avatar'),
onTap: animatedAvatar == null
? null
: () => stoppedAnimationUrl.value =
stoppedAnimationUrl.value == animatedAvatar.animationUrl
? null
: animatedAvatar.animationUrl,
child: LayoutBuilder(
builder: (context, constraints) {
final avatar = isPlaying
? ProgressiveAnimatedAvatar(
key: ValueKey(animatedAvatar.animationUrl),
descriptor: animatedAvatar,
fallback: _AvatarFallback(initial: initial),
)
: AvatarImageContent(
imageUrl: animatedAvatar?.posterUrl ?? avatarUrl,
preferThumbnail: true,
fallback: _AvatarFallback(initial: initial),
);
return AvatarClip(
isAgent: isAgent,
child: !isAgent || !usesInsetAgentArtwork(avatarUrl)
? avatar
: Transform.scale(
scale: animatedAvatarArtworkScale,
child: avatar,
),
);
},
),
),
);
}
}
class _AvatarFallback extends StatelessWidget {
final String initial;
const _AvatarFallback({required this.initial});
@override
Widget build(BuildContext context) {
return Container(
color: context.controlSurface,
alignment: Alignment.center,
child: Text(
initial,
style: context.textTheme.displayLarge?.copyWith(
color: context.colors.onPrimaryContainer,
fontWeight: FontWeight.w600,
),
),
);
}
}