inbox-probes.ts (54649B)
1 import { 2 inboxProbeArchiveAttemptEvidence, 3 type InboxProbeArchiveAttemptResult, 4 inboxProbeReadbackAttemptEvidence, 5 type InboxProbeReadbackAttemptResult 6 } from '../nostr/private-pool.ts'; 7 import { inboxProbePolicyMatches } from '../nostr/inbox-access.ts'; 8 import { reconcileInboxProbeArchiveAdmission } from '../nostr/private-publisher.ts'; 9 import { 10 recoveredInboxProbeBinding, 11 inboxProbeNonceVerificationEvidence, 12 disposeInboxProbeNonceProof, 13 disposeRecoveredInboxProbe, 14 type RecoveredInboxProbe, 15 type InboxProbeNonceProof, 16 type RecoveredInboxProbeNonceProof 17 } from '../nostr/self-recovery-reader.ts'; 18 import { 19 inboxAccessConstructionBinding, 20 type InboxAccessController 21 } from '../messaging/inbox-access-controller.ts'; 22 import type { InboxOperatorQualification } from '../config/inbox-operators.ts'; 23 import type { RelayPolicy } from '../config/relays.ts'; 24 import { 25 inboxProbeGiftwrapSnapshot, 26 inboxProbeGiftwrapSeal, 27 type InboxProbeGiftwrap 28 } from '../nostr/giftwrap-builder.ts'; 29 import { inboxProbeSealIdentity } from '../nostr/seal-builder.ts'; 30 import { 31 inboxProbeSnapshot, 32 inboxProbeRumorWire, 33 inboxProbeReservationHandle, 34 inboxProbeActionOwner, 35 inboxProbeOperatorBinding, 36 stopInboxProbeIdentity, 37 type InboxProbeIdentity 38 } from '../nostr/inbox-access.ts'; 39 import { 40 privateSessionOwnership, 41 withIdlePrivateLocalStorage, 42 type PrivateSession 43 } from '../runtime/private-session.ts'; 44 import { 45 privateStorageOwner, 46 commitPrivateRecord, 47 observePrivateRecord, 48 privateProbeRemovalEvidence, 49 type PrivateProbeRemovalProof, 50 type PrivateStorageRepository, 51 type PrivateStorageFailure 52 } from './private-storage.ts'; 53 import { 54 decodePrivateRecord, 55 privateRecordWire, 56 privateRecordSnapshot, 57 type PrivateAccessProbe, 58 type PrivateAccessProbeReceipt, 59 type PrivateRecordHandle 60 } from './private-records.ts'; 61 import { LOCAL_PERSISTENCE_BUDGETS } from '../config/budgets.ts'; 62 import { 63 verifyEnvelope, 64 verifiedEnvelopeSnapshot 65 } from '../nostr/verified-envelope.ts'; 66 67 declare const acknowledgementBrand: unique symbol; 68 export type InboxProbeAcknowledgement = Readonly<{ 69 [acknowledgementBrand]: true; 70 }>; 71 export type InboxProbeCommitResult = 72 | Readonly<{ 73 status: 'prepared' | 'existing' | 'reconciled'; 74 acknowledgement: InboxProbeAcknowledgement; 75 }> 76 | Readonly<{ 77 status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped'; 78 disposition: 'original_protected'; 79 }>; 80 type Lineage = { 81 repository: PrivateStorageRepository; 82 session: PrivateSession; 83 identity: InboxProbeIdentity | RecoveredInboxProbe; 84 record(): PrivateAccessProbe; 85 wire(): string; 86 begin(): boolean; 87 finish(): void; 88 active(): boolean; 89 retire(): void; 90 admit(record: PrivateAccessProbe, wire: string): void; 91 }; 92 function createLineage( 93 repository: PrivateStorageRepository, 94 session: PrivateSession, 95 identity: InboxProbeIdentity | RecoveredInboxProbe, 96 originalRecord: PrivateAccessProbe, 97 originalWire: string 98 ): Lineage { 99 let record = originalRecord, 100 wire = originalWire, 101 pending = false, 102 retired = false; 103 const lineage: Lineage = { 104 repository, 105 session, 106 identity, 107 record: () => record, 108 wire: () => wire, 109 begin() { 110 if (pending || retired) return false; 111 pending = true; 112 return true; 113 }, 114 finish() { 115 pending = false; 116 }, 117 active: () => !retired, 118 retire() { 119 retired = true; 120 forgetInboxProbeDelivery(lineage); 121 }, 122 admit(next, nextWire) { 123 record = next; 124 wire = nextWire; 125 } 126 }; 127 return lineage; 128 } 129 const lineages = new WeakMap<InboxProbeIdentity, Lineage>(); 130 type Saved = Readonly<{ 131 repository: PrivateStorageRepository; 132 session: PrivateSession; 133 lineage: Lineage; 134 current(): boolean; 135 revoke(): void; 136 }> & 137 ( 138 | Readonly<{ source: 'construction'; identity: InboxProbeIdentity }> 139 | Readonly<{ 140 source: 'recovered'; 141 identity: RecoveredInboxProbe; 142 access: InboxAccessController; 143 policy: RelayPolicy; 144 operator: InboxOperatorQualification; 145 }> 146 ); 147 const acknowledgements = new WeakMap<InboxProbeAcknowledgement, Saved>(); 148 // Actual native-admitted source owners only. Decoded journal rows cannot enter 149 // this bounded, weak repository/session index, including after a realm reload. 150 const deliveryJournals = new WeakMap< 151 PrivateStorageRepository, 152 WeakMap<PrivateSession, Map<string, Saved>> 153 >(); 154 declare const deliveryObservationBrand: unique symbol; 155 export type InboxProbeDeliveryObservation = Readonly<{ 156 [deliveryObservationBrand]: true; 157 }>; 158 const deliveryObservations = new WeakMap< 159 InboxProbeDeliveryObservation, 160 Readonly<{ 161 saved: Saved; 162 entries: Map<string, Saved>; 163 id: string; 164 wire: string; 165 eventId: string; 166 outerWire: string; 167 }> 168 >(); 169 function currentDeliveryJournal(saved: Saved) { 170 try { 171 return saved.lineage.active() && saved.current(); 172 } catch { 173 return false; 174 } 175 } 176 function forgetInboxProbeDelivery(lineage: Lineage) { 177 const entries = deliveryJournals 178 .get(lineage.repository) 179 ?.get(lineage.session); 180 const id = lineage.record().id; 181 if (entries?.get(id)?.lineage === lineage) entries.delete(id); 182 } 183 function rememberInboxProbeDelivery( 184 acknowledgement: InboxProbeAcknowledgement 185 ) { 186 const saved = acknowledgements.get(acknowledgement); 187 if (!saved || !currentDeliveryJournal(saved)) return; 188 let sessions = deliveryJournals.get(saved.repository); 189 if (!sessions) { 190 sessions = new WeakMap(); 191 deliveryJournals.set(saved.repository, sessions); 192 } 193 let entries = sessions.get(saved.session); 194 if (!entries) { 195 entries = new Map(); 196 sessions.set(saved.session, entries); 197 } 198 for (const [id, entry] of entries) 199 if (!currentDeliveryJournal(entry)) entries.delete(id); 200 const id = saved.lineage.record().id; 201 if ( 202 !entries.has(id) && 203 entries.size >= LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 204 ) 205 return; 206 entries.set(id, saved); 207 } 208 209 // Called by actual admitted-envelope retention under its existing owner lock. 210 // The result is local receive bookkeeping, never qualification or transport 211 // authority. Exact source AND fresh whole-owner native custody are required. 212 export async function observeInboxProbeDelivery( 213 repository: PrivateStorageRepository, 214 session: PrivateSession, 215 eventId: string, 216 outerWire: string, 217 cancellation?: AbortSignal 218 ): Promise<InboxProbeDeliveryObservation | 'ordinary' | 'stopped'> { 219 const entries = deliveryJournals.get(repository)?.get(session); 220 if (!entries) return 'ordinary'; 221 for (const [id, saved] of entries) { 222 if (!currentDeliveryJournal(saved)) { 223 entries.delete(id); 224 continue; 225 } 226 const lineage = saved.lineage, 227 record = lineage.record(); 228 if (record.self?.eventId !== eventId || record.self.wire !== outerWire) 229 continue; 230 const ownership = privateSessionOwnership(session), 231 wire = lineage.wire(); 232 const drop = () => { 233 if (entries.get(id) === saved) entries.delete(id); 234 }; 235 if (!ownership?.current() || cancellation?.aborted) { 236 drop(); 237 return 'stopped'; 238 } 239 try { 240 const observed = await observePrivateRecord( 241 repository, 242 'private_sends', 243 id 244 ); 245 if (!ownership.current() || cancellation?.aborted) { 246 drop(); 247 return 'stopped'; 248 } 249 if ( 250 !currentDeliveryJournal(saved) || 251 entries.get(id) !== saved || 252 !observed.ok || 253 lineage.wire() !== wire || 254 observed.value.wire !== wire || 255 privateRecordWire(observed.value.handle, ownership.owner, id) !== wire 256 ) { 257 drop(); 258 return 'ordinary'; 259 } 260 const proof = Object.freeze({}) as InboxProbeDeliveryObservation; 261 deliveryObservations.set(proof, { 262 saved, 263 entries, 264 id, 265 wire, 266 eventId, 267 outerWire 268 }); 269 return proof; 270 } catch { 271 drop(); 272 return ownership.current() && !cancellation?.aborted 273 ? 'ordinary' 274 : 'stopped'; 275 } 276 } 277 return 'ordinary'; 278 } 279 // One-use source observation crosses the async native-reader boundary. Its 280 // exact issuer/index/Lineage is rechecked synchronously at exclusion consumption; 281 // a copied proof or a newly registered replacement cannot provide authority. 282 export function consumeInboxProbeDelivery( 283 proof: InboxProbeDeliveryObservation, 284 repository: PrivateStorageRepository, 285 session: PrivateSession, 286 eventId: string, 287 outerWire: string 288 ): boolean { 289 const observed = deliveryObservations.get(proof); 290 if (!observed) return false; 291 deliveryObservations.delete(proof); 292 const { saved, entries, id, wire } = observed; 293 const current = 294 saved.repository === repository && 295 saved.session === session && 296 observed.eventId === eventId && 297 observed.outerWire === outerWire && 298 entries.get(id) === saved && 299 saved.lineage.wire() === wire && 300 currentDeliveryJournal(saved); 301 if (!current && entries.get(id) === saved) entries.delete(id); 302 return current; 303 } 304 const actions = new WeakMap< 305 InboxProbeGiftwrap, 306 Readonly<{ 307 repository: PrivateStorageRepository; 308 session: PrivateSession; 309 pending(): boolean; 310 }> 311 >(); 312 const refuse = ( 313 status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped' 314 ): InboxProbeCommitResult => ({ status, disposition: 'original_protected' }); 315 316 // This owner accepts only the original genuine construction chain. Decoding a 317 // row, copying a snapshot or supplying the same public key grants no authority. 318 function input( 319 repository: PrivateStorageRepository, 320 session: PrivateSession, 321 wrap: InboxProbeGiftwrap 322 ) { 323 const artifact = inboxProbeGiftwrapSnapshot(wrap), 324 seal = inboxProbeGiftwrapSeal(wrap), 325 identity = seal && inboxProbeSealIdentity(seal), 326 reservation = identity && inboxProbeSnapshot(identity), 327 handle = identity && inboxProbeReservationHandle(identity); 328 if ( 329 !artifact || 330 !identity || 331 !reservation || 332 !handle || 333 !inboxProbeRumorWire(identity, session) 334 ) 335 return undefined; 336 const ownership = privateSessionOwnership(session); 337 if ( 338 !ownership?.current() || 339 privateStorageOwner(repository) !== ownership.owner || 340 reservation.owner !== ownership.owner || 341 artifact.owner !== reservation.owner || 342 artifact.destination !== reservation.owner || 343 artifact.command !== reservation.id || 344 artifact.rumorHash !== reservation.rumorHash || 345 artifact.createdAt !== reservation.createdAt 346 ) 347 return undefined; 348 const verified = verifyEnvelope(artifact.wire), 349 event = verified.ok && verifiedEnvelopeSnapshot(verified.value), 350 reservationWire = privateRecordWire( 351 handle, 352 reservation.owner, 353 reservation.id 354 ); 355 if ( 356 !event || 357 !reservationWire || 358 event.kind !== 1059 || 359 JSON.stringify(event.tags) !== JSON.stringify([['p', reservation.owner]]) 360 ) 361 return undefined; 362 const record: PrivateAccessProbe = { 363 ...reservation, 364 revision: 1, 365 self: { eventId: event.id, wire: artifact.wire }, 366 receipts: [] 367 }, 368 decoded = decodePrivateRecord( 369 JSON.stringify(record), 370 reservation.owner, 371 reservation.id 372 ); 373 if (!decoded.ok) return undefined; 374 const wire = privateRecordWire( 375 decoded.value, 376 reservation.owner, 377 reservation.id 378 ); 379 if (!wire) return undefined; 380 const frozenReservation = JSON.stringify(reservation), 381 frozenArtifact = JSON.stringify(artifact); 382 function current() { 383 return ( 384 ownership!.current() && 385 !!inboxProbeRumorWire(identity!, session) && 386 privateStorageOwner(repository) === reservation!.owner && 387 JSON.stringify(inboxProbeSnapshot(identity!)) === frozenReservation && 388 JSON.stringify(inboxProbeGiftwrapSnapshot(wrap)) === frozenArtifact 389 ); 390 } 391 return current() 392 ? { 393 identity, 394 reservation, 395 reservationWire, 396 record, 397 handle: decoded.value, 398 wire, 399 current 400 } 401 : undefined; 402 } 403 404 // Native completion and a separate physical-wire observation are necessary. 405 // This local acknowledgement permits neither EVENT nor readiness or cleanup. 406 export async function commitInboxProbe( 407 repository: PrivateStorageRepository, 408 session: PrivateSession, 409 wrap: InboxProbeGiftwrap, 410 review: unknown 411 ): Promise<InboxProbeCommitResult> { 412 if ( 413 typeof window === 'undefined' || 414 review !== 'reviewed_inbox_probe_commit' || 415 typeof wrap !== 'object' || 416 wrap === null 417 ) 418 return refuse('invalid'); 419 const prior = actions.get(wrap); 420 if (prior?.pending()) return refuse('busy'); 421 if (prior && (prior.repository !== repository || prior.session !== session)) 422 return refuse('invalid_scope'); 423 let pending = true; 424 let captured: ReturnType<typeof input>; 425 try { 426 actions.set(wrap, { repository, session, pending: () => pending }); 427 captured = input(repository, session, wrap); 428 if (!captured) return refuse('invalid'); 429 const original = captured; 430 if (!navigator.locks?.request) return refuse('unavailable'); 431 return await navigator.locks.request( 432 'harvestcircle:owner:' + original.reservation.owner, 433 { mode: 'exclusive', ifAvailable: true }, 434 async (lock) => { 435 if (!lock) return refuse('busy'); 436 if (!original.current()) return refuse('stopped'); 437 const idle = await withIdlePrivateLocalStorage( 438 session, 439 async (): Promise<InboxProbeCommitResult> => { 440 if (!original.current()) return refuse('stopped'); 441 const { owner, id } = original.reservation, 442 loaded = await observePrivateRecord( 443 repository, 444 'private_sends', 445 id 446 ); 447 if (!original.current()) return refuse('stopped'); 448 if (!loaded.ok) return refuse(loaded.reason); 449 const previous = lineages.get(original.identity); 450 if ( 451 previous && 452 (previous.repository !== repository || 453 previous.session !== session) 454 ) 455 return refuse('invalid_scope'); 456 const expectedWire = previous?.wire() ?? original.wire; 457 let status: 'prepared' | 'existing' | 'reconciled'; 458 if (loaded.value.wire === expectedWire) { 459 status = 'existing'; 460 } else { 461 if (previous || loaded.value.wire !== original.reservationWire) 462 return refuse('conflict'); 463 const committed = await commitPrivateRecord( 464 repository, 465 original.handle, 466 loaded.value.handle 467 ); 468 if (!original.current()) return refuse('stopped'); 469 if (!committed.ok && committed.reason !== 'unknown_completion') 470 return refuse(committed.reason); 471 status = !committed.ok 472 ? 'reconciled' 473 : committed.value.state === 'existing' 474 ? 'existing' 475 : 'prepared'; 476 } 477 const readback = await observePrivateRecord( 478 repository, 479 'private_sends', 480 id 481 ); 482 if (!original.current()) return refuse('stopped'); 483 if (!readback.ok) return refuse(readback.reason); 484 if (readback.value.wire !== expectedWire) return refuse('conflict'); 485 // The handle and physical wire have both passed complete-owner 486 // validation. Their equality is checked independently of metadata 487 // normalization; equivalent raw JSON changes cannot be hidden. 488 if ( 489 privateRecordWire(readback.value.handle, owner, id) !== 490 expectedWire 491 ) 492 return refuse('conflict'); 493 const lineage = 494 previous ?? 495 createLineage( 496 repository, 497 session, 498 original.identity, 499 original.record, 500 original.wire 501 ); 502 lineages.set(original.identity, lineage); 503 const acknowledgement = Object.freeze( 504 {} 505 ) as InboxProbeAcknowledgement; 506 let revoked = false; 507 acknowledgements.set(acknowledgement, { 508 source: 'construction', 509 repository, 510 session, 511 identity: original.identity, 512 lineage, 513 current: () => !revoked && lineage.active() && original.current(), 514 revoke: () => { 515 revoked = true; 516 } 517 }); 518 rememberInboxProbeDelivery(acknowledgement); 519 return { status, acknowledgement }; 520 } 521 ); 522 return idle.ok 523 ? idle.value 524 : refuse(original.current() ? 'busy' : 'stopped'); 525 } 526 ); 527 } catch { 528 return refuse( 529 captured ? (captured.current() ? 'unavailable' : 'stopped') : 'invalid' 530 ); 531 } finally { 532 pending = false; 533 if (!captured && !prior) actions.delete(wrap); 534 } 535 } 536 537 export function inboxProbeAcknowledgementSnapshot( 538 acknowledgement: InboxProbeAcknowledgement 539 ) { 540 const saved = acknowledgements.get(acknowledgement); 541 return saved?.current() 542 ? { 543 record: JSON.parse( 544 JSON.stringify(saved.lineage.record()) 545 ) as PrivateAccessProbe, 546 fact: 'acknowledged_local_probe_ciphertext_only' as const 547 } 548 : undefined; 549 } 550 551 export async function verifyInboxProbeAcknowledgement( 552 repository: PrivateStorageRepository, 553 session: PrivateSession, 554 acknowledgement: InboxProbeAcknowledgement 555 ): Promise<boolean> { 556 const saved = acknowledgements.get(acknowledgement); 557 if ( 558 !saved || 559 saved.repository !== repository || 560 saved.session !== session || 561 !saved.current() 562 ) 563 return false; 564 const readback = await observePrivateRecord( 565 repository, 566 'private_sends', 567 saved.lineage.record().id 568 ); 569 const valid = 570 saved.current() && 571 readback.ok && 572 readback.value.wire === saved.lineage.wire() && 573 privateRecordWire( 574 readback.value.handle, 575 saved.lineage.record().owner, 576 saved.lineage.record().id 577 ) === saved.lineage.wire(); 578 if (!valid) saved.revoke(); 579 return valid; 580 } 581 582 // Genuine lexical associations only. Detached row fields cannot mint a binding. 583 export function inboxProbePublicationBinding( 584 repository: PrivateStorageRepository, 585 session: PrivateSession, 586 acknowledgement: InboxProbeAcknowledgement, 587 policy: RelayPolicy 588 ) { 589 const saved = acknowledgements.get(acknowledgement); 590 if ( 591 !saved || 592 saved.source !== 'construction' || 593 saved.repository !== repository || 594 saved.session !== session || 595 !saved.current() || 596 !inboxProbePolicyMatches(saved.identity, session, policy) 597 ) 598 return undefined; 599 return { 600 identity: saved.identity, 601 record: JSON.parse( 602 JSON.stringify(saved.lineage.record()) 603 ) as PrivateAccessProbe, 604 wire: saved.lineage.wire(), 605 current: () => 606 saved.current() && 607 inboxProbePolicyMatches(saved.identity, session, policy) 608 }; 609 } 610 611 export type RecoveredInboxProbeAdoptionResult = 612 | Readonly<{ 613 status: 'adopted' | 'existing'; 614 acknowledgement: InboxProbeAcknowledgement; 615 }> 616 | Readonly<{ 617 status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped'; 618 disposition: 'original_protected'; 619 }>; 620 function createRecoveryAdoption() { 621 let pending = false, 622 result: RecoveredInboxProbeAdoptionResult | undefined; 623 return { 624 pending: () => pending, 625 result: () => result, 626 begin() { 627 pending = true; 628 }, 629 finish() { 630 pending = false; 631 }, 632 admit(value: RecoveredInboxProbeAdoptionResult) { 633 result = value; 634 return value; 635 } 636 }; 637 } 638 type RecoveryAdoption = ReturnType<typeof createRecoveryAdoption>; 639 const recoveredAdoptions = new WeakMap<RecoveredInboxProbe, RecoveryAdoption>(); 640 641 // A recovered proof is not a construction identity. Its acknowledgement adopts 642 // only complete current native custody; old receipt labels remain unverified. 643 export async function adoptRecoveredInboxProbe( 644 repository: PrivateStorageRepository, 645 session: PrivateSession, 646 access: InboxAccessController, 647 policy: RelayPolicy, 648 operator: InboxOperatorQualification, 649 proof: RecoveredInboxProbe, 650 review: unknown 651 ): Promise<RecoveredInboxProbeAdoptionResult> { 652 const refuse = ( 653 status: PrivateStorageFailure | 'invalid' | 'busy' | 'stopped' 654 ): RecoveredInboxProbeAdoptionResult => ({ 655 status, 656 disposition: 'original_protected' 657 }); 658 if ( 659 typeof window === 'undefined' || 660 review !== 'reviewed_original_inbox_probe_retry' 661 ) 662 return refuse('invalid'); 663 let action: RecoveryAdoption | undefined, 664 issued: InboxProbeAcknowledgement | undefined; 665 try { 666 // Authenticate the proof and all lexical associations before any passive 667 // private ownership or callback-capable native/SDK admission. 668 const original = recoveredInboxProbeBinding( 669 proof, 670 repository, 671 session, 672 access, 673 policy, 674 operator 675 ); 676 if (!original || privateStorageOwner(repository) !== original.owner) 677 return refuse('invalid_scope'); 678 const previous = recoveredAdoptions.get(proof); 679 if (previous?.pending()) return refuse('busy'); 680 const previousResult = previous?.result(); 681 if (previousResult && !('acknowledgement' in previousResult)) 682 return previousResult; 683 action = previous ?? createRecoveryAdoption(); 684 action.begin(); 685 recoveredAdoptions.set(proof, action); 686 const known = action.result(); 687 const prior = 688 known && 'acknowledgement' in known ? known.acknowledgement : undefined; 689 const saved = prior && acknowledgements.get(prior); 690 function current() { 691 const now = recoveredInboxProbeBinding( 692 proof, 693 repository, 694 session, 695 access, 696 policy, 697 operator 698 ); 699 return ( 700 !!now && 701 now.storedWire === original!.storedWire && 702 now.command === original!.command && 703 now.eventId === original!.eventId && 704 (!saved || saved.current()) 705 ); 706 } 707 if (!current()) return action.admit(refuse('stopped')); 708 if (!navigator.locks?.request) return action.admit(refuse('unavailable')); 709 const result = await navigator.locks.request( 710 'harvestcircle:owner:' + original.owner, 711 { mode: 'exclusive', ifAvailable: true }, 712 async (lock): Promise<RecoveredInboxProbeAdoptionResult> => { 713 if (!lock) return refuse('busy'); 714 if (!current()) return refuse('stopped'); 715 const idle = await withIdlePrivateLocalStorage( 716 session, 717 async (): Promise<RecoveredInboxProbeAdoptionResult> => { 718 if (!current()) return refuse('stopped'); 719 const observed = await observePrivateRecord( 720 repository, 721 'private_sends', 722 original.command 723 ); 724 if (!current()) return refuse('stopped'); 725 if (!observed.ok) return refuse(observed.reason); 726 const expected = saved?.lineage.wire() ?? original.storedWire; 727 if ( 728 observed.value.wire !== expected || 729 privateRecordWire( 730 observed.value.handle, 731 original.owner, 732 original.command 733 ) !== expected 734 ) { 735 saved?.revoke(); 736 return refuse('conflict'); 737 } 738 if (prior) return { status: 'existing', acknowledgement: prior }; 739 const record = privateRecordSnapshot( 740 observed.value.handle, 741 original.owner, 742 original.command 743 ); 744 if ( 745 !record || 746 record.family !== 'private_access_probe' || 747 !record.self || 748 record.self.eventId !== original.eventId || 749 record.rumorHash !== original.rumorHash || 750 !current() 751 ) 752 return refuse('invalid_record'); 753 const lineage = createLineage( 754 repository, 755 session, 756 proof, 757 record, 758 expected 759 ); 760 let revoked = false; 761 const acknowledgement = Object.freeze( 762 {} 763 ) as InboxProbeAcknowledgement; 764 issued = acknowledgement; 765 acknowledgements.set(acknowledgement, { 766 source: 'recovered', 767 repository, 768 session, 769 identity: proof, 770 access, 771 policy, 772 operator, 773 lineage, 774 current: () => !revoked && lineage.active() && current(), 775 revoke: () => { 776 revoked = true; 777 } 778 }); 779 rememberInboxProbeDelivery(acknowledgement); 780 return { status: 'adopted', acknowledgement }; 781 } 782 ); 783 return idle.ok ? idle.value : refuse(current() ? 'busy' : 'stopped'); 784 } 785 ); 786 // Busy before admission can retry this same original proof. No failed 787 // custody or stopped acknowledgement can be recaptured as a new lineage. 788 if (result.status !== 'busy') action.admit(result); 789 if (!('acknowledgement' in result) && issued) 790 acknowledgements.get(issued)?.revoke(); 791 return result; 792 } catch { 793 if (issued) acknowledgements.get(issued)?.revoke(); 794 const result = refuse('unavailable'); 795 action?.admit(result); 796 return result; 797 } finally { 798 action?.finish(); 799 } 800 } 801 802 // Separate recovered binding: unchanged original/C1 factories cannot accept it. 803 // This is memory lineage only; every effect must reread exact native custody. 804 export function recoveredInboxProbePublicationBinding( 805 repository: PrivateStorageRepository, 806 session: PrivateSession, 807 acknowledgement: InboxProbeAcknowledgement, 808 policy: RelayPolicy 809 ) { 810 const saved = acknowledgements.get(acknowledgement); 811 if ( 812 !saved || 813 saved.source !== 'recovered' || 814 saved.repository !== repository || 815 saved.session !== session || 816 saved.policy !== policy || 817 !saved.current() 818 ) 819 return undefined; 820 return { 821 identity: saved.identity, 822 access: saved.access, 823 record: JSON.parse( 824 JSON.stringify(saved.lineage.record()) 825 ) as PrivateAccessProbe, 826 wire: saved.lineage.wire(), 827 current: () => saved.current() 828 }; 829 } 830 export type InboxProbeArchiveCommitResult = Readonly<{ 831 status: 832 | 'saved' 833 | 'existing' 834 | 'reconciled' 835 | PrivateStorageFailure 836 | 'invalid' 837 | 'busy'; 838 disposition: 'original_protected'; 839 }>; 840 const appliedArchiveEvidence = new WeakMap< 841 InboxProbeArchiveAttemptResult | InboxProbeReadbackAttemptResult, 842 Lineage 843 >(); 844 // This query authenticates the exact result's native-applied Lineage. Labels, 845 // cloned receipts and merely settled network attempts cannot release a charge. 846 export function appliedInboxProbeArchiveAdmission( 847 result: InboxProbeArchiveAttemptResult 848 ) { 849 const effect = inboxProbeArchiveAttemptEvidence(result), 850 lineage = appliedArchiveEvidence.get(result); 851 if (!effect || !lineage || effect.repository !== lineage.repository) 852 return undefined; 853 const saved = acknowledgements.get(effect.acknowledgement); 854 if (!saved || saved.lineage !== lineage) return undefined; 855 const record = lineage.record(), 856 fact = record.receipts.find( 857 (receipt) => JSON.stringify(receipt) === effect.receiptWire 858 ); 859 if (!fact || fact.role !== 'access_archive') return undefined; 860 return { 861 session: lineage.session, 862 command: record.id, 863 actionId: fact.actionId, 864 origin: fact.origin, 865 eventId: fact.eventId, 866 attempt: fact.attempt 867 }; 868 } 869 // Only actual SDK attempt observations can advance memory-only provenance. 870 // This bookkeeping can settle after owner loss, but cannot authorize traffic. 871 async function commitProbeAttempt( 872 repository: PrivateStorageRepository, 873 result: InboxProbeArchiveAttemptResult | InboxProbeReadbackAttemptResult, 874 role: 'access_archive' | 'access_readback' 875 ): Promise<InboxProbeArchiveCommitResult> { 876 const refuse = ( 877 status: InboxProbeArchiveCommitResult['status'] 878 ): InboxProbeArchiveCommitResult => ({ 879 status, 880 disposition: 'original_protected' 881 }); 882 const effect = 883 role === 'access_archive' 884 ? inboxProbeArchiveAttemptEvidence( 885 result as InboxProbeArchiveAttemptResult 886 ) 887 : inboxProbeReadbackAttemptEvidence( 888 result as InboxProbeReadbackAttemptResult 889 ); 890 if (!effect || effect.repository !== repository) return refuse('invalid'); 891 const saved = acknowledgements.get(effect.acknowledgement), 892 lineage = saved?.lineage; 893 if ( 894 !saved || 895 !lineage || 896 lineage.repository !== repository || 897 privateStorageOwner(repository) !== lineage.record().owner || 898 !lineage.record().self 899 ) 900 return refuse('invalid'); 901 if (!lineage.begin()) return refuse('busy'); 902 try { 903 if (typeof window === 'undefined' || !navigator.locks?.request) 904 return refuse('unavailable'); 905 return await navigator.locks.request( 906 'harvestcircle:owner:' + lineage.record().owner, 907 { mode: 'exclusive', ifAvailable: true }, 908 async (lock) => { 909 if (!lock) return refuse('busy'); 910 const owner = lineage.record().owner, 911 id = lineage.record().id, 912 observed = await observePrivateRecord( 913 repository, 914 'private_sends', 915 id 916 ); 917 if (!observed.ok) return refuse(observed.reason); 918 if ( 919 observed.value.wire !== lineage.wire() || 920 privateRecordWire(observed.value.handle, owner, id) !== lineage.wire() 921 ) 922 return refuse('conflict'); 923 if (appliedArchiveEvidence.get(result) === lineage) { 924 if (role === 'access_archive') 925 reconcileInboxProbeArchiveAdmission( 926 result as InboxProbeArchiveAttemptResult 927 ); 928 return refuse('existing'); 929 } 930 if ( 931 effect.predecessorWire !== lineage.wire() || 932 lineage.record().revision === Number.MAX_SAFE_INTEGER 933 ) 934 return refuse('conflict'); 935 const fact: unknown = JSON.parse(effect.receiptWire); 936 const candidate = decodePrivateRecord( 937 JSON.stringify({ 938 ...lineage.record(), 939 revision: lineage.record().revision + 1, 940 receipts: [...lineage.record().receipts, fact] 941 }), 942 owner, 943 id 944 ); 945 if (!candidate.ok) return refuse('invalid_record'); 946 const nextWire = privateRecordWire(candidate.value, owner, id), 947 next = privateRecordSnapshot(candidate.value, owner, id); 948 if (!nextWire || !next || next.family !== 'private_access_probe') 949 return refuse('invalid_record'); 950 const last = next.receipts[next.receipts.length - 1]; 951 if ( 952 last.role !== role || 953 last.eventId !== lineage.record().self!.eventId || 954 !( 955 role === 'access_archive' 956 ? lineage.record().binding.archiveTargets 957 : lineage.record().binding.readTargets 958 ).includes(last.origin) 959 ) 960 return refuse('invalid_record'); 961 const committed = await commitPrivateRecord( 962 repository, 963 candidate.value, 964 observed.value.handle 965 ); 966 if (!committed.ok && committed.reason !== 'unknown_completion') 967 return refuse(committed.reason); 968 const readback = await observePrivateRecord( 969 repository, 970 'private_sends', 971 id 972 ); 973 if (!readback.ok) return refuse('unknown_completion'); 974 if ( 975 readback.value.wire !== nextWire || 976 privateRecordWire(readback.value.handle, owner, id) !== nextWire 977 ) 978 return refuse('conflict'); 979 // Only this actual append/native completion/fresh physical observation can 980 // refresh live ACKs. A decoded receipt or metadata label never can. 981 lineage.admit(next, nextWire); 982 appliedArchiveEvidence.set(result, lineage); 983 if (role === 'access_archive') 984 reconcileInboxProbeArchiveAdmission( 985 result as InboxProbeArchiveAttemptResult 986 ); 987 return refuse( 988 !committed.ok 989 ? 'reconciled' 990 : committed.value.state === 'existing' 991 ? 'existing' 992 : 'saved' 993 ); 994 } 995 ); 996 } catch { 997 return refuse('unknown_completion'); 998 } finally { 999 lineage.finish(); 1000 } 1001 } 1002 1003 export function commitInboxProbeArchiveAttempt( 1004 repository: PrivateStorageRepository, 1005 result: InboxProbeArchiveAttemptResult 1006 ): Promise<InboxProbeArchiveCommitResult> { 1007 return commitProbeAttempt(repository, result, 'access_archive'); 1008 } 1009 export function commitInboxProbeReadbackAttempt( 1010 repository: PrivateStorageRepository, 1011 result: InboxProbeReadbackAttemptResult 1012 ): Promise<InboxProbeArchiveCommitResult> { 1013 return commitProbeAttempt(repository, result, 'access_readback'); 1014 } 1015 1016 declare const nonceAcknowledgementBrand: unique symbol; 1017 export type InboxProbeNonceAcknowledgement = Readonly<{ 1018 [nonceAcknowledgementBrand]: true; 1019 }>; 1020 export type InboxProbeNonceCommitResult = Readonly<{ 1021 status: 1022 | 'saved' 1023 | 'existing' 1024 | 'reconciled' 1025 | PrivateStorageFailure 1026 | 'invalid' 1027 | 'busy' 1028 | 'stopped'; 1029 disposition: 'original_protected'; 1030 acknowledgement?: InboxProbeNonceAcknowledgement; 1031 provenance?: 'current' | 'historical_only'; 1032 }>; 1033 type NonceProof = InboxProbeNonceProof | RecoveredInboxProbeNonceProof; 1034 type NonceOperationInput = Readonly<{ 1035 repository: PrivateStorageRepository; 1036 session: PrivateSession; 1037 policy: RelayPolicy; 1038 proof: NonceProof; 1039 acknowledgement: InboxProbeAcknowledgement; 1040 observation: InboxProbeReadbackAttemptResult; 1041 lineage: Lineage; 1042 baseWire: string; 1043 nextWire: string; 1044 nextRecord: PrivateAccessProbe; 1045 nextHandle: PrivateRecordHandle; 1046 }>; 1047 type NonceOperation = NonceOperationInput & 1048 Readonly<{ 1049 uncertain(): boolean; 1050 applied(): boolean; 1051 markAttempted(): void; 1052 markDefiniteFailure(): void; 1053 markApplied(): void; 1054 acknowledgementToken(): InboxProbeNonceAcknowledgement | undefined; 1055 issueAcknowledgement(): InboxProbeNonceAcknowledgement; 1056 }>; 1057 function createNonceOperation(input: NonceOperationInput): NonceOperation { 1058 let uncertain = false, 1059 applied = false, 1060 acknowledgement: InboxProbeNonceAcknowledgement | undefined; 1061 return { 1062 ...input, 1063 uncertain: () => uncertain, 1064 applied: () => applied, 1065 markAttempted() { 1066 uncertain = true; 1067 }, 1068 markDefiniteFailure() { 1069 uncertain = false; 1070 }, 1071 markApplied() { 1072 applied = true; 1073 }, 1074 acknowledgementToken: () => acknowledgement, 1075 issueAcknowledgement() { 1076 return (acknowledgement ??= Object.freeze( 1077 {} 1078 ) as InboxProbeNonceAcknowledgement); 1079 } 1080 }; 1081 } 1082 const nonceOperations = new WeakMap<NonceProof, NonceOperation>(); 1083 const nonceAcknowledgements = new WeakMap< 1084 InboxProbeNonceAcknowledgement, 1085 NonceOperation 1086 >(); 1087 function currentNonceOperation(operation: NonceOperation): boolean { 1088 const evidence = inboxProbeNonceVerificationEvidence( 1089 operation.proof, 1090 operation.repository, 1091 operation.session, 1092 operation.policy 1093 ); 1094 return ( 1095 !!evidence && 1096 evidence.acknowledgement === operation.acknowledgement && 1097 evidence.observation === operation.observation && 1098 evidence.current() && 1099 acknowledgements.get(evidence.acknowledgement)?.lineage === 1100 operation.lineage && 1101 appliedArchiveEvidence.get(evidence.observation) === operation.lineage 1102 ); 1103 } 1104 function nonceSuccess( 1105 operation: NonceOperation, 1106 status: 'saved' | 'existing' | 'reconciled' 1107 ): InboxProbeNonceCommitResult { 1108 if (!currentNonceOperation(operation)) 1109 return { 1110 status, 1111 disposition: 'original_protected', 1112 provenance: 'historical_only' 1113 }; 1114 let acknowledgement = operation.acknowledgementToken(); 1115 if (!acknowledgement) { 1116 acknowledgement = operation.issueAcknowledgement(); 1117 nonceAcknowledgements.set(acknowledgement, operation); 1118 } 1119 return { 1120 status, 1121 disposition: 'original_protected', 1122 provenance: 'current', 1123 acknowledgement 1124 }; 1125 } 1126 1127 // Persist a genuine local nonce observation, never a caller receipt/status. 1128 // A source-admitted native operation may settle after loss as history only. 1129 export async function commitInboxProbeNonceVerification( 1130 repository: PrivateStorageRepository, 1131 session: PrivateSession, 1132 policy: RelayPolicy, 1133 proof: NonceProof 1134 ): Promise<InboxProbeNonceCommitResult> { 1135 const refuse = ( 1136 status: InboxProbeNonceCommitResult['status'] 1137 ): InboxProbeNonceCommitResult => ({ 1138 status, 1139 disposition: 'original_protected' 1140 }); 1141 try { 1142 if (typeof window === 'undefined') return refuse('invalid'); 1143 const evidence = inboxProbeNonceVerificationEvidence( 1144 proof, 1145 repository, 1146 session, 1147 policy 1148 ), 1149 saved = evidence && acknowledgements.get(evidence.acknowledgement), 1150 effect = 1151 evidence && inboxProbeReadbackAttemptEvidence(evidence.observation); 1152 // All strong nonce/read/ACK associations precede passive ownership or DB. 1153 if ( 1154 !evidence || 1155 !saved || 1156 !effect || 1157 effect.repository !== repository || 1158 effect.acknowledgement !== evidence.acknowledgement || 1159 saved.repository !== repository || 1160 saved.session !== session || 1161 appliedArchiveEvidence.get(evidence.observation) !== saved.lineage || 1162 !evidence.current() 1163 ) 1164 return refuse('invalid'); 1165 const fact = JSON.parse(effect.receiptWire) as PrivateAccessProbeReceipt; 1166 const lineage = saved.lineage; 1167 if ( 1168 fact.role !== 'access_readback' || 1169 fact.status !== 'readback' || 1170 fact.eventId !== evidence.eventId || 1171 !lineage.record().self || 1172 evidence.command !== lineage.record().id || 1173 evidence.owner !== lineage.record().owner || 1174 !Number.isSafeInteger(evidence.verifiedAtMilliseconds) || 1175 evidence.verifiedAtMilliseconds < 0 1176 ) 1177 return refuse('invalid'); 1178 const original = lineage; 1179 if (!original.begin()) return refuse('busy'); 1180 // Only the owner that actually acquired begin may finish this lineage. 1181 try { 1182 if (!navigator.locks?.request) return refuse('unavailable'); 1183 return await navigator.locks.request( 1184 'harvestcircle:owner:' + evidence.owner, 1185 { mode: 'exclusive', ifAvailable: true }, 1186 async (lock): Promise<InboxProbeNonceCommitResult> => { 1187 if (!lock) return refuse('busy'); 1188 if (!evidence.current()) return refuse('stopped'); 1189 const job = await withIdlePrivateLocalStorage( 1190 session, 1191 async (): Promise<InboxProbeNonceCommitResult> => { 1192 if (!evidence.current()) return refuse('stopped'); 1193 const observed = await observePrivateRecord( 1194 repository, 1195 'private_sends', 1196 evidence.command 1197 ); 1198 if (!evidence.current()) return refuse('stopped'); 1199 if (!observed.ok) return refuse(observed.reason); 1200 let operation = nonceOperations.get(proof); 1201 if ( 1202 operation && 1203 (operation.repository !== repository || 1204 operation.session !== session || 1205 operation.policy !== policy || 1206 operation.lineage !== original || 1207 operation.acknowledgement !== evidence.acknowledgement || 1208 operation.observation !== evidence.observation) 1209 ) 1210 return refuse('invalid_scope'); 1211 if ( 1212 privateRecordWire( 1213 observed.value.handle, 1214 evidence.owner, 1215 evidence.command 1216 ) !== observed.value.wire 1217 ) 1218 return refuse('conflict'); 1219 if (operation?.applied()) { 1220 if (observed.value.wire !== original.wire()) 1221 return refuse('conflict'); 1222 return nonceSuccess(operation, 'existing'); 1223 } 1224 if ( 1225 operation?.uncertain() && 1226 observed.value.wire === operation.nextWire 1227 ) { 1228 if (original.wire() !== operation.baseWire) 1229 return refuse('conflict'); 1230 original.admit(operation.nextRecord, operation.nextWire); 1231 operation.markApplied(); 1232 return nonceSuccess(operation, 'reconciled'); 1233 } 1234 if ( 1235 observed.value.wire !== original.wire() || 1236 (operation && operation.baseWire !== original.wire()) 1237 ) 1238 return refuse('conflict'); 1239 if (!operation) { 1240 if (original.record().revision === Number.MAX_SAFE_INTEGER) 1241 return refuse('invalid_record'); 1242 const candidate = decodePrivateRecord( 1243 JSON.stringify({ 1244 ...original.record(), 1245 revision: original.record().revision + 1, 1246 receipts: [ 1247 ...original.record().receipts, 1248 { 1249 ...fact, 1250 status: 'nonce_verified', 1251 observedAtMilliseconds: evidence.verifiedAtMilliseconds 1252 } 1253 ] 1254 }), 1255 evidence.owner, 1256 evidence.command 1257 ); 1258 if (!candidate.ok) return refuse('invalid_record'); 1259 const nextWire = privateRecordWire( 1260 candidate.value, 1261 evidence.owner, 1262 evidence.command 1263 ), 1264 nextRecord = privateRecordSnapshot( 1265 candidate.value, 1266 evidence.owner, 1267 evidence.command 1268 ); 1269 if ( 1270 !nextWire || 1271 !nextRecord || 1272 nextRecord.family !== 'private_access_probe' 1273 ) 1274 return refuse('invalid_record'); 1275 operation = createNonceOperation({ 1276 repository, 1277 session, 1278 policy, 1279 proof, 1280 acknowledgement: evidence.acknowledgement, 1281 observation: evidence.observation, 1282 lineage: original, 1283 baseWire: original.wire(), 1284 nextWire, 1285 nextRecord, 1286 nextHandle: candidate.value 1287 }); 1288 } 1289 // This is the actual append-admission boundary. Before it, stale 1290 // proof has no write. After it, only bounded history may settle. 1291 if (!currentNonceOperation(operation)) return refuse('stopped'); 1292 nonceOperations.set(proof, operation); 1293 const previousUncertainty = operation.uncertain(); 1294 operation.markAttempted(); 1295 const committed = await commitPrivateRecord( 1296 repository, 1297 operation.nextHandle, 1298 observed.value.handle 1299 ); 1300 if (!committed.ok && committed.reason !== 'unknown_completion') { 1301 operation.markDefiniteFailure(); 1302 return refuse(committed.reason); 1303 } 1304 if ( 1305 committed.ok && 1306 committed.value.state === 'existing' && 1307 !previousUncertainty 1308 ) { 1309 // A matching handwritten successor is not our completed append. 1310 operation.markDefiniteFailure(); 1311 return refuse('conflict'); 1312 } 1313 const after = await observePrivateRecord( 1314 repository, 1315 'private_sends', 1316 evidence.command 1317 ); 1318 if (!after.ok) return refuse('unknown_completion'); 1319 if ( 1320 after.value.wire !== operation.nextWire || 1321 privateRecordWire( 1322 after.value.handle, 1323 evidence.owner, 1324 evidence.command 1325 ) !== operation.nextWire 1326 ) 1327 return refuse('conflict'); 1328 original.admit(operation.nextRecord, operation.nextWire); 1329 operation.markApplied(); 1330 return nonceSuccess( 1331 operation, 1332 !committed.ok 1333 ? 'reconciled' 1334 : committed.value.state === 'existing' 1335 ? 'existing' 1336 : 'saved' 1337 ); 1338 } 1339 ); 1340 if (!job.ok) return refuse(evidence.current() ? 'busy' : 'stopped'); 1341 if (job.value.acknowledgement && !evidence.current()) 1342 return { 1343 status: job.value.status, 1344 disposition: 'original_protected', 1345 provenance: 'historical_only' 1346 }; 1347 return job.value; 1348 } 1349 ); 1350 } finally { 1351 original.finish(); 1352 } 1353 } catch { 1354 return refuse('unknown_completion'); 1355 } 1356 } 1357 1358 // Local source provenance only. Later cleanup/readiness must independently 1359 // reobserve native custody and all required genuine current target effects. 1360 export function inboxProbeNonceAcknowledgementBinding( 1361 repository: PrivateStorageRepository, 1362 session: PrivateSession, 1363 acknowledgement: InboxProbeNonceAcknowledgement, 1364 policy: RelayPolicy 1365 ) { 1366 const saved = nonceAcknowledgements.get(acknowledgement); 1367 if ( 1368 !saved || 1369 saved.repository !== repository || 1370 saved.session !== session || 1371 saved.policy !== policy || 1372 !saved.applied() || 1373 !currentNonceOperation(saved) 1374 ) 1375 return undefined; 1376 return { 1377 owner: saved.lineage.record().owner, 1378 command: saved.lineage.record().id, 1379 eventId: saved.lineage.record().self!.eventId, 1380 probeAcknowledgement: saved.acknowledgement, 1381 proof: saved.proof, 1382 observation: saved.observation, 1383 record: JSON.parse( 1384 JSON.stringify(saved.lineage.record()) 1385 ) as PrivateAccessProbe, 1386 wire: saved.lineage.wire(), 1387 current: () => currentNonceOperation(saved) 1388 }; 1389 } 1390 1391 declare const cleanupSelectionBrand: unique symbol; 1392 export type InboxProbeCleanupSelection = Readonly<{ 1393 [cleanupSelectionBrand]: true; 1394 }>; 1395 type CleanupSelection = Readonly<{ 1396 repository: PrivateStorageRepository; 1397 session: PrivateSession; 1398 policy: RelayPolicy; 1399 operation: NonceOperation; 1400 access: InboxAccessController; 1401 operator: InboxOperatorQualification; 1402 nonceReadReceipt: string; 1403 admissions(): readonly string[]; 1404 record: PrivateAccessProbe; 1405 wire: string; 1406 current(): boolean; 1407 }>; 1408 const cleanupSelections = new WeakMap< 1409 InboxProbeCleanupSelection, 1410 CleanupSelection 1411 >(); 1412 1413 // A positive label is not an effect. Only exact source results already applied 1414 // to this very Lineage can resolve a historical archive attempt or qualify a 1415 // required target. Array membership does not confer provenance. 1416 export function captureInboxProbeCleanupSelection( 1417 repository: PrivateStorageRepository, 1418 session: PrivateSession, 1419 policy: RelayPolicy, 1420 nonce: InboxProbeNonceAcknowledgement, 1421 observations: unknown, 1422 review: unknown 1423 ): InboxProbeCleanupSelection | undefined { 1424 if ( 1425 typeof window === 'undefined' || 1426 review !== 'reviewed_inbox_probe_cleanup_selection' 1427 ) 1428 return undefined; 1429 try { 1430 const operation = nonceAcknowledgements.get(nonce); 1431 if ( 1432 !operation || 1433 operation.repository !== repository || 1434 operation.session !== session || 1435 operation.policy !== policy || 1436 !operation.applied() || 1437 !currentNonceOperation(operation) 1438 ) 1439 return undefined; 1440 const saved = acknowledgements.get(operation.acknowledgement), 1441 record = operation.lineage.record(), 1442 wire = operation.lineage.wire(); 1443 if (!saved || !record.self || !Array.isArray(observations)) 1444 return undefined; 1445 // Array length does not bound a custom iterator. Inspect only a fixed 1446 // number of own data elements; descriptor traps may invalidate authority, 1447 // so the exact Lineage/nonce/C7 fence below still follows every inspection. 1448 function ownObservation(value: object, name: string): unknown { 1449 const field = Object.getOwnPropertyDescriptor(value, name); 1450 return field && 'value' in field ? field.value : undefined; 1451 } 1452 const length = ownObservation(observations, 'length'); 1453 if ( 1454 typeof length !== 'number' || 1455 !Number.isSafeInteger(length) || 1456 length < 1 || 1457 length > record.receipts.length 1458 ) 1459 return undefined; 1460 const positives = new Map<string, true>(); 1461 for (let index = 0; index < length; index++) { 1462 const value = ownObservation(observations, String(index)); 1463 if ( 1464 !value || 1465 typeof value !== 'object' || 1466 appliedArchiveEvidence.get(value as InboxProbeArchiveAttemptResult) !== 1467 operation.lineage 1468 ) 1469 return undefined; 1470 const effect = 1471 inboxProbeArchiveAttemptEvidence( 1472 value as InboxProbeArchiveAttemptResult 1473 ) ?? 1474 inboxProbeReadbackAttemptEvidence( 1475 value as InboxProbeReadbackAttemptResult 1476 ); 1477 if ( 1478 !effect || 1479 effect.repository !== repository || 1480 acknowledgements.get(effect.acknowledgement)?.lineage !== 1481 operation.lineage 1482 ) 1483 return undefined; 1484 positives.set(effect.receiptWire, true); 1485 } 1486 if (appliedArchiveEvidence.get(operation.observation) !== operation.lineage) 1487 return undefined; 1488 const nonceFact = operation.nextRecord.receipts.at(-1); 1489 if ( 1490 !nonceFact || 1491 nonceFact.status !== 'nonce_verified' || 1492 !record.receipts.some( 1493 (fact) => JSON.stringify(fact) === JSON.stringify(nonceFact) 1494 ) 1495 ) 1496 return undefined; 1497 const accepted = new Map<string, number>(), 1498 unresolved = new Map<string, number>(); 1499 let read = false; 1500 for (const [index, fact] of record.receipts.entries()) { 1501 const key = JSON.stringify([fact.role, fact.origin, fact.eventId]); 1502 if (fact.role === 'access_archive') { 1503 if (fact.status === 'accepted') { 1504 if (positives.has(JSON.stringify(fact))) accepted.set(key, index); 1505 } else unresolved.set(key, index); 1506 } else if ( 1507 fact.status === 'readback' && 1508 positives.has(JSON.stringify(fact)) && 1509 inboxProbeReadbackAttemptEvidence(operation.observation) 1510 ?.receiptWire === JSON.stringify(fact) 1511 ) { 1512 read = true; 1513 } 1514 } 1515 if ( 1516 !read || 1517 record.binding.archiveTargets.some( 1518 (origin) => 1519 !accepted.has( 1520 JSON.stringify(['access_archive', origin, record.self!.eventId]) 1521 ) 1522 ) 1523 ) 1524 return undefined; 1525 for (const [key, index] of unresolved) 1526 if ((accepted.get(key) ?? -1) <= index) return undefined; 1527 const access = 1528 saved.source === 'construction' 1529 ? inboxProbeActionOwner(saved.identity, session, policy) 1530 : saved.access, 1531 scope = access && inboxAccessConstructionBinding(access, session, policy), 1532 operator = 1533 saved.source === 'construction' 1534 ? inboxProbeOperatorBinding( 1535 saved.identity, 1536 repository, 1537 session, 1538 policy 1539 ) 1540 : saved.operator; 1541 if (!access || !scope || !operator) return undefined; 1542 function current() { 1543 return ( 1544 operation!.lineage.active() && 1545 operation!.lineage.wire() === wire && 1546 currentNonceOperation(operation!) && 1547 scope!.current() 1548 ); 1549 } 1550 if (!current()) return undefined; 1551 const token = Object.freeze({}) as InboxProbeCleanupSelection; 1552 cleanupSelections.set(token, { 1553 repository, 1554 session, 1555 policy, 1556 operation, 1557 access, 1558 operator, 1559 nonceReadReceipt: inboxProbeReadbackAttemptEvidence( 1560 operation.observation 1561 )!.receiptWire, 1562 admissions: () => Array.from(positives.keys()), 1563 record: JSON.parse(JSON.stringify(record)) as PrivateAccessProbe, 1564 wire, 1565 current 1566 }); 1567 return token; 1568 } catch { 1569 return undefined; 1570 } 1571 } 1572 1573 export function inboxProbeCleanupSelectionBinding( 1574 token: InboxProbeCleanupSelection, 1575 repository: PrivateStorageRepository, 1576 session: PrivateSession, 1577 policy: RelayPolicy 1578 ) { 1579 const saved = cleanupSelections.get(token); 1580 if ( 1581 !saved || 1582 saved.repository !== repository || 1583 saved.session !== session || 1584 saved.policy !== policy || 1585 !saved.current() 1586 ) 1587 return undefined; 1588 return { 1589 identity: saved.operation.lineage.identity, 1590 source: acknowledgements.get(saved.operation.acknowledgement)!.source, 1591 access: saved.access, 1592 operator: saved.operator, 1593 nonceReadReceipt: saved.nonceReadReceipt, 1594 admissions: saved.admissions, 1595 nonce: saved.operation.acknowledgementToken()!, 1596 record: JSON.parse(JSON.stringify(saved.record)) as PrivateAccessProbe, 1597 wire: saved.wire, 1598 current: saved.current, 1599 begin: () => saved.current() && saved.operation.lineage.begin(), 1600 finish: () => saved.operation.lineage.finish() 1601 }; 1602 } 1603 1604 // Native proof, not an absent ID or decoded row, permits disposal of this exact 1605 // genuine source lineage. No controller is closed and no readiness is granted. 1606 export function retireInboxProbeCleanupSelection( 1607 token: InboxProbeCleanupSelection, 1608 proof: PrivateProbeRemovalProof 1609 ): boolean { 1610 const saved = cleanupSelections.get(token); 1611 if (!saved || !saved.current()) return false; 1612 const removed = privateProbeRemovalEvidence( 1613 proof, 1614 saved.repository, 1615 saved.session 1616 ); 1617 if (!removed || removed.selection !== token || removed.wire !== saved.wire) 1618 return false; 1619 disposeInboxProbeNonceProof( 1620 saved.operation.proof, 1621 saved.repository, 1622 saved.session, 1623 saved.policy 1624 ); 1625 const origin = acknowledgements.get(saved.operation.acknowledgement)!; 1626 if (origin.source === 'construction') stopInboxProbeIdentity(origin.identity); 1627 else 1628 disposeRecoveredInboxProbe( 1629 origin.identity, 1630 saved.repository, 1631 saved.session, 1632 saved.policy 1633 ); 1634 saved.operation.lineage.retire(); 1635 origin.revoke(); 1636 cleanupSelections.delete(token); 1637 return true; 1638 }