mirror of
https://github.com/block/buzz.git
synced 2026-11-24 10:12:19 +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>
638 lines
22 KiB
Dart
638 lines
22 KiB
Dart
import '../storage/serial_queue.dart';
|
|
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:buzz/shared/http/app_http_client.dart';
|
|
|
|
import '../storage/secure_storage.dart';
|
|
|
|
import 'hosted_environment.dart';
|
|
import 'bounded_http_response.dart';
|
|
import '../relay/relay_session.dart';
|
|
import 'account_identity_store.dart';
|
|
|
|
/// Errors contain no response bodies, credentials, or recovered private keys.
|
|
/// Only [AccountFailure.signedOut] means "no session"; every other failure
|
|
/// leaves the account state unknown.
|
|
enum AccountFailure {
|
|
signedOut,
|
|
denied,
|
|
accountSetupRequired,
|
|
unavailable,
|
|
invalidResponse,
|
|
storage,
|
|
|
|
/// Login completed for a different account than the stored session.
|
|
differentAccount,
|
|
|
|
/// The server definitively refused this request (400/404/409/422); sending
|
|
/// it again unchanged cannot succeed.
|
|
rejected,
|
|
}
|
|
|
|
class BuilderlabAccount {
|
|
const BuilderlabAccount({
|
|
required this.subject,
|
|
required this.expiresAt,
|
|
this.email,
|
|
this.needsAccountSetup = false,
|
|
});
|
|
final bool needsAccountSetup;
|
|
final String subject;
|
|
final String? email;
|
|
final DateTime expiresAt;
|
|
}
|
|
|
|
/// Builderlab's CLI and NIP-FA adapter use the same server-side CLI credential.
|
|
/// This client uses the native header, never a browser cookie. Browser handoff
|
|
/// is deliberately a separate boundary: an app link is not an account session.
|
|
///
|
|
/// One session per device, scoped to its account subject. A login for another
|
|
/// subject is refused until the caller clears the session and every fact it
|
|
/// holds for the previous subject.
|
|
class BuilderlabAccountClient {
|
|
/// [accountOrigin] defaults to the hosted account environment. An
|
|
/// organization client uses its own trusted origin and session record.
|
|
BuilderlabAccountClient({
|
|
http.Client? httpClient,
|
|
FlutterSecureStorage? storage,
|
|
Uri? accountOrigin,
|
|
this.onSessionChanged,
|
|
}) : _http = httpClient ?? newAppHttpClient(),
|
|
_storage = storage ?? defaultStorage,
|
|
accountOrigin = accountOrigin ?? origin;
|
|
|
|
/// Device-only: the session never syncs or restores onto another device.
|
|
@visibleForTesting
|
|
static const defaultStorage = accountSecureStorage;
|
|
|
|
static final origin = HostedEnvironment.origin;
|
|
final Uri accountOrigin;
|
|
|
|
/// Receives the session credential each time one is adopted, and null when
|
|
/// it is cleared or a restore finds no session. Only a trusted owner of
|
|
/// [accountOrigin]'s session may set it, for example to share the session
|
|
/// with the notification extension. A failed clear fails the operation that
|
|
/// cleared, so a signed-out session is never left shared; a failed share of
|
|
/// an adopted session is retried at the next adopt.
|
|
final Future<void> Function(String? credential)? onSessionChanged;
|
|
static const _prefix = '/api/goose';
|
|
|
|
/// Remote-agent registry routes, shared with desktop.
|
|
/// Safe request diagnostics: no headers, credentials, bodies or user data.
|
|
({String path, int status})? lastRejectedRequest;
|
|
|
|
static const _beekeeperRoutes = {
|
|
'/v3/beekeeper/get-model-catalog',
|
|
'/v3/beekeeper/register-agent',
|
|
'/v3/beekeeper/update-agent',
|
|
'/v3/beekeeper/delete-agent',
|
|
'/v3/beekeeper/attest-agent',
|
|
'/v3/beekeeper/list-agents',
|
|
};
|
|
|
|
/// Agent listings carry each agent's instructions (up to 20,000 characters
|
|
/// apiece), so they get room for many full agents; every other route keeps
|
|
/// the default bound.
|
|
static int _responseLimit(String path) =>
|
|
path == '/v3/beekeeper/list-agents' ? 4 * 1024 * 1024 : 65536;
|
|
|
|
/// Sessions are scoped per origin so staging never reads production state.
|
|
late final _storageKey =
|
|
'buzz_hosted_session_${accountOrigin.host.replaceAll('.', '_')}_v1';
|
|
final http.Client _http;
|
|
final FlutterSecureStorage _storage;
|
|
String? _credential;
|
|
// The adopted credential while the notification extension lacks its copy.
|
|
String? _unshared;
|
|
bool _sharing = false;
|
|
BuilderlabAccount? _account;
|
|
// The session that last signed out, in memory only, so push-stop requests
|
|
// already pending can still reach their relays for a short while.
|
|
({String credential, DateTime until})? _signedOut;
|
|
final _queue = SerialQueue();
|
|
// Session storage changes, kept apart from [_queue] so signing out never
|
|
// waits behind a pending account request.
|
|
final _storageQueue = SerialQueue();
|
|
// Advances at each sign-out, so a request already in flight cannot adopt or
|
|
// save a session afterwards.
|
|
int _sessionEpoch = 0;
|
|
|
|
/// How long after sign-out [pushStopAssertion] can still issue.
|
|
static const pushStopWindow = Duration(minutes: 10);
|
|
bool _disposed = false;
|
|
|
|
BuilderlabAccount? get account => _account;
|
|
|
|
/// The signed-in subject, notifying when an account signs in, out or changes.
|
|
ValueListenable<String?> get subjectChanges => _subject;
|
|
final _subject = ValueNotifier<String?>(null);
|
|
|
|
/// Changes whenever a verified session is adopted, including the same subject.
|
|
/// Consumers can retry work refused before reauthentication or account setup.
|
|
ValueListenable<int> get sessionChanges => _sessionGeneration;
|
|
final _sessionGeneration = ValueNotifier<int>(0);
|
|
|
|
/// Runs operations one at a time in call order, so a callback exchange that
|
|
/// arrives during startup restore waits instead of failing.
|
|
Future<T> _serial<T>(Future<T> Function() operation) {
|
|
final result = _queue.run(() {
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
return operation();
|
|
});
|
|
return result;
|
|
}
|
|
|
|
/// Locally retained account for recording offline edits only. This does not
|
|
/// authorize network requests; those still require a verified session.
|
|
Future<String?> retainedSubject() async {
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
final current = account;
|
|
if (current != null) return current.subject;
|
|
// Local edits must not queue behind a network restore that may be offline.
|
|
final generation = _sessionGeneration.value;
|
|
final record = await _readRecord();
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
if (generation != _sessionGeneration.value) return retainedSubject();
|
|
return record?.subject;
|
|
}
|
|
|
|
/// Concurrent callers share one restore, so a second one cannot replace the
|
|
/// account the first adopted while its callers still hold that session.
|
|
Future<BuilderlabAccount?> restore() =>
|
|
_restoring ??= _restore().whenComplete(() => _restoring = null);
|
|
Future<BuilderlabAccount?>? _restoring;
|
|
Future<BuilderlabAccount?> _restore() => _serial(() async {
|
|
// Read behind any sign-out still clearing, so this never adopts the
|
|
// session it is deleting.
|
|
final (epoch, record) = await _storageQueue.run(
|
|
() async => (_sessionEpoch, await _readRecord()),
|
|
);
|
|
if (record == null) {
|
|
// Retries a removal that failed after an earlier sign-out.
|
|
await _unshare();
|
|
return null;
|
|
}
|
|
try {
|
|
final verified = await _verify(record.credential);
|
|
// Signed out while the check was pending.
|
|
if (epoch != _sessionEpoch) return null;
|
|
if (verified.subject != record.subject) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
return _adopt(record.credential, verified);
|
|
} on AccountFailure catch (failure) {
|
|
if (failure == AccountFailure.signedOut) {
|
|
await _clearSince(epoch);
|
|
return null;
|
|
}
|
|
rethrow;
|
|
}
|
|
});
|
|
|
|
/// Receives a one-use code only from a validated browser callback. PKCE is
|
|
/// verified by Builderlab; state and callback origin are checked by the caller.
|
|
/// [isCurrent] is checked just before the session is saved, so a caller can
|
|
/// abandon an exchange without it later replacing a newer session.
|
|
Future<BuilderlabAccount> exchange({
|
|
required String code,
|
|
required String verifier,
|
|
bool Function()? isCurrent,
|
|
}) {
|
|
// Taken at the call, so an exchange queued before a sign-out can never
|
|
// sign back in after it.
|
|
final epoch = _sessionEpoch;
|
|
return _serial(() async {
|
|
if (epoch != _sessionEpoch) throw AccountFailure.unavailable;
|
|
if (code.isEmpty ||
|
|
!RegExp(r'^[A-Za-z0-9._~-]{43,128}$').hasMatch(verifier)) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
final stored = await _readRecord();
|
|
final result = await _request(
|
|
'/v1/auth/login/exchange',
|
|
body: {'code': code, 'code_verifier': verifier},
|
|
);
|
|
final credential = result['session_credential'];
|
|
if (credential is! String ||
|
|
credential.isEmpty ||
|
|
credential.length > 512) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
final verified = await _verify(credential);
|
|
if (DateTime.tryParse(
|
|
result['expires_at'] is String
|
|
? result['expires_at'] as String
|
|
: '',
|
|
) !=
|
|
verified.expiresAt) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
if (stored != null && stored.subject != verified.subject) {
|
|
throw AccountFailure.differentAccount;
|
|
}
|
|
final record = jsonEncode({
|
|
'origin': accountOrigin.toString(),
|
|
'credential': credential,
|
|
'subject': verified.subject,
|
|
'expires_at': verified.expiresAt.toIso8601String(),
|
|
});
|
|
// Saved and adopted as one storage change, so a sign-out lands wholly
|
|
// before or after it.
|
|
return _storageQueue.run(() async {
|
|
if (_disposed ||
|
|
epoch != _sessionEpoch ||
|
|
(isCurrent != null && !isCurrent())) {
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
try {
|
|
await _storage.write(key: _storageKey, value: record);
|
|
if (await _storage.read(key: _storageKey) != record) {
|
|
throw AccountFailure.storage;
|
|
}
|
|
} catch (_) {
|
|
throw AccountFailure.storage;
|
|
}
|
|
return _adopt(credential, verified, reauthenticated: true);
|
|
});
|
|
});
|
|
}
|
|
|
|
/// An unreadable record is a storage failure, never an absent session: its
|
|
/// subject is unknown, so only an explicit [clearLocalSession] may drop it.
|
|
Future<({String credential, String subject})?> _readRecord() async {
|
|
final String? saved;
|
|
try {
|
|
saved = await _storage.read(key: _storageKey);
|
|
} catch (_) {
|
|
throw AccountFailure.storage;
|
|
}
|
|
if (saved == null) return null;
|
|
try {
|
|
final value = jsonDecode(saved);
|
|
if (value is Map<String, dynamic> &&
|
|
value['origin'] == accountOrigin.toString() &&
|
|
value['credential'] is String &&
|
|
value['subject'] is String) {
|
|
return (
|
|
credential: value['credential'] as String,
|
|
subject: value['subject'] as String,
|
|
);
|
|
}
|
|
} on FormatException {
|
|
// Falls through to the storage failure below.
|
|
}
|
|
throw AccountFailure.storage;
|
|
}
|
|
|
|
BuilderlabAccount _adopt(
|
|
String credential,
|
|
BuilderlabAccount verified, {
|
|
bool reauthenticated = false,
|
|
}) {
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
final changed =
|
|
reauthenticated ||
|
|
_credential != credential ||
|
|
_account?.needsAccountSetup != verified.needsAccountSetup;
|
|
_credential = credential;
|
|
// Assigned before notifying, so subject listeners see the new account.
|
|
_account = verified;
|
|
_subject.value = verified.subject;
|
|
if (changed) _sessionGeneration.value++;
|
|
_unshared = credential;
|
|
_share();
|
|
return verified;
|
|
}
|
|
|
|
/// Shares the adopted credential with the notification extension. Sharing is
|
|
/// push enrichment and must never gate sign-in, so a failure is retried by
|
|
/// the next account request instead of being thrown.
|
|
void _share() {
|
|
final share = onSessionChanged;
|
|
final credential = _unshared;
|
|
if (share == null || credential == null || _sharing) return;
|
|
_sharing = true;
|
|
unawaited(
|
|
share(credential)
|
|
.then((_) {
|
|
if (_unshared == credential) _unshared = null;
|
|
})
|
|
.catchError(
|
|
(Object error) => debugPrint('Session share failed: $error'),
|
|
)
|
|
.whenComplete(() {
|
|
_sharing = false;
|
|
// A newer credential adopted while this write was in flight still needs sharing.
|
|
final pending = _unshared;
|
|
if (pending != null && pending != credential) _share();
|
|
}),
|
|
);
|
|
}
|
|
|
|
Future<BuilderlabAccount> _verify(String credential) async {
|
|
final result = await _request('/v1/auth/me', credential: credential);
|
|
final subject = result['subject'];
|
|
final expiry = result['expires_at'];
|
|
final parsed = expiry is String ? DateTime.tryParse(expiry) : null;
|
|
if (subject is! String || subject.isEmpty || parsed == null) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
if (!parsed.isAfter(DateTime.now().toUtc())) throw AccountFailure.signedOut;
|
|
final needsSetup =
|
|
result['account_status'] == 'ACCOUNT_STATUS_NEEDS_DETAILS';
|
|
return BuilderlabAccount(
|
|
subject: subject,
|
|
email: result['email'] is String ? result['email'] as String : null,
|
|
expiresAt: parsed,
|
|
needsAccountSetup: needsSetup,
|
|
);
|
|
}
|
|
|
|
/// Public identity metadata only. Private-key recovery belongs to the identity
|
|
/// storage owner, which must derive and verify the key before any persistence.
|
|
Future<Map<String, dynamic>> currentIdentity() =>
|
|
post('/v1/buzz/nostr-identities/current', {});
|
|
|
|
/// Saves a successfully admitted destination to the same account, even if
|
|
/// another session operation was queued before this request runs.
|
|
Future<void> rememberCommunity(
|
|
String relay, {
|
|
required String expectedSubject,
|
|
}) async {
|
|
final result = await _post('/v1/buzz/known-communities/add', {
|
|
'community_url': relay,
|
|
}, expectedSubject: expectedSubject);
|
|
if (result['error'] != null) throw AccountFailure.rejected;
|
|
}
|
|
|
|
/// Edits only the account's saved destination list; relay membership and
|
|
/// credentials are unchanged. Both operations are idempotent.
|
|
Future<void> updateKnownCommunity(
|
|
String relay, {
|
|
required bool removed,
|
|
required String expectedSubject,
|
|
}) async {
|
|
final result = await post(
|
|
'/v1/buzz/known-communities/${removed ? 'remove' : 'add'}',
|
|
{'community_url': relay},
|
|
expectedSubject: expectedSubject,
|
|
);
|
|
if (result['error'] != null) throw AccountFailure.rejected;
|
|
}
|
|
|
|
/// Authenticated JSON POST to a Buzz account route on the fixed origin. The
|
|
/// credential never leaves this client. A 401 clears the stored session only
|
|
/// when the session check also rejects it; otherwise it is [AccountFailure.denied].
|
|
Future<Map<String, dynamic>> post(
|
|
String path,
|
|
Map<String, dynamic> body, {
|
|
String? expectedSubject,
|
|
}) => _post(path, body, expectedSubject: expectedSubject);
|
|
|
|
Future<Map<String, dynamic>> _post(
|
|
String path,
|
|
Map<String, dynamic> body, {
|
|
String? signingKey,
|
|
String? expectedSubject,
|
|
}) {
|
|
if (!RegExp(r'^/v1/buzz(/[a-z0-9_-]+)+$').hasMatch(path) &&
|
|
!_beekeeperRoutes.contains(path)) {
|
|
throw ArgumentError.value(
|
|
path,
|
|
'path',
|
|
'not an allowed Builderlab route',
|
|
);
|
|
}
|
|
return _serial(() async {
|
|
final epoch = _sessionEpoch;
|
|
final credential = _credential;
|
|
if (credential == null) throw AccountFailure.signedOut;
|
|
_share();
|
|
if (expectedSubject != null && _account?.subject != expectedSubject) {
|
|
throw AccountFailure.denied;
|
|
}
|
|
try {
|
|
return await _request(
|
|
path,
|
|
credential: credential,
|
|
body: body,
|
|
signingKey: signingKey,
|
|
);
|
|
} on AccountFailure catch (failure) {
|
|
if (failure == AccountFailure.denied &&
|
|
_account?.needsAccountSetup == true) {
|
|
throw AccountFailure.accountSetupRequired;
|
|
}
|
|
if (failure != AccountFailure.signedOut) rethrow;
|
|
}
|
|
// Routes also answer 401 for authorization failures, so only a rejected
|
|
// session check ends the session.
|
|
try {
|
|
await _verify(credential);
|
|
} on AccountFailure catch (failure) {
|
|
if (failure == AccountFailure.signedOut) await _clearSince(epoch);
|
|
rethrow;
|
|
}
|
|
throw AccountFailure.denied;
|
|
});
|
|
}
|
|
|
|
/// Proves the saved key. The issuer may establish its first account binding;
|
|
/// conflicting or retired bindings are refused atomically by the backend.
|
|
Future<Map<String, dynamic>> relayAssertion(
|
|
String relay,
|
|
String nsec, {
|
|
required String expectedSubject,
|
|
}) => _post(
|
|
'/v1/buzz/identity/assertions',
|
|
{
|
|
'relay_url': relay,
|
|
'nostr_pubkey': AccountIdentityStore.publicKeyForNsec(nsec),
|
|
},
|
|
signingKey: nsec,
|
|
expectedSubject: expectedSubject,
|
|
);
|
|
|
|
/// A relay assertion from the session that signed out within
|
|
/// [pushStopWindow], for a push-stop request only. That session is never
|
|
/// stored, shared or used for anything else, so it cannot sign back in.
|
|
Future<Map<String, dynamic>> pushStopAssertion(String relay, String nsec) =>
|
|
_serial(() async {
|
|
final signedOut = _signedOut;
|
|
if (signedOut == null || !DateTime.now().isBefore(signedOut.until)) {
|
|
_signedOut = null;
|
|
throw AccountFailure.signedOut;
|
|
}
|
|
final pubkey = AccountIdentityStore.publicKeyForNsec(nsec);
|
|
// Never creates a binding: the key must already belong to the account.
|
|
final current = await _request(
|
|
'/v1/buzz/nostr-identities/current',
|
|
credential: signedOut.credential,
|
|
body: {},
|
|
);
|
|
final identity = current['identity'];
|
|
if (identity is! Map || identity['pubkey_hex'] != pubkey) {
|
|
throw AccountFailure.denied;
|
|
}
|
|
return _request(
|
|
'/v1/buzz/identity/assertions',
|
|
credential: signedOut.credential,
|
|
body: {'relay_url': relay, 'nostr_pubkey': pubkey},
|
|
signingKey: nsec,
|
|
);
|
|
});
|
|
|
|
/// Runs at once, without waiting for pending account requests; none of them
|
|
/// can adopt or save a session after it.
|
|
Future<void> clearLocalSession() {
|
|
if (_disposed) return Future.error(AccountFailure.unavailable);
|
|
_sessionEpoch++;
|
|
return _storageQueue.run(_clear);
|
|
}
|
|
|
|
/// Ends a session a request found rejected, unless a sign-out already did.
|
|
Future<void> _clearSince(int epoch) => _storageQueue.run(() async {
|
|
if (epoch == _sessionEpoch) await _clear();
|
|
});
|
|
Future<void> _clear() async {
|
|
// A session saved but not yet restored (an offline launch) still backs
|
|
// the push stops that follow, so read it before deleting it.
|
|
var signedOut = _credential;
|
|
if (signedOut == null) {
|
|
try {
|
|
signedOut = (await _readRecord())?.credential;
|
|
} on AccountFailure {
|
|
// Unreadable: there is no credential to keep.
|
|
}
|
|
}
|
|
// Nothing may share the credential again while it is being removed.
|
|
_unshared = null;
|
|
// Attempt both removals so one failure never leaves the other copy live.
|
|
var failed = false;
|
|
try {
|
|
await _storage.delete(key: _storageKey);
|
|
} catch (_) {
|
|
failed = true;
|
|
}
|
|
try {
|
|
await _unshare();
|
|
} on AccountFailure {
|
|
failed = true;
|
|
}
|
|
if (failed) {
|
|
// The record may already be gone, so an unrestored session's credential
|
|
// must survive for the retry's push stops.
|
|
if (_credential == null && signedOut != null) {
|
|
_signedOut = (
|
|
credential: signedOut,
|
|
until: DateTime.now().add(pushStopWindow),
|
|
);
|
|
}
|
|
// The account stays signed in, so the extension gets its copy back.
|
|
_unshared = _credential;
|
|
_share();
|
|
throw AccountFailure.storage;
|
|
}
|
|
if (signedOut != null) {
|
|
_signedOut = (
|
|
credential: signedOut,
|
|
until: DateTime.now().add(pushStopWindow),
|
|
);
|
|
}
|
|
_credential = null;
|
|
_unshared = null;
|
|
_account = null;
|
|
if (!_disposed) {
|
|
_subject.value = null;
|
|
_sessionGeneration.value++;
|
|
}
|
|
}
|
|
|
|
Future<void> _unshare() async {
|
|
final share = onSessionChanged;
|
|
if (share == null) return;
|
|
try {
|
|
await share(null);
|
|
} catch (_) {
|
|
throw AccountFailure.storage;
|
|
}
|
|
}
|
|
|
|
Future<Map<String, dynamic>> _request(
|
|
String path, {
|
|
String? credential,
|
|
Map<String, dynamic>? body,
|
|
String? signingKey,
|
|
}) async {
|
|
try {
|
|
final request =
|
|
http.Request(
|
|
body == null ? 'GET' : 'POST',
|
|
accountOrigin.replace(path: '$_prefix$path'),
|
|
)
|
|
..followRedirects = false
|
|
..headers['Accept'] = 'application/json';
|
|
if (credential != null) {
|
|
request.headers['X-BB-Session-Credential'] = credential;
|
|
}
|
|
if (body != null) {
|
|
request.headers['Content-Type'] = 'application/json';
|
|
request.headers['Origin'] = accountOrigin.toString();
|
|
request.body = jsonEncode(body);
|
|
if (signingKey != null) {
|
|
request.headers['Authorization'] = buildNip98AuthHeader(
|
|
method: 'POST',
|
|
url: request.url.toString(),
|
|
bodyBytes: request.bodyBytes,
|
|
nsec: signingKey,
|
|
);
|
|
}
|
|
}
|
|
final response = await boundedHttpResponse(
|
|
_http,
|
|
request,
|
|
maxBytes: _responseLimit(path),
|
|
);
|
|
if (kDebugMode && response.statusCode >= 400) {
|
|
debugPrint(
|
|
'Builderlab ${accountOrigin.host} ${request.method} $path: HTTP ${response.statusCode} contentType=${response.headers['content-type']?.split(';').first}',
|
|
);
|
|
}
|
|
if (response.statusCode == 401) throw AccountFailure.signedOut;
|
|
if (response.statusCode == 403) throw AccountFailure.denied;
|
|
if (const {400, 404, 409, 422}.contains(response.statusCode)) {
|
|
lastRejectedRequest = (path: path, status: response.statusCode);
|
|
throw AccountFailure.rejected;
|
|
}
|
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
final value = jsonDecode(utf8.decode(response.bodyBytes));
|
|
if (value is! Map<String, dynamic>) throw AccountFailure.invalidResponse;
|
|
return value;
|
|
} on AccountFailure {
|
|
rethrow;
|
|
} on FormatException {
|
|
throw AccountFailure.invalidResponse;
|
|
} catch (_) {
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
}
|
|
|
|
void dispose() {
|
|
_disposed = true;
|
|
_credential = null;
|
|
_signedOut = null;
|
|
_account = null;
|
|
_subject.dispose();
|
|
_sessionGeneration.dispose();
|
|
_http.close();
|
|
}
|
|
}
|