mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +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>
349 lines
12 KiB
Dart
349 lines
12 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:uuid/uuid.dart';
|
|
|
|
import '../community/community.dart';
|
|
|
|
import '../storage/secure_storage.dart';
|
|
import '../storage/serial_queue.dart';
|
|
import 'builderlab_account.dart';
|
|
import 'known_community_address.dart';
|
|
|
|
/// Retained account for a local add or removal only.
|
|
extension LocalEditSubject on BuilderlabAccountClient {
|
|
/// An unreadable session record makes a local add or removal behave as
|
|
/// signed out: no owner stamp and no tombstone, so the device edit still
|
|
/// succeeds as it did before account sync. Account sync itself stays strict:
|
|
/// it requires a verified session and never reads this fallback.
|
|
Future<String?> localEditSubject() async {
|
|
try {
|
|
return await retainedSubject();
|
|
} on AccountFailure catch (failure) {
|
|
if (failure == AccountFailure.storage) return null;
|
|
rethrow;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Durable account-list edits. Community credentials and relay membership never
|
|
/// enter this queue. Each account keeps its own snapshot and latest URL intents.
|
|
class KnownCommunitySync extends ChangeNotifier {
|
|
/// Reconciles committed, explicitly owned additions and queued removals.
|
|
KnownCommunitySync({
|
|
required this.account,
|
|
required this.localCommunities,
|
|
this.acknowledgeRemoval,
|
|
FlutterSecureStorage? storage,
|
|
this.retryDelay = const Duration(seconds: 2),
|
|
}) : _storage = storage ?? accountSecureStorage {
|
|
account.subjectChanges.addListener(_sessionChanged);
|
|
account.sessionChanges.addListener(_sessionChanged);
|
|
}
|
|
|
|
/// Account API whose verified session authorizes each destination edit.
|
|
final BuilderlabAccountClient account;
|
|
|
|
/// Durable device records, including their explicit account ownership.
|
|
final Future<List<Community>> Function() localCommunities;
|
|
|
|
/// Removes a credential-free local tombstone only after server acknowledgment.
|
|
final Future<void> Function(String revision)? acknowledgeRemoval;
|
|
final FlutterSecureStorage _storage;
|
|
|
|
/// Initial transient retry delay; subsequent failures back off up to 32x.
|
|
final Duration retryDelay;
|
|
|
|
/// Latest failure for the current account; pending work remains durable.
|
|
Object? get failure => _failure;
|
|
Object? _failure;
|
|
final _queue = SerialQueue();
|
|
Timer? _retry;
|
|
bool _disposed = false;
|
|
bool _active = true;
|
|
Future<void>? _work;
|
|
bool _again = false;
|
|
String? _blockedSubject;
|
|
int _failures = 0;
|
|
|
|
String _key(String subject) =>
|
|
'buzz_known_communities_v1_${base64Url.encode(utf8.encode('${account.accountOrigin.origin}\n$subject'))}';
|
|
|
|
Future<_SyncState> _read(String subject) async {
|
|
final raw = await _storage.read(key: _key(subject));
|
|
return raw == null ? _SyncState() : _SyncState.decode(raw);
|
|
}
|
|
|
|
Future<void> _write(String subject, _SyncState state) =>
|
|
_storage.write(key: _key(subject), value: state.encode());
|
|
|
|
bool _current(String subject) =>
|
|
!_disposed && account.account?.subject == subject;
|
|
|
|
void _sessionChanged() {
|
|
_failure = null;
|
|
_blockedSubject = null;
|
|
_failures = 0;
|
|
_retry?.cancel();
|
|
notifyListeners();
|
|
trigger();
|
|
}
|
|
|
|
/// Stop retries immediately when the app leaves the foreground.
|
|
void setActive(bool active) {
|
|
_active = active;
|
|
_retry?.cancel();
|
|
if (active) trigger();
|
|
}
|
|
|
|
/// Persist removal before deleting the local record. The drain sends it only
|
|
/// once the local record is absent, so failed local deletion cannot forget it
|
|
/// remotely. Signed-out edits never borrow another account's credentials.
|
|
Future<void> remove(String relay, {String? expectedSubject}) async {
|
|
final subject = expectedSubject ?? await account.localEditSubject();
|
|
if (await account.localEditSubject() != subject) {
|
|
throw AccountFailure.differentAccount;
|
|
}
|
|
final url = knownCommunityAddress(relay);
|
|
if (subject == null || url == null) return;
|
|
await _queue.run(() async {
|
|
final state = await _read(subject);
|
|
if (!_current(subject)) throw AccountFailure.differentAccount;
|
|
final local = await localCommunities();
|
|
if (!_current(subject)) throw AccountFailure.differentAccount;
|
|
for (final item in local) {
|
|
if (knownCommunityAddress(item.relayUrl) == url &&
|
|
item.accountSyncOwner == _owner(subject) &&
|
|
item.accountSyncRevision != null) {
|
|
state.observed[url] = item.accountSyncRevision!;
|
|
}
|
|
}
|
|
state.pending[url] = true;
|
|
await _write(subject, state);
|
|
});
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
|
|
String _owner(String subject) => '${account.accountOrigin.origin}\n$subject';
|
|
|
|
/// Stamp only explicit additions. Saving this returned record atomically with
|
|
/// credentials is the durable add intent; a later journal failure cannot turn
|
|
/// a completed join into an authentication failure. Unclaimed legacy records
|
|
/// and another account's retained records are never automatically uploaded.
|
|
Future<Community> prepareAddition(Community community) async {
|
|
final subject = await account.localEditSubject();
|
|
if (subject == null &&
|
|
community.accountSyncOwner == null &&
|
|
community.accountSyncRevision == null) {
|
|
return community;
|
|
}
|
|
return community.copyWith(
|
|
accountSyncRemoved: false,
|
|
accountSyncOwner: subject == null ? null : _owner(subject),
|
|
accountSyncRevision: subject == null ? null : const Uuid().v4(),
|
|
);
|
|
}
|
|
|
|
/// An explicit retry clears a refused request without dropping its intent.
|
|
void retry() {
|
|
_blockedSubject = null;
|
|
_failure = null;
|
|
_failures = 0;
|
|
notifyListeners();
|
|
trigger();
|
|
}
|
|
|
|
/// Pending removals for visible status, including across app restarts.
|
|
Future<Set<String>> pendingRemovals(String subject) => _queue.run(() async {
|
|
final records = await localCommunities();
|
|
final removed = records
|
|
.where(
|
|
(c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject),
|
|
)
|
|
.map((c) => c.relayUrl)
|
|
.toSet();
|
|
try {
|
|
final state = await _read(subject);
|
|
removed.addAll(
|
|
state.pending.entries.where((e) => e.value).map((e) => e.key),
|
|
);
|
|
} catch (_) {
|
|
// A separate journal failure must not conceal a committed local removal.
|
|
if (removed.isEmpty) rethrow;
|
|
}
|
|
return removed;
|
|
});
|
|
|
|
/// Run after startup, a saved-community change, sign-in, or app resume.
|
|
void trigger() => unawaited(synchronize());
|
|
|
|
/// Coalesce concurrent refreshes and complete after their queued work drains.
|
|
Future<void> synchronize() {
|
|
if (_disposed || !_active) return Future.value();
|
|
_retry?.cancel();
|
|
final work = _work;
|
|
if (work != null) {
|
|
_again = true;
|
|
return work;
|
|
}
|
|
return _work = _drain().whenComplete(() => _work = null);
|
|
}
|
|
|
|
Future<void> _drain() async {
|
|
do {
|
|
_again = false;
|
|
await _run();
|
|
} while (_again && !_disposed && _active);
|
|
}
|
|
|
|
Future<void> _run() async {
|
|
String? attemptSubject;
|
|
try {
|
|
final session = account.account ?? await account.restore();
|
|
if (session == null || !_current(session.subject) || !_active) return;
|
|
final subject = session.subject;
|
|
attemptSubject = subject;
|
|
if (_blockedSubject == subject) return;
|
|
// Local deletion and this intent share a single storage commit. Drain it
|
|
// independently of the older account-only journal, even if that is broken.
|
|
final committed = await localCommunities();
|
|
for (final item in committed.where(
|
|
(c) => c.accountSyncRemoved && c.accountSyncOwner == _owner(subject),
|
|
)) {
|
|
if (!_current(subject)) return;
|
|
await account.updateKnownCommunity(
|
|
item.relayUrl,
|
|
removed: true,
|
|
expectedSubject: subject,
|
|
);
|
|
if (!_current(subject)) return;
|
|
await acknowledgeRemoval?.call(item.accountSyncRevision!);
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
var local = <String>{};
|
|
await _queue.run(() async {
|
|
final records = (await localCommunities())
|
|
.where((c) => !c.accountSyncRemoved)
|
|
.toList();
|
|
local = records
|
|
.where((c) => c.accountSyncOwner == _owner(subject))
|
|
.map((c) => knownCommunityAddress(c.relayUrl))
|
|
.whereType<String>()
|
|
.toSet();
|
|
final state = await _read(subject);
|
|
if (!_current(subject)) return;
|
|
final owned = records
|
|
.where(
|
|
(item) =>
|
|
item.accountSyncOwner == _owner(subject) &&
|
|
item.accountSyncRevision != null,
|
|
)
|
|
.map((item) => knownCommunityAddress(item.relayUrl))
|
|
.whereType<String>()
|
|
.toSet();
|
|
// Older preview journals had no ownership evidence for inferred adds.
|
|
state.pending.removeWhere(
|
|
(url, removed) => !removed && !owned.contains(url),
|
|
);
|
|
final revisions = <String, List<String>>{};
|
|
for (final item in records) {
|
|
final url = knownCommunityAddress(item.relayUrl);
|
|
final revision = item.accountSyncRevision;
|
|
if (url == null ||
|
|
revision == null ||
|
|
item.accountSyncOwner != _owner(subject)) {
|
|
continue;
|
|
}
|
|
(revisions[url] ??= []).add(revision);
|
|
}
|
|
for (final entry in revisions.entries) {
|
|
final url = entry.key;
|
|
final revision = (entry.value..sort()).join(',');
|
|
if (state.observed[url] != revision) {
|
|
// A committed re-add wins over an older removal, even if the app
|
|
// stopped before it could update this separate retry journal.
|
|
state.pending[url] = false;
|
|
state.observed[url] = revision;
|
|
}
|
|
}
|
|
await _write(subject, state);
|
|
});
|
|
while (_current(subject) && _active) {
|
|
final pending = await _queue.run(() => _read(subject));
|
|
final entries = pending.pending.entries.where(
|
|
(entry) => !entry.value || !local.contains(entry.key),
|
|
);
|
|
if (entries.isEmpty) break;
|
|
final op = entries.first;
|
|
if (!_current(subject)) return;
|
|
await account.updateKnownCommunity(
|
|
op.key,
|
|
removed: op.value,
|
|
expectedSubject: subject,
|
|
);
|
|
if (!_current(subject)) return;
|
|
await _queue.run(() async {
|
|
final latest = await _read(subject);
|
|
// An edit made while the request was in flight wins over its ack.
|
|
if (latest.pending[op.key] == op.value) {
|
|
latest.pending.remove(op.key);
|
|
await _write(subject, latest);
|
|
}
|
|
});
|
|
if (!_disposed) notifyListeners();
|
|
}
|
|
_failures = 0;
|
|
if (_failure != null) {
|
|
_failure = null;
|
|
notifyListeners();
|
|
}
|
|
} catch (error) {
|
|
if (_disposed || (attemptSubject != null && !_current(attemptSubject))) {
|
|
return;
|
|
}
|
|
_failure = error;
|
|
notifyListeners();
|
|
if (error == AccountFailure.denied ||
|
|
error == AccountFailure.rejected ||
|
|
error == AccountFailure.invalidResponse ||
|
|
error == AccountFailure.accountSetupRequired) {
|
|
// Preserve intent but do not hammer a refused API until a new sign-in.
|
|
_blockedSubject = account.account?.subject;
|
|
} else if (_active && error != AccountFailure.signedOut) {
|
|
final multiplier = 1 << (_failures++).clamp(0, 5);
|
|
_retry = Timer(retryDelay * multiplier, trigger);
|
|
}
|
|
debugPrint('Account community sync deferred: $error');
|
|
}
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_retry?.cancel();
|
|
account.subjectChanges.removeListener(_sessionChanged);
|
|
account.sessionChanges.removeListener(_sessionChanged);
|
|
super.dispose();
|
|
}
|
|
}
|
|
|
|
class _SyncState {
|
|
_SyncState({Map<String, String>? observed, Map<String, bool>? pending})
|
|
: observed = observed ?? {},
|
|
pending = pending ?? {};
|
|
final Map<String, String> observed;
|
|
final Map<String, bool> pending;
|
|
|
|
factory _SyncState.decode(String raw) {
|
|
final value = jsonDecode(raw) as Map<String, dynamic>;
|
|
return _SyncState(
|
|
observed: (value['observed'] as Map?)?.cast<String, String>() ?? {},
|
|
pending: (value['pending'] as Map).cast<String, bool>(),
|
|
);
|
|
}
|
|
|
|
String encode() => jsonEncode({'observed': observed, 'pending': pending});
|
|
}
|