mirror of
https://github.com/block/buzz.git
synced 2026-11-03 16:01:35 +00:00
Follows #8654. Deriving an x-only public key from a secret key with `nostr.Keys(secret).public` costs about 5.6 ms in pure Dart on an iPhone SE (2nd gen, Profile). The app does it in 10 places, including relay config, the signed-event relay's `pubkey` getter, push lease checks, status updates, and the settings identity row's `build` method. This routes all of them through `derivePublicKeyHex` from #8654, which takes 16.5 µs on the same device. Behavior is unchanged for valid keys: output is the same lowercase hex. For a malformed or out-of-range key the thrown type changes from nostr's `InvalidKeyException` to `ArgumentError`; every affected site either catches all errors or rethrows its own `FormatException`/`StateError`, and nothing in `lib` or `test` matches on the old type. Sites that need a full `nostr.Keys` object (key generation, `AccountIdentityStore`) are unchanged. ### Validation - `derivePublicKeyHex` is checked against `nostr.Keys` for 64 random keys in #8654's `event_signing_test.dart`. - Full mobile analyze and test suite pass on this branch after rebasing onto main, including the package's own tests. - iPhone 12 mini, Profile build of this stack (with #8656 and #8657 on top): paired to the internal Buzz community through Desktop; relay auth, identity row, avatar, and channel/DM/inbox loading all worked under the derived key. 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>
147 lines
5.3 KiB
Dart
147 lines
5.3 KiB
Dart
import 'package:buzz/shared/crypto/event_signing.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
import '../hosted/hosted_relay_auth.dart';
|
|
import '../community/community_provider.dart';
|
|
import 'relay_client.dart';
|
|
|
|
/// Relay connection configuration.
|
|
///
|
|
/// In the pure-nostr world the only secrets the app cares about are:
|
|
/// - `baseUrl` — where the relay lives (used for WS + media upload)
|
|
/// - `nsec` — the user's signing key (drives NIP-42 AUTH and event sigs)
|
|
class RelayConfig {
|
|
const RelayConfig({required String baseUrl, String? nsec})
|
|
: _baseUrl = baseUrl,
|
|
_nsec = nsec;
|
|
|
|
/// Relay origin exactly as the active community stored it.
|
|
final String _baseUrl;
|
|
|
|
/// Normalized Nostr secret key shared by identity, signing, and NIP-42 AUTH.
|
|
String? get nsec => _nsec?.trim();
|
|
|
|
final String? _nsec;
|
|
|
|
/// The origin as persisted, before scheme canonicalization.
|
|
///
|
|
/// Exists solely so identity-scoped storage keys written before [baseUrl]
|
|
/// was canonicalized stay reachable — see [readMigratedPref]. Never use it
|
|
/// for network I/O; [baseUrl] and [wsUrl] are the addresses to connect to.
|
|
String get storedOrigin => _baseUrl;
|
|
|
|
/// Relay origin as an HTTP(S) URL.
|
|
///
|
|
/// Communities are persisted with whichever scheme their onboarding flow
|
|
/// used: device pairing stores `https://` (it rejects anything else), while
|
|
/// an invite join stores the `wss://` relay URL carried by the invite link.
|
|
/// Every consumer treats this as an HTTP origin — [wsUrl], the `/query`
|
|
/// endpoint, media upload and Blossom auth — so a `wss://` base silently
|
|
/// degrades all of them. Folding the websocket schemes back here keeps both
|
|
/// onboarding paths equivalent, including for already-persisted communities.
|
|
///
|
|
/// Derived rather than normalized in the constructor so that the constructor
|
|
/// stays `const`: the compile-time fallback below relies on canonicalization
|
|
/// to keep its identity stable across rebuilds, and Riverpod's default
|
|
/// `updateShouldNotify` is `previous != next`, which falls back to identity
|
|
/// here. A fresh instance per rebuild would resubscribe every listener.
|
|
String get baseUrl {
|
|
final uri = Uri.tryParse(_baseUrl);
|
|
if (uri == null) return _baseUrl;
|
|
final scheme = switch (uri.scheme) {
|
|
'wss' => 'https',
|
|
'ws' => 'http',
|
|
_ => null,
|
|
};
|
|
return scheme == null ? _baseUrl : uri.replace(scheme: scheme).toString();
|
|
}
|
|
|
|
/// Derive the websocket URL from the HTTP base URL.
|
|
String get wsUrl {
|
|
final uri = Uri.parse(baseUrl);
|
|
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';
|
|
return uri.replace(scheme: scheme).toString();
|
|
}
|
|
}
|
|
|
|
/// Compile-time environment config via --dart-define.
|
|
///
|
|
/// Run with:
|
|
/// flutter run --dart-define=BUZZ_RELAY_URL=http://localhost:3000 \
|
|
/// --dart-define=BUZZ_PUSH_GATEWAY_URL=http://localhost:8080
|
|
///
|
|
/// Or create a `.env.json` and use --dart-define-from-file=.env.json
|
|
class Env {
|
|
static const relayUrl = String.fromEnvironment(
|
|
'BUZZ_RELAY_URL',
|
|
defaultValue: 'http://localhost:3000',
|
|
);
|
|
|
|
/// Optional gateway origin. Without it this artifact has no push capability.
|
|
static const pushGatewayUrl = String.fromEnvironment('BUZZ_PUSH_GATEWAY_URL');
|
|
|
|
/// Whether this artifact can offer push notification enrollment.
|
|
static const pushGatewayConfigured = pushGatewayUrl != '';
|
|
}
|
|
|
|
class RelayConfigNotifier extends Notifier<RelayConfig> {
|
|
@override
|
|
RelayConfig build() {
|
|
// Push lease bookkeeping updates the community while using its live
|
|
// session. Only connection-context changes may restart that session.
|
|
final context = ref.watch(
|
|
activeCommunityProvider.select((value) {
|
|
final active = value.value;
|
|
return (id: active?.id, relayUrl: active?.relayUrl, nsec: active?.nsec);
|
|
}),
|
|
);
|
|
if (context.relayUrl != null) {
|
|
return RelayConfig(baseUrl: context.relayUrl!, nsec: context.nsec);
|
|
}
|
|
|
|
// Fallback to compile-time env config (dev mode).
|
|
return const RelayConfig(baseUrl: Env.relayUrl);
|
|
}
|
|
|
|
void update({required String baseUrl, String? nsec}) {
|
|
state = RelayConfig(baseUrl: baseUrl, nsec: nsec);
|
|
}
|
|
}
|
|
|
|
final relayConfigProvider = NotifierProvider<RelayConfigNotifier, RelayConfig>(
|
|
RelayConfigNotifier.new,
|
|
);
|
|
|
|
/// Derive the hex pubkey from a bech32 nsec, or null on any failure.
|
|
String? pubkeyFromNsec(String? nsec) {
|
|
if (nsec == null || nsec.isEmpty) return null;
|
|
try {
|
|
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
|
|
if (privkeyHex.isEmpty) return null;
|
|
return derivePublicKeyHex(privkeyHex);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/// The current user's hex pubkey, derived from the active community nsec.
|
|
final myPubkeyProvider = Provider<String?>((ref) {
|
|
final config = ref.watch(relayConfigProvider);
|
|
return pubkeyFromNsec(config.nsec);
|
|
});
|
|
|
|
/// Provides a [RelayClient] that reacts to config changes.
|
|
///
|
|
/// Only used for the media upload HTTP endpoint now — all data flow goes
|
|
/// through the relay WebSocket session.
|
|
final relayClientProvider = Provider<RelayClient>((ref) {
|
|
final config = ref.watch(relayConfigProvider);
|
|
final client = RelayClient(
|
|
baseUrl: config.baseUrl,
|
|
httpClient: ref.watch(hostedHttpClientFactoryProvider)(),
|
|
);
|
|
ref.onDispose(client.dispose);
|
|
return client;
|
|
});
|