Files
buzz/mobile/lib/shared/utils/string_utils.dart
Logan Johnson 82656ffea0 fix(mobile): standardize public-key identity display on npub (#7493)
🤖

## Summary

In the mobile app, anyone who hasn't set a display name shows up as a
raw 64-character hex key (e.g. `3a5d4f9c…`) — unreadable, and
unrecognizable as the same identity across screens. Profile and Settings
also let you copy that raw hex. Nostr public keys have a standard
readable form — `npub1…`, the same encoding other Nostr apps and our
desktop app already display. This PR makes every mobile identity surface
render npub instead:

- **Unnamed people everywhere** — message and thread authors, reactions,
typing indicators, member lists, channel details, DM headers and tiles,
inbox, search, forum cards, Pulse notes and reply context, mention
suggestions, and invite rows — now show a compact npub label: first 8 +
last 4 characters of the full npub joined by an ellipsis
(`npub1abcd…wxyz`), the same truncation desktop uses. Previously these
showed truncated raw hex.
- **DM fallback avatars and blank names** — 1:1 DM tiles and headers key
their fallback avatar to the same non-self counterpart the label names,
including self-first participant order; a self-DM keeps its
hex-key-derived initial. Blank or whitespace-only display names fall
back to the compact npub instead of rendering empty, while nonblank
authored names render verbatim (padding included).
- **Profile sheet → "Copy public key"** now copies the full canonical
npub — never raw hex. When the identity string isn't a valid public key,
the copy tile is disabled, so a malformed key never reaches the
clipboard.
- **Settings → Identity (pubkey)** displays and copies the full npub; an
invalid identity reads "Identity unavailable" with copy disabled.
- **Invalid identities never leak truncated raw hex** into the UI
anywhere — they render a neutral "Unknown identity" label.
- **Unchanged on purpose:** display names and verified handles (NIP-05 —
the `name@domain` badge) still render as before. Unnamed avatars keep
distinct per-key initials, derived from the underlying hex key rather
than the npub — otherwise every unnamed key would render the same "N"
initial. Event IDs are not public keys, so they keep their hex
truncation (in Pulse's "Replying to", the parent author shows npub while
an event-id fallback still shows hex). The nevent share link, private
keys, and internal hex storage are untouched. Inputs that accept a key
(invite/member entry) accept both hex and npub and keep working in hex
internally.

### Related issue

N/A. Searched open issues/PRs for npub identity display on mobile —
closest related: none found. Desktop's parallel npub standardization
lives in the stacked desktop PRs (#7488 foundation, #7489 controls,
#7495 display surfaces); this is the independent mobile slice (based
directly on `main`, not on those branches).

### Testing

At exact head `5a620e420a1fd57d9d8011ac26434eed32fcf765` (base: `main`
`44316ff72`; 40 files, +1,345/−154):

- Full mobile suite: 2,098 tests passing (`cd mobile && flutter test`);
`flutter analyze` clean; `dart format --set-exit-if-changed .` clean —
the same checks CI runs.
- Widget/unit coverage at production seams: compact labels and hex-keyed
avatar initials for DM headers/tiles, member rows, mention suggestions,
and Pulse reply context; DM fallback avatars keyed to the labeled
counterpart (self-first order and self-DMs); blank/whitespace
display-name npub fallback with nonblank authored labels verbatim,
including the Activity inbox sender and profile-sheet heading (each with
its own empty/whitespace production-seam regression); full-npub copy and
disabled-copy semantics in profile and settings; invalid-key
suppression; and hex↔npub input round-trips.

Verified via unit and widget tests — no device/simulator validation is
claimed.

### Task provenance

Buzz channel: `1f0e4a3d-7e01-4efe-bb16-843b357f85c9`

Task:
buzz://message?channel=1f0e4a3d-7e01-4efe-bb16-843b357f85c9&id=86b34eb4bd84a1472419e9af22636c011c0fe273e3c196f967d7a36996e149b6

---------

Signed-off-by: Logan Johnson <loganj@squareup.com>
Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
2026-09-09 14:08:24 -04:00

53 lines
2.1 KiB
Dart

import 'package:nostr/nostr.dart' as nostr;
/// Neutral label rendered when an identity string cannot be read as a Nostr
/// public key — malformed identities never leak truncated raw hex into the UI.
const String unknownIdentityLabel = 'Unknown identity';
final RegExp _hexPubkeyPattern = RegExp(r'^[0-9a-fA-F]{64}$');
/// The canonical full NIP-19 npub for [identity], or null when [identity] is
/// not a valid public key.
///
/// Accepts both canonical public-key forms — a 64-character hex key (any
/// case) or an `npub1…` string — and returns the full canonical npub.
/// Already-npub input round-trips through the codec so the result is always
/// the canonical lowercase encoding. Internal storage stays hex; the npub is
/// the user-facing display/copy form. Invalid input returns null (never a
/// passthrough of the raw string) so callers can suppress copy actions.
String? fullNpub(String identity) {
final trimmed = identity.trim();
try {
if (_hexPubkeyPattern.hasMatch(trimmed)) {
return _encodeNpub(trimmed.toLowerCase());
}
final decoded = nostr.Nip19.decode(payload: trimmed);
if (decoded.prefix != nostr.Nip19Prefix.npub ||
!_hexPubkeyPattern.hasMatch(decoded.data)) {
return null;
}
return _encodeNpub(decoded.data.toLowerCase());
} catch (_) {
return null;
}
}
String _encodeNpub(String hexPubkey) =>
nostr.Nip19.encode(prefix: nostr.Nip19Prefix.npub, data: hexPubkey);
/// The canonical compact public-key label: the first 8 and last 4 characters
/// of the full npub joined by an ellipsis — the same truncation desktop uses
/// for identity surfaces.
///
/// A compact label is a recognition aid, never a verification path; copy
/// actions expose the full npub via [fullNpub]. Accepts hex or npub input
/// (already-npub input yields the same label as its underlying key).
/// Returns [unknownIdentityLabel] when [identity] is not a valid public key.
String shortPubkey(String identity) {
final npub = fullNpub(identity);
if (npub == null) return unknownIdentityLabel;
return npub.length <= 12
? npub
: '${npub.substring(0, 8)}…${npub.substring(npub.length - 4)}';
}