mirror of
https://github.com/block/buzz.git
synced 2026-11-25 18:52:52 +00:00
On iOS, custom emoji in the native emoji picker often render as the sparkle fallback icon instead of the image. The native picker downloads custom emoji with `URLSession` and asks Flutter for request headers over the `mediaHeaders` channel call. That call returned only the media read `Authorization` header. Hosted relays also require the `Nostr-Federated-Identity` assertion, which the Flutter image path gets from `HostedRelayHttpClient`, so relay-hosted emoji get a 401 and the picker falls back to sparkles. Emoji hosted elsewhere still load, which is why only some are missing. The `mediaHeaders` bridge now also includes the hosted relay assertion via a new `HostedRelayAuth.headersForUrl`, scoped to the relay's own origin like `HostedRelayHttpClient`. The native loader refuses redirects for requests that carry the assertion, matching the Dart client, so the token can't be forwarded to another host. The iOS reactions sheet had the same gap: it passes avatar and custom emoji URLs to native views with only the `Authorization` header. A new `nativeMediaHeadersProvider` combines both headers for any native media consumer, and the reactions sheet uses it. ### Validation - Added tests: the native picker's `mediaHeaders` call returns the relay assertion for relay media and no headers for an external emoji URL; `headersForUrl` returns the assertion only for the relay origin (not another host, subdomain or port). The reactions sheet passes the combined headers for avatars and custom emoji, and `nativeMediaHeadersProvider` merges both headers only for relay URLs. - Focused existing validation: the emoji picker and organization relay auth suites pass, and `flutter analyze` is clean. In the full mobile suite, the only failures are 10 in `notification_toggle_test`, `push_bootstrap_test` and `push_bridge_test`, and they fail the same way on `main`. - Automated full-app simulator run (iPhone 17 Pro, iOS 27, debug build of this branch with hosted auth enabled, signed in to two hosted communities through a cloned simulator keychain, driven with AXe). Covered: launch signed in, channel and DM lists, opening a channel and a DM, the native emoji picker (its Custom section shows the emoji as an image, not the sparkle fallback), sending a custom emoji message and seeing it render, reacting with the custom emoji (shown in the quick-reaction row and as a reaction pill), opening a thread, switching communities, avatars and community icons, background and resume, and a cold relaunch. Result: no crashes or regressions seen. Screenshots are omitted because they show real account and community names. - Limitations: this run does not reproduce the original bug. The hosted community's custom emoji also loaded in a temporary build with the relay assertion removed from the `mediaHeaders` bridge, so its emoji URL evidently doesn't need the assertion, and the run doesn't prove the fix. The reactions detail sheet could not be reached because simulated long presses on the pill opened the message menu, and inline image attachments were not exercised. A device build against a community whose emoji are relay-hosted is still needed to confirm the fix. 🤖 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> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
392 lines
13 KiB
Dart
392 lines
13 KiB
Dart
import 'dart:async';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../relay/relay_provider.dart';
|
|
import 'builderlab_account.dart';
|
|
import 'account_identity_store.dart';
|
|
import 'hosted_environment.dart';
|
|
import 'organization_environment.dart';
|
|
import 'organization_key_backup.dart';
|
|
import '../push/push_bridge.dart';
|
|
|
|
final builderlabAccountProvider = Provider<BuilderlabAccountClient>((ref) {
|
|
final account = BuilderlabAccountClient();
|
|
ref.onDispose(account.dispose);
|
|
return account;
|
|
});
|
|
|
|
/// The organization's own account session, separate from the hosted account.
|
|
/// Null unless this build configures [OrganizationEnvironment].
|
|
final organizationAccountProvider = Provider<BuilderlabAccountClient?>((ref) {
|
|
final origin = OrganizationEnvironment.origin;
|
|
if (origin == null) return null;
|
|
final account = BuilderlabAccountClient(
|
|
accountOrigin: origin,
|
|
// The notification extension mints its own assertions for these relays.
|
|
onSessionChanged: (credential) => shareOrganizationSessionWithNotifications(
|
|
origin: origin,
|
|
credential: credential,
|
|
relayHosts: OrganizationEnvironment.relayHosts,
|
|
),
|
|
);
|
|
ref.onDispose(account.dispose);
|
|
return account;
|
|
});
|
|
|
|
/// Outlives relay-auth rebuilds, so its settled keys and in-flight attempts
|
|
/// are never duplicated. Null unless this build configures an organization.
|
|
final organizationKeyBackupProvider = Provider<OrganizationKeyBackup?>((ref) {
|
|
final organization = ref.watch(organizationAccountProvider);
|
|
return organization == null ? null : OrganizationKeyBackup(organization);
|
|
});
|
|
|
|
final hostedRelayAuthProvider = Provider<HostedRelayAuth>((ref) {
|
|
final auth = HostedRelayAuth(
|
|
ref.watch(builderlabAccountProvider),
|
|
organization: ref.watch(organizationAccountProvider),
|
|
organizationBackup: ref.watch(organizationKeyBackupProvider),
|
|
);
|
|
ref.onDispose(auth.dispose);
|
|
return auth;
|
|
});
|
|
|
|
/// Each transport owns its client lifetime; configuration and auth are shared.
|
|
final hostedHttpClientFactoryProvider = Provider<http.Client Function()>((ref) {
|
|
final auth = ref.watch(hostedRelayAuthProvider);
|
|
final config = ref.watch(relayConfigProvider);
|
|
return () => HostedRelayHttpClient(auth, config);
|
|
});
|
|
|
|
/// One account session per realm, with a short-lived assertion for the current
|
|
/// relay/key. Hosted communities use [account] when [enabled]; the build's
|
|
/// organization relays use [organization]. Enable alongside backend issuance;
|
|
/// legacy and self-hosted builds stay usable.
|
|
class HostedRelayAuth extends ChangeNotifier {
|
|
HostedRelayAuth(
|
|
this.account, {
|
|
this.organization,
|
|
this.organizationBackup,
|
|
this.organizationRelay = OrganizationEnvironment.protects,
|
|
this.enabled = const bool.fromEnvironment('BUZZ_HOSTED_RELAY_AUTH'),
|
|
DateTime Function()? now,
|
|
}) : _now = now ?? DateTime.now;
|
|
|
|
final BuilderlabAccountClient account;
|
|
final BuilderlabAccountClient? organization;
|
|
|
|
/// Backs up each organization relay key once its assertion has bound it.
|
|
final OrganizationKeyBackup? organizationBackup;
|
|
final bool Function(Uri relay) organizationRelay;
|
|
final bool enabled;
|
|
final DateTime Function() _now;
|
|
({
|
|
String relay,
|
|
String pubkey,
|
|
String token,
|
|
DateTime expiry,
|
|
BuilderlabAccount account,
|
|
})?
|
|
_cached;
|
|
// Per account client, so a stalled issuer never delays an unrelated one.
|
|
final _pending = <BuilderlabAccountClient, Future<void>>{};
|
|
bool _disposed = false;
|
|
// Orders issuance and refusals, so a stale result never replaces a newer
|
|
// failure for another relay or key.
|
|
int _sequence = 0;
|
|
int _failureSequence = 0;
|
|
String? failedRelay;
|
|
String? failedPubkey;
|
|
AccountFailure? failure;
|
|
|
|
bool protects(RelayConfig config) => _accountFor(config) != null;
|
|
|
|
/// Whether this relay uses the organization's session, not the hosted one.
|
|
bool organizationProtects(RelayConfig config) =>
|
|
organization != null && identical(_accountFor(config), organization);
|
|
|
|
BuilderlabAccountClient? _accountFor(RelayConfig config) {
|
|
final relay = Uri.parse(config.baseUrl);
|
|
if (organization != null && organizationRelay(relay)) {
|
|
return organization;
|
|
}
|
|
if (enabled &&
|
|
HostedEnvironment.requiresAuth(relay.host) &&
|
|
HostedEnvironment.supportsRelay(relay)) {
|
|
return account;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Headers for optional reads, without starting account work or changing
|
|
/// recovery state. Null means protected metadata must wait for active auth.
|
|
Map<String, String>? cachedHeaders(RelayConfig config) {
|
|
if (_disposed) return null;
|
|
if (!protects(config)) return const {};
|
|
final cached = _cached;
|
|
if (cached == null ||
|
|
cached.relay != Uri.parse(config.wsUrl).replace(path: '').toString() ||
|
|
cached.pubkey != pubkeyFromNsec(config.nsec) ||
|
|
!identical(cached.account, _accountFor(config)?.account) ||
|
|
!cached.expiry.isAfter(_now())) {
|
|
return null;
|
|
}
|
|
return {'Nostr-Federated-Identity': 'Bearer ${cached.token}'};
|
|
}
|
|
|
|
/// [headers] for a request made outside [HostedRelayHttpClient], such as a
|
|
/// native download. Scoped like that client: only the relay's own origin
|
|
/// gets the assertion, so it never reaches a third-party host.
|
|
Future<Map<String, String>> headersForUrl(RelayConfig config, Uri url) async {
|
|
if (!_isRelayOrigin(config, url)) return const {};
|
|
return headers(config);
|
|
}
|
|
|
|
/// Synchronous [headersForUrl] for callers that hand headers to native code
|
|
/// up front. Uses the assertion the live relay session already holds; with
|
|
/// none cached the request goes out without it and the relay decides.
|
|
Map<String, String> cachedHeadersForUrl(RelayConfig config, Uri url) {
|
|
if (!_isRelayOrigin(config, url)) return const {};
|
|
return cachedHeaders(config) ?? const {};
|
|
}
|
|
|
|
static bool _isRelayOrigin(RelayConfig config, Uri url) =>
|
|
(url.scheme == 'http' || url.scheme == 'https') &&
|
|
// `Uri.origin` throws for a hostless URI, which a community can supply.
|
|
url.host.isNotEmpty &&
|
|
url.origin == Uri.parse(config.baseUrl).origin;
|
|
|
|
Future<Map<String, String>> headers(RelayConfig config) async {
|
|
final client = _accountFor(config);
|
|
if (client == null) return const {};
|
|
try {
|
|
return await _headers(config, client);
|
|
} on AccountFailure catch (failure) {
|
|
// Without an organization session, connect as before and let the relay
|
|
// decide: an enforcing relay refuses, and sign-in is offered.
|
|
if (failure == AccountFailure.signedOut &&
|
|
identical(client, organization)) {
|
|
return const {};
|
|
}
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
Future<Map<String, String>> _headers(
|
|
RelayConfig config,
|
|
BuilderlabAccountClient client,
|
|
) async {
|
|
final relay = Uri.parse(config.wsUrl).replace(path: '').toString();
|
|
final pubkey = pubkeyFromNsec(config.nsec);
|
|
if (pubkey == null) throw AccountFailure.denied;
|
|
while (!_disposed) {
|
|
final cached = _cached;
|
|
if (cached != null &&
|
|
cached.relay == relay &&
|
|
cached.pubkey == pubkey &&
|
|
identical(cached.account, client.account) &&
|
|
cached.expiry.isAfter(_now())) {
|
|
return {'Nostr-Federated-Identity': 'Bearer ${cached.token}'};
|
|
}
|
|
final pending = _pending[client];
|
|
if (pending != null) {
|
|
// Different communities share account restoration, never assertions.
|
|
try {
|
|
await pending;
|
|
} on AccountFailure {
|
|
if (failedRelay == config.baseUrl && failedPubkey == pubkey) rethrow;
|
|
}
|
|
continue;
|
|
}
|
|
final operation = _issue(config, client, relay, pubkey);
|
|
_pending[client] = operation;
|
|
try {
|
|
await operation;
|
|
} finally {
|
|
if (identical(_pending[client], operation)) _pending.remove(client);
|
|
}
|
|
}
|
|
throw AccountFailure.unavailable;
|
|
}
|
|
|
|
Future<void> _issue(
|
|
RelayConfig config,
|
|
BuilderlabAccountClient account,
|
|
String relay,
|
|
String pubkey,
|
|
) async {
|
|
final started = ++_sequence;
|
|
try {
|
|
if (account.account == null && await account.restore() == null) {
|
|
throw AccountFailure.signedOut;
|
|
}
|
|
final session = account.account!;
|
|
final current = await account.currentIdentity();
|
|
if (!identical(session, account.account)) throw AccountFailure.denied;
|
|
final identity = current['identity'];
|
|
if (current['error'] != null) throw AccountFailure.invalidResponse;
|
|
if (identity == null && identical(account, organization)) {
|
|
// The organization's issuer binds the proven key on first issuance;
|
|
// that binding is how a member's existing key joins the organization.
|
|
} else if (identity == null) {
|
|
// Issuance can create a binding. Reconnect must not silently give a
|
|
// different, unbound hosted account this community's saved identity.
|
|
final AccountIdentitySnapshot? saved;
|
|
try {
|
|
saved = await AccountIdentityStore()
|
|
.forSubject(session.subject)
|
|
.read();
|
|
} on AccountIdentityFailure {
|
|
throw AccountFailure.storage;
|
|
}
|
|
if (saved?.pubkey != pubkey ||
|
|
!saved!.hasBackupFor(
|
|
backend: BuilderlabAccountClient.origin.origin,
|
|
subject: session.subject,
|
|
)) {
|
|
throw AccountFailure.denied;
|
|
}
|
|
} else if (identity is! Map || identity['pubkey_hex'] != pubkey) {
|
|
throw AccountFailure.denied;
|
|
}
|
|
final value = await account.relayAssertion(
|
|
relay,
|
|
config.nsec!,
|
|
expectedSubject: session.subject,
|
|
);
|
|
final token = value['assertion'];
|
|
final expiry = value['expires_at'];
|
|
if (token is! String ||
|
|
token.isEmpty ||
|
|
token.length > 16384 ||
|
|
token.contains(RegExp(r'[\r\n]')) ||
|
|
value['nostr_pubkey'] != pubkey ||
|
|
expiry is! int) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
final now = _now().millisecondsSinceEpoch ~/ 1000;
|
|
if (expiry <= now) {
|
|
throw AccountFailure.invalidResponse;
|
|
}
|
|
final expires = DateTime.fromMillisecondsSinceEpoch(
|
|
expiry * 1000,
|
|
isUtc: true,
|
|
);
|
|
if (_disposed) throw AccountFailure.unavailable;
|
|
if (!identical(session, account.account)) {
|
|
return;
|
|
}
|
|
_cached = (
|
|
relay: relay,
|
|
pubkey: pubkey,
|
|
token: token,
|
|
expiry: expires.subtract(
|
|
Duration(seconds: (expiry - now) > 60 ? 30 : (expiry - now) ~/ 2),
|
|
),
|
|
account: session,
|
|
);
|
|
// Issuance alone cannot prove admission after a relay refusal.
|
|
if (failure != AccountFailure.denied) connected(config);
|
|
if (identical(account, organization)) {
|
|
unawaited(organizationBackup?.afterAssertion(config.nsec!, pubkey));
|
|
}
|
|
} on AccountFailure catch (error) {
|
|
// Issuers run in parallel, so a failure that started before another
|
|
// relay's unresolved failure was recorded must not replace it.
|
|
final otherScope =
|
|
failure != null &&
|
|
(failedRelay != config.baseUrl || failedPubkey != pubkey);
|
|
if (!_disposed && !(otherScope && _failureSequence > started)) {
|
|
_record(config.baseUrl, pubkey, error, started);
|
|
}
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
/// Clear a scoped failure only after this community actually reconnects.
|
|
void connected(RelayConfig config) {
|
|
if (_disposed || (failedRelay != null && failedRelay != config.baseUrl)) {
|
|
return;
|
|
}
|
|
failure = null;
|
|
failedRelay = null;
|
|
failedPubkey = null;
|
|
notifyListeners();
|
|
}
|
|
|
|
void rejected(
|
|
RelayConfig config,
|
|
String? usedToken, {
|
|
bool terminal = false,
|
|
}) {
|
|
if (!protects(config) || usedToken == null) return;
|
|
if ('Bearer ${_cached?.token}' == usedToken) _cached = null;
|
|
if (terminal && !_disposed) {
|
|
_record(
|
|
config.baseUrl,
|
|
pubkeyFromNsec(config.nsec),
|
|
AccountFailure.denied,
|
|
++_sequence,
|
|
);
|
|
}
|
|
}
|
|
|
|
void _record(
|
|
String relay,
|
|
String? pubkey,
|
|
AccountFailure error,
|
|
int sequence,
|
|
) {
|
|
failedRelay = relay;
|
|
failedPubkey = pubkey;
|
|
failure = error;
|
|
_failureSequence = sequence;
|
|
notifyListeners();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_disposed = true;
|
|
_cached = null;
|
|
super.dispose();
|
|
}
|
|
}
|
|
|
|
/// Captures the signing context with the request. Never follows redirects with
|
|
/// credentials or replays a failed write automatically.
|
|
class HostedRelayHttpClient extends http.BaseClient {
|
|
HostedRelayHttpClient(
|
|
this.auth,
|
|
this.config, {
|
|
http.Client? inner,
|
|
this.canSend,
|
|
}) : _inner = inner ?? http.Client();
|
|
final HostedRelayAuth auth;
|
|
final RelayConfig config;
|
|
final http.Client _inner;
|
|
final bool Function()? canSend;
|
|
|
|
@override
|
|
Future<http.StreamedResponse> send(http.BaseRequest request) async {
|
|
final origin = Uri.parse(config.baseUrl);
|
|
final scoped = request.url.origin == origin.origin && auth.protects(config);
|
|
if (scoped) {
|
|
request.followRedirects = false;
|
|
request.headers.addAll(await auth.headers(config));
|
|
}
|
|
if (canSend != null && !canSend!()) {
|
|
throw StateError('Relay request expired');
|
|
}
|
|
final response = await _inner.send(request);
|
|
if (scoped && (response.statusCode == 401 || response.statusCode == 403)) {
|
|
auth.rejected(config, request.headers['Nostr-Federated-Identity']);
|
|
}
|
|
return response;
|
|
}
|
|
|
|
@override
|
|
void close() => _inner.close();
|
|
}
|