mirror of
https://github.com/block/buzz.git
synced 2026-11-03 16:01:35 +00:00
Block is turning on NIP-FI enforcement on the Block relay. Desktop gets organization sign-in in block/buzz-app#1424. Mobile can already attach NIP-FI assertions, but only for Builderlab-hosted communities, through the build's single Builderlab account. The dogfood build needs that account for public hosted communities, so it can't simply be pointed at the Block tenant. This adds a separate **organization realm**, configured at build time: - `BUZZ_ORGANIZATION_URL`: the tenant's HTTPS origin (for example `https://block.builderlab.xyz`). - `BUZZ_ORGANIZATION_RELAYS`: the exact relay hosts that trust that tenant. The two must be set together. The app refuses to start if they're malformed, overlap a hosted community, or reuse the hosted origin. Without them, nothing changes. For a configured relay: - The app keeps its own organization session and signs in through the browser at the tenant's existing login (`/api/goose/v1/auth/login`). Block SSO happens there. - It requests assertions from the same `/v1/buzz/identity/assertions` route that hosted communities use, and attaches them to the relay socket, HTTP, media, huddle and remote-agent requests. - Unlike the hosted path, it doesn't require an identity backup before the first binding. As on desktop, the tenant binds the member's existing key on first issuance. A key already bound to a different one is refused before any request is sent. - When signed out, it connects without an assertion and lets the relay decide. A bottom banner offers **Sign in**. After sign-in, the relay reconnects with a fresh assertion. Hosted communities keep their existing banner and flow. The tenant accepts only the registered `xyz.block.buzz.mobile:/auth/callback` return URL, so both realms share it. Each `BrowserAuth` owner leaves callbacks whose `state` belongs to another owner's attempt to that owner. ### Before merge - [ ] Kenny Lopez reviews the visible changes. ### Validation Added tests (`organization_relay_auth_test.dart`): - Configuration parsing and exact host matching. - An assertion is issued for the exact relay and key, then cached. - A different bound key is refused. - Signed out connects without an assertion. - Other relays never receive the assertion. - The shared callback is routed between the hosted and organization owners. Full `mobile-check` and `mobile-test` pass. RunnerTests pass locally except `testNativeNavigationTitleExpandsAgainAtTop`, which this PR doesn't touch. Added tests (`organization_sign_in_test.dart`, `relay_auth_isolation_test.dart`, `builderlab_account_test.dart`), each failing without its fix: - Concurrent account restores at cold start share one adopted account. - An exchange from a cancelled attempt never changes a newer sign-in. - Storage failures while clearing the intent or cancelling leave the busy state. - An unreadable saved organization session is replaced by signing in again. - A stalled organization issuer never delays a hosted relay's assertion. This test needs `BUZZ_AUTH_DOMAINS` and skips without it. CI's configured-auth-domains step doesn't list it yet, because that workflow change needs a token with `workflow` scope. Added tests also cover a restore after an offline start (the banner clears once a relay retry restores the session) and the iOS bridge allowlist (`/auth/native` and tenant login on Builderlab subdomains; other hosts, paths, ports, userinfo and fragments refused). Simulator (iPhone 17, iOS 27) with the dogfood defines against the production Block relay `buzz.block.builderlab.xyz`, on a WARP Mac: - The app starts with the organization configuration and connects to the relay while signed out, showing the organization **Sign in** banner. - **Sign in** opens the system sign-in session for `block.builderlab.xyz`, and the banner shows **Finishing organization sign-in…**. Cancelling returns to **Sign in** with no error. Before the bridge fix, no browser opened and the banner reported that sign-in did not finish. - The bottom banners (organization sign-in, hosted reconnect, and the sign-in recovery row) now sit above Home's floating Search/New bar, which used to cover **Sign in**. A journey test checks the banner clears the bar, and fails without the fix.  - The simulator run stopped at the system consent prompt (SSO does not work in the simulator). The app calls were driven through the VM service (the same `signIn()`/`cancel()` the banner buttons call) because the simulator could not be tapped. Device (iPhone 12 mini) against bb-block staging in enforce mode, where every probe without an assertion gets 401: - Signed out, the organization banner shows and the app stays responsive. Cancel at the consent prompt returns to **Sign in**, and retry works. - Block SSO through Okta completes, and the relay admits the reconnect with the assertion. - After relaunch the app connects, loads channel history, and shows no banner for over 60 seconds. - Before the restore fix, 2 of 4 cold starts showed "cannot use this community with this key" although the session was valid. With it, 8 of 8 cold starts connected. Known limitation: adding an enforcing organization relay by community link is tracked in #8791. The dogfood build enables this in squareup/buzz-releases (`tomb/dogfood-organization-sign-in`). App Store builds stay unchanged. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
412 lines
14 KiB
Dart
412 lines
14 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 '../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.needsAccountSetup = false,
|
|
});
|
|
final bool needsAccountSetup;
|
|
final String subject;
|
|
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,
|
|
}) : _http = httpClient ?? http.Client(),
|
|
_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;
|
|
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',
|
|
};
|
|
|
|
/// 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;
|
|
BuilderlabAccount? _account;
|
|
final _queue = SerialQueue();
|
|
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);
|
|
|
|
/// 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;
|
|
}
|
|
|
|
/// 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 {
|
|
final record = await _readRecord();
|
|
if (record == null) return null;
|
|
try {
|
|
final verified = await _verify(record.credential);
|
|
if (verified.subject != record.subject) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
return _adopt(record.credential, verified);
|
|
} on AccountFailure catch (failure) {
|
|
if (failure == AccountFailure.signedOut) {
|
|
await _clear();
|
|
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,
|
|
}) => _serial(() async {
|
|
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;
|
|
}
|
|
if (_disposed || (isCurrent != null && !isCurrent())) {
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
final record = jsonEncode({
|
|
'origin': accountOrigin.toString(),
|
|
'credential': credential,
|
|
'subject': verified.subject,
|
|
'expires_at': verified.expiresAt.toIso8601String(),
|
|
});
|
|
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);
|
|
});
|
|
|
|
/// 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) {
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
_credential = credential;
|
|
// Assigned before notifying, so subject listeners see the new account.
|
|
_account = verified;
|
|
_subject.value = verified.subject;
|
|
return verified;
|
|
}
|
|
|
|
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 standing = result['account_standing'];
|
|
final needsSetup =
|
|
standing is Map &&
|
|
(standing['details_status'] == 'ACCOUNT_DETAILS_STATUS_MISSING' ||
|
|
standing['screening_status'] ==
|
|
'ACCOUNT_SCREENING_STATUS_NOT_SCREENED');
|
|
return BuilderlabAccount(
|
|
subject: subject,
|
|
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;
|
|
}
|
|
|
|
/// 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 credential = _credential;
|
|
if (credential == null) throw AccountFailure.signedOut;
|
|
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 _clear();
|
|
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,
|
|
);
|
|
|
|
Future<void> clearLocalSession() => _serial(_clear);
|
|
Future<void> _clear() async {
|
|
_credential = null;
|
|
_account = null;
|
|
if (!_disposed) _subject.value = null;
|
|
try {
|
|
await _storage.delete(key: _storageKey);
|
|
} 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);
|
|
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;
|
|
_account = null;
|
|
_subject.dispose();
|
|
_http.close();
|
|
}
|
|
}
|