@@ -9,18 +9,30 @@ import 'relay_provider.dart';
99const _mediaGetAuthKind = 24242 ;
1010const _mediaGetAuthLifetimeSeconds = 600 ;
1111
12+ /// Re-sign this long before the cached auth event expires, so an in-flight
13+ /// request signed just before the boundary still lands well within validity.
14+ const _mediaGetAuthRefreshMarginSeconds = 60 ;
15+
1216/// Builds BUD-01 Blossom `t=get` auth headers for relay-host media URLs.
1317///
1418/// Returns an empty map for non-relay URLs or when no signing key is available,
1519/// so callers can safely use this on arbitrary profile/custom-emoji URLs without
1620/// leaking Buzz credentials to third-party hosts.
17- @immutable
21+ ///
22+ /// The signed header is memoized until [_mediaGetAuthRefreshMarginSeconds]
23+ /// before expiry: repeated calls return the byte-identical map instead of
24+ /// producing a fresh Schnorr signature per widget build. The service itself is
25+ /// rebuilt (dropping the memo) whenever the relay config — base URL or signing
26+ /// identity — changes, via [mediaGetAuthServiceProvider] .
1827class MediaGetAuthService {
1928 final String _baseUrl;
2029 final String ? _nsec;
2130 final DateTime Function () _now;
2231
23- const MediaGetAuthService ({
32+ Map <String , String >? _cachedHeaders;
33+ DateTime ? _refreshAt;
34+
35+ MediaGetAuthService ({
2436 required String baseUrl,
2537 required String ? nsec,
2638 DateTime Function ()? now,
@@ -36,12 +48,29 @@ class MediaGetAuthService {
3648 if (uri == null || relayUri == null ) return const {};
3749 if (! _isRelayMediaUrl (uri, relayUri)) return const {};
3850
51+ final cached = _cachedHeaders;
52+ final refreshAt = _refreshAt;
53+ if (cached != null && refreshAt != null && _now ().isBefore (refreshAt)) {
54+ return cached;
55+ }
56+
3957 try {
58+ final signedAt = _now ();
4059 final authEvent = _buildGetAuthEvent (nsec);
4160 final encoded = base64Url
4261 .encode (utf8.encode (authEvent.toJson ()))
4362 .replaceAll ('=' , '' );
44- return {'Authorization' : 'Nostr $encoded ' };
63+ final headers = Map <String , String >.unmodifiable ({
64+ 'Authorization' : 'Nostr $encoded ' ,
65+ });
66+ _cachedHeaders = headers;
67+ _refreshAt = signedAt.add (
68+ const Duration (
69+ seconds:
70+ _mediaGetAuthLifetimeSeconds - _mediaGetAuthRefreshMarginSeconds,
71+ ),
72+ );
73+ return headers;
4574 } catch (_) {
4675 // Read auth is best-effort: while the relay rollout flag is off, an
4776 // unsigned fetch still works. Once the flag is on, this request will 403
0 commit comments