sign-listing.ts (16759B)
1 import { makeFixture, type Mode } from './approved-signing.ts'; 2 import { fixturePolicy, discovery, inbox } from './inbox-setup.ts'; 3 import { 4 createIdentitySession, 5 connectIdentity, 6 probeIdentityMessaging, 7 disconnectIdentity 8 } from '../../../src/lib/runtime/identity-session.ts'; 9 import { 10 createPublicScheduler, 11 createPublicRun, 12 openInboxRequest, 13 closePublicScheduler 14 } from '../../../src/lib/nostr/request-scope.ts'; 15 import { createInboxResolver } from '../../../src/lib/messaging/resolve-inbox.ts'; 16 import { 17 createInboxSetupView, 18 checkInboxSetupView, 19 unlockInboxSetupView, 20 closeInboxSetupView 21 } from '../../../src/lib/messaging/inbox-setup-view.ts'; 22 import { captureNewListingReadiness } from '../../../src/lib/publishing/new-listing-readiness.ts'; 23 import { 24 openBrowserDatabase, 25 closeBrowserDatabase, 26 browserDatabaseTransaction 27 } from '../../../src/lib/persistence/database.ts'; 28 import { 29 createPublicPublicationRepository, 30 publicPublicationDraftRepository, 31 readPublicListingIntent 32 } from '../../../src/lib/persistence/public-publications.ts'; 33 import { 34 createPublicDraftController, 35 closePublicDraftController 36 } from '../../../src/lib/publishing/draft-controller.ts'; 37 import { 38 reviewNewListing, 39 reserveNewListing, 40 listingReviewSnapshot 41 } from '../../../src/lib/publishing/prepare-listing.ts'; 42 import { 43 publicRecordSnapshot, 44 decodePublicRecord 45 } from '../../../src/lib/persistence/records.ts'; 46 import type { PublicOperationRecord } from '../../../src/lib/contracts/local-records.ts'; 47 import { 48 beginListingSigning, 49 runListingSigning, 50 stopListingSigning, 51 listingSigningSnapshot, 52 listingPublicationSnapshot 53 } from '../../../src/lib/publishing/sign-listing.ts'; 54 55 export async function createFixture() { 56 const signer = makeFixture(10050), 57 identity = createIdentitySession(), 58 policy = fixturePolicy(); 59 const preference = signer.sign({ 60 ...signer.template, 61 kind: 10050, 62 created_at: 100, 63 tags: [['relay', inbox]], 64 content: '' 65 }); 66 const prior = Object.getOwnPropertyDescriptor(window, 'nostr'); 67 let signs = 0, 68 keys = 0, 69 mode: Mode = 'exact', 70 observedOwner = signer.owner; 71 let beforeSign: (() => Promise<void>) | undefined; 72 Object.defineProperty(window, 'nostr', { 73 configurable: true, 74 value: { 75 getPublicKey: () => { 76 keys++; 77 return Promise.resolve(observedOwner); 78 }, 79 signEvent: async (input: Parameters<typeof signer.sign>[0]) => { 80 signs++; 81 await beforeSign?.(); 82 return signer.sign(input, mode); 83 }, 84 nip44: { 85 encrypt: (_peer: string, text: string) => 86 Promise.resolve('fixture:' + text), 87 decrypt: (_peer: string, text: string) => Promise.resolve(text.slice(8)) 88 } 89 } 90 }); 91 await connectIdentity(identity); 92 await probeIdentityMessaging(identity, 'reviewed_self_copy'); 93 const scheduler = createPublicScheduler({ 94 now: () => 0, 95 schedule: () => () => {} 96 }); 97 const run = createPublicRun(scheduler, policy); 98 const resolver = createInboxResolver( 99 run, 100 signer.owner, 101 (next) => 102 openInboxRequest( 103 run, 104 signer.owner, 105 (sink) => { 106 sink({ 107 type: 'EVENT', 108 from: discovery, 109 id: 'fixture', 110 event: preference 111 }); 112 sink({ type: 'EOSE', from: discovery, id: 'fixture' }); 113 return () => {}; 114 }, 115 next 116 ), 117 () => true 118 ); 119 // HC_TEST_ONLY_QUALIFICATION_PORT: original SDK owners, controlled exercised 120 // access observation; no real extension/operator/relay qualification. 121 const setup = createInboxSetupView({ 122 identity, 123 policy, 124 lookup: () => Promise.resolve(resolver), 125 observeAccess: (context) => ({ 126 ...context, 127 readTargets: context.readTargets.slice(), 128 archiveTargets: context.archiveTargets.slice(), 129 receive: 'qualified_exercised', 130 archive: 'qualified_exercised', 131 current: () => true 132 }) 133 }); 134 if (!setup) throw Error('original setup missing'); 135 await checkInboxSetupView(setup); 136 await unlockInboxSetupView(setup); 137 const ready = captureNewListingReadiness( 138 identity, 139 setup, 140 'reviewed_new_listing_inbox' 141 ); 142 if (!ready) throw Error('original readiness missing'); 143 const opened = await openBrowserDatabase(); 144 if (opened.state !== 'ready') throw Error(opened.reason); 145 const database = opened.owner, 146 repository = createPublicPublicationRepository(database, signer.owner); 147 const drafts = repository && publicPublicationDraftRepository(repository); 148 if (!repository || !drafts) throw Error('original repository missing'); 149 const originalRepository = repository; 150 const controller = await createPublicDraftController(drafts, { 151 title: 'Carrots', 152 description: 'Exact signed description', 153 location: 'Local farm', 154 amount: '2', 155 currency: 'USD', 156 unit: 'kg', 157 quantity: '', 158 contactType: '', 159 contactValue: '' 160 }); 161 if (!controller) throw Error('original controller missing'); 162 const command = crypto.randomUUID(); 163 const reviewed = await reviewNewListing( 164 repository, 165 controller, 166 ready, 167 command, 168 'reviewed_new_listing' 169 ); 170 if (reviewed.status !== 'review') throw Error(reviewed.reason); 171 const original = reviewed.review, 172 preview = listingReviewSnapshot(original); 173 if (!preview) throw Error('original preview missing'); 174 const reserved = await reserveNewListing( 175 original, 176 'publish_reviewed_listing' 177 ); 178 if (reserved.status !== 'saved') throw Error(reserved.status); 179 const signing = beginListingSigning(original, 'sign_reviewed_listing'); 180 if (!signing) throw Error('original signing missing'); 181 const originalSigning = signing; 182 async function stored() { 183 const read = await readPublicListingIntent(originalRepository, command); 184 const row = 185 read.status === 'found' && 186 publicRecordSnapshot(read.record, signer.owner, command); 187 if (!row || row.family !== 'public_operation') 188 throw Error('original stored command missing'); 189 return row; 190 } 191 function invoke() { 192 return runListingSigning(originalSigning, 'sign_reviewed_listing'); 193 } 194 return { 195 async exact() { 196 const a = invoke(), 197 b = invoke(), 198 same = a === b; 199 const result = await a, 200 row = await stored(); 201 const plan = 202 result.status === 'prepared' 203 ? listingPublicationSnapshot(result.publication) 204 : undefined; 205 const retry = await invoke(); 206 return { 207 status: result.status, 208 same, 209 signatures: signs, 210 keys, 211 revision: row.revision, 212 artifact: row.artifact, 213 plan, 214 expectedHash: preview.expectedHash, 215 originalCapture: row.capture.wire === preview.templateWire, 216 retry: retry.status, 217 sameArtifact: 218 retry.status === 'prepared' && 219 listingPublicationSnapshot(retry.publication)?.wire === plan?.wire 220 }; 221 }, 222 async wrong(next: Mode) { 223 mode = next; 224 const result = await invoke(), 225 row = await stored(); 226 const retry = await invoke(); 227 return { 228 status: result.status, 229 signatures: signs, 230 revision: row.revision, 231 artifact: row.artifact, 232 retry: retry.status, 233 exposed: result.status === 'prepared' 234 }; 235 }, 236 async changedKey() { 237 const other = makeFixture(10050); 238 observedOwner = other.owner; 239 other.close(); 240 const result = await invoke(), 241 row = await stored(); 242 return { 243 status: result.status, 244 signatures: signs, 245 keys, 246 revision: row.revision, 247 artifact: row.artifact, 248 exposed: result.status === 'prepared' 249 }; 250 }, 251 async late(logout: boolean, retireSetup = false) { 252 let release = () => {}, 253 entered = () => {}; 254 const enteredPromise = new Promise<void>((resolve) => { 255 entered = resolve; 256 }); 257 const held = new Promise<void>((resolve) => { 258 release = resolve; 259 }); 260 beforeSign = () => { 261 entered(); 262 return held; 263 }; 264 const pending = invoke(); 265 await enteredPromise; 266 if (retireSetup) closeInboxSetupView(setup); 267 else stopListingSigning(originalSigning); 268 if (logout) disconnectIdentity(identity); 269 release(); 270 const result = await pending, 271 row = await stored(); 272 return { 273 status: result.status, 274 signatures: signs, 275 revision: row.revision, 276 artifact: row.artifact, 277 exposed: result.status === 'prepared', 278 snapshot: listingSigningSnapshot(originalSigning), 279 originalOwner: signer.owner, 280 expectedHash: preview.expectedHash, 281 command 282 }; 283 }, 284 async fault( 285 revision: 1 | 2, 286 unknown: boolean, 287 unavailableReadback = false, 288 tamper: 'none' | 'valid' | 'corrupt' = 'none' 289 ) { 290 const put = Object.getOwnPropertyDescriptor( 291 IDBObjectStore.prototype, 292 'put' 293 ), 294 abort = Object.getOwnPropertyDescriptor( 295 IDBTransaction.prototype, 296 'abort' 297 ); 298 const get = Object.getOwnPropertyDescriptor( 299 IDBObjectStore.prototype, 300 'get' 301 ); 302 if (!put || !abort || !get) throw Error('native descriptors missing'); 303 const nativePut = put.value as IDBObjectStore['put']; 304 const nativeGet = get.value as IDBObjectStore['get']; 305 let faultPuts = 0, 306 nativePuts = 0; 307 Object.defineProperty(IDBObjectStore.prototype, 'put', { 308 ...put, 309 value: function ( 310 this: IDBObjectStore, 311 ...args: Parameters<IDBObjectStore['put']> 312 ) { 313 const value: unknown = args[0]; 314 const wire = 315 typeof value === 'object' && 316 value && 317 'wire' in value && 318 typeof value.wire === 'string' 319 ? value.wire 320 : undefined; 321 const row = wire 322 ? (JSON.parse(wire) as { revision: number }) 323 : undefined; 324 if (this.name === 'public_operations' && row?.revision === revision) { 325 faultPuts++; 326 if (unknown) { 327 const request = nativePut.apply(this, args); 328 nativePuts++; 329 if (tamper !== 'none') 330 request.addEventListener('success', () => { 331 let changedWire = '{"schema":999}'; 332 if (tamper === 'valid') { 333 const originalRow = JSON.parse( 334 wire! 335 ) as PublicOperationRecord; 336 const different = JSON.parse( 337 preview.templateWire 338 ) as typeof signer.template; 339 different.tags = different.tags.map((tag) => 340 tag[0] === 'd' ? ['d', crypto.randomUUID()] : tag 341 ); 342 const signed = signer.sign(different); 343 const templateWire = JSON.stringify({ 344 pubkey: signed.pubkey, 345 kind: signed.kind, 346 created_at: signed.created_at, 347 tags: signed.tags, 348 content: signed.content 349 }); 350 changedWire = JSON.stringify({ 351 ...originalRow, 352 capture: { 353 ...originalRow.capture, 354 wire: templateWire, 355 hash: signed.id 356 }, 357 artifact: { 358 eventId: signed.id, 359 wire: JSON.stringify(signed) 360 } 361 }); 362 if ( 363 !decodePublicRecord(changedWire, signer.owner, command).ok 364 ) 365 throw Error('actual changed signed capture is not valid'); 366 } 367 nativePut.call(this, { 368 owner: signer.owner, 369 id: command, 370 wire: changedWire 371 }); 372 nativePuts++; 373 faultPuts++; 374 }); 375 throw Error('HC_TEST_ONLY actual put lost acknowledgement'); 376 } 377 this.transaction.abort(); 378 throw Error('HC_TEST_ONLY actual definite rollback'); 379 } 380 const request = nativePut.apply(this, args); 381 if (this.name === 'public_operations') nativePuts++; 382 return request; 383 } 384 }); 385 if (unknown) 386 Object.defineProperty(IDBTransaction.prototype, 'abort', { 387 ...abort, 388 value() { 389 throw Error('HC_TEST_ONLY unavailable abort channel'); 390 } 391 }); 392 if (unavailableReadback) 393 Object.defineProperty(IDBObjectStore.prototype, 'get', { 394 ...get, 395 value: function ( 396 this: IDBObjectStore, 397 ...args: Parameters<IDBObjectStore['get']> 398 ) { 399 if (this.name === 'public_operations' && faultPuts > 0) 400 throw Error( 401 'HC_TEST_ONLY actual readback unavailable after committed signed artifact' 402 ); 403 return nativeGet.apply(this, args); 404 } 405 }); 406 let result; 407 try { 408 result = await invoke(); 409 } finally { 410 Object.defineProperty(IDBObjectStore.prototype, 'put', put); 411 Object.defineProperty(IDBTransaction.prototype, 'abort', abort); 412 Object.defineProperty(IDBObjectStore.prototype, 'get', get); 413 } 414 const observed = await readPublicListingIntent( 415 originalRepository, 416 command 417 ); 418 const row = tamper === 'corrupt' ? undefined : await stored(); 419 let corruptWire: string | undefined; 420 if (tamper === 'corrupt') 421 corruptWire = await new Promise<string>((resolve, reject) => { 422 const tx = browserDatabaseTransaction( 423 database, 424 ['public_operations'], 425 'readonly' 426 ); 427 const request = tx 428 .objectStore('public_operations') 429 .get([signer.owner, command]); 430 let wire: string | undefined; 431 request.addEventListener('success', () => { 432 const raw: unknown = request.result; 433 if ( 434 typeof raw === 'object' && 435 raw && 436 'wire' in raw && 437 typeof raw.wire === 'string' 438 ) 439 wire = raw.wire; 440 }); 441 tx.addEventListener('complete', () => 442 wire === undefined 443 ? reject(Error('actual corrupt row missing')) 444 : resolve(wire) 445 ); 446 tx.addEventListener('abort', () => 447 reject(Error('actual raw read aborted')) 448 ); 449 }); 450 const plan = 451 result.status === 'prepared' 452 ? listingPublicationSnapshot(result.publication) 453 : undefined; 454 let retryStatus: string | undefined, 455 retryPuts = 0, 456 retryExact = false; 457 if (unavailableReadback || tamper !== 'none') { 458 Object.defineProperty(IDBObjectStore.prototype, 'put', { 459 ...put, 460 value: function ( 461 this: IDBObjectStore, 462 ...args: Parameters<IDBObjectStore['put']> 463 ) { 464 if (this.name === 'public_operations') retryPuts++; 465 return nativePut.apply(this, args); 466 } 467 }); 468 try { 469 const retry = await invoke(); 470 retryStatus = retry.status; 471 retryExact = 472 retry.status === 'prepared' && 473 listingPublicationSnapshot(retry.publication)?.wire === 474 row?.artifact?.wire; 475 } finally { 476 Object.defineProperty(IDBObjectStore.prototype, 'put', put); 477 } 478 } 479 return { 480 status: result.status, 481 exposed: !!plan, 482 signatures: signs, 483 revision: row?.revision, 484 artifact: row?.artifact, 485 faultPuts, 486 nativePuts, 487 readStatus: observed.status, 488 corruptWire, 489 retryStatus, 490 retryPuts, 491 retryExact, 492 sameArtifact: !!plan && plan.wire === row?.artifact?.wire, 493 originalCapture: row?.capture.wire === preview.templateWire 494 }; 495 }, 496 close() { 497 closePublicDraftController(controller); 498 closeBrowserDatabase(database); 499 closeInboxSetupView(setup); 500 disconnectIdentity(identity); 501 closePublicScheduler(scheduler); 502 signer.close(); 503 if (prior) Object.defineProperty(window, 'nostr', prior); 504 else Reflect.deleteProperty(window, 'nostr'); 505 } 506 }; 507 }