mirror of
https://github.com/block/buzz.git
synced 2026-11-28 12:12:04 +00:00
Existing mobile identities entering the Builderlab hosted flow now require confirmation before the app reserves the account’s identity slot, binds the identity, or uploads its secret key. Cancelling leaves saved community keys usable and allows another identity to be selected, including after restart. Imported keys remain tentative until approval; paired keys remain safely retained outside the account slot. The confirmation shows the receiving account’s verified email and public key, explains that Builderlab can decrypt the backup and signed-in account users can recover it, and discloses that the app cannot change the linked identity later. **Cancel setup** stops future work without claiming to undo earlier binding or an upload whose acknowledgement was lost. The user can sign out; missing account identification blocks confirmation. Browser-initiated binding uses **Link and continue**, with explicit bind-only wording and no upload. Fresh keys generated in the current hosted attempt use ordinary onboarding without an extra backup prompt. Interrupted attempts without a confirmed backup ask again; approval is deliberately not persisted or carried across retries, cancellation, restart, account changes, or a replaced flow. Confirmed matching backup receipts skip the backup prompt. Cloud recovery and organization-managed backup are separate flows and are not changed here; this PR does not resolve server-side consent or recovery-authorization policy. Updated against main through `ce42853982` (#9418). Integration commit `dfb29fe5e7` includes the landed Hickory security fix and the shared workflow-test/runner repair. The consent implementation is unchanged from Carl’s reviewed `e11025ebed`; the CI merge preserves its configured public consent journeys. Validation at `e11025ebed`: 96 focused tests across eight files passed with public hosted domains configured; Flutter analysis passed. In an isolated source/Git/build copy, removing pre-adoption consent, bypassing the upload gate, and removing stale-confirmation checks each failed the consent journeys; restoring the code passed. Carl’s independent source review found no blockers. Mandatory hooks and hosted mobile CI passed, including both consent journeys in the configured public lane. Integration validation at `dfb29fe5e7`: 99 focused tests passed; one additional fullscreen-onboarding test failed its background community-admission assertion. An isolated clean-main control at `ce42853982` reproduces the same failure with the same expected/actual values. All consent journeys passed. Required commit and push hooks passed, including mobile analysis and the broader default mobile suite. Hosted CI is green at `dfb29fe5e7` ([run 43320753801](https://github.com/block/buzz/actions/runs/43320753801)). Security and the previously failing Rust/workflow gates now pass. The Mobile Checks log confirms both consent journeys executed successfully; that run has no pending checks. Review follow-up `ac9ac9be35`, integrated with main `279a31daac` at current head `1acfd2dff6`, is test-only: the browser journey now restores a saved account key without a receipt, cancels without binding, restarts and requires explicit approval before `/verify`. Both consent journeys passed again after integration using the updated CI settings. Disabling only the production bind gate in an isolated source/Git/build copy now fails the added step; restoring it passes. Mandatory commit/push hooks passed. Hosted CI is green at `1acfd2dff6` ([run 43343333843](https://github.com/block/buzz/actions/runs/43343333843)); no failing or pending checks remain. The Mobile Checks log confirms both consent journeys executed successfully, including the extended browser-binding journey. Carl’s latest review on `dfb29fe5e7` found no production blockers; its recommended test gap is addressed by this follow-up. Native-device and human acceptance have not been recorded here; the author’s ready-for-review setting is preserved. Try it: with two saved self-hosted keys, connect to Builderlab, select A, cancel, restart, then select B. Check the receiving account and key before approval. Repeat with an imported/paired key and a browser bind link; cancel must not reserve or bind the new selection. After an interrupted upload, cancellation must describe that earlier effects may remain. Confirm that ordinary brand-new onboarding has no extra backup step. --------- Signed-off-by: Wes <wesbillman@users.noreply.github.com> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
440 lines
15 KiB
Dart
440 lines
15 KiB
Dart
import '../storage/serial_queue.dart';
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
import '../crypto/event_signing.dart';
|
|
import '../storage/secure_storage.dart';
|
|
|
|
import 'hosted_environment.dart';
|
|
|
|
/// Safe failures: never include a secret or the storage/plugin exception.
|
|
enum AccountIdentityFailure {
|
|
unreadable,
|
|
invalidKey,
|
|
occupied,
|
|
absent,
|
|
mismatch,
|
|
}
|
|
|
|
/// Evidence from a successful backup/recovery, not merely an attempted upload.
|
|
class BackupReceipt {
|
|
BackupReceipt({
|
|
required this.backend,
|
|
required this.subject,
|
|
required this.pubkey,
|
|
required this.backupId,
|
|
}) {
|
|
final uri = Uri.tryParse(backend);
|
|
if (uri == null ||
|
|
uri.scheme != 'https' ||
|
|
uri.host.isEmpty ||
|
|
uri.origin != backend ||
|
|
subject.isEmpty ||
|
|
backupId.isEmpty ||
|
|
!RegExp(r'^[0-9a-f]{64}$').hasMatch(pubkey)) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
}
|
|
|
|
final String backend;
|
|
final String subject;
|
|
final String pubkey;
|
|
final String backupId;
|
|
|
|
Map<String, String> _json() => {
|
|
'backend': backend,
|
|
'subject': subject,
|
|
'pubkey': pubkey,
|
|
'backup_id': backupId,
|
|
};
|
|
|
|
static BackupReceipt _decode(dynamic value) => BackupReceipt(
|
|
backend: value['backend'] as String,
|
|
subject: value['subject'] as String,
|
|
pubkey: value['pubkey'] as String,
|
|
backupId: value['backup_id'] as String,
|
|
);
|
|
}
|
|
|
|
/// Public facts only. Signing material never enters observable UI state.
|
|
class AccountIdentitySnapshot {
|
|
const AccountIdentitySnapshot(this.pubkey, this.backup);
|
|
final String pubkey;
|
|
final BackupReceipt? backup;
|
|
|
|
bool hasBackupFor({required String backend, required String subject}) =>
|
|
// Retired walkthrough receipts must never authorize real admission.
|
|
!(backup?.backupId.startsWith('debug-simulated-backup:') ?? false) &&
|
|
backup?.backend == backend &&
|
|
backup?.subject == subject &&
|
|
backup?.pubkey == pubkey;
|
|
}
|
|
|
|
/// The key a backup protects, and where its confirmed receipt is recorded.
|
|
abstract interface class BackupIdentity {
|
|
Future<AccountIdentitySnapshot?> read();
|
|
|
|
/// Service-only signing boundary; never return keys from [operation].
|
|
Future<T> withKeys<T>(Future<T> Function(nostr.Keys keys) operation);
|
|
|
|
Future<void> confirmBackup(BackupReceipt receipt);
|
|
}
|
|
|
|
/// Create-only AccountKey slots per backend and authenticated subject. Exact-key retries
|
|
/// are idempotent; they never discard or replace an existing backup receipt. Does not choose or mutate legacy
|
|
/// community identities. Migration must explicitly resolve a candidate first.
|
|
///
|
|
/// Key and recovered receipt share one secure record, so restart cannot observe
|
|
/// a saved recovered key without its receipt. All instances serialize within the
|
|
/// app isolate. Native extensions/other isolates must not write this slot:
|
|
/// FlutterSecureStorage does not provide a cross-process compare-and-set.
|
|
class AccountIdentityStore implements BackupIdentity {
|
|
AccountIdentityStore({FlutterSecureStorage? storage, String? subject})
|
|
: _storage = storage ?? accountSecureStorage,
|
|
_subject = subject,
|
|
_pairingPubkey = null;
|
|
|
|
AccountIdentityStore._paired(this._storage, this._pairingPubkey)
|
|
: _subject = null;
|
|
|
|
final String? _subject;
|
|
final String? _pairingPubkey;
|
|
|
|
/// Retain a transferred key before account login without occupying any
|
|
/// account slot or replacing a previous pending transfer.
|
|
AccountIdentityStore forPairing(String pubkey) {
|
|
if (!RegExp(r'^[0-9a-f]{64}$').hasMatch(pubkey)) {
|
|
throw AccountIdentityFailure.invalidKey;
|
|
}
|
|
return AccountIdentityStore._paired(_storage, pubkey);
|
|
}
|
|
|
|
/// Pin an operation to its authenticated account, never a mutable session.
|
|
AccountIdentityStore forSubject(String subject) {
|
|
if (subject.isEmpty) throw AccountIdentityFailure.mismatch;
|
|
return AccountIdentityStore(storage: _storage, subject: subject);
|
|
}
|
|
|
|
String get _key => _pairingPubkey != null
|
|
? '${storageKey}_pairing_$_pairingPubkey'
|
|
: _subject == null
|
|
? storageKey
|
|
: '${storageKey}_subject_${base64Url.encode(utf8.encode(_subject))}';
|
|
|
|
static final storageKey =
|
|
'buzz_account_identity_${HostedEnvironment.origin.host.replaceAll('.', '_')}_v1';
|
|
static final _queue = SerialQueue();
|
|
final FlutterSecureStorage _storage;
|
|
// Public lookup hints from the choices shown by this store. Always reread
|
|
// and validate the record; never retain signing material across selection.
|
|
final _savedLocations = <String, String>{};
|
|
|
|
Future<T> _serialized<T>(Future<T> Function() operation) {
|
|
final result = _queue.run(() => operation());
|
|
return result;
|
|
}
|
|
|
|
@override
|
|
Future<AccountIdentitySnapshot?> read() => _serialized(() async {
|
|
final record = await _read();
|
|
return record?.snapshot;
|
|
});
|
|
|
|
Future<AccountIdentitySnapshot> create(
|
|
String nsec, {
|
|
BackupReceipt? recoveredBackup,
|
|
void Function()? checkCurrent,
|
|
}) => _serialized(() async {
|
|
checkCurrent?.call();
|
|
// Read before parsing/generating any candidate: corrupt != absent.
|
|
final existing = await _read();
|
|
final pubkey = publicKeyForNsec(nsec);
|
|
if (existing != null) {
|
|
if (existing.pubkey != pubkey) throw AccountIdentityFailure.occupied;
|
|
if (recoveredBackup == null) return existing.snapshot;
|
|
if (existing.backup != null) {
|
|
if (jsonEncode(existing.backup!._json()) !=
|
|
jsonEncode(recoveredBackup._json())) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
return existing.snapshot;
|
|
}
|
|
}
|
|
if (recoveredBackup != null && recoveredBackup.pubkey != pubkey) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
checkCurrent?.call();
|
|
final record = _Record(nsec, pubkey, recoveredBackup);
|
|
await _write(record);
|
|
return record.snapshot;
|
|
});
|
|
|
|
/// Authorization runs under the identity writer lock and must not reenter it.
|
|
/// A completed but unacknowledged write is reused on retry, never regenerated.
|
|
/// [onGenerated] runs only after this call confirmed a newly generated key.
|
|
Future<AccountIdentitySnapshot?> generateIfAbsent({
|
|
required Future<bool> Function() authorize,
|
|
void Function()? onGenerated,
|
|
}) => _serialized(() async {
|
|
final existing = await _read();
|
|
if (existing != null) return existing.snapshot;
|
|
if (!await authorize()) return null;
|
|
final keys = nostr.Keys.generate();
|
|
final record = _Record(keys.nsec, keys.public, null);
|
|
await _write(record);
|
|
onGenerated?.call();
|
|
return record.snapshot;
|
|
});
|
|
|
|
@override
|
|
Future<AccountIdentitySnapshot> confirmBackup(BackupReceipt receipt) =>
|
|
_serialized(() async {
|
|
final record = await _read();
|
|
if (record == null) throw AccountIdentityFailure.absent;
|
|
if (record.pubkey != receipt.pubkey) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
final updated = _Record(record.nsec, record.pubkey, receipt);
|
|
await _write(updated);
|
|
return updated.snapshot;
|
|
});
|
|
|
|
static bool _isIdentityKey(String key) =>
|
|
key == storageKey ||
|
|
key.startsWith('${storageKey}_subject_') ||
|
|
key.startsWith('${storageKey}_pairing_');
|
|
|
|
AccountIdentityStore _atKey(String key) => key == storageKey
|
|
? AccountIdentityStore(storage: _storage)
|
|
: key.startsWith('${storageKey}_pairing_')
|
|
? forPairing(key.substring('${storageKey}_pairing_'.length))
|
|
: forSubject(
|
|
utf8.decode(
|
|
base64Url.decode(key.substring('${storageKey}_subject_'.length)),
|
|
),
|
|
);
|
|
|
|
// Android readAll decrypts unrelated entries too. An unrelated broken entry
|
|
// must not prevent reading the legacy/current slot or an explicitly named key.
|
|
Future<Set<String>> _identityKeys({String? pubkey}) async {
|
|
try {
|
|
return (await _storage.readAll()).keys.where(_isIdentityKey).toSet();
|
|
} catch (_) {
|
|
// A partial inventory cannot establish absence or authorize generation.
|
|
if (pubkey == null) throw AccountIdentityFailure.unreadable;
|
|
return {storageKey, _key, forPairing(pubkey)._key};
|
|
}
|
|
}
|
|
|
|
/// Saved account keys offered for explicit reuse, including pre-scope keys.
|
|
Future<List<AccountIdentitySnapshot>> identities() => _serialized(() async {
|
|
final keys = await _identityKeys();
|
|
final identities = <String, AccountIdentitySnapshot>{};
|
|
final locations = <String, String>{};
|
|
for (final key in keys) {
|
|
final record = await _atKey(key)._read();
|
|
if (record != null) {
|
|
identities[record.pubkey] = record.snapshot;
|
|
locations[record.pubkey] = key;
|
|
}
|
|
}
|
|
_savedLocations
|
|
..clear()
|
|
..addAll(locations);
|
|
return identities.values.toList();
|
|
});
|
|
|
|
/// Release this slot's unconfirmed copy of [pubkey] so a definitively
|
|
/// rejected choice can be made again. Refuses (false) unless another saved
|
|
/// slot or [heldElsewhere] holds the same key; never releases a receipt.
|
|
/// An already-empty slot counts as released, so a retry after a partial
|
|
/// failure or restart converges.
|
|
Future<bool> releaseUnconfirmed(
|
|
String pubkey, {
|
|
required Future<bool> Function(String nsec) heldElsewhere,
|
|
required void Function() checkCurrent,
|
|
}) => _serialized(() async {
|
|
final record = await _read();
|
|
if (record == null) return true;
|
|
if (record.pubkey != pubkey || record.backup != null) return false;
|
|
var kept = false;
|
|
for (final key in await _identityKeys(pubkey: pubkey)) {
|
|
if (key == _key) continue;
|
|
try {
|
|
if ((await _atKey(key)._read())?.nsec == record.nsec) kept = true;
|
|
} on AccountIdentityFailure {
|
|
// An unreadable slot is never evidence of a copy.
|
|
}
|
|
}
|
|
if (!kept && !await heldElsewhere(record.nsec)) return false;
|
|
checkCurrent();
|
|
try {
|
|
await _storage.delete(key: _key);
|
|
} catch (_) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
if (await _storage.read(key: _key) != null) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
return true;
|
|
});
|
|
|
|
/// Copy a chosen saved account key without deleting its original owner.
|
|
Future<AccountIdentitySnapshot> adoptSaved(
|
|
String pubkey, {
|
|
required void Function() checkCurrent,
|
|
}) async => create(await _savedNsec(pubkey), checkCurrent: checkCurrent);
|
|
|
|
/// Supplies only the explicitly selected saved key to an admission service.
|
|
Future<T> withSavedIdentity<T>(
|
|
String pubkey,
|
|
Future<T> Function(String nsec) operation,
|
|
) async => operation(await _savedNsec(pubkey));
|
|
|
|
Future<String> _savedNsec(String pubkey) => _serialized(() async {
|
|
try {
|
|
final location = _savedLocations[pubkey];
|
|
if (location != null) {
|
|
final record = await _atKey(location)._read();
|
|
if (record?.pubkey == pubkey) return record!.nsec;
|
|
}
|
|
final keys = await _identityKeys(pubkey: pubkey);
|
|
for (final key in keys) {
|
|
final record = await _atKey(key)._read();
|
|
if (record?.pubkey == pubkey) return record!.nsec;
|
|
}
|
|
} catch (_) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
throw AccountIdentityFailure.absent;
|
|
});
|
|
|
|
/// Service-only signing/export boundary. Do not return keys from this closure
|
|
/// to a provider/widget. Avoid reentering this store inside the callback.
|
|
@override
|
|
Future<T> withKeys<T>(Future<T> Function(nostr.Keys keys) operation) =>
|
|
_serialized(() async {
|
|
final record = await _read();
|
|
if (record == null) throw AccountIdentityFailure.absent;
|
|
return operation(keysForHex(_nsecHex(record.nsec)));
|
|
});
|
|
|
|
Future<_Record?> _read() async {
|
|
try {
|
|
final raw = await _storage.read(key: _key);
|
|
// Preserve the old record. Only a receipt for this exact account can
|
|
// authorize its automatic migration; other keys remain explicit choices.
|
|
if (raw == null && _subject != null) {
|
|
final legacy = await AccountIdentityStore(storage: _storage)._read();
|
|
if (legacy?.backup?.subject == _subject &&
|
|
legacy?.backup?.backend == HostedEnvironment.origin.origin) {
|
|
await _write(legacy!);
|
|
return legacy;
|
|
}
|
|
}
|
|
if (raw == null) return null;
|
|
final value = jsonDecode(raw) as Map<String, dynamic>;
|
|
if (value['version'] != 1) throw AccountIdentityFailure.unreadable;
|
|
final nsec = value['nsec'] as String;
|
|
final pubkey = publicKeyForNsec(nsec);
|
|
if (value['pubkey'] != pubkey ||
|
|
(_pairingPubkey != null && _pairingPubkey != pubkey)) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
final receipt = value['backup'] == null
|
|
? null
|
|
: BackupReceipt._decode(value['backup']);
|
|
if (receipt != null &&
|
|
(receipt.pubkey != pubkey ||
|
|
(_subject != null && receipt.subject != _subject))) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
return _Record(nsec, pubkey, receipt);
|
|
} catch (_) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
}
|
|
|
|
Future<void> _write(_Record record) async {
|
|
if ((_pairingPubkey != null && record.pubkey != _pairingPubkey) ||
|
|
(_subject != null &&
|
|
record.backup != null &&
|
|
record.backup!.subject != _subject)) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
final raw = jsonEncode({
|
|
'version': 1,
|
|
'nsec': record.nsec,
|
|
'pubkey': record.pubkey,
|
|
'backup': record.backup?._json(),
|
|
});
|
|
try {
|
|
await _storage.write(key: _key, value: raw);
|
|
if (await _storage.read(key: _key) != raw) {
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
} catch (_) {
|
|
// A write may have completed: caller must reread, never replace/recreate.
|
|
throw AccountIdentityFailure.unreadable;
|
|
}
|
|
}
|
|
|
|
/// Validate a candidate without exposing signing material to the UI.
|
|
///
|
|
/// Derives the public key with libsecp256k1. This runs on every relay auth
|
|
/// assertion, where the pure-Dart derivation in `nostr.Keys` cost ~7 ms.
|
|
static String publicKeyForNsec(String nsec) =>
|
|
derivePublicKeyHex(_validSecretHex(_nsecHex(nsec)));
|
|
|
|
/// Validated signing keys for an nsec held outside this store.
|
|
static nostr.Keys keysForNsec(String nsec) => keysForHex(_nsecHex(nsec));
|
|
|
|
/// Rejects invalid secp256k1 scalars before constructing a signing key.
|
|
///
|
|
/// `nostr.Keys` always derives the public key in pure Dart and cannot take
|
|
/// a precomputed one, so this stays for the rare callers that need a
|
|
/// `nostr.Keys` object.
|
|
static nostr.Keys keysForHex(String hex) => nostr.Keys(_validSecretHex(hex));
|
|
|
|
static String _validSecretHex(String hex) {
|
|
if (!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(hex)) {
|
|
throw AccountIdentityFailure.invalidKey;
|
|
}
|
|
final scalar = BigInt.parse(hex, radix: 16);
|
|
final order = BigInt.parse(
|
|
'fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141',
|
|
radix: 16,
|
|
);
|
|
if (scalar <= BigInt.zero || scalar >= order) {
|
|
throw AccountIdentityFailure.invalidKey;
|
|
}
|
|
return hex;
|
|
}
|
|
|
|
static String _nsecHex(String nsec) {
|
|
try {
|
|
final decoded = nostr.Nip19.decode(payload: nsec);
|
|
if (decoded.prefix != nostr.Nip19Prefix.nsec ||
|
|
!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(decoded.data)) {
|
|
throw AccountIdentityFailure.invalidKey;
|
|
}
|
|
return decoded.data;
|
|
} catch (_) {
|
|
throw AccountIdentityFailure.invalidKey;
|
|
}
|
|
}
|
|
}
|
|
|
|
class _Record {
|
|
const _Record(this.nsec, this.pubkey, this.backup);
|
|
final String nsec;
|
|
final String pubkey;
|
|
final BackupReceipt? backup;
|
|
AccountIdentitySnapshot get snapshot =>
|
|
AccountIdentitySnapshot(pubkey, backup);
|
|
}
|