inbox-preference-publisher.spec.ts (17202B)
1 import { test, expect } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { fileURLToPath } from 'node:url'; 4 import { createHash } from 'node:crypto'; 5 import { once } from 'node:events'; 6 import { WebSocketServer } from 'ws'; 7 import { createStaticHarness } from '../integration/harness/static.ts'; 8 import type * as Fixture from './harness/inbox-preference-publisher.ts'; 9 import type { PublicQuotaRepository } from '../../src/lib/persistence/quota.ts'; 10 import type { BrowserDatabase } from '../../src/lib/persistence/database.ts'; 11 import type { InboxPreferenceAction } from '../../src/lib/messaging/inbox-setup-operation.ts'; 12 declare global { 13 interface Window { 14 hcp066: typeof Fixture; 15 hcp066Fixture: Awaited<ReturnType<typeof Fixture.makePublisherFixture>>; 16 hcp066Repo: PublicQuotaRepository; 17 hcp066Db: BrowserDatabase; 18 hcp066Action: InboxPreferenceAction; 19 hcp066Id: string; 20 hcp066Restore?: () => void; 21 hcp066Trace: ReturnType<typeof Fixture.installEffectTrace>; 22 hcp066ReleaseFault?: ReturnType<typeof Fixture.installUnsubscribeFailure>; 23 hcp066Run?: Promise<{ status: string }>; 24 } 25 } 26 let server: Awaited<ReturnType<typeof createStaticHarness>>, 27 socketServer: WebSocketServer, 28 bundle: string, 29 endpoint: string; 30 let frames: string[] = [], 31 response: 'accepted' | 'refused' | 'silent' | 'timeout-refusal' = 'accepted'; 32 test.beforeAll(async () => { 33 server = await createStaticHarness(); 34 socketServer = new WebSocketServer({ 35 host: '127.0.0.1', 36 port: 0, 37 maxPayload: 65536 38 }); 39 await once(socketServer, 'listening'); 40 const address = socketServer.address(); 41 if (!address || typeof address === 'string') 42 throw new Error('missing loopback'); 43 endpoint = 'ws://127.0.0.1:' + address.port; 44 socketServer.on('connection', (socket) => 45 socket.on('message', (bytes) => { 46 const raw = Buffer.isBuffer(bytes) 47 ? bytes.toString() 48 : Array.isArray(bytes) 49 ? Buffer.concat(bytes).toString() 50 : Buffer.from(bytes).toString(), 51 frame = JSON.parse(raw) as [string, { id: string }]; 52 if (frame[0] === 'EVENT') { 53 frames.push(raw); 54 if (response === 'silent') return; 55 socket.send( 56 JSON.stringify([ 57 'OK', 58 frame[1].id, 59 response === 'accepted', 60 response === 'accepted' 61 ? '' 62 : response === 'timeout-refusal' 63 ? 'Timeout' 64 : 'blocked: controlled refusal' 65 ]) 66 ); 67 } 68 }) 69 ); 70 const result = await build({ 71 configFile: false, 72 logLevel: 'silent', 73 build: { 74 write: false, 75 minify: false, 76 lib: { 77 entry: fileURLToPath( 78 new URL('./harness/inbox-preference-publisher.ts', import.meta.url) 79 ), 80 name: 'hcp066', 81 formats: ['iife'] 82 } 83 } 84 }); 85 const output = Array.isArray(result) ? result[0] : result; 86 if (!('output' in output)) throw new Error('missing output'); 87 const chunks = output.output.filter((x) => x.type === 'chunk'); 88 expect(chunks).toHaveLength(1); 89 bundle = chunks[0].code; 90 console.log( 91 JSON.stringify({ 92 fixture: 'HCP066_ACTUAL_SDK_REAL_IDB_WEBLOCK_LOOPBACK', 93 bundleSha256: createHash('sha256').update(bundle).digest('hex'), 94 moduleIds: Object.keys(chunks[0].modules), 95 qualification: 96 'controlled local source only; no real extension/operator/retention/client qualification' 97 }) 98 ); 99 }); 100 test.afterAll(async () => { 101 for (const socket of socketServer.clients) socket.terminate(); 102 await new Promise<void>((resolve) => socketServer.close(() => resolve())); 103 await server.close(); 104 }); 105 test.beforeEach(async ({ page }) => { 106 frames = []; 107 response = 'accepted'; 108 await page.addInitScript( 109 ({ endpoint }) => { 110 const Native = window.WebSocket; 111 class LoopbackSocket extends Native { 112 constructor(url: string | URL, protocols?: string | string[]) { 113 if (String(url) !== 'wss://discovery.example.org/') 114 throw new Error('unexpected fixture destination'); 115 super(endpoint, protocols); 116 } 117 } 118 window.WebSocket = LoopbackSocket; 119 }, 120 { endpoint } 121 ); 122 await page.goto(server.url + '/search'); 123 await page.addScriptTag({ content: bundle }); 124 await page.evaluate(async () => { 125 const s = window.hcp066, 126 f = await s.makePublisherFixture(); 127 window.hcp066Fixture = f; 128 const opened = await s.openBrowserDatabase(); 129 if (opened.state !== 'ready') throw new Error(opened.reason); 130 window.hcp066Db = opened.owner; 131 const repo = s.createPublicQuotaRepository(opened.owner, f.owner); 132 if (!repo) throw new Error('missing repo'); 133 window.hcp066Repo = repo; 134 const reviewed = await s.reviewInboxSetup( 135 f.identity, 136 f.resolve(), 137 f.policy, 138 s.setupInput(), 139 () => 101 140 ); 141 if (reviewed.status !== 'review') throw new Error(reviewed.reason); 142 const id = crypto.randomUUID(); 143 window.hcp066Id = id; 144 await s.saveInboxPreferenceOperation( 145 repo, 146 reviewed.review, 147 f.resolve(), 148 id, 149 'reviewed_global_inbox_replacement' 150 ); 151 const action = await s.beginInboxPreferenceOperation( 152 repo, 153 f.identity, 154 f.policy, 155 reviewed.review, 156 id, 157 () => Promise.resolve(f.resolve()), 158 'reviewed_global_inbox_replacement' 159 ); 160 if (action.status !== 'prepared') throw new Error(action.status); 161 window.hcp066Action = action.action; 162 }); 163 }); 164 test.afterEach(async ({ page }) => { 165 if (!page.isClosed()) 166 await page.evaluate(() => { 167 window.hcp066Restore?.(); 168 window.hcp066Trace?.restore(); 169 window.hcp066ReleaseFault?.restore(); 170 window.hcp066Fixture?.close(); 171 if (window.hcp066Db) window.hcp066.closeBrowserDatabase(window.hcp066Db); 172 }); 173 }); 174 test('actual marker is acknowledged before signing and exact artifact before the first SDK EVENT', async ({ 175 page 176 }) => { 177 const result = await page.evaluate(async () => { 178 const s = window.hcp066, 179 f = window.hcp066Fixture; 180 window.hcp066Trace = s.installEffectTrace(); 181 let marker = -1; 182 f.beforeSign(async () => { 183 const stored = await s.loadPreferenceOperation( 184 window.hcp066Repo, 185 window.hcp066Id 186 ); 187 if (stored.ok) 188 marker = s.publicRecordSnapshot( 189 stored.value, 190 f.owner, 191 window.hcp066Id 192 )!.revision; 193 }); 194 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 195 const stored = await s.loadPreferenceOperation( 196 window.hcp066Repo, 197 window.hcp066Id 198 ); 199 return { 200 status: result.status, 201 marker, 202 trace: window.hcp066Trace.events(), 203 signs: f.signs(), 204 row: stored.ok 205 ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id) 206 : null 207 }; 208 }); 209 expect(result.status).toBe('completed'); 210 expect(result.marker).toBe(1); 211 expect(result.signs).toBe(1); 212 expect(result.trace.indexOf('ack:2')).toBeGreaterThan(-1); 213 expect(result.trace.indexOf('EVENT')).toBeGreaterThan( 214 result.trace.indexOf('ack:2') 215 ); 216 expect(frames).toHaveLength(1); 217 expect(JSON.parse(frames[0]) as unknown[]).toEqual([ 218 'EVENT', 219 JSON.parse( 220 result.row!.family !== 'public_draft' ? result.row!.artifact!.wire : '' 221 ) as unknown 222 ]); 223 expect( 224 result.row!.family !== 'public_draft' && result.row!.receipts[0].status 225 ).toBe('accepted'); 226 }); 227 for (const revision of [1, 2]) 228 test(`real IDB abort at revision ${revision} prevents EVENT and unknown attempt cannot sign again`, async ({ 229 page 230 }) => { 231 const result = await page.evaluate(async (revision) => { 232 const s = window.hcp066, 233 f = window.hcp066Fixture; 234 window.hcp066Restore = s.failPreferenceWrite(revision); 235 const first = await s.runInboxPreferenceOperation(window.hcp066Action); 236 const resume = await s.resumeInboxPreferenceOperation( 237 window.hcp066Repo, 238 f.identity, 239 f.policy, 240 window.hcp066Id, 241 () => Promise.resolve(f.resolve()), 242 'reviewed_stored_inbox_preference' 243 ); 244 if (revision === 2 && resume.status === 'prepared') 245 await s.runInboxPreferenceOperation(resume.action); 246 const stored = await s.loadPreferenceOperation( 247 window.hcp066Repo, 248 window.hcp066Id 249 ); 250 return { 251 status: first.status, 252 signs: f.signs(), 253 revision: stored.ok 254 ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id)! 255 .revision 256 : -1 257 }; 258 }, revision); 259 expect(result.status).toBe('storage_failed'); 260 expect(result.signs).toBe(revision === 1 ? 0 : 1); 261 expect(result.revision).toBe(revision - 1); 262 expect(frames).toHaveLength(0); 263 }); 264 test('late changed extension owner keeps unsigned uncertainty and never publishes', async ({ 265 page 266 }) => { 267 const result = await page.evaluate(async () => { 268 const s = window.hcp066, 269 f = window.hcp066Fixture; 270 f.beforeSign(() => { 271 f.changeOwner(); 272 return Promise.resolve(); 273 }); 274 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 275 const stored = await s.loadPreferenceOperation( 276 window.hcp066Repo, 277 window.hcp066Id 278 ); 279 return { 280 status: result.status, 281 signs: f.signs(), 282 row: stored.ok 283 ? s.publicRecordSnapshot(stored.value, f.owner, window.hcp066Id) 284 : null 285 }; 286 }); 287 expect(result.status).not.toBe('completed'); 288 expect(result.signs).toBe(1); 289 expect(result.row!.revision).toBe(1); 290 expect( 291 result.row!.family !== 'public_draft' && result.row!.artifact 292 ).toBeNull(); 293 expect(frames).toHaveLength(0); 294 }); 295 test('explicit stored retry sends the identical artifact without a second signature; accepted targets are skipped', async ({ 296 page 297 }) => { 298 response = 'refused'; 299 await page.evaluate(() => 300 window.hcp066.runInboxPreferenceOperation(window.hcp066Action) 301 ); 302 expect(frames).toHaveLength(1); 303 response = 'accepted'; 304 const retry = async () => 305 page.evaluate(async () => { 306 const s = window.hcp066, 307 f = window.hcp066Fixture; 308 s.disconnectIdentity(f.identity); 309 const identity = s.createIdentitySession(); 310 await s.connectIdentity(identity); 311 await s.probeIdentityMessaging(identity, 'reviewed_self_copy'); 312 const prepared = await s.resumeInboxPreferenceOperation( 313 window.hcp066Repo, 314 identity, 315 f.policy, 316 window.hcp066Id, 317 () => Promise.resolve(f.resolve()), 318 'reviewed_stored_inbox_preference' 319 ); 320 if (prepared.status !== 'prepared') throw new Error(prepared.status); 321 const result = { 322 result: (await s.runInboxPreferenceOperation(prepared.action)).status, 323 signs: f.signs() 324 }; 325 s.disconnectIdentity(identity); 326 return result; 327 }); 328 expect(await retry()).toEqual({ result: 'completed', signs: 1 }); 329 expect(frames).toHaveLength(2); 330 expect(frames[1]).toBe(frames[0]); 331 expect(await retry()).toEqual({ result: 'completed', signs: 1 }); 332 expect(frames).toHaveLength(2); 333 }); 334 test('Stop during the actual permission wait prevents publication and preserves uncertainty', async ({ 335 page 336 }) => { 337 const result = await page.evaluate(async () => { 338 const s = window.hcp066, 339 f = window.hcp066Fixture; 340 f.beforeSign(() => { 341 s.stopInboxPreferenceOperation(window.hcp066Action); 342 return Promise.resolve(); 343 }); 344 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 345 const row = await s.loadPreferenceOperation( 346 window.hcp066Repo, 347 window.hcp066Id 348 ); 349 return { 350 status: result.status, 351 signs: f.signs(), 352 revision: row.ok 353 ? s.publicRecordSnapshot(row.value, f.owner, window.hcp066Id)!.revision 354 : -1 355 }; 356 }); 357 expect(result).toEqual({ status: 'stopped', signs: 1, revision: 1 }); 358 expect(frames).toHaveLength(0); 359 }); 360 test('competing and incomplete preference observations block explicit stored resume', async ({ 361 page 362 }) => { 363 response = 'refused'; 364 await page.evaluate(() => 365 window.hcp066.runInboxPreferenceOperation(window.hcp066Action) 366 ); 367 const result = await page.evaluate(async () => { 368 const s = window.hcp066, 369 f = window.hcp066Fixture; 370 const competing = await s.resumeInboxPreferenceOperation( 371 window.hcp066Repo, 372 f.identity, 373 f.policy, 374 window.hcp066Id, 375 () => Promise.resolve(f.resolve(f.competing())), 376 'reviewed_stored_inbox_preference' 377 ); 378 const partial = await s.resumeInboxPreferenceOperation( 379 window.hcp066Repo, 380 f.identity, 381 f.policy, 382 window.hcp066Id, 383 () => Promise.resolve(f.resolve(undefined, false)), 384 'reviewed_stored_inbox_preference' 385 ); 386 return [competing.status, partial.status, f.signs()]; 387 }); 388 expect(result).toEqual(['conflict', 'conflict', 1]); 389 expect(frames).toHaveLength(1); 390 }); 391 test('actual SDK timeouts allow only three explicit same-artifact attempts and retain each named fact', async ({ 392 page 393 }) => { 394 test.setTimeout(86_400_000); 395 response = 'silent'; 396 const result = await page.evaluate(async () => { 397 const s = window.hcp066, 398 f = window.hcp066Fixture; 399 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 400 const row = await s.loadPreferenceOperation( 401 window.hcp066Repo, 402 window.hcp066Id 403 ); 404 const snapshot = row.ok 405 ? s.publicRecordSnapshot(row.value, f.owner, window.hcp066Id) 406 : null; 407 return { 408 status: result.status, 409 signs: f.signs(), 410 receipts: 411 snapshot && snapshot.family !== 'public_draft' ? snapshot.receipts : [] 412 }; 413 }); 414 expect(result.status).toBe('needs_action'); 415 expect(result.signs).toBe(1); 416 expect(frames).toHaveLength(3); 417 expect(new Set(frames).size).toBe(1); 418 expect( 419 result.receipts.map((row) => [row.origin, row.attempt, row.status]) 420 ).toEqual( 421 [1, 2, 3].map((attempt) => [ 422 'wss://discovery.example.org', 423 attempt, 424 'timed_out' 425 ]) 426 ); 427 }); 428 test('Stop during the actual policy digest prevents even a new durable signing marker', async ({ 429 page 430 }) => { 431 const result = await page.evaluate(async () => { 432 const s = window.hcp066, 433 f = window.hcp066Fixture; 434 const original = Reflect.get<SubtleCrypto, 'digest'>( 435 crypto.subtle, 436 'digest' 437 ); 438 crypto.subtle.digest = async function ( 439 ...args: Parameters<SubtleCrypto['digest']> 440 ) { 441 const buffer = await original.call(this, ...args); 442 s.stopInboxPreferenceOperation(window.hcp066Action); 443 return buffer; 444 }; 445 try { 446 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 447 const read = await s.loadPreferenceOperation( 448 window.hcp066Repo, 449 window.hcp066Id 450 ); 451 return { 452 status: result.status, 453 signs: f.signs(), 454 revision: read.ok 455 ? s.publicRecordSnapshot(read.value, f.owner, window.hcp066Id)! 456 .revision 457 : -1 458 }; 459 } finally { 460 crypto.subtle.digest = original; 461 } 462 }); 463 expect(result).toEqual({ status: 'stopped', signs: 0, revision: 0 }); 464 expect(frames).toHaveLength(0); 465 }); 466 test('a real relay refusal worded Timeout is ambiguous evidence and never automatically retried', async ({ 467 page 468 }) => { 469 response = 'timeout-refusal'; 470 const result = await page.evaluate(async () => { 471 const s = window.hcp066, 472 f = window.hcp066Fixture; 473 const result = await s.runInboxPreferenceOperation(window.hcp066Action); 474 const read = await s.loadPreferenceOperation( 475 window.hcp066Repo, 476 window.hcp066Id 477 ); 478 const row = read.ok 479 ? s.publicRecordSnapshot(read.value, f.owner, window.hcp066Id) 480 : null; 481 return { 482 status: result.status, 483 signs: f.signs(), 484 receipts: 485 row && row.family !== 'public_draft' 486 ? row.receipts.map((fact) => fact.status) 487 : [] 488 }; 489 }); 490 expect(result).toEqual({ 491 status: 'needs_action', 492 signs: 1, 493 receipts: ['unknown'] 494 }); 495 expect(frames).toHaveLength(1); 496 }); 497 test('pending real publication release failure blocks terminal cleanup until the same control is released', async ({ 498 page 499 }) => { 500 response = 'silent'; 501 await page.evaluate(() => { 502 const s = window.hcp066; 503 window.hcp066ReleaseFault = s.installUnsubscribeFailure(); 504 window.hcp066Run = s.runInboxPreferenceOperation(window.hcp066Action); 505 }); 506 await expect.poll(() => frames.length).toBe(1); 507 const result = await page.evaluate(async () => { 508 const s = window.hcp066, 509 pool = s.getPublicPool(window.hcp066Fixture.policy)!; 510 let firstFailed = false; 511 try { 512 s.closePublicPool(pool); 513 } catch { 514 firstFailed = true; 515 } 516 window.hcp066ReleaseFault!.allowRelease(); 517 s.closePublicPool(pool); 518 s.closePublicPool(pool); 519 return { firstFailed, status: (await window.hcp066Run)!.status }; 520 }); 521 expect(result.firstFailed).toBe(true); 522 expect(result.status).not.toBe('completed'); 523 expect(frames).toHaveLength(1); 524 });