Files
buzz/mobile/test/features/onboarding/hosted_journeys_test.dart
Tom Brow b58ee08404 fix(mobile): request hosted relay assertions only when NIP-FI is required (#9225)
Port the desktop NIP-FI requirement rule to mobile: hosted relay connections request an account assertion only when the relay's NIP-11 document requires NIP-FI, so communities that have not enabled it keep connecting with BUZZ_HOSTED_RELAY_AUTH on.

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 18:57:05 -08:00

2075 lines
79 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters

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

import '../../helpers/controllable_pairing_socket.dart';
import 'package:buzz/shared/widgets/buzz_toast.dart';
import 'package:buzz/features/onboarding/hosted_reconnect_banner.dart';
import 'package:buzz/shared/hosted/hosted_community_creation.dart';
import 'package:buzz/shared/community/community_grid_option.dart';
import 'package:buzz/shared/hosted/account_identity_store.dart';
import 'package:buzz/shared/hosted/hosted_flow.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/features/pairing/pairing_provider.dart';
import 'package:buzz/shared/deeplink/pending_deep_link_provider.dart';
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'package:nostr/nostr.dart' as nostr;
import 'package:buzz/features/profile/profile_setup_page.dart';
import 'package:buzz/features/profile/profile_setup_avatar_editor.dart';
import 'package:buzz/features/profile/profile_avatar_draft.dart';
import 'package:buzz/shared/emoji/emoji_avatar.dart';
import 'package:buzz/shared/widgets/playing_avatar_image.dart';
import 'package:buzz/features/pairing/pairing_page.dart';
import 'package:buzz/hosted_app_gate.dart';
import 'package:buzz/onboarding_app_entry.dart';
import 'package:buzz/shared/auth/auth.dart';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:buzz/shared/hosted/hosted_relay_auth.dart';
import 'package:buzz/shared/relay/relay_session.dart';
import 'package:buzz/shared/relay/relay_provider.dart';
import 'package:buzz/shared/relay/media_image.dart';
import 'package:buzz/shared/utils/string_utils.dart';
import 'package:buzz/shared/widgets/mobile_tab_footer_backdrop.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import '../../helpers/hosted_journey_fixture.dart';
void main() {
// Bottom banners over Home must stay above its floating tab bar, which the
// fixture's stand-in home does not draw.
void expectAboveTabBar(WidgetTester tester, String label) {
final screen = tester.getSize(find.byType(HostedAppGate)).height;
expect(
tester.getRect(find.text(label)).bottom,
lessThanOrEqualTo(screen - mobileTabBarHeight - mobileTabBarBottomGap),
);
}
void journey(
String name,
Future<void> Function(WidgetTester, HostedJourneyFixture) run, {
bool requiresAuthDomain = false,
bool requiresBuilderlab = true,
}) {
testWidgets(
name,
(tester) async {
final fixture = HostedJourneyFixture();
// Keep asynchronous storage/HTTP owners in one real zone across tests;
// their serialized tails otherwise outlive the widget fake clock. The
// fixture pumps bounded frames with event-loop yields, not pumpAndSettle.
await tester.runAsync(
() => http.runWithClient(() async {
try {
await run(tester, fixture);
} finally {
await fixture.dispose(tester);
}
}, fixture.client),
);
},
skip:
(requiresBuilderlab && HostedEnvironment.authDomains.isEmpty) ||
(requiresAuthDomain &&
!HostedEnvironment.requiresAuth('one.communities.buzz.xyz')),
);
}
for (final selfHosted in [false, true]) {
journey(
'finishing ${selfHosted ? "self-hosted" : "hosted"} Add connects only the chosen destination',
(tester, f) async {
await f.initialize();
f.offerProfile = false;
f.rows.addAll([f.row('one'), f.row('two')]);
await f.mount(tester, openEntry: false);
await f.flow.signInAccount();
await f.settle(tester);
expect(find.text('Select a community'), findsOneWidget);
await tester.tap(find.byKey(const Key('community-switcher-add')));
await f.settle(tester);
expect(find.text('Add a community'), findsOneWidget);
expect(f.probes, isEmpty);
f.secondRelayFailures = 1;
if (selfHosted) {
await f.tap(tester, 'Enter a community link');
await tester.enterText(
find.byKey(const Key('community-link-input')).hitTestable(),
'my-community.example',
);
await f.tap(tester, 'Continue');
await f.tap(tester, 'Saved identity');
} else {
await f.tap(tester, 'Find my communities');
await tester.tap(find.byType(CommunityGridOption).first);
await f.settle(tester);
}
final newRelay = selfHosted
? 'wss://my-community.example'
: 'wss://one.communities.buzz.xyz';
final saved = await f.storage.loadAll();
expect(saved.map((c) => c.relayUrl), [newRelay]);
expect(await f.storage.loadActiveId(), saved.single.id);
expect(f.probes.map((c) => c.relayUrl), [newRelay]);
expect(f.secondRelayFailures, 1);
expect(find.byType(OnboardingAppEntry), findsNothing);
expect(find.text('Community home').hitTestable(), findsOneWidget);
},
);
}
journey('welcome cancels browser sign-in and can retry', (tester, f) async {
await f.initialize(localIdentity: false, signedIn: false);
f.bound = null;
f.offerProfile = false;
await f.mount(tester, addingCommunity: false);
expect(find.text('Use an existing identity'), findsNothing);
expect(find.text('or sign in with email').hitTestable(), findsOneWidget);
Future<void> cancelled() async {
for (var i = 0; i < 100 && f.flow.stage != HostedFlowStage.idle; i++) {
await Future<void>.delayed(Duration.zero);
await tester.pump();
}
expect(f.flow.stage, HostedFlowStage.idle);
await f.settle(tester);
expect(find.text('or sign in with email').hitTestable(), findsOneWidget);
}
final abandonedBrowser = Completer<void>();
f.beforeBrowserReturn = () => abandonedBrowser.future;
await f.tap(tester, 'or sign in with email');
expect(find.text('Cancel sign-in').hitTestable(), findsOneWidget);
await f.tap(tester, 'Cancel sign-in');
abandonedBrowser.complete();
await cancelled();
expect(f.flow.account.account, isNull);
f.beforeBrowserReturn = () async {
throw PlatformException(code: 'cancelled');
};
await f.tap(tester, 'or sign in with email');
await cancelled();
f.beforeBrowserReturn = null;
await f.tap(tester, 'or sign in with email');
await f.settle(tester);
expect(find.text('Create my Buzz identity'), findsNothing);
expect((await f.store.read())!.backup, isNotNull);
});
for (final entry in [
'sign-in',
'import',
'import community link',
'community link',
'create community',
]) {
final importing = entry.startsWith('import');
journey('new account $entry keeps its identity on retry', (
tester,
f,
) async {
await f.initialize(localIdentity: false);
f.bound = null;
f.offerProfile = false;
if (entry == 'import') f.rows.addAll([f.row('one'), f.row('two')]);
await f.mount(tester, addingCommunity: false);
if (importing) {
// An upgraded signed-in account has never chosen import on welcome.
await f.tap(tester, 'Use an existing identity');
expect(
find.text('Import existing identity').hitTestable(),
findsOneWidget,
);
expect(await f.store.read(), isNull);
await tester.tap(find.byTooltip('Back').hitTestable());
await f.settle(tester);
expect(
find.text('Use an existing identity').hitTestable(),
findsOneWidget,
);
}
// iOS 16 stops before any identity generation, binding or admission.
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('buzz/hosted_hpke'),
(_) async => false,
);
try {
await f.flow.signInAccount();
expect(f.flow.problem, HostedFlowProblem.unsupportedPlatform);
expect(await f.store.read(), isNull);
expect(f.bound, isNull);
expect(f.probes, isEmpty);
} finally {
debugDefaultTargetPlatformOverride = null;
}
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('buzz/hosted_hpke'),
(call) async => call.method == 'isSupported'
? true
: {
'enc': Uint8List.fromList([4, ...List.filled(64, 2)]),
'ciphertext': Uint8List(48),
},
);
if (importing) {
// Keep the authenticated account; import is an in-app setup action.
await f.settle(tester);
await tester.tap(find.byTooltip('Back').hitTestable());
} else {
await f.flow.signOutAccount();
}
await f.settle(tester);
expect(await f.store.read(), isNull);
var failUpload = true;
f.beforeUploadReturn = () async {
if (failUpload) {
failUpload = false;
throw AccountFailure.unavailable;
}
};
if (entry == 'community link') {
await f.link(tester, 'one', invite: false);
} else if (entry == 'create community') {
await f.flow.start(HostedCreateCommunity('new-home'));
} else {
await f.tap(
tester,
importing ? 'Use an existing identity' : 'or sign in with email',
);
}
await f.settle(tester);
expect(find.text('Create my Buzz identity'), findsNothing);
if (importing) {
expect(
f.browserStarts,
0,
); // Authenticated import never launches Auth0.
// The authenticated import choice must survive process death.
await f.restart(tester);
await f.tap(tester, 'Community home');
expect(
find.text('Import existing identity').hitTestable(),
findsOneWidget,
);
expect(await f.store.read(), isNull);
// A new destination must not cancel the pending import choice.
if (entry == 'import community link') {
await f.link(tester, 'one');
expect(find.text('Create my Buzz identity'), findsNothing);
expect(await f.store.read(), isNull);
await f.link(tester, 'one', invite: false);
await f.restart(tester);
await f.tap(tester, 'Start login again');
}
expect(find.text('Create my Buzz identity'), findsNothing);
expect(await f.store.read(), isNull);
await f.tap(tester, 'Import existing identity');
await tester.enterText(
find.byType(TextField).hitTestable(),
f.keys.nsec,
);
await f.tap(tester, 'Preview identity');
final started = Completer<void>();
final release = Completer<void>();
f.beforeStatusReturn = () async {
if (!started.isCompleted) started.complete();
await release.future;
};
await f.tap(tester, 'Import this identity');
await started.future.timeout(const Duration(seconds: 5));
// Dismiss while the real import is awaiting its external status response.
Navigator.of(
tester.element(find.byType(TextField).hitTestable()),
).pop();
await f.settle(tester);
release.complete();
f.beforeStatusReturn = null;
await f.settle(tester);
expect(f.bound, f.keys.public);
}
final saved = await f.store.read();
expect(saved, isNotNull);
expect(f.bound, saved!.pubkey);
expect(saved.backup, isNull);
expect(f.flow.problem, HostedFlowProblem.retry);
if (importing) {
expect(
(await f.flow.browser.retainedIntent())!['import_identity'],
isNull,
);
await f.restart(tester);
if (entry == 'import community link') {
await f.tap(tester, 'Start login again');
} else {
await f.tap(tester, 'Community home');
expect(
find.text('Import existing identity').hitTestable(),
findsNothing,
);
await f.tap(tester, 'Find my communities');
}
} else {
await f.tap(tester, 'Try again');
}
expect((await f.store.read())!.pubkey, saved.pubkey);
expect((await f.store.read())!.backup, isNotNull);
if (entry == 'import') {
// An older app may have retained the flag after saving this identity.
await f.flow.browser.retainIntent({
'type': 'account',
'import_identity': 'true',
});
await f.restart(tester);
await f.tap(tester, 'Community home');
expect(
find.text('Import existing identity').hitTestable(),
findsNothing,
);
await f.tap(tester, 'Find my communities');
expect(find.text('one').hitTestable(), findsOneWidget);
expect((await f.store.read())!.pubkey, saved.pubkey);
} else if (entry == 'import community link') {
expect(
(await f.storage.loadAll()).single.relayUrl,
'wss://one.communities.buzz.xyz',
);
}
});
}
journey(
'web binding keeps an explicit identity choice without backup support',
(tester, f) async {
await f.initialize(localIdentity: false);
f.bound = null;
await f.mount(tester);
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('buzz/hosted_hpke'),
(_) async => false,
);
final nativeChannels = <MethodChannel>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform_views,
(call) async {
if (call.method == 'create') {
final id = (call.arguments as Map)['id'];
final channel = MethodChannel('buzz/ios_navigation_bar/$id');
nativeChannels.add(channel);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
(_) async => null,
);
}
return null;
},
);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/url_launcher'),
(_) async => true,
);
try {
f.container
.read(pendingDeepLinkProvider.notifier)
.open(
Uri(
scheme: 'buzz',
host: 'nostr-bind',
queryParameters: {
'challenge_id': '12345678-1234-1234-1234-123456789012',
'nonce': 'a' * 43,
'verification_code': '123456',
'audience': 'buzz:nostr-identity',
'action': 'bind_nostr_identity',
'protocol': 'buzz-nostr-identity',
'version': '1',
'origin': HostedEnvironment.origin.toString(),
'expires_at': '2099-01-01T00:00:00Z',
'return': 'browser_fragment_v1',
'callback_url': HostedEnvironment.origin
.resolve('/buzz')
.toString(),
},
),
);
await f.settle(tester);
expect(
find.text('Create my Buzz identity').hitTestable(),
findsOneWidget,
);
expect(
find.text('Import existing identity').hitTestable(),
findsOneWidget,
);
expect(await f.store.read(), isNull);
expect(f.bound, isNull);
expect(f.sent('/verify'), isEmpty);
await f.tap(tester, 'Create my Buzz identity');
expect(f.flow.problem, HostedFlowProblem.unsupportedPlatform);
expect(await f.store.read(), isNull);
expect(f.bound, isNull);
// Once the OS supports sealing, creation still requires an explicit tap.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('buzz/hosted_hpke'),
(_) async => true,
);
await f.flow.retry();
await f.settle(tester);
expect(await f.store.read(), isNull);
await f.tap(tester, 'Create my Buzz identity');
final saved = (await f.store.read())!;
expect(f.bound, saved.pubkey);
expect(
saved.backup,
isNull,
); // Web binding has never promised mobile backup.
expect(f.flow.stage, HostedFlowStage.browserReturned);
} finally {
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
debugDefaultTargetPlatformOverride = null;
for (final channel in nativeChannels) {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
null,
);
}
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform_views,
null,
);
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/url_launcher'),
null,
);
}
},
);
journey('linked account without backup imports its key without replacing it', (
tester,
f,
) async {
await f.initialize(localIdentity: false);
f.offerProfile = false;
await f.mount(tester);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.setupIdentity);
expect(f.probes, isEmpty);
expect(find.text('Create my Buzz identity'), findsNothing);
expect(find.text('Import existing identity'), findsOneWidget);
await f.tap(tester, 'Import existing identity');
await tester.enterText(
find.byType(TextField).hitTestable(),
f.secondKeys.nsec,
);
await f.tap(tester, 'Preview identity');
await f.tap(tester, 'Import this identity');
expect(
find.text(
'This key doesn’t match the identity linked to your Builderlab account.',
),
findsOneWidget,
);
expect(await f.store.read(), isNull);
expect(f.bound, f.keys.public);
await tester.enterText(find.byType(TextField).hitTestable(), f.keys.nsec);
await f.tap(tester, 'Preview identity');
await f.tap(tester, 'Import this identity');
expect((await f.store.read())!.pubkey, f.keys.public);
expect((await f.store.read())!.backup, isNotNull);
expect(f.requests.where((r) => r.url.path.endsWith('/recovery')), isEmpty);
});
journey('system Back leaves community link entry', (tester, f) async {
await f.initialize();
await f.mount(tester);
await f.tap(tester, 'Enter a community link');
expect(
tester
.widget<PairingPage>(find.byType(PairingPage))
.enteringCommunityLink,
isTrue,
);
await tester.binding.handlePopRoute();
await f.settle(tester);
expect(
tester
.widget<PairingPage>(find.byType(PairingPage))
.enteringCommunityLink,
isFalse,
);
expect(find.text('Enter a community link').hitTestable(), findsOneWidget);
});
journey('retiring profile setup removes both profile and avatar routes', (
tester,
f,
) async {
await f.initialize();
f.rows.add(f.row('one'));
await f.mount(tester);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(f.probes, isEmpty);
await tester.tap(find.byType(CommunityGridOption).first);
await f.settle(tester);
await tester.enterText(
find.byType(TextField).hitTestable(),
'Draft Person',
);
expect(find.byTooltip('Add profile photo'), findsNothing);
await f.tap(tester, 'Continue');
expect(find.text('Choose your avatar'), findsOneWidget);
expect(f.profileWrites, isEmpty);
await tester.tap(find.byTooltip('Add profile photo'));
await f.settle(tester);
expect(find.byType(ProfileSetupAvatarEditor), findsOneWidget);
await f.link(tester, 'two');
expect(
find.byType(ProfileSetupAvatarEditor, skipOffstage: false),
findsNothing,
);
expect(find.text('Choose your avatar', skipOffstage: false), findsNothing);
expect(f.profileWrites, isEmpty);
});
for (final skipAvatar in [false, true]) {
journey(
'fallback profile preserves drafts and recovers save failures (skip: $skipAvatar)',
(tester, f) async {
await f.initialize();
f.rows.add(f.row('one'));
await f.mount(tester);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(f.probes, isEmpty);
await tester.tap(find.byType(CommunityGridOption).first);
await f.settle(tester);
await tester.enterText(
find.byType(TextField).hitTestable(),
'Draft Person',
);
expect(find.byTooltip('Add profile photo'), findsNothing);
await f.tap(tester, 'Continue');
expect(find.text('Choose your avatar'), findsOneWidget);
expect(f.profileWrites, isEmpty);
await tester.tap(find.byTooltip('Add profile photo'));
await f.settle(tester);
final url = emojiAvatarDataUrl('🐝', 0xFFFFE75C);
Navigator.of(
tester.element(find.byType(ProfileSetupAvatarEditor)),
).pop(ProfileUrlAvatarDraft(url));
await f.settle(tester);
expect(
tester
.widget<PlayingAvatarImage>(find.byType(PlayingAvatarImage))
.imageUrl,
url,
);
await tester.tap(find.byTooltip('Back'));
await f.settle(tester);
expect(find.text('Choose a display name'), findsOneWidget);
expect(
tester
.widget<TextField>(find.byType(TextField).hitTestable())
.controller!
.text,
'Draft Person',
);
await f.tap(tester, 'Continue');
expect(find.byTooltip('Edit profile photo'), findsOneWidget);
f.profileSaveFailures = 1;
await f.tap(tester, 'Continue');
expect(f.profileWrites, isEmpty);
expect(find.text('Not now'), findsOneWidget);
expect(find.byTooltip('Edit profile photo'), findsOneWidget);
await f.tap(tester, skipAvatar ? 'Skip' : 'Continue');
expect(f.profileWrites, ['Draft Person']);
expect(f.profileAvatars, skipAvatar ? isEmpty : [url]);
},
);
}
journey(
'QR credentials preserve an existing hosted identity or enter an opt-out community',
(tester, f) async {
if (HostedEnvironment.requiresAuth('paired.communities.buzz.xyz')) {
await f.initialize();
final original = Community.create(
name: 'One',
relayUrl: 'https://one.communities.buzz.xyz',
pubkey: f.keys.public,
nsec: f.keys.nsec,
);
await f.storage.save(original);
await f.storage.saveActiveId(original.id);
late ControllablePairingSocket socket;
await f.mount(
tester,
pairingSocketFactory:
({
required wsUrl,
required ephemeralPrivkey,
required onMessage,
required onDisconnected,
}) {
return socket = ControllablePairingSocket(
ephemeralPrivkey: ephemeralPrivkey,
onMessage: onMessage,
onDisconnected: onDisconnected,
);
},
);
final transferred = nostr.Keys('2'.padLeft(64, '0'));
const sessionSecret =
'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
final notifier = f.container.read(pairingProvider.notifier);
await notifier.pair(
'nostrpair://${transferred.public}?secret=$sessionSecret&relay=wss%3A%2F%2Fpairing.buzz.xyz&v=1',
);
notifier.setProtectSensitiveActions(false);
notifier.confirmSas();
socket.sendSourceMessage(
sourceSecret: transferred.secret,
sessionSecretHex: sessionSecret,
message: {'type': 'sas-confirm'},
includeTranscriptHash: true,
);
await f.settle(tester);
socket.sendSourceMessage(
sourceSecret: transferred.secret,
sessionSecretHex: sessionSecret,
message: {
'type': 'payload',
'payload_type': 'credentials',
'payload': jsonEncode({
'relayUrl': 'https://paired.communities.buzz.xyz',
'nsec': transferred.nsec,
'pubkey': transferred.public,
}),
},
);
await f.settle(tester);
const message =
'This device uses a different identity. Your saved identity has been kept.';
expect(find.text(message).hitTestable(), findsOneWidget);
expect(find.text('Scan a QR code').hitTestable(), findsOneWidget);
final announcement = find.ancestor(
of: find.text(message),
matching: find.byWidgetPredicate(
(widget) =>
widget is Semantics && widget.properties.liveRegion == true,
),
);
expect(announcement, findsOneWidget);
final saved = (await f.storage.loadAll()).single;
expect(saved.pubkey, f.keys.public);
expect(saved.nsec, f.keys.nsec);
expect((await f.store.read())?.pubkey, f.keys.public);
await tester.tap(find.byTooltip('Back').hitTestable());
await f.settle(tester);
expect(find.text('Community home').hitTestable(), findsOneWidget);
return;
}
// Seed a previous account session: an opt-out build must not restore it.
await f.initialize(localIdentity: false);
f.requests.clear();
await f.mount(
tester,
pairingValidator: ({required relayUrl, required nsec}) async {},
);
if (HostedEnvironment.authDomains.isEmpty) {
expect(f.activeFlow, isNull);
expect(f.requests, isEmpty);
expect(find.text('Connect to Builderlab'), findsNothing);
expect(find.text('Continue with Builderlab'), findsNothing);
expect(find.text('Create a community'), findsNothing);
expect(find.text('Enter a community link'), findsOneWidget);
expect(find.text('Scan a QR code'), findsOneWidget);
expect(find.text('Use pairing code'), findsNothing);
await f.tap(tester, 'Enter a community link');
expect(
find.byKey(const Key('community-link-input')).hitTestable(),
findsOneWidget,
);
expect(f.activeFlow, isNull);
await tester.tap(find.byTooltip('Back').hitTestable());
await f.settle(tester);
expect(f.requests, isEmpty);
}
final notifier = f.container.read(pairingProvider.notifier);
await notifier.pair(
base64Url.encode(
utf8.encode(
jsonEncode({
'relayUrl': 'https://paired.communities.buzz.xyz',
'nsec': f.keys.nsec,
'pubkey': f.keys.public,
}),
),
),
);
await f.settle(tester);
final saved = (await f.storage.loadAll()).single;
expect(saved.nsec, f.keys.nsec);
expect(saved.pubkey, f.keys.public);
expect(f.sent('/exchange'), isEmpty);
expect(f.sent('/current'), isEmpty);
expect(f.sent('/nsec-backups/status'), isEmpty);
expect(find.text('Reconnect to Builderlab'), findsNothing);
},
requiresBuilderlab: false,
);
journey(
'a refused organization account changes to another without the hosted one',
(tester, f) async {
f.relayAuthEnabled = true;
f.organizationEnabled = true;
await f.initialize();
// Signed in to the organization as an account bound to another key.
f.organizationSubject = 'other-member';
f.organizationBound = f.secondKeys.public;
await f.signInOrganization();
final community = Community.create(
name: 'Block',
relayUrl: 'wss://${HostedJourneyFixture.organizationRelayHost}',
pubkey: f.keys.public,
nsec: f.keys.nsec,
);
await f.storage.save(community);
await f.storage.saveActiveId(community.id);
await f.mount(tester, openEntry: false);
final sessionSubscription = f.container.listen(
relaySessionProvider,
(_, _) {},
);
addTearDown(sessionSubscription.close);
await f.settle(tester);
const refused = 'Denied access to this community.';
expect(find.text(refused), findsOneWidget);
expectAboveTabBar(tester, 'Use a different account');
expect(f.sent('/identity/assertions'), isEmpty);
// Retry keeps the refused account and fails the same way.
await f.tap(tester, 'Retry');
expect(find.text(refused), findsOneWidget);
expect(f.organizationBrowserStarts, 0);
f.organizationSubject = 'journey-owner';
f.organizationBound = f.keys.public;
final hosted = f.container.read(builderlabAccountProvider);
final hostedCredential = await const FlutterSecureStorage().read(
key:
'buzz_hosted_session_'
'${hosted.accountOrigin.host.replaceAll('.', '_')}_v1',
);
expect(hostedCredential, isNotNull);
final connects = f.socketHeaders.length;
await f.tap(tester, 'Use a different account');
await f.settle(tester);
expect(f.organizationBrowserStarts, 1);
expect(
f.container.read(organizationAccountProvider)!.account!.subject,
'journey-owner',
);
expect(find.text(refused), findsNothing);
expect(find.text('Use a different account'), findsNothing);
// The real relay session reconnects with the new account's assertion.
expect(f.socketHeaders.length, greaterThan(connects));
expect(
f.socketHeaders.last['Nostr-Federated-Identity'],
'Bearer organization-assertion',
);
expect(
f.container.read(relaySessionProvider).status,
SessionStatus.connected,
);
// Only the organization session changed.
expect(
await const FlutterSecureStorage().read(
key:
'buzz_hosted_session_'
'${hosted.accountOrigin.host.replaceAll('.', '_')}_v1',
),
hostedCredential,
);
expect(
f.requests.where(
(r) =>
r.url.origin != HostedJourneyFixture.organizationOrigin.origin &&
r.url.path.endsWith('/identity/assertions'),
),
isEmpty,
);
expect((await f.storage.loadAll()).single.nsec, community.nsec);
},
requiresBuilderlab: false,
);
journey(
'a hosted community gets assertions only once its relay requires NIP-FI',
(tester, f) async {
f.relayAuthEnabled = true;
f.nipFiRequired = false;
await f.initialize();
final community = Community.create(
name: 'One',
relayUrl: 'wss://one.communities.buzz.xyz',
pubkey: f.keys.public,
nsec: f.keys.nsec,
);
await f.storage.save(community);
await f.storage.saveActiveId(community.id);
await f.mount(tester, openEntry: false);
final sessionSubscription = f.container.listen(
relaySessionProvider,
(_, _) {},
);
addTearDown(sessionSubscription.close);
final session = f.container.read(relaySessionProvider.notifier);
await f.settle(tester);
// The issuer refuses hosts without NIP-FI; the app never asks it.
expect(f.socketHeaders, isNotEmpty);
expect(f.socketHeaders, everyElement(isEmpty));
await session.queryRelay(const []);
expect(f.sent('/query'), hasLength(1));
expect(f.sent('/identity/assertions'), isEmpty);
expect(
find.textContaining('cannot reconnect to this community'),
findsNothing,
);
// Cached-only reads (saved profile cards, native media) go out without
// an assertion instead of waiting for one that will never come.
final auth = f.container.read(hostedRelayAuthProvider);
final config = f.container.read(relayConfigProvider);
expect(auth.cachedHeaders(config), isEmpty);
// Unreachable discovery fails transiently, never as a denial.
f.nipFiRequired = null;
await session.reconnect();
await f.settle(tester);
expect(f.container.read(hostedRelayAuthProvider).failure, isNull);
// Requests keep the last answer instead of failing with discovery.
await session.queryRelay(const []);
expect(f.sent('/query'), hasLength(2));
expect(f.sent('/identity/assertions'), isEmpty);
// Once the community requires NIP-FI, its next connection carries one.
f.nipFiRequired = true;
final discoveries = f.discoveries;
await session.reconnect();
await f.settle(tester);
expect(f.discoveries, greaterThan(discoveries));
expect(f.socketHeaders.last, {
'Nostr-Federated-Identity': 'Bearer synthetic-assertion',
});
expect(f.sent('/identity/assertions'), hasLength(1));
await session.queryRelay(const []);
expect(f.sent('/identity/assertions'), hasLength(1));
expect(auth.cachedHeaders(config), {
'Nostr-Federated-Identity': 'Bearer synthetic-assertion',
});
},
requiresAuthDomain: true,
);
journey(
'saved community signs in again without changing identity or onboarding',
(tester, f) async {
f.relayAuthEnabled = true;
await f.initialize(signedIn: false);
final community = Community.create(
name: 'One',
relayUrl: 'wss://one.communities.buzz.xyz',
pubkey: f.keys.public,
nsec: f.keys.nsec,
);
await f.storage.save(community);
await f.storage.saveActiveId(community.id);
await f.mount(tester, openEntry: false);
// The real signed-in app watches its session; the fixture's home is inert.
final sessionSubscription = f.container.listen(
relaySessionProvider,
(_, _) {},
);
addTearDown(sessionSubscription.close);
final session = f.container.read(relaySessionProvider.notifier);
await f.settle(tester);
if (!HostedEnvironment.requiresAuth(Uri.parse(community.relayUrl).host)) {
expect(find.text('Reconnect to Builderlab'), findsNothing);
expect(f.socketHeaders, isNotEmpty);
expect(f.socketHeaders, everyElement(isEmpty));
expect(f.sent('/assertions'), isEmpty);
expect(f.container.read(relayConfigProvider).nsec, community.nsec);
return;
}
expect(find.text('Reconnect to Builderlab'), findsOneWidget);
expect(f.socketHeaders, isEmpty);
final feedbackContext = tester.element(
find.byType(HostedReconnectBanner),
);
showBuzzToast(feedbackContext, 'Copied');
await f.settle(tester);
expect(find.text('Copied'), findsOneWidget);
expect(find.text('Reconnect to Builderlab'), findsNothing);
expect(find.text('Sign in'), findsNothing);
var retried = false;
showBuzzToast(
feedbackContext,
'Couldn’t save changes',
onRetry: () {
retried = true;
},
);
await f.settle(tester);
expect(find.text('Copied'), findsNothing);
expect(find.text('Reconnect to Builderlab'), findsNothing);
await f.tap(tester, 'Retry');
expect(retried, isTrue);
expect(find.text('Reconnect to Builderlab'), findsOneWidget);
final browser = Completer<void>();
f.beforeBrowserReturn = () => browser.future;
await f.tap(tester, 'Sign in');
await f.tap(tester, 'Cancel sign-in');
browser.complete();
await f.settle(tester);
expect(find.text('Reconnect to Builderlab'), findsOneWidget);
expect(f.socketHeaders, isEmpty);
f.beforeBrowserReturn = null;
await f.tap(tester, 'Sign in');
await f.settle(tester);
expect(f.socketHeaders, isNotEmpty);
expect(find.text('Reconnect to Builderlab'), findsNothing);
await session.queryRelay(const []);
expect(f.sent('/query'), hasLength(1));
final proofRequest = f.sent('/identity/assertions').single;
expect(
proofRequest.headers['X-BB-Session-Credential'],
'synthetic-session',
);
final proof =
jsonDecode(
utf8.decode(
base64Decode(
proofRequest.headers['Authorization']!.substring(6),
),
),
)
as Map;
expect(proof['pubkey'], f.keys.public);
expect(
proof['tags'],
contains(equals(['u', proofRequest.url.toString()])),
);
// Production media transport attaches only to its captured community,
// refuses redirects, and renews an expired assertion without browser UI.
final media = f.container.read(mediaHttpClientProvider);
for (final origin in [
'https://one.communities.buzz.xyz',
'https://outside.example',
]) {
await media.get(Uri.parse('$origin/auth-transport'));
final request = f.requests.last;
expect(
request.headers['Nostr-Federated-Identity'],
origin.contains('communities.buzz.xyz')
? 'Bearer synthetic-assertion'
: isNull,
);
if (origin.contains('communities.buzz.xyz')) {
expect(request.followRedirects, isFalse);
}
}
final logins = f.browserStarts;
final issued = f.sent('/identity/assertions').length;
f.assertionNow = f.assertionNow.add(const Duration(minutes: 6));
await session.queryRelay(const []);
expect(f.sent('/identity/assertions'), hasLength(issued + 1));
expect(f.browserStarts, logins);
f.expiredSession = true;
f.assertionNow = f.assertionNow.add(const Duration(minutes: 6));
await expectLater(
session.queryRelay(const []),
throwsA(AccountFailure.signedOut),
);
await f.settle(tester);
expect(find.text('Reconnect to Builderlab'), findsOneWidget);
final beforeWrongAccount = f.sent('/identity/assertions').length;
f.bound = f.secondKeys.public;
f.subject = 'wrong-owner';
await f.tap(tester, 'Sign in');
await f.settle(tester);
expect(
find.text(
'This account cannot reconnect to this community with its saved key.',
),
findsOneWidget,
);
expect(f.sent('/identity/assertions'), hasLength(beforeWrongAccount));
// An empty different account cannot claim the saved key through reconnect.
f.bound = null;
await f.tap(tester, 'Use a different account');
await f.settle(tester);
expect(
find.text(
'This account cannot reconnect to this community with its saved key.',
),
findsOneWidget,
);
expect(f.sent('/identity/assertions'), hasLength(beforeWrongAccount));
expect(f.bound, isNull);
expect(await f.store.read(), isNull);
expect((await f.storage.loadAll()).single.nsec, community.nsec);
f.subject = 'journey-owner';
f.bound = f.keys.public;
await f.tap(tester, 'Use a different account');
await f.settle(tester);
expect(
f.container.read(builderlabAccountProvider).account!.subject,
'journey-owner',
);
expect(find.text('Use a different account'), findsNothing);
expect((await f.storage.loadAll()).single.nsec, community.nsec);
// A legacy account can link the existing saved key on first issuance.
f.bound = null;
f.assertionNow = f.assertionNow.add(const Duration(minutes: 6));
await session.reconnect();
await f.settle(tester);
expect(f.bound, f.keys.public);
expect(
find.text(
'This account cannot reconnect to this community with its saved key.',
),
findsNothing,
);
expect((await f.storage.loadAll()).single.nsec, community.nsec);
expect(await f.storage.loadActiveId(), community.id);
expect((await f.store.read())!.pubkey, f.keys.public);
for (final path in [
'/status',
'/enrollment',
'/known-communities/list',
]) {
expect(
f.sent(path),
isEmpty,
reason: 'Reconnect must not run onboarding',
);
}
// The issuer can succeed while the relay refuses the upgrade. One
// renewal is allowed, then stop; a user retry can recover later.
f.refuseUpgrade = true;
final attempts = f.socketHeaders.length;
await session.reconnect();
await f.settle(tester);
expect(f.socketHeaders.length, attempts + 2);
expect(
f.container.read(relaySessionProvider).status,
SessionStatus.disconnected,
);
expect(find.text('Use a different account'), findsOneWidget);
f.refuseUpgrade = false;
await session.reconnect();
await f.settle(tester);
// A timed-out query cannot dispatch later when a slow issuer completes.
final stalled = Completer<void>();
f.beforeAssertionReturn = () => stalled.future;
f.assertionNow = f.assertionNow.add(const Duration(minutes: 6));
final queries = f.sent('/query').length;
await expectLater(
session.queryRelay(const [], timeout: const Duration(milliseconds: 20)),
throwsA(isA<TimeoutException>()),
);
stalled.complete();
await f.settle(tester);
expect(f.sent('/query'), hasLength(queries));
f.beforeAssertionReturn = null;
expect(f.container.read(relayConfigProvider).nsec, community.nsec);
},
requiresBuilderlab: false,
);
for (final savedIncomplete in [false, true]) {
journey(
'${savedIncomplete ? 'incomplete saved' : 'fresh'} account signs in, backs up, accepts invite and retries starters before home',
(tester, f) async {
await f.initialize(
localIdentity: false,
cloudChoice: true,
signedIn: savedIncomplete,
);
f.needsAccountSetup = savedIncomplete;
f.starterFailures = 2;
final browserReturn = Completer<void>();
f.beforeBrowserReturn = () async {
await browserReturn.future;
f.needsAccountSetup = false;
};
final enrollmentReached = Completer<void>();
final enrollmentReturn = Completer<void>();
f.beforeEnrollmentReturn = () {
enrollmentReached.complete();
return enrollmentReturn.future;
};
await f.mount(tester);
await f.link(tester, 'one');
try {
expect(
find.text('Enter a community link').hitTestable(),
findsOneWidget,
);
expect(find.text('Scan a QR code').hitTestable(), findsOneWidget);
expect(f.browserUrls.single.path, '/auth/native');
expect(f.browserUrls.single.origin, HostedEnvironment.origin.origin);
expect(
await f.flow.browser.retainedIntent(),
containsPair('code', 'invite-one'),
);
expect(f.sent('/exchange'), savedIncomplete ? hasLength(1) : isEmpty);
expect(f.sent('/api/invites/claim'), isEmpty);
expect(find.text('Start login again'), findsNothing);
expect(find.text('Complete sign-in in your browser.'), findsNothing);
} finally {
browserReturn.complete();
}
await enrollmentReached.future.timeout(const Duration(seconds: 5));
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
try {
expect(find.text('Create my Buzz identity'), findsNothing);
expect(find.text('Import existing identity'), findsNothing);
expect(find.byTooltip('Back').hitTestable(), findsNothing);
// External teardown still fences pending enrollment.
await f.flow.leave();
await tester.pump();
} finally {
enrollmentReturn.complete();
}
await f.settle(tester);
expect(f.sent('/nsec-backups'), isEmpty);
final retainedKey = (await f.store.read())!.pubkey;
f.beforeEnrollmentReturn = null;
// A dispatched upload can succeed after cancellation. Its receipt must
// still be durable; resuming must not replay an acknowledged backup.
f.beforeUploadReturn = () => f.flow.leave();
await f.link(tester, 'one');
expect((await f.store.read())!.backup, isNotNull);
f.beforeUploadReturn = null;
// Production legal documents exceed the ordinary 64 KiB account limit.
f.policyResponses.add(
http.Response(
jsonEncode({
'policy': {
'version': 'one.communities.buzz.xyz',
'age_attestation_required': true,
'terms_markdown': 'Be kind to this community.',
'privacy_markdown': 'Public privacy notice. ' * 5000,
},
}),
200,
),
);
await f.link(tester, 'one');
expect((await f.store.read())!.pubkey, retainedKey);
expect(f.browserStarts, 1);
final generated = (await f.store.read())!;
expect(generated.pubkey, f.bound);
expect(generated.backup, isNotNull);
expect(f.sent('/verify'), hasLength(1));
expect(f.sent('/nsec-backups'), hasLength(1));
final accept = find.widgetWithText(FilledButton, 'Accept and join');
expect(tester.widget<FilledButton>(accept).onPressed, isNull);
expect(f.sent('/claim'), isEmpty);
expect(await f.storage.loadAll(), isEmpty);
await f.tap(tester, 'Terms of service');
expect(find.text('Be kind to this community.'), findsOneWidget);
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(find.text('Try again').hitTestable(), findsOneWidget);
final pending = (await f.storage.loadAll()).single;
expect(pending.starterSetupIncomplete, isTrue);
expect(pending.pubkey, generated.pubkey);
expect(f.sent('/claim'), hasLength(1));
expect(
jsonDecode(f.sent('/claim').single.body)['policy_receipt'],
'synthetic-policy-receipt',
);
expect(
jsonDecode(f.sent('/accept-policy').single.body)['age_confirmed'],
isTrue,
);
// Reopen the saved invite after its claim was consumed. Starter recovery
// must retain the durable marker and must not claim it again.
await f.link(tester, 'one');
expect(
(await f.storage.loadAll()).single.starterSetupIncomplete,
isTrue,
);
expect(find.text('Try again').hitTestable(), findsOneWidget);
await f.tap(tester, 'Try again');
expect(
find.byType(ProfileSetupPage, skipOffstage: false),
findsOneWidget,
);
expect(
find.ancestor(
of: find.byType(TextField).hitTestable(),
matching: find.byType(BottomSheet),
),
findsNothing,
);
expect(f.sent('/claim'), hasLength(1));
expect(f.recoveryScopes, hasLength(3));
expect(
f.recoveryScopes.every((scope) => scope.nsec == pending.nsec),
isTrue,
);
await tester.enterText(
find.byType(TextField).hitTestable(),
'Journey Person',
);
await f.tap(tester, 'Continue');
expect(f.profileWrites, isEmpty);
await f.tap(tester, 'Skip');
expect(f.profileWrites, ['Journey Person']);
final saved = (await f.storage.loadAll()).single;
expect(saved.id, pending.id);
expect(saved.starterSetupIncomplete, isFalse);
expect(await f.storage.loadActiveId(), saved.id);
expect(find.byType(OnboardingAppEntry), findsNothing);
expect(find.text('Community home').hitTestable(), findsOneWidget);
},
requiresAuthDomain: true,
);
}
for (final boundAccount in [false, true]) {
journey(
'switch accounts preserves both keys and requires unbound reuse consent ($boundAccount)',
(tester, f) async {
await f.initialize();
final original = f.store;
await f.mount(tester);
await f.container.read(builderlabAccountProvider).clearLocalSession();
f.subject = 'new-owner';
f.bound = boundAccount ? f.secondKeys.public : null;
if (boundAccount) f.cloudKeys.add(f.secondKeys);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(
f.flow.stage,
boundAccount ? HostedFlowStage.idle : HostedFlowStage.chooseIdentity,
);
expect(f.probes, isEmpty);
if (!boundAccount) {
expect(find.text('Saved identity'), findsOneWidget);
expect(f.sent('/verify'), isEmpty);
expect(f.sent('/nsec-backups'), isEmpty);
expect(await f.store.read(), isNull);
await f.tap(tester, fullNpub(f.keys.public)!);
}
final saved = (await f.store.read())!;
expect(
saved.pubkey,
boundAccount ? f.secondKeys.public : f.keys.public,
);
expect(saved.backup!.subject, 'new-owner');
expect((await original.read())!.pubkey, f.keys.public);
expect((await original.read())!.backup!.subject, 'journey-owner');
},
);
}
journey('new unbound account can create a new identity beside saved keys', (
tester,
f,
) async {
await f.initialize();
final original = f.store;
await f.mount(tester);
await f.container.read(builderlabAccountProvider).clearLocalSession();
f.subject = 'new-owner';
f.bound = null;
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(find.text('Saved identity'), findsOneWidget);
expect(await f.store.read(), isNull);
await f.tap(tester, 'Create a new identity');
final saved = (await f.store.read())!;
expect(saved.pubkey, isNot(f.keys.public));
expect(saved.backup!.subject, 'new-owner');
expect(f.bound, saved.pubkey);
expect((await original.read())!.pubkey, f.keys.public);
expect((await original.read())!.backup!.subject, 'journey-owner');
});
Future<AccountIdentityStore> rejectedSavedChoice(
WidgetTester tester,
HostedJourneyFixture f,
) async {
await f.initialize();
final original = f.store;
await f.mount(tester);
await f.container.read(builderlabAccountProvider).clearLocalSession();
f.subject = 'new-owner';
f.bound = null;
f.rejectedBindings.add(f.keys.public);
await f.flow.signInAccount();
await f.settle(tester);
await f.tap(tester, fullNpub(f.keys.public)!);
return original;
}
journey(
'rejected saved choice survives restart, then choosing again can create and bind',
(tester, f) async {
final original = await rejectedSavedChoice(tester, f);
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(find.text('Choose a different identity'), findsOneWidget);
expect((await f.store.read())!.pubkey, f.keys.public);
await f.restart(tester);
await f.flow.signInAccount();
await f.settle(tester);
// The saved choice skips selection and retries the same rejection.
expect(f.flow.problem, HostedFlowProblem.requestRejected);
await f.tap(tester, 'Choose a different identity');
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(await f.store.read(), isNull);
expect(find.text('Saved identity'), findsOneWidget);
await f.tap(tester, 'Create a new identity');
final saved = (await f.store.read())!;
expect(saved.pubkey, isNot(f.keys.public));
expect(f.bound, saved.pubkey);
expect(saved.backup!.subject, 'new-owner');
expect((await original.read())!.pubkey, f.keys.public);
expect((await original.read())!.backup!.subject, 'journey-owner');
},
);
journey('a release outlived by leaving cannot reopen the flow', (
tester,
f,
) async {
final original = await rejectedSavedChoice(tester, f);
final gate = Completer<void>();
f.beforeStatusReturn = () => gate.future;
final statuses = f.sent('/status').length;
await tester.tap(find.text('Choose a different identity').hitTestable());
while (f.sent('/status').length == statuses) {
await tester.pump(const Duration(milliseconds: 10));
}
await f.flow.leave();
f.beforeStatusReturn = null;
gate.complete();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.idle);
expect((await f.store.read())!.pubkey, f.keys.public);
expect((await original.read())!.backup, isNotNull);
});
journey('an account switch during release keeps both accounts intact', (
tester,
f,
) async {
final original = await rejectedSavedChoice(tester, f);
final chosen = f.store;
// Account requests are serialized, so the switch lands right after the
// recheck, before the slot is released.
f.beforeStatusReturn = () async {
f.beforeStatusReturn = null;
f.subject = 'third-owner';
unawaited(
f.container.read(builderlabAccountProvider).clearLocalSession(),
);
};
await f.tap(tester, 'Choose a different identity');
expect(f.flow.stage, HostedFlowStage.blocked);
expect(f.flow.canChooseDifferentIdentity, isFalse);
expect((await chosen.read())!.pubkey, f.keys.public);
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(f.flow.canCreateIdentity, isTrue);
expect(await f.store.read(), isNull);
expect((await chosen.read())!.pubkey, f.keys.public);
expect((await original.read())!.pubkey, f.keys.public);
expect((await original.read())!.backup, isNotNull);
});
journey('a failed release keeps the choice across restart, then retries', (
tester,
f,
) async {
await rejectedSavedChoice(tester, f);
final slot =
'${AccountIdentityStore.storageKey}_subject_'
'${base64Url.encode(utf8.encode('new-owner'))}';
final keychain = _StickyKeychain(
Map.of(await const FlutterSecureStorage().readAll()),
)..sticky = slot;
FlutterSecureStorage.setMockInitialValues(keychain);
await f.tap(tester, 'Choose a different identity');
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isTrue);
expect((await f.store.read())!.pubkey, f.keys.public);
await f.tap(tester, 'Choose a different identity');
expect(f.flow.canChooseDifferentIdentity, isTrue);
expect((await f.store.read())!.pubkey, f.keys.public);
await f.restart(tester);
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isTrue);
keychain.sticky = null;
await f.tap(tester, 'Choose a different identity');
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(await f.store.read(), isNull);
expect(find.text('Saved identity'), findsOneWidget);
});
journey('a refused release keeps the choice, then retries', (
tester,
f,
) async {
await rejectedSavedChoice(tester, f);
// Without an inventory, the copy kept elsewhere cannot be confirmed.
final keychain = _StickyKeychain(
Map.of(await const FlutterSecureStorage().readAll()),
)..locked = true;
FlutterSecureStorage.setMockInitialValues(keychain);
await f.tap(tester, 'Choose a different identity');
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isTrue);
expect((await f.store.read())!.pubkey, f.keys.public);
keychain.locked = false;
await f.tap(tester, 'Choose a different identity');
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(await f.store.read(), isNull);
});
journey('leaving from the picker ignores a late creation', (tester, f) async {
await f.initialize();
await f.mount(tester);
await f.container.read(builderlabAccountProvider).clearLocalSession();
f.subject = 'new-owner';
f.bound = null;
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.canCreateIdentity, isTrue);
final leaving = f.flow.leave();
await f.flow.createIdentity();
await leaving;
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.idle);
expect(await f.store.read(), isNull);
});
journey('a rejected paired key offers no other identity', (tester, f) async {
if (!HostedEnvironment.requiresAuth('paired.communities.buzz.xyz')) return;
await f.initialize(localIdentity: false, cloudChoice: true);
await f.mount(tester);
f.rejectedBindings.add(f.keys.public);
await f.flow.stagePairedCommunity(
Community.create(
name: 'Paired',
relayUrl: 'https://paired.communities.buzz.xyz',
pubkey: f.keys.public,
nsec: f.keys.nsec,
),
isCurrent: () => true,
);
await f.flow.retry();
await f.settle(tester);
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isFalse);
expect(find.text('Choose a different identity'), findsNothing);
});
for (final status in [503, 403]) {
journey('ambiguous binding failure ($status) offers no release', (
tester,
f,
) async {
f.bindStatus = status;
await rejectedSavedChoice(tester, f);
expect(f.flow.stage, HostedFlowStage.blocked);
expect(f.flow.canChooseDifferentIdentity, isFalse);
expect(find.text('Choose a different identity'), findsNothing);
expect((await f.store.read())!.pubkey, f.keys.public);
});
}
journey('challenge rejection and stale evidence offer no release', (
tester,
f,
) async {
f.challengeStatus = 409;
await rejectedSavedChoice(tester, f);
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isFalse);
f
..challengeStatus = null
..bindStatus = 409;
await f.flow.retry();
await f.settle(tester);
expect(f.flow.canChooseDifferentIdentity, isTrue);
f.challengeStatus = 409;
await f.flow.retry();
await f.settle(tester);
// The earlier attempt's rejection is not reused.
expect(f.flow.problem, HostedFlowProblem.requestRejected);
expect(f.flow.canChooseDifferentIdentity, isFalse);
expect((await f.store.read())!.pubkey, f.keys.public);
});
journey(
'choose second cloud identity, dismiss profile, and enter only the selected community',
(tester, f) async {
await f.initialize(localIdentity: false, cloudChoice: true);
f.cloudKeys.addAll([f.keys, f.secondKeys]);
f.rejectList = true;
f.secondRelayFailures = 1;
final legacy = Community.create(
name: 'Saved local',
relayUrl: 'wss://saved.example',
pubkey: f.keys.public,
nsec: f.keys.nsec,
);
await f.storage.save(legacy);
await f.storage.saveActiveId(legacy.id);
await f.mount(tester);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseIdentity);
expect(f.probes, isEmpty);
expect(find.text('Use Builderlab identity'), findsNWidgets(2));
await f.tap(tester, fullNpub(f.secondKeys.public)!);
expect((await f.store.read())!.pubkey, f.secondKeys.public);
expect(
find.text('We could not finish connecting. You can try again.'),
findsOneWidget,
);
expect(
find.text(
'No communities available to add. Scan a QR code or use an invite link.',
),
findsNothing,
);
f.rejectList = false;
await f.tap(tester, 'Try again');
expect(f.flow.stage, HostedFlowStage.idle);
expect(f.probes, isEmpty);
expect(find.text('Signed in to BuilderLab'), findsOneWidget);
expect(find.text('Scan a QR code'), findsOneWidget);
expect(find.text('Use pairing code'), findsNothing);
f.rows.addAll([f.row('one'), f.row('two')]);
// Account restoration may resume independently of the Add choices.
await f.flow.signInAccount();
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(f.probes, isEmpty);
await tester.tap(find.byType(CommunityGridOption).first);
await f.settle(tester);
// Continue explicitly admits the selected communities.
expect(find.byType(CheckboxListTile).hitTestable(), findsNothing);
expect(
find.byType(ProfileSetupPage, skipOffstage: false),
findsOneWidget,
);
final firstSaved = (await f.storage.loadAll()).firstWhere(
(c) => c.relayUrl == 'wss://one.communities.buzz.xyz',
);
Navigator.of(
tester.element(find.byType(ProfileSetupPage, skipOffstage: false)),
rootNavigator: true,
).pop();
await f.settle(tester);
expect(f.profileWrites, isEmpty);
expect(
(await f.storage.loadAll()).map((c) => c.id),
containsAll([legacy.id, firstSaved.id]),
);
final saved = await f.storage.loadAll();
expect(saved, hasLength(2));
expect(saved.singleWhere((c) => c.id == legacy.id).nsec, f.keys.nsec);
expect(
saved
.where((c) => c.id != legacy.id)
.every((c) => c.nsec == f.secondKeys.nsec),
isTrue,
);
expect(
saved
.singleWhere((c) => c.relayUrl == 'wss://one.communities.buzz.xyz')
.id,
firstSaved.id,
);
expect(await f.storage.loadActiveId(), firstSaved.id);
expect(
f.probes.where((c) => c.relayUrl == 'wss://one.communities.buzz.xyz'),
hasLength(1),
);
expect(
f.probes.where((c) => c.relayUrl == 'wss://two.communities.buzz.xyz'),
isEmpty,
);
expect(find.byType(OnboardingAppEntry), findsNothing);
},
);
for (final unreadableProfile in [false, true]) {
journey(
'new device recovers and preserves existing/unreadable profile ($unreadableProfile)',
(tester, f) async {
await f.initialize(localIdentity: false);
// Exercise both an already-bound recovery and recovery that must bind
// its confirmed backup, without requiring native sealing in either case.
if (unreadableProfile) {
f.bound = null;
f.cloudKeys.add(f.keys);
} else {
f.cloudKeys.addAll([f.secondKeys, f.keys]);
}
f.rows.addAll([f.row('one'), f.row('two')]);
f.offerProfile = false;
f.profileUnavailable = unreadableProfile;
await f.mount(tester);
// Account restoration may resume independently of the Add choices.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('buzz/hosted_hpke'),
(call) async {
expect(
call.method,
'isSupported',
reason: 'Recovery must not seal a new backup',
);
return false;
},
);
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
try {
await f.flow.signInAccount();
} finally {
debugDefaultTargetPlatformOverride = null;
}
await f.settle(tester);
expect(f.flow.stage, HostedFlowStage.chooseCommunities);
expect(f.probes, isEmpty);
await tester.tap(find.byType(CommunityGridOption).last);
await f.settle(tester);
// Only the tapped community is admitted.
expect(f.profileWrites, isEmpty);
expect(
find.byType(ProfileSetupPage, skipOffstage: false),
findsNothing,
);
final communities = await f.storage.loadAll();
expect(communities, hasLength(1));
expect(
communities.map((c) => c.relayUrl),
equals(['wss://two.communities.buzz.xyz']),
);
final saved = communities.singleWhere(
(c) => c.relayUrl == 'wss://two.communities.buzz.xyz',
);
expect(saved.nsec, f.keys.nsec);
expect(saved.pubkey, f.keys.public);
expect((await f.store.read())!.pubkey, f.keys.public);
expect(f.sent('/recovery'), hasLength(1));
expect(f.sent('/challenge'), hasLength(unreadableProfile ? 1 : 0));
expect(f.sent('/nsec-backups'), isEmpty);
expect(f.sent('/enrollment'), isEmpty);
expect(await f.storage.loadActiveId(), saved.id);
expect(find.byType(OnboardingAppEntry), findsNothing);
expect(f.probes.map((c) => c.relayUrl), [
'wss://two.communities.buzz.xyz',
]);
await f.tap(tester, 'Community home');
await f.tap(tester, 'Find my communities');
expect(find.byType(CommunityGridOption), findsNWidgets(2));
await tester.tap(find.byType(CommunityGridOption).first);
await f.settle(tester);
expect((await f.storage.loadAll()), hasLength(2));
expect(f.probes.map((c) => c.relayUrl), [
'wss://two.communities.buzz.xyz',
'wss://one.communities.buzz.xyz',
]);
},
);
}
journey(
'self-hosted link explicitly reuses saved account key and persists admission',
(tester, f) async {
await f.initialize();
f.requests.clear();
await f.mount(tester);
await f.tap(tester, 'Enter a community link');
await tester.enterText(
find.byKey(const Key('community-link-input')).hitTestable(),
'my-community.example',
);
await f.tap(tester, 'Continue');
// Choices loaded successfully; enumeration breaks before selection.
// The account-scoped key remains directly readable throughout admission.
f.identityStorage.failEnumeration = true;
await f.tap(tester, 'Saved identity');
final saved = (await f.storage.loadAll()).single;
expect(saved.relayUrl, 'wss://my-community.example');
expect(saved.nsec, f.keys.nsec);
expect(await f.storage.loadActiveId(), saved.id);
expect(f.probes, hasLength(1));
expect(f.sent('/claim'), isEmpty);
f.identityStorage.failEnumeration = false;
expect(
(await const FlutterSecureStorage().readAll()).keys.where(
(key) => key.startsWith('buzz_pending_self_hosted_'),
),
isEmpty,
);
// Reopening an interrupted self-hosted invite follows legacy recovery.
await f.storage.save(saved.copyWith(starterSetupIncomplete: true));
f.container.invalidate(communityListProvider);
f.container
.read(pendingDeepLinkProvider.notifier)
.open(
Uri(
scheme: 'buzz',
host: 'join',
queryParameters: {
'relay': saved.relayUrl,
'code': 'consumed-invite',
},
),
);
await f.settle(tester);
expect(f.recoveryScopes, hasLength(1));
expect(
(await f.storage.loadAll()).single.starterSetupIncomplete,
isFalse,
);
expect(f.sent('/claim'), isEmpty);
expect(find.byType(OnboardingAppEntry), findsNothing);
await f.container
.read(communityListProvider.notifier)
.removeCommunity(saved.id);
await AccountIdentityStore(
subject: 'other-owner',
).create(f.secondKeys.nsec);
await f.restart(tester);
await f.tap(tester, 'Community home');
await f.tap(tester, 'Enter a community link');
await tester.enterText(
find.byKey(const Key('community-link-input')).hitTestable(),
'my-community.example',
);
await f.tap(tester, 'Continue');
// A refused key must not pin the URL against an explicit allowed choice.
f.refusedSelfHostedPubkey = f.keys.public;
await f.tap(tester, shortPubkey(f.keys.public));
expect(await f.storage.loadAll(), isEmpty);
expect(find.textContaining('Could not join.'), findsOneWidget);
await f.tap(tester, shortPubkey(f.secondKeys.public));
expect((await f.storage.loadAll()).single.nsec, f.secondKeys.nsec);
expect(
(await AccountIdentityStore().forPairing(f.keys.public).read())!.pubkey,
f.keys.public,
);
if (HostedEnvironment.authDomains.isEmpty) {
expect(f.requests, isEmpty);
}
},
requiresBuilderlab: false,
);
journey(
'saved pending account retains invite across retry without reopening setup',
(tester, f) async {
await f.initialize();
// /me reports stored details as pending even when legacy screening
// standing still says MISSING + NOT_SCREENED.
f.screeningPending = true;
// If setup is incorrectly reopened, allow its callback to finish so the
// no-browser assertion fails instead of cycling until the test times out.
f.beforeBrowserReturn = () async => f.screeningPending = false;
await f.mount(tester);
await f.link(tester, 'one');
expect(f.browserStarts, 0);
expect(f.sent('/claim'), isEmpty);
expect(await f.storage.loadAll(), isEmpty);
expect(find.text('Accept and join').hitTestable(), findsOneWidget);
await f.restart(tester);
await f.tap(tester, 'Start login again');
expect(find.text('Accept and join').hitTestable(), findsOneWidget);
expect(f.browserStarts, 0);
f.screeningPending = false;
expect(
f.sent('/api/join-policy').last.url.host,
'one.communities.buzz.xyz',
);
Navigator.of(
tester.element(find.text('Accept and join')),
rootNavigator: true,
).pop();
await f.settle(tester);
await f.restart(tester);
expect(find.text('Start login again'), findsNothing);
expect(find.text('Community home').hitTestable(), findsOneWidget);
expect(f.sent('/accept-policy'), isEmpty);
expect(f.sent('/claim'), isEmpty);
expect(f.probes, isEmpty);
expect(await f.storage.loadAll(), isEmpty);
expect(await f.storage.loadActiveId(), isNull);
expect((await f.store.read())!.pubkey, f.keys.public);
// An open relay's successful AUTH must not convert a failed invitation
// into a completed claim for a non-member.
f.offerProfile = false;
f.inviteExpired = true;
f.missingList = true;
await f.link(tester, 'one');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(await f.storage.loadAll(), isEmpty);
expect(f.probes, isEmpty);
expect(
find.text('This invite has expired. Ask for a new invite link.'),
findsOneWidget,
);
f.missingList = false;
await f.link(tester, 'one');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(await f.storage.loadAll(), isEmpty);
expect(f.probes, isEmpty);
// The server admits this identity but its reply is lost. The retained
// intent resumes after restart even once the code has expired.
f.inviteExpired = false;
f.missingList = false;
f.loseClaimResponse = true;
await f.link(tester, 'one');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(await f.storage.loadAll(), isEmpty);
expect(f.rows, hasLength(1));
f.inviteExpired = true;
f.rejectList = true;
await f.restart(tester);
await f.tap(tester, 'Start login again');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(await f.storage.loadAll(), isEmpty);
expect(f.probes, isEmpty);
f.rejectList = false;
await f.tap(tester, 'Try again');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
final saved = (await f.storage.loadAll()).single;
expect(saved.relayUrl, 'wss://one.communities.buzz.xyz');
expect(saved.pubkey, f.keys.public);
expect(await f.storage.loadActiveId(), saved.id);
expect(find.text('Community home').hitTestable(), findsOneWidget);
},
requiresAuthDomain: true,
);
journey(
'create survives a lost response and restart, then joins the same owned community',
(tester, f) async {
await f.initialize();
f.loseCreateResponse = true;
await f.mount(tester);
// Creation is entered elsewhere; retain its restart/persistence journey.
await f.flow.start(HostedCreateCommunity('new-home'));
await f.settle(tester);
expect(find.text('Try again').hitTestable(), findsOneWidget);
expect(f.owned, hasLength(1));
expect(await f.storage.loadAll(), isEmpty);
await f.restart(tester);
await f.tap(tester, 'Start login again');
expect(
find.byType(ProfileSetupPage, skipOffstage: false),
findsOneWidget,
);
await tester.enterText(find.byType(TextField).hitTestable(), 'Creator');
await f.tap(tester, 'Continue');
await f.tap(tester, 'Skip');
final saved = (await f.storage.loadAll()).single;
expect(saved.relayUrl, 'wss://new-home.communities.buzz.xyz');
expect(saved.nsec, f.keys.nsec);
expect(await f.storage.loadActiveId(), saved.id);
expect(f.sent('/v1/buzz/communities'), hasLength(2));
expect(f.owned, hasLength(1));
expect(f.sent('/status'), isEmpty);
expect(f.browserStarts, 0);
expect(f.profileWrites, ['Creator']);
expect(find.text('Community home').hitTestable(), findsOneWidget);
},
);
for (final (sentinel, guidance, retryable) in [
(
'invite_restricted',
'This account, or the account that owns it, is restricted in this community. Contact a community administrator. If the restriction is temporary, try again after it ends.',
true,
),
(
'invite_owner_mismatch',
'This account does not match its recorded owner. Use the correct account or owner identity to join this community.',
false,
),
]) {
journey('$sentinel is rendered without discarding the hosted invite', (
tester,
f,
) async {
await f.initialize();
f.offerProfile = false;
f.claimError = sentinel;
// Even recorded membership must not turn a current explicit denial
// into successful admission through lost-response reconciliation.
f.rows.add(f.row('one'));
await f.mount(tester);
await f.link(tester, 'one');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(find.text(guidance), findsOneWidget);
expect(await f.storage.loadAll(), isEmpty);
expect(f.probes, isEmpty);
expect(f.sent('/claim'), hasLength(1));
expect(f.sent('/communities/joined'), isEmpty);
expect(
find.text('Try again').hitTestable(),
retryable ? findsOneWidget : findsNothing,
);
await f.settle(tester);
expect(f.sent('/claim'), hasLength(1));
expect((await f.flow.browser.retainedIntent())!['code'], 'invite-one');
f.claimError = null;
if (retryable) {
await f.tap(tester, 'Try again');
} else {
// Owner mismatch requires the correct identity, not an automatic
// retry. Explicitly abandon setup, then reopen the same link after
// the server-side owner conflict has been corrected.
await tester.tap(find.byTooltip('Back').hitTestable());
await f.settle(tester);
expect((await f.store.read())!.pubkey, f.keys.public);
await f.link(tester, 'one');
}
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
expect(f.sent('/claim'), hasLength(2));
for (final request in f.sent('/claim')) {
expect(jsonDecode(request.body)['code'], 'invite-one');
}
expect((await f.storage.loadAll()).single.pubkey, f.keys.public);
expect(find.text('Community home').hitTestable(), findsOneWidget);
}, requiresAuthDomain: true);
}
journey(
'second invitation replaces pending consent and only joins the newer community',
(tester, f) async {
await f.initialize();
f.offerProfile = false;
f.saveFailures = 1;
// The first dispatched attempt ends; retry owns the pending consent.
// A new incoming link must now invalidate that consent, not wait on it.
f.policyResponses.addAll([
http.Response('<html>Unavailable</html>', 502),
http.Response('', 503),
http.Response('{"error":"proxy_busy"}', 503),
http.Response('', 429),
]);
await f.mount(tester);
await f.link(tester, 'one');
while (f.policyResponses.isNotEmpty) {
expect(find.text('Try again').hitTestable(), findsOneWidget);
expect(await f.storage.loadAll(), isEmpty);
await f.tap(tester, 'Try again');
}
await f.tap(tester, 'Try again');
expect(find.text('Accept and join').hitTestable(), findsOneWidget);
await f.link(tester, 'two');
await tester.tap(find.byType(CheckboxListTile));
await f.settle(tester);
await f.tap(tester, 'Accept and join');
final saved = (await f.storage.loadAll()).single;
expect(saved.relayUrl, 'wss://two.communities.buzz.xyz');
expect(saved.starterSetupIncomplete, isFalse);
expect(f.sent('/claim'), hasLength(1));
expect(f.sent('/claim').single.url.host, 'two.communities.buzz.xyz');
expect(f.sent('/accept-policy'), hasLength(1));
expect(
f.sent('/accept-policy').single.url.host,
'two.communities.buzz.xyz',
);
// The remote add was accepted but its acknowledgement was lost. The
// saved community and pending intent survive; retry never reclaims it.
expect(find.text('Try again').hitTestable(), findsOneWidget);
expect(f.knownSaved, {'wss://two.communities.buzz.xyz'});
await f.restart(tester);
await f.tap(tester, 'Start login again');
expect((await f.storage.loadAll()).single.id, saved.id);
expect(f.sent('/claim'), hasLength(1));
expect(f.sent('/known-communities/add'), hasLength(2));
expect(find.byType(OnboardingAppEntry), findsNothing);
},
requiresAuthDomain: true,
);
}
/// A keychain whose [sticky] entry cannot be deleted.
class _StickyKeychain extends MapBase<String, String> {
_StickyKeychain(this._entries);
final Map<String, String> _entries;
String? sticky;
bool locked = false;
@override
String? operator [](Object? key) => _entries[key];
@override
void operator []=(String key, String value) => _entries[key] = value;
@override
void clear() => _entries.clear();
@override
Iterable<String> get keys =>
locked ? throw StateError('keychain is locked') : _entries.keys;
@override
String? remove(Object? key) {
if (key == sticky) throw StateError('keychain item is in use');
return _entries.remove(key);
}
}