stop-send.ts (11148B)
1 import { 2 stopPrivateSend, 3 privateStopSendSnapshot 4 } from '../../../src/lib/messaging/stop-send.ts'; 5 import { privateSendStatus } from '../../../src/lib/messaging/send-status.ts'; 6 import { reconcilePrivateSendAttempt } from '../../../src/lib/persistence/private-send-settlements.ts'; 7 import { 8 capturePrivatePublication, 9 capturePrivatePublicationAction 10 } from '../../../src/lib/nostr/private-publisher.ts'; 11 import { 12 publishPrivateGiftWrapAttempt, 13 type PrivateGiftWrapAttemptResult 14 } from '../../../src/lib/nostr/private-pool.ts'; 15 import { makeFixture as makeRecoveryFixture } from './resume-preparation.ts'; 16 import { 17 validateRelayPolicy, 18 readRelayPolicy 19 } from '../../../src/lib/config/relays.ts'; 20 import { createInboxRoutePlan } from '../../../src/lib/messaging/inbox-routing.ts'; 21 import { 22 createPrivateSession, 23 closePrivateSession 24 } from '../../../src/lib/runtime/private-session.ts'; 25 import { 26 getPrivatePool, 27 closePrivatePool 28 } from '../../../src/lib/nostr/private-pool.ts'; 29 import { 30 resumeEncryptedPreparation, 31 qualifyRecoveredPrivatePair, 32 resumePreparationSnapshot, 33 resumeRecoveredRumor, 34 stopResumePreparation 35 } from '../../../src/lib/messaging/resume-preparation.ts'; 36 import { rumorPlanSnapshot } from '../../../src/lib/messaging/rumor-plan.ts'; 37 import { decodePrivateRecord } from '../../../src/lib/persistence/private-records.ts'; 38 import { 39 capturePrivateRetry, 40 runPrivateRetry, 41 type PrivateRetry 42 } from '../../../src/lib/messaging/retry-send.ts'; 43 import { 44 pairedDeliveryAcknowledgementSnapshot, 45 commitPairedDeliveryReceipt, 46 type PairedDeliveryAcknowledgement 47 } from '../../../src/lib/persistence/private-sends.ts'; 48 export async function makeFixture(initialise = true) { 49 const f = await makeRecoveryFixture(initialise); 50 const policy = validateRelayPolicy( 51 JSON.stringify({ 52 ...readRelayPolicy(f.context.policy), 53 messagingEnabled: true 54 }) 55 ); 56 if (!policy) throw Error('invalid private fixture policy'); 57 const plan = createInboxRoutePlan( 58 policy, 59 f.owner, 60 f.peer, 61 f.context.own, 62 f.context.other 63 ); 64 if (!plan) throw Error('missing private route plan'); 65 const context = { ...f.context, policy, plan }; 66 const session = await createPrivateSession( 67 f.identity, 68 'reviewed_private_session' 69 ); 70 if (!session) throw Error('missing genuine private session'); 71 const pool = getPrivatePool(session, policy, [ 72 'wss://peer.example.org', 73 'wss://archive.example.org' 74 ]); 75 if (!pool) throw Error('missing private pool'); 76 const resume = f.capture(); 77 let receipt: PairedDeliveryAcknowledgement | undefined, 78 retry: PrivateRetry | undefined; 79 let observed: PrivateGiftWrapAttemptResult | undefined; 80 let restoreFault = () => {}, 81 injected = 0; 82 async function prepare() { 83 const recovered = await resumeEncryptedPreparation( 84 resume, 85 context, 86 'reviewed_private_resume' 87 ); 88 if (!['prepared', 'already_prepared'].includes(recovered.status)) 89 return recovered; 90 const qualified = await qualifyRecoveredPrivatePair( 91 resume, 92 context, 93 'reviewed_stored_private_retry' 94 ); 95 if ('receipt' in qualified) receipt = qualified.receipt; 96 return { status: qualified.status }; 97 } 98 function capture(review: unknown = 'reviewed_private_retry') { 99 retry = receipt 100 ? capturePrivateRetry( 101 f.repository, 102 session!, 103 receipt, 104 context, 105 pool!, 106 review 107 ) 108 : undefined; 109 return !!retry; 110 } 111 return { 112 ...f, 113 async row() { 114 const value = await f.row(); 115 if (!value) throw Error('missing actual paired row'); 116 return value; 117 }, 118 async sendStatus() { 119 const row = await f.row(); 120 const decoded = row && decodePrivateRecord(row.wire, f.owner, f.command); 121 return decoded?.ok 122 ? privateSendStatus(decoded.value, f.owner, f.command) 123 : undefined; 124 }, 125 async publishObserved() { 126 if (!receipt) throw Error('missing genuine pair'); 127 const action = capturePrivatePublicationAction( 128 f.repository, 129 session, 130 receipt, 131 context, 132 'reviewed_private_retry' 133 ); 134 const permission = 135 action && 136 capturePrivatePublication( 137 f.repository, 138 session, 139 receipt, 140 context, 141 'peer', 142 'wss://peer.example.org', 143 'reviewed_private_delivery', 144 action 145 ); 146 if (!permission) throw Error('missing genuine permission'); 147 observed = await publishPrivateGiftWrapAttempt( 148 pool, 149 permission, 150 new AbortController().signal 151 ); 152 return observed; 153 }, 154 settleObserved(clone = false) { 155 if (!observed) throw Error('missing actual SDK result'); 156 return reconcilePrivateSendAttempt(clone ? { ...observed } : observed); 157 }, 158 async replaceImmutableScope() { 159 let db: IDBDatabase | undefined; 160 const native = Reflect.get<IDBIndex, 'openCursor'>( 161 IDBIndex.prototype, 162 'openCursor' 163 ); 164 IDBIndex.prototype.openCursor = function ( 165 ...args: Parameters<IDBIndex['openCursor']> 166 ) { 167 if (this.objectStore.name === 'private_sends') 168 db = this.objectStore.transaction.db; 169 return native.apply(this, args); 170 }; 171 let row; 172 try { 173 row = await f.row(); 174 } finally { 175 IDBIndex.prototype.openCursor = native; 176 } 177 if (!db || !row) throw Error('missing native row'); 178 const wire = JSON.stringify({ 179 ...row.record, 180 revision: row.record.revision + 1, 181 rumorHash: 'b'.repeat(64) 182 }); 183 if (!decodePrivateRecord(wire, f.owner, f.command).ok) 184 throw Error('invalid controlled successor'); 185 const tx = db.transaction(['private_sends'], 'readwrite'); 186 tx.objectStore('private_sends').put({ 187 owner: f.owner, 188 id: f.command, 189 wire 190 }); 191 await new Promise<void>((resolve, reject) => { 192 tx.addEventListener('complete', () => resolve()); 193 tx.addEventListener('abort', () => reject(Error('fixture abort'))); 194 }); 195 return wire; 196 }, 197 faultSettlement(kind: 'abort' | 'readback') { 198 const put = Reflect.get<IDBObjectStore, 'put'>( 199 IDBObjectStore.prototype, 200 'put' 201 ); 202 const cursor = Reflect.get<IDBIndex, 'openCursor'>( 203 IDBIndex.prototype, 204 'openCursor' 205 ); 206 let written = false; 207 IDBObjectStore.prototype.put = function ( 208 ...args: Parameters<IDBObjectStore['put']> 209 ) { 210 const request = put.apply(this, args); 211 if (this.name === 'private_sends') { 212 written = true; 213 if (kind === 'abort') this.transaction.abort(); 214 } 215 return request; 216 }; 217 IDBIndex.prototype.openCursor = function ( 218 ...args: Parameters<IDBIndex['openCursor']> 219 ) { 220 if ( 221 kind === 'readback' && 222 written && 223 this.objectStore.name === 'private_sends' && 224 this.objectStore.transaction.mode === 'readonly' 225 ) 226 throw Error('actual post-put readback failure'); 227 return cursor.apply(this, args); 228 }; 229 restoreFault = () => { 230 IDBObjectStore.prototype.put = put; 231 IDBIndex.prototype.openCursor = cursor; 232 }; 233 }, 234 prepare, 235 capture, 236 run: (review: unknown = 'reviewed_private_retry') => 237 retry 238 ? runPrivateRetry(retry, review) 239 : Promise.resolve({ status: 'invalid' as const }), 240 snapshot: () => retry && privateStopSendSnapshot(retry), 241 proof: () => receipt && pairedDeliveryAcknowledgementSnapshot(receipt), 242 recovered: () => ({ 243 snapshot: resumePreparationSnapshot(resume), 244 rumor: !!rumorPlanSnapshot(resumeRecoveredRumor(resume)!) 245 }), 246 stop: () => { 247 if (retry) stopPrivateSend(retry); 248 }, 249 clearRecovery: () => stopResumePreparation(resume), 250 countsValue: () => f.counts(), 251 async controlledArchiveSuccessor() { 252 if (!receipt) throw Error('missing genuine custody'); 253 const row = (await f.row())?.record; 254 if (!row) throw Error('missing actual ciphertext'); 255 // Controlled metadata race, not a claim of an additional relay ACK. 256 return commitPairedDeliveryReceipt( 257 f.repository, 258 receipt, 259 JSON.stringify({ 260 actionId: '12345678-1234-4234-8234-123456789abe', 261 role: 'self_archive', 262 origin: 'wss://archive.example.org', 263 attempt: 1, 264 eventId: row.self.eventId, 265 status: 'accepted', 266 observedAtMilliseconds: 100, 267 readbackWire: null 268 }) 269 ); 270 }, 271 async injectUnacknowledgedSuccessBetweenReads() { 272 const stored = await f.row(); 273 if (!stored?.record.peerArtifact || !stored.record.deliveryPlan) 274 throw Error('missing real paired record'); 275 const row = stored.record; 276 const facts = [ 277 row.deliveryPlan!.routes.peer, 278 row.deliveryPlan!.routes.archive 279 ].flatMap((route) => 280 route.targets.map((origin) => ({ 281 actionId: '12345678-1234-4234-8234-123456789abf', 282 role: route.role, 283 origin, 284 attempt: 1, 285 eventId: 286 route.role === 'peer' 287 ? row.peerArtifact!.eventId 288 : row.self.eventId, 289 status: 'accepted', 290 observedAtMilliseconds: 100, 291 readbackWire: null 292 })) 293 ); 294 const wire = JSON.stringify({ 295 ...row, 296 revision: row.revision + 1, 297 receipts: [...(row.receipts ?? []), ...facts] 298 }); 299 if (!decodePrivateRecord(wire, f.owner, f.command).ok) 300 throw Error('invalid controlled race row'); 301 const native = Reflect.get<IDBIndex, 'openCursor'>( 302 IDBIndex.prototype, 303 'openCursor' 304 ); 305 IDBIndex.prototype.openCursor = function ( 306 ...args: Parameters<IDBIndex['openCursor']> 307 ) { 308 const request = native.apply(this, args); 309 if (this.objectStore.name === 'private_sends' && injected === 0) { 310 injected++; 311 // Queue real RW behind first genuine verification and ahead of the 312 // next load. No opaque acknowledgement is renewed by this mutation. 313 const transaction = this.objectStore.transaction.db.transaction( 314 ['private_sends'], 315 'readwrite' 316 ); 317 transaction 318 .objectStore('private_sends') 319 .put({ owner: f.owner, id: f.command, wire }); 320 } 321 return request; 322 }; 323 restoreFault = () => { 324 IDBIndex.prototype.openCursor = native; 325 }; 326 return { 327 originalWire: stored.wire, 328 changedWire: wire, 329 revision: row.revision 330 }; 331 }, 332 injected: () => injected, 333 clearFault() { 334 restoreFault(); 335 restoreFault = () => {}; 336 }, 337 close() { 338 restoreFault(); 339 if (retry) stopPrivateSend(retry); 340 stopResumePreparation(resume); 341 closePrivatePool(pool); 342 closePrivateSession(session); 343 f.close(); 344 } 345 }; 346 }