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>
274 lines
9.4 KiB
Dart
274 lines
9.4 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:crypto/crypto.dart';
|
|
import 'package:uuid/uuid.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
|
|
import '../hosted/organization_environment.dart';
|
|
import '../hosted/known_community_address.dart';
|
|
import '../storage/secure_storage.dart';
|
|
import '../storage/serial_queue.dart';
|
|
|
|
import 'community.dart';
|
|
|
|
class CommunityStorage {
|
|
static const _keyCommunities = 'buzz_communities';
|
|
static const _keyActiveId = 'buzz_active_community_id';
|
|
|
|
// Legacy keys for migration.
|
|
static const _legacyCommunities = 'buzz_workspaces';
|
|
static const _legacyActiveId = 'buzz_active_workspace_id';
|
|
static const _legacyRelayUrl = 'buzz_relay_url';
|
|
static const _legacyToken = 'buzz_token';
|
|
static const _legacyPubkey = 'buzz_pubkey';
|
|
static const _legacyNsec = 'buzz_nsec';
|
|
|
|
final FlutterSecureStorage _secure;
|
|
|
|
/// Whether this build shows a saved community. Others stay stored, with
|
|
/// their keys, for a build that can reach them.
|
|
final bool Function(Community community) _visible;
|
|
|
|
CommunityStorage({
|
|
FlutterSecureStorage? secure,
|
|
bool Function(Community community)? visible,
|
|
}) : _secure = secure ?? communitySecureStorage,
|
|
_visible = visible ?? reachableInBuild;
|
|
|
|
/// An internal build reaches only its organization's community.
|
|
static bool reachableInBuild(Community community) =>
|
|
!OrganizationEnvironment.enabled ||
|
|
OrganizationEnvironment.protects(Uri.parse(community.relayUrl));
|
|
|
|
/// Load all communities this build shows. On first call, migrates legacy
|
|
/// single-community credentials if present.
|
|
Future<List<Community>> loadAll() async => (await _loadStored())
|
|
.where((c) => _visible(c) && !c.accountSyncRemoved)
|
|
.toList();
|
|
|
|
/// Device records and credential-free removal intents for account sync.
|
|
Future<List<Community>> loadForAccountSync() async =>
|
|
(await _loadStored()).where(_visible).toList();
|
|
|
|
/// Retire only the acknowledged revision; a newer intent survives.
|
|
Future<void> acknowledgeRemoval(String revision) =>
|
|
_pendingInvites.run(() async {
|
|
final all = await _loadStored();
|
|
all.removeWhere(
|
|
(c) => c.accountSyncRemoved && c.accountSyncRevision == revision,
|
|
);
|
|
await _secure.write(
|
|
key: _keyCommunities,
|
|
value: jsonEncode(all.map((c) => c.toJson()).toList()),
|
|
);
|
|
});
|
|
|
|
Future<List<Community>> _loadStored() async {
|
|
final raw = await _secure.read(key: _keyCommunities);
|
|
if (raw != null) return _decodeList(raw);
|
|
|
|
final legacyCommunities = await _secure.read(key: _legacyCommunities);
|
|
if (legacyCommunities != null) {
|
|
final communities = _decodeList(legacyCommunities);
|
|
await _saveList(communities);
|
|
final legacyActiveId = await _secure.read(key: _legacyActiveId);
|
|
if (legacyActiveId != null) await saveActiveId(legacyActiveId);
|
|
await _secure.delete(key: _legacyCommunities);
|
|
await _secure.delete(key: _legacyActiveId);
|
|
return communities;
|
|
}
|
|
|
|
// Migration: check for legacy single-community keys.
|
|
final legacyUrl = await _secure.read(key: _legacyRelayUrl);
|
|
final legacyToken = await _secure.read(key: _legacyToken);
|
|
if (legacyUrl != null && legacyToken != null) {
|
|
final legacyPubkey = await _secure.read(key: _legacyPubkey);
|
|
final legacyNsec = await _secure.read(key: _legacyNsec);
|
|
|
|
final name = Community.nameFromUrl(legacyUrl);
|
|
final community = Community.create(
|
|
name: name,
|
|
relayUrl: legacyUrl,
|
|
pubkey: legacyPubkey,
|
|
nsec: legacyNsec,
|
|
sensitiveActionPolicy: SensitiveActionPolicy.disabledByUser,
|
|
);
|
|
|
|
await _saveList([community]);
|
|
await saveActiveId(community.id);
|
|
|
|
// Delete legacy keys.
|
|
await _secure.delete(key: _legacyRelayUrl);
|
|
await _secure.delete(key: _legacyToken);
|
|
await _secure.delete(key: _legacyPubkey);
|
|
await _secure.delete(key: _legacyNsec);
|
|
|
|
return [community];
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
static final _pendingInvites = SerialQueue();
|
|
static const _pendingInvitePrefix = 'buzz_pending_invite_v1_';
|
|
|
|
static String _pendingInviteKey(String relayUrl, String code) {
|
|
final uri = Uri.parse(relayUrl);
|
|
final origin = uri
|
|
.replace(
|
|
scheme: ['https', 'wss'].contains(uri.scheme) ? 'https' : 'http',
|
|
)
|
|
.origin;
|
|
return '$_pendingInvitePrefix${sha256.convert(utf8.encode(jsonEncode([origin, code])))}';
|
|
}
|
|
|
|
/// Retain the claim identity before sending a request with uncertain outcomes.
|
|
/// A failed read/write must never generate a replacement for an unknown key.
|
|
Future<String> pendingInviteIdentity(
|
|
String relayUrl,
|
|
String code,
|
|
String Function() generate,
|
|
) => _pendingInvites.run(() async {
|
|
final key = _pendingInviteKey(relayUrl, code);
|
|
final saved = await _secure.read(key: key);
|
|
if (saved != null) return saved;
|
|
final nsec = generate();
|
|
await _secure.write(key: key, value: nsec);
|
|
if (await _secure.read(key: key) != nsec) {
|
|
throw StateError('Could not retain the pending invite identity');
|
|
}
|
|
return nsec;
|
|
});
|
|
|
|
/// Retire the journal only after the destination identity is durably saved.
|
|
Future<void> completePendingInvite(
|
|
String relayUrl,
|
|
String code,
|
|
Community community,
|
|
) => _pendingInvites.run(() async {
|
|
final saved = await loadAll();
|
|
if (!saved.any(
|
|
(item) => item.id == community.id && item.nsec == community.nsec,
|
|
)) {
|
|
return;
|
|
}
|
|
final key = _pendingInviteKey(relayUrl, code);
|
|
if (await _secure.read(key: key) == community.nsec) {
|
|
await _secure.delete(key: key);
|
|
}
|
|
});
|
|
|
|
Future<void> save(Community community) => _pendingInvites.run(() async {
|
|
final all = await loadAll();
|
|
final index = all.indexWhere((w) => w.id == community.id);
|
|
if (index >= 0) {
|
|
all[index] = community;
|
|
} else {
|
|
all.add(community);
|
|
}
|
|
await _saveList(all);
|
|
});
|
|
|
|
/// Replaces the complete stored community list in one secure-storage write.
|
|
Future<void> saveAll(List<Community> communities) =>
|
|
_pendingInvites.run(() => _saveList(communities));
|
|
|
|
/// Remove locally and retain the confirmed account edit in the same write.
|
|
/// Other identities owned by this account keep its destination entry alive.
|
|
Future<void> remove(
|
|
String id, {
|
|
String? accountSyncOwner,
|
|
}) => _pendingInvites.run(() async {
|
|
final all = await loadAll();
|
|
final removedKeys = all
|
|
.where((item) => item.id == id)
|
|
.map((item) => item.nsec)
|
|
.whereType<String>()
|
|
.toSet();
|
|
if (removedKeys.isNotEmpty) {
|
|
// Retire every journal copy before removing the saved community. If a
|
|
// deletion fails, keep that community so sign-out can safely retry.
|
|
final records = await _secure.readAll();
|
|
for (final entry in records.entries) {
|
|
if (entry.key.startsWith(_pendingInvitePrefix) &&
|
|
removedKeys.contains(entry.value)) {
|
|
await _secure.delete(key: entry.key);
|
|
if (await _secure.read(key: entry.key) != null) {
|
|
throw StateError('Could not remove the pending invite identity');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
final removed = all.where((c) => c.id == id).firstOrNull;
|
|
all.removeWhere((w) => w.id == id);
|
|
final removedUrl = removed == null
|
|
? null
|
|
: knownCommunityAddress(removed.relayUrl);
|
|
// Another identity owned by this account retains its destination row.
|
|
// Otherwise commit deletion and remote intent in the same storage write.
|
|
if (removed != null &&
|
|
removedUrl != null &&
|
|
accountSyncOwner != null &&
|
|
!all.any(
|
|
(c) =>
|
|
!c.accountSyncRemoved &&
|
|
c.accountSyncOwner == accountSyncOwner &&
|
|
knownCommunityAddress(c.relayUrl) == removedUrl,
|
|
)) {
|
|
all.add(
|
|
Community(
|
|
id: 'account-removal-${const Uuid().v4()}',
|
|
name: removed.name,
|
|
relayUrl: removedUrl,
|
|
addedAt: DateTime.now(),
|
|
accountSyncOwner: accountSyncOwner,
|
|
accountSyncRevision: const Uuid().v4(),
|
|
accountSyncRemoved: true,
|
|
),
|
|
);
|
|
}
|
|
await _saveList(all);
|
|
});
|
|
|
|
Future<String?> loadActiveId() async {
|
|
return _secure.read(key: _keyActiveId);
|
|
}
|
|
|
|
Future<void> saveActiveId(String id) async {
|
|
await _secure.write(key: _keyActiveId, value: id);
|
|
}
|
|
|
|
Future<void> clearActiveId() async {
|
|
await _secure.delete(key: _keyActiveId);
|
|
}
|
|
|
|
List<Community> _decodeList(String raw) {
|
|
final list = jsonDecode(raw) as List<dynamic>;
|
|
return list
|
|
.map((entry) => Community.fromJson(entry as Map<String, dynamic>))
|
|
.toList();
|
|
}
|
|
|
|
/// Replaces the communities this build shows, keeping the others.
|
|
Future<void> _saveList(List<Community> communities) async {
|
|
final raw = await _secure.read(key: _keyCommunities);
|
|
final hidden = raw == null
|
|
? const <Community>[]
|
|
: _decodeList(raw).where(
|
|
(item) =>
|
|
!_visible(item) ||
|
|
(item.accountSyncRemoved &&
|
|
!communities.any(
|
|
(c) =>
|
|
c.accountSyncOwner == item.accountSyncOwner &&
|
|
knownCommunityAddress(c.relayUrl) ==
|
|
knownCommunityAddress(item.relayUrl),
|
|
)),
|
|
);
|
|
final json = jsonEncode(
|
|
[...hidden, ...communities].map((item) => item.toJson()).toList(),
|
|
);
|
|
await _secure.write(key: _keyCommunities, value: json);
|
|
}
|
|
}
|