records.ts (13063B)
1 import { 2 inspectLocalTemplate, 3 type PublicSignedFields, 4 type LocalUnsignedTemplate 5 } from '../nostr/local-template.ts'; 6 import { exactLocalFields } from '../contracts/local-records.ts'; 7 import { canonicalDeletionCoordinate } from '../nostr/deletion-adapter.ts'; 8 import { 9 createPublicHeadCandidate, 10 publicHeadSnapshot 11 } from '../catalog/heads.ts'; 12 import { 13 LOCAL_PERSISTENCE_BUDGETS, 14 PUBLIC_INGRESS_BUDGETS, 15 PUBLIC_PUBLICATION_BUDGETS, 16 RELAY_BUDGETS 17 } from '../config/budgets.ts'; 18 import { canonicalRelayOrigin } from '../config/relays.ts'; 19 import { canonicalPublicKey } from '../contracts/public-key.ts'; 20 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 21 import { canonicalLocalId } from '../private-handles.ts'; 22 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 23 import { 24 verifyEnvelope, 25 verifiedEnvelopeSnapshot 26 } from '../nostr/verified-envelope.ts'; 27 import type { 28 ConversationMappingRecord, 29 PublicRecord 30 } from '../contracts/local-records.ts'; 31 32 declare const recordBrand: unique symbol; 33 declare const mappingBrand: unique symbol; 34 export type PublicRecordHandle = Readonly<{ [recordBrand]: true }>; 35 export type ConversationMappingHandle = Readonly<{ [mappingBrand]: true }>; 36 type Saved = Readonly<{ owner: string; id: string; wire: string }>; 37 const records = new WeakMap<PublicRecordHandle, Saved>(); 38 const mappings = new WeakMap<ConversationMappingHandle, Saved>(); 39 export type RecordFailure = 40 | 'invalid_scope' 41 | 'oversized' 42 | 'malformed' 43 | 'unsupported_schema' 44 | 'owner_mismatch' 45 | 'id_mismatch'; 46 type Result<T> = 47 | Readonly<{ ok: true; value: T }> 48 | Readonly<{ ok: false; reason: RecordFailure }>; 49 function object(value: unknown): value is Record<string, unknown> { 50 return typeof value === 'object' && value !== null && !Array.isArray(value); 51 } 52 const exact = exactLocalFields; 53 function hash(value: unknown): value is string { 54 return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value); 55 } 56 function unsigned(value: unknown): value is number { 57 return safeUnsignedInteger(value) !== undefined; 58 } 59 function signed( 60 wire: unknown, 61 owner: string, 62 kinds: readonly number[] 63 ): PublicSignedFields | undefined { 64 if (typeof wire !== 'string') return undefined; 65 const verified = verifyEnvelope(wire); 66 if (!verified.ok) return undefined; 67 const event = verifiedEnvelopeSnapshot(verified.value); 68 return event && 69 exact(event, [ 70 'id', 71 'pubkey', 72 'created_at', 73 'kind', 74 'tags', 75 'content', 76 'sig' 77 ]) && 78 event.pubkey === owner && 79 kinds.includes(event.kind) 80 ? event 81 : undefined; 82 } 83 function draft(form: unknown): boolean { 84 const keys = [ 85 'title', 86 'description', 87 'location', 88 'amount', 89 'currency', 90 'unit', 91 'quantity', 92 'contactType', 93 'contactValue' 94 ]; 95 if ( 96 !exact(form, keys) || 97 typeof form.contactType !== 'string' || 98 !['', 'email', 'phone', 'https'].includes(form.contactType) 99 ) 100 return false; 101 let bytes = 0; 102 for (const key of keys) { 103 const value = form[key]; 104 if ( 105 typeof value !== 'string' || 106 !boundedUtf8(value, LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes) 107 ) 108 return false; 109 bytes += new TextEncoder().encode(value).length; 110 if (bytes > LOCAL_PERSISTENCE_BUDGETS.draftComposedBytes) return false; 111 } 112 // Incomplete strings remain exact; publication validation is a separate step. 113 return true; 114 } 115 function capture( 116 value: unknown, 117 owner: string, 118 preference: boolean 119 ): Record<string, unknown> | undefined { 120 if ( 121 !exact(value, ['kind', 'wire', 'hash', 'targets', 'policyFingerprint']) || 122 !(preference 123 ? value.kind === 10050 124 : value.kind === 30402 || value.kind === 5) || 125 !hash(value.hash) || 126 !hash(value.policyFingerprint) || 127 typeof value.wire !== 'string' || 128 !boundedUtf8(value.wire, PUBLIC_INGRESS_BUDGETS.eventBytes) || 129 !Array.isArray(value.targets) || 130 value.targets.length === 0 || 131 value.targets.length > RELAY_BUDGETS.public || 132 value.targets.some( 133 (target: unknown) => canonicalRelayOrigin(target) !== target 134 ) || 135 new Set(value.targets).size !== value.targets.length 136 ) 137 return undefined; 138 const template = inspectLocalTemplate(value.wire, owner, value.kind); 139 return template?.hash === value.hash ? value : undefined; 140 } 141 function linkedSource( 142 raw: unknown, 143 owner: string, 144 template: LocalUnsignedTemplate 145 ): boolean { 146 if (typeof raw !== 'string') return false; 147 const proof = verifyEnvelope(raw); 148 if (!proof.ok) return false; 149 const source = createPublicHeadCandidate(proof.value); 150 if (!source) return false; 151 const head = publicHeadSnapshot(source); 152 if (head.kind !== 30402 || head.pubkey !== owner) return false; 153 if (template.kind === 30402) { 154 const identifier = template.tags.find((tag) => tag[0] === 'd')?.[1] ?? ''; 155 const event = verifiedEnvelopeSnapshot(proof.value); 156 return ( 157 identifier === head.identifier && 158 template.created_at > head.created_at && 159 template.tags.find((tag) => tag[0] === 'published_at')?.[1] === 160 event?.tags.find((tag) => tag[0] === 'published_at')?.[1] 161 ); 162 } 163 if (template.kind !== 5 || template.created_at < head.created_at) 164 return false; 165 const coordinate = `30402:${owner}:${head.identifier}`; 166 let targets = 0; 167 for (const tag of template.tags) { 168 if (tag[0] === 'e') { 169 if (tag[1]?.toLowerCase() !== head.id) return false; 170 targets++; 171 } else if (tag[0] === 'a') { 172 if ( 173 typeof tag[1] !== 'string' || 174 canonicalDeletionCoordinate(tag[1]) !== coordinate 175 ) 176 return false; 177 targets++; 178 } 179 } 180 return targets > 0; 181 } 182 function operation(row: Record<string, unknown>): boolean { 183 const preference = row.family === 'preference_operation'; 184 const keys = [ 185 'schema', 186 'family', 187 'owner', 188 'id', 189 'revision', 190 'source', 191 'capture', 192 'artifact', 193 'receipts' 194 ]; 195 if (preference) keys.push('consent'); 196 if ( 197 !exact(row, keys) || 198 (preference && row.consent !== 'explicit_review') || 199 typeof row.owner !== 'string' 200 ) 201 return false; 202 const prepared = capture(row.capture, row.owner, preference); 203 if (!prepared || !object(row.source)) return false; 204 const source = row.source; 205 const template = inspectLocalTemplate( 206 prepared.wire, 207 row.owner, 208 prepared.kind 209 ); 210 if (!template) return false; 211 if (preference) { 212 if ( 213 !exact(source, ['type', 'wire']) || 214 source.type !== 'inbox_head' || 215 (source.wire !== null && !signed(source.wire, row.owner, [10050])) 216 ) 217 return false; 218 } else if (source.type === 'draft') { 219 if ( 220 prepared.kind !== 30402 || 221 !exact(source, ['type', 'id', 'revision']) || 222 !canonicalLocalId(source.id) || 223 !unsigned(source.revision) 224 ) 225 return false; 226 } else if ( 227 !exact(source, ['type', 'wire']) || 228 source.type !== 'public_head' || 229 !signed(source.wire, row.owner, [30402]) || 230 !linkedSource(source.wire, row.owner, template) 231 ) 232 return false; 233 let artifact: PublicSignedFields | undefined; 234 if (row.artifact !== null) { 235 if ( 236 !exact(row.artifact, ['eventId', 'wire']) || 237 row.artifact.eventId !== prepared.hash 238 ) 239 return false; 240 artifact = signed(row.artifact.wire, row.owner, [Number(prepared.kind)]); 241 if (!artifact || artifact.id !== prepared.hash) return false; 242 } 243 if (!Array.isArray(row.receipts) || (!artifact && row.receipts.length !== 0)) 244 return false; 245 for (const receipt of row.receipts as unknown[]) { 246 if ( 247 !( 248 exact(receipt, [ 249 'actionId', 250 'origin', 251 'role', 252 'attempt', 253 'eventId', 254 'status', 255 'observedAtMilliseconds', 256 'readbackWire' 257 ]) || 258 (preference && 259 exact(receipt, [ 260 'actionId', 261 'origin', 262 'role', 263 'attempt', 264 'eventId', 265 'status', 266 'observedAtMilliseconds', 267 'readbackWire', 268 'readbackOrigin' 269 ])) 270 ) || 271 ('readbackOrigin' in receipt && 272 (receipt.readbackWire === null || 273 typeof receipt.readbackOrigin !== 'string' || 274 canonicalRelayOrigin(receipt.readbackOrigin) !== 275 receipt.readbackOrigin)) || 276 !canonicalLocalId(receipt.actionId) || 277 receipt.role !== (preference ? 'preference' : 'publication') || 278 !(prepared.targets as unknown[]).includes(receipt.origin) || 279 receipt.eventId !== prepared.hash || 280 !unsigned(receipt.attempt) || 281 receipt.attempt < 1 || 282 receipt.attempt > PUBLIC_PUBLICATION_BUDGETS.attemptsPerTargetAction || 283 !unsigned(receipt.observedAtMilliseconds) || 284 typeof receipt.status !== 'string' || 285 !['accepted', 'refused', 'timed_out', 'unknown', 'stopped'].includes( 286 receipt.status 287 ) 288 ) 289 return false; 290 if (receipt.readbackWire !== null) { 291 const observed = signed(receipt.readbackWire, row.owner, [ 292 Number(prepared.kind) 293 ]); 294 if ( 295 !artifact || 296 !observed || 297 observed.id !== artifact.id || 298 observed.sig !== artifact.sig 299 ) 300 return false; 301 } 302 } 303 return true; 304 } 305 function read( 306 raw: unknown, 307 expectedOwner: unknown, 308 expectedId: unknown 309 ): Result<Saved> { 310 const owner = canonicalPublicKey(expectedOwner), 311 id = canonicalLocalId(expectedId); 312 if (!owner || !id) return { ok: false, reason: 'invalid_scope' }; 313 if (typeof raw !== 'string') return { ok: false, reason: 'malformed' }; 314 if (!boundedUtf8(raw, LOCAL_PERSISTENCE_BUDGETS.publicOperationBytes)) 315 return { ok: false, reason: 'oversized' }; 316 try { 317 const row: unknown = JSON.parse(raw); 318 if (!object(row) || JSON.stringify(row) !== raw) 319 return { ok: false, reason: 'malformed' }; 320 if (row.schema !== 1) return { ok: false, reason: 'unsupported_schema' }; 321 if (row.owner !== owner) return { ok: false, reason: 'owner_mismatch' }; 322 if (row.id !== id) return { ok: false, reason: 'id_mismatch' }; 323 return { ok: true, value: { owner, id, wire: raw } }; 324 } catch { 325 return { ok: false, reason: 'malformed' }; 326 } 327 } 328 export function decodePublicRecord( 329 raw: unknown, 330 expectedOwner: unknown, 331 expectedId: unknown 332 ): Result<PublicRecordHandle> { 333 const parsed = read(raw, expectedOwner, expectedId); 334 if (!parsed.ok) return parsed; 335 try { 336 const row: Record<string, unknown> = JSON.parse( 337 parsed.value.wire 338 ) as Record<string, unknown>; 339 if (!unsigned(row.revision)) return { ok: false, reason: 'malformed' }; 340 const valid = 341 row.family === 'public_draft' 342 ? exact(row, [ 343 'schema', 344 'family', 345 'owner', 346 'id', 347 'revision', 348 'savedAtMilliseconds', 349 'form' 350 ]) && 351 unsigned(row.savedAtMilliseconds) && 352 draft(row.form) 353 : (row.family === 'public_operation' || 354 row.family === 'preference_operation') && 355 operation(row); 356 if (!valid) return { ok: false, reason: 'malformed' }; 357 const token = Object.freeze({}) as PublicRecordHandle; 358 records.set(token, parsed.value); 359 return { ok: true, value: token }; 360 } catch { 361 return { ok: false, reason: 'malformed' }; 362 } 363 } 364 export function publicRecordSnapshot( 365 handle: PublicRecordHandle, 366 owner: unknown, 367 id: unknown 368 ): PublicRecord | undefined { 369 const saved = records.get(handle); 370 return saved && 371 saved.owner === canonicalPublicKey(owner) && 372 saved.id === canonicalLocalId(id) 373 ? (JSON.parse(saved.wire) as PublicRecord) 374 : undefined; 375 } 376 export function publicRecordWire( 377 handle: PublicRecordHandle, 378 owner: unknown, 379 id: unknown 380 ): string | undefined { 381 const saved = records.get(handle); 382 return saved && 383 saved.owner === canonicalPublicKey(owner) && 384 saved.id === canonicalLocalId(id) 385 ? saved.wire 386 : undefined; 387 } 388 export function decodeConversationMapping( 389 raw: unknown, 390 expectedOwner: unknown, 391 expectedId: unknown 392 ): Result<ConversationMappingHandle> { 393 const parsed = read(raw, expectedOwner, expectedId); 394 if (!parsed.ok) return parsed; 395 const row: unknown = JSON.parse(parsed.value.wire); 396 if ( 397 !exact(row, ['schema', 'family', 'owner', 'id', 'peer']) || 398 row.family !== 'conversation_handle' || 399 !canonicalPublicKey(row.peer) || 400 row.peer === row.owner 401 ) 402 return { ok: false, reason: 'malformed' }; 403 const token = Object.freeze({}) as ConversationMappingHandle; 404 mappings.set(token, parsed.value); 405 return { ok: true, value: token }; 406 } 407 export function conversationMappingSnapshot( 408 handle: ConversationMappingHandle, 409 owner: unknown, 410 id: unknown 411 ): ConversationMappingRecord | undefined { 412 const saved = mappings.get(handle); 413 return saved && 414 saved.owner === canonicalPublicKey(owner) && 415 saved.id === canonicalLocalId(id) 416 ? (JSON.parse(saved.wire) as ConversationMappingRecord) 417 : undefined; 418 }