Files
buzz/mobile/lib/features/channels/thread_detail_page/thread_message.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

482 lines
22 KiB
Dart

part of '../thread_detail_page.dart';
const _landingHighlightOpacity = 0.12;
class _ThreadMessage extends HookConsumerWidget {
final TimelineMessage message;
final Map<String, String> channelNames;
final String channelId;
final String? currentPubkey;
final bool showAuthor;
final bool showAvatar;
final bool startsDay;
final bool endsDay;
final bool isHighlighted;
final List<TimelineMessage>? allMessages;
final bool isMember;
final bool isArchived;
final FocusNode? composerFocusNode;
final VoidCallback? restoreComposerFocus;
/// Whether this is the message the thread hangs off, which keeps a standing
/// "+" where replies only get one once they carry a reaction.
final bool isThreadHead;
const _ThreadMessage({
required this.message,
required this.channelNames,
required this.channelId,
required this.currentPubkey,
required this.showAuthor,
this.showAvatar = true,
this.startsDay = false,
this.endsDay = false,
this.isHighlighted = false,
this.allMessages,
this.isMember = false,
this.isArchived = false,
this.isThreadHead = false,
this.composerFocusNode,
this.restoreComposerFocus,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final container = ProviderScope.containerOf(context, listen: false);
final startsThreads = ref.watch(channelStartsThreadsProvider(channelId));
// This page is the head's thread, so replying to the head focuses its
// composer rather than pushing another copy of the page. A head without a
// composer offers no reply.
final onReply = isThreadHead ? restoreComposerFocus : null;
final replyMessages = isThreadHead && onReply == null ? null : allMessages;
final VoidCallback? onMediaReply = replyMessages == null || !startsThreads
? null
: onReply ??
() {
if (!context.mounted) return;
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => ThreadDetailPage(
threadHead: message,
allMessages: replyMessages,
channelId: channelId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
),
),
);
};
final messageSnapshotKey = useMemoized(GlobalKey.new, const []);
final swipeContentKey = useMemoized(GlobalKey.new, const []);
final mediaOffset = useMessageMediaOffset(message.content, message.tags);
final pk = message.pubkey.toLowerCase();
final ownMessage = currentPubkey?.toLowerCase() == pk;
final showSenderIdentity = showMessageAuthorName(
ref,
channelId,
message.pubkey,
currentPubkey,
);
final profile =
ref.watch(userCacheProvider.select((cache) => cache[pk])) ??
ref.read(userCacheProvider.notifier).get(pk);
final displayName = watchChannelIdentityLabel(ref, channelId, pk);
final isAgent =
ref.watch(agentMentionPubkeysProvider(channelId)).contains(pk) ||
profile?.ownerPubkey != null;
final userCache = ref.watch(userCacheProvider);
final knownAgentPubkeys = agentPubkeysWithProfileOwners(
knownAgentPubkeys: ref.watch(agentMentionPubkeysProvider(channelId)),
profileOwnedAgentPubkeys: [
for (final profile in userCache.values)
if (profile.ownerPubkey != null) profile.pubkey,
],
);
final mentionNames = <String, String>{};
final agentMentionPubkeys = <String>{};
for (final mpk in message.mentionPubkeys) {
final normalizedPubkey = mpk.toLowerCase();
final p = userCache[normalizedPubkey];
if (p?.displayName != null) {
mentionNames[normalizedPubkey] = p!.displayName!;
}
if (knownAgentPubkeys.contains(normalizedPubkey)) {
agentMentionPubkeys.add(normalizedPubkey);
}
}
final resolvedMentionNames = mentionNamesWithDirectoryLabels(
mentionPubkeys: message.mentionPubkeys,
profileMentionNames: mentionNames,
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: agentMentionPubkeys,
);
final mentionLabels = watchChannelIdentityLabels(
ref,
channelId,
message.mentionPubkeys,
);
void openMessageActions(MessageLongPressDetails details) {
showMessageActions(
context: context,
ref: ref,
message: message,
channelId: channelId,
canManageMessage: readCanManageMessage(ref, pk, currentPubkey),
allMessages: replyMessages,
onReply: onReply,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
anchorRect: details.anchorRect,
captureAnchorSnapshot: details.captureSnapshot,
onPopoverPreviewVisibilityChanged: details.setSourceHidden,
onPopoverDismissed: () => details.setSourceHidden(false),
composerFocusNode: composerFocusNode,
restoreComposerFocus: restoreComposerFocus,
);
}
final reducedMotion = MediaQuery.disableAnimationsOf(context);
final highlightController = useAnimationController(
duration: _landingHighlightTransitionDuration,
);
final highlightProgress = useAnimation(highlightController);
useEffect(() {
if (reducedMotion) {
highlightController.value = isHighlighted ? 1 : 0;
} else {
unawaited(
highlightController.animateTo(
isHighlighted ? 1 : 0,
duration: _landingHighlightTransitionDuration,
curve: Curves.easeOutCubic,
),
);
}
return null;
}, [highlightController, isHighlighted, reducedMotion]);
final highlightColor = highlightProgress == 0
? Colors.transparent
: context.colors.primary.withValues(
alpha: _landingHighlightOpacity * highlightProgress,
);
final content = NotificationListener<MessageGalleryScrollNotification>(
onNotification: (notification) {
mediaOffset.value = notification.offset;
return true;
},
child: Padding(
padding: EdgeInsets.only(top: showAuthor && !startsDay ? Grid.xs : 0),
child: DecoratedBox(
key: ValueKey('thread-message-${message.id}'),
decoration: BoxDecoration(
color: highlightColor,
borderRadius: BorderRadius.circular(Radii.md),
),
child: Material(
color: Colors.transparent,
borderRadius: BorderRadius.circular(Radii.md),
// The media carousel intentionally continues through the list's
// trailing gutter. InkWell still clips its ink to [borderRadius],
// while leaving overflowing message content visible.
clipBehavior: Clip.none,
child: MessageLongPressInkWell(
key: ValueKey('thread-message-row-${message.id}'),
onLongPressDetails: openMessageActions,
borderRadius: BorderRadius.circular(Radii.md),
highlightColor: context.colors.primary.withValues(alpha: 0.1),
snapshotKey: messageSnapshotKey,
// Empty row space beside the message's parts is not the message.
targetsOnly: true,
child: Padding(
padding: EdgeInsets.only(
bottom: endsDay
? 0
: (showAvatar ? Grid.quarter : Grid.quarter / 2),
),
child: MessageFooterLayout(
animateSize: true,
overlap: message.reactions.isNotEmpty ? Grid.xs : 0,
footer: (isThreadHead || message.reactions.isNotEmpty)
? Align(
alignment: ownMessage
? Alignment.centerRight
: Alignment.centerLeft,
child: Padding(
padding: EdgeInsets.only(
right: ownMessage ? Grid.xxs : 0,
left: ownMessage || !showSenderIdentity
? 0
: messageAvatarSize +
messageAvatarContentGap +
Grid.xxs,
),
child: MessageLongPressTarget(
child: ReactionRow(
combined: true,
messageId: message.id,
channelId: channelId,
reactions: message.reactions,
onToggle: (emoji) => toggleReaction(
context,
container,
message,
emoji,
),
showAddButton: isMember && !isArchived,
onAddReaction: addReactionPickerFor(
context: context,
message: message,
),
),
),
),
)
: const SizedBox.shrink(),
child: RepaintBoundary(
key: messageSnapshotKey,
child: Stack(
clipBehavior: Clip.none,
children: [
Row(
textDirection: ownMessage
? TextDirection.rtl
: TextDirection.ltr,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (!ownMessage && showSenderIdentity)
const SizedBox(width: messageAvatarSize),
if (!ownMessage && showSenderIdentity)
const SizedBox(width: messageAvatarContentGap),
Expanded(
child: Padding(
padding: EdgeInsets.only(
top: showAuthor && !startsDay ? Grid.half : 0,
),
child: Column(
crossAxisAlignment: ownMessage
? CrossAxisAlignment.end
: CrossAxisAlignment.start,
children: [
if (showAuthor)
Padding(
padding: EdgeInsets.only(
bottom: Grid.quarter,
left: ownMessage
? 0
: messageBubbleHorizontalInset,
right: ownMessage
? messageBubbleHorizontalInset
: 0,
),
child: MessageLongPressTarget(
child: MessageAuthorMeta(
mainAxisSize: MainAxisSize.min,
timestampGap: Grid.half,
showIdentity: showSenderIdentity,
showTimestamp: true,
reversed: false,
alignment: ownMessage
? MainAxisAlignment.end
: MainAxisAlignment.start,
nameStyle: messageBylineTextStyle
.copyWith(
fontWeight: FontWeight.w500,
),
metadataStyle:
messageBylineTextStyle,
timestampStyle:
messageBylineTextStyle,
displayName: ownMessage
? 'You'
: displayName,
username: ownMessage
? null
: messageUsernameLabel(profile),
timestamp: formatMessageTime(
message.createdAt,
),
nameColor:
context.tertiaryTextColor,
metadataColor:
context.tertiaryTextColor,
onAuthorTap: () =>
showUserProfileSheet(
context,
message.pubkey,
names:
channelIdentityNamesProvider(
channelId,
),
),
displayNameKey: ValueKey(
'thread-message-author-${message.id}',
),
usernameKey: ValueKey(
'thread-message-username-${message.id}',
),
timestampKey: ValueKey(
'thread-message-timestamp-${message.id}',
),
),
),
),
IdentityLinkChannel(
channelId: channelId,
child: MessageContent(
key: swipeContentKey,
content: message.content,
edited: message.edited,
bubble: true,
additionalTextWidth:
!ownMessage && !showSenderIdentity
? messageAvatarSize +
messageAvatarContentGap
: 0,
hasReactions:
message.reactions.isNotEmpty,
bubbleEnd: showAvatar,
bubbleStart: showAuthor,
ownMessage: ownMessage,
trimTrailingSpacing: true,
mentionNames: resolvedMentionNames,
mentionLabels: mentionLabels,
agentMentionPubkeys:
agentMentionPubkeys,
channelNames: channelNames,
tags: message.tags,
baseStyle: messageBodyTextStyle
.copyWith(
color: context.colors.onSurface,
),
scaleEmojiOnly: true,
mediaCarouselTrailingOverflow:
Grid.gutter,
onMediaReply: onMediaReply,
nativePhotoActions: nativeImageActions(
context: context,
ref: ref,
message: message,
channelId: channelId,
canManageMessage: () =>
readCanManageMessage(
ref,
pk,
currentPubkey,
),
),
onMediaMore:
(viewerContext, imageUrl) =>
showImageActions(
context: viewerContext,
ref: ref,
message: message,
channelId: channelId,
imageUrl: imageUrl,
canManageMessage:
readCanManageMessage(
ref,
pk,
currentPubkey,
),
onDeleted: () {
if (viewerContext.mounted) {
Navigator.of(
viewerContext,
).maybePop();
}
},
),
onChannelTap: (targetChannelId) {
unawaited(
openChannelLink(
context: context,
ref: ref,
channelId: targetChannelId,
currentChannelId: channelId,
),
);
},
onMentionTap: (pubkey) =>
showUserProfileSheet(
context,
pubkey,
names:
channelIdentityNamesProvider(
channelId,
),
),
),
),
],
),
),
),
],
),
if (showAvatar && !ownMessage && showSenderIdentity)
Positioned(
left: ownMessage ? null : 0,
right: ownMessage ? 0 : null,
bottom: 0,
child: MessageMediaAvatar(
offset: mediaOffset,
child: MessageLongPressTarget(
child: Semantics(
container: true,
label: 'Open $displayName profile',
button: true,
excludeSemantics: true,
onTap: () => showUserProfileSheet(
context,
message.pubkey,
names: channelIdentityNamesProvider(
channelId,
),
),
child: GestureDetector(
onTap: () => showUserProfileSheet(
context,
message.pubkey,
names: channelIdentityNamesProvider(
channelId,
),
),
child: _Avatar(
profile: profile,
pubkey: message.pubkey,
isAgent: isAgent,
),
),
),
),
),
),
],
),
),
),
),
),
),
),
),
);
return MessageSwipeReply(
contentKey: swipeContentKey,
message: message,
allMessages: replyMessages,
onReply: onReply,
channelId: channelId,
currentPubkey: currentPubkey,
isMember: isMember,
isArchived: isArchived,
child: content,
);
}
}