search-results.spec.ts (12730B)
1 import { expect, test } from '@playwright/test'; 2 import { createHash } from 'node:crypto'; 3 import { execFileSync } from 'node:child_process'; 4 import { 5 cp, 6 mkdtemp, 7 readFile, 8 readdir, 9 rm, 10 writeFile 11 } from 'node:fs/promises'; 12 import { tmpdir } from 'node:os'; 13 import path from 'node:path'; 14 import { fileURLToPath } from 'node:url'; 15 import { once } from 'node:events'; 16 import { finalizeEvent } from 'applesauce-core/helpers'; 17 import WebSocket, { WebSocketServer, type RawData } from 'ws'; 18 function wireText(bytes: RawData): string { 19 const buffer = Array.isArray(bytes) 20 ? Buffer.concat(bytes) 21 : Buffer.isBuffer(bytes) 22 ? bytes 23 : Buffer.from(bytes); 24 return buffer.toString('utf8'); 25 } 26 import { createStaticHarness } from '../integration/harness/static.ts'; 27 const capsule = fileURLToPath(new URL('../../../', import.meta.url)); 28 let directory: string; 29 let server: Awaited<ReturnType<typeof createStaticHarness>>; 30 // Verification fixture: compile exact primary source, deriving only its fixed 31 // deployment allowlist. Never alter the primary output or production policy. 32 test.beforeAll(async () => { 33 test.setTimeout(86_400_000); 34 directory = await mkdtemp(path.join(tmpdir(), 'hcp043-search-')); 35 try { 36 const checkout = path.join(directory, 'checkout'), 37 web = path.join(checkout, 'web'); 38 execFileSync('git', [ 39 'clone', 40 '--quiet', 41 '--no-hardlinks', 42 capsule, 43 checkout 44 ]); 45 for (const relative of ['package.json', 'pnpm-lock.yaml', 'src']) 46 await cp(path.join(capsule, 'web', relative), path.join(web, relative), { 47 recursive: true 48 }); 49 const identities: { path: string; sha256: string }[] = []; 50 async function identify(dir: string, prefix = '') { 51 for (const entry of await readdir(dir, { withFileTypes: true })) { 52 const relative = prefix + entry.name; 53 if (entry.isDirectory()) 54 await identify(path.join(dir, entry.name), relative + '/'); 55 else 56 identities.push({ 57 path: relative, 58 sha256: createHash('sha256') 59 .update(await readFile(path.join(dir, entry.name))) 60 .digest('hex') 61 }); 62 } 63 } 64 await identify(path.join(web, 'src')); 65 await cp( 66 path.join(capsule, 'web/tools/source-boundaries.mjs'), 67 path.join(web, 'tools/source-boundaries.mjs') 68 ); 69 identities.push({ 70 path: 'tools/source-boundaries.mjs', 71 sha256: createHash('sha256') 72 .update(await readFile(path.join(web, 'tools/source-boundaries.mjs'))) 73 .digest('hex') 74 }); 75 const policy = 76 "import { validateRelayPolicy } from './relays.ts'; const policy=validateRelayPolicy(JSON.stringify({schemaVersion:1,public:[{origin:'wss://one.example.org',read:true,write:false,nip50:false},{origin:'wss://failed.example.org',read:true,write:false,nip50:false}],inbox:[],postingEnabled:false,messagingEnabled:false,operatorDenylist:[]})); if(!policy) throw new Error('fixture_policy'); export const deploymentRelayPolicy=policy;"; 77 await writeFile( 78 path.join(web, 'src/lib/config/deployment-relays.ts'), 79 policy 80 ); 81 const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], { 82 cwd: path.join(capsule, 'web') 83 }) 84 .toString() 85 .trim(); 86 const installed = execFileSync( 87 'corepack', 88 [ 89 'pnpm', 90 'install', 91 '--offline', 92 '--frozen-lockfile', 93 '--store-dir', 94 path.dirname(sourceStore) 95 ], 96 { cwd: web, timeout: 86400000 } 97 ).toString(); 98 const sourceAudit = execFileSync( 99 process.execPath, 100 ['tools/check-source.mjs'], 101 { cwd: web } 102 ).toString(); 103 execFileSync(process.execPath, ['tools/build-info.mjs'], { cwd: web }); 104 const compiled = execFileSync( 105 process.execPath, 106 ['node_modules/vite/bin/vite.js', 'build'], 107 { cwd: web, timeout: 86400000 } 108 ).toString(); 109 console.log( 110 JSON.stringify({ 111 fixture: 'HCP043_TEST_ONLY_FIXED_POLICY', 112 identities, 113 policy, 114 policySha256: createHash('sha256').update(policy).digest('hex'), 115 sourceStore, 116 installed, 117 sourceAudit, 118 compiled 119 }) 120 ); 121 server = await createStaticHarness({ buildRoot: path.join(web, 'build') }); 122 } catch (error) { 123 await rm(directory, { recursive: true, force: true }); 124 throw error; 125 } 126 }); 127 test.afterAll(async () => { 128 if (server) await server.close(); 129 if (directory) await rm(directory, { recursive: true, force: true }); 130 }); 131 test('real search renders verified loopback rows, persistent partial notices, independent row actions and restored query/scroll', async ({ 132 browser 133 }) => { 134 const corpus = JSON.parse( 135 await readFile( 136 path.join(capsule, 'contracts/interop/food_availability/corpus.v1.json'), 137 'utf8' 138 ) 139 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 140 const base = JSON.parse( 141 corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous 142 ) as { tags: string[][]; content: string; created_at: number }; 143 const key = crypto.getRandomValues(new Uint8Array(32)); 144 const listings = Array.from({ length: 26 }, (_, n) => 145 finalizeEvent( 146 { 147 kind: 30402, 148 created_at: base.created_at - n, 149 tags: base.tags.map((t) => 150 t[0] === 'd' 151 ? ['d', `browser_${n}`] 152 : t[0] === 'title' 153 ? ['title', `Carrots ${n}`] 154 : [...t] 155 ), 156 content: base.content 157 }, 158 key 159 ) 160 ); 161 const profile = finalizeEvent( 162 { 163 kind: 0, 164 created_at: base.created_at, 165 tags: [], 166 content: JSON.stringify({ 167 display_name: '<img src=https://tracking.example.org>' 168 }) 169 }, 170 key 171 ); 172 key.fill(0); 173 const relay = new WebSocketServer({ 174 host: '127.0.0.1', 175 port: 0, 176 maxPayload: 65536 177 }); 178 const queries: Record<string, unknown>[] = [], 179 closed: string[] = []; 180 relay.on('connection', (socket) => { 181 socket.on('message', (bytes) => { 182 const frame = JSON.parse(wireText(bytes)) as unknown[]; 183 if (frame[0] === 'CLOSE') { 184 closed.push(String(frame[1])); 185 return; 186 } 187 if (frame[0] !== 'REQ') return; 188 const id = String(frame[1]), 189 filters = frame.slice(2) as Record<string, unknown>[]; 190 queries.push(...filters); 191 const kind = (filters[0].kinds as number[])[0]; 192 const values = 193 kind === 0 194 ? [profile] 195 : kind === 30402 196 ? listings.filter((v) => 197 filters.some( 198 (f) => 199 (!f.authors || 200 (f.authors as string[]).includes(v.pubkey)) && 201 (!f['#d'] || 202 (f['#d'] as string[]).includes( 203 v.tags.find((t) => t[0] === 'd')![1] 204 )) && 205 (!f.until || v.created_at <= Number(f.until)) 206 ) 207 ) 208 : []; 209 for (const value of values) 210 socket.send(JSON.stringify(['EVENT', id, value])); 211 socket.send(JSON.stringify(['EOSE', id])); 212 }); 213 }); 214 await once(relay, 'listening'); 215 const address = relay.address(); 216 if (!address || typeof address === 'string') throw Error('fixture_port'); 217 const context = await browser.newContext({ 218 viewport: { width: 320, height: 700 } 219 }), 220 bridges: WebSocket[] = [], 221 external: string[] = [], 222 failures: string[] = []; 223 try { 224 await context.route('**/*', (route) => { 225 if (new URL(route.request().url()).origin === server.url) 226 return route.continue(); 227 external.push(route.request().url()); 228 return route.abort(); 229 }); 230 await context.routeWebSocket('**/*', (route) => { 231 if (new URL(route.url()).hostname === 'failed.example.org') { 232 route.onMessage((message) => { 233 const frame = JSON.parse(String(message)) as unknown[]; 234 if (frame[0] === 'REQ') 235 route.send( 236 JSON.stringify(['CLOSED', frame[1], 'fixture source unavailable']) 237 ); 238 }); 239 return; 240 } 241 expect(new URL(route.url()).hostname).toBe('one.example.org'); 242 const bridge = new WebSocket(`ws://127.0.0.1:${address.port}`); 243 bridges.push(bridge); 244 const pending: (string | Buffer)[] = []; 245 bridge.on('open', () => { 246 for (const message of pending.splice(0)) bridge.send(message); 247 }); 248 bridge.on('message', (bytes) => route.send(wireText(bytes))); 249 route.onMessage((message) => { 250 if (bridge.readyState === WebSocket.OPEN) bridge.send(message); 251 else pending.push(message); 252 }); 253 route.onClose(() => { 254 bridge.close(); 255 }); 256 }); 257 const page = await context.newPage(); 258 page.on('pageerror', (e) => failures.push(e.message)); 259 await page.goto(server.url + '/search?q=carrots'); 260 const input = page.getByRole('textbox', { 261 name: 'What are you looking for?' 262 }); 263 await expect(input).toBeEnabled(); 264 await input.focus(); 265 const rows = page 266 .getByRole('listitem') 267 .filter({ has: page.getByRole('link', { name: /^Carrots / }) }); 268 try { 269 await expect(rows).toHaveCount(20); 270 } catch (error) { 271 console.log( 272 JSON.stringify({ 273 fixtureFailure: true, 274 failures, 275 queries, 276 external, 277 body: await page.locator('body').innerText() 278 }) 279 ); 280 throw error; 281 } 282 await expect(input).toBeFocused(); 283 await expect( 284 page.getByText('These results may be incomplete.', { exact: false }) 285 ).toBeVisible(); 286 await expect( 287 page.getByRole('button', { name: 'Show more', exact: true }) 288 ).toBeVisible(); 289 const discovery = () => 290 queries.filter((q) => (q.kinds as number[])[0] === 30402 && !q.authors) 291 .length; 292 const before = discovery(); 293 await page.getByRole('button', { name: 'Show more', exact: true }).click(); 294 await expect(rows).toHaveCount(26); 295 expect(discovery()).toBe(before); 296 await page.waitForTimeout(350); 297 expect(discovery()).toBe(before); 298 const first = rows.first(); 299 await first.getByText('Publisher details', { exact: true }).click(); 300 await expect( 301 first.getByText(profile.pubkey, { exact: true }) 302 ).toBeVisible(); 303 expect(new URL(page.url()).pathname).toBe('/search'); 304 await expect( 305 page.getByRole('button', { name: 'Search older listings', exact: true }) 306 ).toBeVisible(); 307 expect( 308 await page.evaluate( 309 () => document.documentElement.scrollWidth <= innerWidth 310 ) 311 ).toBe(true); 312 await rows.nth(3).getByRole('link').scrollIntoViewIfNeeded(); 313 const scroll = await page.evaluate(() => scrollY); 314 await rows.nth(3).getByRole('link').click(); 315 await expect(page).toHaveURL(/\/products\/naddr/); 316 await page.goBack(); 317 await expect( 318 page.getByRole('textbox', { name: 'What are you looking for?' }) 319 ).toHaveValue('carrots'); 320 // Kit history snapshots and the reviewed scalar helper restore public query 321 // position after genuine rows render. No private context is retained. 322 await expect 323 .poll(() => page.evaluate(() => scrollY)) 324 .toBeCloseTo(scroll, -1); 325 await page 326 .getByRole('textbox', { name: 'What are you looking for?' }) 327 .fill('turnips'); 328 await page.getByRole('button', { name: 'Search', exact: true }).click(); 329 await expect(page).toHaveURL(server.url + '/search?q=turnips'); 330 await expect(rows).toHaveCount(0); 331 await page.goBack(); 332 await expect( 333 page.getByRole('textbox', { name: 'What are you looking for?' }) 334 ).toHaveValue('carrots'); 335 await expect(rows).toHaveCount(20); 336 await page.goForward(); 337 await expect(input).toHaveValue('turnips'); 338 await expect(rows).toHaveCount(0); 339 await page.goBack(); 340 await expect(input).toHaveValue('carrots'); 341 await expect(rows).toHaveCount(20); 342 const olderCount = discovery(); 343 await page 344 .getByRole('button', { name: 'Search older listings', exact: true }) 345 .click(); 346 await expect.poll(discovery).toBe(olderCount + 1); 347 await page.goto(server.url + '/about'); 348 await expect.poll(() => closed.length).toBeGreaterThan(0); 349 expect(external).toEqual([]); 350 expect(failures).toEqual([]); 351 expect(await page.evaluate(() => 'nostr' in window)).toBe(false); 352 } finally { 353 await context.close(); 354 for (const bridge of bridges) bridge.terminate(); 355 for (const socket of relay.clients) socket.terminate(); 356 await new Promise<void>((resolve, reject) => 357 relay.close((e) => (e ? reject(e) : resolve())) 358 ); 359 } 360 });