|
| 1 | +part of 'agent_identity_provider.dart'; |
| 2 | + |
| 3 | +/// Evidence requirements, not a claim that an ordinary identity is human. |
| 4 | +enum SelectedMentionKind { ordinary, agent, unresolvedAgent } |
| 5 | + |
| 6 | +/// Fresh evidence for one exact selected key. This is NOT permission to write: |
| 7 | +/// consumers must apply their existing agent eligibility evaluator to [agent], |
| 8 | +/// normal channel invitation permission, consent and scope fences separately. |
| 9 | +/// An existing member needs no role write, whatever their current role is. |
| 10 | +class SelectedMentionAuthorization { |
| 11 | + final SelectedMentionKind kind; |
| 12 | + final bool isMember; |
| 13 | + |
| 14 | + /// Policy projection with relay-authenticated destination membership only. |
| 15 | + /// Null for ordinary identities or unresolved prior-agent evidence. Missing |
| 16 | + /// owner policy produces a deny-all entry, never runtime fallback. |
| 17 | + final AgentDirectoryEntry? agent; |
| 18 | + |
| 19 | + const SelectedMentionAuthorization._(this.kind, this.isMember, this.agent); |
| 20 | + |
| 21 | + bool get requiresAgentAuthorization => kind != SelectedMentionKind.ordinary; |
| 22 | + |
| 23 | + /// Role selection only, never an invitation authorization. A consumer must |
| 24 | + /// first validate eligibility and consent and skip writes for existing members. |
| 25 | + String? get invitationRole => switch (kind) { |
| 26 | + SelectedMentionKind.ordinary => 'member', |
| 27 | + SelectedMentionKind.agent => 'bot', |
| 28 | + SelectedMentionKind.unresolvedAgent => null, |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +/// Read all selected keys, not just candidates whose saved isAgent bit is true. |
| 33 | +/// [priorAgentKeys] is denial-only taint: lost provenance cannot turn a saved |
| 34 | +/// agent capability into an ordinary-member invitation or notification bypass. |
| 35 | +/// Absence of agent evidence permits the existing ordinary membership flow, |
| 36 | +/// NOT a humanity assertion. Positive fresh evidence overrides saved false. |
| 37 | +/// |
| 38 | +/// Every requested key has a result or the entire read throws. This read makes |
| 39 | +/// no cache writes and does not opt into resolveProfileOwners. Check [isCurrent] |
| 40 | +/// again before each side effect; re-read after consent and accepted invitations. |
| 41 | +Future<Map<String, SelectedMentionAuthorization>> |
| 42 | +readSelectedMentionAuthorization( |
| 43 | + RelaySessionNotifier session, |
| 44 | + Set<String> requestedKeys, { |
| 45 | + required String viewer, |
| 46 | + required String channelId, |
| 47 | + Set<String> priorAgentKeys = const {}, |
| 48 | + required bool Function() isCurrent, |
| 49 | +}) async { |
| 50 | + void check() { |
| 51 | + if (!isCurrent()) throw StateError('Mention authorization scope changed'); |
| 52 | + } |
| 53 | + |
| 54 | + check(); |
| 55 | + if (requestedKeys.length > 1000 || |
| 56 | + !requestedKeys.containsAll(priorAgentKeys) || |
| 57 | + requestedKeys.any((key) => !RegExp(r'^[0-9a-f]{64}$').hasMatch(key)) || |
| 58 | + !RegExp(r'^[0-9a-f]{64}$').hasMatch(viewer) || |
| 59 | + channelId.isEmpty) { |
| 60 | + throw StateError('Invalid selected mention request'); |
| 61 | + } |
| 62 | + if (requestedKeys.isEmpty) return const {}; |
| 63 | + final authority = await session.fetchRelaySelf(); |
| 64 | + check(); |
| 65 | + final membership = await _membershipPages( |
| 66 | + session, |
| 67 | + authority, |
| 68 | + viewer, |
| 69 | + channelId, |
| 70 | + check, |
| 71 | + ); |
| 72 | + check(); |
| 73 | + NostrEvent? roster; |
| 74 | + for (final event in membership) { |
| 75 | + if (event.kind != 39002 || |
| 76 | + event.pubkey != authority || |
| 77 | + event.getTagValue('d') != channelId) { |
| 78 | + continue; |
| 79 | + } |
| 80 | + if (roster == null || _newer(event, roster)) roster = event; |
| 81 | + } |
| 82 | + // A malformed newest head is unavailable, never permission to invite someone |
| 83 | + // whose current membership could not be established. Missing head is likewise |
| 84 | + // not a trustworthy empty roster at this destination. |
| 85 | + if (roster == null || |
| 86 | + !verifySignedEvent(roster) || |
| 87 | + roster.tags.where((t) => t.isNotEmpty && t[0] == 'd').length != 1) { |
| 88 | + throw StateError('Destination membership unavailable'); |
| 89 | + } |
| 90 | + final members = <String, String>{}; |
| 91 | + for (final tag in roster.tags.where((t) => t.isNotEmpty && t[0] == 'p')) { |
| 92 | + if (tag.length < 2 || members.containsKey(tag[1])) { |
| 93 | + throw StateError('Ambiguous destination membership'); |
| 94 | + } |
| 95 | + members[tag[1]] = tag.length >= 4 ? tag[3] : 'member'; |
| 96 | + } |
| 97 | + final runtime = await _queryAgentFilters(session, [ |
| 98 | + for (final key in requestedKeys) |
| 99 | + NostrFilter(kinds: const [10100], authors: [key], limit: 1), |
| 100 | + ], checkCurrent: check); |
| 101 | + check(); |
| 102 | + Map<String, NostrEvent> profiles = const {}; |
| 103 | + final policies = await resolveAgentPolicies( |
| 104 | + session, |
| 105 | + runtime.where((e) => requestedKeys.contains(e.pubkey)).toList(), |
| 106 | + requestedKeys: requestedKeys, |
| 107 | + checkCurrent: check, |
| 108 | + onProfileEvidence: (value) => profiles = value, |
| 109 | + ); |
| 110 | + check(); |
| 111 | + final latestRuntime = <String, NostrEvent>{}; |
| 112 | + for (final event in runtime) { |
| 113 | + if (event.kind != 10100 || !requestedKeys.contains(event.pubkey)) continue; |
| 114 | + final previous = latestRuntime[event.pubkey]; |
| 115 | + if (previous == null || _newer(event, previous)) { |
| 116 | + latestRuntime[event.pubkey] = event; |
| 117 | + } |
| 118 | + } |
| 119 | + final byKey = {for (final policy in policies) policy.pubkey: policy}; |
| 120 | + final result = <String, SelectedMentionAuthorization>{}; |
| 121 | + for (final key in requestedKeys) { |
| 122 | + final profile = profiles[key]; |
| 123 | + final owner = profile == null ? null : verifiedOaOwnerPubkey(profile); |
| 124 | + final invalidProfile = |
| 125 | + profile != null && |
| 126 | + (!verifySignedEvent(profile) || |
| 127 | + (owner == null && |
| 128 | + profile.tags.any((t) => t.isNotEmpty && t[0] == 'auth'))); |
| 129 | + final runtimeHead = latestRuntime[key]; |
| 130 | + final knownAgent = |
| 131 | + owner != null || |
| 132 | + members[key] == 'bot' || |
| 133 | + (runtimeHead != null && verifySignedEvent(runtimeHead)); |
| 134 | + final unresolved = |
| 135 | + invalidProfile || |
| 136 | + (runtimeHead != null && !verifySignedEvent(runtimeHead)) || |
| 137 | + (!knownAgent && priorAgentKeys.contains(key)); |
| 138 | + final kind = unresolved |
| 139 | + ? SelectedMentionKind.unresolvedAgent |
| 140 | + : knownAgent |
| 141 | + ? SelectedMentionKind.agent |
| 142 | + : SelectedMentionKind.ordinary; |
| 143 | + AgentDirectoryEntry? agent; |
| 144 | + if (kind == SelectedMentionKind.agent) { |
| 145 | + final policy = byKey[key]; |
| 146 | + // Ownership without a matching valid policy must not revive headless |
| 147 | + // runtime authority. mergeAgentPolicies remains the sole policy parser. |
| 148 | + final missingOwnedPolicy = owner != null && policy?.ownerPubkey != owner; |
| 149 | + agent = AgentDirectoryEntry( |
| 150 | + pubkey: key, |
| 151 | + ownerPubkey: owner, |
| 152 | + displayName: policy?.displayName, |
| 153 | + respondTo: missingOwnedPolicy ? 'nobody' : policy?.respondTo, |
| 154 | + respondToAllowlist: missingOwnedPolicy |
| 155 | + ? const [] |
| 156 | + : policy?.respondToAllowlist ?? const [], |
| 157 | + channelIds: |
| 158 | + members.containsKey(viewer) && |
| 159 | + members.containsKey(key) && |
| 160 | + (owner == viewer || members[key] == 'bot') |
| 161 | + ? [channelId] |
| 162 | + : const [], |
| 163 | + ); |
| 164 | + } |
| 165 | + result[key] = SelectedMentionAuthorization._( |
| 166 | + kind, |
| 167 | + members.containsKey(key), |
| 168 | + agent, |
| 169 | + ); |
| 170 | + } |
| 171 | + check(); |
| 172 | + return Map.unmodifiable(result); |
| 173 | +} |
0 commit comments