inbox-access-qualification.spec.ts (47852B)
1 import { test, expect, type Page } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { once } from 'node:events'; 4 import { fileURLToPath } from 'node:url'; 5 import { WebSocketServer, type WebSocket } from 'ws'; 6 import { createStaticHarness } from '../integration/harness/static.ts'; 7 import type * as Fixture from './harness/inbox-access-qualification.ts'; 8 import type { PrivateAccessProbe } from '../../src/lib/persistence/private-records.ts'; 9 declare global { 10 interface Window { 11 qa: typeof Fixture; 12 qaFixture: Awaited<ReturnType<typeof Fixture.makeQualificationFixture>>; 13 qaPending?: Promise<unknown>; 14 qaRestore?: () => void; 15 qaFinishAttempt?: () => Promise<string>; 16 qaRelease?: () => void; 17 qaCloseMode?: 'hold' | 'fail'; 18 qaHeldClose?: (() => void)[]; 19 qaCloseCalls?: number; 20 } 21 } 22 let server: Awaited<ReturnType<typeof createStaticHarness>>, 23 sockets: WebSocketServer, 24 endpoint: string, 25 bundle: string, 26 head = ''; 27 let ackMode: 'accept' | 'refuse' | 'hold' = 'accept'; 28 let authMode: 'accept' | 'refuse' | 'hold' = 'accept'; 29 let holdRead = false, 30 challenge = false; 31 const origins = [ 32 'wss://inbox.example.org', 33 'wss://peer.example.org', 34 'wss://archive.example.org' 35 ], 36 physical = new Set<WebSocket>(), 37 physicalOrigins = new WeakMap<WebSocket, string>(), 38 archived = new Map<string, unknown>(), 39 frames: { origin: string; frame: unknown[] }[] = []; 40 test.beforeAll(async () => { 41 server = await createStaticHarness(); 42 sockets = new WebSocketServer({ 43 host: '127.0.0.1', 44 port: 0, 45 maxPayload: 65536 46 }); 47 await once(sockets, 'listening'); 48 const address = sockets.address(); 49 if (!address || typeof address === 'string') 50 throw Error('actual loopback endpoint'); 51 endpoint = 'ws://127.0.0.1:' + address.port; 52 sockets.on('connection', (socket, request) => { 53 physical.add(socket); 54 socket.on('close', () => physical.delete(socket)); 55 const origin = new URL(request.url!, 'http://127.0.0.1').searchParams.get( 56 'origin' 57 )!; 58 physicalOrigins.set(socket, origin); 59 if (challenge && origin !== 'wss://discovery.example.org') 60 socket.send(JSON.stringify(['AUTH', 's5a-source-challenge'])); 61 socket.on('message', (bytes) => { 62 const raw = Buffer.isBuffer(bytes) 63 ? bytes 64 : Array.isArray(bytes) 65 ? Buffer.concat(bytes) 66 : Buffer.from(bytes), 67 frame = JSON.parse(raw.toString()) as unknown[]; 68 if (frames.length >= 1000) throw Error('controlled fixture frame bound'); 69 frames.push({ origin, frame }); 70 if (frame[0] === 'REQ') { 71 const filter = frame[2] as { kinds?: number[]; ids?: string[] }; 72 if (filter.kinds?.includes(10050) && head) 73 socket.send(JSON.stringify(['EVENT', frame[1], JSON.parse(head)])); 74 if (filter.kinds?.includes(1059)) { 75 if (holdRead) return; 76 const event = archived.get(JSON.stringify([origin, filter.ids?.[0]])); 77 if (event) socket.send(JSON.stringify(['EVENT', frame[1], event])); 78 } 79 socket.send(JSON.stringify(['EOSE', frame[1]])); 80 } else if (frame[0] === 'AUTH') { 81 const event = frame[1] as { id: string }; 82 if (authMode !== 'hold') 83 socket.send( 84 JSON.stringify([ 85 'OK', 86 event.id, 87 authMode === 'accept', 88 'controlled auth response' 89 ]) 90 ); 91 } else if (frame[0] === 'EVENT') { 92 const event = frame[1] as { id: string }; 93 if (ackMode === 'accept') 94 archived.set(JSON.stringify([origin, event.id]), event); 95 if (ackMode !== 'hold') 96 socket.send( 97 JSON.stringify([ 98 'OK', 99 event.id, 100 ackMode === 'accept', 101 'controlled refusal' 102 ]) 103 ); 104 } 105 }); 106 }); 107 const result = await build({ 108 configFile: false, 109 logLevel: 'silent', 110 build: { 111 write: false, 112 minify: false, 113 lib: { 114 entry: fileURLToPath( 115 new URL('./harness/inbox-access-qualification.ts', import.meta.url) 116 ), 117 name: 'qa', 118 formats: ['iife'] 119 } 120 } 121 }); 122 const output = Array.isArray(result) ? result[0] : result; 123 if (!('output' in output)) throw Error('actual compiled nonce-facts harness'); 124 const chunks = output.output.filter((x) => x.type === 'chunk'); 125 expect(chunks).toHaveLength(1); 126 bundle = chunks[0].code; 127 }); 128 test.afterAll(async () => { 129 for (const socket of sockets.clients) socket.terminate(); 130 await new Promise<void>((resolve) => sockets.close(() => resolve())); 131 await server.close(); 132 }); 133 test.beforeEach(async ({ page }, testInfo) => { 134 await expect.poll(() => physical.size).toBe(0); 135 ackMode = 'accept'; 136 authMode = 'accept'; 137 holdRead = false; 138 challenge = false; 139 archived.clear(); 140 frames.length = 0; 141 head = ''; 142 await page.addInitScript( 143 ({ endpoint, origins }) => { 144 const Native = window.WebSocket; 145 window.WebSocket = class extends Native { 146 constructor(url: string | URL, protocols?: string | string[]) { 147 const origin = new URL(String(url)).origin; 148 if (!['wss://discovery.example.org', ...origins].includes(origin)) 149 throw Error('unapproved fixture origin'); 150 super(endpoint + '/?origin=' + encodeURIComponent(origin), protocols); 151 } 152 override close(code?: number, reason?: string) { 153 window.qaCloseCalls = (window.qaCloseCalls ?? 0) + 1; 154 if (window.qaCloseMode === 'fail') 155 throw Error('actual controlled physical close failure'); 156 if (window.qaCloseMode === 'hold') 157 (window.qaHeldClose ??= []).push(() => super.close(code, reason)); 158 else super.close(code, reason); 159 } 160 }; 161 }, 162 { endpoint, origins } 163 ); 164 await page.goto(server.url + '/search'); 165 await page.addScriptTag({ content: bundle }); 166 head = await page.evaluate( 167 async ({ origins, authRequired }) => { 168 window.qaFixture = await window.qa.makeQualificationFixture(authRequired); 169 return window.qaFixture.host.preferenceWire(origins); 170 }, 171 { origins, authRequired: testInfo.title.includes('required AUTH') } 172 ); 173 await page.evaluate(async () => { 174 const f = window.qaFixture; 175 await f.open(); 176 if ((await f.prepareOriginal()).status !== 'prepared') 177 throw Error('actual original S3/R1'); 178 }); 179 }); 180 test.afterEach(async ({ page }) => { 181 if (!page.isClosed()) 182 await page.evaluate(async () => { 183 window.qaRestore?.(); 184 window.qaCloseMode = undefined; 185 for (const release of window.qaHeldClose ?? []) release(); 186 window.qaRelease?.(); 187 window.qaFixture.host.mode('normal'); 188 window.qaFixture.host.settle(); 189 window.qaFixture.close(); 190 await window.qaPending; 191 }); 192 }); 193 194 async function prepare(page: Page, recovered: boolean) { 195 expect( 196 await page.evaluate( 197 async (recovered) => (await window.qaFixture.qualify(recovered)).status, 198 recovered 199 ) 200 ).toBe('saved'); 201 } 202 for (const recovered of [false, true]) { 203 for (const mode of ['hold', 'fail'] as const) 204 test(`${recovered ? 'REC' : 'original'} qualification respects actual ${mode} physical cleanup without implicit retries`, async ({ 205 page 206 }) => { 207 await prepare(page, recovered); 208 await page.evaluate(async () => { 209 const f = window.qaFixture, 210 pool = window.qa.getPrivatePool( 211 f.actors().session, 212 f.host.policy, 213 ['wss://inbox.example.org'], 214 Object.freeze({}), 215 'receive' 216 ); 217 if (!pool) throw Error('actual independent receive scope'); 218 const auth = await window.qa.beginInboxAuthentication( 219 pool, 220 'wss://inbox.example.org', 221 'reviewed_connection_auth' 222 ); 223 if (!auth) throw Error('actual independent AUTH connection'); 224 window.qaRelease = () => { 225 window.qa.closeInboxAuthentication(auth); 226 window.qa.closePrivatePool(pool); 227 }; 228 }); 229 await expect 230 .poll(() => 231 [...physical].some( 232 (socket) => 233 physicalOrigins.get(socket) === 'wss://inbox.example.org' 234 ) 235 ) 236 .toBe(true); 237 const result = await page.evaluate(async (mode) => { 238 const f = window.qaFixture; 239 window.qaCloseMode = mode; 240 let failed = false; 241 try { 242 window.qaRelease!(); 243 } catch { 244 failed = true; 245 } 246 const before = f.host.counts(), 247 closes = window.qaCloseCalls ?? 0, 248 held = window.qaHeldClose?.length ?? 0, 249 hook = f.nativeFault('read_loss'); 250 try { 251 const result = await f.qualifyAccess(); 252 return { 253 status: result.status, 254 current: !!window.qa.inboxProbeNonceAcknowledgementBinding( 255 f.repository, 256 f.actors().session, 257 f.nonce()!, 258 f.host.policy 259 ), 260 before, 261 after: f.host.counts(), 262 closes, 263 afterCloses: window.qaCloseCalls ?? 0, 264 held, 265 afterHeld: window.qaHeldClose?.length ?? 0, 266 failed, 267 native: hook.counts() 268 }; 269 } finally { 270 hook.restore(); 271 } 272 }, mode); 273 expect(result.status).toBe('busy'); 274 expect(result.current).toBe(true); 275 expect(result.after).toEqual(result.before); 276 expect(result.native.readonly).toBe(0); 277 expect(result.afterCloses).toBe(result.closes); 278 expect(result.afterHeld).toBe(result.held); 279 if (mode === 'fail') expect(result.failed).toBe(true); 280 else expect(result.held).toBeGreaterThan(0); 281 await page.evaluate(() => { 282 window.qaCloseMode = undefined; 283 for (const release of window.qaHeldClose ?? []) release(); 284 try { 285 window.qaRelease!(); 286 } catch (error) { 287 if ( 288 !(error instanceof Error) || 289 ![ 290 'private_pool_close_pending', 291 'private_pool_close_failed' 292 ].includes(error.message) 293 ) 294 throw error; 295 } 296 }); 297 await expect 298 .poll(() => page.evaluate(() => window.qaFixture.idle())) 299 .toBe(true); 300 expect( 301 await page.evaluate( 302 async () => (await window.qaFixture.qualifyAccess()).status 303 ) 304 ).toBe('qualified'); 305 }); 306 for (const foreign of [ 307 'operator', 308 'policy', 309 'controller', 310 'session', 311 'repository' 312 ] as const) 313 test(`${recovered ? 'REC' : 'original'} removed qualification rejects different genuine or copied ${foreign} with no effects`, async ({ 314 page 315 }) => { 316 await prepare(page, recovered); 317 const result = await page.evaluate(async (foreign) => { 318 const f = window.qaFixture; 319 if (!(await f.select()) || (await f.remove()).status !== 'removed') 320 throw Error('actual reviewed removal'); 321 const a = f.actors(), 322 other = 323 foreign === 'controller' 324 ? { 325 access: (await f.replaceController())!, 326 session: a.session, 327 close() {} 328 } 329 : foreign === 'session' 330 ? await f.alternateController(true) 331 : undefined, 332 opened = 333 foreign === 'repository' 334 ? await window.qa.openBrowserDatabase() 335 : undefined, 336 repository = 337 opened?.state === 'ready' 338 ? window.qa.createPrivateStorageRepository( 339 opened.owner, 340 f.host.owner 341 )! 342 : f.repository, 343 policy = 344 foreign === 'policy' 345 ? window.qa.validateRelayPolicy( 346 JSON.stringify(window.qa.readRelayPolicy(f.host.policy)) 347 )! 348 : f.host.policy, 349 operator = 350 foreign === 'operator' 351 ? window.qa.validateInboxOperatorQualification( 352 window.qa.inboxOperatorQualificationWire( 353 f.host.qualification, 354 f.host.policy 355 )! 356 )! 357 : f.host.qualification, 358 before = f.host.counts(), 359 hook = f.nativeFault('read_loss'); 360 try { 361 const result = window.qa.qualifyRemovedInboxAccess( 362 repository, 363 other?.session ?? a.session, 364 policy, 365 other?.access ?? a.access, 366 operator, 367 f.removal()!, 368 'reviewed_qualify_inbox_access' 369 ); 370 return { 371 status: result.status, 372 before, 373 after: f.host.counts(), 374 native: hook.counts() 375 }; 376 } finally { 377 hook.restore(); 378 other?.close(); 379 if (opened?.state === 'ready') 380 window.qa.closeBrowserDatabase(opened.owner); 381 } 382 }, foreign); 383 expect(result.status).toBe('invalid_scope'); 384 expect(result.after).toEqual(result.before); 385 expect(result.native.readonly).toBe(0); 386 expect(result.native.deletes).toBe(0); 387 }); 388 for (const forged of ['nonce', 'observations'] as const) 389 test(`${recovered ? 'REC' : 'original'} copied genuine ${forged} cannot substitute for applied source provenance`, async ({ 390 page 391 }) => { 392 await prepare(page, recovered); 393 const result = await page.evaluate(async (forged) => { 394 const f = window.qaFixture, 395 a = f.actors(), 396 before = f.host.counts(), 397 hook = f.nativeFault('read_loss'); 398 try { 399 const result = await window.qa.qualifyInboxAccess( 400 f.repository, 401 a.session, 402 f.host.policy, 403 a.access, 404 f.host.qualification, 405 forged === 'nonce' ? { ...f.nonce()! } : f.nonce()!, 406 forged === 'observations' 407 ? f.observations().map((x) => ({ ...x })) 408 : f.observations(), 409 'reviewed_qualify_inbox_access' 410 ); 411 return { 412 status: result.status, 413 before, 414 after: f.host.counts(), 415 native: hook.counts() 416 }; 417 } finally { 418 hook.restore(); 419 } 420 }, forged); 421 expect(result.status).toBe('invalid_scope'); 422 expect(result.after).toEqual(result.before); 423 expect(result.native.readonly).toBe(0); 424 }); 425 test(`${recovered ? 'REC' : 'original'} a copied genuine removal cannot issue access and the exact real removal remains eligible`, async ({ 426 page 427 }) => { 428 await prepare(page, recovered); 429 const result = await page.evaluate(async () => { 430 const f = window.qaFixture, 431 a = f.actors(); 432 if (!(await f.select()) || (await f.remove()).status !== 'removed') 433 throw Error('actual successful reviewed removal'); 434 const before = f.host.counts(), 435 forged = window.qa.qualifyRemovedInboxAccess( 436 f.repository, 437 a.session, 438 f.host.policy, 439 a.access, 440 f.host.qualification, 441 { ...f.removal()! }, 442 'reviewed_qualify_inbox_access' 443 ), 444 genuine = f.qualifyRemoved(); 445 return { 446 forged: forged.status, 447 genuine: genuine.status, 448 before, 449 after: f.host.counts() 450 }; 451 }); 452 expect(result.forged).toBe('invalid_scope'); 453 expect(result.genuine).toBe('qualified'); 454 expect(result.after).toEqual(result.before); 455 }); 456 test(`${recovered ? 'REC' : 'original'} wrong fresh owner key cannot qualify`, async ({ 457 page 458 }) => { 459 await prepare(page, recovered); 460 const result = await page.evaluate(async () => { 461 const f = window.qaFixture, 462 before = f.host.counts(), 463 hook = f.nativeFault('read_loss'); 464 f.host.mode('wrong_key'); 465 try { 466 const result = await f.qualifyAccess(); 467 return { 468 status: result.status, 469 before, 470 after: f.host.counts(), 471 native: hook.counts() 472 }; 473 } finally { 474 f.host.mode('normal'); 475 hook.restore(); 476 } 477 }); 478 expect(result.status).toBe('stopped'); 479 expect(result.after).toEqual({ 480 ...result.before, 481 keys: result.before.keys + 1 482 }); 483 expect(result.native.readonly).toBe(0); 484 }); 485 test(`${recovered ? 'REC' : 'original'} explicit qualification Stop prevents reuse of the same genuine nonce`, async ({ 486 page 487 }) => { 488 await prepare(page, recovered); 489 const result = await page.evaluate(async () => { 490 const f = window.qaFixture, 491 first = await f.qualifyAccess(), 492 token = first.qualification!, 493 context = f.context(), 494 before = f.host.counts(); 495 window.qa.stopInboxAccessQualification(token); 496 const again = await f.qualifyAccess(); 497 return { 498 current: 499 window.qa.observeQualifiedInboxAccess(token)(context)?.current() ?? 500 false, 501 snapshot: window.qa.inboxAccessQualificationSnapshot(token), 502 status: again.status, 503 before, 504 after: f.host.counts() 505 }; 506 }); 507 expect(result).toMatchObject({ current: false, status: 'stopped' }); 508 expect(result.snapshot).toBeUndefined(); 509 expect(result.after).toEqual(result.before); 510 }); 511 test(`${recovered ? 'REC' : 'original'} unrelated actual SDK local storage work does not invalidate issued access`, async ({ 512 page 513 }) => { 514 await prepare(page, recovered); 515 const result = await page.evaluate(async () => { 516 const f = window.qaFixture; 517 await f.qualifyAccess(); 518 const context = f.context(), 519 before = f.host.counts(); 520 const during = await f.withHeld('SDK', async () => ({ 521 current: f.observation(context)?.current(), 522 status: (await f.qualifyAccess()).status 523 })); 524 return { 525 during, 526 afterCurrent: f.observation(context)?.current(), 527 before, 528 after: f.host.counts() 529 }; 530 }); 531 expect(result).toMatchObject({ 532 during: { current: true, status: 'qualified' }, 533 afterCurrent: true 534 }); 535 expect(result.after).toEqual(result.before); 536 }); 537 for (const lane of ['archive', 'read'] as const) 538 test(`${recovered ? 'REC' : 'original'} later actual selected ${lane} immediately and permanently invalidates issued access`, async ({ 539 page 540 }) => { 541 await prepare(page, recovered); 542 expect( 543 await page.evaluate( 544 async () => (await window.qaFixture.qualifyAccess()).status 545 ) 546 ).toBe('qualified'); 547 const mark = traffic().length; 548 if (lane === 'archive') ackMode = 'hold'; 549 else holdRead = true; 550 await page.evaluate( 551 ({ recovered, lane }) => { 552 const f = window.qaFixture; 553 window.qaPending = 554 lane === 'archive' 555 ? recovered 556 ? f.publish('wss://peer.example.org') 557 : f.originalPublish('wss://peer.example.org') 558 : recovered 559 ? f.read('wss://peer.example.org') 560 : f.originalRead('wss://peer.example.org'); 561 }, 562 { recovered, lane } 563 ); 564 await expect.poll(() => traffic().length).toBeGreaterThan(mark); 565 const during = await page.evaluate(async () => { 566 const f = window.qaFixture, 567 before = f.host.counts(), 568 result = await f.qualifyAccess(); 569 return { 570 status: result.status, 571 current: f.observation(f.context())?.current() ?? false, 572 before, 573 after: f.host.counts() 574 }; 575 }); 576 expect(during.status).toBe('stopped'); 577 expect(during.current).toBe(false); 578 expect(during.after).toEqual(during.before); 579 const actual = traffic() 580 .slice(mark) 581 .find((x) => x.frame[0] === (lane === 'archive' ? 'EVENT' : 'REQ'))!; 582 for (const socket of physical) 583 if (physicalOrigins.get(socket) === actual.origin) { 584 if (lane === 'archive') { 585 const event = actual.frame[1] as { id: string }; 586 archived.set(JSON.stringify([actual.origin, event.id]), event); 587 socket.send( 588 JSON.stringify([ 589 'OK', 590 event.id, 591 true, 592 'actual held archive accepted' 593 ]) 594 ); 595 } else socket.send(JSON.stringify(['EOSE', actual.frame[1]])); 596 } 597 const final = await page.evaluate(async () => { 598 const attempt = (await window.qaPending) as { status: string }; 599 const f = window.qaFixture, 600 before = f.host.counts(), 601 again = await f.qualifyAccess(); 602 return { 603 attempt: attempt.status, 604 status: again.status, 605 current: f.observation(f.context())?.current() ?? false, 606 before, 607 after: f.host.counts() 608 }; 609 }); 610 expect(final.attempt).toBe(lane === 'archive' ? 'accepted' : 'empty'); 611 expect(final.status).toBe('stopped'); 612 expect(final.current).toBe(false); 613 expect(final.after).toEqual(final.before); 614 }); 615 test(`${recovered ? 'REC' : 'original'} unapplied archive blocks first qualification and later append cannot revive that input`, async ({ 616 page 617 }) => { 618 await prepare(page, recovered); 619 const result = await page.evaluate(async (recovered) => { 620 const f = window.qaFixture, 621 archive = await (recovered 622 ? f.publish('wss://peer.example.org') 623 : f.originalPublish('wss://peer.example.org')); 624 if (!archive || archive.status !== 'accepted') 625 throw Error('actual accepted archive'); 626 const before = f.host.counts(), 627 first = await f.qualifyAccess(), 628 after = f.host.counts(), 629 appended = await f.append(archive), 630 again = await f.qualifyAccess([...f.observations(), archive]); 631 return { 632 first: first.status, 633 again: again.status, 634 appended: appended.status, 635 before, 636 after 637 }; 638 }, recovered); 639 expect(result).toMatchObject({ 640 first: 'stopped', 641 again: 'stopped', 642 appended: 'saved' 643 }); 644 expect(result.after).toEqual(result.before); 645 }); 646 test(`${recovered ? 'REC' : 'original'} an actual cleanup lease and aborted delete permanently retire the issued journal fence`, async ({ 647 page 648 }) => { 649 await prepare(page, recovered); 650 const result = await page.evaluate(async () => { 651 const f = window.qaFixture, 652 first = await f.qualifyAccess(), 653 old = window.qa.observeQualifiedInboxAccess(first.qualification!)( 654 f.context() 655 )!; 656 if (!(await f.select())) throw Error('actual selected cleanup'); 657 const hook = f.nativeFault('abort'); 658 try { 659 const removal = await f.remove(), 660 before = f.host.counts(), 661 current = old.current(), 662 again = await f.qualifyAccess(); 663 const rows = (await f.host.stored()).length; 664 return { 665 removed: removal.status, 666 counts: hook.counts(), 667 current, 668 again: again.status, 669 before, 670 after: f.host.counts(), 671 rows 672 }; 673 } finally { 674 hook.restore(); 675 } 676 }); 677 expect(result.removed).toBe('aborted'); 678 expect(result.counts).toMatchObject({ 679 deletes: 1, 680 completes: 0, 681 aborts: 1 682 }); 683 expect(result.rows).toBe(1); 684 expect(result.current).toBe(false); 685 expect(result.again).toBe('stopped'); 686 expect(result.after).toEqual(result.before); 687 }); 688 for (const mode of ['accept', 'refuse', 'hold'] as const) 689 test(`${recovered ? 'REC' : 'original'} required AUTH ${mode} uses actual C7 response and challenge currentness`, async ({ 690 page 691 }) => { 692 await prepare(page, recovered); 693 const before = await page.evaluate(() => window.qaFixture.host.counts()); 694 expect( 695 await page.evaluate( 696 async () => (await window.qaFixture.qualifyAccess()).status 697 ) 698 ).toBe('invalid_scope'); 699 expect(await page.evaluate(() => window.qaFixture.host.counts())).toEqual( 700 before 701 ); 702 challenge = true; 703 expect(['waiting', 'challenge']).toContain( 704 await page.evaluate(async () => 705 window.qa.authenticateInboxAccess( 706 window.qaFixture.actors().access, 707 'wss://inbox.example.org', 708 'reviewed_inbox_connection_auth' 709 ) 710 ) 711 ); 712 for (const socket of physical) 713 if (physicalOrigins.get(socket) === 'wss://inbox.example.org') 714 socket.send(JSON.stringify(['AUTH', 's5a-source-challenge'])); 715 await expect 716 .poll(() => 717 page.evaluate( 718 () => 719 window.qa 720 .inboxAccessControllerSnapshot(window.qaFixture.actors().access) 721 ?.auth.find((x) => x.origin === 'wss://inbox.example.org') 722 ?.state 723 ) 724 ) 725 .toBe('challenge'); 726 expect( 727 await page.evaluate( 728 async () => (await window.qaFixture.qualifyAccess()).status 729 ) 730 ).toBe('invalid_scope'); 731 authMode = mode; 732 await page.evaluate(() => { 733 window.qaPending = window.qa.respondInboxAccessAuthentication( 734 window.qaFixture.actors().access, 735 'wss://inbox.example.org', 736 'reviewed_inbox_auth_response' 737 ); 738 }); 739 await expect 740 .poll(() => frames.filter((x) => x.frame[0] === 'AUTH').length) 741 .toBe(1); 742 if (mode === 'hold') { 743 expect( 744 await page.evaluate( 745 async () => (await window.qaFixture.qualifyAccess()).status 746 ) 747 ).toBe('invalid_scope'); 748 // Complete this exact held response on its actual connection. 749 const sent = frames.find((x) => x.frame[0] === 'AUTH')!, 750 event = sent.frame[1] as { id: string }; 751 for (const socket of physical) 752 if (physicalOrigins.get(socket) === sent.origin) 753 socket.send( 754 JSON.stringify([ 755 'OK', 756 event.id, 757 true, 758 'controlled held auth accepted' 759 ]) 760 ); 761 } 762 expect(await page.evaluate(async () => await window.qaPending)).toBe( 763 mode === 'refuse' ? 'refused' : 'accepted' 764 ); 765 const result = await page.evaluate(async () => { 766 const f = window.qaFixture, 767 before = f.host.counts(), 768 q = await f.qualifyAccess(); 769 return { 770 status: q.status, 771 before, 772 after: f.host.counts(), 773 current: f.observation(f.context())?.current() 774 }; 775 }); 776 if (mode === 'refuse') { 777 expect(result.status).toBe('invalid_scope'); 778 expect(result.after).toEqual(result.before); 779 } else { 780 expect(result.status).toBe('qualified'); 781 expect(result.current).toBe(true); 782 for (const socket of physical) 783 if (physicalOrigins.get(socket) === 'wss://inbox.example.org') 784 socket.send(JSON.stringify(['AUTH', 's5a-new-real-challenge'])); 785 await expect 786 .poll(() => 787 page.evaluate( 788 () => 789 window.qa.inboxAccessControllerSnapshot( 790 window.qaFixture.actors().access 791 )?.auth[0]?.state 792 ) 793 ) 794 .toBe('challenge'); 795 expect( 796 await page.evaluate( 797 () => 798 window.qaFixture 799 .observation(window.qaFixture.context()) 800 ?.current() ?? false 801 ) 802 ).toBe(false); 803 } 804 }); 805 for (const held of ['lock', 'SDK'] as const) 806 test(`${recovered ? 'REC' : 'original'} actual ${held} contention refuses before provider and permits an explicit retry`, async ({ 807 page 808 }) => { 809 await prepare(page, recovered); 810 const result = await page.evaluate(async (held) => { 811 const f = window.qaFixture, 812 before = f.host.counts(), 813 hook = f.nativeFault('read_loss'); 814 try { 815 const denied = await f.withHeld(held, () => f.qualifyAccess()), 816 during = hook.counts(), 817 after = f.host.counts(), 818 retry = await f.qualifyAccess(); 819 return { 820 status: denied.status, 821 before, 822 after, 823 during, 824 retry: retry.status 825 }; 826 } finally { 827 hook.restore(); 828 } 829 }, held); 830 expect(result.status).toBe('busy'); 831 expect(result.after).toEqual(result.before); 832 expect(result.during.readonly).toBe(0); 833 expect(result.retry).toBe('qualified'); 834 }); 835 for (const kind of [ 836 'missing', 837 'changed', 838 'corrupt_tail', 839 'alias', 840 'foreign_tail' 841 ] as const) 842 test(`${recovered ? 'REC' : 'original'} actual native ${kind} is checked before qualification`, async ({ 843 page 844 }) => { 845 await prepare(page, recovered); 846 const result = await page.evaluate(async (kind) => { 847 const f = window.qaFixture, 848 row = (await f.host.stored()).find((x) => x.id === f.command())!; 849 if (kind === 'missing') await f.removeFixtureRow(); 850 else if (kind === 'changed') { 851 const record = JSON.parse(row.wire) as PrivateAccessProbe; 852 await f.host.inject([ 853 { 854 ...row, 855 wire: JSON.stringify({ ...record, revision: record.revision + 1 }) 856 } 857 ]); 858 } else if (kind === 'alias') 859 await f.host.inject([{ ...row, id: crypto.randomUUID() }]); 860 else 861 await f.host.inject([ 862 { 863 owner: kind === 'foreign_tail' ? 'f'.repeat(64) : f.host.owner, 864 id: crypto.randomUUID(), 865 wire: '{' 866 } 867 ]); 868 const rows = await f.host.stored(), 869 before = f.host.counts(), 870 result = await f.qualifyAccess(), 871 after = f.host.counts(); 872 return { 873 status: result.status, 874 before, 875 after, 876 unchanged: 877 JSON.stringify(rows) === JSON.stringify(await f.host.stored()) 878 }; 879 }, kind); 880 if (kind === 'foreign_tail') expect(result.status).toBe('qualified'); 881 else expect(result.status).not.toBe('qualified'); 882 expect(result.after).toEqual({ 883 ...result.before, 884 keys: result.before.keys + 1 885 }); 886 expect(result.unchanged).toBe(true); 887 }); 888 for (const at of ['provider', 'native'] as const) 889 for (const loss of ['head', 'controller', 'session'] as const) 890 test(`${recovered ? 'REC' : 'original'} genuine ${loss} loss at ${at} cannot issue access`, async ({ 891 page 892 }) => { 893 await prepare(page, recovered); 894 const result = await page.evaluate( 895 async ({ at, loss }) => { 896 const f = window.qaFixture, 897 a = f.actors(); 898 let losses = 0; 899 const lose = () => { 900 losses++; 901 if (loss === 'head') a.churnHead(); 902 else if (loss === 'session') 903 window.qa.closePrivateSession(a.session); 904 else f.stop(); 905 }; 906 const off = 907 at === 'provider' ? f.host.keyCallback(1, lose) : undefined; 908 const hook = 909 at === 'native' ? f.nativeFault('read_loss', lose) : undefined; 910 const before = f.host.counts(); 911 try { 912 const result = await f.qualifyAccess(); 913 return { 914 status: result.status, 915 before, 916 after: f.host.counts(), 917 losses, 918 native: hook?.counts() 919 }; 920 } finally { 921 off?.(); 922 hook?.restore(); 923 } 924 }, 925 { at, loss } 926 ); 927 expect(result.losses).toBe(1); 928 expect(result.status).not.toBe('qualified'); 929 expect(result.after).toEqual({ 930 ...result.before, 931 keys: result.before.keys + 1 932 }); 933 if (at === 'native') expect(result.native?.deletes).toBe(0); 934 }); 935 test(`${recovered ? 'REC' : 'original'} actual native qualification read abort cannot issue access`, async ({ 936 page 937 }) => { 938 await prepare(page, recovered); 939 const result = await page.evaluate(async () => { 940 const f = window.qaFixture, 941 hook = f.nativeFault('initial_read_abort'); 942 try { 943 const result = await f.qualifyAccess(); 944 return { status: result.status, counts: hook.counts() }; 945 } finally { 946 hook.restore(); 947 } 948 }); 949 expect(result.status).not.toBe('qualified'); 950 expect(result.counts.readonly).toBe(1); 951 expect(result.counts.deletes).toBe(0); 952 }); 953 test(`${recovered ? 'REC' : 'original'} held fresh key serializes reentry and controller stop fences late settlement`, async ({ 954 page 955 }) => { 956 await prepare(page, recovered); 957 await page.evaluate(() => { 958 const f = window.qaFixture; 959 f.host.mode('hold_key'); 960 window.qaPending = f.qualifyAccess(); 961 }); 962 await expect 963 .poll(() => page.evaluate(() => window.qaFixture.host.waiting())) 964 .toBe('key'); 965 const during = await page.evaluate(async () => { 966 const f = window.qaFixture, 967 before = f.host.counts(), 968 second = await f.qualifyAccess(); 969 f.stop(); 970 f.host.settle(); 971 const first = await window.qaPending; 972 return { before, after: f.host.counts(), second: second.status, first }; 973 }); 974 expect(during.second).toBe('busy'); 975 expect(during.after).toEqual(during.before); 976 expect(during.first).toMatchObject({ status: 'stopped' }); 977 }); 978 for (const foreign of ['controller', 'session', 'repository'] as const) 979 test(`${recovered ? 'REC' : 'original'} different genuine ${foreign} cannot consume source qualification`, async ({ 980 page 981 }) => { 982 await prepare(page, recovered); 983 const result = await page.evaluate(async (foreign) => { 984 const f = window.qaFixture, 985 a = f.actors(), 986 other = 987 foreign === 'controller' 988 ? { 989 access: (await f.replaceController())!, 990 session: a.session, 991 close() {} 992 } 993 : foreign === 'session' 994 ? await f.alternateController(true) 995 : undefined, 996 opened = 997 foreign === 'repository' 998 ? await window.qa.openBrowserDatabase() 999 : undefined; 1000 const repository = 1001 opened?.state === 'ready' 1002 ? window.qa.createPrivateStorageRepository( 1003 opened.owner, 1004 f.host.owner 1005 )! 1006 : f.repository; 1007 const before = f.host.counts(), 1008 hook = f.nativeFault('read_loss'); 1009 try { 1010 const result = await window.qa.qualifyInboxAccess( 1011 repository, 1012 other?.session ?? a.session, 1013 f.host.policy, 1014 other?.access ?? a.access, 1015 f.host.qualification, 1016 f.nonce()!, 1017 f.observations(), 1018 'reviewed_qualify_inbox_access' 1019 ); 1020 return { 1021 status: result.status, 1022 before, 1023 after: f.host.counts(), 1024 native: hook.counts() 1025 }; 1026 } finally { 1027 hook.restore(); 1028 other?.close(); 1029 if (opened?.state === 'ready') 1030 window.qa.closeBrowserDatabase(opened.owner); 1031 } 1032 }, foreign); 1033 expect(result.status).toBe('invalid_scope'); 1034 expect(result.after).toEqual(result.before); 1035 expect(result.native.readonly).toBe(0); 1036 }); 1037 test(`${recovered ? 'REC' : 'original'} a genuinely later applied read and distinct nonce restores access within the original meter`, async ({ 1038 page 1039 }) => { 1040 await prepare(page, recovered); 1041 archived.clear(); 1042 expect( 1043 await page.evaluate(async (recovered) => { 1044 const f = window.qaFixture; 1045 return ( 1046 await (recovered 1047 ? f.read('wss://inbox.example.org') 1048 : f.originalRead('wss://inbox.example.org')) 1049 )?.status; 1050 }, recovered) 1051 ).toBe('empty'); 1052 expect( 1053 await page.evaluate( 1054 async () => (await window.qaFixture.qualifyAccess()).status 1055 ) 1056 ).toBe('stopped'); 1057 // Restore only the actual signed archived event, through a real accepted EVENT. 1058 expect( 1059 await page.evaluate(async (recovered) => { 1060 const f = window.qaFixture, 1061 archive = await (recovered 1062 ? f.publish('wss://peer.example.org') 1063 : f.originalPublish('wss://peer.example.org')); 1064 if (!archive) throw Error('actual remaining archive attempt'); 1065 return (await f.append(archive)).status; 1066 }, recovered) 1067 ).toBe('saved'); 1068 expect( 1069 await page.evaluate( 1070 async (recovered) => 1071 window.qaFixture.renewQualificationNonce( 1072 recovered, 1073 'wss://peer.example.org' 1074 ), 1075 recovered 1076 ) 1077 ).toBe('saved'); 1078 expect( 1079 await page.evaluate( 1080 async () => (await window.qaFixture.qualifyAccess()).status 1081 ) 1082 ).toBe('qualified'); 1083 }); 1084 for (const afterRemoval of [false, true]) 1085 test(`${recovered ? 'REC' : 'original'} later applied archive cannot mask an unaccounted read ${afterRemoval ? 'through removal' : 'before first qualification'}`, async ({ 1086 page 1087 }) => { 1088 await prepare(page, recovered); 1089 archived.clear(); 1090 const result = await page.evaluate( 1091 async ({ recovered, afterRemoval }) => { 1092 const f = window.qaFixture, 1093 read = await (recovered 1094 ? f.read('wss://peer.example.org') 1095 : f.originalRead('wss://peer.example.org')), 1096 archive = await (recovered 1097 ? f.publish('wss://archive.example.org') 1098 : f.originalPublish('wss://archive.example.org')); 1099 if (!archive || archive.status !== 'accepted') 1100 throw Error('actual later accepted archive'); 1101 const appended = await f.append(archive), 1102 observations = [...f.observations(), archive], 1103 before = f.host.counts(); 1104 let status: string; 1105 let removed: string | undefined; 1106 if (afterRemoval) { 1107 if ( 1108 !(await f.select( 1109 'reviewed_inbox_probe_cleanup_selection', 1110 observations 1111 )) 1112 ) 1113 throw Error('actual selection with later archive'); 1114 removed = (await f.remove()).status; 1115 status = f.qualifyRemoved().status; 1116 } else status = (await f.qualifyAccess(observations)).status; 1117 return { 1118 read: read?.status, 1119 appended: appended.status, 1120 status, 1121 removed, 1122 coverage: !!f.removalBinding()?.qualification, 1123 before, 1124 after: f.host.counts() 1125 }; 1126 }, 1127 { recovered, afterRemoval } 1128 ); 1129 expect(result.read).toBe('empty'); 1130 expect(result.appended).toBe('saved'); 1131 if (afterRemoval) { 1132 expect(result.removed).toBe('removed'); 1133 expect(result.coverage).toBe(false); 1134 expect(result.status).toBe('invalid_scope'); 1135 } else { 1136 expect(result.status).toBe('stopped'); 1137 expect(result.after).toEqual(result.before); 1138 } 1139 }); 1140 test(`${recovered ? 'REC' : 'original'} actual retained journal qualifies with one fresh key and no crypto/network/write`, async ({ 1141 page 1142 }) => { 1143 await prepare(page, recovered); 1144 const beforeTraffic = traffic().length; 1145 const result = await page.evaluate(async () => { 1146 const f = window.qaFixture, 1147 before = f.host.counts(), 1148 rows = await f.host.stored(), 1149 first = await f.qualifyAccess(), 1150 token = first.qualification!, 1151 context = f.context(), 1152 observation = f.observation(context), 1153 after = f.host.counts(), 1154 again = await f.qualifyAccess(); 1155 return { 1156 status: first.status, 1157 before, 1158 after, 1159 repeated: f.host.counts(), 1160 same: again.qualification === token, 1161 current: observation?.current(), 1162 snapshot: f.snapshot(), 1163 unchanged: 1164 JSON.stringify(rows) === JSON.stringify(await f.host.stored()), 1165 copied: !!window.qa.observeQualifiedInboxAccess({ ...token })(context) 1166 }; 1167 }); 1168 expect(result.status).toBe('qualified'); 1169 expect(result.after).toEqual({ 1170 ...result.before, 1171 keys: result.before.keys + 1 1172 }); 1173 expect(result.repeated).toEqual(result.after); 1174 expect(result).toMatchObject({ 1175 same: true, 1176 current: true, 1177 unchanged: true, 1178 copied: false, 1179 snapshot: { authority: 'source_fixture', sourceOnly: true } 1180 }); 1181 expect(traffic().length).toBe(beforeTraffic); 1182 }); 1183 test(`${recovered ? 'REC' : 'original'} actual successful cleanup preserves independent qualified coverage`, async ({ 1184 page 1185 }) => { 1186 await prepare(page, recovered); 1187 const result = await page.evaluate(async () => { 1188 const f = window.qaFixture, 1189 initial = await f.qualifyAccess(), 1190 old = window.qa.observeQualifiedInboxAccess(initial.qualification!)( 1191 f.context() 1192 )!; 1193 if (!(await f.select())) throw Error('actual cleanup selection'); 1194 const removed = await f.remove(), 1195 before = f.host.counts(), 1196 qualified = f.qualifyRemoved(), 1197 after = f.host.counts(); 1198 return { 1199 removed: removed.status, 1200 status: qualified.status, 1201 before, 1202 after, 1203 old: old.current(), 1204 current: f.observation(f.context())?.current(), 1205 native: (await f.host.stored()).length, 1206 coverage: !!f.removalBinding()?.qualification 1207 }; 1208 }); 1209 expect(result).toMatchObject({ 1210 removed: 'removed', 1211 status: 'qualified', 1212 old: false, 1213 current: true, 1214 native: 0, 1215 coverage: true 1216 }); 1217 expect(result.after).toEqual(result.before); 1218 }); 1219 for (const beforeFirst of [false, true]) 1220 test(`${recovered ? 'REC' : 'original'} unjournaled read gap ${beforeFirst ? 'before first issuance' : 'after issuance'} never revives access through cleanup`, async ({ 1221 page 1222 }) => { 1223 await prepare(page, recovered); 1224 if (!beforeFirst) 1225 expect( 1226 await page.evaluate( 1227 async () => (await window.qaFixture.qualifyAccess()).status 1228 ) 1229 ).toBe('qualified'); 1230 archived.clear(); 1231 const result = await page.evaluate(async (recovered) => { 1232 const f = window.qaFixture, 1233 rows = await f.host.stored(), 1234 read = await (recovered 1235 ? f.read('wss://peer.example.org') 1236 : f.originalRead('wss://peer.example.org')), 1237 before = f.host.counts(), 1238 qualified = await f.qualifyAccess(), 1239 after = f.host.counts(), 1240 unchanged = 1241 JSON.stringify(rows) === JSON.stringify(await f.host.stored()); 1242 if (!(await f.select())) 1243 throw Error('genuine C3B cleanup still eligible'); 1244 const removal = await f.remove(), 1245 postBefore = f.host.counts(), 1246 post = f.qualifyRemoved(), 1247 postAfter = f.host.counts(); 1248 return { 1249 read: read?.status, 1250 status: qualified.status, 1251 before, 1252 after, 1253 unchanged, 1254 removed: removal.status, 1255 post: post.status, 1256 postBefore, 1257 postAfter, 1258 coverage: !!f.removalBinding()?.qualification, 1259 rows: (await f.host.stored()).length 1260 }; 1261 }, recovered); 1262 expect(result).toMatchObject({ 1263 read: 'empty', 1264 status: 'stopped', 1265 unchanged: true, 1266 removed: 'removed', 1267 post: 'invalid_scope', 1268 coverage: false, 1269 rows: 0 1270 }); 1271 expect(result.after).toEqual(result.before); 1272 expect(result.postAfter).toEqual(result.postBefore); 1273 }); 1274 for (const removedPath of [false, true]) 1275 test(`${recovered ? 'REC' : 'original'} ${removedPath ? 'removed' : 'journal'} genuine qualification survives its own actual foreground inbox`, async ({ 1276 page 1277 }) => { 1278 await prepare(page, recovered); 1279 expect( 1280 await page.evaluate(async (removedPath) => { 1281 const f = window.qaFixture; 1282 if (!removedPath) return (await f.qualifyAccess()).status; 1283 if (!(await f.select()) || (await f.remove()).status !== 'removed') 1284 throw Error('actual own-inbox reviewed removal'); 1285 return f.qualifyRemoved().status; 1286 }, removedPath) 1287 ).toBe('qualified'); 1288 expect( 1289 await page.evaluate(async () => await window.qaFixture.startOwnInbox()) 1290 ).toBe(true); 1291 await expect 1292 .poll( 1293 async () => 1294 await page.evaluate(() => window.qaFixture.syncSnapshot()?.state) 1295 ) 1296 .toBe('live'); 1297 expect( 1298 await page.evaluate(() => 1299 window.qaFixture.observation(window.qaFixture.context())?.current() 1300 ) 1301 ).toBe(true); 1302 expect(traffic().some((x) => x.frame[0] === 'REQ')).toBe(true); 1303 const firstStop = await page.evaluate(() => { 1304 try { 1305 window.qaFixture.stopOwnInbox(); 1306 return 'closed'; 1307 } catch (error) { 1308 if ( 1309 error instanceof Error && 1310 error.message === 'private_inbox_cleanup_required' 1311 ) 1312 return 'physical_close_pending'; 1313 throw error; 1314 } 1315 }); 1316 if (firstStop === 'physical_close_pending') { 1317 await expect 1318 .poll( 1319 () => 1320 Array.from(physical).filter( 1321 (socket) => 1322 physicalOrigins.get(socket) !== 'wss://discovery.example.org' 1323 ).length 1324 ) 1325 .toBe(0); 1326 await page.evaluate(() => window.qaFixture.stopOwnInbox()); 1327 } 1328 }); 1329 for (const kind of ['operator', 'policy'] as const) 1330 test(`${recovered ? 'REC' : 'original'} same-wire copied ${kind} is not qualification provenance`, async ({ 1331 page 1332 }) => { 1333 await prepare(page, recovered); 1334 const result = await page.evaluate(async (kind) => { 1335 const f = window.qaFixture, 1336 a = f.actors(), 1337 before = f.host.counts(), 1338 policy = 1339 kind === 'policy' 1340 ? window.qa.validateRelayPolicy( 1341 JSON.stringify(window.qa.readRelayPolicy(f.host.policy)) 1342 )! 1343 : f.host.policy, 1344 operator = 1345 kind === 'operator' 1346 ? window.qa.validateInboxOperatorQualification( 1347 window.qa.inboxOperatorQualificationWire( 1348 f.host.qualification, 1349 f.host.policy 1350 )! 1351 )! 1352 : f.host.qualification, 1353 result = await window.qa.qualifyInboxAccess( 1354 f.repository, 1355 a.session, 1356 policy, 1357 a.access, 1358 operator, 1359 f.nonce()!, 1360 f.observations(), 1361 'reviewed_qualify_inbox_access' 1362 ); 1363 return { status: result.status, before, after: f.host.counts() }; 1364 }, kind); 1365 expect(result.status).toBe('invalid_scope'); 1366 expect(result.after).toEqual(result.before); 1367 }); 1368 } 1369 1370 const traffic = () => 1371 frames.filter( 1372 (x) => 1373 x.origin !== 'wss://discovery.example.org' && 1374 ['EVENT', 'REQ', 'AUTH'].includes(String(x.frame[0])) 1375 );