Files
buzz/mobile/lib/shared/relay/media_auth.dart
Tom Brow 4ff02bf03b perf(mobile): sign events with native libsecp256k1 on iOS and Android (#8654)
Mobile signs every Nostr event (sends, relay AUTH, media auth headers,
preference writes) in pure Dart on the UI isolate. On an iPhone SE (2nd
gen, Profile build) one BIP-340 signature costs about 10.7 ms and
deriving the public key another 5.6 ms, so a burst of signed writes
drops frames.

This adds `mobile/packages/buzz_secp256k1`, a small FFI package that
builds vendored bitcoin-core/libsecp256k1 v0.8.0 (ecdh, extrakeys,
schnorrsig modules) through a Dart build hook, so the same C and the
same Dart API ship on iOS and Android with no platform bridge code. All
13 `nostr.Event.from` signing sites now go through `signNostrEvent`,
which keeps the `nostr` package's event-id serialization and moves only
key derivation and signing to native code. Calls stay synchronous.

The package also exposes `schnorrVerify` and `ecdhX`; follow-up PRs move
verification and the NIP-44 conversation key over. Incoming relay events
are still not verified, unchanged by this PR.

Safety: the signing context is randomized once per isolate, secret keys
and keypairs are wiped from the native scratch buffer after each call,
aux randomness comes from `Random.secure()`, and the static verify
context runs libsecp256k1's self test before first use.

### Validation

- Added tests: BIP-340 official vectors and native-vs-pure-Dart
differential tests in the package; `event_signing_test.dart` signs with
64 random keys and checks pubkey, event id and signature against the
existing `nostr` builder and verifier, plus malformed-key rejection.
- Full mobile analyze and test suite pass locally.
- Builds: iOS release (framework ~1.3 MB) and Android debug APK with the
library for arm64-v8a, armeabi-v7a and x86_64 (~1.2–1.3 MB each).
- On-device (iPhone SE 2nd gen, Profile, median per op): sign 10,736 µs
→ 41 µs, derive pubkey 5,580 µs → 16.5 µs, full signed event 10,744 µs →
65 µs. Event-id JSON and SHA-256 are 23 µs, so they stay in Dart.
- Device, iOS (iPhone SE 2nd gen, Profile): `buzz_secp256k1.framework`
embedded; the signed-in app authenticated to a real community relay,
loaded channels and history, and paged older messages. No native-asset
or secp256k1 errors in the console.
- Device, Android (emulator, debug): APK contains `libbuzz_secp256k1.so`
and loads it. Against a local mock relay that verifies with the
pure-Dart `nostr` package, the app's NIP-42 AUTH, NIP-98 `POST /query`
headers, and kind 20001/30078 events all verified.
- Blossom GET auth, iOS: the dev relay returns 401 for unauthenticated
`/media/` GETs. From inside the running app, the production
`MediaGetAuthService.headersFor()` header for a nonexistent hash got 404
(accepted, file missing), compared with 401 without it. The community
has no relay-hosted image, so none was rendered.


buzz-review-completed (agent review, Codex and security review clean;
device validation above; human app test not applicable under the mobile
testing exception)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: george <973be878edd6d4f79692a3827f20a6f7fe0ed0362f269ff6b6ba8867033d7d8e@sprout-oss.stage.blox.sqprod.co>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 16:28:26 -07:00

178 lines
6.0 KiB
Dart

import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'relay_provider.dart';
import 'package:buzz/shared/crypto/event_signing.dart';
const _mediaGetAuthKind = 24242;
const _mediaGetAuthLifetimeSeconds = 60;
/// Re-sign this long before the cached auth event expires, so an in-flight
/// request signed just before the boundary still lands well within validity.
/// With a 60-second lifetime, the margin equals the lifetime: each request
/// mints a fresh token (mint-per-request pattern for NIP-FI compliance).
const _mediaGetAuthRefreshMarginSeconds = 60;
/// Builds BUD-01 Blossom `t=get` auth headers for relay-host media URLs.
///
/// Returns an empty map for non-relay URLs or when no signing key is available,
/// so callers can safely use this on arbitrary profile/custom-emoji URLs without
/// leaking Buzz credentials to third-party hosts.
///
/// With a 60-second proof lifetime the refresh margin equals the lifetime, so
/// `_refreshAt == signedAt` and the cache never hits: every call mints a fresh
/// proof (mint-per-request pattern). This is intentional for NIP-FI compliance
/// — caching a 60-second token is staleness-prone and provides no meaningful
/// reduction in signing work. The service itself is rebuilt whenever the relay
/// config — base URL or signing identity — changes, via
/// [mediaGetAuthServiceProvider].
class MediaGetAuthService {
final String _baseUrl;
final String? _nsec;
final String? _pubkey;
final DateTime Function() _now;
Map<String, String>? _cachedHeaders;
DateTime? _refreshAt;
MediaGetAuthService({
required String baseUrl,
required String? nsec,
String? pubkey,
DateTime Function()? now,
}) : _baseUrl = baseUrl,
_nsec = nsec,
_pubkey = pubkey,
_now = now ?? DateTime.now;
bool isRelayMediaUrl(String url) {
final uri = Uri.tryParse(url);
final relayUri = Uri.tryParse(_baseUrl);
if (uri == null || relayUri == null) return false;
return _isRelayMediaUrl(uri, relayUri);
}
Map<String, String> headersFor(String url) {
final nsec = _nsec;
if (nsec == null || nsec.isEmpty) return const {};
if (!isRelayMediaUrl(url)) return const {};
final cached = _cachedHeaders;
final refreshAt = _refreshAt;
if (cached != null && refreshAt != null && _now().isBefore(refreshAt)) {
return cached;
}
try {
final signedAt = _now();
final authEvent = _buildGetAuthEvent(nsec);
final encoded = base64Url
.encode(utf8.encode(authEvent.toJson()))
.replaceAll('=', '');
final headers = Map<String, String>.unmodifiable({
'Authorization': 'Nostr $encoded',
});
_cachedHeaders = headers;
_refreshAt = signedAt.add(
const Duration(
seconds:
_mediaGetAuthLifetimeSeconds - _mediaGetAuthRefreshMarginSeconds,
),
);
return headers;
} catch (_) {
// Read auth is best-effort: while the relay rollout flag is off, an
// unsigned fetch still works. Once the flag is on, this request will 403
// instead of crashing the widget tree because local key material is bad.
return const {};
}
}
bool _isRelayMediaUrl(Uri uri, Uri relayUri) {
if (uri.scheme != 'http' && uri.scheme != 'https') return false;
if (uri.host.isEmpty || relayUri.host.isEmpty) return false;
// Extract the URL's origin and path. Query strings are ignored for media
// host/path detection, matching the fetch target shape used by descriptors.
final base = '${uri.scheme}://${uri.authority}';
final mediaAuthority = extractServerAuthority(base);
final relayAuthority = extractServerAuthority(_baseUrl);
if (mediaAuthority == null || relayAuthority == null) return false;
if (mediaAuthority.toLowerCase() != relayAuthority.toLowerCase()) {
return false;
}
return uri.path.startsWith('/media/');
}
nostr.Event _buildGetAuthEvent(String nsec) {
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
if (privkeyHex.isEmpty) {
throw Exception('Invalid nsec');
}
final expiration =
(_now().millisecondsSinceEpoch ~/ 1000) + _mediaGetAuthLifetimeSeconds;
final tags = <List<String>>[
['t', 'get'],
['expiration', '$expiration'],
if (extractServerAuthority(_baseUrl) case final authority?)
['server', authority],
];
return signNostrEvent(
kind: _mediaGetAuthKind,
content: 'Get buzz-media',
tags: tags,
secretKey: privkeyHex,
// Reuse the cached pubkey rather than deriving it per image.
pubkey: _pubkey,
);
}
}
final mediaGetAuthServiceProvider = Provider<MediaGetAuthService>((ref) {
final config = ref.watch(relayConfigProvider);
return MediaGetAuthService(
baseUrl: config.baseUrl,
nsec: config.nsec,
pubkey: ref.watch(myPubkeyProvider),
);
});
Map<String, String> mediaGetHeadersFor(WidgetRef ref, String url) {
return ref.read(mediaGetAuthServiceProvider).headersFor(url);
}
Map<String, String> mediaGetHeadersForContext(
BuildContext context,
String url,
) {
final container = ProviderScope.containerOf(context, listen: false);
return container.read(mediaGetAuthServiceProvider).headersFor(url);
}
String? extractServerAuthority(String baseUrl) {
final uri = Uri.parse(baseUrl);
if (uri.host.isEmpty) return null;
final host = uri.host.contains(':') ? '[${uri.host}]' : uri.host;
final port = uri.hasPort ? uri.port : null;
final authority = port == null ? host : '$host:$port';
return _normalizeAuthority(authority);
}
String _normalizeAuthority(String authority) {
var normalized = authority.trim().toLowerCase();
if (normalized.endsWith('.')) {
normalized = normalized.substring(0, normalized.length - 1);
}
if (normalized.endsWith(':443')) {
return normalized.substring(0, normalized.length - ':443'.length);
}
if (normalized.endsWith(':80')) {
return normalized.substring(0, normalized.length - ':80'.length);
}
return normalized;
}