mirror of
https://github.com/block/buzz.git
synced 2026-11-24 18:21:59 +00:00
## Summary Switch Community currently shows only device-saved communities, leaving account destinations behind a separate Find step. It now merges saved communities with supported account destinations directly, keeps Add Community, and removes the redundant Find action from that Add route. Initial onboarding and identity recovery keep their discovery entry. Find lists supported account addresses before hosted identity setup; hosted selection still performs binding, backup, and admission, while external selection opens the existing identity flow. Mobile also saves QR/address additions and explicit removals through Builder Lab's existing known-communities account APIs. A per-account local journal retries transient failures, survives restarts, pauses in the background, and fences requests against account changes. External secure addresses use the existing self-hosted entry flow; account destinations never imply membership or bypass admission. Remote list omissions do not delete local identities. Explicit additions store an account owner and revision atomically with local credentials. Legacy/unclaimed destinations remain local-only until explicitly added while signed in; signing into another account never claims retained destinations. Restart reconciliation lets a committed re-add supersede an older removal even if the retry-journal write failed. Local deletion and its credential-free account-removal intent commit in one storage write, independent of the account-only retry journal. Removing one of several local identities owned by the same account at an address retains its account destination until that account’s last identity is removed. Another account’s saved identity does not block removal or lose its credentials during recovery. Offline edits retain the stored account subject without treating it as network authorization. Discovery-only intent survives browser callbacks, app restart, and retry. Onboarding recovery controls have a Material ancestor in the actual route. Pending status is fenced to the current subject; interrupted older removals offer explicit local completion, and denied requests offer browser reauthentication. Same-host ports have distinct labels and confirmations, and unsupported hosted ports are excluded. This changes the mobile client and its public-build CI test list only: no relay endpoints, events, migrations, or backend deployment. ### Related issue No duplicate found among open known-communities/switcher issues and PRs. Related picker editing work: #6632 (renaming communities). ### Testing Validated after merging main (`02535e1b53`) at `c4ee037f7e710962f176540abf88d26e98c2823c`. Wes’s follow-up fixes cover push-revocation commit ordering, same-account removal confirmation, and recovery after completed hosted admission. The merge also preserves main’s toolbar and session protections; a test override now accepts the updated relay subscription parameter. - Formatting, static analysis, and differential file-size checks pass. - Prior full CI and security review passed on `3adb117aae`; security checks also passed on `cf3836ecb`. Fresh CI and security review are required for this head. - Mutation checks fail when either the initiating-account removal guard or the rendered-status subject fence is removed; both guards were restored before final validation. - CI explicitly runs the public-only account discovery and synchronization journeys. - Added journeys cover paused removal across A→B, offline restart, journal read/write failures, duplicate local identities in either removal order, delayed status reads across accounts, real browser handoff after denial, unbound external discovery, and local same-host port removal. - Earlier journeys cover pairing acknowledgement and restart after journal-write failure, same-subject setup completion, offline/rejected removal with reopen/retry, and fresh external-only/mixed account entry. - Regression coverage includes discovery deduplication and retry, hosted and external selection, Add without Find, account-only removal, shared authentication/removal persistence, restart recovery, latest-intent ordering, account changes, and retry pause/resume. - `just mobile-check`, `just file-size-check`, and `just mobile-test`: 4,954 default-build tests passed (71 skipped), plus 27 crypto-package tests. - Full public-account suite: 5,012 passed, 12 skipped, one pre-existing failure in `fullscreen_onboarding_test.dart` ("Home stays hidden until community choice and admission"). The same assertion was reproduced on clean base `8cce12f591`: expected both communities imported, actual only the selected community. - Follow-up regression journeys cover both A/B same-address removal orderings, recovery preserving B’s saved key, the production onboarding widget composition, and retained discovery intent with callback/retry plus normal-sign-in controls. - Native/live-account and human testing remain outstanding. The tests use fake network/storage boundaries; live account API behavior, cross-device synchronization, native accessibility, and timeout/late-server-commit ordering still require integration verification. - The three expanded recovery/removal journeys pass and each fails when the corresponding fix is removed. A durably journaled revocation now finishes the confirmed removal even if the account changes during journaling; pre-journal account mismatches still abort. Confirmation copy counts only same-account identities. Explicit account recovery retires a completed join target while preserving in-progress targets. ### Preview Sample-data Flutter widget renders: saved-only and combined lists. These illustrate the picker layout, not a device session or live account sync. | Saved-only | Combined | | --- | --- | |  |  | ### Manual verification 1. Sign into a public account with a community saved on another device. Open Switch Community; verify it appears alongside local choices and Add. 2. Select a hosted and an external community; verify the existing identity/admission flow opens. Add should not offer Find again. 3. Add a community by QR/address, then check the account list on desktop. Remove it on mobile and verify the account entry disappears while other devices retain their local credentials. 4. Repeat removal offline, restart, then reconnect/resume. Verify the queued removal reaches the account service without switching identities. 5. On a fresh device, verify external-only and mixed account lists offer external entry. Check two ports on the same host remain distinguishable. 6. Sign out of account A and into B; retained A destinations must not upload to B. Explicitly add a B destination and verify it syncs. 7. Reject or interrupt account removal; verify visible pending/failure status. A denied session must open browser sign-in through “Sign in again” and retry after exchange; setup-required accounts retain their setup action. 8. Keep two local identities owned by the same account at one address; removing the first must keep the account entry, and removing the last must queue account removal. Repeat with A and B at that address; removing A must preserve B’s saved credentials and still sync A’s removal. 9. Restart offline with a stored account, add/remove an external community, then reconnect as the same account and verify convergence. Explicit sign-out must not claim new local-only entries. 10. Start Find my communities, restart during browser authentication, then return or retry. External destinations must appear before hosted identity setup; normal sign-in must retain its identity checks. --------- Signed-off-by: kenny lopez <klopez4212@gmail.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
237 lines
6.9 KiB
Dart
237 lines
6.9 KiB
Dart
import 'dart:convert';
|
|
import 'dart:async';
|
|
|
|
import 'package:buzz/shared/deeplink/deep_link.dart';
|
|
import 'package:buzz/shared/hosted/account_identity_store.dart';
|
|
import 'package:buzz/shared/hosted/browser_auth.dart';
|
|
import 'package:buzz/shared/hosted/builderlab_account.dart';
|
|
import 'package:buzz/shared/hosted/hosted_flow.dart';
|
|
import 'package:buzz/shared/hosted/hosted_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;
|
|
|
|
class DiscoveryBrowser extends BrowserAuth {
|
|
final callbacks = StreamController<BrowserAuthCode>.broadcast();
|
|
Map<String, String>? startedIntent;
|
|
@override
|
|
Future<void> start(Map<String, String> intent) async {
|
|
startedIntent = intent;
|
|
}
|
|
|
|
@override
|
|
Stream<BrowserAuthCode> get codes => callbacks.stream;
|
|
@override
|
|
Future<void> dispose() async {
|
|
await callbacks.close();
|
|
await super.dispose();
|
|
}
|
|
|
|
@override
|
|
Future<void> initialize() async {}
|
|
|
|
/// Thrown by [clearIntent] while set, as unavailable storage would.
|
|
Object? clearIntentError;
|
|
@override
|
|
Future<void> clearIntent() async {
|
|
if (clearIntentError case final error?) throw error;
|
|
}
|
|
|
|
@override
|
|
Future<void> cancel() async {}
|
|
}
|
|
|
|
class WidgetDiscoveryAccount extends BuilderlabAccountClient {
|
|
WidgetDiscoveryAccount(this.fixture);
|
|
final HostedCommunitiesFixture fixture;
|
|
@override
|
|
BuilderlabAccount? get account => fixture.expired
|
|
? null
|
|
: BuilderlabAccount(
|
|
subject: fixture.subject,
|
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
);
|
|
@override
|
|
Future<BuilderlabAccount?> restore() async => account;
|
|
@override
|
|
Future<void> rememberCommunity(
|
|
String relay, {
|
|
required String expectedSubject,
|
|
}) async {
|
|
if (account?.subject != expectedSubject) throw AccountFailure.denied;
|
|
fixture.remembered.add(relay);
|
|
}
|
|
|
|
@override
|
|
Future<Map<String, dynamic>> post(
|
|
String path,
|
|
Map<String, dynamic> body, {
|
|
String? expectedSubject,
|
|
}) async {
|
|
fixture.requests.add(path);
|
|
if (path.endsWith('/current')) {
|
|
if (fixture.rejectCurrent) throw AccountFailure.denied;
|
|
return {
|
|
'identity': {'pubkey_hex': fixture.bound},
|
|
};
|
|
}
|
|
if (path.endsWith('/known-communities/list')) {
|
|
return {'communities': fixture.rows};
|
|
}
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
}
|
|
|
|
class HostedCommunitiesFixture {
|
|
final keys = nostr.Keys('1'.padLeft(64, '0'));
|
|
AccountIdentityStore get store => AccountIdentityStore(subject: subject);
|
|
final browser = DiscoveryBrowser();
|
|
late BuilderlabAccountClient account;
|
|
late final HostedFlow flow;
|
|
final admitted = <String>[];
|
|
String? openedCommunity;
|
|
Future<void> Function()? beforeOpen;
|
|
final remembered = <String>[];
|
|
final requests = <String>[];
|
|
List<Map<String, dynamic>> rows = [];
|
|
String? bound;
|
|
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,
|
|
bool withIdentity = true,
|
|
FlutterSecureStorage? accountStorage,
|
|
bool coldAccount = false,
|
|
}) async {
|
|
bound = withIdentity ? keys.public : null;
|
|
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': bound == null ? null : {'pubkey_hex': bound},
|
|
}),
|
|
200,
|
|
);
|
|
}
|
|
if (path.endsWith('/nsec-backups/status')) {
|
|
return http.Response(
|
|
jsonEncode({
|
|
'backup_nostr_pubkeys': <String>[],
|
|
'current_nostr_pubkey': 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(
|
|
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,
|
|
);
|
|
}
|
|
}
|
|
if (withIdentity) await store.create(keys.nsec);
|
|
if (backup && withIdentity) {
|
|
await store.confirmBackup(
|
|
BackupReceipt(
|
|
backend: BuilderlabAccountClient.origin.toString(),
|
|
subject: 'owner',
|
|
pubkey: keys.public,
|
|
backupId: 'fixture-backup',
|
|
),
|
|
);
|
|
}
|
|
flow = HostedFlow(
|
|
account: account,
|
|
browser: browser,
|
|
store: store,
|
|
identity: HostedIdentityService(account: account, store: store),
|
|
openWeb: (uri) async {
|
|
opened = uri;
|
|
return true;
|
|
},
|
|
openLandingCommunity: (link, subject, pubkey, current) async {
|
|
await beforeOpen?.call();
|
|
if (current()) openedCommunity = link.relayUrl;
|
|
},
|
|
enterCommunity: (link, subject, pubkey, current) async {
|
|
// Record the relay host: names are display labels.
|
|
final host = Uri.parse((link as AddCommunityDeepLink).relayUrl).host;
|
|
await beforeAdmission?.call(host);
|
|
if (current()) admitted.add(host);
|
|
},
|
|
);
|
|
}
|
|
|
|
Future<void> dispose() async {
|
|
flow.dispose();
|
|
await browser.dispose();
|
|
account.dispose();
|
|
}
|
|
}
|