Skip to content

Commit 36e6e4f

Browse files
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>
1 parent ed29172 commit 36e6e4f

29 files changed

Lines changed: 2207 additions & 106 deletions

‎mobile/lib/features/channels/channel_detail_page.dart‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,7 @@ import 'thread_replies_provider.dart';
131131
import 'open_channel_routes.dart';
132132
import 'reading_marks.dart';
133133
import 'timeline_message.dart';
134+
import 'edit_authority.dart';
134135

135136
part 'channel_detail_page/message_list.dart';
136137
part 'channel_detail_page/initial_thread_route.dart';
@@ -703,14 +704,26 @@ class _ResolvedChannelDetailPage extends HookConsumerWidget {
703704
final retention = ephemeralChannelDisplay(resolvedChannel);
704705

705706
// The page also rebuilds for read state, presence, roster and layout
706-
// changes. Format only when the events themselves change: the notifier
707-
// publishes a new list for every event change.
707+
// changes. Reformat only when events, reaction identity, or trusted edit
708+
// authorship changes; the notifier publishes a new list for event changes.
708709
final events = messagesState.value ?? const <NostrEvent>[];
710+
final editAuthority = useEditAuthority(ref, events);
709711
final timelineMessages = useMemoized(
710712
() => resolvedChannel.isForum
711713
? <TimelineMessage>[]
712-
: formatTimeline(events, currentPubkey: currentPubkey),
713-
[events, currentPubkey, resolvedChannel.isForum],
714+
: formatTimeline(
715+
events,
716+
currentPubkey: currentPubkey,
717+
agentOwners: editAuthority.owners,
718+
relayPubkey: editAuthority.relayKey,
719+
),
720+
[
721+
events,
722+
currentPubkey,
723+
resolvedChannel.isForum,
724+
editAuthority.owners,
725+
editAuthority.relayKey,
726+
],
714727
);
715728
final timelineEntries = buildMainTimelineEntries(
716729
// End events still update the original card through allMessages.

‎mobile/lib/features/channels/channel_detail_page/huddle_history.dart‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,10 @@ class _HuddleHistoryMessages extends HookConsumerWidget {
108108
final provider = channelMessagesProvider(channelId);
109109
final messages = ref.watch(provider);
110110
final currentPubkey = ref.watch(currentPubkeyProvider);
111+
final editAuthority = useEditAuthority(
112+
ref,
113+
messages.value ?? const <NostrEvent>[],
114+
);
111115
final dateScrollActivity = useDateHeaderScrollActivity(channelId);
112116
final stickyDateHeaderState = useValueNotifier(
113117
StickyDateHeaderState.hidden,
@@ -126,6 +130,8 @@ class _HuddleHistoryMessages extends HookConsumerWidget {
126130
final timeline = formatTimeline(
127131
events,
128132
currentPubkey: currentPubkey,
133+
agentOwners: editAuthority.owners,
134+
relayPubkey: editAuthority.relayKey,
129135
).where((message) => !message.isSystem).toList();
130136
if (timeline.isEmpty) {
131137
return const Center(child: Text('No messages in this Huddle.'));

‎mobile/lib/features/channels/channel_detail_page/initial_thread_route.dart‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,32 @@ extension on _MessageList {
1616
final live = saved == null
1717
? null
1818
: ref.watch(channelMessagesProvider(channelId)).value;
19-
final head = useMemoized(() {
20-
if (channelHead != null || saved == null) return channelHead;
21-
return formatTimeline(
22-
mergeThreadEvents(saved, live ?? const []),
23-
currentPubkey: currentPubkey,
24-
).where((message) => message.id == rootId).firstOrNull;
25-
}, [channelHead, saved, live, currentPubkey, rootId]);
19+
final events = useMemoized(
20+
() => channelHead != null || saved == null
21+
? const <NostrEvent>[]
22+
: mergeThreadEvents(saved, live ?? const []),
23+
[channelHead == null, saved, live],
24+
);
25+
final editAuthority = useEditAuthority(ref, events);
26+
final head = useMemoized(
27+
() {
28+
if (channelHead != null || saved == null) return channelHead;
29+
return formatTimeline(
30+
events,
31+
currentPubkey: currentPubkey,
32+
agentOwners: editAuthority.owners,
33+
relayPubkey: editAuthority.relayKey,
34+
).where((message) => message.id == rootId).firstOrNull;
35+
},
36+
[
37+
channelHead,
38+
events,
39+
currentPubkey,
40+
rootId,
41+
editAuthority.owners,
42+
editAuthority.relayKey,
43+
],
44+
);
2645
useEffect(() {
2746
if (opened.value || head == null) return null;
2847
var cancelled = false;

‎mobile/lib/features/channels/channel_detail_page/message_bubble.dart‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,10 +75,6 @@ class _MessageBubble extends HookConsumerWidget {
7575
final isAgent =
7676
ref.watch(agentMentionPubkeysProvider(currentChannelId)).contains(pk) ||
7777
profile?.ownerPubkey != null;
78-
final canManageMessage =
79-
currentPubkey?.toLowerCase() == pk ||
80-
(profile?.ownerPubkey != null &&
81-
profile?.ownerPubkey == currentPubkey?.toLowerCase());
8278

8379
// Watch only profiles referenced by this message. A batched profile fetch
8480
// should not rebuild every visible message just because an unrelated user
@@ -129,7 +125,7 @@ class _MessageBubble extends HookConsumerWidget {
129125
ref: ref,
130126
message: message,
131127
channelId: currentChannelId,
132-
canManageMessage: canManageMessage,
128+
canManageMessage: readCanManageMessage(ref, pk, currentPubkey),
133129
allMessages: allMessages,
134130
currentPubkey: currentPubkey,
135131
isMember: isMember,
@@ -401,7 +397,12 @@ class _MessageBubble extends HookConsumerWidget {
401397
ref: ref,
402398
message: message,
403399
channelId: currentChannelId,
404-
canManageMessage: canManageMessage,
400+
canManageMessage: () =>
401+
readCanManageMessage(
402+
ref,
403+
pk,
404+
currentPubkey,
405+
),
405406
),
406407
onMediaMore:
407408
(viewerContext, imageUrl) =>
@@ -412,7 +413,11 @@ class _MessageBubble extends HookConsumerWidget {
412413
channelId: currentChannelId,
413414
imageUrl: imageUrl,
414415
canManageMessage:
415-
canManageMessage,
416+
readCanManageMessage(
417+
ref,
418+
pk,
419+
currentPubkey,
420+
),
416421
onDeleted: () {
417422
if (viewerContext.mounted) {
418423
Navigator.of(

‎mobile/lib/features/channels/channel_messages_provider.dart‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import '../../shared/channels/saved_message_store.dart';
77
import '../../shared/relay/relay.dart';
88
import 'channel_event_order.dart';
99
import 'channel_open_timing.dart';
10+
import 'edit_authority.dart';
1011
import 'pending_local_messages_provider.dart';
1112
import 'saved_channel_page.dart';
1213
import 'channel_window.dart';
@@ -19,10 +20,6 @@ part 'channel_messages_provider/thread_summaries.dart';
1920
part 'channel_messages_provider/pagination.dart';
2021
part 'channel_messages_provider/notices.dart';
2122

22-
// Channel history keeps partial reply evidence; full threads stay route-scoped.
23-
const _maxCachedRepliesPerRoot = 256;
24-
const _maxCachedReplies = 2048;
25-
2623
/// How long a chat nobody shows keeps its live subscription. A brief cover,
2724
/// such as a profile pushed over the chat, returns without a catch-up fetch.
2825
const _liveDetachDelay = Duration(seconds: 30);
@@ -36,7 +33,8 @@ const _channelLiveEventKinds = [
3633
/// subscription first, then syncs history via the server-assembled channel
3734
/// window fast path, falling back to the legacy websocket history path when the
3835
/// relay does not return a valid NIP-CW bounds overlay.
39-
class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>> {
36+
class ChannelMessagesNotifier extends Notifier<AsyncValue<List<NostrEvent>>>
37+
with _SummaryEditAuthority {
4038
final String channelId;
4139
final bool flatTimeline;
4240
void Function()? _unsubscribe;

‎mobile/lib/features/channels/channel_messages_provider/pagination.dart‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
part of '../channel_messages_provider.dart';
22

3+
// Channel history keeps partial reply evidence; full threads stay route-scoped.
4+
const _maxCachedRepliesPerRoot = 256;
5+
const _maxCachedReplies = 2048;
6+
37
extension _ChannelHistoryPagination on ChannelMessagesNotifier {
48
Future<ChannelWindowPage> _fetchWindowPage(
59
RelaySessionNotifier session,

‎mobile/lib/features/channels/channel_messages_provider/thread_summaries.dart‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
part of '../channel_messages_provider.dart';
22

3+
/// Edit authority for thread summaries, read when a summary refreshes.
4+
mixin _SummaryEditAuthority on Notifier<AsyncValue<List<NostrEvent>>> {
5+
EditAuthority _summaryEditAuthority(List<NostrEvent> events) =>
6+
readEditAuthority(ref, events);
7+
}
8+
39
extension _ThreadSummaryState on ChannelMessagesNotifier {
410
void _reconcilePageSummaries(ChannelWindowPage page, int pageVersion) {
511
// Nothing below changes the cached replies, so index them once per page.
@@ -152,12 +158,18 @@ extension _ThreadSummaryState on ChannelMessagesNotifier {
152158
) {
153159
final rows = _visibleNestedRows(root).toList();
154160
if (rows.isEmpty) return;
161+
final events = [
162+
...{
163+
for (final event in [...rows, ...replies]) event.id: event,
164+
}.values,
165+
];
166+
final authority = _summaryEditAuthority(events);
155167
final entries = buildMainTimelineEntries(
156-
formatTimeline([
157-
...{
158-
for (final event in [...rows, ...replies]) event.id: event,
159-
}.values,
160-
]),
168+
formatTimeline(
169+
events,
170+
agentOwners: authority.owners,
171+
relayPubkey: authority.relayKey,
172+
),
161173
);
162174
for (final row in rows) {
163175
if ((_threadQueryVersions[row.id] ?? 0) > version) continue;
Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import 'dart:async';
2+
3+
import 'package:flutter_hooks/flutter_hooks.dart';
4+
import 'package:hooks_riverpod/hooks_riverpod.dart';
5+
6+
import '../../shared/channels/saved_message_store.dart';
7+
import '../../shared/profile/user_cache_provider.dart';
8+
import '../../shared/profile/verified_profile_owner.dart';
9+
import '../../shared/relay/relay.dart';
10+
import '../../shared/relay/relay_author_provider.dart';
11+
import 'timeline_message.dart';
12+
13+
/// The signed evidence [formatTimeline] judges cross-signer edits with:
14+
/// verified owners by author, and the relay's trusted signing key.
15+
typedef EditAuthority = ({Map<String, String> owners, String? relayKey});
16+
17+
/// Watches the evidence the cross-signer edits in [events] need, and asks
18+
/// the user cache for the profiles that supply it. Call from a hook build.
19+
///
20+
/// The profiles are asked for on each connect while the edits show, so a
21+
/// request that failed is made again. The cache skips authors it already
22+
/// has a current answer for, with or without an attestation.
23+
///
24+
/// Nothing is watched for a timeline without such edits, so the relay is not
25+
/// asked for its key and unrelated profile changes do not reformat it.
26+
EditAuthority useEditAuthority(WidgetRef ref, List<NostrEvent> events) {
27+
final needs = useMemoized(() => editAuthorityNeeds(events), [events]);
28+
final authors = needs.owners.join(',');
29+
final connected =
30+
authors.isNotEmpty &&
31+
ref.watch(
32+
relaySessionProvider.select(
33+
(session) => session.status == SessionStatus.connected,
34+
),
35+
);
36+
useEffect(() {
37+
if (connected) {
38+
ref.read(userCacheProvider.notifier).requestLinked(needs.owners);
39+
}
40+
return null;
41+
}, [authors, connected]);
42+
return (
43+
owners: authors.isEmpty
44+
? const <String, String>{}
45+
: ref.watch(_editOwnersProvider(authors)),
46+
relayKey: needs.relayKey ? ref.watch(editRelayKeyProvider) : null,
47+
);
48+
}
49+
50+
/// [useEditAuthority] for a notifier that formats once: reads the evidence
51+
/// held now, requests missing profiles without waiting for them, and starts
52+
/// no relay key lookup.
53+
EditAuthority readEditAuthority(Ref ref, List<NostrEvent> events) {
54+
final needs = editAuthorityNeeds(events);
55+
if (needs.owners.isNotEmpty) {
56+
unawaited(ref.read(userCacheProvider.notifier).preload(needs.owners));
57+
}
58+
final profiles = ref.read(userCacheProvider);
59+
return (
60+
owners: {
61+
for (final author in needs.owners)
62+
if (profiles[author]?.ownerEvidence case final evidence?)
63+
author: ?verifiedEvidenceOwner(evidence, author),
64+
},
65+
relayKey: needs.relayKey
66+
? ref.read(_learnedRelayKeyProvider).value ??
67+
ref.read(savedRelayAuthorProvider).value
68+
: null,
69+
);
70+
}
71+
72+
/// Checks ownership for the Edit and Delete actions.
73+
/// Returns true if [viewer] is [author], or if [author]'s signed profile
74+
/// verifies [viewer] as its owner.
75+
/// If a restored profile names [viewer] as owner and lacks a signed copy,
76+
/// requests the profile again and returns false.
77+
/// Call when actions open so the check reads the latest cached profile.
78+
bool readCanManageMessage(WidgetRef ref, String author, String? viewer) {
79+
final key = author.toLowerCase();
80+
final me = viewer?.toLowerCase();
81+
if (me == null) return false;
82+
if (key == me) return true;
83+
final profile = ref.read(userCacheProvider)[key];
84+
final evidence = profile?.ownerEvidence;
85+
if (evidence == null) {
86+
// A restored profile without its signed copy names this viewer: fetch
87+
// the profile again so a later menu can verify the owner.
88+
if (profile?.ownerPubkey == me) {
89+
ref.read(userCacheProvider.notifier).get(key);
90+
}
91+
return false;
92+
}
93+
return verifiedEvidenceOwner(evidence, key) == me;
94+
}
95+
96+
/// Verified owners for comma-joined [authors]. Rebuilt only when one of
97+
/// their verified owners changes, so a timeline reformats only then.
98+
final _editOwnersProvider = Provider.autoDispose
99+
.family<Map<String, String>, String>(
100+
(ref, authors) => {
101+
for (final author in authors.split(','))
102+
author: ?ref.watch(verifiedProfileOwnerProvider(author)),
103+
},
104+
);
105+
106+
/// The relay key last read live for this identity and relay.
107+
class _LearnedRelayKey {
108+
String? value;
109+
}
110+
111+
/// One per identity and relay, so a key never outlives its community.
112+
final _learnedRelayKeyProvider = Provider<_LearnedRelayKey>((ref) {
113+
ref.watch(
114+
relayConfigProvider.select((config) => (config.baseUrl, config.nsec)),
115+
);
116+
return _LearnedRelayKey();
117+
});
118+
119+
/// The relay signing key trusted for edit attribution.
120+
///
121+
/// While connected, asks the relay (NIP-11); a key it returns replaces any
122+
/// earlier one at once, as the saved-message store does on rotation. While
123+
/// offline, reconnecting or reloading, keeps the key last read for this
124+
/// identity and relay, else the key the saved-message store holds. Watch it
125+
/// only when an edit needs it: watching while connected costs a request.
126+
final editRelayKeyProvider = Provider.autoDispose<String?>((ref) {
127+
final learned = ref.watch(_learnedRelayKeyProvider);
128+
final saved = ref.watch(savedRelayAuthorProvider).value;
129+
final connected = ref.watch(
130+
relaySessionProvider.select(
131+
(session) => session.status == SessionStatus.connected,
132+
),
133+
);
134+
if (connected) {
135+
final relay = ref.watch(
136+
relayConfigProvider.select((config) => config.baseUrl),
137+
);
138+
final live = ref.watch(relayAuthorProvider(relay)).value;
139+
if (live != null) learned.value = live;
140+
}
141+
return learned.value ?? saved;
142+
});

‎mobile/lib/features/channels/message_actions.dart‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -500,12 +500,13 @@ Future<void> _shareImage(
500500
}
501501

502502
/// Reuses the gallery's downloads, permissions and message authority for UIKit.
503+
/// [canManageMessage] is read when the gallery opens and before a delete.
503504
NativePhotoActions nativeImageActions({
504505
required BuildContext context,
505506
required WidgetRef ref,
506507
required TimelineMessage message,
507508
required String channelId,
508-
required bool canManageMessage,
509+
required bool Function() canManageMessage,
509510
}) => NativePhotoActions(
510511
canDelete: canManageMessage,
511512
perform: (action, url) async {
@@ -532,7 +533,7 @@ NativePhotoActions nativeImageActions({
532533
await Clipboard.setData(ClipboardData(text: url));
533534
return 'Image link copied';
534535
case 'delete':
535-
if (!canManageMessage) return 'You cannot delete this message';
536+
if (!canManageMessage()) return 'You cannot delete this message';
536537
await ref
537538
.read(channelActionsProvider)
538539
.deleteMessage(channelId: channelId, eventId: message.id);

0 commit comments

Comments
 (0)