mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +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>
460 lines
15 KiB
Dart
460 lines
15 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
import 'account_identity_store.dart';
|
|
import 'builderlab_account.dart';
|
|
import 'device_identity_source.dart';
|
|
|
|
enum HostedIdentityState {
|
|
ready,
|
|
needsSelection,
|
|
needsConsent,
|
|
needsSetup,
|
|
needsBinding,
|
|
needsBackup,
|
|
mismatch,
|
|
recoveryBlocked,
|
|
needsAuthoritativeAbsence,
|
|
}
|
|
|
|
class HostedIdentityResult {
|
|
const HostedIdentityResult(
|
|
this.state, {
|
|
this.pubkey,
|
|
this.choices = const [],
|
|
this.canCreate = false,
|
|
this.generated = false,
|
|
});
|
|
final HostedIdentityState state;
|
|
final String? pubkey;
|
|
final bool canCreate;
|
|
|
|
/// True only when this resolution confirmed generating the key itself.
|
|
final bool generated;
|
|
final List<DeviceIdentityChoice> choices;
|
|
}
|
|
|
|
/// Resolves identity safely. Generation requires a separately verified
|
|
/// complete absence contract and explicit legacy-key reconciliation; neither a
|
|
/// failed recovery nor an unbound account proves there is no prior identity.
|
|
class HostedIdentityService {
|
|
HostedIdentityService({
|
|
required this.account,
|
|
required this.store,
|
|
DeviceIdentitySource? deviceIdentities,
|
|
}) : deviceIdentities = deviceIdentities ?? DeviceIdentitySource();
|
|
|
|
final DeviceIdentitySource deviceIdentities;
|
|
final BuilderlabAccountClient account;
|
|
final AccountIdentityStore store;
|
|
|
|
/// [canAdopt] may require consent before a local key occupies the account slot.
|
|
/// Cloud recovery already has a receipt and does not export a local secret.
|
|
Future<HostedIdentityResult> resolve({
|
|
bool Function()? isCurrent,
|
|
String? selectedPubkey,
|
|
bool createNew = false,
|
|
Set<String> offered = const {},
|
|
String? importNsec,
|
|
bool Function(String pubkey)? canAdopt,
|
|
}) => _resolve(
|
|
isCurrent,
|
|
selectedPubkey,
|
|
createNew,
|
|
offered,
|
|
importNsec,
|
|
canAdopt,
|
|
);
|
|
|
|
Future<HostedIdentityResult> _resolve(
|
|
bool Function()? isCurrent,
|
|
String? selectedPubkey,
|
|
bool createNew,
|
|
Set<String> offered,
|
|
String? importNsec,
|
|
bool Function(String pubkey)? canAdopt,
|
|
) async {
|
|
void checkCurrent() {
|
|
if (isCurrent != null && !isCurrent()) throw AccountFailure.unavailable;
|
|
}
|
|
|
|
checkCurrent();
|
|
final subject = account.account?.subject;
|
|
if (subject == null) throw AccountFailure.signedOut;
|
|
final store = this.store.forSubject(subject);
|
|
final local = await store.read();
|
|
final response = await account.currentIdentity();
|
|
_sameAccount(subject);
|
|
if (response['error'] != null) throw AccountFailure.invalidResponse;
|
|
final identity = response['identity'];
|
|
final String? bound;
|
|
if (identity == null) {
|
|
bound = null; // The current API omits the optional unbound identity.
|
|
} else if (identity is Map<String, dynamic>) {
|
|
bound = _pubkey(identity['pubkey_hex']);
|
|
} else {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
if (local != null && bound != null && importNsec == null) {
|
|
return _result(local, bound, subject);
|
|
}
|
|
|
|
final status = await account.post('/v1/buzz/nsec-backups/status', {});
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
final listed = status['backup_nostr_pubkeys'];
|
|
if (status['error'] != null || listed is! List) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
final statusBound = status['current_nostr_pubkey'] == null
|
|
? null
|
|
: _pubkey(status['current_nostr_pubkey']);
|
|
final statusKeys = listed.map(_pubkey).toSet();
|
|
if (statusBound != bound) throw AccountFailure.invalidResponse;
|
|
if (importNsec != null) {
|
|
final pubkey = AccountIdentityStore.publicKeyForNsec(importNsec);
|
|
// A backup arriving while setup is open must use normal recovery, which
|
|
// records the selected backup receipt before adopting its identity.
|
|
if (bound == null && statusKeys.isNotEmpty) {
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
if (bound != null && bound != pubkey) {
|
|
throw AccountIdentityFailure.mismatch;
|
|
}
|
|
if (canAdopt != null && !canAdopt(pubkey)) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsConsent,
|
|
pubkey: pubkey,
|
|
);
|
|
}
|
|
final imported = await store.create(
|
|
importNsec,
|
|
checkCurrent: () {
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
},
|
|
);
|
|
return _result(imported, bound, subject);
|
|
}
|
|
if (local != null) {
|
|
// A previously chosen recovery key may still await binding after a
|
|
// restart. Its account-scoped receipt and current backup listing preserve
|
|
// that choice even when the account also retains older identities.
|
|
final confirmedSelection =
|
|
statusKeys.contains(local.pubkey) &&
|
|
local.hasBackupFor(
|
|
backend: BuilderlabAccountClient.origin.origin,
|
|
subject: subject,
|
|
);
|
|
if (statusKeys.any((key) => key != local.pubkey) && !confirmedSelection) {
|
|
return const HostedIdentityResult(HostedIdentityState.mismatch);
|
|
}
|
|
return _result(local, bound, subject);
|
|
}
|
|
final device = await deviceIdentities.choices();
|
|
final savedAccounts = await store.identities();
|
|
final choices = [
|
|
...device,
|
|
for (final saved in savedAccounts)
|
|
if (!device.any((item) => item.pubkey == saved.pubkey))
|
|
DeviceIdentityChoice(saved.pubkey, 'Saved identity'),
|
|
];
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
// The authoritative bound key already on this device needs no remote
|
|
// decryption, even when the account retains backups of older identities.
|
|
final matchingDevice =
|
|
bound != null && choices.any((item) => item.pubkey == bound);
|
|
// An unclaimed account may keep its saved keys and start a new identity.
|
|
final unclaimed = statusKeys.isEmpty && bound == null;
|
|
if ((unclaimed && !createNew) || matchingDevice) {
|
|
final eligible = choices
|
|
.where((item) => bound == null || item.pubkey == bound)
|
|
.toList();
|
|
if (eligible.isNotEmpty) {
|
|
final chosen =
|
|
selectedPubkey ??
|
|
(bound != null && eligible.length == 1
|
|
? eligible.single.pubkey
|
|
: null);
|
|
if (!eligible.any((item) => item.pubkey == chosen)) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsSelection,
|
|
choices: eligible,
|
|
canCreate: unclaimed,
|
|
);
|
|
}
|
|
if (canAdopt != null && !canAdopt(chosen!)) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsConsent,
|
|
pubkey: chosen,
|
|
);
|
|
}
|
|
void checkSelection() {
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
}
|
|
|
|
final saved = device.any((item) => item.pubkey == chosen)
|
|
? await deviceIdentities.adopt(
|
|
chosen!,
|
|
store,
|
|
checkCurrent: checkSelection,
|
|
)
|
|
: await store.adoptSaved(chosen!, checkCurrent: checkSelection);
|
|
return _result(saved, bound, subject);
|
|
}
|
|
}
|
|
if (statusKeys.isEmpty && bound != null && !matchingDevice) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsSetup,
|
|
pubkey: bound,
|
|
);
|
|
}
|
|
if (statusBound == null && statusKeys.isEmpty) {
|
|
if (!createNew) {
|
|
return const HostedIdentityResult(
|
|
HostedIdentityState.needsSetup,
|
|
canCreate: true,
|
|
);
|
|
}
|
|
var generatedNow = false;
|
|
final generated = await store.generateIfAbsent(
|
|
onGenerated: () => generatedNow = true,
|
|
authorize: () async {
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
// Every device key must have been offered beside creation, so a
|
|
// new identity never silently passes over an unseen prior one.
|
|
final reconciled = (await deviceIdentities.choices()).every(
|
|
(item) => offered.contains(item.pubkey),
|
|
);
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
return reconciled;
|
|
},
|
|
);
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
return generated == null
|
|
? const HostedIdentityResult(
|
|
HostedIdentityState.needsAuthoritativeAbsence,
|
|
)
|
|
: _result(generated, bound, subject, generated: generatedNow);
|
|
}
|
|
|
|
final recovered = await account.post('/v1/buzz/nsec-backups/recovery', {});
|
|
_sameAccount(subject);
|
|
final candidates = openRecoveredBackups(recovered);
|
|
if (candidates == null) {
|
|
return const HostedIdentityResult(HostedIdentityState.recoveryBlocked);
|
|
}
|
|
if (candidates.isEmpty) {
|
|
return HostedIdentityResult(
|
|
bound == null
|
|
? HostedIdentityState.needsAuthoritativeAbsence
|
|
: HostedIdentityState.recoveryBlocked,
|
|
);
|
|
}
|
|
if (bound == null &&
|
|
(statusKeys.length != candidates.length ||
|
|
!statusKeys.every(candidates.containsKey))) {
|
|
return const HostedIdentityResult(HostedIdentityState.recoveryBlocked);
|
|
}
|
|
// An account binding is authoritative even when older backups contain
|
|
// other keys. Without a binding, distinct keys require an explicit choice;
|
|
// never let response ordering choose the user's identity.
|
|
final chosen =
|
|
bound ??
|
|
selectedPubkey ??
|
|
(candidates.length == 1 ? candidates.keys.single : null);
|
|
final candidate = candidates[chosen];
|
|
if (candidate == null) {
|
|
if (bound != null) {
|
|
return const HostedIdentityResult(HostedIdentityState.mismatch);
|
|
}
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsSelection,
|
|
choices: [
|
|
for (final pubkey in candidates.keys)
|
|
DeviceIdentityChoice(
|
|
pubkey,
|
|
'Use Builderlab identity',
|
|
fromCloud: true,
|
|
),
|
|
],
|
|
);
|
|
}
|
|
if (device.isNotEmpty &&
|
|
!device.any((item) => item.pubkey == candidate.keys.public) &&
|
|
selectedPubkey != candidate.keys.public) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsSelection,
|
|
choices: [
|
|
DeviceIdentityChoice(
|
|
candidate.keys.public,
|
|
'Use Builderlab identity',
|
|
fromCloud: true,
|
|
),
|
|
],
|
|
);
|
|
}
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
final saved = await store.create(
|
|
candidate.keys.nsec,
|
|
checkCurrent: () {
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
},
|
|
recoveredBackup: BackupReceipt(
|
|
backend: BuilderlabAccountClient.origin.origin,
|
|
subject: subject,
|
|
pubkey: candidate.keys.public,
|
|
backupId: candidate.backupId,
|
|
),
|
|
);
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
return _result(saved, bound, subject);
|
|
}
|
|
|
|
/// After a definitive binding rejection of [pubkey], release this account's
|
|
/// unconfirmed copy so the user can choose again. Rechecks that the account
|
|
/// is still unbound with no backups and that the key survives elsewhere;
|
|
/// returns false and keeps the slot otherwise.
|
|
Future<bool> releaseRejected(
|
|
String pubkey, {
|
|
required String subject,
|
|
bool Function()? isCurrent,
|
|
}) async {
|
|
void checkCurrent() {
|
|
if (isCurrent != null && !isCurrent()) throw AccountFailure.unavailable;
|
|
}
|
|
|
|
checkCurrent();
|
|
_sameAccount(subject);
|
|
final store = this.store.forSubject(subject);
|
|
final local = await store.read();
|
|
if (local == null) return true;
|
|
if (local.pubkey != pubkey || local.backup != null) return false;
|
|
final current = await account.currentIdentity();
|
|
_sameAccount(subject);
|
|
if (current['error'] != null) throw AccountFailure.invalidResponse;
|
|
if (current['identity'] != null) return false;
|
|
final status = await account.post('/v1/buzz/nsec-backups/status', {});
|
|
_sameAccount(subject);
|
|
final listed = status['backup_nostr_pubkeys'];
|
|
if (status['error'] != null || listed is! List) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
if (status['current_nostr_pubkey'] != null || listed.isNotEmpty) {
|
|
return false;
|
|
}
|
|
checkCurrent();
|
|
return store.releaseUnconfirmed(
|
|
pubkey,
|
|
heldElsewhere: deviceIdentities.holds,
|
|
checkCurrent: () {
|
|
_sameAccount(subject);
|
|
checkCurrent();
|
|
},
|
|
);
|
|
}
|
|
|
|
HostedIdentityResult _result(
|
|
AccountIdentitySnapshot local,
|
|
String? bound,
|
|
String subject, {
|
|
bool generated = false,
|
|
}) {
|
|
_sameAccount(subject);
|
|
if (bound != null && bound != local.pubkey) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.mismatch,
|
|
pubkey: local.pubkey,
|
|
);
|
|
}
|
|
if (bound == null) {
|
|
return HostedIdentityResult(
|
|
HostedIdentityState.needsBinding,
|
|
pubkey: local.pubkey,
|
|
generated: generated,
|
|
);
|
|
}
|
|
return HostedIdentityResult(
|
|
local.hasBackupFor(
|
|
backend: BuilderlabAccountClient.origin.origin,
|
|
subject: subject,
|
|
)
|
|
? HostedIdentityState.ready
|
|
: HostedIdentityState.needsBackup,
|
|
pubkey: local.pubkey,
|
|
);
|
|
}
|
|
|
|
void _sameAccount(String subject) {
|
|
if (account.account?.subject != subject) {
|
|
throw AccountFailure.differentAccount;
|
|
}
|
|
}
|
|
|
|
static String _pubkey(dynamic value) {
|
|
if (value is! String || !RegExp(r'^[a-fA-F0-9]{64}$').hasMatch(value)) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
return value.toLowerCase();
|
|
}
|
|
}
|
|
|
|
/// A recovered backup's key, derived from its secret, and its backup id.
|
|
typedef RecoveredBackup = ({nostr.Keys keys, String backupId});
|
|
|
|
/// Validates an `/v1/buzz/nsec-backups/recovery` response, keyed by the public
|
|
/// key derived from each secret, never by the advertised one. Null when any
|
|
/// backup failed to open; throws [AccountFailure.invalidResponse] when the
|
|
/// response is malformed, so nothing is stored from a partial result.
|
|
Map<String, RecoveredBackup>? openRecoveredBackups(
|
|
Map<String, dynamic> recovered,
|
|
) {
|
|
final backups = recovered['backups'];
|
|
final failed = recovered['failed_backup_ids'];
|
|
if (recovered['error'] != null ||
|
|
backups is! List ||
|
|
failed is! List ||
|
|
failed.any((id) => id is! String)) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
if (failed.isNotEmpty) return null;
|
|
final candidates = <String, RecoveredBackup>{};
|
|
try {
|
|
for (final backup in backups) {
|
|
if (backup is! Map<String, dynamic>) throw const FormatException();
|
|
final secret = backup['secret_key'];
|
|
final backupId = backup['backup_id'];
|
|
if (secret is! String ||
|
|
!RegExp(r'^[A-Za-z0-9_-]{43}$').hasMatch(secret) ||
|
|
backupId is! String ||
|
|
backupId.isEmpty) {
|
|
throw const FormatException();
|
|
}
|
|
final bytes = base64Url.decode(base64Url.normalize(secret));
|
|
if (bytes.length != 32) throw const FormatException();
|
|
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
|
final keys = AccountIdentityStore.keysForHex(hex);
|
|
if (keys.public !=
|
|
HostedIdentityService._pubkey(backup['nostr_pubkey'])) {
|
|
throw const FormatException();
|
|
}
|
|
candidates.putIfAbsent(
|
|
keys.public,
|
|
() => (keys: keys, backupId: backupId),
|
|
);
|
|
}
|
|
} catch (_) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
return candidates;
|
|
}
|