private-records.ts (27272B)
1 import { canonicalPublicKey } from '../contracts/public-key.ts'; 2 import { exactLocalFields } from '../contracts/local-records.ts'; 3 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 4 import { canonicalLocalId } from '../private-handles.ts'; 5 import { safeUnsignedInteger } from '../nostr/envelope-bounds.ts'; 6 import { 7 verifyEnvelope, 8 verifiedEnvelopeSnapshot 9 } from '../nostr/verified-envelope.ts'; 10 import { 11 canonicalRelayOrigin, 12 readRelayPolicy, 13 validateRelayPolicy 14 } from '../config/relays.ts'; 15 import { 16 inboxOperatorQualificationSnapshot, 17 validateInboxOperatorQualification 18 } from '../config/inbox-operators.ts'; 19 import { 20 incomingGiftWrapTags, 21 parseIncomingLayer 22 } from '../nostr/incoming-wire.ts'; 23 import type { InboxRouteSnapshot } from '../messaging/inbox-routing.ts'; 24 import { 25 LOCAL_PERSISTENCE_BUDGETS, 26 PRIVATE_TRANSPORT_BUDGETS, 27 PRIVATE_PUBLICATION_BUDGETS, 28 RELAY_BUDGETS 29 } from '../config/budgets.ts'; 30 export type PrivateSendReservation = Readonly<{ 31 schema: 1; 32 family: 'private_send_reservation'; 33 owner: string; 34 id: string; 35 revision: 0; 36 peer: string; 37 rumorHash: string; 38 createdAt: number; 39 }>; 40 export type PrivateCiphertextArtifact = Readonly<{ 41 eventId: string; 42 wire: string; 43 }>; 44 export type PrivateSendOperation = Readonly<{ 45 schema: 1; 46 family: 'private_send_operation'; 47 owner: string; 48 id: string; 49 revision: number; 50 peer: string; 51 rumorHash: string; 52 createdAt: number; 53 self: PrivateCiphertextArtifact; 54 peerArtifact: PrivateCiphertextArtifact | null; 55 // Absent in original self-only records; never an implicit migration or an 56 // effect capability. Both ciphertext roles are required for a paired plan. 57 deliveryPlan?: PrivateDeliveryPlan; 58 // Optional compatibility metadata; local observations are never a sender 59 // factory proof, effect permission, person delivery or remote read receipt. 60 receipts?: readonly PrivateTargetReceipt[]; 61 }>; 62 export type PrivateTargetReceipt = Readonly<{ 63 actionId: string; 64 origin: string; 65 role: 'peer' | 'self_archive'; 66 attempt: number; 67 eventId: string; 68 status: 69 'accepted' | 'refused' | 'timed_out' | 'unknown' | 'stopped' | 'readback'; 70 observedAtMilliseconds: number; 71 readbackWire: string | null; 72 }>; 73 export type PrivateDeliveryPlan = Readonly<{ 74 state: 'prepared'; 75 routes: InboxRouteSnapshot; 76 // Earlier reviewed destinations retain the scope of immutable old facts. 77 // These local snapshots never qualify an inbox or authorize replay. 78 previousRoutes?: readonly InboxRouteSnapshot[]; 79 }>; 80 export type ReceivedEnvelopeRecord = Readonly<{ 81 schema: 1; 82 family: 'received_envelope'; 83 owner: string; 84 id: string; 85 revision: number; 86 outer: string; 87 observedAtMilliseconds: number; 88 sources: readonly string[]; 89 read: Readonly<{ rumorHash: string; atMilliseconds: number }> | null; 90 }>; 91 export type PrivateAccessProbeBinding = Readonly<{ 92 preferenceId: string; 93 preferenceCreatedAt: number; 94 readTargets: readonly string[]; 95 archiveTargets: readonly string[]; 96 policyWire: string; 97 operatorWire: string; 98 }>; 99 export type PrivateAccessProbeReceipt = Readonly<{ 100 actionId: string; 101 origin: string; 102 role: 'access_archive' | 'access_readback'; 103 attempt: number; 104 eventId: string; 105 status: 106 | 'accepted' 107 | 'refused' 108 | 'timed_out' 109 | 'unknown' 110 | 'stopped' 111 | 'readback' 112 | 'nonce_verified'; 113 observedAtMilliseconds: number; 114 readbackWire: string | null; 115 }>; 116 // Ciphertext/status bookkeeping only. Neither this record nor a receipt label 117 // is a genuine probe issuer, nested proof, effect or suppression capability. 118 export type PrivateAccessProbe = Readonly<{ 119 schema: 1; 120 family: 'private_access_probe'; 121 owner: string; 122 id: string; 123 revision: number; 124 rumorHash: string; 125 createdAt: number; 126 binding: PrivateAccessProbeBinding; 127 self: PrivateCiphertextArtifact | null; 128 receipts: readonly PrivateAccessProbeReceipt[]; 129 }>; 130 export type PrivateRecord = 131 | PrivateSendReservation 132 | PrivateSendOperation 133 | ReceivedEnvelopeRecord 134 | PrivateAccessProbe; 135 declare const recordBrand: unique symbol; 136 export type PrivateRecordHandle = Readonly<{ [recordBrand]: true }>; 137 const records = new WeakMap< 138 PrivateRecordHandle, 139 Readonly<{ 140 owner: string; 141 id: string; 142 wire: string; 143 outerMetadata?: Readonly<{ id: string; createdAt: number }>; 144 }> 145 >(); 146 export type PrivateRecordFailure = 147 | 'invalid_scope' 148 | 'oversized' 149 | 'malformed' 150 | 'unsupported_schema' 151 | 'owner_mismatch' 152 | 'id_mismatch'; 153 type Result = 154 | Readonly<{ ok: true; value: PrivateRecordHandle }> 155 | Readonly<{ ok: false; reason: PrivateRecordFailure }>; 156 const failed = (reason: PrivateRecordFailure): Result => ({ 157 ok: false, 158 reason 159 }); 160 const hash = (value: unknown): value is string => 161 typeof value === 'string' && /^[0-9a-f]{64}$/.test(value); 162 const unsigned = (value: unknown): value is number => 163 safeUnsignedInteger(value) !== undefined; 164 const reservationFields = [ 165 'schema', 166 'family', 167 'owner', 168 'id', 169 'revision', 170 'peer', 171 'rumorHash', 172 'createdAt' 173 ]; 174 function routeHead(value: unknown): boolean { 175 return ( 176 exactLocalFields(value, ['id', 'createdAt']) && 177 hash(value.id) && 178 unsigned(value.createdAt) 179 ); 180 } 181 function persistedRoute( 182 value: unknown, 183 author: string, 184 role: 'peer' | 'self_archive' 185 ): boolean { 186 if ( 187 !exactLocalFields(value, [ 188 'role', 189 'author', 190 'targets', 191 'knownBase', 192 'sources' 193 ]) || 194 value.role !== role || 195 value.author !== author || 196 !Array.isArray(value.targets) || 197 value.targets.length < 1 || 198 value.targets.length > RELAY_BUDGETS.inbox || 199 new Set(value.targets).size !== value.targets.length || 200 !value.targets.every( 201 (origin) => 202 typeof origin === 'string' && canonicalRelayOrigin(origin) === origin 203 ) || 204 !exactLocalFields(value.knownBase, ['author', 'id', 'createdAt']) || 205 value.knownBase.author !== author || 206 !hash(value.knownBase.id) || 207 !unsigned(value.knownBase.createdAt) || 208 !Array.isArray(value.sources) || 209 value.sources.length < 1 || 210 value.sources.length > RELAY_BUDGETS.public 211 ) 212 return false; 213 const origins = new Set<string>(); 214 function acceptOrigin(origin: string): boolean { 215 if (origins.has(origin)) return false; 216 origins.add(origin); 217 return true; 218 } 219 for (const source of value.sources) { 220 if (typeof source !== 'object' || source === null || Array.isArray(source)) 221 return false; 222 const row = source as Record<string, unknown>; 223 if ( 224 !exactLocalFields( 225 row, 226 row.head === undefined 227 ? ['source', 'state'] 228 : ['source', 'state', 'head'] 229 ) || 230 row.state !== 'eose' || 231 typeof row.source !== 'string' || 232 canonicalRelayOrigin(row.source) !== row.source || 233 !acceptOrigin(row.source) || 234 (row.head !== undefined && !routeHead(row.head)) 235 ) 236 return false; 237 } 238 return true; 239 } 240 function deliveryPlan( 241 value: unknown, 242 owner: string, 243 peer: string 244 ): value is PrivateDeliveryPlan { 245 return ( 246 exactLocalFields(value, [ 247 'state', 248 'routes', 249 ...(typeof value === 'object' && 250 value !== null && 251 'previousRoutes' in value 252 ? ['previousRoutes'] 253 : []) 254 ]) && 255 value.state === 'prepared' && 256 exactLocalFields(value.routes, ['peer', 'archive']) && 257 persistedRoute(value.routes.peer, peer, 'peer') && 258 persistedRoute(value.routes.archive, owner, 'self_archive') && 259 (value.previousRoutes === undefined || 260 (Array.isArray(value.previousRoutes) && 261 value.previousRoutes.length > 0 && 262 value.previousRoutes.every( 263 (previous) => 264 exactLocalFields(previous, ['peer', 'archive']) && 265 persistedRoute(previous.peer, peer, 'peer') && 266 persistedRoute(previous.archive, owner, 'self_archive') 267 ))) 268 ); 269 } 270 // JSON.parse keeps only the last duplicate key. Retaining the original outer 271 // bytes therefore requires a separate syntax-only duplicate check, including 272 // escaped key aliases and nested local metadata. JSON validity/semantics remain 273 // with the ordinary parser/verifier; this scanner never canonicalizes a wire. 274 function uniqueJSONFields(raw: string): boolean { 275 type Frame = { 276 array: boolean; 277 key: boolean; 278 parent: Frame | undefined; 279 accept: (name: string) => boolean; 280 }; 281 function frame(parent: Frame | undefined, array: boolean): Frame { 282 const names = new Set<string>(); 283 return { 284 parent, 285 array, 286 key: !array, 287 accept: (name: string) => { 288 if (names.has(name)) return false; 289 names.add(name); 290 return true; 291 } 292 }; 293 } 294 let current: Frame | undefined; 295 try { 296 for (let index = 0; index < raw.length; index++) { 297 const character = raw[index]; 298 if (character === '"') { 299 let end = index + 1; 300 while (end < raw.length) { 301 if (raw[end] === '\\') { 302 end += 2; 303 continue; 304 } 305 if (raw[end] === '"') break; 306 end++; 307 } 308 if (end >= raw.length) return false; 309 if (current && !current.array && current.key) { 310 const name: unknown = JSON.parse(raw.slice(index, end + 1)); 311 if (typeof name !== 'string' || !current.accept(name)) return false; 312 current = { 313 parent: current.parent, 314 array: current.array, 315 accept: current.accept, 316 key: false 317 }; 318 } 319 index = end; 320 } else if (character === '{' || character === '[') { 321 current = frame(current, character === '['); 322 } else if (character === '}' || character === ']') { 323 if (!current) return false; 324 current = current.parent; 325 } else if (character === ',' && current && !current.array) 326 current = { 327 parent: current.parent, 328 array: current.array, 329 accept: current.accept, 330 key: true 331 }; 332 } 333 return current === undefined; 334 } catch { 335 return false; 336 } 337 } 338 function sendMetadata( 339 value: Record<string, unknown>, 340 owner: string, 341 id: string 342 ): boolean { 343 const peer = canonicalPublicKey(value.peer); 344 return ( 345 value.schema === 1 && 346 value.owner === owner && 347 value.id === id && 348 !!peer && 349 peer !== owner && 350 hash(value.rumorHash) && 351 unsigned(value.createdAt) 352 ); 353 } 354 // Preserved metadata-only reservation admission; never plaintext or crypto proof. 355 export function inspectPrivateSendReservation( 356 raw: unknown, 357 expectedOwner: unknown, 358 expectedId: unknown 359 ): PrivateSendReservation | undefined { 360 const owner = canonicalPublicKey(expectedOwner), 361 id = canonicalLocalId(expectedId); 362 if (!owner || !id || typeof raw !== 'string' || !boundedUtf8(raw, 4096)) 363 return undefined; 364 try { 365 const value: unknown = JSON.parse(raw); 366 if ( 367 !exactLocalFields(value, reservationFields) || 368 !uniqueJSONFields(raw) || 369 value.family !== 'private_send_reservation' || 370 value.revision !== 0 || 371 !sendMetadata(value, owner, id) 372 ) 373 return undefined; 374 return { 375 schema: 1, 376 family: 'private_send_reservation', 377 owner, 378 id, 379 revision: 0, 380 peer: value.peer as string, 381 rumorHash: value.rumorHash as string, 382 createdAt: value.createdAt as number 383 }; 384 } catch { 385 return undefined; 386 } 387 } 388 function outer( 389 raw: unknown, 390 destination: string, 391 received = false 392 ): Readonly<{ id: string; createdAt: number }> | undefined { 393 if ( 394 typeof raw !== 'string' || 395 !boundedUtf8(raw, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes) 396 ) 397 return undefined; 398 const proof = verifyEnvelope(raw); 399 if (!proof.ok) return undefined; 400 if (!uniqueJSONFields(raw)) return undefined; 401 const event = verifiedEnvelopeSnapshot(proof.value); 402 if ( 403 !event || 404 !exactLocalFields(event, [ 405 'id', 406 'pubkey', 407 'created_at', 408 'kind', 409 'tags', 410 'content', 411 'sig' 412 ]) || 413 event.kind !== 1059 || 414 !(received 415 ? incomingGiftWrapTags(event.tags, destination) 416 : JSON.stringify(event.tags) === JSON.stringify([['p', destination]])) 417 ) 418 return undefined; 419 // Structural standard-v2 preflight only. No SDK decrypt or nested admission; 420 // valid encoding/signature cannot prove this ciphertext's inner contents. 421 if ( 422 event.content.length < 132 || 423 !/^[A-Za-z0-9+/]+={0,2}$/.test(event.content) 424 ) 425 return undefined; 426 try { 427 const bytes = atob(event.content); 428 if ( 429 bytes.length < 99 || 430 bytes.charCodeAt(0) !== 2 || 431 btoa(bytes) !== event.content 432 ) 433 return undefined; 434 } catch { 435 return undefined; 436 } 437 return { id: event.id, createdAt: event.created_at }; 438 } 439 function artifact( 440 value: unknown, 441 destination: string 442 ): value is PrivateCiphertextArtifact { 443 return ( 444 exactLocalFields(value, ['eventId', 'wire']) && 445 hash(value.eventId) && 446 outer(value.wire, destination)?.id === value.eventId 447 ); 448 } 449 function receipt( 450 value: unknown, 451 self: PrivateCiphertextArtifact, 452 peer: PrivateCiphertextArtifact, 453 plan: PrivateDeliveryPlan 454 ): boolean { 455 if ( 456 !exactLocalFields(value, [ 457 'actionId', 458 'origin', 459 'role', 460 'attempt', 461 'eventId', 462 'status', 463 'observedAtMilliseconds', 464 'readbackWire' 465 ]) || 466 !canonicalLocalId(value.actionId) || 467 (value.role !== 'peer' && value.role !== 'self_archive') || 468 typeof value.origin !== 'string' || 469 canonicalRelayOrigin(value.origin) !== value.origin || 470 !unsigned(value.attempt) || 471 value.attempt < 1 || 472 value.attempt > PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction || 473 !unsigned(value.observedAtMilliseconds) || 474 typeof value.status !== 'string' || 475 ![ 476 'accepted', 477 'refused', 478 'timed_out', 479 'unknown', 480 'stopped', 481 'readback' 482 ].includes(value.status) 483 ) 484 return false; 485 const route = value.role === 'peer' ? plan.routes.peer : plan.routes.archive, 486 outer = value.role === 'peer' ? peer : self; 487 return ( 488 (route.targets.includes(value.origin) || 489 (plan.previousRoutes ?? []).some((previous) => 490 (value.role === 'peer' 491 ? previous.peer 492 : previous.archive 493 ).targets.includes(value.origin as string) 494 )) && 495 value.eventId === outer.eventId && 496 (value.status === 'readback' 497 ? value.readbackWire === outer.wire 498 : value.readbackWire === null) 499 ); 500 } 501 function probeBinding(value: unknown): value is PrivateAccessProbeBinding { 502 if ( 503 !exactLocalFields(value, [ 504 'preferenceId', 505 'preferenceCreatedAt', 506 'readTargets', 507 'archiveTargets', 508 'policyWire', 509 'operatorWire' 510 ]) || 511 !hash(value.preferenceId) || 512 !unsigned(value.preferenceCreatedAt) || 513 typeof value.policyWire !== 'string' || 514 typeof value.operatorWire !== 'string' 515 ) 516 return false; 517 const policy = validateRelayPolicy(value.policyWire), 518 qualified = validateInboxOperatorQualification(value.operatorWire), 519 declaration = qualified && inboxOperatorQualificationSnapshot(qualified); 520 if ( 521 !policy || 522 !declaration || 523 declaration.authority === 'unconfigured' || 524 declaration.policyWire !== value.policyWire 525 ) 526 return false; 527 const manifest = readRelayPolicy(policy); 528 if (JSON.stringify(manifest) !== value.policyWire) return false; 529 function targets(raw: unknown, role: 'read' | 'write'): boolean { 530 return ( 531 Array.isArray(raw) && 532 raw.length >= 1 && 533 raw.length <= RELAY_BUDGETS.inbox && 534 new Set(raw).size === raw.length && 535 (raw as unknown[]).every( 536 (origin) => 537 typeof origin === 'string' && 538 canonicalRelayOrigin(origin) === origin && 539 manifest.inbox.some( 540 (entry) => entry.origin === origin && entry[role] 541 ) && 542 declaration!.relays.some((entry) => entry.origin === origin) 543 ) 544 ); 545 } 546 return ( 547 targets(value.readTargets, 'read') && targets(value.archiveTargets, 'write') 548 ); 549 } 550 // Pure bounded metadata comparison only. This does not prove a relay effect, 551 // original websocket bytes, nonce decryption, readiness or live ACK lineage. 552 export function inboxProbeReadbackMatches( 553 self: PrivateCiphertextArtifact, 554 owner: string, 555 observedWire: unknown 556 ): boolean { 557 if ( 558 !artifact(self, owner) || 559 parseIncomingLayer( 560 observedWire, 561 PRIVATE_TRANSPORT_BUDGETS.envelopeBytes 562 ) === undefined 563 ) 564 return false; 565 const original = verifyEnvelope(self.wire), 566 observed = verifyEnvelope(observedWire), 567 before = original.ok && verifiedEnvelopeSnapshot(original.value), 568 after = observed.ok && verifiedEnvelopeSnapshot(observed.value); 569 if (!before || !after) return false; 570 const core = (event: typeof before) => 571 JSON.stringify([ 572 event.id, 573 event.pubkey, 574 event.kind, 575 event.created_at, 576 event.tags, 577 event.content, 578 event.sig 579 ]); 580 return core(before) === core(after); 581 } 582 function probeReceipt( 583 value: unknown, 584 self: PrivateCiphertextArtifact, 585 binding: PrivateAccessProbeBinding, 586 owner: string 587 ): value is PrivateAccessProbeReceipt { 588 if ( 589 !exactLocalFields(value, [ 590 'actionId', 591 'origin', 592 'role', 593 'attempt', 594 'eventId', 595 'status', 596 'observedAtMilliseconds', 597 'readbackWire' 598 ]) || 599 !canonicalLocalId(value.actionId) || 600 typeof value.origin !== 'string' || 601 canonicalRelayOrigin(value.origin) !== value.origin || 602 !unsigned(value.attempt) || 603 value.attempt < 1 || 604 value.attempt > PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction || 605 value.eventId !== self.eventId || 606 !unsigned(value.observedAtMilliseconds) 607 ) 608 return false; 609 if (value.role === 'access_archive') 610 return ( 611 binding.archiveTargets.includes(value.origin) && 612 ['accepted', 'refused', 'timed_out', 'unknown', 'stopped'].includes( 613 value.status as string 614 ) && 615 value.readbackWire === null 616 ); 617 return ( 618 value.role === 'access_readback' && 619 binding.readTargets.includes(value.origin) && 620 (value.status === 'readback' || value.status === 'nonce_verified') && 621 inboxProbeReadbackMatches(self, owner, value.readbackWire) 622 ); 623 } 624 // Strict local storage codec only, never installed-account/effect authorization, 625 // genuine sender factory proof, nested authenticity, read receipt or Send. 626 export function decodePrivateRecord( 627 raw: unknown, 628 expectedOwner: unknown, 629 expectedId: unknown 630 ): Result { 631 const owner = canonicalPublicKey(expectedOwner); 632 if (!owner || typeof expectedId !== 'string') return failed('invalid_scope'); 633 const id = 634 canonicalLocalId(expectedId) ?? (hash(expectedId) ? expectedId : undefined); 635 if (!id) return failed('invalid_scope'); 636 if (typeof raw !== 'string') return failed('malformed'); 637 if (!boundedUtf8(raw, LOCAL_PERSISTENCE_BUDGETS.privateSendBytes)) 638 return failed('oversized'); 639 try { 640 const value: unknown = JSON.parse(raw); 641 if (typeof value !== 'object' || value === null || Array.isArray(value)) 642 return failed('malformed'); 643 const fields = value as Record<string, unknown>; 644 if (!uniqueJSONFields(raw)) return failed('malformed'); 645 if (fields.schema !== 1) return failed('unsupported_schema'); 646 if (fields.owner !== owner) return failed('owner_mismatch'); 647 if (fields.id !== id) return failed('id_mismatch'); 648 let record: PrivateRecord; 649 let outerMetadata: Readonly<{ id: string; createdAt: number }> | undefined; 650 if (fields.family === 'private_send_reservation') { 651 const reservation = inspectPrivateSendReservation(raw, owner, id); 652 if (!reservation) return failed('malformed'); 653 record = reservation; 654 } else if (fields.family === 'private_send_operation') { 655 if ( 656 !canonicalLocalId(id) || 657 !exactLocalFields(fields, [ 658 ...reservationFields, 659 'self', 660 'peerArtifact', 661 ...(fields.deliveryPlan === undefined ? [] : ['deliveryPlan']), 662 ...(fields.receipts === undefined ? [] : ['receipts']) 663 ]) || 664 !sendMetadata(fields, owner, id) || 665 !unsigned(fields.revision) || 666 fields.revision < 1 || 667 !artifact(fields.self, owner) || 668 (fields.peerArtifact !== null && 669 !artifact(fields.peerArtifact, fields.peer as string)) || 670 (fields.deliveryPlan !== undefined && 671 (fields.peerArtifact === null || 672 !deliveryPlan( 673 fields.deliveryPlan, 674 owner, 675 fields.peer as string 676 ))) || 677 (fields.receipts !== undefined && 678 (!Array.isArray(fields.receipts) || 679 fields.peerArtifact === null || 680 fields.deliveryPlan === undefined || 681 !deliveryPlan(fields.deliveryPlan, owner, fields.peer as string) || 682 !fields.receipts.every((value) => 683 receipt( 684 value, 685 fields.self as PrivateCiphertextArtifact, 686 fields.peerArtifact as PrivateCiphertextArtifact, 687 fields.deliveryPlan as PrivateDeliveryPlan 688 ) 689 ))) 690 ) 691 return failed('malformed'); 692 record = { 693 schema: 1, 694 family: 'private_send_operation', 695 owner, 696 id, 697 revision: fields.revision, 698 peer: fields.peer as string, 699 rumorHash: fields.rumorHash as string, 700 createdAt: fields.createdAt as number, 701 self: { eventId: fields.self.eventId, wire: fields.self.wire }, 702 peerArtifact: 703 fields.peerArtifact === null 704 ? null 705 : { 706 eventId: fields.peerArtifact.eventId, 707 wire: fields.peerArtifact.wire 708 }, 709 ...(fields.deliveryPlan === undefined 710 ? {} 711 : { deliveryPlan: fields.deliveryPlan }), 712 ...(fields.receipts === undefined 713 ? {} 714 : { receipts: fields.receipts as PrivateTargetReceipt[] }) 715 }; 716 } else if (fields.family === 'private_access_probe') { 717 if ( 718 !canonicalLocalId(id) || 719 !exactLocalFields(fields, [ 720 'schema', 721 'family', 722 'owner', 723 'id', 724 'revision', 725 'rumorHash', 726 'createdAt', 727 'binding', 728 'self', 729 'receipts' 730 ]) || 731 !hash(fields.rumorHash) || 732 !unsigned(fields.createdAt) || 733 !unsigned(fields.revision) || 734 !probeBinding(fields.binding) || 735 !Array.isArray(fields.receipts) || 736 (fields.revision === 0 737 ? fields.self !== null || fields.receipts.length !== 0 738 : !artifact(fields.self, owner) || 739 !fields.receipts.every((fact) => 740 probeReceipt( 741 fact, 742 fields.self as PrivateCiphertextArtifact, 743 fields.binding as PrivateAccessProbeBinding, 744 owner 745 ) 746 )) 747 ) 748 return failed('malformed'); 749 record = { 750 schema: 1, 751 family: 'private_access_probe', 752 owner, 753 id, 754 revision: fields.revision, 755 rumorHash: fields.rumorHash, 756 createdAt: fields.createdAt, 757 binding: fields.binding, 758 self: 759 fields.self === null 760 ? null 761 : (fields.self as PrivateCiphertextArtifact), 762 receipts: fields.receipts as PrivateAccessProbeReceipt[] 763 }; 764 } else if (fields.family === 'received_envelope') { 765 outerMetadata = outer(fields.outer, owner, true); 766 if ( 767 !hash(id) || 768 !exactLocalFields(fields, [ 769 'schema', 770 'family', 771 'owner', 772 'id', 773 'revision', 774 'outer', 775 'observedAtMilliseconds', 776 'sources', 777 'read' 778 ]) || 779 !unsigned(fields.revision) || 780 outerMetadata?.id !== id || 781 !unsigned(fields.observedAtMilliseconds) || 782 !Array.isArray(fields.sources) || 783 fields.sources.length === 0 || 784 fields.sources.length > RELAY_BUDGETS.inbox || 785 fields.sources.some( 786 (source: unknown) => canonicalRelayOrigin(source) !== source 787 ) || 788 new Set(fields.sources).size !== fields.sources.length || 789 (fields.read !== null && 790 (!exactLocalFields(fields.read, ['rumorHash', 'atMilliseconds']) || 791 !hash(fields.read.rumorHash) || 792 !unsigned(fields.read.atMilliseconds))) 793 ) 794 return failed('malformed'); 795 record = { 796 schema: 1, 797 family: 'received_envelope', 798 owner, 799 id, 800 revision: fields.revision, 801 outer: fields.outer as string, 802 observedAtMilliseconds: fields.observedAtMilliseconds, 803 sources: (fields.sources as unknown[]).map( 804 (source) => source as string 805 ), 806 read: 807 fields.read === null 808 ? null 809 : { 810 rumorHash: fields.read.rumorHash as string, 811 atMilliseconds: fields.read.atMilliseconds as number 812 } 813 }; 814 } else return failed('malformed'); 815 const token = Object.freeze({}) as PrivateRecordHandle; 816 records.set(token, { 817 owner, 818 id, 819 wire: JSON.stringify(record), 820 ...(outerMetadata ? { outerMetadata } : {}) 821 }); 822 return { ok: true, value: token }; 823 } catch { 824 return failed('malformed'); 825 } 826 } 827 export function privateRecordWire( 828 token: PrivateRecordHandle, 829 owner: unknown, 830 id: unknown 831 ): string | undefined { 832 const saved = records.get(token); 833 return saved && saved.owner === owner && saved.id === id 834 ? saved.wire 835 : undefined; 836 } 837 export function privateRecordSnapshot( 838 token: PrivateRecordHandle, 839 owner: unknown, 840 id: unknown 841 ): PrivateRecord | undefined { 842 const wire = privateRecordWire(token, owner, id); 843 return wire === undefined ? undefined : (JSON.parse(wire) as PrivateRecord); 844 } 845 // Strict original codec transport metadata only. A detached record or wrong 846 // owner/ID cannot borrow a verified outer; this is never inner/room permission. 847 export function privateReceivedOuterMetadata( 848 token: PrivateRecordHandle, 849 owner: unknown, 850 id: unknown 851 ): Readonly<{ id: string; createdAt: number }> | undefined { 852 const saved = records.get(token); 853 return saved && 854 saved.owner === owner && 855 saved.id === id && 856 saved.outerMetadata 857 ? { ...saved.outerMetadata } 858 : undefined; 859 } 860 // Handle identity contains no private body; callers must still match namespace. 861 export function privateRecordIdentity( 862 token: PrivateRecordHandle 863 ): Readonly<{ owner: string; id: string }> | undefined { 864 const saved = records.get(token); 865 return saved ? { owner: saved.owner, id: saved.id } : undefined; 866 } 867 export function inspectPrivateSendRecord( 868 raw: unknown, 869 owner: unknown, 870 id: unknown 871 ): PrivateSendReservation | PrivateSendOperation | undefined { 872 const decoded = decodePrivateRecord(raw, owner, id); 873 if (!decoded.ok) return undefined; 874 const value = privateRecordSnapshot(decoded.value, owner, id); 875 return value?.family === 'private_send_reservation' || 876 value?.family === 'private_send_operation' 877 ? value 878 : undefined; 879 }