Skip to content

Commit 804c07f

Browse files
committed
fix(mobile): make verified owner policy override runtime access
Signed-off-by: Logan Johnson <[email protected]>
1 parent b2253ce commit 804c07f

4 files changed

Lines changed: 442 additions & 1 deletion

File tree

‎mobile/lib/features/channels/mentions/mention_candidates.dart‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ bool agentIsSharedWithUser(
1212
Set<String> sharedChannelIds,
1313
String? currentPubkey,
1414
) {
15+
if (currentPubkey != null &&
16+
agent.ownerPubkey == currentPubkey.toLowerCase() &&
17+
const ['owner-only', 'allowlist', 'anyone'].contains(agent.respondTo)) {
18+
return true;
19+
}
1520
if (agent.respondTo == 'allowlist' && currentPubkey != null) {
1621
return agent.respondToAllowlist.contains(currentPubkey.toLowerCase());
1722
}
@@ -62,6 +67,11 @@ List<MentionCandidate> buildMentionCandidates({
6267
final profile = userCache[pk];
6368
final ownerPubkey = ownerByAgentPubkey[pk] ?? profile?.ownerPubkey;
6469
final isAgent = member.isBot || ownerPubkey != null;
70+
final policy = relayAgents.where((agent) => agent.pubkey == pk).firstOrNull;
71+
if (policy?.ownerPubkey != null &&
72+
!agentIsSharedWithUser(policy!, sharedChannelIds, currentPubkey)) {
73+
continue;
74+
}
6575
candidates.add(
6676
MentionCandidate(
6777
pubkey: pk,
@@ -121,6 +131,12 @@ List<MentionCandidate> buildMentionCandidates({
121131
// verified NIP-OA owner) or shared via the relay agent directory.
122132
final ownedByCurrentUser =
123133
currentLower != null && ownerPubkey?.toLowerCase() == currentLower;
134+
final policy = relayAgents
135+
.where((agent) => agent.pubkey == pk)
136+
.firstOrNull;
137+
if (policy?.ownerPubkey != null && !sharedAgentPubkeys.contains(pk)) {
138+
continue;
139+
}
124140
if (!ownedByCurrentUser && !sharedAgentPubkeys.contains(pk)) {
125141
continue;
126142
}

‎mobile/lib/shared/mentions/agent_identity_provider.dart‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import 'package:flutter/foundation.dart';
55
import 'package:hooks_riverpod/hooks_riverpod.dart';
66

77
import '../../shared/crypto/nip_oa.dart';
8+
import '../../shared/crypto/signed_event.dart';
89
import '../../shared/relay/relay.dart';
910

11+
part 'agent_policy.dart';
12+
1013
/// A relay agent parsed from its kind:10100 agent-profile event.
1114
///
1215
/// Mirrors the fields desktop's `RelayAgent` uses for mention eligibility
@@ -15,13 +18,15 @@ import '../../shared/relay/relay.dart';
1518
class AgentDirectoryEntry {
1619
final String pubkey;
1720
final String? displayName;
21+
final String? ownerPubkey;
1822
final String? respondTo;
1923
final List<String> respondToAllowlist;
2024
final List<String> channelIds;
2125

2226
const AgentDirectoryEntry({
2327
required this.pubkey,
2428
this.displayName,
29+
this.ownerPubkey,
2530
this.respondTo,
2631
this.respondToAllowlist = const [],
2732
this.channelIds = const [],
@@ -66,7 +71,7 @@ final agentDirectoryProvider = FutureProvider<List<AgentDirectoryEntry>>((
6671
if (sessionState.status != SessionStatus.connected) return const [];
6772
final session = ref.read(relaySessionProvider.notifier);
6873
final events = await session.fetchHistory(NostrFilters.agentProfiles());
69-
return [for (final event in events) AgentDirectoryEntry.fromEvent(event)];
74+
return resolveAgentPolicies(session, events);
7075
});
7176

7277
/// Verified NIP-OA owner pubkey per agent pubkey, from the agents' kind:0
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
part of 'agent_identity_provider.dart';
2+
3+
bool _newer(NostrEvent event, NostrEvent previous) =>
4+
event.createdAt > previous.createdAt ||
5+
(event.createdAt == previous.createdAt &&
6+
event.id.compareTo(previous.id) < 0);
7+
8+
/// Exact-coordinate queries, bounded to ten filters in flight. An empty result
9+
/// is distinct from a failed read; failures must never revive runtime access.
10+
Future<List<NostrEvent>> _queryAgentFilters(
11+
RelaySessionNotifier session,
12+
List<NostrFilter> filters,
13+
) async {
14+
final events = <NostrEvent>[];
15+
for (var start = 0; start < filters.length; start += 10) {
16+
events.addAll(
17+
await session.queryRelay(filters.skip(start).take(10).toList()),
18+
);
19+
}
20+
return events;
21+
}
22+
23+
/// Overlay current owner-authenticated policy onto the existing runtime
24+
/// directory. This does not expand discovery to owner-only coordinates yet.
25+
Future<List<AgentDirectoryEntry>> resolveAgentPolicies(
26+
RelaySessionNotifier session,
27+
List<NostrEvent> runtimeEvents,
28+
) async {
29+
final latest = <String, NostrEvent>{};
30+
for (final event in runtimeEvents.where((event) => event.kind == 10100)) {
31+
final previous = latest[event.pubkey];
32+
if (previous == null || _newer(event, previous)) {
33+
latest[event.pubkey] = event;
34+
}
35+
}
36+
final profiles = latestProfileEvents(
37+
await _queryAgentFilters(session, [
38+
for (final key in latest.keys)
39+
NostrFilter(kinds: const [0], authors: [key], limit: 1),
40+
]),
41+
);
42+
final owners = <String, String>{};
43+
for (final profile in profiles.values) {
44+
final owner = verifiedOaOwnerPubkey(profile);
45+
if (owner != null && latest.containsKey(profile.pubkey)) {
46+
owners[profile.pubkey] = owner;
47+
}
48+
}
49+
final policies = await _queryAgentFilters(session, [
50+
for (final owner in owners.entries)
51+
NostrFilter(
52+
kinds: const [30177],
53+
authors: [owner.value],
54+
tags: {
55+
'#d': [owner.key],
56+
},
57+
limit: 1,
58+
),
59+
]);
60+
return mergeAgentPolicies(latest.values, policies, owners);
61+
}
62+
63+
/// Latest signed owner policy is the access authority, not runtime claims.
64+
/// Malformed/revoked policy reserves the identity with deny-all permissions;
65+
/// it must not fall back to an older permissive policy or kind:10100 record.
66+
List<AgentDirectoryEntry> mergeAgentPolicies(
67+
Iterable<NostrEvent> runtimeEvents,
68+
Iterable<NostrEvent> policies,
69+
Map<String, String> verifiedOwners,
70+
) {
71+
final latestPolicies = <String, NostrEvent>{};
72+
for (final event in policies) {
73+
final key = event.getTagValue('d');
74+
if (key == null || verifiedOwners[key] != event.pubkey) continue;
75+
final previous = latestPolicies[key];
76+
if (previous == null || _newer(event, previous)) {
77+
latestPolicies[key] = event;
78+
}
79+
}
80+
final agents = <String, AgentDirectoryEntry>{};
81+
for (final event in runtimeEvents) {
82+
if (event.kind != 10100 || !verifySignedEvent(event)) continue;
83+
final data = _tryDecodeJsonMap(event.content);
84+
if (data == null) continue;
85+
agents[event.pubkey] = AgentDirectoryEntry(
86+
pubkey: event.pubkey,
87+
displayName: data['display_name'] is String
88+
? data['display_name'] as String
89+
: data['name'] is String
90+
? data['name'] as String
91+
: null,
92+
respondTo: data['respond_to'] is String
93+
? data['respond_to'] as String
94+
: null,
95+
respondToAllowlist: _stringList(data['respond_to_allowlist']) ?? const [],
96+
channelIds: _stringList(data['channel_ids']) ?? const [],
97+
);
98+
}
99+
for (final entry in latestPolicies.entries) {
100+
final event = entry.value;
101+
final data = _tryDecodeJsonMap(event.content);
102+
final mode = data?['respond_to'];
103+
final parallelism = data?['parallelism'];
104+
final allowlist = _stringList(data?['respond_to_allowlist'] ?? []);
105+
final valid =
106+
event.kind == 30177 &&
107+
verifySignedEvent(event) &&
108+
event.tags.where((tag) => tag.isNotEmpty && tag[0] == 'd').length ==
109+
1 &&
110+
data?['name'] is String &&
111+
parallelism is int &&
112+
parallelism >= 0 &&
113+
parallelism <= 4294967295 &&
114+
const ['owner-only', 'allowlist', 'anyone', 'nobody'].contains(mode) &&
115+
allowlist != null &&
116+
const [
117+
'persona_id',
118+
'system_prompt',
119+
'model',
120+
'provider',
121+
'persona_source_version',
122+
].every((key) => data?[key] == null || data?[key] is String);
123+
agents[entry.key] = AgentDirectoryEntry(
124+
pubkey: entry.key,
125+
ownerPubkey: event.pubkey,
126+
displayName: valid
127+
? data!['name'] as String
128+
: agents[entry.key]?.displayName,
129+
respondTo: valid ? mode as String : 'nobody',
130+
respondToAllowlist: valid ? allowlist : const [],
131+
channelIds: agents[entry.key]?.channelIds ?? const [],
132+
);
133+
}
134+
return agents.values.toList();
135+
}
136+
137+
List<String>? _stringList(Object? value) =>
138+
value is List && value.every((v) => v is String)
139+
? value.cast<String>().map((v) => v.toLowerCase()).toList()
140+
: null;

0 commit comments

Comments
 (0)