relays.ts (10149B)
1 import { canonicalPublicKey } from '../contracts/public-key.ts'; 2 import { RELAY_BUDGETS } from './budgets.ts'; 3 4 export interface PublicRelay { 5 readonly origin: string; 6 readonly read: boolean; 7 readonly write: boolean; 8 readonly nip50: boolean; 9 } 10 export interface InboxRelay { 11 readonly origin: string; 12 readonly read: boolean; 13 readonly write: boolean; 14 } 15 export interface RelayManifest { 16 readonly schemaVersion: 1; 17 readonly public: readonly PublicRelay[]; 18 readonly inbox: readonly InboxRelay[]; 19 readonly postingEnabled: boolean; 20 readonly messagingEnabled: boolean; 21 readonly operatorDenylist: readonly string[]; 22 } 23 24 declare const admittedPolicy: unique symbol; 25 export type RelayPolicy = Readonly<{ readonly [admittedPolicy]: true }>; 26 // Only this owner retains the admitted JSON. Detached views cannot change egress. 27 const snapshots = new WeakMap<RelayPolicy, string>(); 28 function fields( 29 value: unknown, 30 names: readonly string[] 31 ): value is Record<string, unknown> { 32 if (!value || typeof value !== 'object' || Array.isArray(value)) return false; 33 let count = 0; 34 for (const key in value) { 35 if (!names.includes(key)) return false; 36 count++; 37 } 38 return count === names.length; 39 } 40 41 // URL admission supplies canonical bracketed hex, never a zone or dotted 42 // IPv4 tail. Independently bound/validate all eight words before BigInt work. 43 function ipv6Bits(value: string): bigint | undefined { 44 if (value.length > 39 || !/^[0-9a-f:]{2,39}$/.test(value)) return undefined; 45 const halves = value.split('::'); 46 if (halves.length > 2) return undefined; 47 const left = halves[0] ? halves[0].split(':') : []; 48 const right = halves.length === 2 && halves[1] ? halves[1].split(':') : []; 49 const present = left.length + right.length; 50 if ( 51 (halves.length === 1 ? present !== 8 : present >= 8) || 52 ![...left, ...right].every((word) => /^[0-9a-f]{1,4}$/.test(word)) 53 ) 54 return undefined; 55 const words = [...left, ...Array<string>(8 - present).fill('0'), ...right]; 56 return words.reduce((bits, word) => (bits << 16n) | BigInt('0x' + word), 0n); 57 } 58 function ipv6Prefix(bits: bigint, network: bigint, length: number): boolean { 59 const shift = BigInt(128 - length); 60 return bits >> shift === network >> shift; 61 } 62 function publicIpv6(host: string): boolean { 63 if (!host.endsWith(']')) return false; 64 const bits = ipv6Bits(host.slice(1, -1)); 65 if ( 66 bits === undefined || 67 !ipv6Prefix(bits, 0x20000000000000000000000000000000n, 3) 68 ) 69 return false; 70 // Frozen IANA IPv6 Special-Purpose registry revision 2025-10-09: 71 // https://www.iana.org/assignments/iana-ipv6-special-registry/. 72 // RFC4291 prefix bits, RFC9637 documentation /20. Conservative relay policy 73 // excludes special protocol/service allocations including globally reachable 74 // exceptions within 2001::/23 and AS112; this is not a routability assertion. 75 // Other registry rows (mapped, translation, local, multicast, SRv6, discard) 76 // are already outside 2000::/3. IPv4/DNS admission is independent below. 77 const special: readonly (readonly [bigint, number])[] = [ 78 [0x20010000000000000000000000000000n, 23], 79 [0x20010db8000000000000000000000000n, 32], 80 [0x20020000000000000000000000000000n, 16], 81 [0x2620004f800000000000000000000000n, 48], 82 [0x3fff0000000000000000000000000000n, 20] 83 ]; 84 // Literal configuration only; browser resolution/connection and actual 85 // operator access still require their separate qualification. 86 return !special.some(([network, length]) => 87 ipv6Prefix(bits, network, length) 88 ); 89 } 90 function publicAddress(host: string): boolean { 91 if (host.startsWith('[')) return publicIpv6(host); 92 if (/^[0-9.]+$/.test(host)) { 93 const [a, b, c] = host.split('.').map(Number); 94 return ( 95 a !== 0 && 96 a !== 10 && 97 a !== 127 && 98 a < 224 && 99 !(a === 100 && b >= 64 && b <= 127) && 100 !(a === 169 && b === 254) && 101 !(a === 172 && b >= 16 && b <= 31) && 102 !(a === 192 && [0, 168].includes(b)) && 103 !(a === 198 && ([18, 19].includes(b) || (b === 51 && c === 100))) && 104 !(a === 203 && b === 0 && c === 113) 105 ); 106 } 107 const labels = host.split('.'); 108 return ( 109 labels.length >= 2 && 110 host.length <= 253 && 111 labels.every((label) => 112 /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label) 113 ) && 114 !/(?:^|\.)(?:localhost|local|internal|invalid|test|example|onion)$/.test( 115 host 116 ) && 117 host !== 'home.arpa' && 118 !host.endsWith('.home.arpa') 119 ); 120 } 121 122 export function canonicalRelayOrigin(value: unknown): string | undefined { 123 if ( 124 typeof value !== 'string' || 125 value.length > 8192 || 126 !value.isWellFormed() || 127 !/^wss:\/\//.test(value) || 128 /[\s\\%\p{Cc}\p{Cf}]/u.test(value) 129 ) 130 return undefined; 131 try { 132 const url = new URL(value); 133 // A canonical origin has no userinfo, resource path, query or fragment, 134 // case/port normalization, percent encoding or trailing slash aliases. 135 if ( 136 url.origin !== value || 137 url.username || 138 url.password || 139 url.port === '0' || 140 !publicAddress(url.hostname) 141 ) 142 return undefined; 143 return url.origin; 144 } catch { 145 return undefined; 146 } 147 } 148 149 function publicRelays(value: unknown): readonly PublicRelay[] | undefined { 150 if (!Array.isArray(value) || value.length > RELAY_BUDGETS.public) 151 return undefined; 152 const rows = (value as unknown[]).map((entry) => { 153 if (!fields(entry, ['origin', 'read', 'write', 'nip50'])) return undefined; 154 const { origin: rawOrigin, read, write, nip50 } = entry; 155 const origin = canonicalRelayOrigin(rawOrigin); 156 if ( 157 !origin || 158 typeof read !== 'boolean' || 159 typeof write !== 'boolean' || 160 typeof nip50 !== 'boolean' || 161 (!read && !write) || 162 (nip50 && !read) 163 ) 164 return undefined; 165 return { origin, read, write, nip50 }; 166 }); 167 if ( 168 rows.some((row) => !row) || 169 rows.some((row, index) => 170 rows.some((other, j) => index !== j && row?.origin === other?.origin) 171 ) 172 ) 173 return undefined; 174 return rows as readonly PublicRelay[]; 175 } 176 function inboxRelays(value: unknown): readonly InboxRelay[] | undefined { 177 if (!Array.isArray(value) || value.length > RELAY_BUDGETS.inbox) 178 return undefined; 179 const rows = (value as unknown[]).map((entry) => { 180 if (!fields(entry, ['origin', 'read', 'write'])) return undefined; 181 const { origin: rawOrigin, read, write } = entry; 182 const origin = canonicalRelayOrigin(rawOrigin); 183 if ( 184 !origin || 185 typeof read !== 'boolean' || 186 typeof write !== 'boolean' || 187 (!read && !write) 188 ) 189 return undefined; 190 return { origin, read, write }; 191 }); 192 if ( 193 rows.some((row) => !row) || 194 rows.some((row, index) => 195 rows.some((other, j) => index !== j && row?.origin === other?.origin) 196 ) 197 ) 198 return undefined; 199 return rows as readonly InboxRelay[]; 200 } 201 202 // Accept bounded JSON, as with verified event ingress. Executable objects, 203 // getters, symbols, caller prototypes and post-admission mutations stay outside. 204 // 64 KiB bounds this public configuration parser; it is not a transport budget. 205 export function validateRelayPolicy(raw: unknown): RelayPolicy | undefined { 206 if ( 207 typeof raw !== 'string' || 208 raw.length > 65536 || 209 !raw.isWellFormed() || 210 new TextEncoder().encode(raw).length > 65536 211 ) 212 return undefined; 213 try { 214 const row: unknown = JSON.parse(raw); 215 if ( 216 !fields(row, [ 217 'schemaVersion', 218 'public', 219 'inbox', 220 'postingEnabled', 221 'messagingEnabled', 222 'operatorDenylist' 223 ]) || 224 row.schemaVersion !== 1 || 225 typeof row.postingEnabled !== 'boolean' || 226 typeof row.messagingEnabled !== 'boolean' || 227 !Array.isArray(row.operatorDenylist) 228 ) 229 return undefined; 230 const publicEntries = publicRelays(row.public); 231 const inboxEntries = inboxRelays(row.inbox); 232 if (!publicEntries || !inboxEntries) return undefined; 233 const denylist = (row.operatorDenylist as unknown[]).map( 234 canonicalPublicKey 235 ); 236 if ( 237 denylist.some((key) => !key) || 238 denylist.some((key, index) => denylist.indexOf(key) !== index) 239 ) 240 return undefined; 241 const token = Object.freeze({}) as RelayPolicy; 242 snapshots.set( 243 token, 244 JSON.stringify({ 245 schemaVersion: 1, 246 public: publicEntries, 247 inbox: inboxEntries, 248 postingEnabled: row.postingEnabled, 249 messagingEnabled: row.messagingEnabled, 250 operatorDenylist: denylist 251 }) 252 ); 253 return token; 254 } catch { 255 return undefined; 256 } 257 } 258 259 export function readRelayPolicy(policy: RelayPolicy): RelayManifest { 260 const raw = snapshots.get(policy); 261 if (!raw) throw new Error('relay_policy_invalid'); 262 return JSON.parse(raw) as RelayManifest; 263 } 264 // Fixed public sources never accept hints. Private targets additionally need 265 // verified recipient preferences; intersection does not authenticate kind10050. 266 // Callers get detached target arrays and cannot mutate the retained policy. 267 export function publicRelayTargets( 268 policy: RelayPolicy, 269 operation: 'read' | 'write' 270 ): readonly string[] { 271 return readRelayPolicy(policy) 272 .public.filter((entry) => entry[operation]) 273 .map((entry) => entry.origin); 274 } 275 export function inboxRelayTargets( 276 policy: RelayPolicy, 277 recipientPreferences: readonly string[], 278 operation: 'read' | 'write' 279 ): readonly string[] { 280 return readRelayPolicy(policy) 281 .inbox.filter( 282 (entry) => entry[operation] && recipientPreferences.includes(entry.origin) 283 ) 284 .map((entry) => entry.origin); 285 } 286 // Source launch-input preparation only. Operator/retention/independent-client 287 // qualification and real permissions remain separate mandatory gates. 288 export function requireLaunchRelayPolicy(policy: RelayPolicy): RelayPolicy { 289 const manifest = readRelayPolicy(policy); 290 if ( 291 !manifest.public.some((relay) => relay.read) || 292 !manifest.public.some(({ write }) => write) || 293 !manifest.inbox.some((relay) => relay.read) || 294 !manifest.inbox.some(({ write }) => write) 295 ) 296 throw new Error('relay_launch_inputs_missing'); 297 return policy; 298 }