fix(mobile): revalidate exact agent intent before publication

Signed-off-by: Logan Johnson <loganj@squareup.com>
This commit is contained in:
Logan Johnson
2026-09-05 17:47:08 -04:00
parent df61d54cb2
commit 59d171d647
5 changed files with 424 additions and 49 deletions

View File

@@ -41,6 +41,15 @@ class ComposeBar extends HookConsumerWidget {
final draftKey = composeDraftKey(channelId, threadHeadId: threadHeadId);
final draftRevision = useRef(0);
final draftIdentity = _composerDraftIdentity(ref);
final authorizationVisit = useRef<Object?>(null);
final authorizationAttempt = useRef<Object?>(null);
useEffect(() {
final visit = Object();
authorizationVisit.value = visit;
return () {
if (authorizationVisit.value == visit) authorizationVisit.value = null;
};
}, [draftKey, draftIdentity]);
final isComposerExpanded = useState(false);
final androidImeTransitionStarted = useState(
defaultTargetPlatform != TargetPlatform.android,
@@ -464,51 +473,93 @@ class ComposeBar extends HookConsumerWidget {
uploadingCount.value > 0) {
return;
}
final submittedDraftRevision = draftRevision.value;
// Resolved before any await: see
// `_reportSendCancelledByCommunitySwitch`.
final messenger = ScaffoldMessenger.maybeOf(context);
// Extract pubkeys for mentions present in the final text.
final selectedMentions = <MentionCandidate>[
for (final entry in mentionMap.value.entries)
if (hasMention(text, entry.key)) entry.value,
];
final outgoing = _OutgoingMentions(selectedMentions);
final scan = await _scanNonMemberMentions(
ref,
channelId: channelId,
selectedMentions: selectedMentions,
currentPubkey: currentPubkey,
);
// Mentioning humans outside the channel prompts "Invite" / "Do
// nothing" (send without inviting) — mirrors desktop's
// NonMemberMentionDialog. Agents keep the existing silent auto-add.
if (scan.humans.isNotEmpty) {
if (!context.mounted) return;
final choice = await _promptNonMemberMention(
context,
names: [for (final candidate in scan.humans) candidate.label],
canInvite: scan.canAddMembers,
);
if (choice == null) return; // Dismissed — keep the draft, send nothing.
outgoing.resolveHumanChoice(choice, scan.humans);
}
final queuedAttachments = List<_PendingAttachment>.of(attachments.value);
final channelActions = ref.read(channelActionsProvider);
// An add that was refused doesn't block the message: it is reported and
// the un-added mentions are demoted to reference tags so the send lands.
Future<void> addMentionedNonMembers() => outgoing.addNonMembers(
channelActions,
scan: scan,
messenger: messenger,
);
final attempt = Object();
authorizationAttempt.value = attempt;
isSending.value = true;
try {
final submittedDraftRevision = draftRevision.value;
var authorizationRevision = submittedDraftRevision;
final visit = authorizationVisit.value;
final config = ref.read(relayConfigProvider);
final readAuthorization = ref.read(agentAuthorizationReaderProvider);
bool isAuthorizationCurrent() =>
context.mounted &&
visit == authorizationVisit.value &&
authorizationRevision == draftRevision.value &&
identical(config, ref.read(relayConfigProvider));
// Resolved before any await: see
// `_reportSendCancelledByCommunitySwitch`.
final messenger = ScaffoldMessenger.maybeOf(context);
// Extract pubkeys for mentions present in the final text.
final selectedMentions = <MentionCandidate>[
for (final entry in mentionMap.value.entries)
if (hasMention(text, entry.key)) entry.value,
];
final outgoing = _OutgoingMentions(selectedMentions);
final intendedAgentKeys = {
for (final mention in selectedMentions)
if (mention.isAgent) mention.pubkey.toLowerCase(),
};
final scan = await _scanNonMemberMentions(
ref,
channelId: channelId,
selectedMentions: selectedMentions,
currentPubkey: currentPubkey,
);
if (intendedAgentKeys.isNotEmpty && !isAuthorizationCurrent()) return;
// Mentioning humans outside the channel prompts "Invite" / "Do
// nothing" (send without inviting) — mirrors desktop's
// NonMemberMentionDialog. Agents keep the existing silent auto-add.
if (scan.humans.isNotEmpty) {
if (!context.mounted) return;
final choice = await _promptNonMemberMention(
context,
names: [for (final candidate in scan.humans) candidate.label],
canInvite: scan.canAddMembers,
);
if (choice == null) {
return; // Dismissed — keep the draft, send nothing.
}
outgoing.resolveHumanChoice(choice, scan.humans);
}
final queuedAttachments = List<_PendingAttachment>.of(
attachments.value,
);
final channelActions = ref.read(channelActionsProvider);
// Agent failures stop publication; the original draft keeps its keys.
Future<void> addMentionedNonMembers() async {
final keys = intendedAgentKeys.intersection(outgoing.pubkeys.toSet());
await authorizeAgentMentions(
readAuthorization,
keys,
currentPubkey,
channelId,
isAuthorizationCurrent,
prepare: true,
);
await outgoing.addNonMembers(
channelActions,
scan: scan,
messenger: messenger,
);
if (!outgoing.pubkeys.toSet().containsAll(keys)) {
throw Exception(
'Mention invitation failed. Draft kept; retry or remove the mention.',
);
}
await authorizeAgentMentions(
readAuthorization,
keys,
currentPubkey,
channelId,
isAuthorizationCurrent,
);
}
if (queuedAttachments.isEmpty) {
if (!context.mounted) return;
await _sendTextOnlyDraft(
@@ -532,13 +583,17 @@ class ComposeBar extends HookConsumerWidget {
return;
}
if (intendedAgentKeys.isNotEmpty && !isAuthorizationCurrent()) return;
final draftText = controller.value;
final draftAttachments = List<_PendingAttachment>.of(attachments.value);
final draftMentions = Map<String, MentionCandidate>.of(
mentionMap.value,
);
clearComposer();
// Agent authorization is preparation, not a detached background send.
final preparingAgents = intendedAgentKeys.isNotEmpty;
if (!preparingAgents) clearComposer();
final clearedDraftRevision = draftRevision.value;
authorizationRevision = clearedDraftRevision;
uploadingCount.value += 1;
uploadProgress.value = 0;
isSending.value = false;
@@ -578,6 +633,11 @@ class ComposeBar extends HookConsumerWidget {
if (queueGeneration != uploadGeneration.value) return;
await addMentionedNonMembers();
if (queueGeneration != uploadGeneration.value) return;
if (preparingAgents) {
if (!isAuthorizationCurrent()) return;
clearComposer();
authorizationRevision = draftRevision.value;
}
await delivery(
payload.content,
outgoing.pubkeys,
@@ -585,10 +645,12 @@ class ComposeBar extends HookConsumerWidget {
);
} catch (error) {
if (cancellation.isCancelled) return;
if (context.mounted) uploadError.value = _formatUploadError(error);
if (context.mounted) {
uploadError.value = _formatUploadError(error);
}
if (context.mounted &&
queueGeneration == uploadGeneration.value &&
draftRevision.value == clearedDraftRevision) {
draftRevision.value == authorizationRevision) {
controller.value = draftText;
attachments.value = draftAttachments;
retainedForRetry = true;
@@ -598,7 +660,13 @@ class ComposeBar extends HookConsumerWidget {
focusNode.requestFocus();
}
} finally {
if (!retainedForRetry) {
final sourceRetainsFiles =
preparingAgents &&
context.mounted &&
attachments.value.any(
(item) => queuedAttachments.contains(item),
);
if (!retainedForRetry && !sourceRetainsFiles) {
await _deleteOwnedAttachments(queuedAttachments);
}
if (activeUploadCancellation.value == cancellation) {
@@ -609,8 +677,17 @@ class ComposeBar extends HookConsumerWidget {
}
}
}());
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(content: Text(_composeSendErrorMessage(error))),
);
}
} finally {
if (context.mounted && isSending.value) isSending.value = false;
if (context.mounted && authorizationAttempt.value == attempt) {
authorizationAttempt.value = null;
isSending.value = false;
}
}
}

View File

@@ -10,6 +10,7 @@ import '../../shared/relay/relay.dart';
part 'agent_policy.dart';
part 'agent_authorization.dart';
part 'agent_publication.dart';
/// A relay agent parsed from its kind:10100 agent-profile event.
///

View File

@@ -0,0 +1,64 @@
part of 'agent_identity_provider.dart';
/// Fresh reader used by the composer; suggestions never authorize publication.
typedef AgentAuthorizationReader =
Future<List<AgentDirectoryEntry>> Function(
Set<String> keys,
String? viewer,
String channelId,
bool Function() isCurrent,
);
final agentAuthorizationReaderProvider = Provider<AgentAuthorizationReader>((
ref,
) {
final session = ref.watch(relaySessionProvider.notifier);
return (keys, viewer, channelId, isCurrent) => readAgentAuthorization(
session,
keys,
viewer: viewer,
channelId: channelId,
isCurrent: isCurrent,
);
});
/// Verify every intended recipient; never silently shrink the notification set.
Future<void> authorizeAgentMentions(
AgentAuthorizationReader read,
Set<String> keys,
String? viewer,
String channelId,
bool Function() isCurrent, {
bool prepare = false,
}) async {
if (keys.isEmpty) return;
const message =
'Could not authorize a mentioned agent. Check its access and channel membership, then retry or remove the mention.';
try {
if (!isCurrent()) throw Exception(message);
final agents = await read(keys, viewer, channelId, isCurrent);
if (!isCurrent()) throw Exception(message);
for (final key in keys) {
final agent = agents.where((a) => a.pubkey == key).firstOrNull;
final owned = agent?.ownerPubkey != null && agent?.ownerPubkey == viewer;
final allowed =
agent != null &&
((owned &&
const [
'owner-only',
'allowlist',
'anyone',
].contains(agent.respondTo)) ||
(agent.respondTo == 'allowlist' &&
agent.respondToAllowlist.contains(viewer)) ||
(agent.respondTo == 'anyone' &&
agent.channelIds.contains(channelId)));
if (!allowed ||
(!(prepare && owned) && !agent.channelIds.contains(channelId))) {
throw Exception(message);
}
}
} catch (_) {
throw Exception(message);
}
}

View File

@@ -30,6 +30,8 @@ import 'package:buzz/shared/widgets/anchored_popover_menu.dart';
import 'package:buzz/shared/widgets/mobile_tab_footer_backdrop.dart';
import 'package:shared_preferences/shared_preferences.dart';
part 'compose_bar_test/publication_tests.dart';
final _pngBytes = Uint8List.fromList([
0x89,
0x50,
@@ -174,6 +176,7 @@ Widget _buildComposeBar({
required ComposeBarOnSend onSend,
List<ChannelMember> members = const <ChannelMember>[],
Future<List<ChannelMember>>? membersFuture,
AgentAuthorizationReader? authorizationReader,
List<AgentDirectoryEntry> relayAgents = const <AgentDirectoryEntry>[],
List<Channel> channels = const <Channel>[],
List<ChannelMember> cachedMembers = const <ChannelMember>[],
@@ -210,6 +213,18 @@ Widget _buildComposeBar({
channelMembersProvider(
'channel-1',
).overrideWith((ref) => membersFuture ?? Future.value(members)),
agentAuthorizationReaderProvider.overrideWithValue(
authorizationReader ??
(keys, viewer, channel, current) async => [
for (final key in keys)
AgentDirectoryEntry(
pubkey: key,
respondTo: 'anyone',
ownerPubkey: viewer,
channelIds: [channel],
),
],
),
agentDirectoryProvider.overrideWith((ref) async => relayAgents),
agentOwnersProvider.overrideWith((ref) async => const <String, String>{}),
relayClientProvider.overrideWithValue(
@@ -641,6 +656,7 @@ class _FakeChannelsNotifier extends ChannelsNotifier {
}
void main() {
_publicationTests();
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() async {
@@ -4235,7 +4251,7 @@ void main() {
addMemberAcknowledgement.complete();
await tester.pumpAndSettle();
expect(sentContent, 'hello @Helper Bot');
expect(sentContent, isNull);
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
'newer draft',

View File

@@ -0,0 +1,217 @@
part of '../compose_bar_test.dart';
void _publicationTests() {
for (final mode in [
'deny',
'missing',
'error',
'revoke',
'removed',
'allow',
]) {
testWidgets('publication authorization $mode retains exact intent', (
tester,
) async {
final key = 'd' * 64;
final signer = nostr.Keys.generate();
var reads = 0;
var sent = 0;
await tester.pumpWidget(
_buildComposeBar(
uploadService: _testUploadService(signer.nsec),
currentPubkey: signer.public,
relayAgents: [_testAgent(key)],
channels: [
_makeCurrentChannel(channelType: 'dm'),
_makeSharedMemberChannel(),
],
authorizationReader: (keys, viewer, destination, current) async {
expect(keys, {key});
expect(destination, 'channel-1');
expect(current(), isTrue);
reads++;
if (mode == 'error') throw StateError('unavailable');
if (mode == 'missing') return [];
return [
AgentDirectoryEntry(
pubkey: key,
ownerPubkey: viewer,
respondTo: mode == 'deny' || (mode == 'revoke' && reads == 2)
? 'nobody'
: 'anyone',
channelIds: mode == 'removed' && reads == 2
? []
: ['channel-1'],
),
];
},
onSend: (_, keys, {mediaTags = const []}) async {
expect(keys, [key]);
sent++;
},
),
);
await _selectAndSendAgentMention(tester);
expect(sent, mode == 'allow' ? 1 : 0);
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
mode == 'allow' ? '' : 'hello @Helper Bot',
);
if (mode != 'allow') {
expect(
find.textContaining('Could not authorize a mentioned agent'),
findsOneWidget,
);
}
expect(
reads,
const ['allow', 'revoke', 'removed'].contains(mode) ? 2 : 1,
);
});
}
testWidgets(
'editing while authorization waits cancels publication without overwriting new draft',
(tester) async {
final key = 'd' * 64;
final signer = nostr.Keys.generate();
final pending = Completer<List<AgentDirectoryEntry>>();
var reads = 0;
var sent = 0;
await tester.pumpWidget(
_buildComposeBar(
uploadService: _testUploadService(signer.nsec),
currentPubkey: signer.public,
relayAgents: [_testAgent(key)],
channels: [
_makeCurrentChannel(channelType: 'dm'),
_makeSharedMemberChannel(),
],
authorizationReader: (_, _, _, _) {
reads++;
return pending.future;
},
onSend: (_, _, {mediaTags = const []}) async {
sent++;
},
),
);
await _expandComposer(tester);
await tester.enterText(find.byType(TextField), '@hel');
await tester.pumpAndSettle();
await tester.tap(find.text('Helper Bot'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'hello @Helper Bot');
await tester.tap(find.byIcon(LucideIcons.arrowUp));
await tester.pump();
expect(reads, 1);
await tester.enterText(find.byType(TextField), 'new intent');
pending.complete([
AgentDirectoryEntry(
pubkey: key,
respondTo: 'anyone',
channelIds: ['channel-1'],
),
]);
await tester.pumpAndSettle();
expect(sent, 0);
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
'new intent',
);
},
);
testWidgets('revocation after upload retains agent draft and attachment', (
tester,
) async {
final signer = nostr.Keys.generate();
final key = 'd' * 64;
final response = Completer<http.Response>();
var uploaded = false;
var reads = 0;
var sent = 0;
final service = MediaUploadService(
baseUrl: 'https://relay.example',
nsec: signer.nsec,
httpClient: http_testing.MockClient((_) {
uploaded = true;
return response.future;
}),
pickGalleryVideo: () async => null,
pickGalleryImage: () async => null,
pickGalleryImages: () async => [
XFile.fromData(_pngBytes, name: 'tiny.png'),
],
);
await tester.pumpWidget(
_buildComposeBar(
uploadService: service,
currentPubkey: signer.public,
relayAgents: [_testAgent(key)],
channels: [
_makeCurrentChannel(channelType: 'dm'),
_makeSharedMemberChannel(),
],
authorizationReader: (_, viewer, _, _) async {
reads++;
return [
AgentDirectoryEntry(
pubkey: key,
ownerPubkey: viewer,
respondTo: reads == 1 ? 'anyone' : 'nobody',
channelIds: ['channel-1'],
),
];
},
onSend: (_, _, {mediaTags = const []}) async {
sent++;
},
),
);
await _openSystemPhotoPicker(tester);
await tester.pumpAndSettle();
await _expandComposer(tester);
await tester.enterText(find.byType(TextField), '@hel');
await tester.pumpAndSettle();
await tester.tap(find.text('Helper Bot'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'hello @Helper Bot');
await tester.tap(find.byIcon(LucideIcons.arrowUp));
await tester.runAsync(() async {
for (var i = 0; i < 100 && !uploaded; i++) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
});
expect(uploaded, isTrue);
response.complete(
http.Response(
jsonEncode({
'url': 'https://relay.example/media/test.png',
'sha256': '0' * 64,
'size': 16,
'type': 'image/png',
'uploaded': 1,
}),
200,
),
);
await tester.runAsync(() async {
await Future<void>.delayed(const Duration(milliseconds: 100));
});
await tester.pumpAndSettle();
expect(reads, 2);
expect(sent, 0);
expect(
tester.widget<TextField>(find.byType(TextField)).controller!.text,
'hello @Helper Bot',
);
expect(
find.byKey(const ValueKey('composer-agent-mention-chip')),
findsOneWidget,
);
expect(
find.textContaining('Could not authorize a mentioned agent'),
findsOneWidget,
);
});
}