Files
buzz/mobile/test/features/onboarding/known_community_sync_integration_test.dart
klopez4212 a82d596fc2 mobile: show account communities in the switcher and sync saved destinations (#9262)
## Summary

Switch Community currently shows only device-saved communities, leaving
account destinations behind a separate Find step. It now merges saved
communities with supported account destinations directly, keeps Add
Community, and removes the redundant Find action from that Add route.
Initial onboarding and identity recovery keep their discovery entry.
Find lists supported account addresses before hosted identity setup;
hosted selection still performs binding, backup, and admission, while
external selection opens the existing identity flow.

Mobile also saves QR/address additions and explicit removals through
Builder Lab's existing known-communities account APIs. A per-account
local journal retries transient failures, survives restarts, pauses in
the background, and fences requests against account changes. External
secure addresses use the existing self-hosted entry flow; account
destinations never imply membership or bypass admission. Remote list
omissions do not delete local identities.

Explicit additions store an account owner and revision atomically with
local credentials. Legacy/unclaimed destinations remain local-only until
explicitly added while signed in; signing into another account never
claims retained destinations. Restart reconciliation lets a committed
re-add supersede an older removal even if the retry-journal write
failed. Local deletion and its credential-free account-removal intent
commit in one storage write, independent of the account-only retry
journal. Removing one of several local identities owned by the same
account at an address retains its account destination until that
account’s last identity is removed. Another account’s saved identity
does not block removal or lose its credentials during recovery. Offline
edits retain the stored account subject without treating it as network
authorization. Discovery-only intent survives browser callbacks, app
restart, and retry. Onboarding recovery controls have a Material
ancestor in the actual route. Pending status is fenced to the current
subject; interrupted older removals offer explicit local completion, and
denied requests offer browser reauthentication. Same-host ports have
distinct labels and confirmations, and unsupported hosted ports are
excluded.

This changes the mobile client and its public-build CI test list only:
no relay endpoints, events, migrations, or backend deployment.

### Related issue

No duplicate found among open known-communities/switcher issues and PRs.
Related picker editing work: #6632 (renaming communities).

### Testing

Validated after merging main (`02535e1b53`) at
`c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover
push-revocation commit ordering, same-account removal confirmation, and
recovery after completed hosted admission. The merge also preserves
main’s toolbar and session protections; a test override now accepts the
updated relay subscription parameter.

- Formatting, static analysis, and differential file-size checks pass.
- Prior full CI and security review passed on `3adb117aae`; security
checks also passed on `cf3836ecb`. Fresh CI and security review are
required for this head.
- Mutation checks fail when either the initiating-account removal guard
or the rendered-status subject fence is removed; both guards were
restored before final validation.
- CI explicitly runs the public-only account discovery and
synchronization journeys.
- Added journeys cover paused removal across A→B, offline restart,
journal read/write failures, duplicate local identities in either
removal order, delayed status reads across accounts, real browser
handoff after denial, unbound external discovery, and local same-host
port removal.
- Earlier journeys cover pairing acknowledgement and restart after
journal-write failure, same-subject setup completion, offline/rejected
removal with reopen/retry, and fresh external-only/mixed account entry.
- Regression coverage includes discovery deduplication and retry, hosted
and external selection, Add without Find, account-only removal, shared
authentication/removal persistence, restart recovery, latest-intent
ordering, account changes, and retry pause/resume.
- `just mobile-check`, `just file-size-check`, and `just mobile-test`:
4,954 default-build tests passed (71 skipped), plus 27 crypto-package
tests.
- Full public-account suite: 5,012 passed, 12 skipped, one pre-existing
failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until
community choice and admission"). The same assertion was reproduced on
clean base `8cce12f591`: expected both communities imported, actual only
the selected community.
- Follow-up regression journeys cover both A/B same-address removal
orderings, recovery preserving B’s saved key, the production onboarding
widget composition, and retained discovery intent with callback/retry
plus normal-sign-in controls.
- Native/live-account and human testing remain outstanding. The tests
use fake network/storage boundaries; live account API behavior,
cross-device synchronization, native accessibility, and
timeout/late-server-commit ordering still require integration
verification.

- The three expanded recovery/removal journeys pass and each fails when
the corresponding fix is removed. A durably journaled revocation now
finishes the confirmed removal even if the account changes during
journaling; pre-journal account mismatches still abort. Confirmation
copy counts only same-account identities. Explicit account recovery
retires a completed join target while preserving in-progress targets.

### Preview

Sample-data Flutter widget renders: saved-only and combined lists. These
illustrate the picker layout, not a device session or live account sync.

| Saved-only | Combined |
| --- | --- |
| ![Saved-only
picker](https://github.com/user-attachments/assets/eeadbd28-5ef0-4bc1-a381-8fdf71563144)
| ![Combined
picker](https://github.com/user-attachments/assets/58080884-82c2-4538-8d9d-54eb95218d81)
|

### Manual verification

1. Sign into a public account with a community saved on another device.
Open Switch Community; verify it appears alongside local choices and
Add.
2. Select a hosted and an external community; verify the existing
identity/admission flow opens. Add should not offer Find again.
3. Add a community by QR/address, then check the account list on
desktop. Remove it on mobile and verify the account entry disappears
while other devices retain their local credentials.
4. Repeat removal offline, restart, then reconnect/resume. Verify the
queued removal reaches the account service without switching identities.
5. On a fresh device, verify external-only and mixed account lists offer
external entry. Check two ports on the same host remain distinguishable.
6. Sign out of account A and into B; retained A destinations must not
upload to B. Explicitly add a B destination and verify it syncs.
7. Reject or interrupt account removal; verify visible pending/failure
status. A denied session must open browser sign-in through “Sign in
again” and retry after exchange; setup-required accounts retain their
setup action.
8. Keep two local identities owned by the same account at one address;
removing the first must keep the account entry, and removing the last
must queue account removal. Repeat with A and B at that address;
removing A must preserve B’s saved credentials and still sync A’s
removal.
9. Restart offline with a stored account, add/remove an external
community, then reconnect as the same account and verify convergence.
Explicit sign-out must not claim new local-only entries.


10. Start Find my communities, restart during browser authentication,
then return or retry. External destinations must appear before hosted
identity setup; normal sign-in must retain its identity checks.

---------

Signed-off-by: kenny lopez <klopez4212@gmail.com>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-15 15:07:56 -08:00

532 lines
20 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'package:flutter/widgets.dart';
import 'package:buzz/shared/hosted/account_community_sync_status.dart';
import 'dart:async';
import 'dart:convert';
import 'package:buzz/features/pairing/pairing_provider.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import '../../helpers/controllable_pairing_socket.dart';
import 'package:buzz/features/channels/channels_page.dart';
import 'package:buzz/shared/community/community_icon_provider.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import '../../helpers/widget_helpers.dart';
import 'package:buzz/shared/auth/auth_provider.dart';
import 'package:buzz/shared/community/community.dart';
import 'package:buzz/shared/community/community_provider.dart';
import 'package:buzz/shared/community/community_storage.dart';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/hosted/known_community_sync.dart';
import 'package:buzz/shared/hosted/known_community_sync_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:nostr/nostr.dart' as nostr;
import '../../shared/community/community_storage_test.dart'
show FakeSecureStorage;
class _Account extends BuilderlabAccountClient {
final changes = ValueNotifier<String?>('owner');
final calls = <String>[];
Object? failure;
List<String> urls = ['wss://paired.example'];
final targets = <String>[];
@override
ValueListenable<String?> get subjectChanges => changes;
@override
BuilderlabAccount get account => BuilderlabAccount(
subject: 'owner',
expiresAt: DateTime.now().add(const Duration(hours: 1)),
);
@override
Future<BuilderlabAccount?> restore() async => account;
@override
Future<Map<String, dynamic>> post(
String path,
Map<String, dynamic> body, {
String? expectedSubject,
}) async {
expectSync(expectedSubject, 'owner');
if (path.endsWith('/list')) {
return {
'communities': urls.map((url) => {'community_url': url}).toList(),
};
}
expectSync(urls, contains(body['community_url']));
targets.add(body['community_url'] as String);
calls.add(path.split('/').last);
if (failure case final error?) throw error;
return {};
}
}
class _JournalStorage extends FakeSecureStorage {
bool failWrites = false;
@override
Future<void> write({
required String key,
required String? value,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) {
if (failWrites) throw StateError('Account journal unavailable');
return super.write(key: key, value: value);
}
}
void main() {
for (final localEntries in [false, true]) {
testWidgets(
'removing ${localEntries ? 'local' : 'account-only'} ports shows precise pending removal',
(tester) async {
if (!HostedEnvironment.enabled) return;
final account = _Account()
..urls = ['wss://team.example:8443', 'wss://team.example:9443'];
final storage = CommunityStorage(secure: FakeSecureStorage());
if (localEntries) {
for (final port in [8443, 9443]) {
await storage.save(
Community(
id: '$port',
name: 'team.example',
relayUrl: 'wss://team.example:$port',
addedAt: DateTime(2025),
),
);
}
}
if (localEntries) {
await storage.save(
Community(
id: 'other-owner',
name: 'Other identity',
relayUrl: 'wss://team.example:9443',
addedAt: DateTime(2025),
accountSyncOwner: '${account.accountOrigin.origin}\nother',
),
);
}
final label = localEntries
? 'team.example (team.example:9443)'
: 'team.example:9443';
final sync = KnownCommunitySync(
account: account,
storage: FakeSecureStorage(),
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
);
// Keep the server response stale so the durable removal filter is exercised.
sync.setActive(false);
addTearDown(sync.dispose);
await tester.pumpWidget(
WidgetHelpers.testable(
enableAccountCommunitySync: true,
overrides: [
builderlabAccountProvider.overrideWithValue(account),
communityStorageProvider.overrideWithValue(storage),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue(
(_) async => false,
),
knownCommunitySyncProvider.overrideWithValue(sync),
communityIconPresentationProvider.overrideWith(
(ref, relay) => null,
),
],
child: CommunitySwitcherPage(
destination: null,
prepareLanding: () async => null,
onFlightChanged: (_) {},
onTransitionProgress: (_) {},
),
),
);
await tester.pumpAndSettle();
expect(find.text(label), findsOneWidget);
await tester.tap(find.text('Edit'));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Remove $label'));
await tester.pumpAndSettle();
expect(find.textContaining('Remove “$label”'), findsOneWidget);
expect(
find.text(
localEntries
? 'team.example (team.example:8443)'
: 'team.example:8443',
),
findsOneWidget,
);
await tester.tap(find.text('Remove').last);
await tester.pumpAndSettle();
expect(
find.text(
localEntries
? 'Other identity (team.example:9443)'
: 'team.example:9443',
),
findsOneWidget,
);
expect(find.textContaining('is pending account sync'), findsOneWidget);
expect(await sync.pendingRemovals('owner'), {
'wss://team.example:9443',
});
expect(account.calls, isEmpty);
account.failure = AccountFailure.unavailable;
sync.setActive(true);
await tester.pumpAndSettle();
expect(find.textContaining('hasn’t synced'), findsOneWidget);
// A refused endpoint remains visible and offers explicit retry.
account.failure = AccountFailure.rejected;
await tester.tap(find.text('Retry account sync'));
await tester.pumpAndSettle();
expect(find.textContaining('hasn’t synced'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
// The service remains scoped to this signed-in account across picker opens.
await tester.pumpWidget(
WidgetHelpers.testable(
enableAccountCommunitySync: true,
overrides: [
builderlabAccountProvider.overrideWithValue(account),
knownCommunitySyncProvider.overrideWithValue(sync),
],
child: const AccountCommunitySyncStatus(),
),
);
await tester.pumpAndSettle();
expect(find.textContaining('hasn’t synced'), findsOneWidget);
account.failure = null;
await tester.tap(find.text('Retry account sync'));
await tester.pumpAndSettle();
expect(find.textContaining('hasn’t synced'), findsNothing);
expect(account.calls, ['remove', 'remove', 'remove']);
expect(account.targets, everyElement('wss://team.example:9443'));
expect(
(await storage.loadAll()).map((c) => c.id),
localEntries ? ['8443', 'other-owner'] : <String>[],
);
expect(tester.takeException(), isNull);
},
);
}
test(
'pairing acknowledges committed re-add despite journal failure and restart',
() async {
const sourceSecret =
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506';
const sessionSecret =
'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
final account = _Account();
final storage = CommunityStorage(secure: FakeSecureStorage());
final journal = _JournalStorage();
var sync = KnownCommunitySync(
account: account,
storage: journal,
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
);
await sync.remove('wss://paired.example');
journal.failWrites = true;
late ControllablePairingSocket socket;
final notifier = PairingNotifier(
credentialValidator:
({required String relayUrl, required String? nsec}) async {},
socketFactory:
({
required wsUrl,
required ephemeralPrivkey,
required onMessage,
required onDisconnected,
}) {
socket = ControllablePairingSocket(
ephemeralPrivkey: ephemeralPrivkey,
onMessage: onMessage,
onDisconnected: onDisconnected,
);
return socket;
},
);
final container = ProviderContainer(
overrides: [
builderlabAccountProvider.overrideWithValue(account),
communityStorageProvider.overrideWithValue(storage),
knownCommunitySyncProvider.overrideWithValue(sync),
pairingProvider.overrideWith(() => notifier),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
],
);
container.read(pairingProvider);
final ready = Completer<void>();
final finished = Completer<void>();
container.listen(pairingProvider, (_, next) {
if (next.status == PairingStatus.transferring && !ready.isCompleted) {
ready.complete();
}
if ((next.status == PairingStatus.success ||
next.status == PairingStatus.error) &&
!finished.isCompleted) {
finished.complete();
}
});
await notifier.pair(
'nostrpair://${nostr.Keys(sourceSecret).public}?secret=$sessionSecret&relay=wss%3A%2F%2Fpairing.buzz.xyz&v=1',
);
notifier.setProtectSensitiveActions(false);
notifier.confirmSas();
socket.sendSourceMessage(
sourceSecret: sourceSecret,
sessionSecretHex: sessionSecret,
message: {'type': 'sas-confirm'},
includeTranscriptHash: true,
);
await ready.future;
socket.sendSourceMessage(
sourceSecret: sourceSecret,
sessionSecretHex: sessionSecret,
message: {
'type': 'payload',
'payload_type': 'credentials',
'payload': jsonEncode({
'relayUrl': 'https://paired.example',
'pubkey': nostr.Keys(sourceSecret).public,
'nsec': nostr.Keys(sourceSecret).nsec,
}),
},
);
await finished.future;
await sync.synchronize();
expect(container.read(pairingProvider).status, PairingStatus.success);
final acknowledgements = socket
.decryptedPublishedMessages(sourceSecret)
.where((m) => m['type'] == 'complete')
.toList();
expect(acknowledgements.single['success'], isTrue);
final saved = (await storage.loadAll()).single;
expect(saved.accountSyncOwner, endsWith('\nowner'));
expect(saved.accountSyncRevision, isNotNull);
expect(await sync.pendingRemovals('owner'), {'wss://paired.example'});
// Recreate the process after local commit, before journal reconciliation.
container.dispose();
sync.dispose();
journal.failWrites = false;
sync = KnownCommunitySync(
account: account,
storage: journal,
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
);
addTearDown(sync.dispose);
await sync.synchronize();
expect(account.calls, ['add']);
expect(await sync.pendingRemovals('owner'), isEmpty);
expect((await storage.loadAll()).single.nsec, saved.nsec);
},
);
test(
'shared authentication and explicit removal enqueue account edits',
() async {
final account = _Account();
final storage = CommunityStorage(secure: FakeSecureStorage());
final sync = KnownCommunitySync(
account: account,
storage: FakeSecureStorage(),
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
);
final container = ProviderContainer(
overrides: [
builderlabAccountProvider.overrideWithValue(account),
communityStorageProvider.overrideWithValue(storage),
knownCommunitySyncProvider.overrideWithValue(sync),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue(
(_) async => false,
),
],
);
addTearDown(() {
container.dispose();
sync.dispose();
});
final community = Community.create(
name: 'Paired',
relayUrl: 'wss://paired.example',
nsec: nostr.Keys('1'.padLeft(64, '0')).nsec,
);
await container.read(communityListProvider.future);
// Pairing, invites, and self-hosted entry all persist through this seam.
await container
.read(authProvider.notifier)
.authenticateWithCommunity(community);
await sync.synchronize();
expect(account.calls, ['add']);
await container.read(communityListProvider.future);
await container
.read(communityListProvider.notifier)
.removeCommunity(community.id);
await sync.synchronize();
expect(account.calls, ['add', 'remove']);
expect(await storage.loadAll(), isEmpty);
},
);
test(
'an unreadable account session leaves local add and removal local-only',
() async {
if (!HostedEnvironment.enabled) return;
final sessions = FakeSecureStorage();
await sessions.write(
key:
'buzz_hosted_session_${HostedEnvironment.origin.host.replaceAll('.', '_')}_v1',
value: 'not json',
);
final account = BuilderlabAccountClient(
storage: sessions,
httpClient: MockClient((_) async => http.Response('{}', 503)),
);
// Any journal write would throw, so success proves nothing was queued.
final journal = _JournalStorage()..failWrites = true;
final storage = CommunityStorage(secure: FakeSecureStorage());
Community local(String id) => Community(
id: id,
name: id,
relayUrl: 'wss://$id.example',
addedAt: DateTime(2025),
nsec: nostr.Keys('1'.padLeft(64, '0')).nsec,
);
await storage.save(local('existing'));
final sync = KnownCommunitySync(
account: account,
storage: journal,
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
)..setActive(false);
final container = ProviderContainer(
overrides: [
builderlabAccountProvider.overrideWithValue(account),
communityStorageProvider.overrideWithValue(storage),
knownCommunitySyncProvider.overrideWithValue(sync),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue(
(_) async => false,
),
],
);
addTearDown(() {
container.dispose();
sync.dispose();
account.dispose();
});
await expectLater(
account.retainedSubject(),
throwsA(AccountFailure.storage),
);
await container.read(authProvider.future);
await container.read(communityListProvider.future);
final added = local('added');
expect(await sync.prepareAddition(added), same(added));
await container
.read(authProvider.notifier)
.authenticateWithCommunity(added, activate: false);
await container.read(communityListProvider.future);
await container
.read(communityListProvider.notifier)
.removeCommunity('existing');
final records = await storage.loadForAccountSync();
expect(records.map((c) => c.id), ['added']);
expect(records.single.accountSyncOwner, isNull);
expect(records.single.accountSyncRevision, isNull);
},
);
test(
'a session record that becomes unreadable mid-removal still fences the account',
() async {
if (!HostedEnvironment.enabled) return;
final sessionKey =
'buzz_hosted_session_${HostedEnvironment.origin.host.replaceAll('.', '_')}_v1';
final sessions = FakeSecureStorage();
final expiry = DateTime.now()
.add(const Duration(days: 1))
.toUtc()
.toIso8601String();
BuilderlabAccountClient client() => BuilderlabAccountClient(
storage: sessions,
httpClient: MockClient((request) async {
if (request.url.path.endsWith('/exchange')) {
return http.Response(
jsonEncode({'session_credential': 'A', 'expires_at': expiry}),
200,
);
}
if (request.url.path.endsWith('/me')) {
return http.Response(
jsonEncode({'subject': 'A', 'expires_at': expiry}),
200,
);
}
return http.Response('{}', 503);
}),
);
// Retain A's session without adopting it, so each read uses the record.
final signIn = client();
await signIn.exchange(code: 'code', verifier: 'a' * 43);
signIn.dispose();
final account = client();
final storage = CommunityStorage(secure: FakeSecureStorage());
await storage.save(
Community(
id: 'existing',
name: 'existing',
relayUrl: 'wss://existing.example',
addedAt: DateTime(2025),
nsec: nostr.Keys('1'.padLeft(64, '0')).nsec,
),
);
final sync = KnownCommunitySync(
account: account,
storage: FakeSecureStorage(),
localCommunities: storage.loadForAccountSync,
acknowledgeRemoval: storage.acknowledgeRemoval,
)..setActive(false);
final container = ProviderContainer(
overrides: [
builderlabAccountProvider.overrideWithValue(account),
communityStorageProvider.overrideWithValue(storage),
knownCommunitySyncProvider.overrideWithValue(sync),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
// The record breaks after the removal captured A, before its recheck.
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue((
_,
) async {
await sessions.write(key: sessionKey, value: 'not json');
return false;
}),
],
);
addTearDown(() {
container.dispose();
sync.dispose();
account.dispose();
});
expect(account.account, isNull);
expect(await account.retainedSubject(), 'A');
await container.read(communityListProvider.future);
await expectLater(
container
.read(communityListProvider.notifier)
.removeCommunity('existing'),
throwsA(AccountFailure.differentAccount),
);
expect((await storage.loadAll()).map((c) => c.id), ['existing']);
},
);
}