Files
buzz/mobile/lib/shared/agents/owned_agent_directory.dart
Tom Brow eee75a1c7b perf(mobile): verify owned-agent registrations natively (#8938)
## Summary

`loadOwnedAgentDirectory` checks the signature of each kind:30177 agent
registration before it trusts the registration's `model`. It did this
with `nostr.Event.fromJson`, which runs the `nostr` package's pure-Dart
Schnorr code on the UI isolate.

This change uses `verifiedNostrEventFromJson`, which the app's other
verification sites already use. It makes the same timestamp, event id
and BIP-340 signature checks with the bundled libsecp256k1. It also
requires lowercase hex for the pubkey and signature, which relay events
already use.

A registration that fails verification still lists its agent without a
model, as before.

## Measurements

- **Synthetic** (Mac, `flutter test`, 20 signed registrations, warm):
pure Dart 163 ms, native 2.6 ms.
- **Device** (iPhone 12 mini, Profile build, first channel open after
launch, first 5 s; runs not matched): `loadOwnedAgentDirectory`
inclusive CPU was 71 ms before (69 ms in `Event._assertValid`) and 2 ms
after.

## Testing

- New test: a registration with a wrong signature still lists the agent,
with no model. The correctly signed registration keeps its model.
- `just mobile-check mobile-test` passes (pre-push hook).

🤖 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: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:00:26 -08:00

154 lines
5.5 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import '../crypto/event_signing.dart';
import '../crypto/nip_oa.dart';
import '../mentions/agent_identity_provider.dart';
import '../relay/relay.dart';
/// Public model information accompanying a verified owned agent profile.
class OwnedAgentDirectoryEntry extends AgentDirectoryEntry {
const OwnedAgentDirectoryEntry({
required super.pubkey,
super.displayName,
super.avatarUrl,
this.model,
});
final String? model;
}
/// The owner's agents in the active community, as desktop's Agents tab lists
/// them: each agent's newest kind:30177 registration must name it and carry
/// the `runtime` tag of its agent type. Registrations an earlier Buzz wrote
/// have no `runtime` until the agent is imported, so they are not listed.
/// Signed profiles prove ownership.
final ownedAgentDirectoryProvider =
FutureProvider<List<OwnedAgentDirectoryEntry>>((ref) async {
ref.watch(relayConfigProvider);
final owner = ref.watch(myPubkeyProvider);
final session = ref.watch(relaySessionProvider);
if (owner == null) return const [];
// Stay loading until connected: an empty list would read as "no
// listed agents" and hide the owner's agents from mentions. The
// provider rebuilds when the session status changes.
if (session.status != SessionStatus.connected) {
return Completer<List<OwnedAgentDirectoryEntry>>().future;
}
final relay = ref.read(relaySessionProvider.notifier);
return loadOwnedAgentDirectory(
owner,
(filter) => relay.queryRelay([filter]),
);
});
/// Uses the active community's authenticated query boundary and paginates it.
Future<List<OwnedAgentDirectoryEntry>> loadOwnedAgentDirectory(
String owner,
Future<List<NostrEvent>> Function(NostrFilter) query,
) async {
final registrations = <String, NostrEvent>{};
final seen = <String>{};
for (var page = 1; ; page++) {
final events = await query(
NostrFilter(
kinds: const [30177],
authors: [owner],
limit: 100,
extensions: {'page': page},
),
);
final fresh = events.where((event) => seen.add(event.id)).toList();
for (final event in fresh) {
if (event.kind != 30177 || event.pubkey != owner) continue;
final key = _tagValue(event, 'd');
if (key == null || !RegExp(r'^[0-9a-f]{64}$').hasMatch(key)) continue;
final previous = registrations[key];
if (previous == null ||
event.createdAt > previous.createdAt ||
(event.createdAt == previous.createdAt &&
event.id.compareTo(previous.id) < 0)) {
registrations[key] = event;
}
}
if (events.length < 100 || fresh.isEmpty) break;
}
final keys = {
for (final MapEntry(:key, :value) in registrations.entries)
if (isListedAgentRegistration(value)) key,
};
final results = <OwnedAgentDirectoryEntry>[];
final ordered = keys.toList();
for (var offset = 0; offset < ordered.length; offset += 50) {
final batch = ordered.skip(offset).take(50).toList();
final events = await query(NostrFilters.profilesBatch(batch));
final latest = <String, NostrEvent>{};
for (final event in events) {
if (event.kind != 0 || !batch.contains(event.pubkey)) continue;
final previous = latest[event.pubkey];
if (previous == null ||
event.createdAt > previous.createdAt ||
(event.createdAt == previous.createdAt &&
event.id.compareTo(previous.id) < 0)) {
latest[event.pubkey] = event;
}
}
for (final event in latest.values) {
if (verifiedProfileOaOwnerPubkey(event) == owner) {
final profile = AgentDirectoryEntry.fromEvent(event);
String? model;
try {
final registration = registrations[event.pubkey]!;
// Native libsecp256k1 verification; the pure-Dart codec took
// several milliseconds per registration on the UI isolate.
verifiedNostrEventFromJson(jsonEncode(registration.toJson()));
final data = jsonDecode(registration.content);
if (data is Map && data['model'] is String) {
final value = (data['model'] as String).trim();
if (value.isNotEmpty) model = value;
}
} catch (_) {
/* Older registrations may have no metadata. */
}
results.add(
OwnedAgentDirectoryEntry(
pubkey: profile.pubkey,
displayName: profile.displayName,
avatarUrl: profile.avatarUrl,
model: model,
),
);
}
}
}
return results;
}
/// An agent type key, `pluginId/typeId`, as desktop's `RUNTIME` pattern
/// (buzz-app `src/features/agents/service.ts`) accepts it.
final _runtimePattern = RegExp(r'^[a-z0-9][a-z0-9._-]*/[a-z0-9][a-z0-9._-]*$');
/// Whether desktop lists this kind:30177 registration as one of the owner's
/// agents: it names the agent and carries a valid `runtime` tag.
bool isListedAgentRegistration(NostrEvent event) {
if (!_runtimePattern.hasMatch(_tagValue(event, 'runtime') ?? '')) {
return false;
}
try {
final content = jsonDecode(event.content);
return content is Map &&
content['name'] is String &&
(content['name'] as String).trim().isNotEmpty;
} on FormatException {
return false;
}
}
String? _tagValue(NostrEvent event, String name) {
for (final tag in event.tags) {
if (tag.length >= 2 && tag.first == name) return tag[1];
}
return null;
}