private-storage.ts (31355B)
1 import { 2 privateSessionOwnership, 3 subscribePrivateSessionClose, 4 type PrivateSession 5 } from '../runtime/private-session.ts'; 6 import { canonicalPublicKey } from '../contracts/public-key.ts'; 7 import { exactLocalFields } from '../contracts/local-records.ts'; 8 import { LOCAL_PERSISTENCE_BUDGETS, RELAY_BUDGETS } from '../config/budgets.ts'; 9 import { privateRecordSettlement } from './local-inventory.ts'; 10 import { 11 inboxProbeCleanupAdmission, 12 type InboxProbeNativeCleanup 13 } from './inbox-probe-cleanup.ts'; 14 import type { InboxProbeCleanupSelection } from './inbox-probes.ts'; 15 import { 16 browserDatabaseState, 17 browserDatabaseTransaction, 18 type BrowserDatabase 19 } from './database.ts'; 20 import { 21 decodePrivateRecord, 22 privateRecordIdentity, 23 privateRecordSnapshot, 24 privateRecordWire, 25 type PrivateRecordHandle, 26 type PrivateRecord 27 } from './private-records.ts'; 28 declare const repositoryBrand: unique symbol; 29 export type PrivateStorageRepository = Readonly<{ [repositoryBrand]: true }>; 30 export type PrivateStorageFailure = 31 | 'invalid_scope' 32 | 'invalid_record' 33 | 'conflict' 34 | 'capacity' 35 | 'corrupt_record' 36 | 'unavailable' 37 | 'aborted' 38 | 'unknown_completion'; 39 export type PrivateStorageResult<T> = 40 | Readonly<{ ok: true; value: T }> 41 | Readonly<{ ok: false; reason: PrivateStorageFailure }>; 42 type Store = 'private_sends' | 'received_envelopes'; 43 type Scope = Readonly<{ database: BrowserDatabase; owner: string }>; 44 type Row = Readonly<{ 45 store: Store; 46 record: PrivateRecord; 47 handle: PrivateRecordHandle; 48 wire: string; 49 bytes: number; 50 }>; 51 const repositories = new WeakMap<PrivateStorageRepository, Scope>(); 52 declare const probeRemovalBrand: unique symbol; 53 export type PrivateProbeRemovalProof = Readonly<{ [probeRemovalBrand]: true }>; 54 const probeRemovals = new WeakMap< 55 PrivateProbeRemovalProof, 56 Readonly<{ 57 repository: PrivateStorageRepository; 58 session: PrivateSession; 59 selection: InboxProbeCleanupSelection; 60 owner: string; 61 id: string; 62 wire: string; 63 }> 64 >(); 65 export function privateProbeRemovalEvidence( 66 proof: PrivateProbeRemovalProof, 67 repository: PrivateStorageRepository, 68 session: PrivateSession 69 ) { 70 const saved = probeRemovals.get(proof); 71 return saved?.repository === repository && saved.session === session 72 ? { 73 selection: saved.selection, 74 owner: saved.owner, 75 id: saved.id, 76 wire: saved.wire 77 } 78 : undefined; 79 } 80 type ValidatedWire = Readonly<{ 81 wire: string; 82 handle: PrivateRecordHandle; 83 bytes: number; 84 }>; 85 type ValidationState = Readonly<{ 86 entries: Map<string, ValidatedWire>; 87 bytes: number; 88 }>; 89 // Ephemeral ciphertext proofs belong to the genuine repository scope. Every 90 // operation still visits every native owner row and checks all keys/headers and 91 // quotas. Neither persisted summaries nor cached count/absence is trusted. 92 const validations = new WeakMap< 93 Scope, 94 Readonly<Record<Store, ValidationState>> 95 >(); 96 function remember( 97 scope: Scope, 98 store: Store, 99 id: string, 100 value: ValidatedWire 101 ): void { 102 const countCap = 103 store === 'private_sends' 104 ? LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 105 : LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes, 106 byteCap = 107 store === 'private_sends' 108 ? LOCAL_PERSISTENCE_BUDGETS.privateSendBytes 109 : LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes; 110 if (value.bytes > byteCap) return; 111 const stores = validations.get(scope) ?? { 112 private_sends: { entries: new Map<string, ValidatedWire>(), bytes: 0 }, 113 received_envelopes: { 114 entries: new Map<string, ValidatedWire>(), 115 bytes: 0 116 } 117 }, 118 state = stores[store], 119 entries = state.entries; 120 let bytes = state.bytes; 121 const old = entries.get(id); 122 if (old) { 123 entries.delete(id); 124 bytes -= old.bytes; 125 } 126 while (entries.size >= countCap || bytes + value.bytes > byteCap) { 127 const first = entries.keys().next().value; 128 if (first === undefined) break; 129 bytes -= entries.get(first)!.bytes; 130 entries.delete(first); 131 } 132 entries.set(id, value); 133 validations.set(scope, { 134 ...stores, 135 [store]: { entries, bytes: bytes + value.bytes } 136 }); 137 } 138 139 const failed = ( 140 reason: PrivateStorageFailure 141 ): PrivateStorageResult<never> => ({ ok: false, reason }); 142 function scopeOf(repository: PrivateStorageRepository): Scope | undefined { 143 const scope = repositories.get(repository); 144 try { 145 if (scope && browserDatabaseState(scope.database).state === 'ready') 146 return scope; 147 if (scope) validations.delete(scope); 148 return undefined; 149 } catch { 150 return undefined; 151 } 152 } 153 // Namespace only, not installed-account or cryptographic/effect permission. 154 export function createPrivateStorageRepository( 155 database: BrowserDatabase, 156 expectedOwner: unknown 157 ): PrivateStorageRepository | undefined { 158 const owner = canonicalPublicKey(expectedOwner); 159 try { 160 if (!owner || browserDatabaseState(database).state !== 'ready') 161 return undefined; 162 const token = Object.freeze({}) as PrivateStorageRepository; 163 repositories.set(token, { database, owner }); 164 return token; 165 } catch { 166 return undefined; 167 } 168 } 169 export function privateStorageOwner( 170 repository: PrivateStorageRepository 171 ): string | undefined { 172 return scopeOf(repository)?.owner; 173 } 174 function stored( 175 scope: Scope, 176 value: unknown, 177 store: Store, 178 owner: string, 179 id: unknown 180 ): Row | undefined { 181 if ( 182 !exactLocalFields(value, ['owner', 'id', 'wire']) || 183 value.owner !== owner || 184 value.id !== id || 185 typeof value.wire !== 'string' || 186 typeof id !== 'string' 187 ) 188 return undefined; 189 const cached = validations.get(scope)?.[store].entries.get(id); 190 const decoded = 191 cached?.wire === value.wire 192 ? { ok: true as const, value: cached.handle } 193 : decodePrivateRecord(value.wire, owner, id); 194 if (!decoded.ok) return undefined; 195 const record = privateRecordSnapshot(decoded.value, owner, id); 196 if ( 197 !record || 198 (record.family === 'received_envelope') !== (store === 'received_envelopes') 199 ) 200 return undefined; 201 // Equal original wire plus the three exact validated header fields fixes the 202 // encoded row length; property ordering does not change that length. 203 const bytes = 204 cached?.wire === value.wire 205 ? cached.bytes 206 : new TextEncoder().encode(JSON.stringify(value)).length; 207 if (cached?.wire !== value.wire) 208 remember(scope, store, id, { 209 wire: value.wire, 210 handle: decoded.value, 211 bytes 212 }); 213 return { store, record, handle: decoded.value, wire: value.wire, bytes }; 214 } 215 // Each store has an independent owner-scoped scan/quota. A corrupt received 216 // namespace cannot reset or consume the outbox, and no uncertain row is evicted. 217 function transaction<T>( 218 scope: Scope, 219 store: Store, 220 mode: 'readonly' | 'readwrite', 221 finish: ( 222 rows: readonly Row[], 223 tx: IDBTransaction, 224 refuse: (reason: PrivateStorageFailure) => void 225 ) => PrivateStorageResult<T> | undefined, 226 watch?: (refuse: (reason: PrivateStorageFailure) => void) => () => void 227 ): Promise<PrivateStorageResult<T>> { 228 let tx: IDBTransaction; 229 try { 230 tx = browserDatabaseTransaction(scope.database, [store], mode); 231 } catch { 232 return Promise.resolve(failed('unavailable')); 233 } 234 const countCap = 235 store === 'private_sends' 236 ? LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 237 : LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes; 238 const byteCap = 239 store === 'private_sends' 240 ? LOCAL_PERSISTENCE_BUDGETS.privateSendBytes 241 : LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes; 242 return new Promise((resolve) => { 243 let result: PrivateStorageResult<T> | undefined, 244 bytes = 0; 245 const rows = new Map<number, Row>(); 246 function refuse(reason: PrivateStorageFailure) { 247 if (result && !result.ok) return; 248 result = failed(reason); 249 try { 250 tx.abort(); 251 } catch { 252 result = failed('unknown_completion'); 253 } 254 } 255 let off = () => {}; 256 tx.addEventListener('complete', () => { 257 off(); 258 resolve(result ?? failed('unknown_completion')); 259 }); 260 tx.addEventListener('abort', () => { 261 off(); 262 // Actual native abort confirms rollback even if another abort call raced. 263 resolve( 264 result && !result.ok && result.reason !== 'unknown_completion' 265 ? result 266 : failed('aborted') 267 ); 268 }); 269 if (watch) { 270 try { 271 off = watch(refuse); 272 } catch { 273 refuse('unavailable'); 274 return; 275 } 276 } 277 try { 278 const cursorRequest = tx 279 .objectStore(store) 280 .index('by_owner') 281 .openCursor(IDBKeyRange.only(scope.owner)); 282 cursorRequest.addEventListener('success', () => { 283 try { 284 const cursor = cursorRequest.result; 285 if (!cursor) { 286 const outcome = finish(Array.from(rows.values()), tx, refuse); 287 if (outcome) result = outcome; 288 return; 289 } 290 const key = cursor.primaryKey; 291 const row = 292 Array.isArray(key) && key.length === 2 && key[0] === scope.owner 293 ? stored(scope, cursor.value, store, scope.owner, key[1]) 294 : undefined; 295 if (!row) { 296 refuse('corrupt_record'); 297 return; 298 } 299 rows.set(rows.size, row); 300 bytes += row.bytes; 301 if (rows.size > countCap || bytes > byteCap) { 302 refuse('capacity'); 303 return; 304 } 305 cursor.continue(); 306 } catch { 307 refuse('aborted'); 308 } 309 }); 310 } catch { 311 refuse('aborted'); 312 } 313 }); 314 } 315 function validTransition( 316 base: PrivateRecord | undefined, 317 next: PrivateRecord 318 ): boolean { 319 if (!base) 320 return ( 321 next.revision === 0 && 322 ((next.family === 'received_envelope' && next.read === null) || 323 (next.family === 'private_access_probe' && 324 next.self === null && 325 next.receipts.length === 0)) 326 ); 327 if ( 328 base.owner !== next.owner || 329 base.id !== next.id || 330 next.revision !== base.revision + 1 331 ) 332 return false; 333 if (base.family === 'received_envelope') { 334 return ( 335 next.family === base.family && 336 base.outer === next.outer && 337 base.observedAtMilliseconds === next.observedAtMilliseconds && 338 base.sources.every((source) => next.sources.includes(source)) 339 ); 340 } 341 if (base.family === 'private_access_probe') 342 return ( 343 next.family === base.family && 344 next.rumorHash === base.rumorHash && 345 next.createdAt === base.createdAt && 346 JSON.stringify(next.binding) === JSON.stringify(base.binding) && 347 (base.self === null || 348 JSON.stringify(base.self) === JSON.stringify(next.self)) && 349 base.receipts.every( 350 (fact, index) => 351 JSON.stringify(fact) === JSON.stringify(next.receipts[index]) 352 ) 353 ); 354 if ( 355 next.family !== 'private_send_operation' || 356 base.peer !== next.peer || 357 base.rumorHash !== next.rumorHash || 358 base.createdAt !== next.createdAt 359 ) 360 return false; 361 return ( 362 base.family === 'private_send_reservation' || 363 (JSON.stringify(base.self) === JSON.stringify(next.self) && 364 (base.deliveryPlan === undefined || 365 JSON.stringify(base.deliveryPlan) === 366 JSON.stringify(next.deliveryPlan) || 367 (!!next.deliveryPlan && 368 JSON.stringify(base.deliveryPlan.routes) !== 369 JSON.stringify(next.deliveryPlan.routes) && 370 JSON.stringify(next.deliveryPlan.previousRoutes) === 371 JSON.stringify([ 372 ...(base.deliveryPlan.previousRoutes ?? []), 373 base.deliveryPlan.routes 374 ]))) && 375 (base.receipts ?? []).every( 376 (fact, index) => 377 JSON.stringify(fact) === JSON.stringify(next.receipts?.[index]) 378 ) && 379 (base.peerArtifact === null || 380 JSON.stringify(base.peerArtifact) === 381 JSON.stringify(next.peerArtifact))) 382 ); 383 } 384 // Local ciphertext CAS only. Factory/identity/read authorization and genuine 385 // durable preparation receipts belong to their workflows. No network or signer 386 // await can occur inside this transaction, and request success grants no credit. 387 export function commitPrivateRecord( 388 repository: PrivateStorageRepository, 389 handle: PrivateRecordHandle, 390 expectedBase: PrivateRecordHandle | null 391 ): Promise< 392 PrivateStorageResult< 393 Readonly<{ id: string; revision: number; state: 'committed' | 'existing' }> 394 > 395 > { 396 const scope = scopeOf(repository), 397 identity = privateRecordIdentity(handle); 398 if (!scope) return Promise.resolve(failed('invalid_scope')); 399 const next = 400 identity && privateRecordSnapshot(handle, scope.owner, identity.id), 401 wire = identity && privateRecordWire(handle, scope.owner, identity.id); 402 const base = 403 identity && expectedBase !== null 404 ? privateRecordSnapshot(expectedBase, scope.owner, identity.id) 405 : undefined; 406 const baseWire = 407 identity && expectedBase !== null 408 ? privateRecordWire(expectedBase, scope.owner, identity.id) 409 : undefined; 410 if ( 411 !identity || 412 !next || 413 !wire || 414 (expectedBase !== null && (!base || !baseWire)) || 415 !validTransition(base, next) 416 ) 417 return Promise.resolve(failed('invalid_record')); 418 const store: Store = 419 next.family === 'received_envelope' 420 ? 'received_envelopes' 421 : 'private_sends'; 422 const row = { owner: scope.owner, id: identity.id, wire }, 423 bytes = new TextEncoder().encode(JSON.stringify(row)).length; 424 return transaction< 425 Readonly<{ id: string; revision: number; state: 'committed' | 'existing' }> 426 >(scope, store, 'readwrite', (rows, tx, refuse) => { 427 const previous = rows.find((row) => row.record.id === identity.id); 428 if (previous?.wire === wire) 429 return { 430 ok: true, 431 value: { id: identity.id, revision: next.revision, state: 'existing' } 432 }; 433 if ((previous?.wire ?? null) !== (baseWire ?? null)) { 434 refuse('conflict'); 435 return; 436 } 437 const countCap = 438 store === 'private_sends' 439 ? LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 440 : LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes; 441 const byteCap = 442 store === 'private_sends' 443 ? LOCAL_PERSISTENCE_BUDGETS.privateSendBytes 444 : LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes; 445 if ( 446 (!previous && rows.length >= countCap) || 447 rows.reduce((total, row) => total + row.bytes, bytes) - 448 (previous?.bytes ?? 0) > 449 byteCap 450 ) { 451 refuse('capacity'); 452 return; 453 } 454 tx.objectStore(store).put(row); 455 return { 456 ok: true, 457 value: { id: identity.id, revision: next.revision, state: 'committed' } 458 }; 459 }); 460 } 461 // Combine received lookup/merge/write only. The caller holds the actual owner 462 // lock. Complete namespace validation and native completion remain mandatory; 463 // changed writes require the caller's later exact readonly verification. 464 export function retainPrivateReceivedRecord( 465 repository: PrivateStorageRepository, 466 session: PrivateSession, 467 incoming: PrivateRecordHandle, 468 cancellation?: AbortSignal 469 ): Promise< 470 PrivateStorageResult< 471 Readonly<{ 472 record: PrivateRecordHandle; 473 status: 'retained' | 'duplicate'; 474 changed: boolean; 475 }> 476 > 477 > { 478 const scope = scopeOf(repository), 479 ownership = privateSessionOwnership(session), 480 identity = privateRecordIdentity(incoming), 481 candidate = 482 scope && 483 identity && 484 privateRecordSnapshot(incoming, scope.owner, identity.id); 485 // Pre-admission cancellation is not evidence of a native rollback. 486 if (cancellation?.aborted) return Promise.resolve(failed('invalid_scope')); 487 if (!scope || !ownership?.current() || ownership.owner !== scope.owner) 488 return Promise.resolve(failed('invalid_scope')); 489 if ( 490 !identity || 491 candidate?.family !== 'received_envelope' || 492 candidate.revision !== 0 || 493 candidate.read !== null || 494 candidate.sources.length !== 1 495 ) 496 return Promise.resolve(failed('invalid_record')); 497 return transaction< 498 Readonly<{ 499 record: PrivateRecordHandle; 500 status: 'retained' | 'duplicate'; 501 changed: boolean; 502 }> 503 >( 504 scope, 505 'received_envelopes', 506 'readwrite', 507 (rows, tx, refuse) => { 508 if (cancellation?.aborted) { 509 refuse('aborted'); 510 return; 511 } 512 if (!ownership.current()) { 513 refuse('invalid_scope'); 514 return; 515 } 516 const previous = rows.find((row) => row.record.id === identity.id); 517 let record = incoming, 518 status: 'retained' | 'duplicate' = 'retained'; 519 if (previous) { 520 if (previous.record.family !== 'received_envelope') { 521 refuse('conflict'); 522 return; 523 } 524 status = 'duplicate'; 525 if (previous.record.sources.includes(candidate.sources[0])) 526 return { 527 ok: true, 528 value: { record: previous.handle, status, changed: false } 529 }; 530 if ( 531 previous.record.sources.length >= RELAY_BUDGETS.inbox || 532 previous.record.revision === Number.MAX_SAFE_INTEGER 533 ) { 534 refuse('capacity'); 535 return; 536 } 537 const decoded = decodePrivateRecord( 538 JSON.stringify({ 539 ...previous.record, 540 revision: previous.record.revision + 1, 541 sources: [...previous.record.sources, candidate.sources[0]] 542 }), 543 scope.owner, 544 identity.id 545 ); 546 if (!decoded.ok) { 547 refuse('invalid_record'); 548 return; 549 } 550 record = decoded.value; 551 } 552 const wire = privateRecordWire(record, scope.owner, identity.id); 553 if (!wire) { 554 refuse('invalid_record'); 555 return; 556 } 557 const row = { owner: scope.owner, id: identity.id, wire }, 558 bytes = new TextEncoder().encode(JSON.stringify(row)).length; 559 if ( 560 (!previous && 561 rows.length >= LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes) || 562 rows.reduce((total, item) => total + item.bytes, bytes) - 563 (previous?.bytes ?? 0) > 564 LOCAL_PERSISTENCE_BUDGETS.receivedCiphertextBytes 565 ) { 566 refuse('capacity'); 567 return; 568 } 569 if (cancellation?.aborted) { 570 refuse('aborted'); 571 return; 572 } 573 if (!ownership.current()) { 574 refuse('invalid_scope'); 575 return; 576 } 577 tx.objectStore('received_envelopes').put(row); 578 return { ok: true, value: { record, status, changed: true } }; 579 }, 580 (refuse) => { 581 const abort = () => refuse('aborted'), 582 off = subscribePrivateSessionClose(session, () => 583 refuse('invalid_scope') 584 ); 585 cancellation?.addEventListener('abort', abort, { once: true }); 586 if (cancellation?.aborted) abort(); 587 return () => { 588 off(); 589 cancellation?.removeEventListener('abort', abort); 590 }; 591 } 592 ); 593 } 594 595 // Observe only the selected validated row after actual native completion. The 596 // handle normalizes metadata; wire is the original physical stored string. 597 // Whole-wire custody owners must compare wire, not the normalized handle alone. 598 export function observePrivateRecord( 599 repository: PrivateStorageRepository, 600 store: Store, 601 id: unknown 602 ): Promise< 603 PrivateStorageResult<Readonly<{ handle: PrivateRecordHandle; wire: string }>> 604 > { 605 const scope = scopeOf(repository); 606 if (!scope) return Promise.resolve(failed('invalid_scope')); 607 if ( 608 (store !== 'private_sends' && store !== 'received_envelopes') || 609 typeof id !== 'string' 610 ) 611 return Promise.resolve(failed('invalid_record')); 612 return transaction<Readonly<{ handle: PrivateRecordHandle; wire: string }>>( 613 scope, 614 store, 615 'readonly', 616 (rows) => { 617 const row = rows.find((row) => row.record.id === id); 618 return row 619 ? { ok: true, value: { handle: row.handle, wire: row.wire } } 620 : failed('invalid_record'); 621 } 622 ); 623 } 624 625 export function loadPrivateRecord( 626 repository: PrivateStorageRepository, 627 store: Store, 628 id: unknown 629 ): Promise<PrivateStorageResult<PrivateRecordHandle>> { 630 const scope = scopeOf(repository); 631 if (!scope) return Promise.resolve(failed('invalid_scope')); 632 if ( 633 (store !== 'private_sends' && store !== 'received_envelopes') || 634 typeof id !== 'string' 635 ) 636 return Promise.resolve(failed('invalid_record')); 637 return transaction<PrivateRecordHandle>(scope, store, 'readonly', (rows) => { 638 const row = rows.find((row) => row.record.id === id); 639 if (!row) return failed('invalid_record'); 640 return { ok: true, value: row.handle }; 641 }); 642 } 643 export function inspectPrivateStorage( 644 repository: PrivateStorageRepository, 645 store: Store 646 ): Promise<PrivateStorageResult<Readonly<{ count: number; bytes: number }>>> { 647 const scope = scopeOf(repository); 648 if (!scope) return Promise.resolve(failed('invalid_scope')); 649 if (store !== 'private_sends' && store !== 'received_envelopes') 650 return Promise.resolve(failed('invalid_record')); 651 return transaction(scope, store, 'readonly', (rows) => ({ 652 ok: true, 653 value: { 654 count: rows.length, 655 bytes: rows.reduce((sum, row) => sum + row.bytes, 0) 656 } 657 })); 658 } 659 660 // Strict bounded original owner namespace scan; opaque ciphertext handles only. 661 // This does not mint identity, decrypt or network permission. 662 export function listPrivateReceivedRecords( 663 repository: PrivateStorageRepository 664 ): Promise<PrivateStorageResult<readonly PrivateRecordHandle[]>> { 665 const scope = scopeOf(repository); 666 if (!scope) return Promise.resolve(failed('invalid_scope')); 667 return transaction<readonly PrivateRecordHandle[]>( 668 scope, 669 'received_envelopes', 670 'readonly', 671 (rows) => { 672 return { ok: true, value: rows.map((row) => row.handle) }; 673 } 674 ); 675 } 676 677 // Strict bounded readonly outbox observations; no publication authority. 678 export function listPrivateSendRecords( 679 repository: PrivateStorageRepository 680 ): Promise<PrivateStorageResult<readonly PrivateRecordHandle[]>> { 681 const scope = scopeOf(repository); 682 if (!scope) return Promise.resolve(failed('invalid_scope')); 683 return transaction<readonly PrivateRecordHandle[]>( 684 scope, 685 'private_sends', 686 'readonly', 687 (rows) => { 688 return { ok: true, value: rows.map((row) => row.handle) }; 689 } 690 ); 691 } 692 693 // Explicit original-owner local received-copy loss only. Immutable selected 694 // whole wires CAS before any delete; independent outbox is never opened. 695 // Actual close aborts an admitted transaction where still possible. Native 696 // complete is necessary, and caller must separately verify readonly absence. 697 export function removePrivateReceivedRecords( 698 repository: PrivateStorageRepository, 699 session: PrivateSession, 700 handles: readonly PrivateRecordHandle[], 701 review: unknown, 702 cancellation?: AbortSignal 703 ): Promise<PrivateStorageResult<Readonly<{ removed: number }>>> { 704 const scope = scopeOf(repository), 705 ownership = privateSessionOwnership(session); 706 if ( 707 review !== 'reviewed_delete_local_received_copies' || 708 !scope || 709 cancellation?.aborted || 710 !ownership?.current() || 711 scope.owner !== ownership.owner 712 ) 713 return Promise.resolve(failed('invalid_scope')); 714 if ( 715 !Array.isArray(handles) || 716 !handles.length || 717 handles.length > LOCAL_PERSISTENCE_BUDGETS.receivedEnvelopes 718 ) 719 return Promise.resolve(failed('invalid_record')); 720 const selected = handles.map((handle: PrivateRecordHandle) => { 721 const identity = privateRecordIdentity(handle); 722 const record = 723 identity && privateRecordSnapshot(handle, scope.owner, identity.id), 724 wire = identity && privateRecordWire(handle, scope.owner, identity.id); 725 return identity && record?.family === 'received_envelope' && wire 726 ? { id: identity.id, wire } 727 : undefined; 728 }); 729 if ( 730 selected.some((x) => !x) || 731 new Set(selected.map((x) => x?.id)).size !== selected.length 732 ) 733 return Promise.resolve(failed('invalid_record')); 734 return transaction<Readonly<{ removed: number }>>( 735 scope, 736 'received_envelopes', 737 'readwrite', 738 (rows, tx, refuse) => { 739 if (!ownership.current() || cancellation?.aborted) { 740 refuse('invalid_scope'); 741 return; 742 } 743 for (const item of selected) { 744 if ( 745 !item || 746 rows.find((row) => row.record.id === item.id)?.wire !== item.wire 747 ) { 748 refuse('conflict'); 749 return; 750 } 751 } 752 if (!ownership.current() || cancellation?.aborted) { 753 refuse('invalid_scope'); 754 return; 755 } 756 for (const item of selected) 757 if (item) 758 tx.objectStore('received_envelopes').delete([scope.owner, item.id]); 759 return { ok: true, value: { removed: selected.length } }; 760 }, 761 (refuse) => { 762 const abort = () => refuse('invalid_scope'); 763 const off = subscribePrivateSessionClose(session, abort); 764 cancellation?.addEventListener('abort', abort, { once: true }); 765 if (cancellation?.aborted) abort(); 766 return () => { 767 off(); 768 cancellation?.removeEventListener('abort', abort); 769 }; 770 } 771 ); 772 } 773 774 // Reviewed settled-send loss only; the cleanup owner holds the owner WebLock 775 // and idle SDK slot. Revalidate the full namespace and immutable selection in 776 // the same short transaction; native complete requires separate absence proof. 777 export function removePrivateSettledSendRecords( 778 repository: PrivateStorageRepository, 779 session: PrivateSession, 780 handles: readonly PrivateRecordHandle[], 781 review: unknown, 782 cancellation?: AbortSignal 783 ): Promise<PrivateStorageResult<Readonly<{ removed: number }>>> { 784 const scope = scopeOf(repository), 785 ownership = privateSessionOwnership(session); 786 if ( 787 review !== 'reviewed_delete_local_settled_sends' || 788 !scope || 789 cancellation?.aborted || 790 !ownership?.current() || 791 scope.owner !== ownership.owner 792 ) 793 return Promise.resolve(failed('invalid_scope')); 794 if ( 795 !Array.isArray(handles) || 796 !handles.length || 797 handles.length > LOCAL_PERSISTENCE_BUDGETS.unfinishedPrivateSends 798 ) 799 return Promise.resolve(failed('invalid_record')); 800 const selected = handles.map((handle: PrivateRecordHandle) => { 801 const identity = privateRecordIdentity(handle), 802 record = 803 identity && privateRecordSnapshot(handle, scope.owner, identity.id), 804 wire = identity && privateRecordWire(handle, scope.owner, identity.id); 805 return identity && 806 record && 807 privateRecordSettlement(record) === 'settled' && 808 wire 809 ? { id: identity.id, wire } 810 : undefined; 811 }); 812 if ( 813 selected.some((x) => !x) || 814 new Set(selected.map((x) => x?.id)).size !== selected.length 815 ) 816 return Promise.resolve(failed('invalid_record')); 817 return transaction<Readonly<{ removed: number }>>( 818 scope, 819 'private_sends', 820 'readwrite', 821 (rows, tx, refuse) => { 822 if (!ownership.current() || cancellation?.aborted) { 823 refuse('invalid_scope'); 824 return; 825 } 826 for (const item of selected) { 827 const actual = item && rows.find((row) => row.record.id === item.id); 828 if ( 829 !item || 830 actual?.wire !== item.wire || 831 privateRecordSettlement(actual.record) !== 'settled' 832 ) { 833 refuse('conflict'); 834 return; 835 } 836 } 837 if (!ownership.current() || cancellation?.aborted) { 838 refuse('invalid_scope'); 839 return; 840 } 841 for (const item of selected) 842 if (item) 843 tx.objectStore('private_sends').delete([scope.owner, item.id]); 844 return { ok: true, value: { removed: selected.length } }; 845 }, 846 (refuse) => { 847 const abort = () => refuse('invalid_scope'), 848 off = subscribePrivateSessionClose(session, abort); 849 cancellation?.addEventListener('abort', abort, { once: true }); 850 if (cancellation?.aborted) abort(); 851 return () => { 852 off(); 853 cancellation?.removeEventListener('abort', abort); 854 }; 855 } 856 ); 857 } 858 859 // The only admission is a genuine ticket minted inside the cleanup owner's 860 // actual WebLock/idle SDK job. Ordinary settlement still protects all probes. 861 // No asynchronous/provider work occurs inside the native readwrite transaction. 862 export async function removePrivateInboxProbe( 863 repository: PrivateStorageRepository, 864 session: PrivateSession, 865 ticket: InboxProbeNativeCleanup 866 ): Promise< 867 | Readonly<{ ok: true; value: PrivateProbeRemovalProof }> 868 | Readonly<{ 869 ok: false; 870 reason: PrivateStorageFailure; 871 disposition: 'not_removed' | 'may_have_removed'; 872 }> 873 > { 874 const denied = (reason: PrivateStorageFailure, uncertain = false) => ({ 875 ok: false as const, 876 reason, 877 disposition: uncertain 878 ? ('may_have_removed' as const) 879 : ('not_removed' as const) 880 }); 881 const admitted = inboxProbeCleanupAdmission(ticket, repository, session); 882 if (!admitted) return denied('invalid_scope'); 883 const scope = scopeOf(repository), 884 ownership = privateSessionOwnership(session); 885 if ( 886 !scope || 887 !ownership?.current() || 888 scope.owner !== ownership.owner || 889 admitted.owner !== scope.owner || 890 !admitted.current() || 891 !admitted.take() 892 ) 893 return denied('invalid_scope'); 894 const committed = await transaction<Readonly<{ removed: number }>>( 895 scope, 896 'private_sends', 897 'readwrite', 898 (rows, tx, refuse) => { 899 if ( 900 !admitted.current() || 901 !ownership.current() || 902 admitted.signal.aborted 903 ) { 904 refuse('invalid_scope'); 905 return; 906 } 907 const selected = rows.find((row) => row.record.id === admitted.id); 908 if ( 909 !selected || 910 selected.record.family !== 'private_access_probe' || 911 selected.wire !== admitted.wire 912 ) { 913 refuse('conflict'); 914 return; 915 } 916 const store = tx.objectStore('private_sends'), 917 remove = store.delete.bind(store); 918 if ( 919 !admitted.current() || 920 !ownership.current() || 921 admitted.signal.aborted 922 ) { 923 refuse('invalid_scope'); 924 return; 925 } 926 remove([scope.owner, admitted.id]); 927 return { ok: true, value: { removed: 1 } }; 928 }, 929 (refuse) => { 930 const abort = () => refuse('invalid_scope'), 931 off = subscribePrivateSessionClose(session, abort); 932 admitted.signal.addEventListener('abort', abort, { once: true }); 933 if (admitted.signal.aborted) abort(); 934 return () => { 935 off(); 936 admitted.signal.removeEventListener('abort', abort); 937 }; 938 } 939 ); 940 if (!committed.ok) 941 return denied(committed.reason, committed.reason === 'unknown_completion'); 942 // Actual complete is necessary; separate complete-owner readonly absence is 943 // also necessary. Preexisting/manual absence can never reach proof issuance. 944 const readback = await listPrivateSendRecords(repository); 945 if (!readback.ok) return denied('unknown_completion', true); 946 if ( 947 readback.value.some( 948 (handle) => privateRecordIdentity(handle)?.id === admitted.id 949 ) 950 ) 951 return denied('conflict', true); 952 const proof = Object.freeze({}) as PrivateProbeRemovalProof; 953 probeRemovals.set(proof, { 954 repository, 955 session, 956 selection: admitted.selection, 957 owner: admitted.owner, 958 id: admitted.id, 959 wire: admitted.wire 960 }); 961 return { ok: true, value: proof }; 962 }