mirror of
https://github.com/block/buzz.git
synced 2026-11-06 09:21:45 +00:00
## Summary This fixes a dead end in mobile Builderlab sign-in. A new account (unbound, with no backups) on a device that already had saved identities could only pick one of those identities. Any saved key forced the picker, and creating a key required the device to have none. If the service then definitively rejected binding the chosen key, the app showed "Let's try that again" with no way forward: the chosen key stayed in the account's slot, so every retry and every launch re-sent the same rejected bind. For an unclaimed account, the picker now also offers **Create a new identity**: - Creation writes only this account's empty identity slot, so every saved and device key is kept. - Creation is offered only when every current device key was among the choices shown, so a new identity never silently passes over a key the user didn't see. - Bound accounts, accounts with backups, pairing and pending import never offer it. When binding a chosen key is definitively rejected, the blocked screen offers **Choose a different identity**: - It appears only for a 400, 404, 409 or 422 from `/verify` in the current attempt, for the current account and pubkey, and never during pairing, whose transferred key is the only choice. Evidence from an earlier attempt is cleared before each bind. A challenge rejection, a 403, a 503 or any other ambiguous failure offers nothing. - Before releasing the slot, it rechecks the account: still unbound (`/current` and status), no backups, the same subject, and a slot that still holds that pubkey without a receipt. - It releases the slot only when another durable copy of the same key exists (the device inventory or another account slot), then verifies the slot is empty. No key is deleted: only the account's pointer to the rejected choice is cleared. A failed or refused release keeps the slot and the choice, so it can be retried in place or after a restart. - After release, the picker runs again and offers the saved keys plus creation. The recovery code lives in `hosted_flow_identity_recovery.dart`, a part of `hosted_flow.dart`, to stay within the mobile file-size limit. ### Related issue None found. ### Testing **Physical iPhone, a signed release build of `1fb633d55` installed over the existing app (keychain and saved identities kept):** a saved identity was rejected, then Choose a different identity, the picker, Create a new identity and Join your community. Joining then completed. This head differs from `1fb633d55` only in the guards for leaving, pairing and a failed or refused release listed below, which this journey does not reach, and in no UI code. The status of that phone's original rejection was not captured, so it is not confirmed to be one of the rejections above. The 409 case is covered by tests. **Tests (red on `main`, green here):** - Identity service and store: creation beside offered keys; refusal for unseen or partly offered device keys; release when another copy exists; refusal for a sole copy, a binding, a backup, a receipt, another account or an unusable recheck; failed delete and retry; a cancelled attempt. - Onboarding journeys: create beside saved keys; select, rejected bind, restart, choose a different identity, create and bind; ambiguous 503 and 403 failures; challenge rejection and stale evidence. - Release boundaries: an account switch at `/current`, at status, or between the recheck and the delete; cancelling between the recheck and the delete; leaving the picker before a late creation; an unreadable device inventory; leaving while a release is in flight; a failed delete retried in place and after a restart; a release refused because the inventory is unreadable, then retried in place; a rejected paired key. Each keeps every key, leaves the new account's slot untouched and leaves a cancelled flow idle, and a retry converges. - Mutating the creation guard, the generation check, the binding recheck, the store's receipt check, the account and cancellation checks before the delete, or the device-inventory error handling fails a test. #### Screenshots Physical iPhone at `1fb633d55` (frames from a screen recording; saved public keys redacted): | Rejected bind | After Choose a different identity | After Create a new identity | | --- | --- | --- | |  |  |  | Widget-test renders of the same screens (the real `HostedFlow` against a mocked account service, with a fixture key; the square at the top left is the test renderer's placeholder for an asset): | Picker on an unclaimed account | Rejected bind | | --- | --- | |  |  | 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: John Tennant <jtennant@squareup.com> Co-authored-by: Xander <ff30c859b96bd5233ffaf5d071200458f1274bd0dab03589214cf1055198491d@buzz.block.builderlab.xyz> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
136 lines
4.8 KiB
Dart
136 lines
4.8 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
|
|
import '../storage/secure_storage.dart';
|
|
|
|
import 'account_identity_store.dart';
|
|
import '../profile/user_profile.dart';
|
|
import '../relay/relay_provider.dart';
|
|
|
|
/// Public identity choices; never contains private signing material.
|
|
class DeviceIdentityChoice {
|
|
const DeviceIdentityChoice(this.pubkey, this.label, {this.fromCloud = false});
|
|
final String pubkey;
|
|
final String label;
|
|
final bool fromCloud;
|
|
}
|
|
|
|
/// Read-only inventory, including legacy records hidden by a newer community list.
|
|
/// Do not call CommunityStorage.loadAll here: it migrates and deletes records.
|
|
class DeviceIdentitySource {
|
|
DeviceIdentitySource({FlutterSecureStorage? storage})
|
|
: _storage = storage ?? communitySecureStorage;
|
|
final FlutterSecureStorage _storage;
|
|
|
|
Future<List<DeviceIdentityChoice>> choices() async => [
|
|
for (final entry in (await _read()).entries)
|
|
DeviceIdentityChoice(entry.key, entry.value.label),
|
|
];
|
|
|
|
/// Read profile metadata only from communities already saved for this key.
|
|
/// A failed/offline community does not prevent trying another saved source.
|
|
Future<UserProfile?> loadProfile(
|
|
String pubkey,
|
|
Future<UserProfile?> Function(RelayConfig config) fetch,
|
|
) async {
|
|
final seen = <String>{};
|
|
for (final key in ['buzz_communities', 'buzz_workspaces']) {
|
|
final raw = await _storage.read(key: key);
|
|
if (raw == null) continue;
|
|
for (final record in jsonDecode(raw) as List) {
|
|
try {
|
|
final value = record as Map<String, dynamic>;
|
|
final nsec = value['nsec'] as String?;
|
|
final relay = value['relayUrl'] as String?;
|
|
if (nsec == null ||
|
|
relay == null ||
|
|
AccountIdentityStore.publicKeyForNsec(nsec) != pubkey ||
|
|
(value['pubkey'] != null && value['pubkey'] != pubkey)) {
|
|
continue;
|
|
}
|
|
final config = RelayConfig(baseUrl: relay, nsec: nsec);
|
|
if (!seen.add(config.baseUrl)) continue;
|
|
if (seen.length > 3) return null;
|
|
final profile = await fetch(config);
|
|
if (profile != null) return profile;
|
|
} catch (_) {
|
|
// Metadata is optional; never alter keys or block identity selection.
|
|
}
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Whether a saved community or previous device record holds exactly [nsec].
|
|
Future<bool> holds(String nsec) async =>
|
|
(await _read())[AccountIdentityStore.publicKeyForNsec(nsec)]?.nsec ==
|
|
nsec;
|
|
|
|
/// Reread and validate the chosen key immediately before create-only adoption.
|
|
Future<AccountIdentitySnapshot> adopt(
|
|
String pubkey,
|
|
AccountIdentityStore store, {
|
|
required void Function() checkCurrent,
|
|
}) async {
|
|
final candidate = (await _read())[pubkey];
|
|
if (candidate == null) throw AccountIdentityFailure.absent;
|
|
checkCurrent();
|
|
return store.create(candidate.nsec, checkCurrent: checkCurrent);
|
|
}
|
|
|
|
/// Supplies a freshly validated saved identity only to an admission service.
|
|
Future<T> withIdentity<T>(
|
|
String pubkey,
|
|
Future<T> Function(String nsec) operation,
|
|
) async {
|
|
final candidate = (await _read())[pubkey];
|
|
if (candidate == null) throw AccountIdentityFailure.absent;
|
|
return operation(candidate.nsec);
|
|
}
|
|
|
|
Future<Map<String, ({String nsec, String label})>> _read() async {
|
|
try {
|
|
final result = <String, ({String nsec, String label})>{};
|
|
final labels = <String, Set<String>>{};
|
|
void add(dynamic nsec, dynamic advertised, String label) {
|
|
if (nsec == null) {
|
|
// Token-only legacy communities legitimately have no private key.
|
|
return;
|
|
}
|
|
if (nsec is! String) throw AccountIdentityFailure.unreadable;
|
|
final pubkey = AccountIdentityStore.publicKeyForNsec(nsec);
|
|
if (advertised != null && advertised != pubkey) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
final names = labels.putIfAbsent(pubkey, () => <String>{})..add(label);
|
|
result[pubkey] = (nsec: nsec, label: names.join(', '));
|
|
}
|
|
|
|
for (final key in ['buzz_communities', 'buzz_workspaces']) {
|
|
final raw = await _storage.read(key: key);
|
|
if (raw == null) continue;
|
|
final records = jsonDecode(raw) as List;
|
|
for (final record in records) {
|
|
final value = record as Map<String, dynamic>;
|
|
add(
|
|
value['nsec'],
|
|
value['pubkey'],
|
|
(value['name'] as String?)?.trim().isNotEmpty == true
|
|
? (value['name'] as String).trim()
|
|
: 'Saved community',
|
|
);
|
|
}
|
|
}
|
|
add(
|
|
await _storage.read(key: 'buzz_nsec'),
|
|
await _storage.read(key: 'buzz_pubkey'),
|
|
'Previous device identity',
|
|
);
|
|
return result;
|
|
} catch (_) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
}
|
|
}
|