inbox-sync.spec.ts (13303B)
1 import { test, expect } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { fileURLToPath } from 'node:url'; 4 import { once } from 'node:events'; 5 import { WebSocketServer, type WebSocket } from 'ws'; 6 import { createStaticHarness } from '../integration/harness/static.ts'; 7 import type * as Fixture from './harness/inbox-sync.ts'; 8 declare global { 9 interface Window { 10 hcp095: typeof Fixture; 11 hcp095Fixture: Awaited<ReturnType<typeof Fixture.makeFixture>>; 12 } 13 } 14 let server: Awaited<ReturnType<typeof createStaticHarness>>, 15 sockets: WebSocketServer, 16 endpoint: string, 17 bundle: string; 18 let requests: unknown[][] = [], 19 closes: unknown[][] = [], 20 live = new Map<WebSocket, string>(), 21 frames: Record<string, unknown>[] = []; 22 test.beforeAll(async () => { 23 server = await createStaticHarness(); 24 sockets = new WebSocketServer({ 25 host: '127.0.0.1', 26 port: 0, 27 maxPayload: 65536 28 }); 29 await once(sockets, 'listening'); 30 const address = sockets.address(); 31 if (!address || typeof address === 'string') 32 throw Error('loopback unavailable'); 33 endpoint = 'ws://127.0.0.1:' + address.port; 34 sockets.on('connection', (socket) => 35 socket.on('message', (bytes) => { 36 const raw = Buffer.isBuffer(bytes) 37 ? bytes 38 : Array.isArray(bytes) 39 ? Buffer.concat(bytes) 40 : Buffer.from(bytes), 41 frame = JSON.parse(raw.toString()) as unknown[]; 42 if (frame[0] === 'CLOSE') { 43 closes.push(frame); 44 return; 45 } 46 if (frame[0] !== 'REQ') return; 47 requests.push(frame); 48 const filter = frame[2] as { limit: number }; 49 if (filter.limit === 0) { 50 live.set(socket, String(frame[1])); 51 for (const event of frames) 52 socket.send(JSON.stringify(['EVENT', frame[1], event])); 53 socket.send(JSON.stringify(['EOSE', frame[1]])); 54 } else { 55 for (const event of frames) 56 socket.send(JSON.stringify(['EVENT', frame[1], event])); 57 socket.send(JSON.stringify(['EOSE', frame[1]])); 58 } 59 }) 60 ); 61 const result = await build({ 62 configFile: false, 63 logLevel: 'silent', 64 build: { 65 write: false, 66 minify: false, 67 lib: { 68 entry: fileURLToPath( 69 new URL('./harness/inbox-sync.ts', import.meta.url) 70 ), 71 name: 'hcp095', 72 formats: ['iife'] 73 } 74 } 75 }); 76 const output = Array.isArray(result) ? result[0] : result; 77 if (!('output' in output)) throw Error('bundle unavailable'); 78 const chunks = output.output.filter((x) => x.type === 'chunk'); 79 expect(chunks).toHaveLength(1); 80 bundle = chunks[0].code; 81 }); 82 test.afterAll(async () => { 83 for (const socket of sockets.clients) socket.terminate(); 84 await new Promise<void>((resolve) => sockets.close(() => resolve())); 85 await server.close(); 86 }); 87 test.beforeEach(async ({ page }) => { 88 requests = []; 89 closes = []; 90 frames = []; 91 live = new Map(); 92 await page.addInitScript( 93 ({ endpoint }) => { 94 const Native = window.WebSocket; 95 window.WebSocket = class extends Native { 96 constructor(url: string | URL, protocols?: string | string[]) { 97 if (new URL(String(url)).origin !== 'wss://archive.example.org') 98 throw Error('unapproved receive destination'); 99 super(endpoint, protocols); 100 } 101 }; 102 }, 103 { endpoint } 104 ); 105 await page.goto(server.url + '/search'); 106 await page.addScriptTag({ content: bundle }); 107 await page.evaluate(async () => { 108 window.hcp095Fixture = await window.hcp095.makeFixture(); 109 }); 110 }); 111 test.afterEach(async ({ page }) => { 112 if (!page.isClosed()) 113 await page.evaluate(() => window.hcp095Fixture?.close()); 114 }); 115 const eventFrom = (wire: string) => JSON.parse(wire) as Record<string, unknown>; 116 function deliver(event: Record<string, unknown>) { 117 for (const [socket, id] of live) 118 socket.send(JSON.stringify(['EVENT', id, event])); 119 } 120 test('closing original unlock after live start sends actual CLOSE and prevents resurrection', async ({ 121 page 122 }) => { 123 await page.evaluate(() => { 124 const f = window.hcp095Fixture; 125 f.capture(); 126 f.start(); 127 }); 128 await expect.poll(() => requests.length).toBe(3); 129 await page.evaluate(() => window.hcp095Fixture.closeUnlock()); 130 await expect.poll(() => closes.length).toBeGreaterThanOrEqual(2); 131 expect( 132 await page.evaluate(() => { 133 const f = window.hcp095Fixture; 134 return { snapshot: f.snapshot(), start: f.start(), capture: f.capture() }; 135 }) 136 ).toMatchObject({ 137 snapshot: { state: 'stopped' }, 138 start: false, 139 capture: false 140 }); 141 expect(requests).toHaveLength(3); 142 }); 143 test('second capture cannot replace the original admitted foreground owner', async ({ 144 page 145 }) => { 146 expect( 147 await page.evaluate(() => { 148 const f = window.hcp095Fixture; 149 return [f.capture(), f.capture(), f.start()]; 150 }) 151 ).toEqual([true, false, true]); 152 await expect.poll(() => requests.length).toBe(3); 153 expect( 154 requests.filter((r) => (r[2] as { limit: number }).limit === 0) 155 ).toHaveLength(1); 156 }); 157 test('logout during actual held fresh-key job fences its settled continuation and no REQ opens', async ({ 158 page 159 }) => { 160 await page.evaluate(() => { 161 const f = window.hcp095Fixture; 162 f.capture(); 163 f.holdNextKey(); 164 f.start(); 165 }); 166 await expect 167 .poll(() => page.evaluate(() => window.hcp095Fixture.pendingKey())) 168 .toBe(true); 169 expect(await page.evaluate(() => window.hcp095Fixture.identityState())).toBe( 170 'pending' 171 ); 172 expect(requests).toEqual([]); 173 expect(await page.evaluate(() => window.hcp095Fixture.keyJobOccupied())).toBe( 174 true 175 ); 176 await page.evaluate(() => window.hcp095Fixture.logoutIdentity()); 177 expect( 178 await page.evaluate(() => window.hcp095Fixture.snapshot()) 179 ).toMatchObject({ state: 'stopped', retained: 0, candidates: 0 }); 180 expect(await page.evaluate(() => window.hcp095Fixture.pendingKey())).toBe( 181 true 182 ); 183 await page.evaluate(() => window.hcp095Fixture.settleKey()); 184 await expect 185 .poll(() => page.evaluate(() => window.hcp095Fixture.keyJobOccupied())) 186 .toBe(false); 187 expect(await page.evaluate(() => window.hcp095Fixture.identityState())).toBe( 188 'guest' 189 ); 190 expect( 191 await page.evaluate(() => { 192 const f = window.hcp095Fixture; 193 return { snapshot: f.snapshot(), start: f.start(), capture: f.capture() }; 194 }) 195 ).toMatchObject({ 196 snapshot: { state: 'stopped', retained: 0, candidates: 0 }, 197 start: false, 198 capture: false 199 }); 200 expect(requests).toEqual([]); 201 }); 202 test('reviewed capture is inert and wrong review or absent exercised access cannot start', async ({ 203 page 204 }) => { 205 expect( 206 await page.evaluate(() => { 207 const f = window.hcp095Fixture; 208 return { 209 wrong: f.capture(true, 'unreviewed'), 210 without: f.capture(false), 211 ready: f.capture(), 212 snapshot: f.snapshot() 213 }; 214 }) 215 ).toMatchObject({ 216 wrong: false, 217 without: false, 218 ready: true, 219 snapshot: { state: 'ready' } 220 }); 221 expect(requests).toEqual([]); 222 }); 223 test('actual live REQ precedes bounded backfill and gap delivery is retained once across both', async ({ 224 page 225 }) => { 226 frames = [eventFrom(await page.evaluate(() => window.hcp095Fixture.outer))]; 227 await page.evaluate(() => { 228 const f = window.hcp095Fixture; 229 f.capture(); 230 f.start(); 231 }); 232 await expect 233 .poll(() => 234 page.evaluate(() => window.hcp095Fixture.snapshot()?.duplicates) 235 ) 236 .toBe(2); 237 const owner = await page.evaluate(() => window.hcp095Fixture.owner); 238 expect(requests).toHaveLength(3); 239 expect(requests.map((r) => (r[2] as { limit: number }).limit)).toEqual([ 240 0, 200, 200 241 ]); 242 expect(requests[0][2]).toEqual({ kinds: [1059], '#p': [owner], limit: 0 }); 243 expect(requests[1][2]).toEqual({ kinds: [1059], '#p': [owner], limit: 200 }); 244 expect( 245 await page.evaluate(() => window.hcp095Fixture.snapshot()) 246 ).toMatchObject({ 247 state: 'live', 248 retained: 1, 249 duplicates: 2, 250 backfill: 'complete', 251 historyComplete: false 252 }); 253 expect(await page.evaluate(() => window.hcp095Fixture.publicContains())).toBe( 254 false 255 ); 256 }); 257 test('single no-later-event live tail arrives after both EOSE without decrypt or throttle', async ({ 258 page 259 }) => { 260 const before = await page.evaluate(() => window.hcp095Fixture.countsValue()); 261 await page.evaluate(() => { 262 const f = window.hcp095Fixture; 263 f.capture(); 264 f.start(); 265 }); 266 await expect.poll(() => requests.length).toBe(3); 267 await expect 268 .poll(() => page.evaluate(() => window.hcp095Fixture.snapshot()?.backfill)) 269 .toBe('complete'); 270 deliver(eventFrom(await page.evaluate(() => window.hcp095Fixture.outer))); 271 await expect 272 .poll(() => 273 page.evaluate(async () => !!(await window.hcp095Fixture.stored())) 274 ) 275 .toBe(true); 276 expect( 277 await page.evaluate(() => window.hcp095Fixture.snapshot()) 278 ).toMatchObject({ state: 'live', retained: 1, historyComplete: false }); 279 const after = await page.evaluate(() => window.hcp095Fixture.countsValue()); 280 expect(after.decrypts).toBe(before.decrypts); 281 expect(after.encrypts).toBe(before.encrypts); 282 expect(after.signs).toBe(before.signs); 283 }); 284 test('repeated start never allocates a second live subscription', async ({ 285 page 286 }) => { 287 expect( 288 await page.evaluate(() => { 289 const f = window.hcp095Fixture; 290 f.capture(); 291 return [f.start(), f.start()]; 292 }) 293 ).toEqual([true, false]); 294 await expect.poll(() => requests.length).toBe(3); 295 expect( 296 requests.filter((r) => (r[2] as { limit: number }).limit === 0) 297 ).toHaveLength(1); 298 }); 299 test('route disposal closes actual live request and suspends original Messages lifetime', async ({ 300 page 301 }) => { 302 await page.evaluate(() => { 303 const f = window.hcp095Fixture; 304 f.capture(); 305 f.start(); 306 }); 307 await expect.poll(() => requests.length).toBe(3); 308 await page.evaluate(() => window.hcp095Fixture.navigateAway()); 309 await expect.poll(() => closes.length).toBeGreaterThanOrEqual(2); 310 expect( 311 await page.evaluate(() => { 312 const f = window.hcp095Fixture; 313 return { snapshot: f.snapshot(), start: f.start(), capture: f.capture() }; 314 }) 315 ).toMatchObject({ 316 snapshot: { 317 state: 'stopped', 318 foregroundOnly: true, 319 historyComplete: false 320 }, 321 start: false, 322 capture: false 323 }); 324 expect(requests).toHaveLength(3); 325 }); 326 test('closed original unlocked cache refuses foreground receive without sockets', async ({ 327 page 328 }) => { 329 expect( 330 await page.evaluate(() => { 331 const f = window.hcp095Fixture; 332 f.closeUnlock(); 333 return f.capture(); 334 }) 335 ).toBe(false); 336 expect(requests).toEqual([]); 337 }); 338 test('revoked actual access after capture fences start', async ({ page }) => { 339 expect( 340 await page.evaluate(() => { 341 const f = window.hcp095Fixture; 342 f.capture(); 343 f.revokeAccess(); 344 return f.start(); 345 }) 346 ).toBe(false); 347 expect(requests).toEqual([]); 348 }); 349 test('fresh extension owner changed before transport prevents live or history REQ', async ({ 350 page 351 }) => { 352 await page.evaluate(() => { 353 const f = window.hcp095Fixture; 354 f.capture(); 355 f.changeKey(); 356 f.start(); 357 }); 358 await expect 359 .poll(() => page.evaluate(() => window.hcp095Fixture.snapshot()?.state)) 360 .toBe('stopped'); 361 expect(requests).toEqual([]); 362 }); 363 test('logout closes captured scope and never revives hidden retrieval', async ({ 364 page 365 }) => { 366 expect( 367 await page.evaluate(() => { 368 const f = window.hcp095Fixture; 369 f.capture(); 370 f.logout(); 371 return { start: f.start(), capture: f.capture(), snapshot: f.snapshot() }; 372 }) 373 ).toMatchObject({ 374 start: false, 375 capture: false, 376 snapshot: { state: 'stopped' } 377 }); 378 expect(requests).toEqual([]); 379 }); 380 test('121 duplicate live deliveries charge before dedup and pause the source', async ({ 381 page 382 }) => { 383 await page.evaluate(() => { 384 const f = window.hcp095Fixture; 385 f.capture(); 386 f.start(); 387 }); 388 await expect.poll(() => requests.length).toBe(3); 389 const e = eventFrom(await page.evaluate(() => window.hcp095Fixture.outer)); 390 for (let i = 0; i < 121; i++) deliver(e); 391 await expect 392 .poll(() => page.evaluate(() => window.hcp095Fixture.snapshot()?.state)) 393 .toBe('needs_action'); 394 expect( 395 await page.evaluate(() => window.hcp095Fixture.snapshot()) 396 ).toMatchObject({ reason: 'budget', historyComplete: false }); 397 await expect.poll(() => closes.length).toBeGreaterThanOrEqual(2); 398 expect(await page.evaluate(() => window.hcp095Fixture.publicContains())).toBe( 399 false 400 ); 401 }); 402 test('actual native retention abort pauses both subscriptions without durable credit', async ({ 403 page 404 }) => { 405 frames = [eventFrom(await page.evaluate(() => window.hcp095Fixture.outer))]; 406 await page.evaluate(() => { 407 const f = window.hcp095Fixture; 408 f.faultRetention('abort'); 409 f.capture(); 410 f.start(); 411 }); 412 await expect 413 .poll(() => page.evaluate(() => window.hcp095Fixture.snapshot()?.state)) 414 .toBe('needs_action'); 415 expect( 416 await page.evaluate(async () => { 417 const f = window.hcp095Fixture; 418 f.restoreFault(); 419 return { snapshot: f.snapshot(), stored: await f.stored() }; 420 }) 421 ).toMatchObject({ 422 snapshot: { retained: 0, reason: 'aborted' }, 423 stored: undefined 424 }); 425 });