mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Ticket 6 of the [Android push design](https://github.com/block/buzz/pull/9555), building on [#9558 resolve push wakes](https://github.com/block/buzz/pull/9558). Enrollment (FCM token registration, ticket 7) landed separately in [#9811 enroll Android push](https://github.com/block/buzz/pull/9811), which also carries the Firebase build config, `POST_NOTIFICATIONS` and the auto-init switch. ## What it does A data-only FCM message wakes the app with no content. This PR turns that wake into notifications natively, with no UI: - `PushWakeService` (a `FirebaseMessagingService`) treats both a message and the deleted-messages callback as "sync now". - If the app is in the foreground it does nothing. Otherwise it starts a headless Flutter engine on `androidPushWakeMain`, which runs ticket 5's `resolvePushWake` and hands the notifications back to native code to post. - If nothing has been posted after 2 s, a generic "New activity" notification appears in the "Other" channel. The real result replaces it silently, or removes it when there is nothing to show. An 8 s native watchdog ends a run whose Dart side hangs. - One run per process. A wake that arrives mid-run joins it and sets the rerun flag from ticket 5. - Channels: Direct messages, Mentions, Other. Each conversation is one `MessagingStyle` notification, grouped under the app. Existing messages in a conversation are recovered from the active notification so a new wake appends instead of replacing. - Tapping opens the conversation through the existing push deep-link path (`pendingPushNotificationLink`), for a cold start and for a running app. This also turns on the cold-start tap handoff for Android, which was iOS-only. - The headless path sends the NIP-FI header that org-protected relays need, using the same `HostedRelayAuth` as the foreground app (background mode: a fresh assertion per wake that never records foreground failures). `resolvePushWake` gets one optional `relayHeaders` hook for it. ## Decisions - **Firebase config is build-time and never committed.** `BUZZ_FIREBASE_APP_ID`, `BUZZ_FIREBASE_API_KEY`, `BUZZ_FIREBASE_PROJECT_ID` and `BUZZ_FIREBASE_SENDER_ID` become string resources (no google-services plugin or JSON file). All four or none: a partial set fails the build, and a build with none works but has no push wake. Documented in `mobile/README.md`. - **The wake only reads the saved account session.** Its account clients share the foreground app's record, so they never save, replace or delete it. A rejected credential is dropped from the wake's memory only, which keeps a sign-in that finished mid-wake. - **No FCM token before enrollment.** Firebase Messaging's auto-init is off, so a configured build does not register with Firebase at launch. Ticket 7 requests the token when the app enrolls. - **Notifications disabled means the wake is skipped entirely**, so nothing is claimed as shown and the next wake after the user re-enables them still delivers. - **Debug hook.** Debug builds include an exported receiver that runs the same code path as the FCM service, for testing without Firebase. ## Known gaps - The foreground app does not yet write the shown-message record, so a message already read in the app can notify again after the app is backgrounded. This needs its own ticket. - `PushWakeService` is now the app's only messaging service, so it should hand `onNewToken` to the registration plugin from [#9811 enroll Android push](https://github.com/block/buzz/pull/9811). It doesn't yet. - Follow-ups now that enrollment is on main: real FCM wakes run one at a time and never join a run; a blocked or silent "Other" channel mutes a slow DM; a stale generic can make one message alert twice; NIP-FI issuance can use the whole wake budget; a consumed tap replays after process death; cold engine start registers every plugin. - Follow-ups from review: - A confirmed age restriction isn't applied to Android wakes, and the Android purge doesn't cancel posted notifications. - One unreadable entry, or a throw from `notify`, sends the whole batch, already recorded as shown, to the generic notification. - The foreground check can lag about 700 ms behind the app becoming visible. - There is no group summary, so below Android 16 several conversations show as separate cards. - On API 24 and 25 the notifications have no priority or defaults, so they don't sound. - A stall delivering the result over the channel can still use up the 1 s reserve before the watchdog. - A shown-message claim writes its marker before its watermark and prune I/O, so a stall past the 250 ms claim grace loses the message (from [#9558 Dart wake-to-notifications](https://github.com/block/buzz/pull/9558)). - A live tap during cold start can be handled before the startup tap, and the tap's target is carried in extras any app can send. - The native side has no JVM tests yet, although `app/src/test/kotlin` exists and CI runs it. A payload-contract test for `WakeNotification.fromDart` and a test of the production `_headlessRelayHeaders` wiring are follow-ups. The device runs below cover the native side, and the Dart side (payload shape, joined runs, header hook, cold-start tap) has tests. ### Validation Run on a Pixel 9a (Android 17) against a local fake relay with test data only, using a profile (AOT) build with the debug hook, since debug (JIT) builds start the Dart engine in 4 to 5 s and say little about real latency. Timings come from the `BuzzPushWake` log tags, measured from the start of the wake. | Scenario | Result | | --- | --- | | Cold wake, process killed, one DM | Notification posted at 2.0 s (engine 0.9 s, Dart ready 1.8 s), three runs within 0.1 s of each other | | Wake while the process is warm | Posted at 0.4 s | | Two conversations in one wake | One grouped notification card, each conversation its own `MessagingStyle`, posted at 2.1 s | | Relay answers in 2.4 s | Generic "New activity" at 2.0 s, replaced by the real notification at 5.8 s, generic removed, replacement did not beep (the system's `notification_alert` event shows no sound for it, while the generic did beep) | | Relay answers in 3.5 s (over the 3 s request limit) | Generic stays at 5.0 s, nothing is claimed | | Next wake after that, relay healthy | Real notification at 0.4 s and the stale generic is gone (the case fixed in `c786957`) | | Relay accepts the connection and never answers | Dart's own 3 s request timeout ends the wake at 5.0 s as incomplete, generic stays | | App in the foreground | Wake ignored, no notification; after backgrounding, the next wake delivers | | Tap, app running in background | The existing deep-link provider receives the right community, channel and message; notification dismisses | | Tap, process killed | Same | | 10 wakes in a row, debug build, app process kept alive | Network threads stay at 3 and total threads flat (53 to 58). Before the switch to dart:io, each wake left about 2 Cronet threads behind (3 to 11 over 5 wakes) | An earlier run on an Android 36 emulator gave the same behavior. Not exercised: the FCM service itself (it is not exported and there is no Firebase config), so the deleted-messages callback was not triggered, though it calls the same entry as the debug hook. The 8 s native watchdog was not reached: a hung relay is always ended earlier by Dart's request timeout, and only a hung Dart isolate would trigger it. NIP-FI against an org-protected relay is covered only by unit tests. The tap was checked up to the deep-link provider, not to the chat screen, because the fake relay does not serve the channel list the app needs to open it. On a debug (JIT) build the main thread is busy for several seconds starting the engine, so the 2 s generic timer, which runs on that thread, fired at 5.3 s. Added tests: [`android_push_wake_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/android_push_wake_test.dart) covers the native payload, joined and sequential wakes, the relay header hook, and a community whose headers fail. [`push_bridge_test.dart`](https://github.com/block/buzz/blob/android-push-wake-handling/mobile/test/shared/push/push_bridge_test.dart) covers the Android cold-start tap. ### Screenshots Before: no notification (nothing handles wakes). After, with test data, on the Pixel 9a (two conversations grouped) and on the emulator (one conversation after a cold wake): <img src="https://github.com/user-attachments/assets/d3d98784-fecc-4757-a867-0a93d5a210a5" width="300" alt="Two conversations grouped on a Pixel"> <img src="https://github.com/user-attachments/assets/1e7fea3c-7f72-4f8d-90d1-8c289cf1b740" width="300" alt="One conversation after a cold wake on an emulator"> ## Regressions - Adds the `POST_NOTIFICATIONS` permission and the Firebase Messaging and `lifecycle-process` dependencies, so the Android build and APK grow. The runtime permission prompt is not part of this PR. - Debug builds ship an exported broadcast receiver that can trigger a wake. Release builds do not include it. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost:3000> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
764 lines
27 KiB
Dart
764 lines
27 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 '../diagnostics/diagnostic_reporter.dart';
|
|
import '../storage/secure_storage.dart';
|
|
|
|
import 'hosted_environment.dart';
|
|
import 'bounded_http_response.dart';
|
|
import 'clock_hint.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,
|
|
DiagnosticReporter diagnostics = const NoopDiagnosticReporter(),
|
|
this.readOnlySession = false,
|
|
DateTime Function() now = DateTime.now,
|
|
}) : _now = now,
|
|
_diagnostics = diagnostics,
|
|
_http = httpClient ?? newAppHttpClient(),
|
|
_storage = storage ?? defaultStorage,
|
|
accountOrigin = accountOrigin ?? origin;
|
|
|
|
/// Where a response body this client can't understand is reported.
|
|
final DiagnosticReporter _diagnostics;
|
|
|
|
/// 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;
|
|
|
|
/// Uses the saved session without ever saving, replacing or deleting it,
|
|
/// for a caller that shares the record with the app that owns it (a
|
|
/// background push wake). A rejected credential is only dropped from memory,
|
|
/// since the owner may have saved a newer session while the check was
|
|
/// pending; signing in or out is refused.
|
|
final bool readOnlySession;
|
|
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;
|
|
|
|
/// Why the last request failed as [AccountFailure.unavailable]: a transport
|
|
/// failure (`unreachable`, `insecure`, `timedOut`, `network`) or an
|
|
/// unexpected status such as `http302`. Safe to show; callers clear it.
|
|
String? lastUnavailableCause;
|
|
|
|
/// Runs [operation], giving it the clock hint of the last refusal (403) that
|
|
/// its own requests to any account client received: how many minutes the
|
|
/// local clock looked off from the server's `Date` when its headers arrived,
|
|
/// when far enough to explain it. See [clockHintMinutes]. Requests made
|
|
/// outside [operation] never supply it.
|
|
static Future<T> observingRefusals<T>(
|
|
Future<T> Function(int? Function() clockHint) operation,
|
|
) {
|
|
final evidence = _RefusalEvidence();
|
|
return runZoned(
|
|
() => operation(() => evidence.clockHint),
|
|
zoneValues: {_RefusalEvidence: evidence},
|
|
);
|
|
}
|
|
|
|
// The local wall clock, compared with a refusal's `Date`.
|
|
final DateTime Function() _now;
|
|
|
|
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,
|
|
}) {
|
|
if (readOnlySession) {
|
|
throw StateError('a read-only session client cannot sign in');
|
|
}
|
|
// 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) {
|
|
_invalidResponse('exchange response has no usable credential');
|
|
}
|
|
final verified = await _verify(credential);
|
|
if (DateTime.tryParse(
|
|
result['expires_at'] is String
|
|
? result['expires_at'] as String
|
|
: '',
|
|
) !=
|
|
verified.expiresAt) {
|
|
_invalidResponse('exchange and session expiry differ');
|
|
}
|
|
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) {
|
|
_invalidResponse('session response lacks a subject or expiry');
|
|
}
|
|
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.
|
|
///
|
|
/// [signer] is the key a community is asking for, when that may not be the
|
|
/// active member's: a bad reply is then reported only while reports name it.
|
|
Future<Map<String, dynamic>> currentIdentity({String? signer}) =>
|
|
post('/v1/buzz/nostr-identities/current', {}, signer: signer);
|
|
|
|
/// 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,
|
|
String? signer,
|
|
}) => _post(path, body, expectedSubject: expectedSubject, signer: signer);
|
|
|
|
Future<Map<String, dynamic>> _post(
|
|
String path,
|
|
Map<String, dynamic> body, {
|
|
String? signingKey,
|
|
String? signer,
|
|
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,
|
|
signer: signer,
|
|
);
|
|
} 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.
|
|
// Gated on [pubkey]: the community may be removed, not the active one.
|
|
final current = await _request(
|
|
'/v1/buzz/nostr-identities/current',
|
|
credential: signedOut.credential,
|
|
body: {},
|
|
signer: pubkey,
|
|
);
|
|
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 (readOnlySession) {
|
|
throw StateError('a read-only session client cannot sign out');
|
|
}
|
|
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) return;
|
|
if (readOnlySession) {
|
|
_credential = null;
|
|
_unshared = null;
|
|
_account = null;
|
|
if (!_disposed) {
|
|
_subject.value = null;
|
|
_sessionGeneration.value++;
|
|
}
|
|
return;
|
|
}
|
|
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;
|
|
}
|
|
}
|
|
|
|
/// [signer], or the key behind [signingKey], is the identity the request
|
|
/// is made for. Its reports go out only while that identity, or no one, is
|
|
/// the member reports name: the outbox may ask for a removed community.
|
|
Future<Map<String, dynamic>> _request(
|
|
String path, {
|
|
String? credential,
|
|
Map<String, dynamic>? body,
|
|
String? signingKey,
|
|
String? signer,
|
|
}) async {
|
|
signer ??= signingKey == null
|
|
? null
|
|
: AccountIdentityStore.publicKeyForNsec(signingKey);
|
|
final diagnostics = signer == null
|
|
? _diagnostics
|
|
: SignerDiagnosticReporter(_diagnostics, signer: signer);
|
|
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,
|
|
);
|
|
}
|
|
}
|
|
// Classified from the headers, so a lost, slow or oversized error body
|
|
// never hides the status.
|
|
final response = await boundedHttpResponse(
|
|
_http,
|
|
request,
|
|
maxBytes: _responseLimit(path),
|
|
onHeaders: (headers) {
|
|
final status = headers.statusCode;
|
|
if (status >= 200 && status < 300) return;
|
|
if (status == 403) {
|
|
final evidence = Zone.current[_RefusalEvidence];
|
|
if (evidence is _RefusalEvidence) {
|
|
evidence.clockHint = clockHintMinutes(
|
|
headers.headers['date'],
|
|
_now(),
|
|
);
|
|
}
|
|
}
|
|
if (const {401, 403, 400, 404, 409, 422}.contains(status) &&
|
|
kDebugMode) {
|
|
debugPrint(
|
|
'Builderlab ${accountOrigin.host} ${request.method} $path: HTTP $status contentType=${headers.headers['content-type']?.split(';').first}',
|
|
);
|
|
}
|
|
if (status == 401) throw AccountFailure.signedOut;
|
|
if (status == 403) throw AccountFailure.denied;
|
|
if (const {400, 404, 409, 422}.contains(status)) {
|
|
lastRejectedRequest = (path: path, status: status);
|
|
throw AccountFailure.rejected;
|
|
}
|
|
_unavailable(path, 'http$status');
|
|
},
|
|
);
|
|
final Object? value;
|
|
try {
|
|
value = jsonDecode(utf8.decode(response.bodyBytes));
|
|
if (value is! Map<String, dynamic>) {
|
|
// Not const: Sentry drops a repeat of the last error object.
|
|
throw FormatException('account response is not an object');
|
|
}
|
|
} on FormatException catch (error, stackTrace) {
|
|
diagnostics.reportError(
|
|
error,
|
|
stackTrace,
|
|
operation: DiagnosticOperation.accountResponse,
|
|
);
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
return value;
|
|
} on AccountFailure {
|
|
rethrow;
|
|
} on FormatException {
|
|
throw AccountFailure.invalidResponse;
|
|
} on TimeoutException {
|
|
_unavailable(path, 'timedOut');
|
|
} catch (error) {
|
|
_unavailable(path, transportFailure(error)?.name ?? 'network');
|
|
}
|
|
}
|
|
|
|
/// A 2xx response whose required fields are missing or unreadable: the
|
|
/// caller sees an invalid response, and it is reported.
|
|
Never _invalidResponse(String what) {
|
|
_diagnostics.reportError(
|
|
FormatException(what),
|
|
StackTrace.current,
|
|
operation: DiagnosticOperation.accountResponse,
|
|
);
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
|
|
Never _unavailable(String path, String cause) {
|
|
lastUnavailableCause = cause;
|
|
debugPrint('Builderlab ${accountOrigin.host} $path: unavailable ($cause)');
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
|
|
void dispose() {
|
|
_disposed = true;
|
|
_credential = null;
|
|
_signedOut = null;
|
|
_account = null;
|
|
_subject.dispose();
|
|
_sessionGeneration.dispose();
|
|
_http.close();
|
|
}
|
|
}
|
|
|
|
/// What [BuilderlabAccountClient.observingRefusals] collects for one operation.
|
|
class _RefusalEvidence {
|
|
int? clockHint;
|
|
}
|