private-publisher.ts (46013B)
1 import { 2 inboxProbePublicationBinding, 3 recoveredInboxProbePublicationBinding, 4 verifyInboxProbeAcknowledgement, 5 inboxProbeCleanupSelectionBinding, 6 retireInboxProbeCleanupSelection, 7 appliedInboxProbeArchiveAdmission, 8 type InboxProbeCleanupSelection, 9 type InboxProbeAcknowledgement 10 } from '../persistence/inbox-probes.ts'; 11 import { 12 inboxProbeActionOwner, 13 stopInboxProbeIdentity, 14 type InboxProbeIdentity 15 } from './inbox-access.ts'; 16 import { 17 disposeRecoveredInboxProbe, 18 type RecoveredInboxProbe 19 } from './self-recovery-reader.ts'; 20 import { 21 inboxAccessControllerSnapshot, 22 inboxAccessConstructionBinding, 23 type InboxAccessController 24 } from '../messaging/inbox-access-controller.ts'; 25 import { privatePoolProbeRetryIdle } from './private-pool.ts'; 26 import type { InboxProbeArchiveAttemptResult } from './private-pool.ts'; 27 import { 28 privateSessionOwnership, 29 withIdlePrivateLocalStorage, 30 type PrivateSession 31 } from '../runtime/private-session.ts'; 32 import { 33 pairedDeliveryAcknowledgementSnapshot, 34 pairedDeliveryTargetAccepted, 35 verifyPairedDeliveryAcknowledgement, 36 type PairedDeliveryAcknowledgement 37 } from '../persistence/private-sends.ts'; 38 import { 39 privateProbeRemovalEvidence, 40 type PrivateProbeRemovalProof, 41 type PrivateStorageRepository 42 } from '../persistence/private-storage.ts'; 43 import type { PairedDeliveryContext } from '../messaging/prepare-send.ts'; 44 import type { PrivateAccessProbeReceipt } from '../persistence/private-records.ts'; 45 import { 46 inboxRoutePlanSnapshot, 47 recheckInboxRoutePlan 48 } from '../messaging/inbox-routing.ts'; 49 import { readRelayPolicy, type RelayPolicy } from '../config/relays.ts'; 50 import { 51 PRIVATE_TRANSPORT_BUDGETS, 52 PRIVATE_PUBLICATION_BUDGETS, 53 LOCAL_PERSISTENCE_BUDGETS 54 } from '../config/budgets.ts'; 55 import { newLocalId } from '../private-handles.ts'; 56 import { boundedUtf8 } from '../contracts/food-availability-v1/text.ts'; 57 import { 58 verifyEnvelope, 59 verifiedEnvelopeSnapshot 60 } from './verified-envelope.ts'; 61 declare const publicationBrand: unique symbol; 62 export type PrivatePublication = Readonly<{ [publicationBrand]: true }>; 63 export type PrivateDeliveryRole = 'peer' | 'self_archive'; 64 declare const actionBrand: unique symbol; 65 export type PrivatePublicationAction = Readonly<{ [actionBrand]: true }>; 66 type NetworkAttempt = Readonly<{ 67 actionId: string; 68 attempt: number; 69 remaining(): number; 70 finish(): void; 71 }>; 72 type Action = { 73 session: PrivateSession; 74 receipt: PairedDeliveryAcknowledgement; 75 context: PairedDeliveryContext; 76 current(): boolean; 77 begin( 78 role: PrivateDeliveryRole, 79 origin: string, 80 eventId: string 81 ): NetworkAttempt | undefined; 82 }; 83 const actions = new WeakMap<PrivatePublicationAction, Action>(); 84 function immutablePair(receipt: PairedDeliveryAcknowledgement) { 85 const row = pairedDeliveryAcknowledgementSnapshot(receipt); 86 return ( 87 row && 88 JSON.stringify({ 89 owner: row.owner, 90 id: row.id, 91 peer: row.peer, 92 rumorHash: row.rumorHash, 93 createdAt: row.createdAt, 94 self: row.self, 95 peerArtifact: row.peerArtifact, 96 deliveryPlan: row.deliveryPlan 97 }) 98 ); 99 } 100 // Source-owned meter shared by ordinary actions and the original probe action. 101 // Provider/native custody waits happen before begin; no caller clock or reset. 102 function networkMeter(probe: boolean) { 103 const actionId = newLocalId(); 104 if (!actionId) return undefined; 105 const counts = new Map<string, number>(); 106 // Probe-only causal obligations survive finish and controller replacement. 107 // The existing three origins/three combined attempts bound this map to nine. 108 const pendingArchives = new Map<string, true>(); 109 let admissionGeneration = 0, 110 lastAdmission: string | undefined, 111 lastReadAdmission: string | undefined; 112 let used = 0, 113 running = false, 114 broken = false, 115 last = -1; 116 function clock() { 117 const now = performance.now(); 118 if (!Number.isFinite(now) || now < 0 || now < last) { 119 broken = true; 120 return undefined; 121 } 122 last = now; 123 return now; 124 } 125 return { 126 current: () => !broken, 127 idle: () => !running, 128 archivesApplied: () => pendingArchives.size === 0, 129 generation: () => admissionGeneration, 130 coveredGeneration( 131 nonceReadReceipt: string, 132 receipts: readonly string[] 133 ): number | undefined { 134 if (!probe || !lastAdmission || !lastReadAdmission) return undefined; 135 const read = JSON.parse(nonceReadReceipt) as PrivateAccessProbeReceipt; 136 // A later archive cannot hide a real read without its own nonce proof. 137 // This receipt comes only from the selected nonce's genuine read effect. 138 if ( 139 read.role !== 'access_readback' || 140 JSON.stringify([ 141 read.actionId, 142 read.role, 143 read.origin, 144 read.eventId, 145 read.attempt 146 ]) !== lastReadAdmission 147 ) 148 return undefined; 149 for (const wire of receipts) { 150 const fact = JSON.parse(wire) as PrivateAccessProbeReceipt; 151 if ( 152 JSON.stringify([ 153 fact.actionId, 154 fact.role, 155 fact.origin, 156 fact.eventId, 157 fact.attempt 158 ]) === lastAdmission 159 ) 160 return admissionGeneration; 161 } 162 return undefined; 163 }, 164 applyArchive( 165 action: string, 166 origin: string, 167 eventId: string, 168 attempt: number 169 ) { 170 if (probe && action === actionId) 171 pendingArchives.delete( 172 JSON.stringify([action, origin, eventId, attempt]) 173 ); 174 }, 175 probeAvailable: (origin: string, eventId: string) => 176 probe && 177 !broken && 178 !running && 179 used < PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds && 180 (counts.get(JSON.stringify([origin, eventId])) ?? 0) < 181 PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction, 182 begin( 183 role: PrivateDeliveryRole | 'access_archive' | 'access_readback', 184 origin: string, 185 eventId: string, 186 current: () => boolean 187 ): NetworkAttempt | undefined { 188 if ( 189 broken || 190 !current() || 191 running || 192 used >= PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds 193 ) 194 return undefined; 195 const key = JSON.stringify( 196 probe ? [origin, eventId] : [role, origin, eventId] 197 ), 198 count = counts.get(key) ?? 0; 199 if (count >= PRIVATE_PUBLICATION_BUDGETS.attemptsPerTargetAction) 200 return undefined; 201 const start = clock(); 202 if (start === undefined) return undefined; 203 counts.set(key, count + 1); 204 if (probe) { 205 admissionGeneration++; 206 lastAdmission = JSON.stringify([ 207 actionId, 208 role, 209 origin, 210 eventId, 211 count + 1 212 ]); 213 if (role === 'access_readback') lastReadAdmission = lastAdmission; 214 } 215 if (probe && role === 'access_archive') 216 pendingArchives.set( 217 JSON.stringify([actionId, origin, eventId, count + 1]), 218 true 219 ); 220 running = true; 221 let finished = false; 222 function remaining() { 223 const now = clock(); 224 return finished || now === undefined || !current() 225 ? 0 226 : Math.max( 227 0, 228 PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds - 229 used - 230 (now - start!) 231 ); 232 } 233 return { 234 actionId, 235 attempt: count + 1, 236 remaining, 237 finish() { 238 if (finished) return; 239 const now = clock(); 240 finished = true; 241 running = false; 242 used = 243 now === undefined 244 ? PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds 245 : Math.min( 246 PRIVATE_PUBLICATION_BUDGETS.networkActionMilliseconds, 247 used + now - start 248 ); 249 } 250 }; 251 } 252 }; 253 } 254 // One explicit action has one network meter, including all artifacts/targets. 255 // SDK identity approval and persisted readback happen before an attempt starts. 256 export function capturePrivatePublicationAction( 257 repository: PrivateStorageRepository, 258 session: PrivateSession, 259 receipt: PairedDeliveryAcknowledgement, 260 context: PairedDeliveryContext, 261 review: unknown 262 ): PrivatePublicationAction | undefined { 263 if (review !== 'reviewed_private_retry') return undefined; 264 const row = pairedDeliveryAcknowledgementSnapshot(receipt), 265 original = immutablePair(receipt), 266 ownership = privateSessionOwnership(session); 267 if (!row || !original || !ownership?.current()) return undefined; 268 for (const route of [ 269 row.deliveryPlan.routes.peer, 270 row.deliveryPlan.routes.archive 271 ]) 272 for (const origin of route.targets) { 273 if ( 274 !capturePrivatePublication( 275 repository, 276 session, 277 receipt, 278 context, 279 route.role, 280 origin, 281 'reviewed_private_delivery' 282 ) 283 ) 284 return undefined; 285 } 286 const meter = networkMeter(false); 287 if (!meter) return undefined; 288 function current() { 289 return ( 290 meter!.current() && 291 ownership!.current() && 292 immutablePair(receipt) === original && 293 recheckInboxRoutePlan( 294 context.plan, 295 context.policy, 296 context.own, 297 context.other 298 ) === 'unchanged' 299 ); 300 } 301 const token = Object.freeze({}) as PrivatePublicationAction; 302 actions.set(token, { 303 session, 304 receipt, 305 context, 306 current, 307 begin: (role, origin, eventId) => 308 meter.begin(role, origin, eventId, current) 309 }); 310 return token; 311 } 312 type Admission = { 313 session: PrivateSession; 314 policy: RelayPolicy; 315 owner: string; 316 command: string; 317 role: PrivateDeliveryRole; 318 origin: string; 319 eventId: string; 320 repository: PrivateStorageRepository; 321 receipt: PairedDeliveryAcknowledgement; 322 wire: string; 323 destination: string; 324 current(): boolean; 325 take(): boolean; 326 action?: Action; 327 }; 328 const permissions = new WeakMap<PrivatePublication, Admission>(); 329 // Genuine current local pair custody plus its frozen routes is necessary, but 330 // this capture opens no socket and does not claim recipient delivery. Each 331 // permission is one effect, not arbitrary bytes, retry or rerouting authority. 332 export function capturePrivatePublication( 333 repository: PrivateStorageRepository, 334 session: PrivateSession, 335 receipt: PairedDeliveryAcknowledgement, 336 context: PairedDeliveryContext, 337 role: PrivateDeliveryRole, 338 origin: string, 339 review: unknown, 340 action?: PrivatePublicationAction 341 ): PrivatePublication | undefined { 342 if ( 343 typeof window === 'undefined' || 344 review !== 'reviewed_private_delivery' || 345 (role !== 'peer' && role !== 'self_archive') || 346 typeof origin !== 'string' 347 ) 348 return undefined; 349 try { 350 const ownership = privateSessionOwnership(session), 351 saved = pairedDeliveryAcknowledgementSnapshot(receipt), 352 budget = action && actions.get(action); 353 if ( 354 action && 355 (!budget || 356 budget.session !== session || 357 budget.receipt !== receipt || 358 budget.context !== context || 359 !budget.current()) 360 ) 361 return undefined; 362 if (!ownership || !saved || ownership.owner !== saved.owner) 363 return undefined; 364 const policy = context.policy, 365 plan = context.plan, 366 own = context.own, 367 other = context.other; 368 const routes = inboxRoutePlanSnapshot(plan), 369 manifest = readRelayPolicy(policy); 370 if ( 371 !routes || 372 !manifest.messagingEnabled || 373 saved.deliveryPlan.state !== 'prepared' || 374 JSON.stringify(routes) !== JSON.stringify(saved.deliveryPlan.routes) || 375 recheckInboxRoutePlan(plan, policy, own, other) !== 'unchanged' 376 ) 377 return undefined; 378 const route = role === 'peer' ? routes.peer : routes.archive; 379 const artifact = role === 'peer' ? saved.peerArtifact : saved.self; 380 const destination = role === 'peer' ? saved.peer : saved.owner; 381 if ( 382 route.role !== role || 383 route.author !== destination || 384 !route.targets.includes(origin) || 385 !manifest.inbox.some( 386 ({ origin: allowed, write }) => allowed === origin && write 387 ) || 388 !boundedUtf8(artifact.wire, PRIVATE_TRANSPORT_BUDGETS.envelopeBytes) 389 ) 390 return undefined; 391 const verified = verifyEnvelope(artifact.wire), 392 event = verified.ok && verifiedEnvelopeSnapshot(verified.value); 393 if ( 394 !event || 395 event.kind !== 1059 || 396 event.id !== artifact.eventId || 397 event.tags.length !== 1 || 398 event.tags[0].length !== 2 || 399 event.tags[0][0] !== 'p' || 400 event.tags[0][1] !== destination 401 ) 402 return undefined; 403 const original = JSON.stringify(saved); 404 let consumed = false; 405 function current() { 406 const fresh = pairedDeliveryAcknowledgementSnapshot(receipt), 407 captured = privateSessionOwnership(session); 408 return ( 409 ownership!.current() && 410 captured?.session === ownership!.session && 411 captured.owner === ownership!.owner && 412 !!fresh && 413 JSON.stringify(fresh) === original && 414 recheckInboxRoutePlan(plan, policy, own, other) === 'unchanged' 415 ); 416 } 417 if (!current()) return undefined; 418 const token = Object.freeze({}) as PrivatePublication; 419 permissions.set(token, { 420 session, 421 policy, 422 owner: saved.owner, 423 command: saved.id, 424 role, 425 origin, 426 eventId: event.id, 427 repository, 428 receipt, 429 wire: artifact.wire, 430 destination, 431 current, 432 ...(budget ? { action: budget } : {}), 433 take() { 434 if (consumed) return false; 435 consumed = true; 436 return true; 437 } 438 }); 439 return token; 440 } catch { 441 return undefined; 442 } 443 } 444 export function privatePublicationSnapshot(token: PrivatePublication) { 445 const saved = permissions.get(token); 446 return saved?.current() 447 ? { 448 owner: saved.owner, 449 command: saved.command, 450 role: saved.role, 451 origin: saved.origin, 452 eventId: saved.eventId 453 } 454 : undefined; 455 } 456 // The owned private pool consumes this after fresh SDK identity observation and 457 // under the owner lock. Actual full persisted record readback precedes every 458 // EVENT. A detached valid signature or guessed local ID cannot mint permission. 459 export async function takePrivatePublication( 460 token: PrivatePublication, 461 session: PrivateSession, 462 policy: RelayPolicy, 463 origin: string 464 ) { 465 const saved = permissions.get(token); 466 if ( 467 !saved || 468 saved.session !== session || 469 saved.policy !== policy || 470 saved.origin !== origin || 471 !saved.current() || 472 !saved.take() 473 ) 474 return undefined; 475 try { 476 if ( 477 !(await verifyPairedDeliveryAcknowledgement( 478 saved.repository, 479 saved.receipt 480 )) || 481 !saved.current() 482 ) 483 return undefined; 484 if ( 485 saved.action && 486 pairedDeliveryTargetAccepted( 487 saved.receipt, 488 saved.role, 489 saved.origin, 490 saved.eventId 491 ) 492 ) 493 return undefined; 494 const verified = verifyEnvelope(saved.wire), 495 event = verified.ok && verifiedEnvelopeSnapshot(verified.value); 496 if ( 497 !event || 498 event.kind !== 1059 || 499 event.id !== saved.eventId || 500 event.tags.length !== 1 || 501 event.tags[0].length !== 2 || 502 event.tags[0][0] !== 'p' || 503 event.tags[0][1] !== saved.destination || 504 !saved.current() 505 ) 506 return undefined; 507 return { 508 event, 509 repository: saved.repository, 510 // Frozen original operation/artifact scope for metadata-only settlement. 511 // It survives session loss without becoming new effect permission. 512 pairWire: (() => { 513 const row = pairedDeliveryAcknowledgementSnapshot(saved.receipt)!; 514 return JSON.stringify({ 515 owner: row.owner, 516 id: row.id, 517 peer: row.peer, 518 rumorHash: row.rumorHash, 519 createdAt: row.createdAt, 520 self: row.self, 521 peerArtifact: row.peerArtifact 522 }); 523 })(), 524 current: () => saved.current(), 525 owner: saved.owner, 526 command: saved.command, 527 role: saved.role, 528 origin: saved.origin, 529 eventId: saved.eventId, 530 beginNetwork: () => 531 saved.action 532 ? saved.action.begin(saved.role, saved.origin, saved.eventId) 533 : undefined, 534 networkMetered: !!saved.action 535 }; 536 } catch { 537 return undefined; 538 } 539 } 540 541 declare const probeActionBrand: unique symbol; 542 export type InboxProbePublicationAction = Readonly<{ 543 [probeActionBrand]: true; 544 }>; 545 declare const probePublicationBrand: unique symbol; 546 export type InboxProbePublication = Readonly<{ [probePublicationBrand]: true }>; 547 type ProbeAction = { 548 source: 'construction' | 'recovered'; 549 token: InboxProbePublicationAction; 550 repository: PrivateStorageRepository; 551 session: PrivateSession; 552 policy: RelayPolicy; 553 identity: InboxProbeIdentity | RecoveredInboxProbe; 554 original: string; 555 current(): boolean; 556 meter: NonNullable<ReturnType<typeof networkMeter>>; 557 }; 558 const probeActions = new WeakMap<InboxProbePublicationAction, ProbeAction>(); 559 const identityActions = new WeakMap< 560 InboxProbeIdentity | RecoveredInboxProbe, 561 ProbeAction | null 562 >(); 563 type ProbeMeter = NonNullable<ReturnType<typeof networkMeter>>; 564 type ProbeMeterOwner = { 565 access: InboxAccessController; 566 original: string; 567 meter: ProbeMeter; 568 current(): boolean; 569 held(): boolean; 570 claimIdentity(): symbol; 571 claim(): boolean; 572 release(): void; 573 retain( 574 identity: InboxProbeIdentity | RecoveredInboxProbe, 575 source: ProbeAction['source'], 576 repository: PrivateStorageRepository 577 ): void; 578 dispose(session: PrivateSession, policy: RelayPolicy): void; 579 }; 580 // Bounded within an actual private-session lifetime, never persisted authority. 581 // Retired action replacement reuses the slot; it cannot grow action history. 582 const commandMeters = new WeakMap< 583 PrivateSession, 584 Map<string, ProbeMeterOwner | null> 585 >(); 586 function probeMeter( 587 session: PrivateSession, 588 policy: RelayPolicy, 589 access: InboxAccessController, 590 command: string, 591 original: string, 592 current: () => boolean, 593 replace: boolean 594 ): ProbeMeter | undefined { 595 const registry = 596 commandMeters.get(session) ?? new Map<string, ProbeMeterOwner | null>(); 597 commandMeters.set(session, registry); 598 const previous = registry.get(command); 599 if (registry.has(command)) { 600 if (!previous || previous.original !== original) return undefined; 601 if (previous.access === access) return previous.meter; 602 const retired = inboxAccessControllerSnapshot(previous.access); 603 if ( 604 !replace || 605 previous.current() || 606 previous.held() || 607 !previous.meter.idle() || 608 !previous.meter.archivesApplied() || 609 retired?.state !== 'stopped' || 610 retired.cleanupRequired || 611 !privatePoolProbeRetryIdle(session, policy) || 612 !current() 613 ) 614 return undefined; 615 } else if ( 616 registry.size >= LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 617 ) { 618 return undefined; 619 } 620 // UUID creation can reenter. No parallel original or recovered capture may 621 // allocate another meter while this exact command's slot is reserved. 622 registry.set(command, null); 623 const meter = networkMeter(true); 624 if ( 625 !meter || 626 !current() || 627 (replace && !privatePoolProbeRetryIdle(session, policy)) 628 ) 629 return undefined; 630 let held = false, 631 claimIdentity = Symbol(); 632 // At most one original and one recovered identity per actual controller. 633 // This is the same bounded command entry, never a historical identity list. 634 const identities = new Map< 635 ProbeAction['source'], 636 Readonly<{ 637 identity: InboxProbeIdentity | RecoveredInboxProbe; 638 repository: PrivateStorageRepository; 639 }> 640 >(); 641 registry.set(command, { 642 access, 643 original, 644 meter, 645 current, 646 held: () => held, 647 claimIdentity: () => claimIdentity, 648 claim() { 649 if (held) return false; 650 held = true; 651 claimIdentity = Symbol(); 652 return true; 653 }, 654 release() { 655 held = false; 656 }, 657 retain(identity, source, repository) { 658 identities.set(source, { identity, repository }); 659 }, 660 dispose(session, policy) { 661 for (const [source, saved] of identities) { 662 if (source === 'construction') 663 stopInboxProbeIdentity(saved.identity as InboxProbeIdentity); 664 else 665 disposeRecoveredInboxProbe( 666 saved.identity as RecoveredInboxProbe, 667 saved.repository, 668 session, 669 policy 670 ); 671 } 672 identities.clear(); 673 } 674 }); 675 return meter; 676 } 677 function probeCommandAvailable( 678 session: PrivateSession, 679 command: string, 680 meter: ProbeMeter 681 ) { 682 const saved = commandMeters.get(session)?.get(command); 683 return !!saved && saved.meter === meter && !saved.held(); 684 } 685 686 declare const probeCleanupLeaseBrand: unique symbol; 687 export type InboxProbeCleanupLease = Readonly<{ 688 [probeCleanupLeaseBrand]: true; 689 }>; 690 type CleanupLease = Readonly<{ 691 repository: PrivateStorageRepository; 692 session: PrivateSession; 693 policy: RelayPolicy; 694 selection: InboxProbeCleanupSelection; 695 entry: ProbeMeterOwner; 696 command: string; 697 wire: string; 698 current(): boolean; 699 scopeCurrent(): boolean; 700 retired(): boolean; 701 markRetired(): void; 702 }>; 703 const cleanupLeases = new WeakMap<InboxProbeCleanupLease, CleanupLease>(); 704 705 declare const qualificationFenceBrand: unique symbol; 706 export type InboxProbeQualificationFence = Readonly<{ 707 [qualificationFenceBrand]: true; 708 }>; 709 const qualificationFences = new WeakMap< 710 InboxProbeQualificationFence, 711 Readonly<{ current(): boolean }> 712 >(); 713 type QualifiedRemoval = Readonly<{ 714 repository: PrivateStorageRepository; 715 session: PrivateSession; 716 policy: RelayPolicy; 717 binding: NonNullable<ReturnType<typeof inboxProbeCleanupSelectionBinding>>; 718 scope: NonNullable<ReturnType<typeof inboxAccessConstructionBinding>>; 719 }>; 720 const qualifiedRemovals = new WeakMap< 721 PrivateProbeRemovalProof, 722 QualifiedRemoval 723 >(); 724 725 // Source admissions and their native-applied effects cover this exact command. 726 // Ordinary pool/SDK activity is deliberately absent from issued currentness. 727 function qualificationBinding( 728 repository: PrivateStorageRepository, 729 session: PrivateSession, 730 policy: RelayPolicy, 731 selection: InboxProbeCleanupSelection, 732 lease?: CleanupLease 733 ) { 734 const binding = inboxProbeCleanupSelectionBinding( 735 selection, 736 repository, 737 session, 738 policy 739 ); 740 if (!binding) return undefined; 741 const entry = commandMeters.get(session)?.get(binding.record.id), 742 action = identityActions.get(binding.identity), 743 scope = inboxAccessConstructionBinding(binding.access, session, policy); 744 if ( 745 !entry || 746 !action || 747 !scope || 748 entry.access !== binding.access || 749 action.repository !== repository || 750 action.session !== session || 751 action.policy !== policy || 752 action.meter !== entry.meter || 753 action.original !== entry.original || 754 entry.original !== probeImmutable(binding.record) || 755 entry.held() !== !!lease || 756 (lease && (lease.entry !== entry || lease.selection !== selection)) || 757 !entry.meter.idle() || 758 !entry.meter.archivesApplied() || 759 !entry.meter.current() 760 ) 761 return undefined; 762 const generation = entry.meter.coveredGeneration( 763 binding.nonceReadReceipt, 764 binding.admissions() 765 ); 766 if ( 767 generation === undefined || 768 !binding.current() || 769 !scope.current() || 770 entry.meter.generation() !== generation || 771 commandMeters.get(session)?.get(binding.record.id) !== entry || 772 entry.held() !== !!lease || 773 !entry.meter.idle() || 774 !entry.meter.archivesApplied() 775 ) 776 return undefined; 777 return { binding, entry, scope, generation }; 778 } 779 780 export function captureInboxProbeQualificationFence( 781 repository: PrivateStorageRepository, 782 session: PrivateSession, 783 policy: RelayPolicy, 784 selection: InboxProbeCleanupSelection 785 ): InboxProbeQualificationFence | undefined { 786 try { 787 const captured = qualificationBinding( 788 repository, 789 session, 790 policy, 791 selection 792 ); 793 if (!captured) return undefined; 794 // A real cleanup claim retires this journal fence even if native deletion 795 // later aborts. Release restores cleanup eligibility, never an old proof. 796 const claimIdentity = captured.entry.claimIdentity(); 797 const token = Object.freeze({}) as InboxProbeQualificationFence; 798 qualificationFences.set(token, { 799 current() { 800 const actual = qualificationBinding( 801 repository, 802 session, 803 policy, 804 selection 805 ); 806 return ( 807 !!actual && 808 actual.entry === captured.entry && 809 actual.entry.claimIdentity() === claimIdentity && 810 actual.generation === captured.generation && 811 actual.binding.wire === captured.binding.wire && 812 actual.binding.operator === captured.binding.operator && 813 actual.binding.access === captured.binding.access 814 ); 815 } 816 }); 817 return token; 818 } catch { 819 return undefined; 820 } 821 } 822 export function inboxProbeQualificationFenceCurrent( 823 token: InboxProbeQualificationFence 824 ): boolean { 825 try { 826 return qualificationFences.get(token)?.current() ?? false; 827 } catch { 828 return false; 829 } 830 } 831 832 // Only actual successful native retirement records this optional historical 833 // source coverage. A genuine unqualified cleanup retains its original behavior. 834 export function inboxProbeQualifiedRemovalBinding( 835 proof: PrivateProbeRemovalProof, 836 repository: PrivateStorageRepository, 837 session: PrivateSession, 838 policy: RelayPolicy 839 ) { 840 const saved = qualifiedRemovals.get(proof); 841 return saved?.repository === repository && 842 saved.session === session && 843 saved.policy === policy && 844 saved.scope.current() 845 ? { 846 access: saved.binding.access, 847 operator: saved.binding.operator, 848 wire: saved.binding.wire, 849 current: saved.scope.current 850 } 851 : undefined; 852 } 853 854 // Only genuine native-applied source evidence can discharge an actual charge. 855 // This works after controller loss without creating current network authority. 856 export function reconcileInboxProbeArchiveAdmission( 857 result: InboxProbeArchiveAttemptResult 858 ): void { 859 const applied = appliedInboxProbeArchiveAdmission(result); 860 if (!applied) return; 861 commandMeters 862 .get(applied.session) 863 ?.get(applied.command) 864 ?.meter.applyArchive( 865 applied.actionId, 866 applied.origin, 867 applied.eventId, 868 applied.attempt 869 ); 870 } 871 872 function cleanupLeaseBinding( 873 repository: PrivateStorageRepository, 874 session: PrivateSession, 875 policy: RelayPolicy, 876 selection: InboxProbeCleanupSelection 877 ) { 878 if (typeof window === 'undefined') return undefined; 879 try { 880 const binding = inboxProbeCleanupSelectionBinding( 881 selection, 882 repository, 883 session, 884 policy 885 ); 886 if (!binding) return undefined; 887 const entry = commandMeters.get(session)?.get(binding.record.id), 888 action = identityActions.get(binding.identity), 889 scope = inboxAccessConstructionBinding(binding.access, session, policy); 890 if ( 891 !entry || 892 !action || 893 !scope || 894 entry.access !== binding.access || 895 action.repository !== repository || 896 action.session !== session || 897 action.policy !== policy || 898 action.meter !== entry.meter || 899 action.original !== entry.original || 900 entry.original !== probeImmutable(binding.record) || 901 !entry.meter.idle() || 902 !entry.meter.archivesApplied() || 903 !entry.meter.current() || 904 entry.held() || 905 !binding.current() 906 ) 907 return undefined; 908 function scopeCurrent() { 909 const snapshot = inboxAccessControllerSnapshot(binding!.access); 910 return ( 911 scope!.current() && 912 !!snapshot && 913 !snapshot.busy && 914 !snapshot.cleanupRequired && 915 snapshot.state !== 'stopped' && 916 privatePoolProbeRetryIdle(session, policy) 917 ); 918 } 919 if (!scopeCurrent()) return undefined; 920 return { binding, entry, scopeCurrent }; 921 } catch { 922 return undefined; 923 } 924 } 925 926 // Pure source/resource preflight before any fresh provider request. The lease 927 // repeats admission after the callback-capable provider wait and native reads. 928 export function inboxProbeCleanupReady( 929 repository: PrivateStorageRepository, 930 session: PrivateSession, 931 policy: RelayPolicy, 932 selection: InboxProbeCleanupSelection 933 ): boolean { 934 return !!cleanupLeaseBinding(repository, session, policy, selection); 935 } 936 937 export function acquireInboxProbeCleanupLease( 938 repository: PrivateStorageRepository, 939 session: PrivateSession, 940 policy: RelayPolicy, 941 selection: InboxProbeCleanupSelection 942 ): InboxProbeCleanupLease | undefined { 943 try { 944 const selected = cleanupLeaseBinding( 945 repository, 946 session, 947 policy, 948 selection 949 ); 950 if (!selected || !selected.entry.claim()) return undefined; 951 const { binding, entry, scopeCurrent } = selected; 952 let retired = false; 953 const token = Object.freeze({}) as InboxProbeCleanupLease; 954 cleanupLeases.set(token, { 955 repository, 956 session, 957 policy, 958 selection, 959 entry, 960 command: binding.record.id, 961 wire: binding.wire, 962 scopeCurrent, 963 current: () => 964 !retired && 965 commandMeters.get(session)?.get(binding.record.id) === entry && 966 entry.held() && 967 entry.meter.idle() && 968 entry.meter.archivesApplied() && 969 entry.meter.current() && 970 binding.current() && 971 scopeCurrent(), 972 retired: () => retired, 973 markRetired() { 974 retired = true; 975 } 976 }); 977 return token; 978 } catch { 979 return undefined; 980 } 981 } 982 export function inboxProbeCleanupLeaseCurrent( 983 lease: InboxProbeCleanupLease 984 ): boolean { 985 return cleanupLeases.get(lease)?.current() ?? false; 986 } 987 export function releaseInboxProbeCleanupLease( 988 lease: InboxProbeCleanupLease 989 ): void { 990 const saved = cleanupLeases.get(lease); 991 if ( 992 saved && 993 !saved.retired() && 994 commandMeters.get(saved.session)?.get(saved.command) === saved.entry 995 ) { 996 saved.entry.release(); 997 cleanupLeases.delete(lease); 998 } 999 } 1000 export function retireInboxProbeCleanupLease( 1001 lease: InboxProbeCleanupLease, 1002 proof: PrivateProbeRemovalProof 1003 ): boolean { 1004 const saved = cleanupLeases.get(lease); 1005 if (!saved?.current()) return false; 1006 const removed = privateProbeRemovalEvidence( 1007 proof, 1008 saved.repository, 1009 saved.session 1010 ); 1011 if ( 1012 !removed || 1013 removed.selection !== saved.selection || 1014 removed.wire !== saved.wire || 1015 removed.id !== saved.command || 1016 !saved.current() 1017 ) 1018 return false; 1019 const coverage = qualificationBinding( 1020 saved.repository, 1021 saved.session, 1022 saved.policy, 1023 saved.selection, 1024 saved 1025 ); 1026 if (!retireInboxProbeCleanupSelection(saved.selection, proof)) return false; 1027 saved.entry.dispose(saved.session, saved.policy); 1028 // Deliberate nonce disposal invalidates old ACKs, not this actual C7 scope. 1029 // Loss during disposal cannot free a protected slot or mint current success. 1030 if ( 1031 !saved.scopeCurrent() || 1032 !saved.entry.meter.idle() || 1033 !saved.entry.meter.archivesApplied() || 1034 commandMeters.get(saved.session)?.get(saved.command) !== saved.entry 1035 ) 1036 return false; 1037 commandMeters.get(saved.session)!.delete(saved.command); 1038 if (coverage && coverage.entry.meter.generation() === coverage.generation) 1039 qualifiedRemovals.set(proof, { 1040 repository: saved.repository, 1041 session: saved.session, 1042 policy: saved.policy, 1043 binding: coverage.binding, 1044 scope: coverage.scope 1045 }); 1046 saved.markRetired(); 1047 cleanupLeases.delete(lease); 1048 return true; 1049 } 1050 function probeImmutable( 1051 row: NonNullable<ReturnType<typeof inboxProbePublicationBinding>>['record'] 1052 ) { 1053 return JSON.stringify({ 1054 owner: row.owner, 1055 id: row.id, 1056 rumorHash: row.rumorHash, 1057 createdAt: row.createdAt, 1058 binding: row.binding, 1059 self: row.self 1060 }); 1061 } 1062 export function captureInboxProbePublicationAction( 1063 repository: PrivateStorageRepository, 1064 session: PrivateSession, 1065 policy: RelayPolicy, 1066 acknowledgement: InboxProbeAcknowledgement, 1067 review: unknown 1068 ): InboxProbePublicationAction | undefined { 1069 if ( 1070 typeof window === 'undefined' || 1071 review !== 'reviewed_inbox_probe_network' 1072 ) 1073 return undefined; 1074 try { 1075 const binding = inboxProbePublicationBinding( 1076 repository, 1077 session, 1078 acknowledgement, 1079 policy 1080 ); 1081 if (!binding || !binding.record.self) return undefined; 1082 const access = inboxProbeActionOwner(binding.identity, session, policy); 1083 if (!access || !binding.current()) return undefined; 1084 const original = probeImmutable(binding.record), 1085 prior = identityActions.get(binding.identity); 1086 if (identityActions.has(binding.identity)) 1087 return prior && 1088 prior.repository === repository && 1089 prior.session === session && 1090 prior.policy === policy && 1091 prior.original === original && 1092 prior.current() 1093 ? prior.token 1094 : undefined; 1095 // Reserve this original identity before callback-capable UUID creation. 1096 // Reentrant capture refuses; failed admission never grants a new meter. 1097 identityActions.set(binding.identity, null); 1098 const meter = probeMeter( 1099 session, 1100 policy, 1101 access, 1102 binding.record.id, 1103 original, 1104 binding.current, 1105 false 1106 ); 1107 if (!meter || !binding.current()) return undefined; 1108 const token = Object.freeze({}) as InboxProbePublicationAction; 1109 const captured: ProbeAction = { 1110 source: 'construction', 1111 token, 1112 repository, 1113 session, 1114 policy, 1115 identity: binding.identity, 1116 original, 1117 current: () => 1118 meter.current() && 1119 binding.current() && 1120 probeCommandAvailable(session, binding.record.id, meter), 1121 meter 1122 }; 1123 identityActions.set(binding.identity, captured); 1124 probeActions.set(token, captured); 1125 commandMeters 1126 .get(session) 1127 ?.get(binding.record.id) 1128 ?.retain(binding.identity, 'construction', repository); 1129 return token; 1130 } catch { 1131 return undefined; 1132 } 1133 } 1134 1135 // Fresh deliberate Retry adopts the same ciphertext, not a construction 1136 // identity. Admission is local readonly work; EVENT/REQ need later permissions. 1137 export async function captureRecoveredInboxProbeRetryAction( 1138 repository: PrivateStorageRepository, 1139 session: PrivateSession, 1140 policy: RelayPolicy, 1141 acknowledgement: InboxProbeAcknowledgement, 1142 review: unknown 1143 ): Promise<InboxProbePublicationAction | undefined> { 1144 if ( 1145 typeof window === 'undefined' || 1146 review !== 'reviewed_original_inbox_probe_retry' 1147 ) 1148 return undefined; 1149 let identity: RecoveredInboxProbe | undefined, 1150 retryBusy = false; 1151 try { 1152 const binding = recoveredInboxProbePublicationBinding( 1153 repository, 1154 session, 1155 acknowledgement, 1156 policy 1157 ); 1158 if (!binding || !binding.record.self) return undefined; 1159 identity = binding.identity; 1160 const original = probeImmutable(binding.record), 1161 previous = identityActions.get(identity); 1162 if (identityActions.has(identity)) 1163 return previous && 1164 previous.repository === repository && 1165 previous.session === session && 1166 previous.policy === policy && 1167 previous.original === original && 1168 previous.current() 1169 ? previous.token 1170 : undefined; 1171 identityActions.set(identity, null); 1172 if (!navigator.locks?.request) return undefined; 1173 const result = await navigator.locks.request( 1174 'harvestcircle:owner:' + binding.record.owner, 1175 { mode: 'exclusive', ifAvailable: true }, 1176 async (lock) => { 1177 if (!lock) { 1178 retryBusy = true; 1179 return undefined; 1180 } 1181 if (!binding.current()) return undefined; 1182 const idle = await withIdlePrivateLocalStorage(session, async () => { 1183 if (!binding.current()) return undefined; 1184 if (!privatePoolProbeRetryIdle(session, policy)) { 1185 retryBusy = true; 1186 return undefined; 1187 } 1188 if ( 1189 !(await verifyInboxProbeAcknowledgement( 1190 repository, 1191 session, 1192 acknowledgement 1193 )) || 1194 !binding.current() || 1195 !privatePoolProbeRetryIdle(session, policy) 1196 ) 1197 return undefined; 1198 const meter = probeMeter( 1199 session, 1200 policy, 1201 binding.access, 1202 binding.record.id, 1203 original, 1204 binding.current, 1205 true 1206 ); 1207 // UUID/currentness callbacks finish before separate final native 1208 // custody observation. A failed admission cannot mint a permission. 1209 if ( 1210 !meter || 1211 ![ 1212 ...binding.record.binding.archiveTargets, 1213 ...binding.record.binding.readTargets 1214 ].some((origin) => 1215 meter.probeAvailable(origin, binding.record.self!.eventId) 1216 ) || 1217 !(await verifyInboxProbeAcknowledgement( 1218 repository, 1219 session, 1220 acknowledgement 1221 )) || 1222 !binding.current() || 1223 !privatePoolProbeRetryIdle(session, policy) 1224 ) 1225 return undefined; 1226 const token = Object.freeze({}) as InboxProbePublicationAction; 1227 const captured: ProbeAction = { 1228 source: 'recovered', 1229 token, 1230 repository, 1231 session, 1232 policy, 1233 identity: binding.identity, 1234 original, 1235 current: () => 1236 meter.current() && 1237 binding.current() && 1238 probeCommandAvailable(session, binding.record.id, meter), 1239 meter 1240 }; 1241 identityActions.set(binding.identity, captured); 1242 probeActions.set(token, captured); 1243 commandMeters 1244 .get(session) 1245 ?.get(binding.record.id) 1246 ?.retain(binding.identity, 'recovered', repository); 1247 return token; 1248 }); 1249 if (!idle.ok) retryBusy = true; 1250 return idle.ok ? idle.value : undefined; 1251 } 1252 ); 1253 return result; 1254 } catch { 1255 return undefined; 1256 } finally { 1257 // Only actual pre-admission busy can explicitly retry this same proof. 1258 if (retryBusy && identity && identityActions.get(identity) === null) 1259 identityActions.delete(identity); 1260 } 1261 } 1262 type ProbePermission = { 1263 role: 'access_archive' | 'access_readback'; 1264 action: ProbeAction; 1265 acknowledgement: InboxProbeAcknowledgement; 1266 wire: string; 1267 predecessorWire: string; 1268 owner: string; 1269 command: string; 1270 origin: string; 1271 eventId: string; 1272 current(): boolean; 1273 take(): boolean; 1274 }; 1275 const probePermissions = new WeakMap<InboxProbePublication, ProbePermission>(); 1276 declare const probeReadbackBrand: unique symbol; 1277 export type InboxProbeReadback = Readonly<{ [probeReadbackBrand]: true }>; 1278 const probeReadbacks = new WeakMap<InboxProbeReadback, ProbePermission>(); 1279 function captureProbePermission( 1280 repository: PrivateStorageRepository, 1281 session: PrivateSession, 1282 policy: RelayPolicy, 1283 acknowledgement: InboxProbeAcknowledgement, 1284 action: InboxProbePublicationAction, 1285 origin: string, 1286 role: ProbePermission['role'] 1287 ): ProbePermission | undefined { 1288 if ( 1289 typeof window === 'undefined' || 1290 (role !== 'access_archive' && role !== 'access_readback') 1291 ) 1292 return undefined; 1293 try { 1294 const captured = probeActions.get(action), 1295 bind = 1296 captured?.source === 'recovered' 1297 ? recoveredInboxProbePublicationBinding 1298 : inboxProbePublicationBinding, 1299 binding = bind(repository, session, acknowledgement, policy); 1300 if ( 1301 !captured || 1302 !binding || 1303 captured.repository !== repository || 1304 captured.session !== session || 1305 captured.policy !== policy || 1306 captured.identity !== binding.identity || 1307 !captured.current() || 1308 captured.original !== probeImmutable(binding.record) || 1309 !binding.record.self || 1310 (captured.source === 'recovered' && 1311 !captured.meter.probeAvailable(origin, binding.record.self.eventId)) || 1312 !( 1313 role === 'access_archive' 1314 ? binding.record.binding.archiveTargets 1315 : binding.record.binding.readTargets 1316 ).includes(origin) 1317 ) 1318 return undefined; 1319 if ( 1320 !readRelayPolicy(policy).inbox.some( 1321 ({ origin: allowed, read, write }) => 1322 allowed === origin && (role === 'access_archive' ? write : read) 1323 ) 1324 ) 1325 return undefined; 1326 const artifact = binding.record.self, 1327 verified = verifyEnvelope(artifact.wire), 1328 event = verified.ok && verifiedEnvelopeSnapshot(verified.value); 1329 if ( 1330 !event || 1331 event.kind !== 1059 || 1332 event.id !== artifact.eventId || 1333 JSON.stringify(event.tags) !== 1334 JSON.stringify([['p', binding.record.owner]]) 1335 ) 1336 return undefined; 1337 const predecessorWire = binding.wire; 1338 let consumed = false; 1339 function current() { 1340 const fresh = bind(repository, session, acknowledgement, policy); 1341 return ( 1342 captured!.current() && 1343 !!fresh && 1344 (captured!.source !== 'recovered' || 1345 consumed || 1346 captured!.meter.probeAvailable(origin, artifact.eventId)) && 1347 fresh.identity === captured!.identity && 1348 fresh.wire === predecessorWire && 1349 probeImmutable(fresh.record) === captured!.original 1350 ); 1351 } 1352 return { 1353 role, 1354 action: captured, 1355 acknowledgement, 1356 wire: artifact.wire, 1357 predecessorWire, 1358 owner: binding.record.owner, 1359 command: binding.record.id, 1360 origin, 1361 eventId: event.id, 1362 current, 1363 take() { 1364 if (consumed) return false; 1365 consumed = true; 1366 return true; 1367 } 1368 }; 1369 } catch { 1370 return undefined; 1371 } 1372 } 1373 export function captureInboxProbePublication( 1374 repository: PrivateStorageRepository, 1375 session: PrivateSession, 1376 policy: RelayPolicy, 1377 acknowledgement: InboxProbeAcknowledgement, 1378 action: InboxProbePublicationAction, 1379 origin: string, 1380 review: unknown 1381 ): InboxProbePublication | undefined { 1382 if (review !== 'reviewed_inbox_probe_publication') return undefined; 1383 const saved = captureProbePermission( 1384 repository, 1385 session, 1386 policy, 1387 acknowledgement, 1388 action, 1389 origin, 1390 'access_archive' 1391 ); 1392 if (!saved) return undefined; 1393 const token = Object.freeze({}) as InboxProbePublication; 1394 probePermissions.set(token, saved); 1395 return token; 1396 } 1397 export function captureInboxProbeReadback( 1398 repository: PrivateStorageRepository, 1399 session: PrivateSession, 1400 policy: RelayPolicy, 1401 acknowledgement: InboxProbeAcknowledgement, 1402 action: InboxProbePublicationAction, 1403 origin: string, 1404 review: unknown 1405 ): InboxProbeReadback | undefined { 1406 if (review !== 'reviewed_inbox_probe_readback') return undefined; 1407 const saved = captureProbePermission( 1408 repository, 1409 session, 1410 policy, 1411 acknowledgement, 1412 action, 1413 origin, 1414 'access_readback' 1415 ); 1416 if (!saved) return undefined; 1417 const token = Object.freeze({}) as InboxProbeReadback; 1418 probeReadbacks.set(token, saved); 1419 return token; 1420 } 1421 export function inboxProbeReadbackSnapshot(permission: InboxProbeReadback) { 1422 const saved = probeReadbacks.get(permission); 1423 return saved?.current() 1424 ? { 1425 owner: saved.owner, 1426 command: saved.command, 1427 role: 'access_readback' as const, 1428 origin: saved.origin, 1429 eventId: saved.eventId 1430 } 1431 : undefined; 1432 } 1433 export function inboxProbePublicationSnapshot( 1434 permission: InboxProbePublication 1435 ) { 1436 const saved = probePermissions.get(permission); 1437 return saved?.current() 1438 ? { 1439 owner: saved.owner, 1440 command: saved.command, 1441 role: 'access_archive' as const, 1442 origin: saved.origin, 1443 eventId: saved.eventId 1444 } 1445 : undefined; 1446 } 1447 async function takeProbePermission( 1448 saved: ProbePermission | undefined, 1449 session: PrivateSession, 1450 policy: RelayPolicy, 1451 origin: string 1452 ) { 1453 if ( 1454 !saved || 1455 saved.action.session !== session || 1456 saved.action.policy !== policy || 1457 saved.origin !== origin || 1458 !saved.current() || 1459 !saved.take() 1460 ) 1461 return undefined; 1462 if ( 1463 !(await verifyInboxProbeAcknowledgement( 1464 saved.action.repository, 1465 session, 1466 saved.acknowledgement 1467 )) || 1468 !saved.current() 1469 ) 1470 return undefined; 1471 const verified = verifyEnvelope(saved.wire), 1472 event = verified.ok && verifiedEnvelopeSnapshot(verified.value); 1473 if ( 1474 !event || 1475 event.kind !== 1059 || 1476 event.id !== saved.eventId || 1477 JSON.stringify(event.tags) !== JSON.stringify([['p', saved.owner]]) || 1478 !saved.current() 1479 ) 1480 return undefined; 1481 return { 1482 event, 1483 repository: saved.action.repository, 1484 acknowledgement: saved.acknowledgement, 1485 predecessorWire: saved.predecessorWire, 1486 current: () => saved.current(), 1487 owner: saved.owner, 1488 command: saved.command, 1489 role: saved.role, 1490 origin, 1491 eventId: saved.eventId, 1492 networkMetered: true, 1493 beginNetwork: () => 1494 saved.action.meter.begin(saved.role, origin, saved.eventId, () => 1495 saved.current() 1496 ) 1497 }; 1498 } 1499 1500 export async function takeInboxProbePublication( 1501 permission: InboxProbePublication, 1502 session: PrivateSession, 1503 policy: RelayPolicy, 1504 origin: string 1505 ) { 1506 const admitted = await takeProbePermission( 1507 probePermissions.get(permission), 1508 session, 1509 policy, 1510 origin 1511 ); 1512 return admitted && { ...admitted, role: 'access_archive' as const }; 1513 } 1514 export async function takeInboxProbeReadback( 1515 permission: InboxProbeReadback, 1516 session: PrivateSession, 1517 policy: RelayPolicy, 1518 origin: string 1519 ) { 1520 const admitted = await takeProbePermission( 1521 probeReadbacks.get(permission), 1522 session, 1523 policy, 1524 origin 1525 ); 1526 return admitted && { ...admitted, role: 'access_readback' as const }; 1527 }