private-blocks.ts (16420B)
1 import { getPublicKey } from 'applesauce-core/helpers'; 2 import { inboxSetupViewOwnership } from '../../../src/lib/messaging/inbox-setup-view.ts'; 3 import { 4 createPublicRuntimeContext, 5 mountPublicRuntime, 6 closePublicRuntime 7 } from '../../../src/lib/runtime/public-runtime.ts'; 8 import { 9 captureCitedProduct, 10 citedProductSnapshot, 11 closeCitedProduct 12 } from '../../../src/lib/messaging/cited-product.ts'; 13 import { 14 createReplyController, 15 updateReplyText, 16 replySnapshot, 17 replyText, 18 sendReply, 19 closeReplyController 20 } from '../../../src/lib/messaging/reply-controller.ts'; 21 // HC_TEST_ONLY_RELAY: original identity, signed nested crypto and native IDB. 22 import { mount, unmount } from 'svelte'; 23 import Panel from './private-blocks-panel.svelte'; 24 export { makeFixture as createQueueFixture } from './decryption-queue.ts'; 25 import { renderFixture, type Scenario } from './conversation-thread.ts'; 26 import { 27 privateBlocksForIdentity, 28 createIdentityLocalPrivateBlocksView, 29 mountLocalPrivateBlocksView, 30 localPrivateBlocksSnapshot, 31 refreshLocalPrivateBlocks, 32 blockLocalPrivatePeer, 33 closeLocalPrivateBlocksView, 34 closeLocalPrivateBlocks, 35 mountLocalPrivateBlocks, 36 LOCAL_PRIVATE_BLOCKS_CONTEXT 37 } from '../../../src/lib/persistence/local-private-blocks.ts'; 38 import { 39 blockInboxConversation, 40 inboxListSnapshot, 41 inboxReplyOwnership, 42 inboxMessageSnapshot, 43 markInboxConversationDisplayed 44 } from '../../../src/lib/messaging/inbox-view.ts'; 45 import { 46 openBrowserDatabase, 47 browserDatabaseTransaction, 48 closeBrowserDatabase 49 } from '../../../src/lib/persistence/database.ts'; 50 import type { AdmittedConversation } from '../../../src/lib/messaging/admit-conversation.ts'; 51 import type { UnlockedSession } from '../../../src/lib/messaging/unlocked-session.ts'; 52 import { 53 createIdentitySession, 54 connectIdentity, 55 probeIdentityMessaging, 56 disconnectIdentity 57 } from '../../../src/lib/runtime/identity-session.ts'; 58 export async function createFixture(kind: Scenario = 'inbound') { 59 const thread = await renderFixture(kind); 60 const blocks = privateBlocksForIdentity(thread.identity); 61 if (!blocks) throw Error('original block owner unavailable'); 62 const token = blocks; 63 const view = createIdentityLocalPrivateBlocksView(thread.identity); 64 await mountLocalPrivateBlocksView(view); 65 const opened = await openBrowserDatabase(); 66 if (opened.state !== 'ready') 67 throw Error('native fixture database unavailable'); 68 const database = opened.owner; 69 const target = document.createElement('div'); 70 document.body.append(target); 71 const panel = mount(Panel, { 72 target, 73 context: new Map([[LOCAL_PRIVATE_BLOCKS_CONTEXT, view]]) 74 }); 75 async function rows() { 76 const tx = browserDatabaseTransaction( 77 database, 78 ['local_preferences'], 79 'readonly' 80 ); 81 const request = tx.objectStore('local_preferences').getAll(); 82 return await new Promise<unknown[]>((resolve, reject) => { 83 tx.addEventListener('complete', () => 84 resolve( 85 (request.result as { owner: string; id: string }[]).filter( 86 (row) => row.owner === thread.owner && row.id === 'private_blocks' 87 ) 88 ) 89 ); 90 tx.addEventListener('abort', () => 91 reject(Error('native preference scan aborted')) 92 ); 93 }); 94 } 95 async function corrupt() { 96 const tx = browserDatabaseTransaction( 97 database, 98 ['local_preferences'], 99 'readwrite' 100 ); 101 tx.objectStore('local_preferences').put({ 102 owner: thread.owner, 103 id: 'private_blocks', 104 wire: 'corrupt' 105 }); 106 await new Promise<void>((resolve, reject) => { 107 tx.addEventListener('complete', () => resolve()); 108 tx.addEventListener('abort', () => 109 reject(Error('native corrupt fixture aborted')) 110 ); 111 }); 112 await refreshLocalPrivateBlocks(token); 113 } 114 const block = () => 115 blockInboxConversation( 116 thread.controller, 117 thread.conversationId, 118 'reviewed_local_private_block' 119 ); 120 async function foreignGeneration() { 121 const proof = inboxReplyOwnership( 122 thread.controller, 123 thread.conversationId, 124 thread.firstRumor 125 ); 126 if (!proof?.current()) throw Error('original genuine proof unavailable'); 127 const other = createIdentitySession(); 128 await connectIdentity(other); 129 await probeIdentityMessaging(other, 'reviewed_self_copy'); 130 const foreign = privateBlocksForIdentity(other); 131 if (!foreign) throw Error('second original identity unavailable'); 132 try { 133 await mountLocalPrivateBlocks(foreign); 134 return await blockLocalPrivatePeer( 135 foreign, 136 proof.room, 137 proof.unlocked, 138 'reviewed_local_private_block' 139 ); 140 } finally { 141 closeLocalPrivateBlocks(foreign); 142 disconnectIdentity(other); 143 } 144 } 145 async function disposeSibling() { 146 const sibling = createIdentityLocalPrivateBlocksView(thread.identity); 147 await mountLocalPrivateBlocksView(sibling); 148 closeLocalPrivateBlocksView(sibling); 149 return localPrivateBlocksSnapshot(token); 150 } 151 let releaseInventory: (() => void) | undefined; 152 function holdInventory() { 153 const native = Reflect.get<IDBTransaction, 'addEventListener'>( 154 IDBTransaction.prototype, 155 'addEventListener' 156 ); 157 let held = false; 158 IDBTransaction.prototype.addEventListener = function ( 159 type: string, 160 listener: EventListenerOrEventListenerObject | null, 161 options?: boolean | AddEventListenerOptions 162 ) { 163 if ( 164 !held && 165 type === 'complete' && 166 this.mode === 'readonly' && 167 this.objectStoreNames.length === 1 && 168 this.objectStoreNames.contains('received_envelopes') && 169 listener 170 ) { 171 held = true; 172 native.call( 173 this, 174 type, 175 (event: Event) => { 176 releaseInventory = () => { 177 releaseInventory = undefined; 178 if (typeof listener === 'function') listener.call(this, event); 179 else listener.handleEvent(event); 180 }; 181 }, 182 options 183 ); 184 IDBTransaction.prototype.addEventListener = native; 185 } else if (listener) native.call(this, type, listener, options); 186 }; 187 } 188 async function abortWrite() { 189 const prototype = IDBObjectStore.prototype, 190 original = Reflect.get<IDBObjectStore, 'put'>(prototype, 'put'); 191 prototype.put = function (value: unknown, key?: IDBValidKey) { 192 const request = original.call(this, value, key); 193 if (this.name === 'local_preferences') this.transaction.abort(); 194 return request; 195 }; 196 try { 197 return await block(); 198 } finally { 199 prototype.put = original; 200 } 201 } 202 async function failReadback() { 203 const prototype = IDBDatabase.prototype, 204 original = Reflect.get<IDBDatabase, 'transaction'>( 205 prototype, 206 'transaction' 207 ); 208 let written = false; 209 prototype.transaction = function ( 210 storeNames: string | string[], 211 mode?: IDBTransactionMode, 212 options?: IDBTransactionOptions 213 ) { 214 const names = typeof storeNames === 'string' ? [storeNames] : storeNames; 215 if (names.includes('local_preferences') && mode === 'readonly' && written) 216 throw Error('actual readback unavailable'); 217 const tx = original.call(this, storeNames, mode, options); 218 if (names.includes('local_preferences') && mode === 'readwrite') 219 tx.addEventListener('complete', () => { 220 written = true; 221 }); 222 return tx; 223 }; 224 try { 225 return await block(); 226 } finally { 227 prototype.transaction = original; 228 } 229 } 230 async function writePreferences(peers: readonly string[], revision: number) { 231 const wire = JSON.stringify({ 232 schema: 1, 233 family: 'private_blocks', 234 owner: thread.owner, 235 id: 'private_blocks', 236 revision, 237 peers: peers.slice().sort() 238 }); 239 const tx = browserDatabaseTransaction( 240 database, 241 ['local_preferences'], 242 'readwrite' 243 ); 244 tx.objectStore('local_preferences').put({ 245 owner: thread.owner, 246 id: 'private_blocks', 247 wire 248 }); 249 await new Promise<void>((resolve, reject) => { 250 tx.addEventListener('complete', () => resolve()); 251 tx.addEventListener('abort', () => 252 reject(Error('actual competing preference write aborted')) 253 ); 254 }); 255 return wire; 256 } 257 const unrelatedPeer = getPublicKey(new Uint8Array(32).fill(88)); 258 async function matchingNativeRow() { 259 const wire = await writePreferences([thread.peer, unrelatedPeer], 17); 260 const before = await rows(); 261 const prototype = IDBDatabase.prototype; 262 const native = Reflect.get<IDBDatabase, 'transaction'>( 263 prototype, 264 'transaction' 265 ); 266 let writes = 0; 267 prototype.transaction = function ( 268 names: string | string[], 269 mode?: IDBTransactionMode, 270 options?: IDBTransactionOptions 271 ) { 272 const stores = typeof names === 'string' ? [names] : names; 273 if (mode === 'readwrite' && stores.includes('local_preferences')) 274 writes++; 275 return native.call(this, names, mode, options); 276 }; 277 try { 278 const result = await block(); 279 return { 280 wire, 281 before, 282 after: await rows(), 283 result, 284 snapshot: localPrivateBlocksSnapshot(token), 285 unrelatedPeer, 286 writes 287 }; 288 } finally { 289 prototype.transaction = native; 290 } 291 } 292 async function competingNativeRow() { 293 const prototype = IDBDatabase.prototype; 294 const native = Reflect.get<IDBDatabase, 'transaction'>( 295 prototype, 296 'transaction' 297 ); 298 let intercepted = false, 299 completion: Promise<string> | undefined; 300 prototype.transaction = function ( 301 names: string | string[], 302 mode?: IDBTransactionMode, 303 options?: IDBTransactionOptions 304 ) { 305 const stores = typeof names === 'string' ? [names] : names; 306 if ( 307 !intercepted && 308 mode === 'readwrite' && 309 stores.includes('local_preferences') 310 ) { 311 intercepted = true; 312 // Queue a genuine independent native write before the producer's CAS 313 // transaction. The actual IndexedDB scheduler orders both transactions. 314 completion = writePreferences([unrelatedPeer], 19); 315 } 316 return native.call(this, names, mode, options); 317 }; 318 try { 319 const result = await block(); 320 await completion; 321 if (!intercepted) throw Error('actual CAS seam was not reached'); 322 return { 323 result, 324 rows: await rows(), 325 snapshot: localPrivateBlocksSnapshot(token), 326 unrelatedPeer 327 }; 328 } finally { 329 prototype.transaction = native; 330 } 331 } 332 async function reloadOwners() { 333 thread.logout(); 334 const snapshots = []; 335 for (const changed of [false, true, false]) { 336 thread.mode(changed ? 'changed_key' : 'normal'); 337 const identity = createIdentitySession(); 338 await connectIdentity(identity); 339 const fresh = privateBlocksForIdentity(identity); 340 if (!fresh) throw Error('new original observed owner unavailable'); 341 const before = thread.delta(); 342 try { 343 await mountLocalPrivateBlocks(fresh); 344 snapshots.push({ 345 snapshot: localPrivateBlocksSnapshot(fresh), 346 before, 347 after: thread.delta() 348 }); 349 } finally { 350 closeLocalPrivateBlocks(fresh); 351 disconnectIdentity(identity); 352 } 353 } 354 thread.mode('normal'); 355 return { 356 snapshots, 357 old: localPrivateBlocksSnapshot(token), 358 rows: await rows() 359 }; 360 } 361 let captured: 362 | (() => Promise<{ 363 current: boolean; 364 citation: unknown; 365 message: unknown; 366 reply: unknown; 367 text: unknown; 368 send: Awaited<ReturnType<typeof sendReply>>; 369 displayed: boolean; 370 }>) 371 | undefined, 372 closeCaptured = () => {}; 373 function captureActions() { 374 if (captured) throw Error('original handles already captured'); 375 const message = thread 376 .thread() 377 .messages.find((row) => 378 row.citations.some((ref) => ref.naddr === thread.carrots) 379 ); 380 if (!message) throw Error('actual authenticated cited message unavailable'); 381 const proof = inboxReplyOwnership( 382 thread.controller, 383 thread.conversationId, 384 message.data.rumorId 385 ); 386 const setup = proof && inboxSetupViewOwnership(proof.setup); 387 if (!proof?.current() || !setup) 388 throw Error('original current ownership unavailable'); 389 const context = createPublicRuntimeContext(); 390 const runtime = mountPublicRuntime(context, setup.policy); 391 if (!runtime) throw Error('original public runtime unavailable'); 392 const citation = captureCitedProduct( 393 thread.controller, 394 thread.conversationId, 395 message.data.rumorId, 396 thread.carrots, 397 runtime, 398 'reviewed_product_citation' 399 ); 400 const reply = createReplyController( 401 thread.controller, 402 thread.conversationId, 403 message.data.rumorId 404 ); 405 if (!citation || !reply) { 406 closePublicRuntime(context); 407 throw Error('original actions unavailable'); 408 } 409 if ( 410 !updateReplyText( 411 reply, 412 'HCP123_OLD_REPLY_MEMORY_ONLY', 413 'reviewed_private_text' 414 ) 415 ) 416 throw Error('original reply text unavailable'); 417 closeCaptured = () => { 418 closeCitedProduct(citation); 419 closeReplyController(reply); 420 closePublicRuntime(context); 421 }; 422 captured = async () => ({ 423 current: proof.current(), 424 citation: citedProductSnapshot(citation), 425 message: inboxMessageSnapshot( 426 thread.controller, 427 thread.conversationId, 428 message.data.rumorId 429 ), 430 reply: replySnapshot(reply), 431 text: replyText(reply), 432 send: await sendReply(reply, 'reviewed_reply_send'), 433 displayed: await markInboxConversationDisplayed( 434 thread.controller, 435 thread.conversationId, 436 [message.data.rumorId], 437 'reviewed_displayed_conversation' 438 ) 439 }); 440 return { 441 current: proof.current(), 442 citation: citedProductSnapshot(citation), 443 text: replyText(reply) 444 }; 445 } 446 async function failLockCompletion() { 447 const locks = navigator.locks; 448 const native = Reflect.get<LockManager, 'request'>(locks, 'request'); 449 const descriptor = Object.getOwnPropertyDescriptor(locks, 'request'); 450 Object.defineProperty(locks, 'request', { 451 configurable: true, 452 value: async (...args: unknown[]) => { 453 // Execute the actual owner WebLock and original native write/readback; 454 // then lose the caller's completion channel, without fabricating a row. 455 await Reflect.apply(native, locks, args); 456 throw Error('controlled owner-lock completion channel unavailable'); 457 } 458 }); 459 try { 460 return await block(); 461 } finally { 462 if (descriptor) Object.defineProperty(locks, 'request', descriptor); 463 else Reflect.deleteProperty(locks, 'request'); 464 } 465 } 466 return { 467 ...thread, 468 rows, 469 corrupt, 470 abortWrite, 471 failReadback, 472 block, 473 foreignGeneration, 474 matchingNativeRow, 475 competingNativeRow, 476 reloadOwners, 477 captureActions, 478 failLockCompletion, 479 capturedActions: () => { 480 if (!captured) throw Error('original handles not captured'); 481 return captured(); 482 }, 483 disposeSibling, 484 waitOwner: () => 485 navigator.locks.request('harvestcircle:owner:' + thread.owner, () => 486 Promise.resolve() 487 ), 488 holdInventory, 489 inventoryHeld: () => !!releaseInventory, 490 releaseInventory: () => releaseInventory?.(), 491 preferences: () => localPrivateBlocksSnapshot(token), 492 list: () => inboxListSnapshot(thread.controller), 493 refresh: () => refreshLocalPrivateBlocks(token), 494 fake: () => { 495 const room = inboxReplyOwnership( 496 thread.controller, 497 thread.conversationId, 498 thread.firstRumor 499 ); 500 return blockLocalPrivatePeer( 501 token, 502 { ...(room?.room ?? {}) } as AdmittedConversation, 503 room?.unlocked ?? ({} as UnlockedSession), 504 'reviewed_local_private_block' 505 ); 506 }, 507 async close() { 508 closeCaptured(); 509 releaseInventory?.(); 510 await unmount(panel); 511 target.remove(); 512 closeLocalPrivateBlocksView(view); 513 closeBrowserDatabase(database); 514 await thread.close(); 515 } 516 }; 517 }