-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnip-11.ts
216 lines (191 loc) · 6.68 KB
/
nip-11.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* @file NIP-11: Relay Information Document
* @module nips/nip-11
* @see https://github.com/nostr-protocol/nips/blob/master/11.md
*/
import { getLogger } from '../utils/logger.js';
import { fetchJson } from '../utils/http.js';
const logger = getLogger('NIP-11');
/**
* Relay information document structure
*/
export interface RelayInformation {
name?: string;
description?: string;
pubkey?: string;
contact?: string;
supported_nips?: number[];
software?: string;
version?: string;
limitation?: {
max_message_length?: number;
max_subscriptions?: number;
max_filters?: number;
max_limit?: number;
max_subid_length?: number;
min_prefix?: number;
max_event_tags?: number;
max_content_length?: number;
min_pow_difficulty?: number;
auth_required?: boolean;
payment_required?: boolean;
};
}
/**
* Fetches relay information document
* @param url - Relay URL (ws:// or wss://)
* @returns {Promise<RelayInformation>} Relay information
*/
export async function getRelayInformation(url: string): Promise<RelayInformation> {
try {
const relayUrl = url.replace('ws://', 'http://').replace('wss://', 'https://');
const response = await fetchJson<RelayInformation>(`${relayUrl}/.well-known/nostr.json`);
return response;
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
logger.error(`Failed to fetch relay information: ${errorMessage}`);
throw new Error(`Failed to fetch relay information: ${errorMessage}`);
}
}
/**
* Checks if relay meets requirements
* @param relay - Relay information
* @param requirements - Required relay features
* @returns {boolean} True if relay meets all requirements
*/
export function checkRelayRequirements(
relay: RelayInformation,
requirements: Partial<RelayInformation>
): boolean {
try {
// Check supported NIPs
if (requirements.supported_nips && relay.supported_nips) {
const missingNips = requirements.supported_nips.filter(
nip => !relay.supported_nips?.includes(nip)
);
if (missingNips.length > 0) {
logger.debug(`Missing required NIPs: ${missingNips.join(', ')}`);
return false;
}
}
// Check limitations
if (requirements.limitation && relay.limitation) {
for (const [key, value] of Object.entries(requirements.limitation)) {
const relayValue = relay.limitation[key as keyof typeof relay.limitation];
// Skip if relay doesn't specify this limitation
if (relayValue === undefined) continue;
// For maximum values, relay should support at least the required value
if (key.startsWith('max_') && typeof relayValue === 'number' && typeof value === 'number') {
if (relayValue < value) {
logger.debug(`Relay ${key} too low: ${relayValue} < ${value}`);
return false;
}
}
// For minimum values, relay should not require more than specified
if (key.startsWith('min_') && typeof relayValue === 'number' && typeof value === 'number') {
if (relayValue > value) {
logger.debug(`Relay ${key} too high: ${relayValue} > ${value}`);
return false;
}
}
// For boolean flags, values must match if specified
if (typeof relayValue === 'boolean' && typeof value === 'boolean') {
if (relayValue !== value) {
logger.debug(`Relay ${key} mismatch: ${relayValue} !== ${value}`);
return false;
}
}
}
}
return true;
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
logger.error(`Error checking relay requirements: ${errorMessage}`);
return false;
}
}
/**
* Validates relay capabilities against required features
* @param info - Relay information
* @param requiredNips - Required NIPs
* @param requiredFeatures - Required relay features
* @returns {boolean} True if relay supports all required features
*/
export function validateRelayCapabilities(
info: RelayInformation,
requiredNips: number[] = [],
requiredFeatures: Partial<RelayInformation['limitation']> = {}
): boolean {
// Check NIP support
if (requiredNips.length > 0) {
if (!info.supported_nips) return false;
if (!requiredNips.every(nip => info.supported_nips?.includes(nip))) {
return false;
}
}
// Check limitations
if (info.limitation) {
for (const [key, value] of Object.entries(requiredFeatures)) {
const relayValue = info.limitation[key as keyof RelayInformation['limitation']];
if (relayValue === undefined) return false;
// For maximum values, relay limit should be higher
if (key.startsWith('max_') && typeof relayValue === 'number' && typeof value === 'number') {
if (relayValue < value) return false;
}
// For minimum values, relay limit should be lower
if (key.startsWith('min_') && typeof relayValue === 'number' && typeof value === 'number') {
if (relayValue > value) return false;
}
// For boolean flags, must match exactly
if (typeof relayValue === 'boolean' && typeof value === 'boolean') {
if (relayValue !== value) return false;
}
}
}
return true;
}
/**
* Creates a relay selection score based on capabilities
* @param info - Relay information
* @param preferences - Scoring preferences
* @returns {number} Relay score (higher is better)
*/
export function scoreRelayCapabilities(
info: RelayInformation,
preferences: {
preferredNips?: number[];
minMessageLength?: number;
minSubscriptions?: number;
requireAuth?: boolean;
requirePayment?: boolean;
} = {}
): number {
let score = 0;
// Score NIP support
if (info.supported_nips && preferences.preferredNips) {
score += preferences.preferredNips.filter(nip =>
info.supported_nips?.includes(nip)
).length * 10;
}
// Score limitations
if (info.limitation) {
const limits = info.limitation;
// Message length
if (limits.max_message_length && preferences.minMessageLength) {
score += limits.max_message_length >= preferences.minMessageLength ? 5 : -5;
}
// Subscriptions
if (limits.max_subscriptions && preferences.minSubscriptions) {
score += limits.max_subscriptions >= preferences.minSubscriptions ? 5 : -5;
}
// Auth requirements
if (preferences.requireAuth !== undefined) {
score += (limits.auth_required === preferences.requireAuth) ? 5 : -10;
}
// Payment requirements
if (preferences.requirePayment !== undefined) {
score += (limits.payment_required === preferences.requirePayment) ? 5 : -10;
}
}
return score;
}