mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
## Summary Turning push notifications off could stay stuck forever. If the relay kept rejecting the opt-out tombstone, `setPushNotificationsEnabled(false)` swallowed the rejection, and the push bootstrap retried the tombstone on every connect, including after restarts. Settings showed the switch off the whole time, while the relay still held the lease. [docs/mobile-push-suppression.md](https://github.com/block/buzz/blob/main/docs/mobile-push-suppression.md) (rule 29) asks for the opposite: a bounded pending state, then a clear warning that notifications may continue, with no automatic retry, and the relay's actual setting on the next sync. - **Bounded pending.** An opt-out ends about 10 seconds after the tap, across every step (capability lookup, connect, authenticate, publish). While it runs, the row says "Turning off…" and the switch is held, so Off, On, Off can't race the first attempt. - **Definite vs. maybe stored.** A one-shot publish now says whether the relay could have seen the event: a refusal, or a failure before the EVENT went out, is definite; a lost acknowledgment after it went out is not. - **Refused: back to the confirmed setting.** When the relay never stored the tombstone, the saved setting goes back to On (the confirmed lease) and Settings shows "Could not confirm that notifications were turned off. Notifications may continue." with a **Retry** below it. The warning lasts for this app run; after a restart, Settings just shows On. - **Maybe stored: kept as a guard, then read back.** When the acknowledgment was lost, the saved opt-out stays as a guard (no lease or enrollment is published, and the community stays in the iOS notification snapshot), while Settings shows the confirmed On with the same warning. On the next sync, the app reads its own lease from the relay: an inactive lease or none confirms Off; an active one turns the switch back On and keeps the warning. A read that fails changes nothing and is tried again on the next connect. The read asks the relay for strong consistency, so a lagging replica can't answer with the lease the tombstone replaced. It fails if the active community changes while it waits, and it settles only the opt-out it was started for, so a Retry made during the read stays pending. - **No flash on success.** Settings reads the community from the community list, which changes in the same step as each opt-out result. The active-community projection trails it by a keychain read, which could show an accepted opt-out as failed for a frame. - **Explicit retry only.** Retry, or turning the switch off again, makes one attempt at a new generation. The bootstrap's automatic tombstone retry is removed. The warning is announced to screen readers when it appears, and Retry has its own label. This applies to every platform: the opt-out path is shared. ### Related issue None found. ### Testing - The Settings recovery journey covers a refusal restoring On with the warning, a restart that drops the warning and makes no attempt, an attempt that never answers (held switch, then the deadline, kept as a guard), a restart that keeps that warning, and a Retry that succeeds. It runs with loading, absent and failed capability, and on a small phone at text scale 2. - The toggle journey, with the real push bootstrap, covers a refusal (a reconnect neither retries nor reads), an unanswered attempt and a lease that's still active: the read on reconnect, a failed read that changes nothing, then Off or On from what the relay holds. - One-shot publish rows: a relay that stalls at authentication fails as never sent; one that stalls at OK, or closes after the EVENT, fails as maybe stored, all by the deadline. - Lease reader rows: the exact strong-read filter, an empty answer, and a community switch during the descriptor fetch or the query. A provider row holds a read while a Retry fails unanswered: the old read leaves the new opt-out pending. - A widget test with slow secure storage checks every frame of an accepted opt-out for the warning. - A relay database test reads back the author's inactive replacement lease with the filter the app uses, and the lease decryption is checked against the member's own and forged events. ### Screenshots After the relay refuses the opt-out (no relay push capability, so the toggle is reachable only because push is on). | Before | After | | --- | --- | | <img src="https://raw.githubusercontent.com/block/buzz/d2e3c753b3068a68728199096bf30e45e8948af7/pr-9854--before.png" width="300" alt="Before: switch shows off while notifications may continue"> | <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after.png" width="300" alt="After: switch back on, with the warning and Retry below it"> | At text scale 2 on a small phone, Retry sits below the warning: <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--after-large-text.png" width="250" alt="Large text: warning readable, Retry below it"> While an opt-out attempt is in flight (new), the switch is held: <img src="https://raw.githubusercontent.com/block/buzz/ebe70a39406cf2c2104788c4cbc2f3302ba5dbbb/pr-9854--turning-off.png" width="300" alt="Notifications row with the subtitle Turning off and the switch held"> --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
674 lines
21 KiB
Dart
674 lines
21 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:math';
|
|
|
|
import 'package:buzz/shared/crypto/event_signing.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:buzz/shared/http/app_http_client.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
|
|
import '../crypto/nip44.dart';
|
|
import '../relay/nostr_models.dart';
|
|
import '../relay/signed_event_relay.dart';
|
|
import 'push_bridge.dart';
|
|
import 'push_subscription.dart';
|
|
|
|
const buzzPushLeaseKind = 30350;
|
|
const buzzPushTransport = 'apns';
|
|
const _maxSafeJsonInteger = 9007199254740991;
|
|
const _maxLeaseLifetimeSeconds = 2592000;
|
|
const _lowercaseHex64Pattern = r'^[0-9a-f]{64}$';
|
|
const _installationIdPattern = r'^[0-9a-f]{32}$';
|
|
|
|
class BuzzPushLeaseDescriptor {
|
|
final String origin;
|
|
|
|
/// Canonical channel-ID grammar advertised by this relay.
|
|
final String hGrammar;
|
|
final String executorKeyId;
|
|
final String executorPubkey;
|
|
final String transport;
|
|
final int maxLeaseTtlSeconds;
|
|
final int maxContentLength;
|
|
final int maxPlaintextLength;
|
|
final int maxEndpointLength;
|
|
final int maxStringLength;
|
|
|
|
const BuzzPushLeaseDescriptor({
|
|
required this.origin,
|
|
this.hGrammar = 'uuid-v4-lowercase',
|
|
required this.executorKeyId,
|
|
required this.executorPubkey,
|
|
required this.transport,
|
|
required this.maxLeaseTtlSeconds,
|
|
required this.maxContentLength,
|
|
required this.maxPlaintextLength,
|
|
required this.maxEndpointLength,
|
|
required this.maxStringLength,
|
|
});
|
|
|
|
factory BuzzPushLeaseDescriptor.fromRelayInformation(
|
|
Map<String, dynamic> information,
|
|
) {
|
|
// NIP-11 makes the list optional: a relay may leave it out or send none.
|
|
final advertised = information['supported_extensions'];
|
|
if (advertised == null || (advertised is List && advertised.isEmpty)) {
|
|
throw const BuzzPushNotAdvertised();
|
|
}
|
|
final extensions = _stringList(advertised, name: 'supported_extensions');
|
|
if (!extensions.contains('buzz-push-v1')) {
|
|
throw const BuzzPushNotAdvertised();
|
|
}
|
|
|
|
final push = _stringMap(information['push'], name: 'push');
|
|
_requireExactKeys(
|
|
push,
|
|
required: const {
|
|
'origin',
|
|
'keys',
|
|
'push_kinds',
|
|
'h_grammar',
|
|
'class_support',
|
|
'limitation',
|
|
},
|
|
allowed: const {
|
|
'origin',
|
|
'keys',
|
|
'push_kinds',
|
|
'h_grammar',
|
|
'class_support',
|
|
'limitation',
|
|
},
|
|
name: 'push descriptor',
|
|
);
|
|
|
|
final origin = _canonicalOrigin(push['origin']);
|
|
final keys = _mapList(push['keys'], name: 'push.keys');
|
|
final keyIds = <String>{};
|
|
final currentKeys = <Map<String, dynamic>>[];
|
|
for (final key in keys) {
|
|
_requireExactKeys(
|
|
key,
|
|
required: const {'id', 'pubkey'},
|
|
allowed: const {'id', 'pubkey', 'current', 'retiring'},
|
|
name: 'push key',
|
|
);
|
|
final id = _nonEmptyString(key['id'], name: 'push key id');
|
|
if (!keyIds.add(id)) {
|
|
throw FormatException('Duplicate push key id: $id');
|
|
}
|
|
_lowercaseHex64(key['pubkey'], name: 'push key pubkey');
|
|
final current = key['current'];
|
|
final retiring = key['retiring'];
|
|
if (current != null && current is! bool) {
|
|
throw const FormatException('push key current must be a boolean');
|
|
}
|
|
if (retiring != null && retiring is! bool) {
|
|
throw const FormatException('push key retiring must be a boolean');
|
|
}
|
|
if (current == true) currentKeys.add(key);
|
|
}
|
|
if (currentKeys.length != 1) {
|
|
throw const FormatException(
|
|
'push descriptor must contain exactly one current key',
|
|
);
|
|
}
|
|
final currentKey = currentKeys.single;
|
|
|
|
const transport = buzzPushTransport;
|
|
|
|
final pushKinds = _intList(push['push_kinds'], name: 'push_kinds');
|
|
if (!buzzPushEligibleKinds.every(pushKinds.contains)) {
|
|
throw const FormatException(
|
|
'NIP-11 does not advertise every Buzz message kind for push',
|
|
);
|
|
}
|
|
final hGrammar = _nonEmptyString(push['h_grammar'], name: 'h_grammar');
|
|
// Retain the advertised grammar so publication can enforce legacy limits.
|
|
if (hGrammar != 'uuid-lowercase' && hGrammar != 'uuid-v4-lowercase') {
|
|
throw const FormatException('Unsupported push h_grammar');
|
|
}
|
|
|
|
final classSupport = _stringMap(
|
|
push['class_support'],
|
|
name: 'class_support',
|
|
);
|
|
final supportedClasses = _stringList(
|
|
classSupport[buzzPushTransport],
|
|
name: 'class_support.apns',
|
|
);
|
|
const knownClasses = {'default'};
|
|
if (supportedClasses.any((value) => !knownClasses.contains(value))) {
|
|
throw const FormatException('class_support contains an unknown class');
|
|
}
|
|
if (!supportedClasses.contains('default')) {
|
|
throw const FormatException('APNs does not support the default class');
|
|
}
|
|
|
|
final limitation = _stringMap(push['limitation'], name: 'limitation');
|
|
_requireExactKeys(
|
|
limitation,
|
|
required: const {
|
|
'max_lease_ttl',
|
|
'max_leases_per_pubkey',
|
|
'max_subscriptions_per_lease',
|
|
'max_kinds',
|
|
'max_authors',
|
|
'max_h',
|
|
'max_tag_values',
|
|
'max_ignore',
|
|
'max_content_len',
|
|
'max_plaintext_len',
|
|
'max_endpoint_len',
|
|
'max_string_len',
|
|
},
|
|
allowed: const {
|
|
'max_lease_ttl',
|
|
'max_leases_per_pubkey',
|
|
'max_subscriptions_per_lease',
|
|
'max_kinds',
|
|
'max_authors',
|
|
'max_h',
|
|
'max_tag_values',
|
|
'max_ignore',
|
|
'max_content_len',
|
|
'max_plaintext_len',
|
|
'max_endpoint_len',
|
|
'max_string_len',
|
|
},
|
|
name: 'push limitation',
|
|
);
|
|
for (final entry in limitation.entries) {
|
|
_positiveInt(entry.value, name: 'limitation.${entry.key}');
|
|
}
|
|
final maxStringLength = limitation['max_string_len'] as int;
|
|
_checkStringLength(origin, maxStringLength, name: 'origin');
|
|
_checkStringLength(
|
|
currentKey['id'] as String,
|
|
maxStringLength,
|
|
name: 'push key id',
|
|
);
|
|
final maxLeaseTtl = limitation['max_lease_ttl'] as int;
|
|
if (maxLeaseTtl > _maxLeaseLifetimeSeconds) {
|
|
throw const FormatException('max_lease_ttl exceeds the NIP-PL v1 limit');
|
|
}
|
|
|
|
return BuzzPushLeaseDescriptor(
|
|
origin: origin,
|
|
hGrammar: hGrammar,
|
|
executorKeyId: currentKey['id'] as String,
|
|
executorPubkey: currentKey['pubkey'] as String,
|
|
transport: transport,
|
|
maxLeaseTtlSeconds: maxLeaseTtl,
|
|
maxContentLength: limitation['max_content_len'] as int,
|
|
maxPlaintextLength: limitation['max_plaintext_len'] as int,
|
|
maxEndpointLength: limitation['max_endpoint_len'] as int,
|
|
maxStringLength: maxStringLength,
|
|
);
|
|
}
|
|
}
|
|
|
|
/// The relay does not offer Buzz push: an expected answer, not a fault.
|
|
class BuzzPushNotAdvertised extends FormatException {
|
|
const BuzzPushNotAdvertised()
|
|
: super('NIP-11 does not advertise buzz-push-v1');
|
|
}
|
|
|
|
/// The desired lease requires channel IDs that this relay cannot accept yet.
|
|
class BuzzPushChannelGrammarException implements Exception {
|
|
const BuzzPushChannelGrammarException();
|
|
|
|
@override
|
|
String toString() =>
|
|
'Push lease requires uuid-lowercase support from the relay';
|
|
}
|
|
|
|
/// Validate both positive and ignore filters without weakening mute semantics.
|
|
void validateBuzzPushChannelGrammar(
|
|
BuzzPushLeaseDescriptor descriptor,
|
|
List<BuzzPushSubscription> subscriptions,
|
|
) {
|
|
if (descriptor.hGrammar == 'uuid-lowercase') return;
|
|
for (final subscription in subscriptions) {
|
|
for (final filter in [subscription.filter, ...subscription.ignore]) {
|
|
for (final channel in filter.hTags ?? const <String>[]) {
|
|
// The legacy Rust validator checked version 4, not the UUID variant.
|
|
if (channel[14] != '4') {
|
|
throw const BuzzPushChannelGrammarException();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<BuzzPushLeaseDescriptor> fetchBuzzPushLeaseDescriptor(
|
|
String relayBaseUrl, {
|
|
http.Client? client,
|
|
Duration timeout = const Duration(seconds: 8),
|
|
}) async {
|
|
final uri = Uri.tryParse(relayBaseUrl);
|
|
if (uri == null ||
|
|
!const {'http', 'https'}.contains(uri.scheme) ||
|
|
uri.host.isEmpty) {
|
|
throw FormatException('Invalid relay HTTP URL: $relayBaseUrl');
|
|
}
|
|
final requestUri = uri.resolve('/');
|
|
final ownedClient = client ?? newAppHttpClient();
|
|
// Closing a client does not stop a request on a shared session.
|
|
final abort = Completer<void>();
|
|
final request = http.AbortableRequest(
|
|
'GET',
|
|
requestUri,
|
|
abortTrigger: abort.future,
|
|
)..headers['Accept'] = 'application/nostr+json';
|
|
try {
|
|
final response = await ownedClient
|
|
.send(request)
|
|
.then(http.Response.fromStream)
|
|
.timeout(timeout);
|
|
if (response.statusCode != 200) {
|
|
throw StateError(
|
|
'NIP-11 request failed with HTTP ${response.statusCode}: ${response.body}',
|
|
);
|
|
}
|
|
final decoded = jsonDecode(response.body);
|
|
if (decoded is! Map<String, dynamic>) {
|
|
throw const FormatException('NIP-11 response must be a JSON object');
|
|
}
|
|
return BuzzPushLeaseDescriptor.fromRelayInformation(decoded);
|
|
} on TimeoutException {
|
|
noteHttpDeadline(request);
|
|
rethrow;
|
|
} finally {
|
|
abort.complete();
|
|
if (client == null) ownedClient.close();
|
|
}
|
|
}
|
|
|
|
class BuzzPushLeasePublication {
|
|
final String eventId;
|
|
final int expiration;
|
|
final String plaintext;
|
|
|
|
const BuzzPushLeasePublication({
|
|
required this.eventId,
|
|
required this.expiration,
|
|
required this.plaintext,
|
|
});
|
|
}
|
|
|
|
typedef BuzzPushLeaseSubmit =
|
|
Future<NostrEvent> Function({
|
|
required int kind,
|
|
required String content,
|
|
required List<List<String>> tags,
|
|
int? createdAt,
|
|
});
|
|
|
|
Future<BuzzPushLeasePublication> publishBuzzDevPushLease({
|
|
required BuzzPushEndpointGrant grant,
|
|
String? leaseInstallationId,
|
|
int? leaseGeneration,
|
|
required BuzzPushLeaseDescriptor descriptor,
|
|
required String nsec,
|
|
required String memberPubkey,
|
|
required List<BuzzPushSubscription> subscriptions,
|
|
required BuzzPushLeaseSubmit submit,
|
|
DateTime Function() now = DateTime.now,
|
|
}) async {
|
|
validateBuzzPushChannelGrammar(descriptor, subscriptions);
|
|
_validateGrant(grant, descriptor);
|
|
final effectiveLeaseInstallationId =
|
|
leaseInstallationId ?? grant.installationId;
|
|
if (!RegExp(_installationIdPattern).hasMatch(effectiveLeaseInstallationId)) {
|
|
throw const FormatException(
|
|
'Lease installation id must be 16 random bytes encoded as lowercase hex',
|
|
);
|
|
}
|
|
final effectiveLeaseGeneration = leaseGeneration ?? grant.generation;
|
|
if (effectiveLeaseGeneration <= 0 ||
|
|
effectiveLeaseGeneration > _maxSafeJsonInteger) {
|
|
throw const FormatException('Lease generation is invalid');
|
|
}
|
|
final normalizedMemberPubkey = _lowercaseHex64(
|
|
memberPubkey,
|
|
name: 'member pubkey',
|
|
);
|
|
final decoded = nostr.Nip19.decode(payload: nsec);
|
|
if (decoded.prefix != nostr.Nip19Prefix.nsec || decoded.data.length != 64) {
|
|
throw const FormatException('Signing key must be a 32-byte nsec');
|
|
}
|
|
final signingPubkey = derivePublicKeyHex(decoded.data);
|
|
if (signingPubkey != normalizedMemberPubkey) {
|
|
throw const FormatException(
|
|
'Authenticated signing key does not match the lease member pubkey',
|
|
);
|
|
}
|
|
|
|
final nowSeconds = now().millisecondsSinceEpoch ~/ 1000;
|
|
final expiration = min(
|
|
grant.expiresAt,
|
|
nowSeconds + descriptor.maxLeaseTtlSeconds,
|
|
);
|
|
if (expiration <= nowSeconds) {
|
|
throw const FormatException('Endpoint grant is already expired');
|
|
}
|
|
|
|
final plaintextMap = <String, dynamic>{
|
|
'v': 1,
|
|
'origin': descriptor.origin,
|
|
'transport': descriptor.transport,
|
|
'endpoint': grant.endpointGrant,
|
|
'generation': effectiveLeaseGeneration,
|
|
'active': true,
|
|
'subscriptions': [
|
|
for (final subscription in subscriptions) subscription.toJson(),
|
|
],
|
|
};
|
|
final plaintext = jsonEncode(plaintextMap);
|
|
if (utf8.encode(plaintext).length > descriptor.maxPlaintextLength) {
|
|
throw const FormatException('lease plaintext exceeds the advertised limit');
|
|
}
|
|
final conversationKey = getConversationKey(
|
|
decoded.data,
|
|
descriptor.executorPubkey,
|
|
);
|
|
final content = nip44Encrypt(conversationKey, plaintext);
|
|
if (utf8.encode(content).length > descriptor.maxContentLength) {
|
|
throw const FormatException(
|
|
'lease ciphertext exceeds the advertised limit',
|
|
);
|
|
}
|
|
final acknowledged = await submit(
|
|
kind: buzzPushLeaseKind,
|
|
content: content,
|
|
tags: [
|
|
['d', effectiveLeaseInstallationId],
|
|
['expiration', '$expiration'],
|
|
['exec', descriptor.executorKeyId],
|
|
],
|
|
createdAt: nowSeconds,
|
|
);
|
|
if (acknowledged.id.isEmpty) {
|
|
throw StateError('Relay returned an empty event id for the push lease');
|
|
}
|
|
return BuzzPushLeasePublication(
|
|
eventId: acknowledged.id,
|
|
expiration: expiration,
|
|
plaintext: plaintext,
|
|
);
|
|
}
|
|
|
|
Future<BuzzPushLeasePublication> publishBuzzDevPushLeaseThroughRelay({
|
|
required BuzzPushEndpointGrant grant,
|
|
String? leaseInstallationId,
|
|
int? leaseGeneration,
|
|
required BuzzPushLeaseDescriptor descriptor,
|
|
required String nsec,
|
|
required String memberPubkey,
|
|
required List<BuzzPushSubscription> subscriptions,
|
|
required SignedEventRelay relay,
|
|
DateTime Function() now = DateTime.now,
|
|
}) => publishBuzzDevPushLease(
|
|
grant: grant,
|
|
leaseInstallationId: leaseInstallationId,
|
|
leaseGeneration: leaseGeneration,
|
|
descriptor: descriptor,
|
|
nsec: nsec,
|
|
memberPubkey: memberPubkey,
|
|
subscriptions: subscriptions,
|
|
submit: relay.submit,
|
|
now: now,
|
|
);
|
|
|
|
/// Publishes the minimal higher-generation inactive lease used when a
|
|
/// community is removed from this device. Gateway delegation is intentionally
|
|
/// untouched because it is scoped to the installation and relay key, not the
|
|
/// community.
|
|
Future<BuzzPushLeasePublication> publishBuzzPushLeaseTombstone({
|
|
required BuzzPushLeaseDescriptor descriptor,
|
|
required String installationId,
|
|
required int generation,
|
|
required String nsec,
|
|
required String memberPubkey,
|
|
required BuzzPushLeaseSubmit submit,
|
|
DateTime Function() now = DateTime.now,
|
|
}) async {
|
|
if (!RegExp(_installationIdPattern).hasMatch(installationId)) {
|
|
throw const FormatException(
|
|
'Installation id must be 16 random bytes encoded as lowercase hex',
|
|
);
|
|
}
|
|
if (generation <= 0 || generation > _maxSafeJsonInteger) {
|
|
throw const FormatException('Tombstone generation is invalid');
|
|
}
|
|
final normalizedMemberPubkey = _lowercaseHex64(
|
|
memberPubkey,
|
|
name: 'member pubkey',
|
|
);
|
|
final decoded = nostr.Nip19.decode(payload: nsec);
|
|
if (decoded.prefix != nostr.Nip19Prefix.nsec || decoded.data.length != 64) {
|
|
throw const FormatException('Signing key must be a 32-byte nsec');
|
|
}
|
|
if (derivePublicKeyHex(decoded.data) != normalizedMemberPubkey) {
|
|
throw const FormatException(
|
|
'Authenticated signing key does not match the lease member pubkey',
|
|
);
|
|
}
|
|
|
|
final nowSeconds = now().millisecondsSinceEpoch ~/ 1000;
|
|
final expiration = nowSeconds + descriptor.maxLeaseTtlSeconds;
|
|
final plaintextMap = <String, dynamic>{
|
|
'v': 1,
|
|
'origin': descriptor.origin,
|
|
'generation': generation,
|
|
'active': false,
|
|
};
|
|
final plaintext = jsonEncode(plaintextMap);
|
|
if (utf8.encode(plaintext).length > descriptor.maxPlaintextLength) {
|
|
throw const FormatException('lease plaintext exceeds the advertised limit');
|
|
}
|
|
final content = nip44Encrypt(
|
|
getConversationKey(decoded.data, descriptor.executorPubkey),
|
|
plaintext,
|
|
);
|
|
if (utf8.encode(content).length > descriptor.maxContentLength) {
|
|
throw const FormatException(
|
|
'lease ciphertext exceeds the advertised limit',
|
|
);
|
|
}
|
|
final acknowledged = await submit(
|
|
kind: buzzPushLeaseKind,
|
|
content: content,
|
|
tags: [
|
|
['d', installationId],
|
|
['expiration', '$expiration'],
|
|
['exec', descriptor.executorKeyId],
|
|
],
|
|
createdAt: nowSeconds,
|
|
);
|
|
if (acknowledged.id.isEmpty) {
|
|
throw StateError('Relay returned an empty event id for the push tombstone');
|
|
}
|
|
return BuzzPushLeasePublication(
|
|
eventId: acknowledged.id,
|
|
expiration: expiration,
|
|
plaintext: plaintext,
|
|
);
|
|
}
|
|
|
|
void _validateGrant(
|
|
BuzzPushEndpointGrant grant,
|
|
BuzzPushLeaseDescriptor descriptor,
|
|
) {
|
|
if (utf8.encode(grant.installationId).length > 64 ||
|
|
!RegExp(_installationIdPattern).hasMatch(grant.installationId)) {
|
|
throw const FormatException(
|
|
'Installation id must be 16 random bytes encoded as lowercase hex',
|
|
);
|
|
}
|
|
if (grant.relayPubkey != descriptor.executorPubkey) {
|
|
throw const FormatException(
|
|
'Stored endpoint grant is delegated to a different relay key',
|
|
);
|
|
}
|
|
if (grant.endpointGrant.isEmpty ||
|
|
utf8.encode(grant.endpointGrant).length > descriptor.maxEndpointLength) {
|
|
throw const FormatException(
|
|
'Endpoint grant violates the advertised endpoint limit',
|
|
);
|
|
}
|
|
if (grant.endpointEpoch <= 0) {
|
|
throw const FormatException('Endpoint grant epoch is invalid');
|
|
}
|
|
if (grant.generation <= 0 || grant.generation > _maxSafeJsonInteger) {
|
|
throw const FormatException('Endpoint grant generation is invalid');
|
|
}
|
|
}
|
|
|
|
String _canonicalOrigin(Object? value) {
|
|
final origin = _nonEmptyString(value, name: 'origin');
|
|
final uri = Uri.tryParse(origin);
|
|
if (uri == null ||
|
|
!const {'ws', 'wss'}.contains(uri.scheme) ||
|
|
uri.host.isEmpty ||
|
|
uri.userInfo.isNotEmpty ||
|
|
uri.path.isNotEmpty ||
|
|
uri.hasQuery ||
|
|
uri.hasFragment ||
|
|
'${uri.scheme}://${uri.authority}' != origin) {
|
|
throw FormatException('Invalid canonical push origin: $origin');
|
|
}
|
|
return origin;
|
|
}
|
|
|
|
void _checkStringLength(String value, int maximum, {required String name}) {
|
|
if (maximum <= 0 || utf8.encode(value).length > maximum) {
|
|
throw FormatException('$name exceeds its advertised byte limit');
|
|
}
|
|
}
|
|
|
|
String _lowercaseHex64(Object? value, {required String name}) {
|
|
final text = _nonEmptyString(value, name: name);
|
|
if (!RegExp(_lowercaseHex64Pattern).hasMatch(text)) {
|
|
throw FormatException('$name must be exactly 64 lowercase hex characters');
|
|
}
|
|
return text;
|
|
}
|
|
|
|
String _nonEmptyString(Object? value, {required String name}) {
|
|
if (value is! String || value.isEmpty) {
|
|
throw FormatException('$name must be a non-empty string');
|
|
}
|
|
return value;
|
|
}
|
|
|
|
int _positiveInt(Object? value, {required String name}) {
|
|
if (value is! int || value <= 0) {
|
|
throw FormatException('$name must be a positive integer');
|
|
}
|
|
return value;
|
|
}
|
|
|
|
Map<String, dynamic> _stringMap(Object? value, {required String name}) {
|
|
if (value is! Map<String, dynamic>) {
|
|
throw FormatException('$name must be an object');
|
|
}
|
|
return value;
|
|
}
|
|
|
|
List<Map<String, dynamic>> _mapList(Object? value, {required String name}) {
|
|
if (value is! List || value.isEmpty) {
|
|
throw FormatException('$name must be a non-empty array');
|
|
}
|
|
return [
|
|
for (final item in value)
|
|
if (item is Map<String, dynamic>)
|
|
item
|
|
else
|
|
throw FormatException('$name entries must be objects'),
|
|
];
|
|
}
|
|
|
|
List<String> _stringList(Object? value, {required String name}) {
|
|
if (value is! List || value.isEmpty) {
|
|
throw FormatException('$name must be a non-empty string array');
|
|
}
|
|
return [
|
|
for (final item in value)
|
|
if (item is String && item.isNotEmpty)
|
|
item
|
|
else
|
|
throw FormatException('$name entries must be non-empty strings'),
|
|
];
|
|
}
|
|
|
|
List<int> _intList(
|
|
Object? value, {
|
|
required String name,
|
|
bool allowEmpty = false,
|
|
}) {
|
|
if (value is! List || (!allowEmpty && value.isEmpty)) {
|
|
throw FormatException(
|
|
'$name must be ${allowEmpty ? 'an' : 'a non-empty'} integer array',
|
|
);
|
|
}
|
|
return [
|
|
for (final item in value)
|
|
if (item is int && item >= 0)
|
|
item
|
|
else
|
|
throw FormatException('$name entries must be non-negative integers'),
|
|
];
|
|
}
|
|
|
|
void _requireExactKeys(
|
|
Map<String, dynamic> value, {
|
|
required Set<String> required,
|
|
required Set<String> allowed,
|
|
required String name,
|
|
}) {
|
|
final missing = required.difference(value.keys.toSet());
|
|
if (missing.isNotEmpty) {
|
|
throw FormatException('$name is missing ${missing.join(', ')}');
|
|
}
|
|
final unexpected = value.keys.toSet().difference(allowed);
|
|
if (unexpected.isNotEmpty) {
|
|
throw FormatException('$name contains unknown field ${unexpected.first}');
|
|
}
|
|
}
|
|
|
|
/// What a kind-30350 lease the relay holds says: whether it is active, and its
|
|
/// generation.
|
|
typedef BuzzPushLeaseState = ({bool active, int generation});
|
|
|
|
/// Decrypts a lease this member published, for reading back the relay's
|
|
/// actual setting.
|
|
BuzzPushLeaseState decryptBuzzPushLease({
|
|
required NostrEvent event,
|
|
required BuzzPushLeaseDescriptor descriptor,
|
|
required String nsec,
|
|
}) {
|
|
final decoded = nostr.Nip19.decode(payload: nsec);
|
|
if (decoded.prefix != nostr.Nip19Prefix.nsec || decoded.data.length != 64) {
|
|
throw const FormatException('Signing key must be a 32-byte nsec');
|
|
}
|
|
if (event.kind != buzzPushLeaseKind ||
|
|
event.pubkey != derivePublicKeyHex(decoded.data)) {
|
|
throw const FormatException('Not a push lease by this member');
|
|
}
|
|
final plaintext = jsonDecode(
|
|
nip44Decrypt(
|
|
getConversationKey(decoded.data, descriptor.executorPubkey),
|
|
event.content,
|
|
),
|
|
);
|
|
if (plaintext case {
|
|
'active': final bool active,
|
|
'generation': final int generation,
|
|
}) {
|
|
return (active: active, generation: generation);
|
|
}
|
|
throw const FormatException('Push lease plaintext is malformed');
|
|
}
|