product-details.spec.ts (14317B)
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 { naddrEncode } from 'applesauce-core/helpers/pointers'; 17 import { finalizeEvent } from 'applesauce-core/helpers'; 18 import WebSocket, { WebSocketServer, type RawData } from 'ws'; 19 function wireText(bytes: RawData): string { 20 const buffer = Array.isArray(bytes) 21 ? Buffer.concat(bytes) 22 : Buffer.isBuffer(bytes) 23 ? bytes 24 : Buffer.from(bytes); 25 return buffer.toString('utf8'); 26 } 27 import { createStaticHarness } from '../integration/harness/static.ts'; 28 const capsule = fileURLToPath(new URL('../../../', import.meta.url)); 29 let directory: string; 30 let server: Awaited<ReturnType<typeof createStaticHarness>>; 31 // Verification fixture: compile exact primary source, deriving only its fixed 32 // deployment allowlist. Never alter the primary output or production policy. 33 test.beforeAll(async () => { 34 test.setTimeout(86_400_000); 35 directory = await mkdtemp(path.join(tmpdir(), 'hcp044-details-')); 36 try { 37 const checkout = path.join(directory, 'checkout'), 38 web = path.join(checkout, 'web'); 39 execFileSync('git', [ 40 'clone', 41 '--quiet', 42 '--no-hardlinks', 43 capsule, 44 checkout 45 ]); 46 for (const relative of ['package.json', 'pnpm-lock.yaml', 'src']) 47 await cp(path.join(capsule, 'web', relative), path.join(web, relative), { 48 recursive: true 49 }); 50 const identities: { path: string; sha256: string }[] = []; 51 async function identify(dir: string, prefix = '') { 52 for (const entry of await readdir(dir, { withFileTypes: true })) { 53 const relative = prefix + entry.name; 54 if (entry.isDirectory()) 55 await identify(path.join(dir, entry.name), relative + '/'); 56 else 57 identities.push({ 58 path: relative, 59 sha256: createHash('sha256') 60 .update(await readFile(path.join(dir, entry.name))) 61 .digest('hex') 62 }); 63 } 64 } 65 await identify(path.join(web, 'src')); 66 await cp( 67 path.join(capsule, 'web/tools/source-boundaries.mjs'), 68 path.join(web, 'tools/source-boundaries.mjs') 69 ); 70 identities.push({ 71 path: 'tools/source-boundaries.mjs', 72 sha256: createHash('sha256') 73 .update(await readFile(path.join(web, 'tools/source-boundaries.mjs'))) 74 .digest('hex') 75 }); 76 const policy = 77 "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;"; 78 await writeFile( 79 path.join(web, 'src/lib/config/deployment-relays.ts'), 80 policy 81 ); 82 const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], { 83 cwd: path.join(capsule, 'web') 84 }) 85 .toString() 86 .trim(); 87 const installed = execFileSync( 88 'corepack', 89 [ 90 'pnpm', 91 'install', 92 '--offline', 93 '--frozen-lockfile', 94 '--store-dir', 95 path.dirname(sourceStore) 96 ], 97 { cwd: web, timeout: 86400000 } 98 ).toString(); 99 const sourceAudit = execFileSync( 100 process.execPath, 101 ['tools/check-source.mjs'], 102 { cwd: web } 103 ).toString(); 104 execFileSync(process.execPath, ['tools/build-info.mjs'], { cwd: web }); 105 const compiled = execFileSync( 106 process.execPath, 107 ['node_modules/vite/bin/vite.js', 'build'], 108 { cwd: web, timeout: 86400000 } 109 ).toString(); 110 console.log( 111 JSON.stringify({ 112 fixture: 'HCP044_TEST_ONLY_FIXED_POLICY', 113 identities, 114 policy, 115 policySha256: createHash('sha256').update(policy).digest('hex'), 116 sourceStore, 117 installed, 118 sourceAudit, 119 compiled 120 }) 121 ); 122 server = await createStaticHarness({ buildRoot: path.join(web, 'build') }); 123 } catch (error) { 124 await rm(directory, { recursive: true, force: true }); 125 throw error; 126 } 127 }); 128 test.afterAll(async () => { 129 if (server) await server.close(); 130 if (directory) await rm(directory, { recursive: true, force: true }); 131 }); 132 test('real product reload renders verified facts, safe guest contact, explicit copy and truthful capability/status gates', async ({ 133 browser 134 }) => { 135 const corpus = JSON.parse( 136 await readFile( 137 path.join(capsule, 'contracts/interop/food_availability/corpus.v1.json'), 138 'utf8' 139 ) 140 ) as { vectors: { id: string; signed_wires: Record<string, string> }[] }; 141 const base = JSON.parse( 142 corpus.vectors.find((v) => v.id.endsWith('_032'))!.signed_wires.previous 143 ) as { tags: string[][]; content: string; created_at: number }; 144 const key = crypto.getRandomValues(new Uint8Array(32)); 145 const listings = ['active', 'sold', 'withdrawn', 'unsupported', 'future'].map( 146 (status, n) => 147 finalizeEvent( 148 { 149 kind: 30402, 150 created_at: 151 status === 'future' 152 ? Math.floor(Date.now() / 1000) + 36000 153 : base.created_at - n, 154 tags: 155 status === 'unsupported' 156 ? [ 157 ['d', status], 158 ['title', 'Other format'] 159 ] 160 : [ 161 ...base.tags.map((t) => 162 t[0] === 'd' 163 ? ['d', status] 164 : t[0] === 'title' 165 ? ['title', `Carrots ${status}`] 166 : t[0] === 'status' 167 ? ['status', status === 'sold' ? 'sold' : 'active'] 168 : [...t] 169 ), 170 ['image', 'https://tracking.example.org/image.png'] 171 ], 172 content: 173 '<img src=https://tracking.example.org> Contact only if supplied.\n\nPublic contact: https://contact.example.org/collect' 174 }, 175 key 176 ) 177 ); 178 const withdrawn = listings[2]; 179 const deletion = finalizeEvent( 180 { 181 kind: 5, 182 created_at: base.created_at + 1, 183 tags: [['e', withdrawn.id]], 184 content: '' 185 }, 186 key 187 ); 188 const profile = finalizeEvent( 189 { 190 kind: 0, 191 created_at: base.created_at, 192 tags: [], 193 content: JSON.stringify({ 194 display_name: '<img src=https://tracking.example.org>' 195 }) 196 }, 197 key 198 ); 199 key.fill(0); 200 const relay = new WebSocketServer({ 201 host: '127.0.0.1', 202 port: 0, 203 maxPayload: 65536 204 }); 205 const queries: Record<string, unknown>[] = [], 206 closed: string[] = []; 207 relay.on('connection', (socket) => { 208 socket.on('message', (bytes) => { 209 const frame = JSON.parse(wireText(bytes)) as unknown[]; 210 if (frame[0] === 'CLOSE') { 211 closed.push(String(frame[1])); 212 return; 213 } 214 if (frame[0] !== 'REQ') return; 215 const id = String(frame[1]), 216 filters = frame.slice(2) as Record<string, unknown>[]; 217 queries.push(...filters); 218 const kind = (filters[0].kinds as number[])[0]; 219 const values = 220 kind === 0 221 ? [profile] 222 : kind === 30402 223 ? listings.filter((v) => 224 filters.some( 225 (f) => 226 (!f.authors || 227 (f.authors as string[]).includes(v.pubkey)) && 228 (!f['#d'] || 229 (f['#d'] as string[]).includes( 230 v.tags.find((t) => t[0] === 'd')![1] 231 )) && 232 (!f.until || v.created_at <= Number(f.until)) 233 ) 234 ) 235 : kind === 5 236 ? [deletion] 237 : []; 238 for (const value of values) 239 socket.send(JSON.stringify(['EVENT', id, value])); 240 socket.send(JSON.stringify(['EOSE', id])); 241 }); 242 }); 243 await once(relay, 'listening'); 244 const address = relay.address(); 245 if (!address || typeof address === 'string') throw Error('fixture_port'); 246 const context = await browser.newContext({ 247 viewport: { width: 320, height: 700 }, 248 permissions: ['clipboard-read', 'clipboard-write'] 249 }), 250 bridges: WebSocket[] = [], 251 external: string[] = [], 252 failures: string[] = []; 253 try { 254 await context.route('**/*', (route) => { 255 if (new URL(route.request().url()).origin === server.url) 256 return route.continue(); 257 external.push(route.request().url()); 258 return route.abort(); 259 }); 260 await context.routeWebSocket('**/*', (route) => { 261 if (new URL(route.url()).hostname === 'failed.example.org') { 262 route.onMessage((message) => { 263 const frame = JSON.parse(String(message)) as unknown[]; 264 if (frame[0] === 'REQ') 265 route.send( 266 JSON.stringify(['CLOSED', frame[1], 'fixture source unavailable']) 267 ); 268 }); 269 return; 270 } 271 expect(new URL(route.url()).hostname).toBe('one.example.org'); 272 const bridge = new WebSocket(`ws://127.0.0.1:${address.port}`); 273 bridges.push(bridge); 274 const pending: (string | Buffer)[] = []; 275 bridge.on('open', () => { 276 for (const message of pending.splice(0)) bridge.send(message); 277 }); 278 bridge.on('message', (bytes) => route.send(wireText(bytes))); 279 route.onMessage((message) => { 280 if (bridge.readyState === WebSocket.OPEN) bridge.send(message); 281 else pending.push(message); 282 }); 283 route.onClose(() => { 284 bridge.close(); 285 }); 286 }); 287 const page = await context.newPage(); 288 page.on('pageerror', (e) => failures.push(e.message)); 289 const coordinate = (identifier: string) => 290 naddrEncode({ kind: 30402, pubkey: listings[0].pubkey, identifier }); 291 const href = (identifier: string) => 292 server.url + '/products/' + coordinate(identifier); 293 await page.goto(href('active')); 294 await expect( 295 page.getByRole('heading', { name: 'Carrots active', exact: true }) 296 ).toBeVisible(); 297 await expect( 298 page.getByRole('button', { name: 'Message seller', exact: true }) 299 ).toBeDisabled(); 300 await expect( 301 page.getByText( 302 'This is last-known information. The listing status check is incomplete.' 303 ) 304 ).toBeVisible(); 305 await expect( 306 page.getByRole('button', { name: 'Manage listing' }) 307 ).toHaveCount(0); 308 await expect(page.locator('img,iframe,textarea')).toHaveCount(0); 309 await page.getByText('Publisher identity', { exact: true }).click(); 310 await expect(page.getByText(profile.pubkey, { exact: true })).toBeVisible(); 311 await page.getByText('Other contact details', { exact: true }).click(); 312 await expect( 313 page.getByRole('link', { 314 name: 'https://contact.example.org/collect', 315 exact: true 316 }) 317 ).toHaveAttribute('href', 'https://contact.example.org/collect'); 318 const contactLink = page.getByRole('link', { 319 name: 'https://contact.example.org/collect', 320 exact: true 321 }); 322 expect(await contactLink.getAttribute('rel')).toBe('noopener noreferrer'); 323 expect(await contactLink.getAttribute('referrerpolicy')).toBe( 324 'no-referrer' 325 ); 326 await page.getByRole('button', { name: 'Copy link', exact: true }).click(); 327 await expect(page.getByRole('main').getByRole('status')).toHaveText( 328 'Link copied.' 329 ); 330 expect(await page.evaluate(() => navigator.clipboard.readText())).toBe( 331 href('active') 332 ); 333 // Test-only anchor exercises Kit client parameter navigation on the actual 334 // component; survival proves this transition did not reload the document. 335 await page.evaluate((target) => { 336 const link = document.createElement('a'); 337 link.href = target; 338 link.textContent = 'Fixture next food'; 339 link.id = 'fixture-client-transition'; 340 document.body.append(link); 341 }, href('sold')); 342 await page 343 .getByRole('link', { name: 'Fixture next food', exact: true }) 344 .click(); 345 await expect( 346 page.getByText('The seller marked this listing sold.', { exact: true }) 347 ).toBeVisible(); 348 await expect(page.locator('#fixture-client-transition')).toHaveCount(1); 349 await page.goBack(); 350 await expect( 351 page.getByRole('heading', { name: 'Carrots active', exact: true }) 352 ).toBeVisible(); 353 await page.reload(); 354 await expect( 355 page.getByRole('heading', { name: 'Carrots active', exact: true }) 356 ).toBeVisible(); 357 for (const [identifier, notice] of [ 358 ['sold', 'The seller marked this listing sold.'], 359 ['withdrawn', 'This listing was withdrawn by its publisher.'], 360 [ 361 'unsupported', 362 'The latest known listing uses an unsupported food format.' 363 ], 364 [ 365 'future', 366 'Listing time could not be confirmed. Food details are unavailable.' 367 ], 368 [ 369 'unobserved', 370 'This listing was not observed in the sources checked. It may be unavailable or missing from these sources.' 371 ] 372 ]) { 373 await page.goto(href(identifier)); 374 await expect(page.getByText(notice, { exact: true })).toBeVisible(); 375 await expect( 376 page.getByRole('button', { name: 'Message seller', exact: true }) 377 ).toHaveCount(0); 378 } 379 await page.goto(server.url + '/products/invalid-reference'); 380 await expect(page.getByText('Not Found', { exact: true })).toBeVisible(); 381 expect(external).toEqual([]); 382 expect(failures).toEqual([]); 383 expect(await page.evaluate(() => 'nostr' in window)).toBe(false); 384 console.log( 385 JSON.stringify({ 386 fixture: 'HCP044_GENUINE_LOOPBACK_DETAIL', 387 queries, 388 external, 389 failures 390 }) 391 ); 392 } finally { 393 await context.close(); 394 for (const bridge of bridges) bridge.terminate(); 395 for (const socket of relay.clients) socket.terminate(); 396 await new Promise<void>((resolve, reject) => 397 relay.close((e) => (e ? reject(e) : resolve())) 398 ); 399 } 400 });