Files
buzz/mobile/lib/shared/community/community_storage.dart
Wes 75854111b8 fix(mobile): retain invite keys and reject incomplete onboarding (#8753)
Self-hosted invite claims retain the generated identity in secure
storage before the HTTP request and reuse it after a lost response or
restart. Saving or reopening an existing destination retires the
matching journal. Sign-out/removal deletes all matching pending key
copies before removing the saved community, preserving the community for
retry if cleanup fails.

Pairing verifies that relay authentication completed before
saving/activating a destination or reporting success. On iOS 16, hosted
entry permits recovery and reuse of backed-up identities, including
binding a recovered identity with a confirmed backup receipt. Paths
requiring a new secure backup explain the iOS 17 requirement before
generating or binding a new key. Self-hosted entry remains available.

### Validation

- Initial focused entry/recovery files: 83 passed, 1 skipped. Review-fix
focused storage, community, invite and hosted files: 82 passed, 1
skipped; extended invite journey: 17 passed, 1 skipped.
- Final hosted journey extension: 20 passed, including both bound and
unbound recovery with native sealing unavailable.
- Isolated mutations removing invite retention, pairing validation,
journal removal/re-entry cleanup or restoring the blanket platform gate
fail their intended regressions. Restored controls pass.
- iOS simulator build passed on the original integration base; final
native/device acceptance remains outstanding.
- Carl and three specialist reviewers found no source-review blockers at
`323cec6ea2`. `a55a246857` adds analyzer fixes, copy cleanup and the
recovered-unbound journey coverage. Reviewers did not run tests or the
app.

- Fixed a push-hook timeout in `4564b3562a`: idle serial queues now
release completed futures, avoiding scheduler retention across widget
tests while preserving in-flight ordering and failure isolation. The
existing dispatcher journey fails promptly before the fix and passes
afterward; Carl reviewed this delta with no blockers. Focused
dispatcher/invite/storage checks passed, and all 20 hosted journeys
passed with hosted auth enabled.

- Mandatory pre-push checks passed at `4564b3562a` (scope, branch skew,
file size, mobile analysis/tests and crypto package checks); GitHub head
verified at that commit.

### Remaining acceptance

Draft pending agent/device and human acceptance. Exercise interrupted
one-use invite claim and retry across restart, sign-out then reopen
without restoring the removed identity, rejected self-hosted pairing,
iOS 16 backed-up identity recovery (including binding), and iOS 16 new
setup blocked before key creation. Synthetic network/storage boundaries
do not prove native durability or live server behavior. Hosted CI
results are not claimed here.

Optional follow-ups remain outside this patch: pruning provably
unadmitted journals, malformed-record recovery, avoiding an iOS 16
dead-end device-key selection, and pre-existing removal/push-revocation
ordering.

This PR contains three existing-path fixes. The two organization-login
fixes depend on #8700 and remain separate: its stale parent conflicts
with main in unrelated relay code, and the required branch-skew hook
prevents publishing that stack unchanged. This PR does not refresh that
parent or change deployment policy.

---------

Signed-off-by: Wes <wesbillman@users.noreply.github.com>
Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
2026-10-30 10:38:24 -06:00

188 lines
6.2 KiB
Dart

import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.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;
CommunityStorage({FlutterSecureStorage? secure})
: _secure = secure ?? communitySecureStorage;
/// Load all communities. On first call, migrates legacy single-community
/// credentials if present.
Future<List<Community>> loadAll() 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) 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) => _saveList(communities);
Future<void> remove(String id) => _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');
}
}
}
}
all.removeWhere((w) => w.id == id);
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();
}
Future<void> _saveList(List<Community> communities) async {
final json = jsonEncode(communities.map((item) => item.toJson()).toList());
await _secure.write(key: _keyCommunities, value: json);
}
}