Files
buzz/mobile/lib/shared/profile/profile_snapshot.dart
Stephen Edwards 36e6e4f8e7 fix(mobile): apply message edits only from authorized authors (#9887)
## Why

Buzz mobile now checks who signed each edit before deciding what to show
in a channel or thread. That includes edits to the first message of a
thread loaded from local storage. Mobile also preserves the information
needed to verify edits after an offline restart and retries missing
profile lookups when the app reconnects.

The companion relay change is #9886.

## Mechanism

Mobile uses the first valid message reference on an edit and shows the
newest edit that passes its checks. It accepts edits from the original
message’s signer. If the relay signed the original, mobile also accepts
edits from the author named by the relay. A verified agent owner can
edit the agent’s chat messages (kinds 9 and 40002) and diff messages
(kind 40008) in the same channel.

**Agent owners.** Mobile verifies the owner named in the agent’s signed
profile. The app reads permission when a user opens the channel or
thread message menu or the image actions. The native photo viewer also
reads permission when it opens and checks again before deleting. These
paths and the timeline use the same signed profile to verify the owner.

When an agent’s signed profile names an owner, mobile saves the signed
event once and reads fields such as the name and avatar from it on
restart. If that entry exceeds the 16 KiB limit, mobile saves the
display fields alone if they fit. Mobile needs the signed profile to
verify the owner. When the app connects, it asks for profiles needed to
check edits in the current timeline and retries unresolved lookups on
reconnect. The cache skips profiles it has already checked with the
relay and public keys the relay recently reported as having no profile.
Once mobile loads a newer profile from the relay that no longer names
the owner, it stops applying that person’s edits. The next time that
person opens the message menu, Edit is absent. In the device test, both
changes took effect after restarting the app.

**Relay signing key.** While connected, mobile looks up the key if the
timeline contains an edit whose signer differs from the original
message’s signer and the original has a public key in an `actor` or `p`
tag. A mention in a `p` tag can also trigger the lookup. Mobile uses
that tagged author only after confirming that the relay signed the
original message.

Mobile keeps the last key during reconnects and can read it from the
saved-message store after an offline restart. If the timeline still
needs the key when mobile reconnects, mobile refreshes it so a rotated
key can take effect during the same session. A failed request or a
response without a key leaves the previous key available. Thread
summaries read the key available when they refresh and start no key
lookup.

## What changed

- Start with `edit_authority.dart` for the profile and key lookups and
the permission check that runs when actions open. See
`timeline_message.dart` for edit selection and
`thread_detail_helpers.dart` for the first message of a thread loaded
from local storage.
- See `verified_profile_owner.dart` for ownership verification,
`profile_snapshot.dart` for storage and restore,
`user_cache_provider.dart` for profile refreshes, and
`SavedMessageStore.relayAuthor` for the saved relay key.
- Tests cover edit selection, owner edits to chat and diff messages, and
edits to a saved thread’s first message after replies load. They also
cover opening message and image actions, restored profiles without a
signed copy and profiles signed by the wrong key, reconnect retries,
offline reopening with a large signed profile, and a newly fetched relay
key replacing a saved key. Tests also verify that the native photo
viewer blocks deletion if permission is withdrawn while it is open, that
opening message actions requests a fresh profile when the saved profile
names the viewer as owner but lacks a signed copy, and that a tampered
saved profile cannot verify ownership.

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

---------

Signed-off-by: Stephen Edwards <sedwards@squareup.com>
2026-11-24 10:34:52 -05:00

265 lines
9.8 KiB
Dart

import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../relay/nostr_models.dart';
import '../relay/relay_provider.dart' show RelayConfig;
import '../theme/community_theme_preference.dart';
import '../theme/theme_provider.dart';
import 'profile_event_parser.dart';
import 'user_profile.dart';
const _keyPrefix = 'buzz.profiles.v1';
const _version = 1;
/// Profiles beyond these bounds are not stored; they load from the relay.
const maxProfileSnapshotProfiles = 2000;
const maxProfileSnapshotBytes = 2 * 1024 * 1024;
/// A single stored profile may not exceed this. Inline `data:` avatars can be
/// large; such profiles are skipped rather than crowding out everyone else.
const maxProfileSnapshotEntryBytes = 16 * 1024;
/// Permission to write one scope's snapshot, captured when the cache starts.
///
/// [ProfileSnapshotStorage.remove] retires every token captured before it, so
/// a pending write during sign-out cannot recreate the snapshot.
class ProfileSnapshotToken {
const ProfileSnapshotToken._(this._key, this._epoch);
final String _key;
final int _epoch;
}
/// Stores the last verified profiles seen per relay and identity, so names and
/// avatars render on launch before the relay answers.
///
/// The data is a cache derived from relay kind:0 events: unreadable,
/// unsupported or oversized data is discarded rather than migrated. Restored
/// profiles are revalidated against the relay on first use each session.
/// A profile with an owner attestation is stored as its signed event, when it
/// fits, so the owner can be verified again offline; the display fields are
/// read from it on restore. Entries without it still supply names and
/// avatars.
class ProfileSnapshotStorage {
ProfileSnapshotStorage(this._prefs);
final SharedPreferences _prefs;
/// Retirement epochs shared by every storage over the same preferences.
static final _epochsByPrefs = Expando<Map<String, int>>();
Map<String, int> get _epochs => _epochsByPrefs[_prefs] ??= {};
/// The scope key. `wss://`/`ws://` origins fold to `https://`/`http://`
/// like `RelayConfig.baseUrl`, so both onboarding paths share a snapshot.
static String key(String pubkey, String relayUrl) {
final relay = normalizeCommunityRelayUrl(
RelayConfig(baseUrl: normalizeCommunityRelayUrl(relayUrl)).baseUrl,
);
return '$_keyPrefix:${pubkey.toLowerCase()}:${Uri.encodeComponent(relay)}';
}
/// Returns the scope's profiles, or an empty list when absent or unusable.
List<ParsedProfileEvent> read(String pubkey, String relayUrl) {
final key = ProfileSnapshotStorage.key(pubkey, relayUrl);
final raw = _prefs.getString(key);
if (raw == null) return const [];
try {
if (raw.length > maxProfileSnapshotBytes ||
utf8.encode(raw).length > maxProfileSnapshotBytes) {
throw const FormatException('size');
}
final json = jsonDecode(raw) as Map<String, dynamic>;
if (json['v'] != _version) throw const FormatException('version');
final profiles = json['profiles'] as List<dynamic>;
if (profiles.length > maxProfileSnapshotProfiles) {
throw const FormatException('count');
}
return [
for (final entry in profiles) ?_decode(entry as Map<String, dynamic>),
];
} catch (_) {
// Unusable cache: drop it without retiring the live writer.
_prefs.remove(key).ignore();
return const [];
}
}
/// Captures write permission for the scope.
ProfileSnapshotToken capture(String pubkey, String relayUrl) {
final key = ProfileSnapshotStorage.key(pubkey, relayUrl);
return ProfileSnapshotToken._(key, _epochs[key] ?? 0);
}
/// Replaces the scope's snapshot with the newest [profiles] that fit the
/// bounds. Returns false when [token] was retired or storage rejected it.
Future<bool> write(
ProfileSnapshotToken token,
Iterable<ParsedProfileEvent> profiles,
) async {
if ((_epochs[token._key] ?? 0) != token._epoch) return false;
final newestFirst = profiles.toList()
..sort((a, b) => b.createdAt.compareTo(a.createdAt));
final entries = <String>[];
// Two bytes per entry cover the list's brackets and separators.
var bytes = 32;
for (final profile in newestFirst) {
if (entries.length == maxProfileSnapshotProfiles) break;
var entry = jsonEncode(_encode(profile));
var entryBytes = utf8.encode(entry).length;
if (entryBytes > maxProfileSnapshotEntryBytes &&
profile.profile.ownerEvidence != null) {
// The name and avatar may still fit without the signed copy; the
// owner stays unverified until the profile is fetched again.
entry = jsonEncode(_encode(profile, evidence: false));
entryBytes = utf8.encode(entry).length;
}
if (entryBytes > maxProfileSnapshotEntryBytes) continue;
if (bytes + entryBytes + 1 > maxProfileSnapshotBytes) break;
bytes += entryBytes + 1;
entries.add(entry);
}
final raw = '{"v":$_version,"profiles":[${entries.join(',')}]}';
if (_prefs.getString(token._key) == raw) return true;
// The token check and SharedPreferences' synchronous in-memory update run
// without an intervening await, so a later remove always wins.
return _prefs.setString(token._key, raw);
}
/// Deletes the scope's snapshot and retires its outstanding tokens.
Future<void> remove(String pubkey, String relayUrl) =>
_removeKey(ProfileSnapshotStorage.key(pubkey, relayUrl));
/// Retires and deletes snapshots without a stored community.
Future<void> removeOrphans(Set<String> retainedKeys) async {
final keys = {..._prefs.getKeys(), ..._epochs.keys};
await Future.wait([
for (final key in keys)
if (key.startsWith('$_keyPrefix:') && !retainedKeys.contains(key))
_removeKey(key).catchError((Object error) {
debugPrint('[ProfileSnapshotStorage] cleanup failed: $error');
}),
]);
}
Future<void> _removeKey(String key) async {
_epochs[key] = (_epochs[key] ?? 0) + 1;
if (!await _prefs.remove(key)) {
throw StateError('Profile snapshot could not be removed.');
}
}
static Map<String, Object?> _encode(
ParsedProfileEvent parsed, {
bool evidence = true,
}) {
final profile = parsed.profile;
final signed = profile.ownerEvidence;
// The signed event holds the display fields, so they are not repeated.
if (evidence && signed != null && signed.id == parsed.eventId) {
return {'owner': ?profile.ownerPubkey, 'signed': signed.toJson()};
}
return {
'pubkey': profile.pubkey,
'event_id': parsed.eventId,
'created_at': parsed.createdAt,
'display_name': ?profile.displayName,
'avatar_url': ?profile.avatarUrl,
'about': ?profile.about,
'nip05': ?profile.nip05Handle,
'owner': ?profile.ownerPubkey,
};
}
/// Null drops an attested entry whose signed event is unusable.
static ParsedProfileEvent? _decode(Map<String, dynamic> json) {
if (!json.containsKey('pubkey')) return _decodeSigned(json);
final pubkey = (json['pubkey'] as String).toLowerCase();
final createdAt = json['created_at'] as int;
final eventId = json['event_id'] as String;
return (
profile: UserProfile(
pubkey: pubkey,
displayName: json['display_name'] as String?,
avatarUrl: json['avatar_url'] as String?,
about: json['about'] as String?,
nip05Handle: json['nip05'] as String?,
ownerPubkey: json['owner'] as String?,
ownerEvidence: _decodeEvidence(
json['signed'],
pubkey: pubkey,
createdAt: createdAt,
eventId: eventId,
),
),
createdAt: createdAt,
eventId: eventId,
);
}
/// An entry stored as its signed event. Its display fields are read from
/// the event without verifying it; owner checks verify it when needed.
static ParsedProfileEvent? _decodeSigned(Map<String, dynamic> json) {
final event = _signedProfile(json['signed']);
if (event == null) return null;
final data = ProfileData.fromEvent(event);
return (
profile: UserProfile(
pubkey: event.pubkey.toLowerCase(),
displayName: data.displayName,
avatarUrl: data.avatarUrl,
about: data.about,
nip05Handle: data.nip05,
ownerPubkey: json['owner'] as String?,
ownerEvidence: event,
),
createdAt: event.createdAt,
eventId: event.id,
);
}
/// The stored signed profile, only when it is this entry's own event.
/// Anything else is dropped without discarding the entry's name.
static NostrEvent? _decodeEvidence(
Object? json, {
required String pubkey,
required int createdAt,
required String eventId,
}) {
final event = _signedProfile(json);
return event != null &&
event.pubkey.toLowerCase() == pubkey &&
event.createdAt == createdAt &&
event.id == eventId
? event
: null;
}
/// A stored kind:0 that carries an owner attestation, else null.
static NostrEvent? _signedProfile(Object? json) {
if (json is! Map<String, dynamic>) return null;
try {
final event = NostrEvent.fromJson(json);
return event.kind == 0 && carriesOwnerAttestation(event) ? event : null;
} on TypeError {
return null;
}
}
}
/// The app's profile snapshot storage, or null where preferences were never
/// provided (isolated tests). Null means profiles live only in memory.
final profileSnapshotStorageProvider = Provider<ProfileSnapshotStorage?>((ref) {
final SharedPreferences prefs;
try {
prefs = ref.watch(savedPrefsProvider);
} catch (_) {
// The unprovided override throws, wrapped by Riverpod.
return null;
}
return ProfileSnapshotStorage(prefs);
});