inbox-probe.ts (22974B)
1 import { makeControllerFixture } from './inbox-access-controller.ts'; 2 import { 3 openBrowserDatabase, 4 closeBrowserDatabase, 5 browserDatabaseTransaction 6 } from '../../../src/lib/persistence/database.ts'; 7 import { createPrivateStorageRepository } from '../../../src/lib/persistence/private-storage.ts'; 8 import { 9 validateInboxOperatorQualification, 10 type InboxOperatorQualification 11 } from '../../../src/lib/config/inbox-operators.ts'; 12 import { 13 readRelayPolicy, 14 validateRelayPolicy 15 } from '../../../src/lib/config/relays.ts'; 16 import { 17 createIdentitySession, 18 connectIdentity, 19 probeIdentityMessaging, 20 disconnectIdentity 21 } from '../../../src/lib/runtime/identity-session.ts'; 22 import { 23 createPrivateSession, 24 closePrivateSession, 25 type PrivateSession 26 } from '../../../src/lib/runtime/private-session.ts'; 27 import { 28 reserveInboxProbeIdentity, 29 inboxProbeSnapshot, 30 inboxProbeRumorWire, 31 type InboxProbeIdentity 32 } from '../../../src/lib/nostr/inbox-access.ts'; 33 import { 34 captureInboxProbeSealOperation, 35 buildInboxProbeSeal, 36 type InboxProbeSealOperation, 37 type InboxProbeRecipientSeal 38 } from '../../../src/lib/nostr/seal-builder.ts'; 39 import { 40 buildInboxProbeGiftwrap, 41 inboxProbeGiftwrapSnapshot, 42 type InboxProbeGiftwrap 43 } from '../../../src/lib/nostr/giftwrap-builder.ts'; 44 import { 45 commitInboxProbe, 46 inboxProbeAcknowledgementSnapshot, 47 type InboxProbeAcknowledgement 48 } from '../../../src/lib/persistence/inbox-probes.ts'; 49 import { decodePrivateRecord } from '../../../src/lib/persistence/private-records.ts'; 50 import { 51 getEventHash, 52 generateSecretKey, 53 getPublicKey, 54 type UnsignedEvent 55 } from 'applesauce-core/helpers'; 56 import { verifyEnvelope } from '../../../src/lib/nostr/verified-envelope.ts'; 57 import { nip44 } from 'applesauce-core/helpers/encryption'; 58 export * from '../../../src/lib/nostr/inbox-access.ts'; 59 export * from '../../../src/lib/nostr/seal-builder.ts'; 60 export * from '../../../src/lib/nostr/giftwrap-builder.ts'; 61 export * from '../../../src/lib/nostr/verify-outbound-envelope.ts'; 62 export * from '../../../src/lib/messaging/inbox-access-controller.ts'; 63 export * from '../../../src/lib/messaging/send-identity.ts'; 64 export * from '../../../src/lib/runtime/private-session.ts'; 65 export * from '../../../src/lib/persistence/inbox-probes.ts'; 66 export * from '../../../src/lib/persistence/private-storage.ts'; 67 export * from '../../../src/lib/persistence/private-records.ts'; 68 export * from '../../../src/lib/persistence/private-sends.ts'; 69 export type Mode = 70 | 'normal' 71 | 'hold_key' 72 | 'hold_encrypt' 73 | 'hold_decrypt' 74 | 'hold_sign' 75 | 'wrong_key' 76 | 'refuse_encrypt' 77 | 'refuse_decrypt' 78 | 'refuse_sign' 79 | 'wrong_encrypt' 80 | 'wrong_decrypt' 81 | 'wrong_sign_author' 82 | 'wrong_sign_time' 83 | 'wrong_sign_tags' 84 | 'cached_signature' 85 | 'stop_encrypt_getter' 86 | 'stop_decrypt_getter'; 87 type Provider = { 88 getPublicKey(): Promise<string>; 89 signEvent(input: UnsignedEvent): Promise<Record<string, unknown>>; 90 nip44: { 91 encrypt(target: string, wire: string): Promise<string>; 92 decrypt(target: string, wire: string): Promise<string>; 93 }; 94 }; 95 // Actual source owners/SDK/Chromium storage and random keys, controlled provider 96 // and anonymous discovery transport. No installed extension/operator/Q evidence. 97 export async function makeProbeFixture() { 98 const base = await makeControllerFixture(true), 99 opened = await openBrowserDatabase(); 100 if (opened.state !== 'ready') 101 throw Error('native fixture database unavailable'); 102 const database = opened.owner, 103 repository = createPrivateStorageRepository(database, base.owner); 104 if (!repository) throw Error('actual private namespace'); 105 const provider = Reflect.get(window, 'nostr') as Provider; 106 const key = provider.getPublicKey.bind(provider), 107 sign = provider.signEvent.bind(provider), 108 encrypt = provider.nip44.encrypt.bind(provider.nip44), 109 decrypt = provider.nip44.decrypt.bind(provider.nip44); 110 let mode: Mode = 'normal', 111 release: (() => void) | undefined, 112 waiting = '', 113 keys = 0, 114 encrypts = 0, 115 decrypts = 0, 116 signs = 0; 117 let controller: Awaited<ReturnType<typeof base.capture>> | undefined, 118 identity: InboxProbeIdentity | undefined, 119 operation: InboxProbeSealOperation | undefined, 120 seal: InboxProbeRecipientSeal | undefined, 121 wrap: InboxProbeGiftwrap | undefined; 122 let acknowledgement: InboxProbeAcknowledgement | undefined; 123 async function pause(stage: string) { 124 if (mode !== 'hold_' + stage) return; 125 waiting = stage; 126 await new Promise<void>((resolve) => { 127 release = resolve; 128 }); 129 waiting = ''; 130 release = undefined; 131 } 132 provider.getPublicKey = async () => { 133 keys++; 134 await pause('key'); 135 return mode === 'wrong_key' ? 'f'.repeat(64) : key(); 136 }; 137 provider.signEvent = async (input) => { 138 signs++; 139 await pause('sign'); 140 if (mode === 'refuse_sign') throw Error('controlled refusal'); 141 const changed = 142 mode === 'wrong_sign_time' 143 ? { ...input, created_at: input.created_at + 1 } 144 : mode === 'wrong_sign_tags' 145 ? { ...input, tags: [['p', base.owner]] } 146 : input; 147 if (mode === 'wrong_sign_author') base.mode('author'); 148 let response: Record<string, unknown>; 149 try { 150 response = await sign(changed); 151 } finally { 152 base.mode('exact'); 153 } 154 return mode === 'cached_signature' 155 ? { ...response, sig: '0'.repeat(128) } 156 : response; 157 }; 158 Object.defineProperty(provider, 'nip44', { 159 configurable: true, 160 value: { 161 get encrypt() { 162 if (mode === 'stop_encrypt_getter' && controller) 163 closeInboxAccessController(controller); 164 return async (target: string, wire: string) => { 165 encrypts++; 166 await pause('encrypt'); 167 if (mode === 'refuse_encrypt') throw Error('controlled refusal'); 168 return encrypt( 169 target, 170 mode === 'wrong_encrypt' ? 'substituted rumor' : wire 171 ); 172 }; 173 }, 174 get decrypt() { 175 if (mode === 'stop_decrypt_getter' && controller) 176 closeInboxAccessController(controller); 177 return async (target: string, wire: string) => { 178 decrypts++; 179 await pause('decrypt'); 180 if (mode === 'refuse_decrypt') throw Error('controlled refusal'); 181 return mode === 'wrong_decrypt' 182 ? 'substituted plaintext' 183 : decrypt(target, wire); 184 }; 185 } 186 } 187 }); 188 const operator = (unsupported = false, unconfigured = false) => { 189 const value = validateInboxOperatorQualification( 190 JSON.stringify({ 191 schemaVersion: 1, 192 revision: 1, 193 authority: unconfigured ? 'unconfigured' : 'source_fixture', 194 policyWire: JSON.stringify(readRelayPolicy(base.policy)), 195 evidenceSha256: unconfigured ? null : 'a'.repeat(64), 196 relays: unconfigured 197 ? [] 198 : readRelayPolicy(base.policy).inbox.map(({ origin }) => ({ 199 origin, 200 auth: 'not_required', 201 recipientRead: 'supported', 202 namedArchiveAck: 'supported', 203 exactReadback: unsupported ? 'unsupported' : 'supported', 204 retention: 'operator_defined' 205 })) 206 }) 207 ); 208 if (!value) throw Error('source-labelled operator fixture'); 209 return value; 210 }; 211 const qualification = operator(); 212 let otherIdentity: ReturnType<typeof createIdentitySession> | undefined, 213 otherSession: PrivateSession | undefined; 214 async function stored() { 215 const tx = browserDatabaseTransaction( 216 database, 217 ['private_sends'], 218 'readonly' 219 ), 220 req = tx.objectStore('private_sends').getAll(); 221 return new Promise<{ owner: string; id: string; wire: string }[]>( 222 (resolve, reject) => { 223 tx.addEventListener('complete', () => 224 resolve(req.result as { owner: string; id: string; wire: string }[]) 225 ); 226 tx.addEventListener('abort', () => reject(Error('inspection aborted'))); 227 } 228 ); 229 } 230 async function inject(rows: { owner: string; id: string; wire: string }[]) { 231 const tx = browserDatabaseTransaction( 232 database, 233 ['private_sends'], 234 'readwrite' 235 ); 236 const store = tx.objectStore('private_sends'); 237 for (const row of rows) store.put(row); 238 await new Promise<void>((resolve, reject) => { 239 tx.addEventListener('complete', () => resolve()); 240 tx.addEventListener('abort', () => 241 reject(Error('controlled injection abort')) 242 ); 243 }); 244 } 245 return { 246 ...base, 247 repository, 248 qualification, 249 operator, 250 foreignRepository() { 251 const secret = generateSecretKey(), 252 owner = getPublicKey(secret); 253 secret.fill(0); 254 const result = createPrivateStorageRepository(database, owner); 255 if (!result) throw Error('actual foreign namespace'); 256 return result; 257 }, 258 copiedPolicy() { 259 const result = validateRelayPolicy( 260 JSON.stringify(readRelayPolicy(base.policy)) 261 ); 262 if (!result) throw Error('genuine alternate policy token'); 263 return result; 264 }, 265 async foreignSession() { 266 otherIdentity = createIdentitySession(); 267 await connectIdentity(otherIdentity); 268 await probeIdentityMessaging(otherIdentity, 'reviewed_self_copy'); 269 otherSession = await createPrivateSession( 270 otherIdentity, 271 'reviewed_private_session' 272 ); 273 if (!otherSession) throw Error('genuine same-owner other session'); 274 return otherSession; 275 }, 276 async capture() { 277 controller = await base.capture(); 278 return controller; 279 }, 280 controller: () => controller, 281 probeIdentity: () => identity, 282 operation: () => operation, 283 seal: () => seal, 284 wrap: () => wrap, 285 acknowledgement: () => acknowledgement, 286 async commitOriginal(review: unknown = 'reviewed_inbox_probe_commit') { 287 if (!wrap) throw Error('missing genuine original wrap'); 288 const result = await commitInboxProbe( 289 repository, 290 base.session, 291 wrap, 292 review 293 ); 294 if ('acknowledgement' in result) acknowledgement = result.acknowledgement; 295 return { 296 status: result.status, 297 snapshot: 298 'acknowledgement' in result 299 ? inboxProbeAcknowledgementSnapshot(result.acknowledgement) 300 : undefined 301 }; 302 }, 303 mode(next: Mode) { 304 mode = next; 305 }, 306 waiting: () => waiting, 307 settle: () => release?.(), 308 counts: () => ({ keys, encrypts, decrypts, signs }), 309 stored, 310 inject, 311 async removeOriginal() { 312 if (!identity) throw Error('missing genuine original'); 313 const record = inboxProbeSnapshot(identity); 314 if (!record) throw Error('stale actual original'); 315 const tx = browserDatabaseTransaction( 316 database, 317 ['private_sends'], 318 'readwrite' 319 ); 320 tx.objectStore('private_sends').delete([base.owner, record.id]); 321 await new Promise<void>((resolve, reject) => { 322 tx.addEventListener('complete', () => resolve()); 323 tx.addEventListener('abort', () => 324 reject(Error('controlled removal abort')) 325 ); 326 }); 327 }, 328 installCommitCompletion(action: () => void) { 329 const original = Object.getOwnPropertyDescriptor( 330 IDBDatabase.prototype, 331 'transaction' 332 )?.value as IDBDatabase['transaction']; 333 let fired = false; 334 IDBDatabase.prototype.transaction = function ( 335 ...args: Parameters<IDBDatabase['transaction']> 336 ) { 337 const tx = original.apply(this, args); 338 if ( 339 !fired && 340 args[1] === 'readwrite' && 341 tx.objectStoreNames.contains('private_sends') 342 ) { 343 fired = true; 344 tx.addEventListener('complete', action); 345 } 346 return tx; 347 }; 348 return () => { 349 IDBDatabase.prototype.transaction = original; 350 }; 351 }, 352 async fillProbeByteHeadroom() { 353 if (!identity || !wrap) throw Error('missing genuine original'); 354 const record = inboxProbeSnapshot(identity), 355 artifact = inboxProbeGiftwrapSnapshot(wrap); 356 if (!record || !artifact) throw Error('stale genuine original'); 357 const self = { 358 eventId: (JSON.parse(artifact.wire) as { id: string }).id, 359 wire: artifact.wire 360 }; 361 // Strict structural filler metadata is not actual transport/nonce evidence. 362 const filler = { 363 ...record, 364 id: crypto.randomUUID(), 365 revision: 1, 366 self, 367 receipts: [] as unknown[] 368 }; 369 const fact = { 370 actionId: crypto.randomUUID(), 371 origin: record.binding.archiveTargets[0], 372 role: 'access_archive', 373 attempt: 1, 374 eventId: self.eventId, 375 status: 'accepted', 376 observedAtMilliseconds: 1, 377 readbackWire: null 378 }; 379 const originalRows = await stored(); 380 const physicalBytes = (rows: typeof originalRows) => 381 rows.reduce( 382 (n, row) => n + new TextEncoder().encode(JSON.stringify(row)).length, 383 0 384 ); 385 const baseBytes = physicalBytes(originalRows); 386 const prepared = JSON.stringify({ ...record, revision: 1, self }); 387 const growth = 388 physicalBytes([{ owner: base.owner, id: record.id, wire: prepared }]) - 389 baseBytes; 390 const rowAt = (n: number) => ({ 391 owner: base.owner, 392 id: filler.id, 393 wire: JSON.stringify({ 394 ...filler, 395 receipts: Array.from({ length: n }, () => fact) 396 }) 397 }); 398 const cap = 8 * 1024 * 1024; 399 const factBytes = physicalBytes([rowAt(1)]) - physicalBytes([rowAt(0)]); 400 let low = 0, 401 high = Math.floor(cap / factBytes) + 2; 402 while (low + 1 < high) { 403 const mid = Math.floor((low + high) / 2); 404 if (baseBytes + physicalBytes([rowAt(mid)]) <= cap) low = mid; 405 else high = mid; 406 } 407 const row = rowAt(low); 408 const strict = decodePrivateRecord(row.wire, row.owner, row.id); 409 if (!strict.ok) throw Error('filler must decode strictly'); 410 await inject([row]); 411 const before = await stored(), 412 bytes = physicalBytes(before), 413 headroom = cap - bytes; 414 if (headroom < 0 || headroom >= growth || before.length >= 100) 415 throw Error('actual physical growth boundary missing'); 416 return { bytes, headroom, growth, count: before.length }; 417 }, 418 async fillCapacity(count = 100) { 419 const secret = generateSecretKey(), 420 peer = getPublicKey(secret); 421 secret.fill(0); 422 const tx = browserDatabaseTransaction( 423 database, 424 ['private_sends'], 425 'readwrite' 426 ), 427 store = tx.objectStore('private_sends'); 428 for (let i = 0; i < count; i++) { 429 const id = crypto.randomUUID(); 430 store.put({ 431 owner: base.owner, 432 id, 433 wire: JSON.stringify({ 434 schema: 1, 435 family: 'private_send_reservation', 436 owner: base.owner, 437 id, 438 revision: 0, 439 peer, 440 rumorHash: 'a'.repeat(64), 441 createdAt: 1 442 }) 443 }); 444 } 445 await new Promise<void>((resolve, reject) => { 446 tx.addEventListener('complete', () => resolve()); 447 tx.addEventListener('abort', () => 448 reject(Error('fixture capacity abort')) 449 ); 450 }); 451 }, 452 installNativeAbort() { 453 const original = Object.getOwnPropertyDescriptor( 454 IDBObjectStore.prototype, 455 'put' 456 )?.value as IDBObjectStore['put']; 457 let fired = false; 458 IDBObjectStore.prototype.put = function ( 459 ...args: Parameters<IDBObjectStore['put']> 460 ) { 461 const request = original.apply(this, args); 462 if (!fired && this.name === 'private_sends') { 463 fired = true; 464 const transaction = this.transaction; 465 request.addEventListener('success', () => transaction.abort()); 466 } 467 return request; 468 }; 469 return () => { 470 IDBObjectStore.prototype.put = original; 471 }; 472 }, 473 installUncertainCommit() { 474 const put = Object.getOwnPropertyDescriptor( 475 IDBObjectStore.prototype, 476 'put' 477 )?.value as IDBObjectStore['put']; 478 const abort = Object.getOwnPropertyDescriptor( 479 IDBTransaction.prototype, 480 'abort' 481 )?.value as IDBTransaction['abort']; 482 let selected: IDBTransaction | undefined, 483 nativeComplete = 0, 484 nativeAbort = 0, 485 putSuccess = 0, 486 abortRefused = 0; 487 IDBTransaction.prototype.abort = function ( 488 ...args: Parameters<IDBTransaction['abort']> 489 ) { 490 if (this === selected) { 491 abortRefused++; 492 throw Error('controlled abort refusal'); 493 } 494 return abort.apply(this, args); 495 }; 496 IDBObjectStore.prototype.put = function ( 497 ...args: Parameters<IDBObjectStore['put']> 498 ) { 499 const request = put.apply(this, args); 500 if (!selected && this.name === 'private_sends') { 501 selected = this.transaction; 502 selected.addEventListener('complete', () => { 503 nativeComplete++; 504 }); 505 selected.addEventListener('abort', () => { 506 nativeAbort++; 507 }); 508 request.addEventListener('success', () => { 509 putSuccess++; 510 }); 511 throw Error('controlled failure after actual native put admission'); 512 } 513 return request; 514 }; 515 return { 516 counts: () => ({ 517 nativeComplete, 518 nativeAbort, 519 putSuccess, 520 abortRefused 521 }), 522 restore: () => { 523 IDBObjectStore.prototype.put = put; 524 IDBTransaction.prototype.abort = abort; 525 } 526 }; 527 }, 528 installChangedReadback() { 529 const original = Object.getOwnPropertyDescriptor( 530 IDBDatabase.prototype, 531 'transaction' 532 )?.value as IDBDatabase['transaction']; 533 let fired = false; 534 IDBDatabase.prototype.transaction = function ( 535 ...args: Parameters<IDBDatabase['transaction']> 536 ) { 537 const tx = original.apply(this, args); 538 if ( 539 !fired && 540 args[1] === 'readwrite' && 541 tx.objectStoreNames.contains('private_sends') 542 ) { 543 fired = true; 544 tx.addEventListener('complete', () => { 545 const next = original.call(this, ['private_sends'], 'readwrite'), 546 store = next.objectStore('private_sends'), 547 rows = store.getAll(); 548 rows.addEventListener('success', () => { 549 for (const row of rows.result as { 550 owner: string; 551 id: string; 552 wire: string; 553 }[]) { 554 if (row.owner !== base.owner) continue; 555 const parsed = JSON.parse(row.wire) as { createdAt: number }; 556 parsed.createdAt++; 557 store.put({ ...row, wire: JSON.stringify(parsed) }); 558 } 559 }); 560 }); 561 } 562 return tx; 563 }; 564 return () => { 565 IDBDatabase.prototype.transaction = original; 566 }; 567 }, 568 async reserve( 569 selected: InboxOperatorQualification = qualification, 570 review = 'reviewed_inbox_probe_reservation' 571 ) { 572 if (!controller) throw Error('missing genuine controller'); 573 const result = await reserveInboxProbeIdentity( 574 repository, 575 base.session, 576 base.policy, 577 controller, 578 selected, 579 review 580 ); 581 if ('identity' in result) identity = result.identity; 582 return { 583 status: result.status, 584 disposition: result.disposition, 585 snapshot: identity && inboxProbeSnapshot(identity) 586 }; 587 }, 588 async prepareSeal() { 589 if (!identity) throw Error('missing genuine reserved probe'); 590 operation = captureInboxProbeSealOperation( 591 base.session, 592 identity, 593 'reviewed_inbox_probe_seal' 594 ); 595 if (!operation) return 'unavailable'; 596 const result = await buildInboxProbeSeal(operation); 597 if (result.status === 'sealed') { 598 seal = result.seal; 599 return 'sealed'; 600 } 601 return result.status; 602 }, 603 wrapOriginal() { 604 if (!seal) throw Error('missing genuine original seal'); 605 wrap = buildInboxProbeGiftwrap(seal, 'reviewed_inbox_probe_wrap'); 606 return wrap ? 'wrapped' : 'wrap_failed'; 607 }, 608 async prepare() { 609 const result = await this.prepareSeal(); 610 return result === 'sealed' ? this.wrapOriginal() : result; 611 }, 612 installWrapFault() { 613 const original = Object.getOwnPropertyDescriptor(nip44.v2, 'encrypt') 614 ?.value as typeof nip44.v2.encrypt; 615 let failing = true, 616 calls = 0; 617 nip44.v2.encrypt = (...args: Parameters<typeof nip44.v2.encrypt>) => { 618 calls++; 619 if (failing) throw Error('controlled SDK wrapper failure'); 620 return original.apply(nip44.v2, args); 621 }; 622 return { 623 allow: () => { 624 failing = false; 625 }, 626 calls: () => calls, 627 restore: () => { 628 nip44.v2.encrypt = original; 629 } 630 }; 631 }, 632 async decryptOriginal() { 633 if (!identity || !wrap) throw Error('missing genuine artifact'); 634 const snapshot = inboxProbeSnapshot(identity), 635 artifact = inboxProbeGiftwrapSnapshot(wrap), 636 original = inboxProbeRumorWire(identity, base.session); 637 if (!snapshot || !artifact || !original) 638 throw Error('stale actual artifact'); 639 const outer = JSON.parse(artifact.wire) as { 640 pubkey: string; 641 content: string; 642 }, 643 sealWire = await decrypt(outer.pubkey, outer.content), 644 signed = verifyEnvelope(sealWire), 645 nested = JSON.parse(sealWire) as { pubkey: string; content: string }, 646 rumorWire = await decrypt(nested.pubkey, nested.content), 647 rumor = JSON.parse(rumorWire) as UnsignedEvent & { id: string }; 648 return { 649 outerVerified: verifyEnvelope(artifact.wire).ok, 650 sealVerified: signed.ok, 651 exactRumor: rumorWire === original, 652 hash: 653 getEventHash(rumor) === snapshot.rumorHash && 654 rumor.id === snapshot.rumorHash, 655 owner: rumor.pubkey === base.owner, 656 recipient: 657 JSON.stringify(rumor.tags) === JSON.stringify([['p', base.owner]]), 658 createdAt: rumor.created_at === snapshot.createdAt, 659 kind: rumor.kind, 660 diagnostic: 661 /^Harvestcircle private inbox access check v1: [0-9a-f]{64}$/.test( 662 rumor.content 663 ) 664 }; 665 }, 666 close() { 667 release?.(); 668 if (otherSession) closePrivateSession(otherSession); 669 if (otherIdentity) disconnectIdentity(otherIdentity); 670 base.close(); 671 closeBrowserDatabase(database); 672 } 673 }; 674 } 675 import { closeInboxAccessController } from '../../../src/lib/messaging/inbox-access-controller.ts';