fix(mobile): sign out from Settings in every build, keeping keys on the device (#9421)

Public and Nostr-only builds had no way to sign out. The only route was
Switch community → Edit, remove every community, then tap Back to get a
"Sign out of BuilderLab?" prompt. Removing a community that way also
deletes its key from the phone, even when the user never exported or
backed it up.

Settings now ends with **Sign out** in every build (internal builds
already had it). After confirming:

- Each community's key is first copied into this device's saved
identities, the same thing internal Sign out already did. Sign-in offers
them again, so signing out never destroys a key that may exist nowhere
else. If saving fails, nothing is removed.
- In a public build, the Builderlab session ends next, before anything
is removed. The Sign in landing that follows never shows the old
session, and nothing started there can be cancelled by it. If the
session or a pending browser sign-in can't be cleared, including a saved
session not yet restored after launch, Sign out stops with an error and
keeps every community. Ending the session never waits behind a pending
account request, such as a stalled session check at launch, and no such
request can restore the session once it finishes later. This path never
shows the hosted setup page over Settings. The removed communities'
push-lease tombstones still publish afterwards: the outbox authenticates
them with the push-stop credential the session leaves behind for 10
minutes, including a saved session that was never restored (an offline
launch), even when a first cleanup attempt failed partway.
- Every community is removed, the active one last, so removing the
others never switches to (and connects) another community on the way
out.
- A Sign out failure now shows its error in Settings. The row used
Settings' outer context, so the snackbar went to the page underneath.

Nothing else changes: the switcher, per-community Remove and the
onboarding landing's Back → "Sign out of BuilderLab?" path behave as
before. Internal Sign out keeps its behavior (one community, key kept,
the landing then ends the organization session). The only new UI is one
row at the bottom of Settings.

| Before | After |
| --- | --- |
| <img width="300" alt="before"
src="https://github.com/user-attachments/assets/f49f7869-3401-4e05-aa7b-debe7a7d425c">
| <img width="300" alt="after"
src="https://github.com/user-attachments/assets/99731c6a-035e-447b-987a-7fa0d8e767cc">
|

Demo (public build, simulator): Sign out → confirm → back at the Buzz
landing, signed out of Builderlab.


https://github.com/user-attachments/assets/da64082b-3b73-46d0-8578-771fca7dec22

### Validation

- Added tests: `settings_sign_out_test.dart`, a Settings journey with
two communities whose keys aren't backed up. Cancelling keeps
everything. Confirming removes both (active last) and both keys end up
in saved identities. The root swaps Settings for the real
`OnboardingAppEntry` as the app does. The authenticated root is wrapped
in the real `HostedAppGate`, and no route may be pushed while Sign out
runs. In a public build it fails three ways, each showing the error in
Settings and removing nothing: a saved session that isn't restored yet
can't be deleted, a restored one can't be deleted, and a pending browser
sign-in can't be cleared. Then, with revocations held pending, the
landing appears with the session already gone and no "Signed in as", and
releasing the revocations changes nothing. It runs in the default lane
and in the CI public-build lane (added to `_ci-clients.yml`). Confirmed
it fails when the key save is removed, when the session ends after the
landing appears, when sign-out goes through the flow's published stages,
when a failed clear is detected only by a missing in-memory session,
when a browser cleanup failure is swallowed, and when the error goes to
the page underneath.
- `organization_relay_auth_test.dart`: a push stop still gets an
assertion after signing out a saved session that was never restored,
including a failed cleanup followed by a successful retry (fails without
the fix).
- Sign-out never waits on a pending account request: the Settings
journey holds `/v1/auth/me` during the final sign-out and checks that
its later completion restores nothing (without the fix, Sign out stalls
and both communities stay). `builderlab_account_test.dart` covers a
session check already pending, one that starts while the session is
being deleted, an exchange queued before the sign-out, and an account
request during the removal that must not share the credential with the
notification extension again.
- Focused existing validation: `internal_build_entry_test.dart` with the
internal-build defines passes.
- Full `just mobile-test` (4,848 passed, 74 skipped) and `just
mobile-check` are clean.
- Automated app run at
([d36150c](d36150ccaf)):
fresh iPhone 17 Pro simulator, public-build Debug signed in to a
Builderlab community. Opened Settings from the community menu (Sign out
is the last row), confirmed Sign out, and landed on the Buzz landing
(Scan a QR code / sign in with email) with no community and no
Builderlab session, and no hosted setup page in between. The screens
match the demo above, which was recorded at an earlier head. Re-signing
in through Builderlab wasn't exercised in the simulator; the journey
test covers the saved identities that sign-in offers. Later commits
change only session-clearing internals, and the tests above cover them.

---------

Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Tom Brow <tomb@squareup.com>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-15 11:31:04 -08:00
committed by GitHub
parent 44c8206bea
commit 5b92e02e2a
12 changed files with 801 additions and 203 deletions

View File

@@ -162,6 +162,7 @@ jobs:
test/shared/hosted/relay_auth_isolation_test.dart
test/features/onboarding/hosted_app_gate_environment_test.dart
test/features/settings/builderlab_account_row_test.dart
test/features/settings/settings_sign_out_test.dart
test/features/onboarding/hosted_journeys_test.dart
test/features/onboarding/hosted_backup_consent_test.dart
test/features/onboarding/onboarding_sign_out_test.dart

View File

@@ -19,8 +19,7 @@ import '../../shared/auth/auth.dart';
import '../../shared/identity_transfer/nsec_export_sheet.dart';
import '../../shared/clipboard_utils.dart';
import '../../shared/hosted/hosted_environment.dart';
import '../../shared/hosted/organization_environment.dart';
import '../../shared/hosted/organization_sign_out.dart';
import '../../shared/hosted/sign_out.dart';
import '../../shared/push/push_relay_capability_provider.dart';
import '../../shared/push/push_bootstrap.dart';
import '../../shared/relay/relay.dart';
@@ -246,21 +245,23 @@ class SettingsPage extends HookConsumerWidget {
],
if (!wide && HostedEnvironment.enabled)
const _BuilderlabAccountSection(),
// An internal build's only way out of its organization, rarely
// needed, so it sits last.
if (OrganizationEnvironment.enabled)
AppListCard(
verticalPadding: Grid.twelve,
children: [
AppListRow(
// Rarely needed, so it sits last.
AppListCard(
verticalPadding: Grid.twelve,
children: [
// Below Settings' own messenger, so a failure shows
// here rather than on the page underneath.
Builder(
builder: (rowContext) => AppListRow(
key: const Key('settings-sign-out'),
icon: BuzzIcons.logOut,
title: 'Sign out',
titleColor: context.colors.error,
onTap: () => confirmOrganizationSignOut(context, ref),
onTap: () => confirmSignOut(rowContext, ref),
),
],
),
),
],
),
if (packageInfo.hasData)
_VersionFooter(
version: packageInfo.data!.version,

View File

@@ -116,6 +116,12 @@ class BuilderlabAccountClient {
// already pending can still reach their relays for a short while.
({String credential, DateTime until})? _signedOut;
final _queue = SerialQueue();
// Session storage changes, kept apart from [_queue] so signing out never
// waits behind a pending account request.
final _storageQueue = SerialQueue();
// Advances at each sign-out, so a request already in flight cannot adopt or
// save a session afterwards.
int _sessionEpoch = 0;
/// How long after sign-out [pushStopAssertion] can still issue.
static const pushStopWindow = Duration(minutes: 10);
@@ -143,7 +149,11 @@ class BuilderlabAccountClient {
_restoring ??= _restore().whenComplete(() => _restoring = null);
Future<BuilderlabAccount?>? _restoring;
Future<BuilderlabAccount?> _restore() => _serial(() async {
final record = await _readRecord();
// Read behind any sign-out still clearing, so this never adopts the
// session it is deleting.
final (epoch, record) = await _storageQueue.run(
() async => (_sessionEpoch, await _readRecord()),
);
if (record == null) {
// Retries a removal that failed after an earlier sign-out.
await _unshare();
@@ -151,13 +161,15 @@ class BuilderlabAccountClient {
}
try {
final verified = await _verify(record.credential);
// Signed out while the check was pending.
if (epoch != _sessionEpoch) return null;
if (verified.subject != record.subject) {
throw AccountFailure.invalidResponse;
}
return _adopt(record.credential, verified);
} on AccountFailure catch (failure) {
if (failure == AccountFailure.signedOut) {
await _clear();
await _clearSince(epoch);
return null;
}
rethrow;
@@ -172,51 +184,65 @@ class BuilderlabAccountClient {
required String code,
required String verifier,
bool Function()? isCurrent,
}) => _serial(() async {
if (code.isEmpty ||
!RegExp(r'^[A-Za-z0-9._~-]{43,128}$').hasMatch(verifier)) {
throw AccountFailure.invalidResponse;
}
final stored = await _readRecord();
final result = await _request(
'/v1/auth/login/exchange',
body: {'code': code, 'code_verifier': verifier},
);
final credential = result['session_credential'];
if (credential is! String ||
credential.isEmpty ||
credential.length > 512) {
throw AccountFailure.invalidResponse;
}
final verified = await _verify(credential);
if (DateTime.tryParse(
result['expires_at'] is String ? result['expires_at'] as String : '',
) !=
verified.expiresAt) {
throw AccountFailure.invalidResponse;
}
if (stored != null && stored.subject != verified.subject) {
throw AccountFailure.differentAccount;
}
if (_disposed || (isCurrent != null && !isCurrent())) {
throw AccountFailure.unavailable;
}
final record = jsonEncode({
'origin': accountOrigin.toString(),
'credential': credential,
'subject': verified.subject,
'expires_at': verified.expiresAt.toIso8601String(),
});
try {
await _storage.write(key: _storageKey, value: record);
if (await _storage.read(key: _storageKey) != record) {
throw AccountFailure.storage;
}) {
// Taken at the call, so an exchange queued before a sign-out can never
// sign back in after it.
final epoch = _sessionEpoch;
return _serial(() async {
if (epoch != _sessionEpoch) throw AccountFailure.unavailable;
if (code.isEmpty ||
!RegExp(r'^[A-Za-z0-9._~-]{43,128}$').hasMatch(verifier)) {
throw AccountFailure.invalidResponse;
}
} catch (_) {
throw AccountFailure.storage;
}
return _adopt(credential, verified);
});
final stored = await _readRecord();
final result = await _request(
'/v1/auth/login/exchange',
body: {'code': code, 'code_verifier': verifier},
);
final credential = result['session_credential'];
if (credential is! String ||
credential.isEmpty ||
credential.length > 512) {
throw AccountFailure.invalidResponse;
}
final verified = await _verify(credential);
if (DateTime.tryParse(
result['expires_at'] is String
? result['expires_at'] as String
: '',
) !=
verified.expiresAt) {
throw AccountFailure.invalidResponse;
}
if (stored != null && stored.subject != verified.subject) {
throw AccountFailure.differentAccount;
}
final record = jsonEncode({
'origin': accountOrigin.toString(),
'credential': credential,
'subject': verified.subject,
'expires_at': verified.expiresAt.toIso8601String(),
});
// Saved and adopted as one storage change, so a sign-out lands wholly
// before or after it.
return _storageQueue.run(() async {
if (_disposed ||
epoch != _sessionEpoch ||
(isCurrent != null && !isCurrent())) {
throw AccountFailure.unavailable;
}
try {
await _storage.write(key: _storageKey, value: record);
if (await _storage.read(key: _storageKey) != record) {
throw AccountFailure.storage;
}
} catch (_) {
throw AccountFailure.storage;
}
return _adopt(credential, verified);
});
});
}
/// An unreadable record is a storage failure, never an absent session: its
/// subject is unknown, so only an explicit [clearLocalSession] may drop it.
@@ -341,6 +367,7 @@ class BuilderlabAccountClient {
);
}
return _serial(() async {
final epoch = _sessionEpoch;
final credential = _credential;
if (credential == null) throw AccountFailure.signedOut;
_share();
@@ -366,7 +393,7 @@ class BuilderlabAccountClient {
try {
await _verify(credential);
} on AccountFailure catch (failure) {
if (failure == AccountFailure.signedOut) await _clear();
if (failure == AccountFailure.signedOut) await _clearSince(epoch);
rethrow;
}
throw AccountFailure.denied;
@@ -418,8 +445,31 @@ class BuilderlabAccountClient {
);
});
Future<void> clearLocalSession() => _serial(_clear);
/// Runs at once, without waiting for pending account requests; none of them
/// can adopt or save a session after it.
Future<void> clearLocalSession() {
if (_disposed) return Future.error(AccountFailure.unavailable);
_sessionEpoch++;
return _storageQueue.run(_clear);
}
/// Ends a session a request found rejected, unless a sign-out already did.
Future<void> _clearSince(int epoch) => _storageQueue.run(() async {
if (epoch == _sessionEpoch) await _clear();
});
Future<void> _clear() async {
// A session saved but not yet restored (an offline launch) still backs
// the push stops that follow, so read it before deleting it.
var signedOut = _credential;
if (signedOut == null) {
try {
signedOut = (await _readRecord())?.credential;
} on AccountFailure {
// Unreadable: there is no credential to keep.
}
}
// Nothing may share the credential again while it is being removed.
_unshared = null;
// Attempt both removals so one failure never leaves the other copy live.
var failed = false;
try {
@@ -433,15 +483,22 @@ class BuilderlabAccountClient {
failed = true;
}
if (failed) {
// The record may already be gone, so an unrestored session's credential
// must survive for the retry's push stops.
if (_credential == null && signedOut != null) {
_signedOut = (
credential: signedOut,
until: DateTime.now().add(pushStopWindow),
);
}
// The account stays signed in, so the extension gets its copy back.
_unshared = _credential;
_share();
throw AccountFailure.storage;
}
final credential = _credential;
if (credential != null) {
if (signedOut != null) {
_signedOut = (
credential: credential,
credential: signedOut,
until: DateTime.now().add(pushStopWindow),
);
}

View File

@@ -23,6 +23,7 @@ import 'hosted_join_policy.dart';
part 'hosted_flow_identity_recovery.dart';
part 'hosted_flow_backup_consent.dart';
part 'hosted_flow_intent.dart';
enum HostedFlowStage {
idle,
@@ -1113,9 +1114,22 @@ class HostedFlow extends ChangeNotifier {
});
}
Future<void> leave({bool noCommunities = false}) async {
/// Ends the account session for a sign-out that also removes this device's
/// communities. Unlike [signOutAccount] it publishes no stage while it runs,
/// so hosted setup never covers the screen that asked, and a failure throws
/// to the caller instead of blocking the flow.
Future<void> endAccountSession() async {
_abandon();
await browser.cancel();
await browser.clearIntent();
await account.clearLocalSession();
if (!_disposed && stage != HostedFlowStage.idle) {
_set(HostedFlowStage.idle);
}
}
void _abandon({bool noCommunities = false}) {
_nextGeneration();
final generation = _generation;
_target = null;
_importRequested = false;
_pairedPubkey = null;
@@ -1124,6 +1138,11 @@ class HostedFlow extends ChangeNotifier {
accountOnly = false;
_clearCommunityBatch();
noCommunitiesToAdd = noCommunities;
}
Future<void> leave({bool noCommunities = false}) async {
_abandon(noCommunities: noCommunities);
final generation = _generation;
try {
await browser.cancel();
if (_disposed || generation != _generation) return;
@@ -1136,46 +1155,6 @@ class HostedFlow extends ChangeNotifier {
}
}
static Map<String, String> _encode(BuzzDeepLink target) {
if (target is HostedCreateCommunity) {
return {'type': 'create', 'name': target.name};
}
if (target is NostrBindDeepLink) return {'type': 'bind', ...target.fields};
if (target is AddCommunityDeepLink) {
return {'type': 'add', 'relay': target.relayUrl, 'name': target.name};
}
final invite = target as InviteDeepLink;
return {
'type': 'invite',
'relay': invite.relayUrl,
'code': invite.code,
if (invite.policyReceipt != null) 'policy_receipt': invite.policyReceipt!,
};
}
static BuzzDeepLink? _decode(Map<String, String> intent) {
if (intent['type'] == 'create') {
final name = intent['name'];
return name != null && HostedCreateCommunity.validName(name)
? HostedCreateCommunity(name)
: null;
}
final fields = Map<String, String>.of(intent)
..remove('type')
..remove('import_identity')
..remove('paired_pubkey')
..remove('paired_protection');
final host = switch (intent['type']) {
'bind' => 'nostr-bind',
'add' => 'add-community',
'invite' => 'join',
_ => '',
};
return parseBuzzDeepLink(
Uri(scheme: 'buzz', host: host, queryParameters: fields),
);
}
@override
void dispose() {
_disposed = true;

View File

@@ -0,0 +1,43 @@
part of 'hosted_flow.dart';
/// The browser sign-in intent that carries [target] through authentication.
Map<String, String> _encode(BuzzDeepLink target) {
if (target is HostedCreateCommunity) {
return {'type': 'create', 'name': target.name};
}
if (target is NostrBindDeepLink) return {'type': 'bind', ...target.fields};
if (target is AddCommunityDeepLink) {
return {'type': 'add', 'relay': target.relayUrl, 'name': target.name};
}
final invite = target as InviteDeepLink;
return {
'type': 'invite',
'relay': invite.relayUrl,
'code': invite.code,
if (invite.policyReceipt != null) 'policy_receipt': invite.policyReceipt!,
};
}
/// The deep link a browser sign-in intent carried, or null if it's invalid.
BuzzDeepLink? _decode(Map<String, String> intent) {
if (intent['type'] == 'create') {
final name = intent['name'];
return name != null && HostedCreateCommunity.validName(name)
? HostedCreateCommunity(name)
: null;
}
final fields = Map<String, String>.of(intent)
..remove('type')
..remove('import_identity')
..remove('paired_pubkey')
..remove('paired_protection');
final host = switch (intent['type']) {
'bind' => 'nostr-bind',
'add' => 'add-community',
'invite' => 'join',
_ => '',
};
return parseBuzzDeepLink(
Uri(scheme: 'buzz', host: host, queryParameters: fields),
);
}

View File

@@ -1,50 +0,0 @@
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../community/community_provider.dart';
import 'account_identity_store.dart';
import '../widgets/confirmation_dialog.dart';
import '../widgets/feedback_snackbar.dart';
/// Signs an internal build out of its organization. Removing the
/// organization's community returns to the Sign in landing, which ends the
/// organization session; it is the only way an internal build signs out.
///
/// The community's key stays on this device as a saved identity, so signing
/// back in reuses it even when the organization holds no backup of it.
Future<void> confirmOrganizationSignOut(
BuildContext context,
WidgetRef ref,
) async {
final messenger = ScaffoldMessenger.of(context);
final navigator = Navigator.of(context);
try {
final community = await ref.read(activeCommunityProvider.future);
if (community == null || !context.mounted) return;
final confirmed = await showDestructiveConfirmation(
context: context,
title: 'Sign out?',
message: 'You’ll need to sign in again to use Buzz on this device.',
confirmLabel: 'Sign out',
);
if (!confirmed || !context.mounted) return;
final nsec = community.nsec;
if (nsec != null && nsec.isNotEmpty) {
// A failure here keeps the community rather than delete the only copy
// of its key.
await AccountIdentityStore()
.forPairing(AccountIdentityStore.publicKeyForNsec(nsec))
.create(nsec);
}
await ref
.read(communityListProvider.notifier)
.removeCommunity(community.id);
// Reveal the Sign in landing under the page that signed out.
navigator.popUntil((route) => route.isFirst);
} catch (e) {
messenger.showFeedbackSnackBar(
SnackBar(content: Text('Failed to sign out: $e')),
kind: ToastKind.error,
);
}
}

View File

@@ -0,0 +1,72 @@
import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../community/community.dart';
import '../community/community_provider.dart';
import 'account_identity_store.dart';
import 'hosted_environment.dart';
import 'hosted_flow_provider.dart';
import '../widgets/confirmation_dialog.dart';
import '../widgets/feedback_snackbar.dart';
/// Signs this device out: removes every community, and in a public build ends
/// the Builderlab session. Each community's key goes to this device's saved
/// identities first, so signing out never destroys a key that may exist
/// nowhere else; signing back in offers it again. In an internal build the
/// Sign in landing that follows ends the organization session.
Future<void> confirmSignOut(BuildContext context, WidgetRef ref) async {
final messenger = ScaffoldMessenger.of(context);
final navigator = Navigator.of(context);
final list = ref.read(communityListProvider.notifier);
final flow = HostedEnvironment.enabled ? ref.read(hostedFlowProvider) : null;
try {
final communities = await ref.read(communityListProvider.future);
final active = await ref.read(activeCommunityProvider.future);
if (communities.isEmpty || !context.mounted) return;
final confirmed = await showDestructiveConfirmation(
context: context,
title: 'Sign out?',
message:
'You’ll need to sign in again to use Buzz on this device. '
'Your identities stay saved on this device.',
confirmLabel: 'Sign out',
);
if (!confirmed || !context.mounted) return;
// Every key is saved before any community is removed, so a failure
// leaves each community with its only copy of its key.
for (final community in communities) {
await keepCommunityKey(community);
}
// The session ends before any community is removed, so the Sign in
// landing never shows it and nothing started there can be cancelled by
// it. Removed communities' push-lease revocations authenticate with the
// push-stop credential it leaves behind.
await flow?.endAccountSession();
// The active community goes last, so removing the others never switches
// to and connects another one.
for (final community in [
...communities.where((c) => c.id != active?.id),
...communities.where((c) => c.id == active?.id),
]) {
await list.removeCommunity(community.id);
}
// Reveal the Sign in landing under the page that signed out.
navigator.popUntil((route) => route.isFirst);
} catch (e) {
messenger.showFeedbackSnackBar(
SnackBar(content: Text('Failed to sign out: $e')),
kind: ToastKind.error,
);
}
}
/// Copies [community]'s key into this device's saved identities, where
/// signing in again offers it. A failure throws, so the caller keeps the
/// community rather than delete the only copy of its key.
Future<void> keepCommunityKey(Community community) async {
final nsec = community.nsec;
if (nsec == null || nsec.isEmpty) return;
await AccountIdentityStore()
.forPairing(AccountIdentityStore.publicKeyForNsec(nsec))
.create(nsec);
}

View File

@@ -62,6 +62,12 @@ void main() {
'buildSignature': '',
});
await tester.pumpAndSettle();
// At large text the footer starts below the fold.
await tester.scrollUntilVisible(
find.text('v0.16.0 (432)'),
200,
scrollable: find.byType(Scrollable).first,
);
expect(find.text('v0.16.0 (432)'), findsOneWidget);
expect(tester.takeException(), isNull);
});

View File

@@ -0,0 +1,290 @@
import 'dart:async';
import 'package:buzz/features/settings/settings_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/account_identity_store.dart';
import 'package:buzz/shared/hosted/hosted_environment.dart';
import 'package:buzz/shared/hosted/hosted_flow_provider.dart';
import 'package:buzz/shared/relay/relay_session.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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:nostr/nostr.dart' as nostr;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../helpers/hosted_communities_fixture.dart';
/// Runs in every build. A public build also signs out of Builderlab:
/// `--dart-define=BUZZ_DISTRIBUTION=public`
/// `--dart-define=BUZZ_BUILDERLAB_URL=https://app.builderlab.xyz`
/// `--dart-define=BUZZ_BUILDERLAB_RELAYS=communities.buzz.xyz`
void main() {
testWidgets(
'Sign out removes every community but keeps each key on this device',
(tester) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(390, 1600);
addTearDown(tester.view.reset);
FlutterSecureStorage.setMockInitialValues({});
SharedPreferences.setMockInitialValues({});
PackageInfo.setMockInitialValues(
appName: 'Buzz',
packageName: 'xyz.block.buzz',
version: '0.16.0',
buildNumber: '1',
buildSignature: '',
);
final prefs = await SharedPreferences.getInstance();
// Neither key is exported or backed up anywhere.
final activeKeys = nostr.Keys.generate();
final otherKeys = nostr.Keys.generate();
final active = Community.create(
name: 'Active',
relayUrl: 'wss://active.example.org',
nsec: activeKeys.nsec,
);
final other = Community.create(
name: 'Other',
relayUrl: 'wss://other.example.org',
nsec: otherKeys.nsec,
);
final storage = CommunityStorage();
await storage.save(active);
await storage.save(other);
await storage.saveActiveId(active.id);
HostedCommunitiesFixture? hosted;
final accountStorage = _AccountStorage();
if (HostedEnvironment.enabled) {
hosted = HostedCommunitiesFixture();
// A later launch whose session restore hasn't succeeded yet: the
// session is saved but not in memory.
await hosted.initialize(
accountStorage: accountStorage,
coldAccount: true,
);
addTearDown(hosted.dispose);
await hosted.flow.leave();
hosted.unavailable = true;
await expectLater(hosted.account.restore(), throwsA(anything));
expect(hosted.account.account, isNull);
}
// Hosted setup must never cover Settings while it signs out.
final pushes = _Pushes();
// The Builderlab session must be gone before the Sign in landing can
// show it or be interrupted by its end.
final sessionAtRemoval = <bool>[];
final removed = <String>[];
// Revocations stay in flight until the landing has been checked.
final revocations = Completer<void>();
addTearDown(() {
if (!revocations.isCompleted) revocations.complete();
});
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
communityStorageProvider.overrideWithValue(storage),
communitySnapshotWriterProvider.overrideWithValue((_) async {}),
communityPushLeaseRevocationEnqueuerProvider.overrideWithValue((
community,
) async {
removed.add(community.id);
sessionAtRemoval.add(hosted?.account.account != null);
return true;
}),
communityPushLeaseRevocationTriggerProvider.overrideWithValue(
() => revocations.future,
),
relaySessionProvider.overrideWith(_OfflineSession.new),
if (hosted != null)
hostedFlowProvider.overrideWithValue(hosted.flow),
],
child: MaterialApp(
theme: AppTheme.light(),
navigatorObservers: [pushes],
home: const _Root(),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open Settings'));
await tester.pumpAndSettle();
// Cancelling keeps everything.
await tester.tap(find.byKey(const Key('settings-sign-out')));
await tester.pumpAndSettle();
expect(find.text('Sign out?'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
expect(await storage.loadAll(), hasLength(2));
Future<void> confirmSignOut() async {
await tester.tap(find.byKey(const Key('settings-sign-out')));
await tester.pumpAndSettle();
pushes.count = 0;
await tester.tap(find.widgetWithText(FilledButton, 'Sign out'));
}
// Each failure keeps every community and shows its error in Settings.
Future<void> signOutFails() async {
await confirmSignOut();
await tester.pumpAndSettle();
expect(pushes.count, 0);
expect(find.byType(SettingsPage), findsOneWidget);
expect(find.textContaining('Failed to sign out'), findsOneWidget);
expect(await storage.loadAll(), hasLength(2));
expect(removed, isEmpty);
ScaffoldMessenger.of(
tester.element(find.byKey(const Key('settings-sign-out'))),
).removeCurrentSnackBar();
await tester.pumpAndSettle();
}
if (hosted != null) {
// The saved session can't be deleted, though it isn't restored yet.
accountStorage.failing = true;
await signOutFails();
hosted.unavailable = false;
expect(await hosted.account.restore(), isNotNull);
// Nor once it is.
await signOutFails();
expect(hosted.account.account, isNotNull);
accountStorage.failing = false;
// A pending browser sign-in can't be forgotten.
hosted.browser.clearIntentError = PlatformException(code: 'keychain');
await signOutFails();
expect(hosted.account.account, isNotNull);
hosted.browser.clearIntentError = null;
}
// A session check still pending must not hold up signing out, nor
// restore the session when it finishes afterwards.
final heldCheck = Completer<void>();
Future<Object?>? pendingRestore;
if (hosted != null) {
hosted.beforeMe = () => heldCheck.future;
pendingRestore = hosted.account.restore().then<Object?>(
(restored) => restored,
onError: (Object error) => error,
);
await tester.pump();
}
addTearDown(() {
if (!heldCheck.isCompleted) heldCheck.complete();
});
await confirmSignOut();
// The landing animates, so it never settles.
await _pumpFor(tester);
expect(pushes.count, 0);
expect(await storage.loadAll(), isEmpty);
expect(find.byType(SettingsPage), findsNothing);
expect(find.byType(OnboardingAppEntry), findsOneWidget);
expect(find.textContaining('Signed in as'), findsNothing);
// The active community goes last, so nothing switches to the other.
expect(removed, [other.id, active.id]);
final saved = await AccountIdentityStore().identities();
expect(
saved.map((identity) => identity.pubkey),
containsAll([activeKeys.public, otherKeys.public]),
);
if (hosted != null) {
expect(sessionAtRemoval, everyElement(isFalse));
expect(hosted.account.account, isNull);
heldCheck.complete();
expect(await pendingRestore, isNull);
expect(hosted.account.account, isNull);
expect(await hosted.account.restore(), isNull);
}
// Revocations finishing later change nothing on the landing.
revocations.complete();
await _pumpFor(tester);
expect(find.byType(OnboardingAppEntry), findsOneWidget);
expect(find.textContaining('Signed in as'), findsNothing);
expect(hosted?.account.account, isNull);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox.shrink());
await _pumpFor(tester);
},
);
}
Future<void> _pumpFor(WidgetTester tester) async {
for (var i = 0; i < 20; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
}
/// Fails to delete the Builderlab session while [failing], as an unavailable
/// Keychain would.
class _AccountStorage extends FlutterSecureStorage {
bool failing = false;
@override
Future<void> delete({
required String key,
AppleOptions? iOptions,
AndroidOptions? aOptions,
LinuxOptions? lOptions,
WebOptions? webOptions,
AppleOptions? mOptions,
WindowsOptions? wOptions,
}) {
if (failing && key.startsWith('buzz_hosted_session_')) {
throw PlatformException(code: 'keychain', message: 'unavailable');
}
return super.delete(key: key);
}
}
/// Swaps in the Sign in landing once the device is signed out, as the app does.
class _Root extends ConsumerWidget {
const _Root();
@override
Widget build(BuildContext context, WidgetRef ref) {
final status = ref.watch(authProvider).value?.status;
if (status == null) return const SizedBox.shrink();
if (status != AuthStatus.authenticated) return const OnboardingAppEntry();
return HostedAppGate(
authenticated: true,
child: Scaffold(
body: TextButton(
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => SettingsPage(
profileHeader: const SizedBox.shrink(),
identityRecoveryPageBuilder: (_) => const SizedBox.shrink(),
),
),
),
child: const Text('Open Settings'),
),
),
);
}
}
/// The relay boundary: nothing connects.
class _OfflineSession extends RelaySessionNotifier {
@override
SessionState build() =>
const SessionState(status: SessionStatus.disconnected);
}
/// Counts routes pushed since [count] was last reset.
class _Pushes extends NavigatorObserver {
int count = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => count++;
}

View File

@@ -7,6 +7,7 @@ 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_identity_service.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:nostr/nostr.dart' as nostr;
@@ -29,8 +30,14 @@ class DiscoveryBrowser extends BrowserAuth {
@override
Future<void> initialize() async {}
/// Thrown by [clearIntent] while set, as unavailable storage would.
Object? clearIntentError;
@override
Future<void> clearIntent() async {}
Future<void> clearIntent() async {
if (clearIntentError case final error?) throw error;
}
@override
Future<void> cancel() async {}
}
@@ -92,72 +99,91 @@ class HostedCommunitiesFixture {
bool rejectList = false;
bool rejectCurrent = false;
bool expired = false;
bool unavailable = false;
String subject = 'owner';
Future<void> Function(String)? beforeAdmission;
Future<void> Function()? beforeList;
Future<void> Function()? beforeMe;
Uri? opened;
Map<String, dynamic> row(String name) => {
'community_url': 'wss://$name.communities.buzz.xyz',
};
Future<void> initialize({bool backup = true, bool widget = false}) async {
Future<void> initialize({
bool backup = true,
bool widget = false,
FlutterSecureStorage? accountStorage,
bool coldAccount = false,
}) async {
bound = keys.public;
final expiry = DateTime.now()
.toUtc()
.add(const Duration(hours: 1))
.toIso8601String();
final client = MockClient((request) async {
final path = request.url.path;
requests.add(path);
if (path.endsWith('/exchange')) {
return http.Response(
jsonEncode({'session_credential': 'fixture', 'expires_at': expiry}),
200,
);
}
if (path.endsWith('/me')) {
await beforeMe?.call();
if (expired) return http.Response('{}', 401);
if (unavailable) return http.Response('{}', 503);
return http.Response(
jsonEncode({
'subject': subject,
'email': 'owner@example.com',
'expires_at': expiry,
}),
200,
);
}
if (path.endsWith('/current')) {
return http.Response(
jsonEncode({
'identity': {'pubkey_hex': bound},
}),
200,
);
}
if (path.endsWith('/known-communities/list')) {
await beforeList?.call();
if (rejectList) return http.Response('{}', 503);
return http.Response(jsonEncode({'communities': rows}), 200);
}
if (path.endsWith('/known-communities/add')) {
final body = jsonDecode(request.body) as Map<String, dynamic>;
return http.Response(
jsonEncode({
'community': {'community_url': body['community_url']},
}),
200,
);
}
return http.Response('{}', 503);
});
account = BuilderlabAccountClient(
httpClient: MockClient((request) async {
final path = request.url.path;
requests.add(path);
if (path.endsWith('/exchange')) {
return http.Response(
jsonEncode({'session_credential': 'fixture', 'expires_at': expiry}),
200,
);
}
if (path.endsWith('/me')) {
if (expired) return http.Response('{}', 401);
return http.Response(
jsonEncode({
'subject': subject,
'email': 'owner@example.com',
'expires_at': expiry,
}),
200,
);
}
if (path.endsWith('/current')) {
return http.Response(
jsonEncode({
'identity': {'pubkey_hex': bound},
}),
200,
);
}
if (path.endsWith('/known-communities/list')) {
await beforeList?.call();
if (rejectList) return http.Response('{}', 503);
return http.Response(jsonEncode({'communities': rows}), 200);
}
if (path.endsWith('/known-communities/add')) {
final body = jsonDecode(request.body) as Map<String, dynamic>;
return http.Response(
jsonEncode({
'community': {'community_url': body['community_url']},
}),
200,
);
}
return http.Response('{}', 503);
}),
storage: accountStorage,
httpClient: client,
);
if (widget) {
account.dispose();
account = WidgetDiscoveryAccount(this);
} else {
await account.exchange(code: 'code', verifier: 'a' * 43);
if (coldAccount) {
// A later process: the session is saved but not restored yet.
account.dispose();
account = BuilderlabAccountClient(
storage: accountStorage,
httpClient: client,
);
}
}
await store.create(keys.nsec);
if (backup) {

View File

@@ -5,6 +5,7 @@ import 'hosted_http_fixture.dart';
import 'dart:convert';
import 'package:buzz/shared/hosted/builderlab_account.dart';
import 'package:buzz/shared/storage/serial_queue.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
@@ -185,7 +186,8 @@ void main() {
onError: (Object error) => failure = error,
),
);
unawaited(client.clearLocalSession().then((_) => cleared = true));
// Any queued account request waits for the deadline.
unawaited(client.restore().then((_) => cleared = true));
await tester.pump();
await tester.pump(const Duration(seconds: 20));
await tester.pump(const Duration(seconds: 5));
@@ -309,6 +311,141 @@ void main() {
expect(verifications, 2);
});
test('a sign-out is never undone by a pending session check', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
final storage = _SessionStorage();
var check = Completer<void>();
final client = BuilderlabAccountClient(
storage: storage,
httpClient: MockClient((request) async {
await check.future;
return http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
);
}),
);
// A check already pending when sign-out starts doesn't hold it up.
final early = client.restore();
await pumpEventQueue();
await client.clearLocalSession();
check.complete();
expect(await early, isNull);
expect(client.account, isNull);
// Nor does a check that starts while the session is being deleted.
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
check = Completer<void>();
final deleted = Completer<void>();
storage.holdDelete = deleted.future;
final clearing = client.clearLocalSession();
final late = client.restore();
await pumpEventQueue();
deleted.complete();
await clearing;
check.complete();
expect(await late, isNull);
expect(client.account, isNull);
expect(await stored(), isNull);
});
test('an exchange queued before a sign-out cannot sign back in', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
final entered = Completer<void>();
final release = Completer<void>();
final client = BuilderlabAccountClient(
httpClient: MockClient((request) async {
if (request.url.path.endsWith('/exchange')) {
return http.Response(
jsonEncode({'session_credential': 'new', 'expires_at': expiry}),
200,
);
}
if (request.headers['X-BB-Session-Credential'] == 'old') {
if (!entered.isCompleted) entered.complete();
await release.future;
}
return http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
);
}),
);
addTearDown(() {
if (!release.isCompleted) release.complete();
client.dispose();
});
final restoring = client.restore();
await entered.future;
final exchanging = client
.exchange(code: 'code', verifier: verifier)
.then<Object?>((value) => value, onError: (Object error) => error);
await client.clearLocalSession();
release.complete();
await restoring;
expect(await exchanging, AccountFailure.unavailable);
expect(client.account, isNull);
expect(await stored(), isNull);
});
test('signing out leaves the extension without the session', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
});
// Extension writes land in call order, as the iOS bridge does.
final writes = SerialQueue();
var shareFails = true;
String? shared = 'old';
final unshareStarted = Completer<void>();
final releaseUnshare = Completer<void>();
final client = BuilderlabAccountClient(
httpClient: MockClient(
(request) async => http.Response(
jsonEncode({'subject': 'account-1', 'expires_at': expiry}),
200,
),
),
onSessionChanged: (credential) => writes.run(() async {
if (credential == null) {
if (!unshareStarted.isCompleted) unshareStarted.complete();
await releaseUnshare.future;
} else if (shareFails) {
throw StateError('keychain unavailable');
}
shared = credential;
}),
);
addTearDown(() {
if (!releaseUnshare.isCompleted) releaseUnshare.complete();
client.dispose();
});
// The first share fails, so the credential waits to be shared again.
await client.restore();
await pumpEventQueue();
shareFails = false;
final clearing = client.clearLocalSession();
await unshareStarted.future;
// An account request arriving mid-removal must not share it again.
final request = client.currentIdentity().then<Object?>(
(value) => value,
onError: (Object error) => error,
);
await pumpEventQueue();
releaseUnshare.complete();
await clearing;
await request;
await writes.run(() async {});
expect(client.account, isNull);
expect(await stored(), isNull);
expect(shared, isNull);
});
test('login for another account keeps the existing session', () async {
FlutterSecureStorage.setMockInitialValues({
storageKey: record('account-1', 'old'),
@@ -459,6 +596,7 @@ void main() {
class _SessionStorage extends FlutterSecureStorage {
bool failDelete = false;
Future<void>? holdDelete;
@override
Future<void> delete({
@@ -471,6 +609,7 @@ class _SessionStorage extends FlutterSecureStorage {
WindowsOptions? wOptions,
}) async {
if (failDelete) throw StateError('storage unavailable');
await holdDelete;
await super.delete(key: key);
}
}

View File

@@ -47,8 +47,11 @@ void main() {
late int assertionLifetime;
late String Function(String relayUrl) tokenFor;
BuilderlabAccountClient organizationClient() => BuilderlabAccountClient(
BuilderlabAccountClient organizationClient({
Future<void> Function(String?)? onSessionChanged,
}) => BuilderlabAccountClient(
accountOrigin: organization,
onSessionChanged: onSessionChanged,
httpClient: MockClient((request) async {
requests.add(request);
expect(request.url.origin, organization.origin);
@@ -390,6 +393,37 @@ void main() {
);
});
test('a push stop still gets an assertion after signing out a saved '
'session that was never restored, across a failed cleanup', () async {
// An offline launch keeps the saved session without adopting it.
await saveSession();
// The first cleanup deletes the record, then fails to unshare.
var unshareFails = true;
final account = organizationClient(
onSessionChanged: (_) async {
if (unshareFails) throw StateError('unshare failed');
},
);
final auth = relayAuth(account);
boundIdentity = {'pubkey_hex': keys.public};
await expectLater(
account.clearLocalSession(),
throwsA(AccountFailure.storage),
);
unshareFails = false;
await account.clearLocalSession();
expect(await account.restore(), isNull);
requests.clear();
tokenFor = (_) => 'push-stop-token';
expect(await auth.headers(relay, background: true), {
'Nostr-Federated-Identity': 'Bearer push-stop-token',
});
expect(requests.last.headers['X-BB-Session-Credential'], 'org-secret');
expect(await auth.headers(relay), isEmpty);
expect(account.account, isNull);
});
test('other relays never receive the organization assertion', () async {
await saveSession();
final auth = relayAuth(organizationClient());