From a82d596fc27fa24f35feee4b283be197c632c8ab Mon Sep 17 00:00:00 2001 From: klopez4212 Date: Sun, 15 Nov 2026 23:07:56 +0000 Subject: [PATCH] mobile: show account communities in the switcher and sync saved destinations (#9262) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 Signed-off-by: Tom Brow Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow Co-authored-by: Tom Brow Co-authored-by: studio --- .github/workflows/_ci-clients.yml | 6 + .../lib/features/channels/channels_page.dart | 10 + .../channels/channels_page/community.dart | 70 +- .../channels_page/community_switcher.dart | 83 ++- .../community_switcher_action.dart | 18 +- .../hosted_community_selection.dart | 28 +- mobile/lib/features/pairing/pairing_page.dart | 8 +- mobile/lib/hosted_app_gate.dart | 23 + mobile/lib/onboarding_app_entry.dart | 108 +-- mobile/lib/shared/auth/auth_provider.dart | 6 +- mobile/lib/shared/community/community.dart | 39 + .../shared/community/community_provider.dart | 43 +- .../shared/community/community_storage.dart | 75 +- .../hosted/account_community_sync_status.dart | 145 ++++ .../lib/shared/hosted/builderlab_account.dart | 53 +- .../lib/shared/hosted/hosted_communities.dart | 37 +- mobile/lib/shared/hosted/hosted_flow.dart | 86 +-- .../hosted/hosted_flow_account_entry.dart | 71 ++ .../hosted/known_communities_provider.dart | 33 + .../hosted/known_community_address.dart | 24 + .../shared/hosted/known_community_sync.dart | 348 +++++++++ .../hosted/known_community_sync_provider.dart | 20 + .../features/age_gate/age_gate_app_test.dart | 3 + .../features/channels/channels_page_test.dart | 10 +- .../community_switcher_discovery_test.dart | 195 +++++ .../invite_active_community_race_test.dart | 4 + .../invites/invite_join_provider_test.dart | 4 + .../account_community_entry_test.dart | 198 ++++++ .../account_sync_recovery_test.dart | 664 ++++++++++++++++++ .../onboarding/hosted_communities_test.dart | 5 +- .../onboarding/hosted_journeys_test.dart | 3 + .../known_communities_provider_test.dart | 133 ++++ ...known_community_sync_integration_test.dart | 531 ++++++++++++++ .../onboarding/known_community_sync_test.dart | 307 ++++++++ .../search/search_channels_journey_test.dart | 1 + .../helpers/hosted_communities_fixture.dart | 18 +- mobile/test/helpers/widget_helpers.dart | 8 +- .../test/shared/auth/auth_provider_test.dart | 4 + .../community/community_provider_test.dart | 4 + .../hosted/builderlab_account_test.dart | 66 ++ .../shared/push/push_root_isolation_test.dart | 2 + 41 files changed, 3343 insertions(+), 151 deletions(-) create mode 100644 mobile/lib/shared/hosted/account_community_sync_status.dart create mode 100644 mobile/lib/shared/hosted/hosted_flow_account_entry.dart create mode 100644 mobile/lib/shared/hosted/known_communities_provider.dart create mode 100644 mobile/lib/shared/hosted/known_community_address.dart create mode 100644 mobile/lib/shared/hosted/known_community_sync.dart create mode 100644 mobile/lib/shared/hosted/known_community_sync_provider.dart create mode 100644 mobile/test/features/channels/community_switcher_discovery_test.dart create mode 100644 mobile/test/features/onboarding/account_community_entry_test.dart create mode 100644 mobile/test/features/onboarding/account_sync_recovery_test.dart create mode 100644 mobile/test/features/onboarding/known_communities_provider_test.dart create mode 100644 mobile/test/features/onboarding/known_community_sync_integration_test.dart create mode 100644 mobile/test/features/onboarding/known_community_sync_test.dart diff --git a/.github/workflows/_ci-clients.yml b/.github/workflows/_ci-clients.yml index 8b97f3a4d6..a6bdb4d1fc 100644 --- a/.github/workflows/_ci-clients.yml +++ b/.github/workflows/_ci-clients.yml @@ -167,6 +167,12 @@ jobs: test/features/onboarding/hosted_backup_consent_test.dart test/features/onboarding/onboarding_sign_out_test.dart test/features/onboarding/hosted_communities_test.dart + test/features/onboarding/account_community_entry_test.dart + test/features/onboarding/account_sync_recovery_test.dart + test/features/onboarding/known_communities_provider_test.dart + test/features/onboarding/known_community_sync_integration_test.dart + test/features/onboarding/known_community_sync_test.dart + test/shared/hosted/builderlab_account_test.dart test/features/pairing/pairing_hosted_handoff_test.dart test/shared/agents/remote_agents_test.dart test/features/agents diff --git a/mobile/lib/features/channels/channels_page.dart b/mobile/lib/features/channels/channels_page.dart index 3e530c36e8..ec11aa621b 100644 --- a/mobile/lib/features/channels/channels_page.dart +++ b/mobile/lib/features/channels/channels_page.dart @@ -7,6 +7,16 @@ import '../../shared/widgets/collapsible_sliver_body.dart'; import '../../shared/http/app_http_client.dart'; import '../../shared/me/me_sync.dart'; import '../../shared/hosted/hosted_relay_auth.dart'; +import '../../shared/hosted/known_communities_provider.dart'; +import '../../shared/hosted/hosted_community_connection.dart'; +import '../../shared/hosted/hosted_flow_provider.dart'; +import '../../shared/deeplink/deep_link.dart'; +import '../../shared/deeplink/pending_deep_link_provider.dart'; +import '../../shared/hosted/hosted_environment.dart'; +import '../../shared/hosted/known_community_sync.dart'; +import '../../shared/hosted/known_community_sync_provider.dart'; +import '../../shared/hosted/known_community_address.dart'; +import '../../shared/hosted/account_community_sync_status.dart'; import '../../shared/hosted/organization_environment.dart'; import '../../shared/hosted/organization_sign_in.dart'; diff --git a/mobile/lib/features/channels/channels_page/community.dart b/mobile/lib/features/channels/channels_page/community.dart index 671783a0e5..eda9069241 100644 --- a/mobile/lib/features/channels/channels_page/community.dart +++ b/mobile/lib/features/channels/channels_page/community.dart @@ -84,19 +84,42 @@ Future _confirmRemoveCommunity( required bool closeSheetAfterRemoval, }) async { final messenger = ScaffoldMessenger.of(context); + final account = ref.read(builderlabAccountProvider); + final sync = ref.read(knownCommunitySyncProvider); try { + final subject = sync == null ? null : await account.localEditSubject(); + if (!context.mounted) return; + final retainsDestination = (ref.read(communityListProvider).value ?? []) + .any( + (item) => + item.id != community.id && + item.accountSyncOwner == + '${account.accountOrigin.origin}\n$subject' && + knownCommunityAddress(item.relayUrl) == + knownCommunityAddress(community.relayUrl), + ); final confirmed = await showDestructiveConfirmation( context: context, title: 'Remove community?', - message: - 'Are you sure you want to remove “${community.name}”? ' - 'You can pair with it again later.', + message: subject == null + ? 'Are you sure you want to remove “${community.pickerName}”? You can pair with it again later.' + : retainsDestination + ? 'Remove this identity for “${community.pickerName}” from this device? Another saved identity still uses this community, so it stays in your account list.' + : 'Remove “${community.pickerName}” from this device and request removal from your Builder Lab community list? Account removal syncs when connected.', confirmLabel: 'Remove', ); - if (!confirmed || !context.mounted) return; + if (!confirmed || + !context.mounted || + (sync != null && await account.localEditSubject() != subject)) { + return; + } await ref .read(communityListProvider.notifier) - .removeCommunity(community.id); + .removeCommunity( + community.id, + confirmedSubject: subject, + accountConfirmed: true, + ); if (closeSheetAfterRemoval && context.mounted) { Navigator.of(context).pop(); } @@ -108,6 +131,43 @@ Future _confirmRemoveCommunity( } } +Future _confirmRemoveAccountCommunity( + BuildContext context, + WidgetRef ref, + AddCommunityDeepLink community, +) async { + final account = ref.read(builderlabAccountProvider); + final sync = ref.read(knownCommunitySyncProvider); + if (sync == null) return; + try { + final subject = await account.retainedSubject(); + if (!context.mounted || subject == null) return; + final confirmed = await showDestructiveConfirmation( + context: context, + title: 'Remove community?', + message: + 'Remove “${community.name}” from your Builder Lab community list? Removal syncs when connected.', + confirmLabel: 'Remove', + ); + if (!confirmed || + !context.mounted || + await account.retainedSubject() != subject) { + return; + } + await sync.remove(community.relayUrl, expectedSubject: subject); + sync.trigger(); + } catch (_) { + if (context.mounted) { + ScaffoldMessenger.of(context).showFeedbackSnackBar( + const SnackBar( + content: Text('Could not save this removal. Please try again.'), + ), + kind: ToastKind.error, + ); + } + } +} + class _CommunityIndicator extends ConsumerWidget { final VoidCallback onTap; diff --git a/mobile/lib/features/channels/channels_page/community_switcher.dart b/mobile/lib/features/channels/channels_page/community_switcher.dart index fcb550bc76..14cfe6e876 100644 --- a/mobile/lib/features/channels/channels_page/community_switcher.dart +++ b/mobile/lib/features/channels/channels_page/community_switcher.dart @@ -90,8 +90,11 @@ class CommunitySwitcherPage extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { final communitiesAsync = ref.watch(communityListProvider); + final known = ref.watch(knownCommunitiesProvider); + final knownAsync = known.isReloading ? known.unwrapPrevious() : known; final activeId = ref.watch(activeCommunityProvider).value?.id; final isEditing = useState(false); + final openingAccountCommunity = useState(false); final flight = useState<_CommunityFlight?>( arrivingCommunity == null ? null @@ -299,12 +302,47 @@ class CommunitySwitcherPage extends HookConsumerWidget { unawaited( navigator.push( MaterialPageRoute( - builder: (_) => const OnboardingAppEntry(addingCommunity: true), + builder: (_) => const OnboardingAppEntry( + addingCommunity: true, + showFindCommunities: false, + ), ), ), ); } + Future openAccountCommunity(AddCommunityDeepLink community) async { + if (openingAccountCommunity.value) return; + openingAccountCommunity.value = true; + final hosted = HostedEnvironment.supportsRelay( + Uri.parse(community.relayUrl), + ); + final flow = hosted ? ref.read(hostedFlowProvider) : null; + final pending = hosted + ? null + : ref.read(pendingDeepLinkProvider.notifier); + final route = ModalRoute.of(context); + Navigator.of(context).pop(); + if (route != null) await route.completed; + // The app's hosted gate presents any required sign-in, identity recovery, + // or admission failure. Merely listing a destination grants no access. + if (flow != null) { + await flow.start(community); + } else { + // The app gate owns the existing self-hosted identity-choice flow. + pending!.open( + Uri( + scheme: 'buzz', + host: 'add-community', + queryParameters: { + 'relay': community.relayUrl, + 'name': community.name, + }, + ), + ); + } + } + final ios = defaultTargetPlatform == TargetPlatform.iOS; final toolbarScope = DuoToolbarScope.maybeOf(context); final strip = ios @@ -374,6 +412,17 @@ class CommunitySwitcherPage extends HookConsumerWidget { ), ), ), + const AccountCommunitySyncStatus(), + if (knownAsync.hasError) + Column( + children: [ + const Text('Could not load your account communities.'), + TextButton( + onPressed: () => ref.invalidate(knownCommunitiesProvider), + child: const Text('Try again'), + ), + ], + ), communitiesAsync.when( loading: () => const Center( child: BuzzLoadingIndicator( @@ -387,7 +436,7 @@ class CommunitySwitcherPage extends HookConsumerWidget { for (final community in communities) CommunityGridOption( id: community.id, - name: community.name, + name: community.pickerName, relayUrl: community.relayUrl, // Keep the current-community marker stable // while the selected avatar leaves the grid. @@ -401,7 +450,8 @@ class CommunitySwitcherPage extends HookConsumerWidget { onSelect: (origin) => selectCommunity(community, origin), badge: _CommunityGridAction( - community: community, + id: community.id, + name: community.pickerName, isActive: community.id == (flight.value == null @@ -416,6 +466,31 @@ class CommunitySwitcherPage extends HookConsumerWidget { ), ), ), + for (final community + in knownAsync.value ?? []) + if (!communities.any( + (saved) => + relayIdentity(saved.relayUrl) == + relayIdentity(community.relayUrl), + )) + CommunityGridOption( + id: community.relayUrl, + name: community.name, + relayUrl: community.relayUrl, + enabled: !isEditing.value, + onSelect: (_) => openAccountCommunity(community), + badge: _CommunityGridAction( + id: community.relayUrl, + name: community.name, + isActive: false, + isEditing: isEditing.value, + onRemove: () => _confirmRemoveAccountCommunity( + context, + ref, + community, + ), + ), + ), CommunityGridAdd(onTap: addCommunity), ], ), @@ -446,7 +521,7 @@ class CommunitySwitcherPage extends HookConsumerWidget { child: PopScope( canPop: flight.value == null, child: IgnorePointer( - ignoring: flight.value != null, + ignoring: flight.value != null || openingAccountCommunity.value, child: AnimatedBuilder( animation: Listenable.merge([centering, controller, reveal]), child: RepaintBoundary( diff --git a/mobile/lib/features/channels/channels_page/community_switcher_action.dart b/mobile/lib/features/channels/channels_page/community_switcher_action.dart index 6fbadcc510..be1943ddd6 100644 --- a/mobile/lib/features/channels/channels_page/community_switcher_action.dart +++ b/mobile/lib/features/channels/channels_page/community_switcher_action.dart @@ -2,13 +2,15 @@ part of '../channels_page.dart'; class _CommunityGridAction extends HookWidget { const _CommunityGridAction({ - required this.community, + required this.id, + required this.name, required this.isActive, required this.isEditing, required this.onRemove, }); - final Community community; + final String id; + final String name; final bool isActive; final bool isEditing; final VoidCallback onRemove; @@ -39,23 +41,23 @@ class _CommunityGridAction extends HookWidget { // A fixed touch target and center keep Edit from nudging the avatar/check. return SizedBox.square( - key: Key('community-switcher-action-${community.id}'), + key: Key('community-switcher-action-$id'), dimension: Grid.xl, child: IconButton( key: Key( - 'community-switcher-${isEditing ? 'remove' : 'selection'}-${community.id}', + 'community-switcher-${isEditing ? 'remove' : 'selection'}-$id', ), - tooltip: isEditing ? 'Remove ${community.name}' : null, + tooltip: isEditing ? 'Remove $name' : null, padding: EdgeInsets.zero, onPressed: isEditing ? onRemove : null, icon: Opacity( - key: Key('community-switcher-action-opacity-${community.id}'), + key: Key('community-switcher-action-opacity-$id'), opacity: isActive ? 1 : t, child: Transform.scale( - key: Key('community-switcher-action-scale-${community.id}'), + key: Key('community-switcher-action-scale-$id'), scale: isActive ? 1 : lerpDouble(.9, 1, t)!, child: Container( - key: Key('community-switcher-badge-${community.id}'), + key: Key('community-switcher-badge-$id'), width: size, height: size, decoration: BoxDecoration( diff --git a/mobile/lib/features/onboarding/hosted_community_selection.dart b/mobile/lib/features/onboarding/hosted_community_selection.dart index b67da7f3fa..f2fcab9fbc 100644 --- a/mobile/lib/features/onboarding/hosted_community_selection.dart +++ b/mobile/lib/features/onboarding/hosted_community_selection.dart @@ -3,6 +3,9 @@ import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import '../../shared/hosted/hosted_flow.dart'; +import '../../shared/hosted/account_community_sync_status.dart'; +import '../../shared/hosted/hosted_environment.dart'; +import '../../shared/deeplink/pending_deep_link_provider.dart'; import '../../shared/theme/grid.dart'; import '../../shared/community/community_grid.dart'; import '../../shared/community/community_grid_option.dart'; @@ -70,6 +73,26 @@ class HostedCommunitySelection extends HookConsumerWidget { name: community.name, relayUrl: community.relayUrl, onSelect: (_) async { + if (!HostedEnvironment.supportsRelay( + Uri.parse(community.relayUrl), + )) { + final pending = ref.read(pendingDeepLinkProvider.notifier); + await flow.leave(); + // Retire hosted setup before the app gate presents the existing + // self-hosted identity/admission route. + await WidgetsBinding.instance.endOfFrame; + pending.open( + Uri( + scheme: 'buzz', + host: 'add-community', + queryParameters: { + 'relay': community.relayUrl, + 'name': community.name, + }, + ), + ); + return; + } flow.chooseLandingCommunity(community.relayUrl); await flow.addSelectedCommunities(); }, @@ -81,12 +104,15 @@ class HostedCommunitySelection extends HookConsumerWidget { return OnboardingStepPage( title: 'Select a community', onBack: onBack ?? () {}, - content: choices, + content: Column( + children: [const AccountCommunitySyncStatus(), choices], + ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const AccountCommunitySyncStatus(), choices, const SizedBox(height: Grid.sm), ], diff --git a/mobile/lib/features/pairing/pairing_page.dart b/mobile/lib/features/pairing/pairing_page.dart index 7032faddf5..293f419344 100644 --- a/mobile/lib/features/pairing/pairing_page.dart +++ b/mobile/lib/features/pairing/pairing_page.dart @@ -76,6 +76,9 @@ class PairingPage extends HookConsumerWidget { final VoidCallback? onCommunityLink; final VoidCallback? onCreateCommunity; final VoidCallback? onBuilderlab; + + /// Opens account destinations before hosted identity setup. + final VoidCallback? onFindCommunities; final VoidCallback? onImportIdentity; final String? accountStatus; final Widget? setupContent; @@ -105,6 +108,7 @@ class PairingPage extends HookConsumerWidget { this.onCommunityLink, this.onCreateCommunity, this.onBuilderlab, + this.onFindCommunities, this.onImportIdentity, this.accountStatus, this.setupContent, @@ -319,7 +323,9 @@ class PairingPage extends HookConsumerWidget { builder: (context, progress, _) => AddCommunityPage( scannerProgress: progress, onboarding: signedInOnboarding, - onFindCommunities: hasKnownCommunities ? onBuilderlab : null, + onFindCommunities: hasKnownCommunities + ? (onFindCommunities ?? onBuilderlab) + : null, onImportIdentity: signedInOnboarding ? onImportIdentity : null, onCreateCommunity: signedInOnboarding ? onCreateCommunity : null, enteringCommunityLink: enteringCommunityLink, diff --git a/mobile/lib/hosted_app_gate.dart b/mobile/lib/hosted_app_gate.dart index 735f1500bb..a99c671be1 100644 --- a/mobile/lib/hosted_app_gate.dart +++ b/mobile/lib/hosted_app_gate.dart @@ -9,6 +9,7 @@ import 'features/profile/profile_setup_page.dart'; import 'features/onboarding/hosted_connect_page.dart'; import 'features/onboarding/self_hosted_entry_sheet.dart'; import 'shared/auth/auth.dart'; +import 'shared/community/community_provider.dart'; import 'shared/theme/grid.dart'; import 'shared/theme/theme_extensions.dart'; import 'shared/widgets/mobile_tab_footer_backdrop.dart'; @@ -22,6 +23,7 @@ import 'features/onboarding/hosted_reconnect_banner.dart'; import 'features/onboarding/organization_sign_in_banner.dart'; import 'shared/hosted/hosted_flow_provider.dart'; +import 'shared/hosted/known_community_sync_provider.dart'; import 'shared/hosted/organization_sign_in.dart'; /// Composition seam shared by signed-in and signed-out application states. @@ -52,6 +54,27 @@ class HostedAppGate extends HookConsumerWidget { unawaited(flow.initialize()); return () => flow.removeListener(onFlowChanged); }, [flow]); + final communitySync = ref.watch(knownCommunitySyncProvider); + ref.listen(communityListProvider, (_, next) { + if (next.hasValue && !next.isLoading && !next.hasError) { + communitySync?.trigger(); + } + }); + useEffect(() { + if (communitySync == null) return null; + final lifecycle = AppLifecycleListener( + onStateChange: (state) => + communitySync.setActive(state == AppLifecycleState.resumed), + ); + scheduleMicrotask(() { + communitySync.setActive( + WidgetsBinding.instance.lifecycleState == null || + WidgetsBinding.instance.lifecycleState == + AppLifecycleState.resumed, + ); + }); + return lifecycle.dispose; + }, [communitySync]); final inlineEntry = ref.watch(hostedInlineEntryProvider); // Create the organization's browser owner before any callback is handled. ref.watch(organizationSignInProvider); diff --git a/mobile/lib/onboarding_app_entry.dart b/mobile/lib/onboarding_app_entry.dart index 65b59beab2..c93ac1e463 100644 --- a/mobile/lib/onboarding_app_entry.dart +++ b/mobile/lib/onboarding_app_entry.dart @@ -8,6 +8,7 @@ import 'features/pairing/pairing_page.dart'; import 'organization_app_entry.dart'; import 'features/pairing/pairing_provider.dart'; import 'shared/hosted/hosted_flow_provider.dart'; +import 'shared/hosted/account_community_sync_status.dart'; import 'shared/hosted/hosted_flow.dart'; import 'shared/hosted/hosted_communities.dart'; import 'shared/hosted/use_known_communities.dart'; @@ -23,11 +24,15 @@ class OnboardingAppEntry extends HookConsumerWidget { super.key, this.addingCommunity = false, this.restoreAccount = true, + this.showFindCommunities = true, this.onExit, this.onComplete, }); final bool addingCommunity; final bool restoreAccount; + + /// The switcher already lists account destinations above its Add action. + final bool showFindCommunities; final VoidCallback? onExit; /// Continues picker restoration before the completed Add route is removed. @@ -110,13 +115,14 @@ class OnboardingAppEntry extends HookConsumerWidget { final hasKnownCommunities = useKnownCommunities( accountKey: flow?.account.account?.subject, active: + showFindCommunities && !existingUser.value && !enteringCommunityLink.value && !creating.value && flow?.stage == HostedFlowStage.idle && (ModalRoute.of(context)?.isCurrent ?? true), load: () async => - (await loadKnownHostedCommunities(flow!.account)).isNotEmpty, + (await loadKnownAccountCommunities(flow!.account)).isNotEmpty, ); final problem = flow != null && flow.accountOnly ? flow.problem : null; final status = flow == null @@ -221,48 +227,64 @@ class OnboardingAppEntry extends HookConsumerWidget { back(); } }, - child: PairingPage( - connectionLanding: true, - showConnectionOptions: - !HostedEnvironment.enabled || addingCommunity || connected, - addingCommunity: addingCommunity, - signedInOnboarding: connected && !addingCommunity && !signingIn, - hasKnownCommunities: hasKnownCommunities, - existingUser: existingUser.value, - enteringCommunityLink: enteringCommunityLink.value, - creatingCommunity: creating.value, - onSubmitCommunity: flow == null - ? null - : (name) { - creating.value = false; - unawaited(flow.start(HostedCreateCommunity(name))); - }, - onCommunityLink: () => enteringCommunityLink.value = true, - onCreateCommunity: flow == null || busy - ? null - : () => creating.value = true, - onBuilderlab: flow == null - ? null - : signingIn - ? () => unawaited(flow.leave()) - : busy - ? null - : () => unawaited(flow.signInAccount()), - onImportIdentity: flow == null || busy - ? null - : () => unawaited(flow.signInAccount(importIdentity: true)), - accountStatus: status, - builderlabBusy: busy && !signingIn, - signInPending: signingIn || busy, - builderlabLabel: signingIn - ? 'Cancel sign-in' - : busy - ? 'Connecting…' - : connected - ? 'Continue with Builderlab' - : 'Sign in with email', - onWelcomeBack: back, - onAlreadyUseBuzz: () => existingUser.value = true, + child: Column( + children: [ + Expanded( + child: PairingPage( + connectionLanding: true, + showConnectionOptions: + !HostedEnvironment.enabled || addingCommunity || connected, + addingCommunity: addingCommunity, + signedInOnboarding: connected && !addingCommunity && !signingIn, + hasKnownCommunities: showFindCommunities && hasKnownCommunities, + existingUser: existingUser.value, + enteringCommunityLink: enteringCommunityLink.value, + creatingCommunity: creating.value, + onSubmitCommunity: flow == null + ? null + : (name) { + creating.value = false; + unawaited(flow.start(HostedCreateCommunity(name))); + }, + onCommunityLink: () => enteringCommunityLink.value = true, + onCreateCommunity: flow == null || busy + ? null + : () => creating.value = true, + onFindCommunities: flow == null || busy + ? null + : () => unawaited(flow.signInAccount(discoverOnly: true)), + onBuilderlab: flow == null + ? null + : signingIn + ? () => unawaited(flow.leave()) + : busy + ? null + : () => unawaited(flow.signInAccount()), + onImportIdentity: flow == null || busy + ? null + : () => unawaited(flow.signInAccount(importIdentity: true)), + accountStatus: status, + builderlabBusy: busy && !signingIn, + signInPending: signingIn || busy, + builderlabLabel: signingIn + ? 'Cancel sign-in' + : busy + ? 'Connecting…' + : connected + ? 'Continue with Builderlab' + : 'Sign in with email', + onWelcomeBack: back, + onAlreadyUseBuzz: () => existingUser.value = true, + ), + ), + if (connected) + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 180), + child: const SingleChildScrollView( + child: Material(child: AccountCommunitySyncStatus()), + ), + ), + ], ), ); } diff --git a/mobile/lib/shared/auth/auth_provider.dart b/mobile/lib/shared/auth/auth_provider.dart index 2768a83c82..c8fdc3dc8e 100644 --- a/mobile/lib/shared/auth/auth_provider.dart +++ b/mobile/lib/shared/auth/auth_provider.dart @@ -1,3 +1,4 @@ +import '../hosted/known_community_sync_provider.dart'; import '../hosted/hosted_relay_auth.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; import 'package:nostr/nostr.dart' as nostr; @@ -62,7 +63,9 @@ class AuthNotifier extends AsyncNotifier { Community community, { bool Function()? shouldContinue, bool activate = true, - }) { + }) async { + final sync = ref.read(knownCommunitySyncProvider); + community = await sync?.prepareAddition(community) ?? community; return ref.read(communityTransitionProvider).runExclusive(() async { if (shouldContinue != null && !shouldContinue()) return; await CommunityEntryRequirements.verify( @@ -75,6 +78,7 @@ class AuthNotifier extends AsyncNotifier { final storage = ref.read(communityStorageProvider); await storage.save(community); if (activate) await storage.saveActiveId(community.id); + sync?.trigger(); await syncStoredCommunitySnapshot(ref); // Invalidate community providers so other consumers pick up the new data. diff --git a/mobile/lib/shared/community/community.dart b/mobile/lib/shared/community/community.dart index a992c28228..463212a2c1 100644 --- a/mobile/lib/shared/community/community.dart +++ b/mobile/lib/shared/community/community.dart @@ -33,6 +33,26 @@ class Community { /// fallbacks always appear in the short form onboarding shows. String get name => HostedEnvironment.communityDisplayName(_name, relayUrl); + /// Account origin and subject that explicitly saved this destination. + /// Legacy/unclaimed records remain local; they are never uploaded on sign-in. + final String? accountSyncOwner; + + /// Unique revision persisted atomically with an explicit local join. + /// A new revision supersedes an earlier queued account removal on recovery. + final String? accountSyncRevision; + + /// Credential-free removal intent, hidden from the device community list. + final bool accountSyncRemoved; + + /// Distinguishes local destinations with nondefault ports in picker actions. + String get pickerName { + final uri = Uri.parse(relayUrl); + if (!uri.hasPort || uri.port == 443 || name.contains(uri.authority)) { + return name; + } + return '$name (${uri.authority})'; + } + final String relayUrl; final String? pubkey; final String? nsec; @@ -54,6 +74,9 @@ class Community { required this.id, required String name, required this.relayUrl, + this.accountSyncOwner, + this.accountSyncRevision, + this.accountSyncRemoved = false, this.pubkey, this.nsec, this.sensitiveActionPolicy = SensitiveActionPolicy.disabledByUser, @@ -89,6 +112,9 @@ class Community { Community copyWith({ String? name, String? relayUrl, + Object? accountSyncOwner = _sentinel, + Object? accountSyncRevision = _sentinel, + bool? accountSyncRemoved, Object? pubkey = _sentinel, Object? nsec = _sentinel, SensitiveActionPolicy? sensitiveActionPolicy, @@ -101,6 +127,13 @@ class Community { id: id, name: name ?? _name, relayUrl: relayUrl ?? this.relayUrl, + accountSyncOwner: accountSyncOwner == _sentinel + ? this.accountSyncOwner + : accountSyncOwner as String?, + accountSyncRevision: accountSyncRevision == _sentinel + ? this.accountSyncRevision + : accountSyncRevision as String?, + accountSyncRemoved: accountSyncRemoved ?? this.accountSyncRemoved, pubkey: pubkey == _sentinel ? this.pubkey : pubkey as String?, nsec: nsec == _sentinel ? this.nsec : nsec as String?, sensitiveActionPolicy: @@ -122,6 +155,9 @@ class Community { 'id': id, 'name': _name, 'relayUrl': relayUrl, + if (accountSyncRemoved) 'accountSyncRemoved': true, + if (accountSyncOwner != null) 'accountSyncOwner': accountSyncOwner, + if (accountSyncRevision != null) 'accountSyncRevision': accountSyncRevision, if (pubkey != null) 'pubkey': pubkey, if (nsec != null) 'nsec': nsec, 'sensitiveActionPolicy': sensitiveActionPolicy.name, @@ -158,6 +194,9 @@ class Community { id: json['id'] as String, name: json['name'] as String, relayUrl: json['relayUrl'] as String, + accountSyncRemoved: json['accountSyncRemoved'] == true, + accountSyncOwner: json['accountSyncOwner'] as String?, + accountSyncRevision: json['accountSyncRevision'] as String?, pubkey: json['pubkey'] as String?, nsec: json['nsec'] as String?, sensitiveActionPolicy: SensitiveActionPolicy.values.firstWhere( diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart index 0003400e7b..d62b12c504 100644 --- a/mobile/lib/shared/community/community_provider.dart +++ b/mobile/lib/shared/community/community_provider.dart @@ -1,3 +1,6 @@ +import '../hosted/known_community_sync.dart'; +import '../hosted/known_community_sync_provider.dart'; +import '../hosted/builderlab_account.dart'; import '../hosted/hosted_relay_auth.dart'; import 'dart:async'; @@ -280,6 +283,8 @@ class CommunityListNotifier extends AsyncNotifier> { /// Add a community. If one with the same relay URL already exists, update /// its credentials instead. Returns the effective community ID. Future addCommunity(Community community) async { + final sync = ref.read(knownCommunitySyncProvider); + community = await sync?.prepareAddition(community) ?? community; await CommunityEntryRequirements.verify( community, ref.read(builderlabAccountProvider), @@ -297,6 +302,8 @@ class CommunityListNotifier extends AsyncNotifier> { final updated = existing.copyWith( pubkey: community.pubkey, nsec: community.nsec, + accountSyncOwner: community.accountSyncOwner, + accountSyncRevision: community.accountSyncRevision, ); final identityChanged = _channelSnapshotPubkey(existing)?.toLowerCase() != @@ -311,6 +318,7 @@ class CommunityListNotifier extends AsyncNotifier> { if (identityChanged) unawaited(_removeOrphanMediaCaches()); await _removeOrphanChannelListSnapshots(updatedList); await syncCommunitySnapshot(ref, updatedList); + sync?.trigger(); return existing.id; } @@ -319,10 +327,24 @@ class CommunityListNotifier extends AsyncNotifier> { state = AsyncData(updatedList); await _removeOrphanChannelListSnapshots(updatedList); await syncCommunitySnapshot(ref, updatedList); + sync?.trigger(); return community.id; } - Future removeCommunity(String id) { + /// Removes a saved identity without letting awaited cleanup change the account + /// that confirmed its remote edit. An explicit null confirmation is local-only. + Future removeCommunity( + String id, { + String? confirmedSubject, + bool accountConfirmed = false, + }) async { + final account = ref.read(builderlabAccountProvider); + final sync = ref.read(knownCommunitySyncProvider); + final subject = sync == null + ? null + : accountConfirmed + ? confirmedSubject + : await account.localEditSubject(); return ref.read(communityTransitionProvider).runExclusive(() async { var revocationJournaled = false; final storage = ref.read(communityStorageProvider); @@ -334,6 +356,9 @@ class CommunityListNotifier extends AsyncNotifier> { final removedIndex = current.indexWhere( (community) => community.id == id, ); + if (sync != null && await account.localEditSubject() != subject) { + throw AccountFailure.differentAccount; + } if (removedIndex >= 0) { await _removeChannelListSnapshot(current[removedIndex]); // Persist every remote-cleanup dependency before erasing credentials. @@ -343,7 +368,21 @@ class CommunityListNotifier extends AsyncNotifier> { communityPushLeaseRevocationEnqueuerProvider, )(current[removedIndex]); } - await storage.remove(id); + // A durable revocation commits this removal to its confirmed account. + // Finish local deletion even if the account changed during journaling; + // aborting now would leave a saved community with a revoked push lease. + if (!revocationJournaled && + sync != null && + await account.localEditSubject() != subject) { + throw AccountFailure.differentAccount; + } + await storage.remove( + id, + accountSyncOwner: subject == null + ? null + : '${account.accountOrigin.origin}\n$subject', + ); + ref.read(knownCommunitySyncProvider)?.trigger(); final updatedList = current.where((w) => w.id != id).toList(); await _removeOrphanChannelListSnapshots(updatedList); diff --git a/mobile/lib/shared/community/community_storage.dart b/mobile/lib/shared/community/community_storage.dart index d885cef896..b676fb47e3 100644 --- a/mobile/lib/shared/community/community_storage.dart +++ b/mobile/lib/shared/community/community_storage.dart @@ -1,9 +1,11 @@ import 'dart:convert'; import 'package:crypto/crypto.dart'; +import 'package:uuid/uuid.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../hosted/organization_environment.dart'; +import '../hosted/known_community_address.dart'; import '../storage/secure_storage.dart'; import '../storage/serial_queue.dart'; @@ -40,9 +42,27 @@ class CommunityStorage { /// Load all communities this build shows. On first call, migrates legacy /// single-community credentials if present. - Future> loadAll() async => + Future> loadAll() async => (await _loadStored()) + .where((c) => _visible(c) && !c.accountSyncRemoved) + .toList(); + + /// Device records and credential-free removal intents for account sync. + Future> loadForAccountSync() async => (await _loadStored()).where(_visible).toList(); + /// Retire only the acknowledged revision; a newer intent survives. + Future acknowledgeRemoval(String revision) => + _pendingInvites.run(() async { + final all = await _loadStored(); + all.removeWhere( + (c) => c.accountSyncRemoved && c.accountSyncRevision == revision, + ); + await _secure.write( + key: _keyCommunities, + value: jsonEncode(all.map((c) => c.toJson()).toList()), + ); + }); + Future> _loadStored() async { final raw = await _secure.read(key: _keyCommunities); if (raw != null) return _decodeList(raw); @@ -138,7 +158,7 @@ class CommunityStorage { } }); - Future save(Community community) async { + Future save(Community community) => _pendingInvites.run(() async { final all = await loadAll(); final index = all.indexWhere((w) => w.id == community.id); if (index >= 0) { @@ -147,12 +167,18 @@ class CommunityStorage { all.add(community); } await _saveList(all); - } + }); /// Replaces the complete stored community list in one secure-storage write. - Future saveAll(List communities) => _saveList(communities); + Future saveAll(List communities) => + _pendingInvites.run(() => _saveList(communities)); - Future remove(String id) => _pendingInvites.run(() async { + /// Remove locally and retain the confirmed account edit in the same write. + /// Other identities owned by this account keep its destination entry alive. + Future remove( + String id, { + String? accountSyncOwner, + }) => _pendingInvites.run(() async { final all = await loadAll(); final removedKeys = all .where((item) => item.id == id) @@ -173,7 +199,34 @@ class CommunityStorage { } } } + final removed = all.where((c) => c.id == id).firstOrNull; all.removeWhere((w) => w.id == id); + final removedUrl = removed == null + ? null + : knownCommunityAddress(removed.relayUrl); + // Another identity owned by this account retains its destination row. + // Otherwise commit deletion and remote intent in the same storage write. + if (removed != null && + removedUrl != null && + accountSyncOwner != null && + !all.any( + (c) => + !c.accountSyncRemoved && + c.accountSyncOwner == accountSyncOwner && + knownCommunityAddress(c.relayUrl) == removedUrl, + )) { + all.add( + Community( + id: 'account-removal-${const Uuid().v4()}', + name: removed.name, + relayUrl: removedUrl, + addedAt: DateTime.now(), + accountSyncOwner: accountSyncOwner, + accountSyncRevision: const Uuid().v4(), + accountSyncRemoved: true, + ), + ); + } await _saveList(all); }); @@ -201,7 +254,17 @@ class CommunityStorage { final raw = await _secure.read(key: _keyCommunities); final hidden = raw == null ? const [] - : _decodeList(raw).where((item) => !_visible(item)); + : _decodeList(raw).where( + (item) => + !_visible(item) || + (item.accountSyncRemoved && + !communities.any( + (c) => + c.accountSyncOwner == item.accountSyncOwner && + knownCommunityAddress(c.relayUrl) == + knownCommunityAddress(item.relayUrl), + )), + ); final json = jsonEncode( [...hidden, ...communities].map((item) => item.toJson()).toList(), ); diff --git a/mobile/lib/shared/hosted/account_community_sync_status.dart b/mobile/lib/shared/hosted/account_community_sync_status.dart new file mode 100644 index 0000000000..9e67527534 --- /dev/null +++ b/mobile/lib/shared/hosted/account_community_sync_status.dart @@ -0,0 +1,145 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_hooks/flutter_hooks.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../community/community_provider.dart'; +import '../widgets/confirmation_dialog.dart'; +import '../widgets/feedback_snackbar.dart'; +import 'builderlab_account.dart'; +import 'hosted_flow_provider.dart'; +import 'hosted_relay_auth.dart'; +import 'known_community_sync_provider.dart'; +import 'known_community_address.dart'; + +/// Durable removals stay visible until the account service acknowledges them. +final pendingAccountRemovalsProvider = + FutureProvider.autoDispose<({String? subject, Set urls})>(( + ref, + ) async { + ref.watch(communityListProvider); + final sync = ref.watch(knownCommunitySyncProvider); + final account = ref.watch(builderlabAccountProvider); + void changed() => ref.invalidateSelf(); + sync?.addListener(changed); + account.subjectChanges.addListener(changed); + ref.onDispose(() { + sync?.removeListener(changed); + account.subjectChanges.removeListener(changed); + }); + final subject = account.account?.subject; + if (subject == null || sync == null) { + return (subject: subject, urls: {}); + } + return (subject: subject, urls: await sync.pendingRemovals(subject)); + }); + +/// Shows queued/failed account edits separately from local community access. +class AccountCommunitySyncStatus extends HookConsumerWidget { + /// Shows status only for the currently selected account. + const AccountCommunitySyncStatus({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final sync = ref.watch(knownCommunitySyncProvider); + useListenable(sync); + final account = ref.watch(builderlabAccountProvider); + useListenable(account.subjectChanges); + final pending = ref.watch(pendingAccountRemovalsProvider); + final value = pending.value; + final removals = value?.subject == account.account?.subject + ? value?.urls ?? {} + : {}; + final subject = account.account?.subject; + final owner = subject == null + ? null + : '${account.accountOrigin.origin}\n$subject'; + final local = (ref.watch(communityListProvider).value ?? const []) + .where((c) => owner != null && c.accountSyncOwner == owner) + .toList(); + final failed = sync?.failure != null || pending.hasError; + if (removals.isEmpty && !failed) return const SizedBox.shrink(); + return Semantics( + liveRegion: true, + child: Column( + children: [ + for (final url in removals) + Text( + failed + ? 'Removal of ${Uri.parse(url).authority} hasn’t synced to your account.' + : 'Removal of ${Uri.parse(url).authority} is pending account sync.', + ), + for (final url in removals) + if (local.any((c) => knownCommunityAddress(c.relayUrl) == url)) + TextButton( + onPressed: () async { + if (subject == null || account.account?.subject != subject) { + return; + } + final confirmed = await showDestructiveConfirmation( + context: context, + title: 'Finish removal?', + message: + 'Remove the remaining identities for ${Uri.parse(url).authority} from this device and sync account removal?', + confirmLabel: 'Remove', + ); + if (!confirmed || + !context.mounted || + account.account?.subject != subject) { + return; + } + try { + for (final item in local.where( + (c) => knownCommunityAddress(c.relayUrl) == url, + )) { + await ref + .read(communityListProvider.notifier) + .removeCommunity( + item.id, + confirmedSubject: subject, + accountConfirmed: true, + ); + } + sync?.retry(); + } catch (_) { + if (context.mounted) { + ScaffoldMessenger.of(context).showFeedbackSnackBar( + const SnackBar( + content: Text( + 'Removal could not finish. Please try again.', + ), + ), + kind: ToastKind.error, + ); + } + } + }, + child: Text( + 'Finish removing ${Uri.parse(url).authority} from this device', + ), + ), + if (failed && removals.isEmpty) + const Text('Could not sync your account communities.'), + TextButton( + onPressed: () { + sync?.retry(); + ref.invalidate(pendingAccountRemovalsProvider); + }, + child: const Text('Retry account sync'), + ), + if (sync?.failure == AccountFailure.accountSetupRequired) + TextButton( + onPressed: () => ref.read(hostedFlowProvider).signInAccount(), + child: const Text('Complete account setup'), + ), + if (sync?.failure == AccountFailure.denied) + TextButton( + onPressed: () => ref + .read(hostedFlowProvider) + .signInAccount(reauthenticate: true), + child: const Text('Sign in again'), + ), + ], + ), + ); + } +} diff --git a/mobile/lib/shared/hosted/builderlab_account.dart b/mobile/lib/shared/hosted/builderlab_account.dart index f4d03ff23a..95ed786926 100644 --- a/mobile/lib/shared/hosted/builderlab_account.dart +++ b/mobile/lib/shared/hosted/builderlab_account.dart @@ -133,6 +133,11 @@ class BuilderlabAccountClient { ValueListenable get subjectChanges => _subject; final _subject = ValueNotifier(null); + /// Changes whenever a verified session is adopted, including the same subject. + /// Consumers can retry work refused before reauthentication or account setup. + ValueListenable get sessionChanges => _sessionGeneration; + final _sessionGeneration = ValueNotifier(0); + /// Runs operations one at a time in call order, so a callback exchange that /// arrives during startup restore waits instead of failing. Future _serial(Future Function() operation) { @@ -143,6 +148,20 @@ class BuilderlabAccountClient { return result; } + /// Locally retained account for recording offline edits only. This does not + /// authorize network requests; those still require a verified session. + Future retainedSubject() async { + if (_disposed) throw AccountFailure.unavailable; + final current = account; + if (current != null) return current.subject; + // Local edits must not queue behind a network restore that may be offline. + final generation = _sessionGeneration.value; + final record = await _readRecord(); + if (_disposed) throw AccountFailure.unavailable; + if (generation != _sessionGeneration.value) return retainedSubject(); + return record?.subject; + } + /// Concurrent callers share one restore, so a second one cannot replace the /// account the first adopted while its callers still hold that session. Future restore() => @@ -239,7 +258,7 @@ class BuilderlabAccountClient { } catch (_) { throw AccountFailure.storage; } - return _adopt(credential, verified); + return _adopt(credential, verified, reauthenticated: true); }); }); } @@ -271,12 +290,21 @@ class BuilderlabAccountClient { throw AccountFailure.storage; } - BuilderlabAccount _adopt(String credential, BuilderlabAccount verified) { + BuilderlabAccount _adopt( + String credential, + BuilderlabAccount verified, { + bool reauthenticated = false, + }) { if (_disposed) throw AccountFailure.unavailable; + final changed = + reauthenticated || + _credential != credential || + _account?.needsAccountSetup != verified.needsAccountSetup; _credential = credential; // Assigned before notifying, so subject listeners see the new account. _account = verified; _subject.value = verified.subject; + if (changed) _sessionGeneration.value++; _unshared = credential; _share(); return verified; @@ -343,6 +371,21 @@ class BuilderlabAccountClient { if (result['error'] != null) throw AccountFailure.rejected; } + /// Edits only the account's saved destination list; relay membership and + /// credentials are unchanged. Both operations are idempotent. + Future updateKnownCommunity( + String relay, { + required bool removed, + required String expectedSubject, + }) async { + final result = await post( + '/v1/buzz/known-communities/${removed ? 'remove' : 'add'}', + {'community_url': relay}, + expectedSubject: expectedSubject, + ); + if (result['error'] != null) throw AccountFailure.rejected; + } + /// Authenticated JSON POST to a Buzz account route on the fixed origin. The /// credential never leaves this client. A 401 clears the stored session only /// when the session check also rejects it; otherwise it is [AccountFailure.denied]. @@ -505,7 +548,10 @@ class BuilderlabAccountClient { _credential = null; _unshared = null; _account = null; - if (!_disposed) _subject.value = null; + if (!_disposed) { + _subject.value = null; + _sessionGeneration.value++; + } } Future _unshare() async { @@ -585,6 +631,7 @@ class BuilderlabAccountClient { _signedOut = null; _account = null; _subject.dispose(); + _sessionGeneration.dispose(); _http.close(); } } diff --git a/mobile/lib/shared/hosted/hosted_communities.dart b/mobile/lib/shared/hosted/hosted_communities.dart index 69374d9ca8..1a24340d4a 100644 --- a/mobile/lib/shared/hosted/hosted_communities.dart +++ b/mobile/lib/shared/hosted/hosted_communities.dart @@ -1,14 +1,19 @@ import '../deeplink/deep_link.dart'; import 'builderlab_account.dart'; import 'hosted_environment.dart'; +import 'known_community_address.dart'; -/// Account-saved destinations, not evidence that this identity is a member. -/// Keep the existing hosted environment boundary and normal relay admission. -Future> loadKnownHostedCommunities( +/// Account-saved destinations this client can enter. These are saved addresses, +/// not evidence of membership; hosted and external entry retain admission checks. +Future> loadKnownAccountCommunities( BuilderlabAccountClient account, ) async { - final response = await account.post('/v1/buzz/known-communities/list', {}); - // Protobuf JSON omits an empty repeated field. + final subject = account.account?.subject; + final response = await account.post( + '/v1/buzz/known-communities/list', + {}, + expectedSubject: subject, + ); final rows = response['communities'] ?? []; if (response['error'] != null || rows is! List) { throw AccountFailure.invalidResponse; @@ -18,20 +23,22 @@ Future> loadKnownHostedCommunities( if (row is! Map || row['community_url'] is! String) { throw AccountFailure.invalidResponse; } - final relay = Uri.tryParse(row['community_url'] as String); - // The account can also save destinations this hosted build cannot enter. - if (relay == null || - relay.scheme != 'wss' || - !RegExp(r'^[a-z0-9]+(?:[.-][a-z0-9]+)*$').hasMatch(relay.host) || - !HostedEnvironment.supportsRelay(relay)) { + final raw = row['community_url'] as String; + if (Uri.tryParse(raw)?.scheme != 'wss') continue; + final relay = knownCommunityAddress(raw); + if (relay == null) continue; + final uri = Uri.parse(relay); + // Hosted domains require their configured HTTPS origin. They cannot use + // self-hosted entry to bypass the build's account/admission boundary. + if (HostedEnvironment.requiresAuth(uri.host) && + !HostedEnvironment.supportsRelay(uri)) { continue; } - final canonical = Uri(scheme: 'wss', host: relay.host); communities.putIfAbsent( - canonical.host, + relay, () => AddCommunityDeepLink( - relayUrl: canonical.toString(), - name: canonical.host, + relayUrl: relay, + name: uri.hasPort ? uri.authority : uri.host, ), ); } diff --git a/mobile/lib/shared/hosted/hosted_flow.dart b/mobile/lib/shared/hosted/hosted_flow.dart index 35f611d635..63b0684335 100644 --- a/mobile/lib/shared/hosted/hosted_flow.dart +++ b/mobile/lib/shared/hosted/hosted_flow.dart @@ -22,6 +22,7 @@ import 'web_connect_binding.dart'; import 'hosted_join_policy.dart'; part 'hosted_flow_identity_recovery.dart'; +part 'hosted_flow_account_entry.dart'; part 'hosted_flow_backup_consent.dart'; part 'hosted_flow_intent.dart'; @@ -151,6 +152,7 @@ class HostedFlow extends ChangeNotifier { String? landingRelay; final Set _addedRelays = {}; bool _addingCommunities = false; + bool _discoverOnly = false; String? _batchSubject; String? _conflictingRelay; String? _failedRelay; @@ -284,6 +286,7 @@ class HostedFlow extends ChangeNotifier { final generation = _generation; _enqueue(() async { _importRequested = code.intent['import_identity'] == 'true'; + _discoverOnly = code.intent['discover_only'] == 'true'; reconnecting = code.intent['type'] == 'reconnect'; accountOnly = reconnecting || code.intent['type'] == 'account'; if (accountOnly) { @@ -330,6 +333,7 @@ class HostedFlow extends ChangeNotifier { if (_disposed || generation != _generation) return; if (retained != null && _target == null) { _importRequested = retained['import_identity'] == 'true'; + _discoverOnly = retained['discover_only'] == 'true'; if (retained['type'] == 'reconnect') { reconnecting = true; accountOnly = true; @@ -368,64 +372,21 @@ class HostedFlow extends ChangeNotifier { Map get _accountIntent => { 'type': 'account', if (_importRequested) 'import_identity': 'true', + if (_discoverOnly) 'discover_only': 'true', }; - /// Explicit Connect completes identity setup and discovers joined communities. - /// Passive startup restore only checks the saved session. + /// Opens account sign-in, optional address discovery, or explicit reauthentication. Future signInAccount({ bool openBrowser = true, bool importIdentity = false, - }) { - if (_target != null || - stage == HostedFlowStage.working || - stage == HostedFlowStage.signIn) { - return Future.value(); - } - final generation = openBrowser ? _nextGeneration() : _generation; - if (openBrowser) { - _importRequested = _importRequested || importIdentity; - reconnecting = false; - accountOnly = true; - _clearCommunityBatch(); - _set(HostedFlowStage.working); - } - return _enqueue(() async { - if (!openBrowser) { - if (_target != null || stage != HostedFlowStage.idle) return; - } - if (openBrowser) { - await browser.retainIntent(_accountIntent); - if (_disposed || generation != _generation) return; - } - final restored = await account.restore(); - if (_disposed || generation != _generation) return; - if (!openBrowser) { - // Mounting the welcome page must not create/bind/back up a key. - if (_importRequested && restored != null) { - final saved = await store.forSubject(restored.subject).read(); - if (_disposed || generation != _generation) return; - if (saved != null) { - // Also repair intents saved before import completion was recorded. - _importRequested = false; - await browser.retainIntent(_accountIntent); - if (_disposed || generation != _generation) return; - } - } - if (_importRequested && restored != null) { - canCreateIdentity = false; - requiredIdentityPubkey = null; - _set(HostedFlowStage.setupIdentity); - } else { - _set(HostedFlowStage.idle); - } - } else if (restored != null) { - await _continue(generation); - } else { - _set(HostedFlowStage.signIn); - await browser.start(_accountIntent); - } - }); - } + bool discoverOnly = false, + bool reauthenticate = false, + }) => _signInAccount( + openBrowser: openBrowser, + importIdentity: importIdentity, + discoverOnly: discoverOnly, + reauthenticate: reauthenticate, + ); /// Securely retain the transferred identity before NIP-AB completion. Hosted /// admission still waits for account, binding and backup in the normal flow. @@ -575,9 +536,18 @@ class HostedFlow extends ChangeNotifier { final store = this.store.forSubject(session.subject); if (target != null && !_acceptTarget(target)) return; if (target == null && _batchSubject != session.subject) { + final discoverOnly = _discoverOnly; _clearCommunityBatch(); + _discoverOnly = discoverOnly; _batchSubject = session.subject; } + if (_discoverOnly && + !_importRequested && + !_addingCommunities && + target == null) { + await _continueCommunities(generation, session.subject, ''); + return; + } final canSealBackup = await HpkeBackup.supportsSealing(); if (_disposed || generation != _generation) return; var resolved = await identity.resolve( @@ -856,6 +826,7 @@ class HostedFlow extends ChangeNotifier { return Future.value(); } _returnToAddedCommunity = returnToAddedCommunity || _returnToAddedCommunity; + _discoverOnly = false; _addingCommunities = true; final generation = _nextGeneration(); _set(HostedFlowStage.working); @@ -908,10 +879,14 @@ class HostedFlow extends ChangeNotifier { generation == _generation && account.account?.subject == subject; if (!_addingCommunities) { - final listed = await loadKnownHostedCommunities(account); + final listed = await loadKnownAccountCommunities(account); if (!current()) return; communities = listed; - selectedRelays = Set.unmodifiable(listed.map((item) => item.relayUrl)); + selectedRelays = Set.unmodifiable({ + for (final item in listed) + if (HostedEnvironment.supportsRelay(Uri.parse(item.relayUrl))) + item.relayUrl, + }); if (listed.isEmpty) { await leave(noCommunities: true); return; @@ -1096,6 +1071,7 @@ class HostedFlow extends ChangeNotifier { _batchSubject = null; _conflictingRelay = null; _addingCommunities = false; + _discoverOnly = false; addingCommunityName = null; } diff --git a/mobile/lib/shared/hosted/hosted_flow_account_entry.dart b/mobile/lib/shared/hosted/hosted_flow_account_entry.dart new file mode 100644 index 0000000000..ef3faa62c5 --- /dev/null +++ b/mobile/lib/shared/hosted/hosted_flow_account_entry.dart @@ -0,0 +1,71 @@ +part of 'hosted_flow.dart'; + +/// Account entry and discovery without requiring a hosted identity first. +extension HostedFlowAccountEntry on HostedFlow { + /// Explicit Connect completes identity setup and discovers joined communities. + /// Passive startup restore only checks the saved session. + Future _signInAccount({ + bool openBrowser = true, + bool importIdentity = false, + bool discoverOnly = false, + bool reauthenticate = false, + }) { + // Completed admission no longer owns account entry. Keep in-flight targets + // intact, but let recovery start a fresh account flow after a successful join. + if (openBrowser && stage == HostedFlowStage.complete) { + _target = null; + _pairedPubkey = null; + pairedSensitiveActionPolicy = null; + } + if (_target != null || + stage == HostedFlowStage.working || + stage == HostedFlowStage.signIn) { + return Future.value(); + } + final generation = openBrowser ? _nextGeneration() : _generation; + if (openBrowser) { + _importRequested = _importRequested || importIdentity; + reconnecting = false; + accountOnly = true; + _clearCommunityBatch(); + _discoverOnly = discoverOnly; + _set(HostedFlowStage.working); + } + return _enqueue(() async { + if (!openBrowser) { + if (_target != null || stage != HostedFlowStage.idle) return; + } + if (openBrowser) { + await browser.retainIntent(_accountIntent); + if (_disposed || generation != _generation) return; + } + final restored = reauthenticate ? null : await account.restore(); + if (_disposed || generation != _generation) return; + if (!openBrowser) { + // Mounting the welcome page must not create/bind/back up a key. + if (_importRequested && restored != null) { + final saved = await store.forSubject(restored.subject).read(); + if (_disposed || generation != _generation) return; + if (saved != null) { + // Also repair intents saved before import completion was recorded. + _importRequested = false; + await browser.retainIntent(_accountIntent); + if (_disposed || generation != _generation) return; + } + } + if (_importRequested && restored != null) { + canCreateIdentity = false; + requiredIdentityPubkey = null; + _set(HostedFlowStage.setupIdentity); + } else { + _set(HostedFlowStage.idle); + } + } else if (restored != null) { + await _continue(generation); + } else { + _set(HostedFlowStage.signIn); + await browser.start(_accountIntent); + } + }); + } +} diff --git a/mobile/lib/shared/hosted/known_communities_provider.dart b/mobile/lib/shared/hosted/known_communities_provider.dart new file mode 100644 index 0000000000..30b53e5742 --- /dev/null +++ b/mobile/lib/shared/hosted/known_communities_provider.dart @@ -0,0 +1,33 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../deeplink/deep_link.dart'; +import 'hosted_communities.dart'; +import 'hosted_environment.dart'; +import 'hosted_relay_auth.dart'; +import 'known_community_sync_provider.dart'; + +/// Account destinations for the switcher. Listing never imports a community or +/// changes the active identity; admission happens only after a selection. +final knownCommunitiesProvider = + FutureProvider.autoDispose>((ref) async { + if (!HostedEnvironment.enabled) return const []; + final account = ref.watch(builderlabAccountProvider); + final sync = ref.watch(knownCommunitySyncProvider); + final builtFor = account.account?.subject; + // A new account reloads, so it never shows the previous account's list; + // any other change refreshes behind the current list. The first listener + // to fire disposes the other, so both decide from the account itself. + void changed() => + ref.invalidateSelf(asReload: account.account?.subject != builtFor); + sync?.addListener(changed); + ref.onDispose(() => sync?.removeListener(changed)); + account.subjectChanges.addListener(changed); + ref.onDispose(() => account.subjectChanges.removeListener(changed)); + final session = account.account ?? await account.restore(); + if (!ref.mounted || session == null) return const []; + final communities = await loadKnownAccountCommunities(account); + if (!ref.mounted || account.account?.subject != session.subject) { + return const []; + } + return communities; + }); diff --git a/mobile/lib/shared/hosted/known_community_address.dart b/mobile/lib/shared/hosted/known_community_address.dart new file mode 100644 index 0000000000..ce18afa84b --- /dev/null +++ b/mobile/lib/shared/hosted/known_community_address.dart @@ -0,0 +1,24 @@ +import '../deeplink/community_link_input.dart'; +import '../deeplink/deep_link.dart'; + +/// A saved account destination must also be a supported mobile address. Keep +/// explicit ports and reject paths, credentials, and insecure transports. +String? knownCommunityAddress(String value) { + final uri = Uri.tryParse(value); + if (uri == null || !{'wss', 'https'}.contains(uri.scheme)) return null; + if (RegExp(r':0+/?$').hasMatch(value) || + (uri.hasPort && (uri.port < 1 || uri.port > 65535))) { + return null; + } + final link = parseCommunityLinkInput(value); + if (link == null) return null; + final parsed = parseAddCommunityDeepLink(link); + if (parsed == null) return null; + final relay = Uri.parse(parsed.relayUrl); + if (relay.hasPort && (relay.port < 1 || relay.port > 65535)) return null; + return Uri( + scheme: 'wss', + host: relay.host.toLowerCase(), + port: relay.hasPort && relay.port != 443 ? relay.port : null, + ).toString(); +} diff --git a/mobile/lib/shared/hosted/known_community_sync.dart b/mobile/lib/shared/hosted/known_community_sync.dart new file mode 100644 index 0000000000..4a7bc5af44 --- /dev/null +++ b/mobile/lib/shared/hosted/known_community_sync.dart @@ -0,0 +1,348 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:uuid/uuid.dart'; + +import '../community/community.dart'; + +import '../storage/secure_storage.dart'; +import '../storage/serial_queue.dart'; +import 'builderlab_account.dart'; +import 'known_community_address.dart'; + +/// Retained account for a local add or removal only. +extension LocalEditSubject on BuilderlabAccountClient { + /// An unreadable session record makes a local add or removal behave as + /// signed out: no owner stamp and no tombstone, so the device edit still + /// succeeds as it did before account sync. Account sync itself stays strict: + /// it requires a verified session and never reads this fallback. + Future localEditSubject() async { + try { + return await retainedSubject(); + } on AccountFailure catch (failure) { + if (failure == AccountFailure.storage) return null; + rethrow; + } + } +} + +/// Durable account-list edits. Community credentials and relay membership never +/// enter this queue. Each account keeps its own snapshot and latest URL intents. +class KnownCommunitySync extends ChangeNotifier { + /// Reconciles committed, explicitly owned additions and queued removals. + KnownCommunitySync({ + required this.account, + required this.localCommunities, + this.acknowledgeRemoval, + FlutterSecureStorage? storage, + this.retryDelay = const Duration(seconds: 2), + }) : _storage = storage ?? accountSecureStorage { + account.subjectChanges.addListener(_sessionChanged); + account.sessionChanges.addListener(_sessionChanged); + } + + /// Account API whose verified session authorizes each destination edit. + final BuilderlabAccountClient account; + + /// Durable device records, including their explicit account ownership. + final Future> Function() localCommunities; + + /// Removes a credential-free local tombstone only after server acknowledgment. + final Future Function(String revision)? acknowledgeRemoval; + final FlutterSecureStorage _storage; + + /// Initial transient retry delay; subsequent failures back off up to 32x. + final Duration retryDelay; + + /// Latest failure for the current account; pending work remains durable. + Object? get failure => _failure; + Object? _failure; + final _queue = SerialQueue(); + Timer? _retry; + bool _disposed = false; + bool _active = true; + Future? _work; + bool _again = false; + String? _blockedSubject; + int _failures = 0; + + String _key(String subject) => + 'buzz_known_communities_v1_${base64Url.encode(utf8.encode('${account.accountOrigin.origin}\n$subject'))}'; + + Future<_SyncState> _read(String subject) async { + final raw = await _storage.read(key: _key(subject)); + return raw == null ? _SyncState() : _SyncState.decode(raw); + } + + Future _write(String subject, _SyncState state) => + _storage.write(key: _key(subject), value: state.encode()); + + bool _current(String subject) => + !_disposed && account.account?.subject == subject; + + void _sessionChanged() { + _failure = null; + _blockedSubject = null; + _failures = 0; + _retry?.cancel(); + notifyListeners(); + trigger(); + } + + /// Stop retries immediately when the app leaves the foreground. + void setActive(bool active) { + _active = active; + _retry?.cancel(); + if (active) trigger(); + } + + /// Persist removal before deleting the local record. The drain sends it only + /// once the local record is absent, so failed local deletion cannot forget it + /// remotely. Signed-out edits never borrow another account's credentials. + Future remove(String relay, {String? expectedSubject}) async { + final subject = expectedSubject ?? await account.localEditSubject(); + if (await account.localEditSubject() != subject) { + throw AccountFailure.differentAccount; + } + final url = knownCommunityAddress(relay); + if (subject == null || url == null) return; + await _queue.run(() async { + final state = await _read(subject); + if (!_current(subject)) throw AccountFailure.differentAccount; + final local = await localCommunities(); + if (!_current(subject)) throw AccountFailure.differentAccount; + for (final item in local) { + if (knownCommunityAddress(item.relayUrl) == url && + item.accountSyncOwner == _owner(subject) && + item.accountSyncRevision != null) { + state.observed[url] = item.accountSyncRevision!; + } + } + state.pending[url] = true; + await _write(subject, state); + }); + if (!_disposed) notifyListeners(); + } + + String _owner(String subject) => '${account.accountOrigin.origin}\n$subject'; + + /// Stamp only explicit additions. Saving this returned record atomically with + /// credentials is the durable add intent; a later journal failure cannot turn + /// a completed join into an authentication failure. Unclaimed legacy records + /// and another account's retained records are never automatically uploaded. + Future prepareAddition(Community community) async { + final subject = await account.localEditSubject(); + if (subject == null && + community.accountSyncOwner == null && + community.accountSyncRevision == null) { + return community; + } + return community.copyWith( + accountSyncRemoved: false, + accountSyncOwner: subject == null ? null : _owner(subject), + accountSyncRevision: subject == null ? null : const Uuid().v4(), + ); + } + + /// An explicit retry clears a refused request without dropping its intent. + void retry() { + _blockedSubject = null; + _failure = null; + _failures = 0; + notifyListeners(); + trigger(); + } + + /// Pending removals for visible status, including across app restarts. + Future> pendingRemovals(String subject) => _queue.run(() async { + final records = await localCommunities(); + final removed = records + .where( + (c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject), + ) + .map((c) => c.relayUrl) + .toSet(); + try { + final state = await _read(subject); + removed.addAll( + state.pending.entries.where((e) => e.value).map((e) => e.key), + ); + } catch (_) { + // A separate journal failure must not conceal a committed local removal. + if (removed.isEmpty) rethrow; + } + return removed; + }); + + /// Run after startup, a saved-community change, sign-in, or app resume. + void trigger() => unawaited(synchronize()); + + /// Coalesce concurrent refreshes and complete after their queued work drains. + Future synchronize() { + if (_disposed || !_active) return Future.value(); + _retry?.cancel(); + final work = _work; + if (work != null) { + _again = true; + return work; + } + return _work = _drain().whenComplete(() => _work = null); + } + + Future _drain() async { + do { + _again = false; + await _run(); + } while (_again && !_disposed && _active); + } + + Future _run() async { + String? attemptSubject; + try { + final session = account.account ?? await account.restore(); + if (session == null || !_current(session.subject) || !_active) return; + final subject = session.subject; + attemptSubject = subject; + if (_blockedSubject == subject) return; + // Local deletion and this intent share a single storage commit. Drain it + // independently of the older account-only journal, even if that is broken. + final committed = await localCommunities(); + for (final item in committed.where( + (c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject), + )) { + if (!_current(subject)) return; + await account.updateKnownCommunity( + item.relayUrl, + removed: true, + expectedSubject: subject, + ); + if (!_current(subject)) return; + await acknowledgeRemoval?.call(item.accountSyncRevision!); + if (!_disposed) notifyListeners(); + } + var local = {}; + await _queue.run(() async { + final records = (await localCommunities()) + .where((c) => !c.accountSyncRemoved) + .toList(); + local = records + .where((c) => c.accountSyncOwner == _owner(subject)) + .map((c) => knownCommunityAddress(c.relayUrl)) + .whereType() + .toSet(); + final state = await _read(subject); + if (!_current(subject)) return; + final owned = records + .where( + (item) => + item.accountSyncOwner == _owner(subject) && + item.accountSyncRevision != null, + ) + .map((item) => knownCommunityAddress(item.relayUrl)) + .whereType() + .toSet(); + // Older preview journals had no ownership evidence for inferred adds. + state.pending.removeWhere( + (url, removed) => !removed && !owned.contains(url), + ); + final revisions = >{}; + for (final item in records) { + final url = knownCommunityAddress(item.relayUrl); + final revision = item.accountSyncRevision; + if (url == null || + revision == null || + item.accountSyncOwner != _owner(subject)) { + continue; + } + (revisions[url] ??= []).add(revision); + } + for (final entry in revisions.entries) { + final url = entry.key; + final revision = (entry.value..sort()).join(','); + if (state.observed[url] != revision) { + // A committed re-add wins over an older removal, even if the app + // stopped before it could update this separate retry journal. + state.pending[url] = false; + state.observed[url] = revision; + } + } + await _write(subject, state); + }); + while (_current(subject) && _active) { + final pending = await _queue.run(() => _read(subject)); + final entries = pending.pending.entries.where( + (entry) => !entry.value || !local.contains(entry.key), + ); + if (entries.isEmpty) break; + final op = entries.first; + if (!_current(subject)) return; + await account.updateKnownCommunity( + op.key, + removed: op.value, + expectedSubject: subject, + ); + if (!_current(subject)) return; + await _queue.run(() async { + final latest = await _read(subject); + // An edit made while the request was in flight wins over its ack. + if (latest.pending[op.key] == op.value) { + latest.pending.remove(op.key); + await _write(subject, latest); + } + }); + if (!_disposed) notifyListeners(); + } + _failures = 0; + if (_failure != null) { + _failure = null; + notifyListeners(); + } + } catch (error) { + if (_disposed || (attemptSubject != null && !_current(attemptSubject))) { + return; + } + _failure = error; + notifyListeners(); + if (error == AccountFailure.denied || + error == AccountFailure.rejected || + error == AccountFailure.invalidResponse || + error == AccountFailure.accountSetupRequired) { + // Preserve intent but do not hammer a refused API until a new sign-in. + _blockedSubject = account.account?.subject; + } else if (_active && error != AccountFailure.signedOut) { + final multiplier = 1 << (_failures++).clamp(0, 5); + _retry = Timer(retryDelay * multiplier, trigger); + } + debugPrint('Account community sync deferred: $error'); + } + } + + @override + void dispose() { + _disposed = true; + _retry?.cancel(); + account.subjectChanges.removeListener(_sessionChanged); + account.sessionChanges.removeListener(_sessionChanged); + super.dispose(); + } +} + +class _SyncState { + _SyncState({Map? observed, Map? pending}) + : observed = observed ?? {}, + pending = pending ?? {}; + final Map observed; + final Map pending; + + factory _SyncState.decode(String raw) { + final value = jsonDecode(raw) as Map; + return _SyncState( + observed: (value['observed'] as Map?)?.cast() ?? {}, + pending: (value['pending'] as Map).cast(), + ); + } + + String encode() => jsonEncode({'observed': observed, 'pending': pending}); +} diff --git a/mobile/lib/shared/hosted/known_community_sync_provider.dart b/mobile/lib/shared/hosted/known_community_sync_provider.dart new file mode 100644 index 0000000000..f0572288f7 --- /dev/null +++ b/mobile/lib/shared/hosted/known_community_sync_provider.dart @@ -0,0 +1,20 @@ +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../community/community_provider.dart'; +import 'hosted_environment.dart'; +import 'hosted_relay_auth.dart'; +import 'known_community_sync.dart'; + +/// Account sync is owned by the app, independent of the active relay session. +final knownCommunitySyncProvider = Provider((ref) { + if (!HostedEnvironment.enabled) return null; + final sync = KnownCommunitySync( + account: ref.watch(builderlabAccountProvider), + localCommunities: () => + ref.read(communityStorageProvider).loadForAccountSync(), + acknowledgeRemoval: (revision) => + ref.read(communityStorageProvider).acknowledgeRemoval(revision), + ); + ref.onDispose(sync.dispose); + return sync; +}); diff --git a/mobile/test/features/age_gate/age_gate_app_test.dart b/mobile/test/features/age_gate/age_gate_app_test.dart index eadec6ccda..723aa677e5 100644 --- a/mobile/test/features/age_gate/age_gate_app_test.dart +++ b/mobile/test/features/age_gate/age_gate_app_test.dart @@ -1,4 +1,6 @@ import 'dart:async'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'dart:convert'; import 'package:buzz/app.dart'; @@ -24,6 +26,7 @@ import 'package:shared_preferences/shared_preferences.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); const appBadgeChannel = MethodChannel('app_badge_plus'); tearDown(() { diff --git a/mobile/test/features/channels/channels_page_test.dart b/mobile/test/features/channels/channels_page_test.dart index a708fa45a0..08c2075622 100644 --- a/mobile/test/features/channels/channels_page_test.dart +++ b/mobile/test/features/channels/channels_page_test.dart @@ -1,7 +1,9 @@ +import 'package:buzz/shared/hosted/known_community_sync_provider.dart'; import 'package:buzz/shared/widgets/ios_message_create_button.dart'; import 'package:buzz/shared/hosted/browser_auth.dart'; import 'package:buzz/shared/hosted/builderlab_account.dart'; import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; +import 'package:buzz/shared/hosted/known_communities_provider.dart'; import 'package:buzz/shared/hosted/organization_sign_in.dart'; import 'package:buzz/features/channels/default_agent_launcher.dart'; import 'package:buzz/features/agents/agents_page.dart'; @@ -121,6 +123,8 @@ void main() { // different identity (the page reads its pubkey from profileProvider). profileProvider.overrideWith(() => profile ?? _FakeProfileNotifier()), presenceProvider.overrideWith(() => _FakePresenceNotifier()), + knownCommunitiesProvider.overrideWith((ref) async => const []), + knownCommunitySyncProvider.overrideWithValue(null), communityIconProvider.overrideWith((ref, relayUrl) async { onCommunityIconLoad?.call(relayUrl); if (loadCommunityIcon != null) return loadCommunityIcon(relayUrl); @@ -4281,7 +4285,11 @@ class _FakeCommunityListNotifier extends CommunityListNotifier { Future> build() async => _communities; @override - Future removeCommunity(String id) async { + Future removeCommunity( + String id, { + String? confirmedSubject, + bool accountConfirmed = false, + }) async { removedIds.add(id); _communities = _communities .where((community) => community.id != id) diff --git a/mobile/test/features/channels/community_switcher_discovery_test.dart b/mobile/test/features/channels/community_switcher_discovery_test.dart new file mode 100644 index 0000000000..207d8498f8 --- /dev/null +++ b/mobile/test/features/channels/community_switcher_discovery_test.dart @@ -0,0 +1,195 @@ +import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'dart:async'; + +import 'package:buzz/features/channels/channels_page.dart'; +import 'package:buzz/shared/auth/auth.dart'; +import 'package:buzz/shared/community/community_icon_provider.dart'; +import 'package:buzz/shared/deeplink/deep_link.dart'; +import 'package:buzz/shared/hosted/known_communities_provider.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:buzz/shared/hosted/hosted_flow_provider.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import '../../helpers/hosted_communities_fixture.dart'; + +import '../../helpers/widget_helpers.dart'; + +final _saved = Community( + id: 'saved', + name: 'Saved community', + relayUrl: 'wss://saved.communities.buzz.xyz', + addedAt: DateTime(2025), +); +const _discovered = AddCommunityDeepLink( + name: 'Account community', + relayUrl: 'wss://other.communities.buzz.xyz', +); + +class _SavedCommunities extends CommunityListNotifier { + @override + Future> build() async => [_saved]; +} + +Widget _page(Future> Function() load) => + WidgetHelpers.testable( + overrides: [ + communityListProvider.overrideWith(_SavedCommunities.new), + activeCommunityProvider.overrideWith((ref) async => _saved), + knownCommunitiesProvider.overrideWith((ref) => load()), + communityIconPresentationProvider.overrideWith((ref, relay) => null), + ], + child: CommunitySwitcherPage( + destination: null, + prepareLanding: () async => null, + onFlightChanged: (_) {}, + onTransitionProgress: (_) {}, + ), + ); + +void main() { + testWidgets('shows account destinations alongside saved communities once', ( + tester, + ) async { + final discovery = Completer>(); + await tester.pumpWidget(_page(() => discovery.future)); + await tester.pump(); + expect(find.text('Saved community'), findsOneWidget); + // Loading adds nothing above the grid, so the grid does not move when the + // account list arrives. + expect(find.bySemanticsLabel('Loading account communities'), findsNothing); + final savedTop = tester.getTopLeft(find.text('Saved community')); + expect(find.byKey(const Key('community-switcher-add')), findsOneWidget); + discovery.complete([ + AddCommunityDeepLink(name: 'Duplicate', relayUrl: '${_saved.relayUrl}/'), + _discovered, + ]); + await tester.pumpAndSettle(); + expect(find.text('Saved community'), findsOneWidget); + expect(find.text('Account community'), findsOneWidget); + expect(find.text('Duplicate'), findsNothing); + expect(tester.getTopLeft(find.text('Saved community')), savedTop); + expect(find.text('Find my communities'), findsNothing); + await tester.tap(find.text('Edit')); + await tester.pumpAndSettle(); + // Edit exposes removal for both local and account-saved destinations. + expect(find.byTooltip('Remove Saved community'), findsOneWidget); + expect(find.byTooltip('Remove Account community'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + for (final adding in [false, true]) { + testWidgets( + adding + ? 'switcher Add omits redundant account discovery' + : 'account selection enters only the chosen community through admission', + (tester) async { + FlutterSecureStorage.setMockInitialValues({}); + final fixture = HostedCommunitiesFixture(); + await fixture.initialize(widget: true); + fixture.rows = [fixture.row('other')]; + addTearDown(fixture.dispose); + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [ + communityListProvider.overrideWith(_SavedCommunities.new), + activeCommunityProvider.overrideWith((ref) async => _saved), + knownCommunitiesProvider.overrideWith( + (ref) async => [_discovered], + ), + communityIconPresentationProvider.overrideWith( + (ref, relay) => null, + ), + hostedFlowProvider.overrideWithValue(fixture.flow), + ], + child: Builder( + builder: (context) => TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => CommunitySwitcherPage( + destination: null, + prepareLanding: () async => null, + onFlightChanged: (_) {}, + onTransitionProgress: (_) {}, + ), + ), + ), + child: const Text('Open switcher'), + ), + ), + ), + ); + await tester.tap(find.text('Open switcher')); + await tester.pumpAndSettle(); + expect(fixture.admitted, isEmpty); + if (adding) { + await tester.tap(find.byKey(const Key('community-switcher-add'))); + await tester.pumpAndSettle(); + expect(find.text('Enter a community link'), findsOneWidget); + expect(find.text('Find my communities'), findsNothing); + expect(fixture.admitted, isEmpty); + } else { + await tester.tap(find.text('Account community')); + await tester.pumpAndSettle(); + expect(fixture.admitted, ['other.communities.buzz.xyz']); + } + expect(find.byKey(const Key('community-switcher-page')), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets( + 'external account destination uses the existing self-hosted entry dispatcher', + (tester) async { + PendingDeepLinkNotifier.debugUriStreamOverride = + const Stream.empty(); + addTearDown(() => PendingDeepLinkNotifier.debugUriStreamOverride = null); + const external = AddCommunityDeepLink( + name: 'External', + relayUrl: 'wss://team.example:8443', + ); + await tester.pumpWidget(_page(() async => [external])); + await tester.pumpAndSettle(); + final container = ProviderScope.containerOf( + tester.element(find.byType(CommunitySwitcherPage)), + ); + final subscription = container.listen(pendingDeepLinkProvider, (_, _) {}); + addTearDown(subscription.close); + await tester.tap(find.text('External')); + await tester.pumpAndSettle(); + expect( + container.read(pendingDeepLinkProvider), + isA().having( + (c) => c.relayUrl, + 'relay', + external.relayUrl, + ), + ); + }, + ); + + testWidgets('failed discovery keeps saved choices and Add, and can retry', ( + tester, + ) async { + var attempts = 0; + await tester.pumpWidget( + _page(() async { + if (++attempts == 1) throw StateError('offline'); + return [_discovered]; + }), + ); + await tester.pumpAndSettle(); + expect(find.text('Saved community'), findsOneWidget); + expect(find.byKey(const Key('community-switcher-add')), findsOneWidget); + expect( + find.text('Could not load your account communities.'), + findsOneWidget, + ); + await tester.tap(find.text('Try again')); + await tester.pumpAndSettle(); + expect(find.text('Account community'), findsOneWidget); + expect(find.text('Could not load your account communities.'), findsNothing); + expect(attempts, 2); + }); +} diff --git a/mobile/test/features/invites/invite_active_community_race_test.dart b/mobile/test/features/invites/invite_active_community_race_test.dart index b870788a6d..57f1ffcf8e 100644 --- a/mobile/test/features/invites/invite_active_community_race_test.dart +++ b/mobile/test/features/invites/invite_active_community_race_test.dart @@ -1,5 +1,7 @@ import 'dart:async'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + import 'package:buzz/features/invites/invite_join_provider.dart'; import 'package:buzz/shared/auth/auth.dart'; import 'package:buzz/shared/deeplink/deep_link.dart'; @@ -12,6 +14,8 @@ import 'package:nostr/nostr.dart' as nostr; import '../../shared/community/community_storage_test.dart'; void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); for (final finishReadBeforeJoin in [false, true]) { test('first invite setup succeeds when old active read finishes ' '${finishReadBeforeJoin ? 'before' : 'after'} new selection', () async { diff --git a/mobile/test/features/invites/invite_join_provider_test.dart b/mobile/test/features/invites/invite_join_provider_test.dart index 959ff296d0..ac69ecff58 100644 --- a/mobile/test/features/invites/invite_join_provider_test.dart +++ b/mobile/test/features/invites/invite_join_provider_test.dart @@ -1,5 +1,7 @@ import 'package:buzz/shared/hosted/hosted_environment.dart'; import 'dart:async'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; @@ -18,6 +20,8 @@ import 'package:buzz/shared/deeplink/deep_link.dart'; import '../../shared/community/community_storage_test.dart'; void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); test( 'legacy invite entry refuses staging before key generation or claim', () async { diff --git a/mobile/test/features/onboarding/account_community_entry_test.dart b/mobile/test/features/onboarding/account_community_entry_test.dart new file mode 100644 index 0000000000..e3fa847292 --- /dev/null +++ b/mobile/test/features/onboarding/account_community_entry_test.dart @@ -0,0 +1,198 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:buzz/shared/hosted/browser_auth.dart'; +import 'package:buzz/shared/hosted/hosted_flow.dart'; +import 'package:buzz/shared/hosted/hosted_identity_service.dart'; +import 'package:buzz/features/onboarding/self_hosted_entry_sheet.dart'; +import 'package:buzz/hosted_app_gate.dart'; +import 'package:buzz/onboarding_app_entry.dart'; +import 'package:buzz/shared/community/community_icon_provider.dart'; +import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/hosted/hosted_flow_provider.dart'; +import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../helpers/hosted_communities_fixture.dart'; +import '../../helpers/widget_helpers.dart'; + +void main() { + for (final discover in [true, false]) { + for (final callback in [true, false]) { + testWidgets( + 'browser restart retains discovery=$discover callback=$callback', + (tester) async { + if (!HostedEnvironment.enabled) return; + FlutterSecureStorage.setMockInitialValues({}); + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('buzz/hosted_hpke'), + (_) async => false, + ); + addTearDown(() { + debugDefaultTargetPlatformOverride = null; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('buzz/hosted_hpke'), + null, + ); + }); + final fixture = HostedCommunitiesFixture(); + await fixture.initialize(withIdentity: false); + fixture.rows = [ + {'community_url': 'wss://external.example:8443'}, + ]; + await fixture.account.clearLocalSession(); + await fixture.flow.initialize(); + await fixture.flow.signInAccount(discoverOnly: discover); + final intent = fixture.browser.startedIntent!; + fixture.flow.dispose(); + await fixture.browser.dispose(); + final browser = DiscoveryBrowser(); + final flow = HostedFlow( + account: fixture.account, + browser: browser, + store: fixture.store, + identity: HostedIdentityService( + account: fixture.account, + store: fixture.store, + ), + openWeb: (_) async => true, + enterCommunity: (_, _, _, _) async {}, + ); + await flow.initialize(); + if (callback) { + browser.callbacks.add(BrowserAuthCode('return', 'a' * 43, intent)); + await tester.pumpAndSettle(); + } else { + // Restored intent also survives a retry before the browser returns. + await flow.retry(); + browser.callbacks.add( + BrowserAuthCode('return', 'a' * 43, browser.startedIntent!), + ); + await tester.pumpAndSettle(); + } + if (discover) { + expect(flow.stage, HostedFlowStage.chooseCommunities); + expect(flow.communities.map((c) => c.relayUrl), [ + 'wss://external.example:8443', + ]); + expect( + fixture.requests.where((p) => p.contains('nostr-identities')), + isEmpty, + ); + } else { + expect(flow.stage, HostedFlowStage.blocked); + expect(flow.problem, HostedFlowProblem.unsupportedPlatform); + expect( + fixture.requests.where((p) => p.endsWith('/current')), + isNotEmpty, + ); + } + debugDefaultTargetPlatformOverride = null; + flow.dispose(); + await browser.dispose(); + fixture.account.dispose(); + }, + ); + } + } + + for (final scenario in ['external-only', 'mixed', 'hosted-selection']) { + final mixed = scenario != 'external-only'; + testWidgets( + 'fresh $scenario account discovers destinations before admission', + (tester) async { + if (!HostedEnvironment.enabled) return; + FlutterSecureStorage.setMockInitialValues({}); + PendingDeepLinkNotifier.debugUriStreamOverride = + const Stream.empty(); + addTearDown( + () => PendingDeepLinkNotifier.debugUriStreamOverride = null, + ); + final fixture = HostedCommunitiesFixture(); + await fixture.initialize(widget: true, withIdentity: mixed); + addTearDown(fixture.dispose); + fixture.rows = [ + {'community_url': 'wss://team.example:8443'}, + {'community_url': 'wss://team.example:9443'}, + {'community_url': 'wss://unsupported.communities.buzz.xyz:8443'}, + if (mixed) fixture.row('hosted'), + ]; + await tester.pumpWidget( + WidgetHelpers.testable( + overrides: [ + hostedFlowProvider.overrideWithValue(fixture.flow), + builderlabAccountProvider.overrideWithValue(fixture.account), + communityIconPresentationProvider.overrideWith( + (ref, relay) => null, + ), + ], + child: const HostedAppGate( + authenticated: false, + child: OnboardingAppEntry(), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Find my communities'), findsOneWidget); + await tester.tap(find.text('Find my communities')); + await tester.pumpAndSettle(); + expect(find.text('team.example:8443'), findsOneWidget); + expect(find.text('team.example:9443'), findsOneWidget); + expect( + find.text('unsupported.communities.buzz.xyz:8443'), + findsNothing, + ); + expect(find.text('hosted'), mixed ? findsOneWidget : findsNothing); + expect( + fixture.requests.where((p) => p.contains('nostr-identities')), + isEmpty, + ); + if (scenario == 'hosted-selection') { + await tester.tap(find.text('hosted')); + await tester.pumpAndSettle(); + expect(fixture.admitted, ['hosted.communities.buzz.xyz']); + expect( + fixture.requests.where((p) => p.endsWith('/current')), + isNotEmpty, + ); + expect(find.byType(SelfHostedEntrySheet), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + return; + } + final port = mixed ? 9443 : 8443; + final row = find.byKey( + Key('community-switcher-row-wss://team.example:$port'), + ); + final semantics = tester.ensureSemantics(); + expect(tester.getSemantics(row).label, contains('team.example:$port')); + semantics.dispose(); + await tester.tap(find.text('team.example:$port')); + await tester.pumpAndSettle(); + expect(find.byType(SelfHostedEntrySheet), findsOneWidget); + expect( + tester + .widget(find.byType(SelfHostedEntrySheet)) + .relay, + 'wss://team.example:$port', + ); + expect(fixture.admitted, isEmpty); + if (!mixed) { + expect( + fixture.requests.where((p) => p.contains('nostr-identities')), + isEmpty, + reason: + 'external discovery must not resolve, bind, or back up a hosted key', + ); + expect(await fixture.store.read(), isNull); + } + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + }, + ); + } +} diff --git a/mobile/test/features/onboarding/account_sync_recovery_test.dart b/mobile/test/features/onboarding/account_sync_recovery_test.dart new file mode 100644 index 0000000000..33a75488d5 --- /dev/null +++ b/mobile/test/features/onboarding/account_sync_recovery_test.dart @@ -0,0 +1,664 @@ +import 'package:buzz/shared/deeplink/deep_link.dart'; +import 'package:buzz/hosted_app_gate.dart'; +import 'package:buzz/onboarding_app_entry.dart'; +import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'dart:async'; +import 'dart:convert'; + +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/account_community_sync_status.dart'; +import 'package:buzz/shared/hosted/account_identity_store.dart'; +import 'package:buzz/shared/hosted/browser_auth.dart'; +import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/hosted/hosted_flow.dart'; +import 'package:buzz/shared/hosted/hosted_flow_provider.dart'; +import 'package:buzz/shared/hosted/hosted_identity_service.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/material.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.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 '../../helpers/hosted_communities_fixture.dart'; +import '../../helpers/widget_helpers.dart'; +import '../../shared/community/community_storage_test.dart' + show FakeSecureStorage; + +class _Backend { + final expiry = DateTime.now() + .add(const Duration(days: 1)) + .toUtc() + .toIso8601String(); + String subject = 'A'; + bool offline = false; + bool denied = false; + Completer? restoreGate; + final restoreStarted = Completer(); + final edits = <({String subject, String op, String url})>[]; + final sessions = FakeSecureStorage(); + BuilderlabAccountClient client() => BuilderlabAccountClient( + storage: sessions, + httpClient: MockClient((request) async { + final path = request.url.path; + if (path.endsWith('/me') && restoreGate != null) { + if (!restoreStarted.isCompleted) restoreStarted.complete(); + await restoreGate!.future; + } + if (offline) return http.Response('{}', 503); + if (path.endsWith('/exchange')) { + return http.Response( + jsonEncode({'session_credential': subject, 'expires_at': expiry}), + 200, + ); + } + if (path.endsWith('/me')) { + return http.Response( + jsonEncode({ + 'subject': request.headers['X-BB-Session-Credential'], + 'expires_at': expiry, + }), + 200, + ); + } + if (path.endsWith('/nostr-identities/current')) { + return http.Response( + jsonEncode({ + 'identity': {'pubkey_hex': nostr.Keys('1'.padLeft(64, '0')).public}, + }), + 200, + ); + } + if (path.endsWith('/nsec-backups/status')) { + return http.Response( + jsonEncode({ + 'backup_nostr_pubkeys': [], + 'current_nostr_pubkey': nostr.Keys('1'.padLeft(64, '0')).public, + }), + 200, + ); + } + if (path.endsWith('/list')) { + return http.Response('{"communities":[]}', 200); + } + if (path.contains('known-communities')) { + final body = jsonDecode(request.body) as Map; + if (denied) return http.Response('{}', 403); + edits.add(( + subject: request.headers['X-BB-Session-Credential']!, + op: path.split('/').last, + url: body['community_url'] as String, + )); + return http.Response('{}', 200); + } + return http.Response('{}', 503); + }), + ); +} + +class _BrokenJournal extends FakeSecureStorage { + String? broken; + @override + Future read({ + required String key, + AppleOptions? iOptions, + AndroidOptions? aOptions, + LinuxOptions? lOptions, + WebOptions? webOptions, + AppleOptions? mOptions, + WindowsOptions? wOptions, + }) { + if (broken == 'read') throw StateError('journal read failed'); + return super.read(key: key); + } + + @override + Future write({ + required String key, + required String? value, + AppleOptions? iOptions, + AndroidOptions? aOptions, + LinuxOptions? lOptions, + WebOptions? webOptions, + AppleOptions? mOptions, + WindowsOptions? wOptions, + }) { + if (broken == 'write') throw StateError('journal write failed'); + return super.write(key: key, value: value); + } +} + +Community _community(String id, [String url = 'wss://private.example']) => + Community( + id: id, + name: Uri.parse(url).host, + relayUrl: url, + addedAt: DateTime(2025), + nsec: nostr.Keys('1'.padLeft(64, '0')).nsec, + ); + +ProviderContainer _container( + BuilderlabAccountClient account, + CommunityStorage storage, + KnownCommunitySync sync, { + Future Function(Community)? beforeRemove, +}) => ProviderContainer( + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + communityStorageProvider.overrideWithValue(storage), + knownCommunitySyncProvider.overrideWithValue(sync), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + communityPushLeaseRevocationEnqueuerProvider.overrideWithValue( + beforeRemove ?? (_) async => false, + ), + ], +); + +KnownCommunitySync _sync( + BuilderlabAccountClient account, + CommunityStorage storage, { + FakeSecureStorage? journal, +}) => KnownCommunitySync( + account: account, + localCommunities: storage.loadForAccountSync, + acknowledgeRemoval: storage.acknowledgeRemoval, + storage: journal ?? FakeSecureStorage(), +); + +Future _signIn(BuilderlabAccountClient client) => + client.exchange(code: 'code', verifier: 'a' * 43); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); + + test( + 'confirmed removal stays with A across delayed push cleanup and A to B', + () async { + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final sync = _sync(account, storage)..setActive(false); + final entered = Completer(); + final release = Completer(); + var pause = true; + final container = _container( + account, + storage, + sync, + beforeRemove: (_) async { + if (pause) { + entered.complete(); + await release.future; + } + return false; + }, + ); + addTearDown(() { + container.dispose(); + sync.dispose(); + account.dispose(); + }); + await storage.save(await sync.prepareAddition(_community('first'))); + await container.read(communityListProvider.future); + final removing = container + .read(communityListProvider.notifier) + .removeCommunity('first'); + final rejected = expectLater( + removing, + throwsA(AccountFailure.differentAccount), + ); + await entered.future; + await account.clearLocalSession(); + backend.subject = 'B'; + await _signIn(account); + release.complete(); + await rejected; + expect((await storage.loadAll()).map((c) => c.id), ['first']); + sync.setActive(true); + await sync.synchronize(); + expect(backend.edits, isEmpty); + await account.clearLocalSession(); + backend.subject = 'A'; + await _signIn(account); + pause = false; + await container + .read(communityListProvider.notifier) + .removeCommunity( + 'first', + confirmedSubject: 'A', + accountConfirmed: true, + ); + await sync.synchronize(); + expect(await storage.loadAll(), isEmpty); + expect(backend.edits.where((e) => e.op == 'remove'), [ + (subject: 'A', op: 'remove', url: 'wss://private.example'), + ]); + expect(backend.edits.every((e) => e.subject == 'A'), isTrue); + // Once push revocation is durable, an account change must not strand the + // saved identity with a revoked lease. Finish A's confirmed removal. + final committedContainer = _container( + account, + storage, + sync, + beforeRemove: (_) async { + await account.clearLocalSession(); + backend.subject = 'B'; + await _signIn(account); + return true; + }, + ); + addTearDown(committedContainer.dispose); + sync.setActive(false); + await storage.save(await sync.prepareAddition(_community('committed'))); + await committedContainer.read(communityListProvider.future); + await committedContainer + .read(communityListProvider.notifier) + .removeCommunity('committed'); + expect(await storage.loadAll(), isEmpty); + await account.clearLocalSession(); + backend.subject = 'A'; + await _signIn(account); + sync.setActive(true); + await sync.synchronize(); + expect(await sync.pendingRemovals('A'), isEmpty); + }, + ); + + for (final queuedFirst in [false, true]) { + test( + 'A removal preserves B at the same URL (queued first: $queuedFirst)', + () async { + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final sync = _sync(account, storage)..setActive(false); + final container = _container(account, storage, sync); + addTearDown(() { + container.dispose(); + sync.dispose(); + account.dispose(); + }); + await storage.save(await sync.prepareAddition(_community('A'))); + if (queuedFirst) await sync.remove('wss://private.example'); + await account.clearLocalSession(); + backend.subject = 'B'; + await _signIn(account); + final b = _community( + 'B', + ).copyWith(nsec: nostr.Keys('2'.padLeft(64, '0')).nsec); + await storage.save(await sync.prepareAddition(b)); + await account.clearLocalSession(); + backend.subject = 'A'; + await _signIn(account); + await container.read(communityListProvider.future); + if (queuedFirst) { + // Old journal ordering: local deletion committed before restart. + await storage.remove('A'); + } else { + await container + .read(communityListProvider.notifier) + .removeCommunity('A'); + } + sync.setActive(true); + await sync.synchronize(); + expect((await storage.loadAll()).single.nsec, b.nsec); + expect((await storage.loadAll()).single.id, 'B'); + expect(backend.edits, [ + (subject: 'A', op: 'remove', url: 'wss://private.example'), + ]); + expect(await sync.pendingRemovals('A'), isEmpty); + }, + ); + } + + for (final failure in ['read', 'write']) { + test( + 'local removal survives $failure failure and duplicate identities, then restart converges', + () async { + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final journal = _BrokenJournal(); + var sync = _sync(account, storage, journal: journal)..setActive(false); + var container = _container(account, storage, sync); + for (final id in ['first', 'second']) { + await storage.save(await sync.prepareAddition(_community(id))); + } + await container.read(communityListProvider.future); + journal.broken = failure; + final firstId = failure == 'read' ? 'first' : 'second'; + final lastId = failure == 'read' ? 'second' : 'first'; + await container + .read(communityListProvider.notifier) + .removeCommunity(firstId); + expect((await storage.loadAll()).map((c) => c.id), [lastId]); + expect( + (await storage.loadForAccountSync()).where( + (c) => c.accountSyncRemoved, + ), + isEmpty, + ); + await container + .read(communityListProvider.notifier) + .removeCommunity(lastId); + expect(await storage.loadAll(), isEmpty); + final retained = await storage.loadForAccountSync(); + expect(retained.single.accountSyncRemoved, isTrue); + expect(retained.single.nsec, isNull); + // Simulate process loss immediately after the atomic local commit. + container.dispose(); + sync.dispose(); + sync = _sync(account, storage, journal: journal); + container = _container(account, storage, sync); + await sync.synchronize(); + expect(backend.edits, [ + (subject: 'A', op: 'remove', url: 'wss://private.example'), + ]); + expect(await storage.loadForAccountSync(), isEmpty); + journal.broken = null; + sync.retry(); + await sync.synchronize(); + expect(backend.edits, hasLength(1)); + container.dispose(); + sync.dispose(); + account.dispose(); + }, + ); + } + + test( + 'offline restart retains explicit add and remove for A, never sign-out or B', + () async { + final backend = _Backend(); + var account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + var sync = _sync(account, storage)..setActive(false); + await storage.save( + await sync.prepareAddition(_community('old', 'wss://old.example')), + ); + sync.dispose(); + account.dispose(); + account = backend.client(); + backend.offline = true; + backend.restoreGate = Completer(); + final restoring = expectLater( + account.restore(), + throwsA(AccountFailure.unavailable), + ); + await backend.restoreStarted.future; + sync = _sync(account, storage)..setActive(false); + var container = _container(account, storage, sync); + await container.read(communityListProvider.future); + await container + .read(authProvider.notifier) + .authenticateWithCommunity( + _community('new', 'wss://new.example'), + activate: false, + ); + await container.read(communityListProvider.future); + await container + .read(communityListProvider.notifier) + .removeCommunity('old'); + expect( + (await storage.loadAll()).single.accountSyncOwner, + endsWith('\nA'), + ); + expect(await sync.pendingRemovals('A'), {'wss://old.example'}); + backend.restoreGate!.complete(); + await restoring; + backend.restoreGate = null; + container.dispose(); + sync.dispose(); + account.dispose(); + account = backend.client(); + backend.offline = false; + sync = _sync(account, storage); + await sync.synchronize(); + expect(backend.edits.toSet(), { + (subject: 'A', op: 'remove', url: 'wss://old.example'), + (subject: 'A', op: 'add', url: 'wss://new.example'), + }); + await account.clearLocalSession(); + container = _container(account, storage, sync); + await container + .read(authProvider.notifier) + .authenticateWithCommunity( + _community('signed-out', 'wss://unclaimed.example'), + activate: false, + ); + expect((await storage.loadAll()).last.accountSyncOwner, isNull); + backend.subject = 'B'; + await _signIn(account); + await sync.synchronize(); + expect(backend.edits.where((e) => e.subject == 'B'), isEmpty); + container.dispose(); + sync.dispose(); + account.dispose(); + }, + ); + + testWidgets( + 'interrupted old removal offers explicit local completion and converges', + (tester) async { + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final journal = FakeSecureStorage(); + var sync = _sync(account, storage, journal: journal)..setActive(false); + await storage.save( + await sync.prepareAddition( + _community('interrupted', 'https://private.example'), + ), + ); + await sync.remove('wss://private.example'); + await account.clearLocalSession(); + backend.subject = 'B'; + await _signIn(account); + final b = _community( + 'B', + ).copyWith(nsec: nostr.Keys('2'.padLeft(64, '0')).nsec); + await storage.save(await sync.prepareAddition(b)); + await account.clearLocalSession(); + backend.subject = 'A'; + await _signIn(account); + // Old preview prefix: journal committed but local deletion did not happen. + sync.dispose(); + sync = _sync(account, storage, journal: journal); + await sync.synchronize(); + expect(backend.edits, isEmpty); + await tester.pumpWidget( + WidgetHelpers.testable( + enableAccountCommunitySync: true, + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + knownCommunitySyncProvider.overrideWithValue(sync), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue((_) async {}), + communityPushLeaseRevocationEnqueuerProvider.overrideWithValue( + (_) async => false, + ), + ], + child: const AccountCommunitySyncStatus(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap( + find.text('Finish removing private.example from this device'), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Remove').last); + await tester.pumpAndSettle(); + await sync.synchronize(); + expect((await storage.loadAll()).single.id, 'B'); + expect((await storage.loadAll()).single.nsec, b.nsec); + expect(await sync.pendingRemovals('A'), isEmpty); + expect( + backend.edits.every( + (e) => + e.subject == 'A' && + e.op == 'remove' && + e.url == 'wss://private.example', + ), + isTrue, + ); + expect(backend.edits, isNotEmpty); + await tester.pumpWidget(const SizedBox.shrink()); + sync.dispose(); + account.dispose(); + }, + ); + + testWidgets('pending status drops A immediately while B refresh is delayed', ( + tester, + ) async { + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + Completer? gate; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async { + await gate?.future; + return []; + }, + )..setActive(false); + addTearDown(() { + sync.dispose(); + account.dispose(); + }); + await sync.remove('wss://a-private.example'); + await tester.pumpWidget( + WidgetHelpers.testable( + enableAccountCommunitySync: true, + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + knownCommunitySyncProvider.overrideWithValue(sync), + ], + child: const AccountCommunitySyncStatus(), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('a-private.example'), findsOneWidget); + await account.clearLocalSession(); + backend.subject = 'B'; + await _signIn(account); + await sync.remove('wss://b-private.example'); + gate = Completer(); + await tester.pump(); + await tester.pump(); + expect(find.textContaining('a-private.example'), findsNothing); + gate.complete(); + gate = null; + await tester.pumpAndSettle(); + expect(find.textContaining('b-private.example'), findsOneWidget); + }); + + testWidgets( + 'denied removal recovery opens browser and same-account exchange resumes it', + (tester) async { + if (!HostedEnvironment.enabled) return; + PendingDeepLinkNotifier.debugUriStreamOverride = + const Stream.empty(); + addTearDown(() => PendingDeepLinkNotifier.debugUriStreamOverride = null); + final backend = _Backend(); + final account = backend.client(); + await _signIn(account); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final sync = _sync(account, storage); + final browser = DiscoveryBrowser(); + final store = AccountIdentityStore(subject: 'A'); + final keys = nostr.Keys('1'.padLeft(64, '0')); + await store.create(keys.nsec); + await store.confirmBackup( + BackupReceipt( + backend: BuilderlabAccountClient.origin.toString(), + subject: 'A', + pubkey: keys.public, + backupId: 'backup', + ), + ); + final flow = HostedFlow( + account: account, + browser: browser, + store: store, + identity: HostedIdentityService(account: account, store: store), + openWeb: (_) async => true, + enterCommunity: (_, _, _, _) async {}, + ); + await flow.initialize(); + await flow.start( + const AddCommunityDeepLink( + name: 'Joined', + relayUrl: 'wss://joined.communities.buzz.xyz', + ), + ); + expect(flow.stage, HostedFlowStage.complete); + backend.edits.clear(); + backend.denied = true; + await sync.remove('wss://denied.example'); + await sync.synchronize(); + expect(sync.failure, AccountFailure.denied); + await tester.pumpWidget( + ProviderScope( + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + knownCommunitySyncProvider.overrideWithValue(sync), + hostedFlowProvider.overrideWithValue(flow), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: const HostedAppGate( + authenticated: false, + child: OnboardingAppEntry(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('Retry account sync'), findsOneWidget); + expect( + find.ancestor( + of: find.byType(AccountCommunitySyncStatus), + matching: find.byType(Material), + ), + findsWidgets, + ); + await tester.tap(find.text('Sign in again')); + await tester.pump(); + await tester.pump(); + expect(browser.startedIntent, isNotNull); + backend.denied = false; + browser.callbacks.add( + BrowserAuthCode('fresh', 'a' * 43, browser.startedIntent!), + ); + await tester.pumpAndSettle(); + await sync.synchronize(); + expect(await sync.pendingRemovals('A'), isEmpty); + expect(backend.edits, [ + (subject: 'A', op: 'remove', url: 'wss://denied.example'), + ]); + await tester.pumpWidget(const SizedBox.shrink()); + flow.dispose(); + await browser.dispose(); + sync.dispose(); + account.dispose(); + }, + ); +} diff --git a/mobile/test/features/onboarding/hosted_communities_test.dart b/mobile/test/features/onboarding/hosted_communities_test.dart index af1c46b471..ab9506ef8e 100644 --- a/mobile/test/features/onboarding/hosted_communities_test.dart +++ b/mobile/test/features/onboarding/hosted_communities_test.dart @@ -253,7 +253,10 @@ void main() { await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); expect(f.flow.stage, HostedFlowStage.signIn); - expect(f.browser.startedIntent, {'type': 'account'}); + expect(f.browser.startedIntent, { + 'type': 'account', + 'discover_only': 'true', + }); expect(find.byType(HostedConnectPage), findsNothing); expect( find.bySemanticsLabel('Cancel sign-in').hitTestable(), diff --git a/mobile/test/features/onboarding/hosted_journeys_test.dart b/mobile/test/features/onboarding/hosted_journeys_test.dart index bb7c0b98a2..5374036751 100644 --- a/mobile/test/features/onboarding/hosted_journeys_test.dart +++ b/mobile/test/features/onboarding/hosted_journeys_test.dart @@ -314,6 +314,9 @@ void main() { findsNothing, ); await f.tap(tester, 'Find my communities'); + // Discovery no longer repairs hosted identity state until selection. + expect((await f.store.read())!.backup, isNull); + await f.tap(tester, 'one'); } } else { await f.tap(tester, 'Try again'); diff --git a/mobile/test/features/onboarding/known_communities_provider_test.dart b/mobile/test/features/onboarding/known_communities_provider_test.dart new file mode 100644 index 0000000000..7bec40e370 --- /dev/null +++ b/mobile/test/features/onboarding/known_communities_provider_test.dart @@ -0,0 +1,133 @@ +import 'package:buzz/shared/hosted/known_community_sync_provider.dart'; +import 'dart:async'; + +import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/hosted/hosted_relay_auth.dart'; +import 'package:buzz/shared/hosted/known_communities_provider.dart'; +import 'package:buzz/shared/hosted/known_community_sync.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; + +import '../../shared/community/community_storage_test.dart' + show FakeSecureStorage; + +class _Account extends BuilderlabAccountClient { + final subject = ValueNotifier('first'); + final firstResponse = Completer>(); + final requested = []; + int restores = 0; + + @override + ValueListenable get subjectChanges => subject; + @override + BuilderlabAccount? get account => subject.value == null + ? null + : BuilderlabAccount( + subject: subject.value!, + expiresAt: DateTime.now().add(const Duration(hours: 1)), + ); + @override + Future restore() async { + restores++; + return account; + } + + @override + Future> post( + String path, + Map body, { + String? expectedSubject, + }) async { + requested.add(path); + if (subject.value == 'first') return firstResponse.future; + return { + 'communities': [ + {'community_url': 'wss://second.communities.buzz.xyz'}, + ], + }; + } +} + +void main() { + test( + 'discovery honors build boundary and discards old account results', + () async { + final account = _Account(); + final container = ProviderContainer( + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + knownCommunitySyncProvider.overrideWithValue(null), + ], + ); + addTearDown(() { + container.dispose(); + account.subject.dispose(); + account.dispose(); + }); + container.listen(knownCommunitiesProvider, (_, _) {}); + if (!HostedEnvironment.enabled) { + expect(await container.read(knownCommunitiesProvider.future), isEmpty); + expect(account.restores, 0); + expect(account.requested, isEmpty); + return; + } + await container.pump(); + expect(account.requested, ['/v1/buzz/known-communities/list']); + account.subject.value = 'second'; + await container.pump(); + final current = await container.read(knownCommunitiesProvider.future); + expect(current.single.relayUrl, 'wss://second.communities.buzz.xyz'); + account.firstResponse.complete({ + 'communities': [ + {'community_url': 'wss://first.communities.buzz.xyz'}, + ], + }); + await container.pump(); + expect(container.read(knownCommunitiesProvider).value, current); + account.subject.value = null; + await container.pump(); + expect(await container.read(knownCommunitiesProvider.future), isEmpty); + }, + ); + + test('sync changes keep the shown list; account changes clear it', () async { + if (!HostedEnvironment.enabled) return; + final account = _Account()..subject.value = 'second'; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => [], + )..setActive(false); + final container = ProviderContainer( + overrides: [ + builderlabAccountProvider.overrideWithValue(account), + knownCommunitySyncProvider.overrideWithValue(sync), + ], + ); + addTearDown(() { + container.dispose(); + sync.dispose(); + account.subject.dispose(); + account.dispose(); + }); + container.listen(knownCommunitiesProvider, (_, _) {}); + final shown = await container.read(knownCommunitiesProvider.future); + expect(shown.single.relayUrl, 'wss://second.communities.buzz.xyz'); + // A sync change refetches behind the current list. + sync.retry(); + final refreshing = container.read(knownCommunitiesProvider); + expect(refreshing.isRefreshing, isTrue); + expect(refreshing.value, shown); + await container.pump(); + expect(account.requested, hasLength(2)); + // The adopted session is reused, so listing never re-verifies it. + expect(account.restores, 0); + // A different account never sees the previous account's list. + account.subject.value = 'first'; + final reloading = container.read(knownCommunitiesProvider); + expect(reloading.isReloading, isTrue); + expect(reloading.unwrapPrevious().hasValue, isFalse); + }); +} diff --git a/mobile/test/features/onboarding/known_community_sync_integration_test.dart b/mobile/test/features/onboarding/known_community_sync_integration_test.dart new file mode 100644 index 0000000000..6de3502185 --- /dev/null +++ b/mobile/test/features/onboarding/known_community_sync_integration_test.dart @@ -0,0 +1,531 @@ +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('owner'); + final calls = []; + Object? failure; + List urls = ['wss://paired.example']; + final targets = []; + @override + ValueListenable get subjectChanges => changes; + @override + BuilderlabAccount get account => BuilderlabAccount( + subject: 'owner', + expiresAt: DateTime.now().add(const Duration(hours: 1)), + ); + @override + Future restore() async => account; + @override + Future> post( + String path, + Map 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 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'] : [], + ); + 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(); + final finished = Completer(); + 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']); + }, + ); +} diff --git a/mobile/test/features/onboarding/known_community_sync_test.dart b/mobile/test/features/onboarding/known_community_sync_test.dart new file mode 100644 index 0000000000..4c7b83a36f --- /dev/null +++ b/mobile/test/features/onboarding/known_community_sync_test.dart @@ -0,0 +1,307 @@ +import 'dart:async'; + +import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/hosted/hosted_environment.dart'; +import 'package:buzz/shared/hosted/builderlab_account.dart'; +import 'package:buzz/shared/hosted/hosted_communities.dart'; +import 'package:buzz/shared/hosted/known_community_address.dart'; +import 'package:buzz/shared/hosted/known_community_sync.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../shared/community/community_storage_test.dart' + show FakeSecureStorage; + +class _Account extends BuilderlabAccountClient { + final subject = ValueNotifier('owner'); + final calls = <({String subject, String path, String? relay})>[]; + Object? failure; + Future Function()? pause; + List rows = []; + + @override + ValueListenable get subjectChanges => subject; + @override + BuilderlabAccount? get account => subject.value == null + ? null + : BuilderlabAccount( + subject: subject.value!, + expiresAt: DateTime.now().add(const Duration(hours: 1)), + ); + @override + Future restore() async => account; + @override + Future> post( + String path, + Map body, { + String? expectedSubject, + }) async { + if (account?.subject != expectedSubject) { + throw AccountFailure.differentAccount; + } + calls.add(( + subject: expectedSubject!, + path: path, + relay: body['community_url'] as String?, + )); + await pause?.call(); + if (failure case final error?) throw error; + return path.endsWith('/list') ? {'communities': rows} : {}; + } +} + +Community _claimed( + String url, { + String owner = 'owner', + String revision = 'first', +}) => Community( + id: url, + name: url, + relayUrl: url, + addedAt: DateTime(2026), + accountSyncOwner: '${HostedEnvironment.origin.origin}\n$owner', + accountSyncRevision: revision, +); + +void main() { + test( + 'retained and legacy destinations are not claimed by the next account', + () async { + final account = _Account(); + final local = [ + _claimed('wss://private-a.example'), + _claimed( + 'wss://legacy.example', + ).copyWith(accountSyncOwner: null, accountSyncRevision: null), + ]; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => local, + ); + addTearDown(sync.dispose); + await sync.synchronize(); + account.subject.value = null; + await sync.synchronize(); + account.subject.value = 'another'; + await sync.synchronize(); + expect(account.calls.map((c) => (c.subject, c.relay)), [ + ('owner', 'wss://private-a.example'), + ]); + local.add( + await sync.prepareAddition(_claimed('wss://explicit-b.example')), + ); + await sync.synchronize(); + expect(account.calls.last.subject, 'another'); + expect(account.calls.last.relay, 'wss://explicit-b.example'); + expect(account.calls, hasLength(2)); + }, + ); + + test('reconciles owned secure additions, then records removals', () async { + final account = _Account(); + var local = [ + 'https://team.example:8443/', + 'wss://one.communities.buzz.xyz', + 'ws://insecure.example', + ]; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => local.map(_claimed).toList(), + ); + addTearDown(sync.dispose); + await sync.synchronize(); + expect(account.calls.map((c) => c.relay), [ + 'wss://team.example:8443', + 'wss://one.communities.buzz.xyz', + ]); + expect(account.calls.every((c) => c.path.endsWith('/add')), isTrue); + await sync.synchronize(); + expect(account.calls, hasLength(2)); + await sync.remove('wss://team.example:8443'); + // Failed/cancelled local removal cannot delete the account entry. + await sync.synchronize(); + expect(account.calls, hasLength(2)); + local = ['wss://one.communities.buzz.xyz']; + await sync.synchronize(); + expect(account.calls.last.path, endsWith('/remove')); + expect(account.calls.last.relay, 'wss://team.example:8443'); + expect(await sync.pendingRemovals('owner'), isEmpty); + }); + + test( + 'offline removal survives restart and retries without another user action', + () async { + final account = _Account(); + final storage = FakeSecureStorage(); + var local = ['wss://team.example']; + var sync = KnownCommunitySync( + account: account, + storage: storage, + localCommunities: () async => local.map(_claimed).toList(), + ); + await sync.synchronize(); + account.failure = AccountFailure.unavailable; + await sync.remove(local.single); + local = []; + await sync.synchronize(); + expect(await sync.pendingRemovals('owner'), {'wss://team.example'}); + sync.dispose(); + account.failure = null; + sync = KnownCommunitySync( + account: account, + storage: storage, + localCommunities: () async => local.map(_claimed).toList(), + ); + addTearDown(sync.dispose); + await sync.synchronize(); + expect(account.calls.last.path, endsWith('/remove')); + expect(await sync.pendingRemovals('owner'), isEmpty); + }, + ); + + test( + 'a removal queued during an add wins over the late add response', + () async { + final account = _Account(); + final started = Completer(); + final release = Completer(); + account.pause = () async { + if (!started.isCompleted) started.complete(); + await release.future; + }; + var local = ['wss://team.example']; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => local.map(_claimed).toList(), + ); + addTearDown(sync.dispose); + final running = sync.synchronize(); + await started.future; + await sync.remove(local.single); + local = []; + sync.trigger(); + release.complete(); + await running; + expect(account.calls.map((c) => c.path.split('/').last), [ + 'add', + 'remove', + ]); + expect(await sync.pendingRemovals('owner'), isEmpty); + }, + ); + + test('old account work never drains using a new account session', () async { + final account = _Account(); + final storage = FakeSecureStorage(); + final started = Completer(); + final release = Completer(); + final sync = KnownCommunitySync( + account: account, + storage: storage, + localCommunities: () async => [], + ); + addTearDown(sync.dispose); + await sync.remove('wss://old.example'); + account.pause = () async { + if (!started.isCompleted) started.complete(); + await release.future; + }; + final running = sync.synchronize(); + await started.future; + account.subject.value = 'another'; + release.complete(); + await running; + expect(account.calls.map((c) => c.subject), ['owner']); + expect(await sync.pendingRemovals('owner'), {'wss://old.example'}); + account.subject.value = 'owner'; + await sync.synchronize(); + expect(account.calls.map((c) => c.subject), ['owner', 'owner']); + expect(await sync.pendingRemovals('owner'), isEmpty); + }); + + test( + 'refused API parks edits until sign-in instead of retrying indefinitely', + () async { + final account = _Account()..failure = AccountFailure.rejected; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => [_claimed('wss://team.example')], + ); + addTearDown(sync.dispose); + await sync.synchronize(); + await sync.synchronize(); + expect(account.calls, hasLength(1)); + account.failure = null; + account.subject.value = null; + await sync.synchronize(); + account.subject.value = 'owner'; + await sync.synchronize(); + expect(account.calls, hasLength(2)); + }, + ); + + test( + 'transient retries pause in background and resume without user action', + () { + fakeAsync((clock) { + final account = _Account()..failure = AccountFailure.unavailable; + final sync = KnownCommunitySync( + account: account, + storage: FakeSecureStorage(), + localCommunities: () async => [_claimed('wss://team.example')], + ); + sync.trigger(); + clock.flushMicrotasks(); + expect(account.calls, hasLength(1)); + clock.elapse(const Duration(seconds: 2)); + expect(account.calls, hasLength(2)); + sync.setActive(false); + clock.elapse(const Duration(minutes: 1)); + expect(account.calls, hasLength(2)); + account.failure = null; + sync.setActive(true); + clock.flushMicrotasks(); + expect(account.calls, hasLength(3)); + clock.elapse(const Duration(minutes: 1)); + expect(account.calls, hasLength(3)); + sync.dispose(); + }); + }, + ); + + test( + 'account discovery preserves supported external addresses and ports', + () async { + final account = _Account() + ..rows = [ + {'community_url': 'wss://team.example:8443/'}, + {'community_url': 'wss://team.example:9443'}, + {'community_url': 'wss://one.communities.buzz.xyz:8443'}, + {'community_url': 'wss://one.communities.buzz.xyz:443'}, + {'community_url': 'wss://one.communities.buzz.xyz/'}, + {'community_url': 'ws://insecure.example'}, + {'community_url': 'wss://user:pass@team.example'}, + {'community_url': 'wss://team.example/path'}, + ]; + final all = await loadKnownAccountCommunities(account); + expect(all.map((c) => c.relayUrl), [ + 'wss://team.example:8443', + 'wss://team.example:9443', + if (!HostedEnvironment.requiresAuth('one.communities.buzz.xyz')) + 'wss://one.communities.buzz.xyz:8443', + 'wss://one.communities.buzz.xyz', + ]); + expect(all.take(2).map((c) => c.name), [ + 'team.example:8443', + 'team.example:9443', + ]); + expect(knownCommunityAddress('wss://team.example:65536'), isNull); + expect(knownCommunityAddress('wss://team.example:0'), isNull); + }, + ); +} diff --git a/mobile/test/features/search/search_channels_journey_test.dart b/mobile/test/features/search/search_channels_journey_test.dart index ca75cbecc0..fe76e07c9a 100644 --- a/mobile/test/features/search/search_channels_journey_test.dart +++ b/mobile/test/features/search/search_channels_journey_test.dart @@ -935,6 +935,7 @@ class _RenamingSession extends _HeldSession { void Function(NostrEvent) onEvent, { void Function(String message)? onClosed, required void Function(RelaySubscriptionStatus status) onStatusChanged, + bool resumeSince = true, }) async { onStatusChanged(RelaySubscriptionStatus.ready); return () {}; diff --git a/mobile/test/helpers/hosted_communities_fixture.dart b/mobile/test/helpers/hosted_communities_fixture.dart index 159d0e8731..64d6300128 100644 --- a/mobile/test/helpers/hosted_communities_fixture.dart +++ b/mobile/test/helpers/hosted_communities_fixture.dart @@ -113,10 +113,11 @@ class HostedCommunitiesFixture { Future initialize({ bool backup = true, bool widget = false, + bool withIdentity = true, FlutterSecureStorage? accountStorage, bool coldAccount = false, }) async { - bound = keys.public; + bound = withIdentity ? keys.public : null; final expiry = DateTime.now() .toUtc() .add(const Duration(hours: 1)) @@ -146,7 +147,16 @@ class HostedCommunitiesFixture { if (path.endsWith('/current')) { return http.Response( jsonEncode({ - 'identity': {'pubkey_hex': bound}, + 'identity': bound == null ? null : {'pubkey_hex': bound}, + }), + 200, + ); + } + if (path.endsWith('/nsec-backups/status')) { + return http.Response( + jsonEncode({ + 'backup_nostr_pubkeys': [], + 'current_nostr_pubkey': bound, }), 200, ); @@ -185,8 +195,8 @@ class HostedCommunitiesFixture { ); } } - await store.create(keys.nsec); - if (backup) { + if (withIdentity) await store.create(keys.nsec); + if (backup && withIdentity) { await store.confirmBackup( BackupReceipt( backend: BuilderlabAccountClient.origin.toString(), diff --git a/mobile/test/helpers/widget_helpers.dart b/mobile/test/helpers/widget_helpers.dart index 1f15c54417..ea683a0551 100644 --- a/mobile/test/helpers/widget_helpers.dart +++ b/mobile/test/helpers/widget_helpers.dart @@ -1,3 +1,4 @@ +import 'package:buzz/shared/hosted/known_community_sync_provider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -9,9 +10,14 @@ class WidgetHelpers { required Widget child, List overrides = const [], bool disableAnimations = false, + bool enableAccountCommunitySync = false, }) { return ProviderScope( - overrides: overrides, + overrides: [ + if (!enableAccountCommunitySync) + knownCommunitySyncProvider.overrideWithValue(null), + ...overrides, + ], child: MaterialApp( theme: AppTheme.light(), home: Builder( diff --git a/mobile/test/shared/auth/auth_provider_test.dart b/mobile/test/shared/auth/auth_provider_test.dart index 018ff8f8e7..2ce7ac25cc 100644 --- a/mobile/test/shared/auth/auth_provider_test.dart +++ b/mobile/test/shared/auth/auth_provider_test.dart @@ -1,5 +1,7 @@ import 'dart:async'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; + import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -13,6 +15,8 @@ import 'package:buzz/shared/push/push_bridge.dart'; import '../community/community_storage_test.dart'; void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); test('waits for transition teardown before replacing credentials', () async { final storage = CommunityStorage(secure: FakeSecureStorage()); final active = Community.create( diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index ffe5ae441e..77b20c270d 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -1,4 +1,6 @@ import 'dart:async'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'dart:convert'; import 'dart:io'; @@ -21,6 +23,8 @@ import 'package:nostr/nostr.dart' as nostr; import 'community_storage_test.dart'; void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUp(() => FlutterSecureStorage.setMockInitialValues({})); late FakeSecureStorage fakeSecure; late CommunityStorage communityStorage; late ProviderContainer container; diff --git a/mobile/test/shared/hosted/builderlab_account_test.dart b/mobile/test/shared/hosted/builderlab_account_test.dart index c5d356a731..fa7049d7d5 100644 --- a/mobile/test/shared/hosted/builderlab_account_test.dart +++ b/mobile/test/shared/hosted/builderlab_account_test.dart @@ -1,3 +1,5 @@ +import 'package:buzz/shared/hosted/known_community_sync.dart'; +import '../community/community_storage_test.dart' show FakeSecureStorage; import 'dart:async'; import 'hosted_http_fixture.dart'; @@ -20,6 +22,70 @@ void main() { final verifier = List.filled(43, 'a').join(); setUp(() => FlutterSecureStorage.setMockInitialValues({})); + test( + 'same-subject setup completion resumes a parked account removal', + () async { + var needsSetup = true; + var removals = 0; + final client = BuilderlabAccountClient( + storage: FakeSecureStorage(), + httpClient: MockClient((request) async { + if (request.url.path.endsWith('/exchange')) { + return http.Response( + jsonEncode({ + 'session_credential': 'same-credential', + 'expires_at': expiry, + }), + 200, + ); + } + if (request.url.path.endsWith('/me')) { + return http.Response( + jsonEncode({ + 'subject': 'same-owner', + 'expires_at': expiry, + 'account_status': needsSetup + ? 'ACCOUNT_STATUS_NEEDS_DETAILS' + : 'ACCOUNT_STATUS_ACTIVE', + }), + 200, + ); + } + removals++; + return http.Response('{}', needsSetup ? 403 : 200); + }), + ); + await client.exchange(code: 'first', verifier: verifier); + final sync = KnownCommunitySync( + account: client, + storage: FakeSecureStorage(), + localCommunities: () async => [], + ); + addTearDown(() { + sync.dispose(); + client.dispose(); + }); + await sync.remove('wss://team.example'); + await sync.synchronize(); + expect(sync.failure, AccountFailure.accountSetupRequired); + expect(removals, 1); + await client.restore(); + await sync.synchronize(); + expect( + removals, + 1, + reason: 'ordinary restore must not bypass the parked session', + ); + needsSetup = false; + await client.exchange(code: 'setup-completed', verifier: verifier); + await sync.synchronize(); + expect(client.account!.subject, 'same-owner'); + expect(removals, 2); + expect(await sync.pendingRemovals('same-owner'), isEmpty); + expect(sync.failure, isNull); + }, + ); + test( 'real client exchanges PKCE code, verifies, persists and restores session', () async { diff --git a/mobile/test/shared/push/push_root_isolation_test.dart b/mobile/test/shared/push/push_root_isolation_test.dart index cb2e393358..4943812ecc 100644 --- a/mobile/test/shared/push/push_root_isolation_test.dart +++ b/mobile/test/shared/push/push_root_isolation_test.dart @@ -11,6 +11,7 @@ import 'package:buzz/features/settings/settings_page.dart'; import 'package:buzz/shared/push/push_setup_recovery.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../community/community_storage_test.dart' show FakeSecureStorage; import 'package:buzz/features/age_gate/age_signal_provider.dart'; import 'package:buzz/features/home/home_page.dart'; @@ -34,6 +35,7 @@ import 'package:shared_preferences/shared_preferences.dart'; void main() { final nativeChannels = []; setUp(() { + FlutterSecureStorage.setMockInitialValues({}); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(SystemChannels.platform_views, (