Skip to content

Commit 9bcf69f

Browse files
committed
fix(mobile): preserve SEND scope and authority at owner 7534
Signed-off-by: Logan Johnson <[email protected]>
1 parent 2943008 commit 9bcf69f

9 files changed

Lines changed: 518 additions & 76 deletions

File tree

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ import 'voice_note_composer_recorder.dart';
4949
import 'voice_note_recording.dart';
5050

5151
part 'compose_bar/helpers.dart';
52+
part 'compose_bar/selected_mention_preparation.dart';
5253
part 'compose_bar/agent_mention_labels.dart';
5354
part 'compose_bar/markdown_editing_controller.dart';
5455
part 'compose_bar/draft_lifecycle.dart';

‎mobile/lib/features/channels/compose_bar/compose_bar_widget.dart‎

Lines changed: 76 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -485,50 +485,60 @@ class ComposeBar extends HookConsumerWidget {
485485
var authorizationRevision = submittedDraftRevision;
486486
final visit = authorizationVisit.value;
487487
final config = ref.read(relayConfigProvider);
488-
final readAuthorization = ref.read(agentAuthorizationReaderProvider);
488+
// Equivalent refreshes retain scope; destination/credentials do not.
489+
bool isConfigScopeCurrent() {
490+
final current = ref.read(relayConfigProvider);
491+
return current.baseUrl == config.baseUrl &&
492+
current.nsec == config.nsec;
493+
}
494+
495+
final readSelected = ref.read(
496+
selectedMentionAuthorizationReaderProvider,
497+
);
498+
final session = ref.read(relaySessionProvider.notifier);
499+
final observedProfiles = <String, NostrEvent>{};
500+
final observedKeys = <String>{};
501+
bool profilesCurrent() => observedProfiles.entries.every((entry) {
502+
final order = ref
503+
.read(userCacheProvider.notifier)
504+
.profileEventOrder(entry.key);
505+
final event = entry.value;
506+
return order == null ||
507+
order.createdAt < event.createdAt ||
508+
(order.createdAt == event.createdAt &&
509+
order.eventId.compareTo(event.id) >= 0);
510+
});
489511
bool ownsSource() =>
490512
context.mounted &&
491513
visit == authorizationVisit.value &&
492-
identical(config, ref.read(relayConfigProvider));
514+
isConfigScopeCurrent();
493515
bool isAuthorizationCurrent() =>
494516
ownsSource() &&
517+
identical(session, ref.read(relaySessionProvider.notifier)) &&
518+
currentPubkey == ref.read(currentPubkeyProvider) &&
519+
profilesCurrent() &&
495520
submittedUploadGeneration == uploadGeneration.value &&
496521
authorizationRevision == draftRevision.value &&
497-
identical(config, ref.read(relayConfigProvider));
522+
isConfigScopeCurrent();
498523
void ensureAuthorizationCurrent() {
499524
if (!context.mounted) throw const _ComposeAuthorizationCancelled();
500-
if (!identical(config, ref.read(relayConfigProvider))) {
501-
throw StateError('Community changed during authorization');
525+
if (!isConfigScopeCurrent()) {
526+
throw const _ComposeCommunityChanged();
502527
}
503528
if (submittedUploadGeneration != uploadGeneration.value ||
504529
visit != authorizationVisit.value ||
505530
authorizationRevision != draftRevision.value) {
506531
throw const _ComposeAuthorizationCancelled();
507532
}
533+
if (!identical(session, ref.read(relaySessionProvider.notifier)) ||
534+
currentPubkey != ref.read(currentPubkeyProvider) ||
535+
!profilesCurrent()) {
536+
throw Exception('Mention evidence changed; retry the draft');
537+
}
508538
}
509539

510540
checkPreparationCurrent = ensureAuthorizationCurrent;
511541

512-
Future<void> authorize(Set<String> keys, {bool prepare = false}) async {
513-
if (keys.isEmpty) return;
514-
ensureAuthorizationCurrent();
515-
try {
516-
await authorizeAgentMentions(
517-
readAuthorization,
518-
keys,
519-
currentPubkey,
520-
channelId,
521-
isAuthorizationCurrent,
522-
prepare: prepare,
523-
);
524-
} catch (_) {
525-
// A stale request is cancellation, not an access decision.
526-
ensureAuthorizationCurrent();
527-
rethrow;
528-
}
529-
ensureAuthorizationCurrent();
530-
}
531-
532542
// Resolved before any await: see
533543
// `_reportSendCancelledByCommunitySwitch`.
534544
final messenger = ScaffoldMessenger.maybeOf(context);
@@ -542,15 +552,34 @@ class ComposeBar extends HookConsumerWidget {
542552
selectedMentions,
543553
'${ref.read(relayConfigProvider).baseUrl} / $channelId',
544554
);
545-
final intendedAgentKeys = {
555+
final selectedKeys = outgoing.pubkeys.toSet();
556+
final priorAgentKeys = {
546557
for (final mention in selectedMentions)
547558
if (mention.isAgent) mention.pubkey.toLowerCase(),
548559
};
560+
Future<Map<String, SelectedMentionAuthorization>> authorize(
561+
Set<String> keys, {
562+
bool prepare = false,
563+
}) => _authorizeSelectedMentions(
564+
keys,
565+
readSelected: readSelected,
566+
priorAgentKeys: priorAgentKeys,
567+
observedKeys: observedKeys,
568+
observedProfiles: observedProfiles,
569+
currentPubkey: currentPubkey,
570+
channelId: channelId,
571+
ensureAuthorizationCurrent: ensureAuthorizationCurrent,
572+
isAuthorizationCurrent: isAuthorizationCurrent,
573+
prepare: prepare,
574+
);
575+
576+
final initialEvidence = await authorize(selectedKeys, prepare: true);
549577
final scan = await _scanNonMemberMentions(
550578
ref,
551579
channelId: channelId,
552580
selectedMentions: selectedMentions,
553581
currentPubkey: currentPubkey,
582+
evidence: initialEvidence,
554583
);
555584

556585
ensureAuthorizationCurrent();
@@ -583,7 +612,18 @@ class ComposeBar extends HookConsumerWidget {
583612

584613
// Agent failures stop publication; the original draft keeps its keys.
585614
Future<void> addMentionedNonMembers() async {
586-
final keys = intendedAgentKeys.intersection(outgoing.pubkeys.toSet());
615+
final keys = outgoing.pubkeys.toSet();
616+
Future<bool> authorizeWrite(String key, String role) async {
617+
final evidence = await authorize(keys, prepare: true);
618+
final fresh = evidence[key]!;
619+
if (fresh.invitationRole != role) {
620+
throw Exception(
621+
'Mention classification changed; retry invitation consent',
622+
);
623+
}
624+
return !fresh.isMember;
625+
}
626+
587627
await authorize(keys, prepare: true);
588628
ensureAuthorizationCurrent();
589629
invitationStarted.value = true;
@@ -592,6 +632,7 @@ class ComposeBar extends HookConsumerWidget {
592632
scan: scan,
593633
messenger: messenger,
594634
ensureCurrent: ensureAuthorizationCurrent,
635+
authorizeWrite: authorizeWrite,
595636
);
596637
if (!outgoing.pubkeys.toSet().containsAll(keys)) {
597638
throw Exception(
@@ -600,7 +641,7 @@ class ComposeBar extends HookConsumerWidget {
600641
}
601642
await authorize(keys);
602643
if (queuedAttachments.isEmpty ||
603-
(intendedAgentKeys.isNotEmpty ||
644+
(selectedKeys.isNotEmpty ||
604645
scan.humans.isNotEmpty ||
605646
scan.agentPubkeys.isNotEmpty)) {
606647
ensureAuthorizationCurrent();
@@ -639,7 +680,7 @@ class ComposeBar extends HookConsumerWidget {
639680
);
640681
// Agent authorization is preparation, not a detached background send.
641682
final preparingAgents =
642-
intendedAgentKeys.isNotEmpty || scan.humans.isNotEmpty;
683+
selectedKeys.isNotEmpty || scan.humans.isNotEmpty;
643684
if (!preparingAgents) clearComposer();
644685
final clearedDraftRevision = draftRevision.value;
645686
authorizationRevision = clearedDraftRevision;
@@ -697,8 +738,11 @@ class ComposeBar extends HookConsumerWidget {
697738
} on _ComposeAuthorizationCancelled {
698739
// Keep the newer draft without displaying a false access error.
699740
} catch (error) {
700-
if (cancellation.isCancelled) return;
701-
if (error is StateError) {
741+
if (cancellation.isCancelled &&
742+
error is! _ComposeCommunityChanged) {
743+
return;
744+
}
745+
if (error is _ComposeCommunityChanged) {
702746
_reportSendCancelledByCommunitySwitch(messenger);
703747
} else if (context.mounted) {
704748
uploadError.value = _formatUploadError(error);
@@ -735,25 +779,8 @@ class ComposeBar extends HookConsumerWidget {
735779
}
736780
}());
737781
} catch (error) {
738-
var communityChanged = false;
739-
// Failed awaits need the same scope/edit classification as success.
740-
try {
741-
checkPreparationCurrent?.call();
742-
if (error is _ComposeAuthorizationCancelled) return;
743-
} on _ComposeAuthorizationCancelled {
744-
return;
745-
} on StateError {
746-
communityChanged = true;
747-
}
748782
if (context.mounted) {
749-
final messenger = ScaffoldMessenger.maybeOf(context);
750-
if (communityChanged) {
751-
_reportSendCancelledByCommunitySwitch(messenger);
752-
} else {
753-
messenger?.showSnackBar(
754-
SnackBar(content: Text(_composeSendErrorMessage(error))),
755-
);
756-
}
783+
_reportComposeSendError(context, error, checkPreparationCurrent);
757784
}
758785
} finally {
759786
if (context.mounted && authorizationAttempt.value == attempt) {

‎mobile/lib/features/channels/compose_bar/draft_lifecycle.dart‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ class _ComposeAuthorizationCancelled implements Exception {
44
const _ComposeAuthorizationCancelled();
55
}
66

7+
class _ComposeCommunityChanged implements Exception {
8+
const _ComposeCommunityChanged();
9+
}
10+
711
Future<void> _sendTextOnlyDraft({
812
required BuildContext context,
913
required _MarkdownEditingController controller,
@@ -59,7 +63,7 @@ Future<void> _sendTextOnlyDraft({
5963
delivered = true;
6064
} on _ComposeAuthorizationCancelled {
6165
restoreClearedDraft();
62-
} on StateError {
66+
} on _ComposeCommunityChanged {
6367
restoreClearedDraft();
6468
_reportSendCancelledByCommunitySwitch(messenger);
6569
} catch (error) {

‎mobile/lib/features/channels/compose_bar/helpers.dart‎

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

3+
void _reportComposeSendError(
4+
BuildContext context,
5+
Object error,
6+
VoidCallback? checkPreparationCurrent,
7+
) {
8+
var displayError = error;
9+
var communityChanged = false;
10+
// Failed awaits need the same scope/edit classification as success.
11+
try {
12+
checkPreparationCurrent?.call();
13+
if (error is _ComposeAuthorizationCancelled) return;
14+
} on _ComposeAuthorizationCancelled {
15+
return;
16+
} on _ComposeCommunityChanged {
17+
communityChanged = true;
18+
} on Exception catch (currentError) {
19+
displayError = currentError;
20+
}
21+
if (context.mounted) {
22+
final messenger = ScaffoldMessenger.maybeOf(context);
23+
if (communityChanged) {
24+
_reportSendCancelledByCommunitySwitch(messenger);
25+
} else {
26+
messenger?.showSnackBar(
27+
SnackBar(content: Text(_composeSendErrorMessage(displayError))),
28+
);
29+
}
30+
}
31+
}
32+
333
String _composerDraftIdentity(WidgetRef ref) =>
434
'${ref.watch(relayConfigProvider).baseUrl}'
535
':${ref.watch(myPubkeyProvider) ?? 'anon'}';
@@ -450,6 +480,7 @@ Future<_NonMemberAddOutcome> _addMentionedNonMembers(
450480
required bool canAddMembers,
451481
required VoidCallback ensureCurrent,
452482
required VoidCallback onAccepted,
483+
required Future<bool> Function(String, String) authorizeWrite,
453484
}) async {
454485
final pending = [
455486
for (final pubkey in agentPubkeys) ([pubkey], 'bot'),
@@ -469,8 +500,10 @@ Future<_NonMemberAddOutcome> _addMentionedNonMembers(
469500
final notAdded = <String>[];
470501
final errors = <String>[];
471502
for (final (pubkeys, role) in pending) {
503+
ensureCurrent();
504+
if (!await authorizeWrite(pubkeys.single, role)) continue;
505+
ensureCurrent();
472506
try {
473-
ensureCurrent();
474507
await channelActions.addMembers(
475508
channelId: channelId,
476509
pubkeys: pubkeys,
@@ -480,7 +513,10 @@ Future<_NonMemberAddOutcome> _addMentionedNonMembers(
480513
ensureCurrent();
481514
} on _ComposeAuthorizationCancelled {
482515
rethrow;
516+
} on _ComposeCommunityChanged {
517+
rethrow;
483518
} on StateError {
519+
ensureCurrent();
484520
rethrow;
485521
} catch (error) {
486522
notAdded.addAll(
@@ -517,6 +553,7 @@ Future<_NonMemberMentionScan> _scanNonMemberMentions(
517553
required String channelId,
518554
required List<MentionCandidate> selectedMentions,
519555
required String? currentPubkey,
556+
required Map<String, SelectedMentionAuthorization> evidence,
520557
}) async {
521558
final none = _NonMemberMentionScan(
522559
channelId: channelId,
@@ -533,9 +570,6 @@ Future<_NonMemberMentionScan> _scanNonMemberMentions(
533570
).wait;
534571
final channel = channels.firstWhere((candidate) => candidate.id == channelId);
535572
if (channel.isDm) return none;
536-
final memberPubkeys = {
537-
for (final member in members) member.pubkey.toLowerCase(),
538-
};
539573
String? selfRole;
540574
if (currentPubkey != null) {
541575
final self = currentPubkey.toLowerCase();
@@ -552,8 +586,9 @@ Future<_NonMemberMentionScan> _scanNonMemberMentions(
552586
final seen = <String>{};
553587
for (final candidate in selectedMentions) {
554588
final pubkey = candidate.pubkey.toLowerCase();
555-
if (memberPubkeys.contains(pubkey) || !seen.add(pubkey)) continue;
556-
if (candidate.isAgent) {
589+
final fresh = evidence[pubkey]!;
590+
if (fresh.isMember || !seen.add(pubkey)) continue;
591+
if (fresh.invitationRole == 'bot') {
557592
agentPubkeys.add(pubkey);
558593
} else {
559594
humans.add(candidate);
@@ -621,8 +656,7 @@ class _OutgoingMentions {
621656
case _NonMemberMentionChoice.invite:
622657
_inviteAgents = true;
623658
_invitedHumanPubkeys = [
624-
for (final candidate in nonMembers)
625-
if (!candidate.isAgent) candidate.pubkey.toLowerCase(),
659+
for (final candidate in nonMembers) candidate.pubkey.toLowerCase(),
626660
];
627661
case _NonMemberMentionChoice.sendWithoutInviting:
628662
demote(nonMembers.map((candidate) => candidate.pubkey));
@@ -635,15 +669,19 @@ class _OutgoingMentions {
635669
required _NonMemberMentionScan scan,
636670
required ScaffoldMessengerState? messenger,
637671
required VoidCallback ensureCurrent,
672+
required Future<bool> Function(String, String) authorizeWrite,
638673
}) async {
639674
final outcome = await _addMentionedNonMembers(
640675
channelActions,
641676
channelId: scan.channelId,
642677
agentPubkeys: _inviteAgents ? scan.agentPubkeys : const [],
643-
humanPubkeys: _invitedHumanPubkeys,
678+
humanPubkeys: _invitedHumanPubkeys
679+
.where((key) => !scan.agentPubkeys.contains(key))
680+
.toList(),
644681
canAddMembers: scan.canAddMembers,
645682
ensureCurrent: ensureCurrent,
646683
onAccepted: () => acceptedInvitations++,
684+
authorizeWrite: authorizeWrite,
647685
);
648686
if (outcome.notAdded.isNotEmpty) {
649687
throw Exception('Message not sent. ${outcome.errors.join(' ')}');

0 commit comments

Comments
 (0)