account-isolation.spec.ts (9917B)
1 import { expect, test, type Page } from '@playwright/test'; 2 import { build } from 'vite'; 3 import { svelte } from '@sveltejs/vite-plugin-svelte'; 4 import { fileURLToPath } from 'node:url'; 5 import { createHash } from 'node:crypto'; 6 import { once } from 'node:events'; 7 import { WebSocketServer } from 'ws'; 8 import { createStaticHarness } from '../integration/harness/static.ts'; 9 import type * as Fixture from './harness/account-isolation.ts'; 10 declare global { 11 interface Window { 12 hcp137: typeof Fixture; 13 hcp137Thread?: Awaited<ReturnType<typeof Fixture.thread.renderFixture>>; 14 hcp137Auth?: Awaited<ReturnType<typeof Fixture.auth.makeAuthFixture>>; 15 hcp137OldAuth?: Awaited<ReturnType<typeof Fixture.auth.makeAuthFixture>>; 16 hcp137Pending?: Promise<boolean>; 17 hcp137Action?: NonNullable< 18 Awaited<ReturnType<typeof Fixture.auth.beginInboxAuthentication>> 19 >; 20 } 21 } 22 let server: Awaited<ReturnType<typeof createStaticHarness>>, 23 sockets: WebSocketServer, 24 endpoint: string, 25 bundle: string; 26 let authOwners: string[] = [], 27 closedOwners: string[] = []; 28 test.beforeAll(async () => { 29 server = await createStaticHarness(); 30 sockets = new WebSocketServer({ 31 host: '127.0.0.1', 32 port: 0, 33 maxPayload: 65536 34 }); 35 await once(sockets, 'listening'); 36 const address = sockets.address(); 37 if (!address || typeof address === 'string') throw Error('missing loopback'); 38 endpoint = 'ws://127.0.0.1:' + address.port; 39 sockets.on('connection', (socket) => { 40 let authenticatedOwner: string | undefined; 41 socket.send(JSON.stringify(['AUTH', 'hcp137-current-connection'])); 42 socket.on('close', () => { 43 if (authenticatedOwner) closedOwners.push(authenticatedOwner); 44 }); 45 socket.on('message', (bytes) => { 46 const raw = Buffer.isBuffer(bytes) 47 ? bytes 48 : Array.isArray(bytes) 49 ? Buffer.concat(bytes) 50 : Buffer.from(bytes); 51 const frame = JSON.parse(raw.toString()) as unknown[]; 52 if (frame[0] === 'AUTH') { 53 const event = frame[1] as { id: string; pubkey: string }; 54 authenticatedOwner = event.pubkey; 55 authOwners.push(event.pubkey); 56 socket.send(JSON.stringify(['OK', event.id, true, ''])); 57 } 58 if (frame[0] === 'REQ') socket.send(JSON.stringify(['EOSE', frame[1]])); 59 if (frame[0] === 'EVENT') 60 socket.send( 61 JSON.stringify(['OK', (frame[1] as { id: string }).id, true, '']) 62 ); 63 }); 64 }); 65 const result = await build({ 66 configFile: false, 67 logLevel: 'silent', 68 plugins: [svelte({ configFile: false })], 69 resolve: { 70 conditions: ['browser'], 71 alias: { 72 '$app/navigation': fileURLToPath( 73 new URL('./harness/conversation-thread.ts', import.meta.url) 74 ) 75 } 76 }, 77 build: { 78 write: false, 79 minify: false, 80 lib: { 81 entry: fileURLToPath( 82 new URL('./harness/account-isolation.ts', import.meta.url) 83 ), 84 name: 'hcp137', 85 formats: ['iife'] 86 } 87 } 88 }); 89 const output = Array.isArray(result) ? result[0] : result; 90 if (!('output' in output)) throw Error('missing actual bundle'); 91 const chunks = output.output.filter((item) => item.type === 'chunk'); 92 expect(chunks).toHaveLength(1); 93 bundle = chunks[0].code; 94 console.log( 95 JSON.stringify({ 96 fixture: 'HCP137_ORIGINAL_ACCOUNT_CONSUMERS', 97 bundleSha256: createHash('sha256').update(bundle).digest('hex'), 98 moduleIds: Object.keys(chunks[0].modules), 99 qualification: 100 'Actual Chromium/native storage/SDK signed AUTH on controlled loopback; dummy AUTH self probe and original genuine thread decryption are distinct; no installed extension/deployed host Q.' 101 }) 102 ); 103 }); 104 test.afterAll(async () => { 105 for (const socket of sockets.clients) socket.terminate(); 106 await new Promise<void>((resolve) => sockets.close(() => resolve())); 107 await server.close(); 108 }); 109 test.beforeEach(async ({ page }) => { 110 authOwners = []; 111 closedOwners = []; 112 await page.addInitScript( 113 ({ endpoint }) => { 114 const Native = window.WebSocket; 115 window.WebSocket = class extends Native { 116 constructor(url: string | URL, protocols?: string | string[]) { 117 if ( 118 ![ 119 'wss://peer.example.org', 120 'wss://archive.example.org', 121 'wss://discovery.example.org', 122 'wss://inbox.example.org' 123 ].includes(new URL(String(url)).origin) 124 ) 125 throw Error('unapproved fixture destination'); 126 super(endpoint, protocols); 127 } 128 }; 129 }, 130 { endpoint } 131 ); 132 await page.goto(server.url + '/search'); 133 await page.addScriptTag({ content: bundle }); 134 }); 135 test.afterEach(async ({ page }) => { 136 if (!page.isClosed()) 137 await page.evaluate(async () => { 138 window.hcp137Thread?.settle(); 139 await window.hcp137Pending; 140 window.hcp137Auth?.close(); 141 window.hcp137OldAuth?.close(); 142 await window.hcp137Thread?.close(); 143 }); 144 }); 145 async function successor(page: Page) { 146 await page.evaluate(async () => { 147 const s = window.hcp137.auth, 148 f = window.hcp137Auth; 149 const current = f ?? (await s.makeAuthFixture()); 150 window.hcp137Auth = current; 151 const action = await s.beginInboxAuthentication( 152 current.pool, 153 s.inbox, 154 'reviewed_connection_auth' 155 ); 156 if (!action) throw Error('missing successor AUTH'); 157 window.hcp137Action = action; 158 }); 159 await expect 160 .poll(() => 161 page.evaluate( 162 () => 163 window.hcp137Action && 164 window.hcp137.auth.inboxAuthSnapshot(window.hcp137Action)?.state 165 ) 166 ) 167 .toBe('challenge'); 168 const action = await page.evaluate(async () => { 169 const s = window.hcp137.auth, 170 f = window.hcp137Auth, 171 action = window.hcp137Action; 172 if (!f || !action) throw Error('missing actual successor action'); 173 return { 174 status: (await s.respondInboxAuthentication(action)).status, 175 owner: f.owner, 176 ownership: f.ownership() 177 }; 178 }); 179 expect(action.status).toBe('accepted'); 180 expect(action.ownership.private).toBe(true); 181 expect(action.ownership.identity).toBe(true); 182 return action; 183 } 184 for (const held of [false, true]) 185 test(`${held ? 'held late decrypt' : 'rendered thread'} cannot disclose or write into a different accepted account`, async ({ 186 page 187 }) => { 188 await page.evaluate(async () => { 189 window.hcp137Thread = await window.hcp137.thread.renderFixture(); 190 }); 191 await page 192 .getByRole('button', { name: 'Check current preference' }) 193 .click(); 194 if (held) { 195 await page.evaluate(() => { 196 const f = window.hcp137Thread; 197 if (!f) throw Error('missing original thread'); 198 f.mode('hold_decrypt'); 199 window.hcp137Pending = f.unlock(); 200 }); 201 await expect 202 .poll(() => page.evaluate(() => window.hcp137Thread?.pending())) 203 .toBe(true); 204 } else { 205 await page 206 .getByRole('button', { name: 'Unlock messages', exact: true }) 207 .click(); 208 await expect( 209 page.getByText('Actual encrypted thread fixture', { exact: true }) 210 ).toBeVisible(); 211 } 212 const original = await page.evaluate(async () => { 213 const f = window.hcp137Thread; 214 if (!f) throw Error('missing original thread'); 215 const native = await f.native(); 216 f.logout(); 217 return { owner: f.owner, native, id: f.conversationId }; 218 }); 219 await expect(page.locator('[data-message-id]')).toHaveCount(0); 220 if (held) { 221 // The page-local provider slot stays occupied until the original prompt settles. 222 expect(await page.evaluate(() => window.hcp137Thread?.pending())).toBe( 223 true 224 ); 225 await page.evaluate(() => window.hcp137Thread?.settle()); 226 expect(await page.evaluate(() => window.hcp137Pending)).toBe(false); 227 } 228 const next = await successor(page); 229 expect(next.owner).not.toBe(original.owner); 230 expect(authOwners).toEqual([next.owner]); 231 const after = await page.evaluate(async () => { 232 const f = window.hcp137Thread; 233 if (!f) throw Error('missing stale consumer'); 234 return { 235 resolve: await f.resolve(f.conversationId), 236 thread: f.thread(), 237 native: await f.native(), 238 current: window.hcp137Auth?.ownership() 239 }; 240 }); 241 expect(after.resolve).toBe(false); 242 expect(after.thread.status).not.toBe('ready'); 243 expect(after.native).toEqual(original.native); 244 expect(after.current?.identity).toBe(true); 245 expect(after.current?.private).toBe(true); 246 await expect(page.locator('[data-message-id]')).toHaveCount(0); 247 await expect( 248 page.getByText('Actual encrypted thread fixture', { exact: true }) 249 ).toHaveCount(0); 250 expect(page.url()).not.toContain(original.owner); 251 expect(page.url()).not.toContain(next.owner); 252 await expect(page).toHaveTitle('HarvestCircle'); 253 }); 254 test('logout closes original private AUTH socket and clears cache before different-account AUTH', async ({ 255 page 256 }) => { 257 const first = await successor(page); 258 await page.evaluate(() => { 259 window.hcp137OldAuth = window.hcp137Auth; 260 window.hcp137Auth = undefined; 261 window.hcp137OldAuth?.logout(); 262 }); 263 await expect.poll(() => closedOwners).toContain(first.owner); 264 const old = await page.evaluate(() => window.hcp137OldAuth?.ownership()); 265 expect(old?.identity).toBe(false); 266 expect(old?.private).not.toBe(true); 267 expect(old?.cache).toEqual({ closed: true, count: 0, bytes: 0 }); 268 const next = await successor(page); 269 expect(next.owner).not.toBe(first.owner); 270 expect(authOwners).toEqual([first.owner, next.owner]); 271 const stable = await page.evaluate(() => ({ 272 old: window.hcp137OldAuth?.ownership(), 273 current: window.hcp137Auth?.ownership() 274 })); 275 expect(stable.old).toEqual(old); 276 expect(stable.current?.private).toBe(true); 277 expect(stable.current?.identity).toBe(true); 278 });