import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import assert from 'node:assert/strict'; import {createRequire} from 'node:module'; import {fileURLToPath} from 'node:url'; const {chromium, webkit, devices} = await import(process.env.PLAYWRIGHT_MODULE || 'playwright'); const require = createRequire(import.meta.url); const {createApp} = require('../server/app.cjs'); const C = require('../server/catalog.cjs'); const U = require('../server/util.cjs'); const build = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..'); const out = path.resolve(process.env.PILOT_QA_OUTPUT || path.join(build, 'qa-catalog')); assert(out.startsWith(build + path.sep) && !out.startsWith(path.join(build, 'project') + path.sep), 'QA output must stay inside the privacy build, outside the distributable project'); fs.mkdirSync(out, {recursive: true}); for (const filename of ['RESULTS.json', 'FAILURES.json']) fs.rmSync(path.join(out, filename), {force: true}); const NOW = '2026-10-22T12:00:00.000Z'; const PASSWORD = 'Fictional catalogue privacy browser password!'; const languages = ['en', 'pt', 'es', 'fr', 'ar', 'zh'].filter(l => !process.env.PILOT_CATALOG_LANG || l === process.env.PILOT_CATALOG_LANG); const engines = [['chromium', chromium], ['webkit', webkit]].filter(([name]) => !process.env.PILOT_CATALOG_ENGINE || name === process.env.PILOT_CATALOG_ENGINE); assert(languages.length && engines.length, 'invalid language/engine filter must not produce an empty passing matrix'); const results = [], failures = [], errors = []; const searchExamples = { en: 'I want real estate in Dubai up to USD 50k', pt: 'Quero imóveis em Dubai até USD 50 mil', es: 'Quiero inmuebles en Dubai hasta USD 50 mil', fr: 'Je cherche immobilier Dubai pour USD 50k', ar: 'اريد شراء عقارات في دبي USD ٥٠k', zh: '我想购买迪拜的房地产资产 USD 50k' }; const searchMatches = ['DEMO-OFFER-001', 'DEMO-OFFER-021']; const fixtureCompanies = Array.from({length: 20}, (_, i) => String(i + 1).padStart(3, '0')) .flatMap(id => [C.getCompany('DEMO-BUYER-' + id), C.getCompany('DEMO-SELLER-' + id)]); const hash = await U.passwordHash(PASSWORD); function noDirectory(value, label) { if (!value || typeof value !== 'object') return; for (const [key, child] of Object.entries(value)) { assert(!['companies', 'sellerId', 'referenceBuyerId', 'counterpartyId'].includes(key), label + ': leaked ' + key); noDirectory(child, label + '.' + key); } } function scopedExample(value, role, label) { assert.equal(value.buyer, null, label + ': reference buyer'); assert.equal(value.state.catalogContext?.buyer ?? null, null, label + ': nested buyer'); noDirectory(value, label); assert.deepEqual(value.artifacts.map(a => a.type).sort(), ['checklist', 'costs', 'factsheet', 'ownership']); const text = JSON.stringify(value); for (const company of fixtureCompanies.filter(c => c.role === 'buyer')) { assert(!text.includes(company.name) && !text.includes(company.contact) && !text.includes(company.id), label + ': buyer identity'); } if (role === 'holder') assert.equal(value.seller, null, label + ': seller-to-seller profile'); else { assert.equal(value.seller.name, C.getCompany(C.getOffer(value.offer.id).sellerId).name); for (const key of ['id', 'alias', 'active', 'profileComplete', 'contact', 'mandate', 'preferences']) { assert(!Object.hasOwn(value.seller, key), label + ': seller private ' + key); } } } async function layout(page, label) { await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); await page.waitForFunction(() => [...document.images].every(image => image.complete)); const check = await page.evaluate(() => ({ overflow: document.documentElement.scrollWidth > innerWidth + 1, ids: [...document.querySelectorAll('[id]')].map(e => e.id), labels: [...document.querySelectorAll('input:not([type=hidden]),select,textarea')] .filter(e => !e.labels?.length && !e.getAttribute('aria-label') && !e.getAttribute('aria-labelledby')).map(e => e.id), images: [...document.images].filter(e => !e.naturalWidth).map(e => e.src), missing: Object.entries(PilotCopy).flatMap(([language, copy]) => [...CatalogCopyKeys, ...SharedCopyKeys, ...SearchCopyKeys, ...(window.ProductCopyKeys || [])] .filter(key => typeof copy[key] !== 'string' || !copy[key]).map(key => language + ':' + key)), icons: [...document.querySelectorAll('i[data-lucide]')].map(e => e.dataset.lucide), invalid: /undefined|Missing translation/.test(document.body.innerText), directory: document.querySelectorAll('[data-nav=companies],[data-ui=catalog-company],a[href="#companies"],a[href^="#company="],.company-item').length, lang: document.documentElement.lang, dir: document.documentElement.dir })); assert.equal(check.overflow, false, label + ': horizontal overflow'); assert.equal(check.ids.length, new Set(check.ids).size, label + ': duplicate IDs'); for (const key of ['labels', 'images', 'missing', 'icons']) assert.deepEqual(check[key], [], label + ': ' + key); assert.equal(check.invalid, false, label + ': invalid text'); assert.equal(check.directory, 0, label + ': directory navigation'); return check; } async function route(page, target, selector) { await page.evaluate(target => { location.hash = target; }, target); if (selector) await page.locator(selector).first().waitFor(); } async function search(page, value, count) { const input = page.locator('#catalog-query'); await input.fill(value); if (await input.evaluate(element => Boolean(element.form))) await input.press('Enter'); await page.waitForFunction(expected => document.querySelectorAll('[data-search-results] .catalog-card').length === expected, count); } async function expectSearch(page) { const ids = await page.locator('[data-search-results] .catalog-card').evaluateAll(cards => cards.map(card => card.dataset.offer).sort()); assert.deepEqual(ids, searchMatches, 'localized natural-language search must return only matching asset/market/ticket offers'); } async function voice(page, lang) { const status = async key => { const expected = await page.evaluate(({lang, key}) => PilotCopy[lang][key], {lang, key}); assert((await page.locator('#alerts').innerText()).includes(expected), 'localized voice status: ' + key); }; await page.evaluate(() => { GlemoSearch.stopVoice(); window.__privacyVoice = {constructed: 0, started: 0, stopped: 0, confirmations: 0, messages: [], languages: []}; for (const key of ['SpeechRecognition', 'webkitSpeechRecognition']) { Object.defineProperty(window, key, {value: undefined, writable: true, configurable: true}); } window.confirm = text => { __privacyVoice.confirmations++; __privacyVoice.messages.push(text); return false; }; }); await page.locator('[data-ui=voice-search]').click(); await status('searchVoiceUnavailable'); assert.equal(await page.evaluate(() => __privacyVoice.confirmations), 0, 'unavailable browser must not request voice consent'); await page.evaluate(() => { window.SpeechRecognition = class { constructor() { __privacyVoice.constructed++; window.__privacyRecognition = this; } start() { __privacyVoice.started++; __privacyVoice.languages.push(this.lang); this.onstart?.(); } stop() { __privacyVoice.stopped++; this.onend?.(); } abort() { this.onend?.(); } }; }); await page.locator('[data-ui=voice-search]').click(); await status('searchVoiceCancelled'); assert.equal(await page.evaluate(() => __privacyVoice.constructed), 0, 'recognizer must not be created without consent'); await page.evaluate(() => { window.confirm = text => { __privacyVoice.confirmations++; __privacyVoice.messages.push(text); return true; }; }); await page.locator('[data-ui=voice-search]').click(); await status('searchListening'); const first = await page.evaluate(() => __privacyVoice); assert.equal(first.started, 1); assert.equal(first.constructed, 1); assert.equal(first.languages[0], {en: 'en-US', pt: 'pt-BR', es: 'es-ES', fr: 'fr-FR', ar: 'ar-AE', zh: 'zh-CN'}[lang]); const consent = await page.evaluate(lang => PilotCopy[lang].searchVoiceConsent, lang); assert(first.messages.every(message => message === consent), 'voice consent must be localized and disclose the provider'); await page.locator('[data-ui=voice-search]').click(); assert.equal(await page.evaluate(() => __privacyVoice.stopped), 1, 'second microphone click stops active recognition'); assert.equal(await page.evaluate(() => __privacyVoice.started), 1, 'second click must not start another recognizer'); await page.locator('[data-ui=voice-search]').click(); await page.evaluate(query => { __privacyRecognition.onresult({results: [[{transcript: query}]]}); __privacyRecognition.onend(); }, searchExamples[lang]); await expectSearch(page); assert.equal(await page.locator('#catalog-query').inputValue(), searchExamples[lang]); await page.locator('[data-ui=voice-search]').click(); await page.evaluate(() => { __privacyRecognition.onerror({error: 'not-allowed'}); __privacyRecognition.onend(); }); await status('searchVoiceDenied'); assert.equal(await page.locator('#catalog-query').inputValue(), searchExamples[lang], 'denied voice input must preserve the current query'); await search(page, '', 24); } async function makeFixture() { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'glemo-catalog-privacy-')); const app = await createApp({dataDir: dir, now: () => NOW}); try { const origin = await app.listen(), people = {}; for (const role of ['admin', 'buyer', 'holder']) { const id = U.id(), org = U.id(), alias = 'catalog-privacy-' + role; app.store.run('INSERT INTO organizations VALUES (?,?,?)', org, 'DEMO isolated ' + role, NOW); app.store.run('INSERT INTO users VALUES (?,?,?,?,?,?,?)', id, alias, role, org, hash, 1, NOW); app.store.run('INSERT INTO profiles VALUES (?,?,?,?)', id, JSON.stringify({completed: true, country: 'AE', categories: ['Real estate'], qualified: true, history: 'DEMO PRIVATE ' + role, referrals: '', shareReferences: false, preferences: {inApp: true, email: false, push: false}}), 1, NOW); people[role] = {id, alias}; } return {app, dir, origin, people}; } catch (error) { await app.close(); fs.rmSync(dir, {recursive: true, force: true}); throw error; } } async function capture(page, engine, label) { // WebKit injects styles during capture; functional contexts always retain the real CSP. let target = page, clone; if (engine === 'webkit') { clone = await page.context().browser().newContext({viewport: page.viewportSize(), storageState: await page.context().storageState(), bypassCSP: true}); target = await clone.newPage(); await target.goto(page.url()); await target.locator('.catalog-card').first().waitFor(); } try { await target.screenshot({path: path.join(out, label + '.png'), caret: 'initial'}); } finally { await clone?.close(); } } for (const [engine, type] of engines) { let browser, fixture; try { browser = await type.launch(engine === 'chromium' ? {channel: 'chrome', headless: true} : {headless: true}); fixture = await makeFixture(); const {app, origin, people} = fixture; for (const role of ['buyer', 'holder']) for (const viewport of ['desktop', 'mobile']) { const context = await browser.newContext({ ...(viewport === 'mobile' ? (engine === 'webkit' ? devices['iPhone 13'] : devices['Pixel 7']) : {viewport: {width: 1440, height: 900}}), acceptDownloads: true, reducedMotion: 'reduce' }); try { const outbound = []; await context.route('**/*', request => { const url = new URL(request.request().url()); if (url.origin === origin || url.protocol === 'blob:') return request.continue(); outbound.push(request.request().url()); return request.abort(); }); const login = await context.request.post(origin + '/api/auth/login', { headers: {Origin: origin}, data: {alias: people[role].alias, password: PASSWORD} }); assert.equal(login.status(), 200, await login.text()); const page = await context.newPage(); page.setDefaultTimeout(10000); const originalWidth = page.viewportSize().width; let currentLabel = engine + '-' + role + '-' + viewport; page.on('pageerror', error => errors.push({label: currentLabel, message: error.message})); page.on('console', message => { if (message.type() === 'error' && /Content Security Policy|Refused to/.test(message.text())) { errors.push({label: currentLabel, message: message.text()}); } }); for (const lang of languages) { const label = currentLabel = engine + '-' + role + '-' + viewport + '-' + lang; try { const response = await context.request.get(origin + '/api/catalog'); assert.equal(response.status(), 200); const data = await response.json(); assert.deepEqual(Object.keys(data).sort(), ['offers', 'simulation', 'version']); assert.equal(data.offers.length, 24); noDirectory(data, label + ' catalogue'); for (const offer of data.offers) assert(!Object.hasOwn(offer, 'issuer'), label + ': catalogue issuer'); assert.equal((await context.request.get(origin + '/api/admin/fixtures?role=admin')).status(), 403); for (const url of ['/api/catalog/companies', '/api/catalog/companies/DEMO-BUYER-001']) { assert.equal((await context.request.get(origin + url)).status(), 404); } await page.goto(origin + '/?lang=' + lang + '#catalog'); await page.locator('.catalog-card').first().waitFor(); assert.equal(await page.locator('.catalog-card').count(), 24); const inspected = await layout(page, label + ' catalogue'); assert.equal(inspected.lang, lang); assert.equal(inspected.dir, lang === 'ar' ? 'rtl' : 'ltr'); const cards = await page.locator('.catalog-card').allTextContents(); for (const company of fixtureCompanies) assert(!cards.join('\n').includes(company.name), label + ': company profile on card'); await search(page, 'DEMO-OFFER-001', 1); await search(page, '', 24); assert.equal(await page.evaluate(() => typeof GlemoSearch.match), 'function', label + ': local intent parser loaded'); await search(page, searchExamples[lang], 2); await expectSearch(page); await search(page, '', 24); await voice(page, lang); assert.deepEqual(outbound, [], label + ': local search/mock voice must not make external requests'); await page.locator('#catalog-country').selectOption('HK'); await page.locator('#catalog-category').selectOption('Treasury'); assert.equal(await page.locator('.catalog-card').count(), 1); await page.locator('#catalog-country').selectOption(''); await page.locator('#catalog-category').selectOption(''); const nextLanguage = languages[(languages.indexOf(lang) + 1) % languages.length]; await page.locator('#language').selectOption(nextLanguage); assert.equal(await page.locator('html').getAttribute('lang'), nextLanguage); await page.locator('#language').selectOption(lang); for (const target of ['companies', 'company=DEMO-BUYER-001', 'company=DEMO-SELLER-001']) { await route(page, target); await page.waitForFunction(() => Boolean(document.querySelector('.catalog-card')) && !document.querySelector('.company-item,.company-profile,[data-ui=catalog-company]')); await layout(page, label + ' blocked ' + target); } const id = 'DEMO-OFFER-001'; const example = await context.request.get(origin + '/api/catalog/offers/' + id + '/example?role=admin'); assert.equal(example.status(), 200); scopedExample(await example.json(), role, label + ' factsheet API'); await route(page, 'catalog', '.catalog-card'); await page.locator('[data-ui=catalog-offer][data-id="' + id + '"]').click(); await page.locator('[data-ui=catalog-json]').waitFor(); const visible = await page.locator('#workspace').innerText(), seller = C.getCompany(C.getOffer(id).sellerId); if (role === 'buyer') { assert(visible.includes(seller.name), label + ': missing contextual seller'); await page.locator('[data-commercial-profile=seller] summary').click(); } else assert(!visible.includes(seller.name), label + ': another seller profile'); for (const company of fixtureCompanies.filter(c => c.role === 'buyer')) assert(!visible.includes(company.name), label + ': buyer reference in factsheet'); assert.equal(await page.locator('[data-ui=catalog-company]').count(), 0); await layout(page, label + ' factsheet'); for (const artifact of await page.locator('[data-artifact] summary').all()) await artifact.click(); await layout(page, label + ' expanded artifacts'); for (const format of ['json', 'html']) { const pending = page.waitForEvent('download'); await page.locator('[data-ui=catalog-' + format + ']').click(); const download = await pending, filename = path.join(out, label + '-factsheet.' + format); await download.saveAs(filename); const content = fs.readFileSync(filename, 'utf8'); assert(!content.includes('undefined'), label + ': bad exported text'); for (const company of fixtureCompanies.filter(c => c.role === 'buyer')) { assert(!content.includes(company.name) && !content.includes(company.contact) && !content.includes(company.id), label + ': export buyer identity'); } if (format === 'json') scopedExample(JSON.parse(content), role, label + ' JSON export'); else { assert(content.includes('lang="' + lang + '"'), label + ': export language'); if (role === 'buyer') assert(content.includes(seller.name), label + ': export seller missing'); } } await route(page, 'catalog', '.catalog-card'); if (viewport === 'mobile') { await page.setViewportSize({width: 320, height: 900}); await layout(page, label + ' 320'); await page.setViewportSize({width: 390, height: 844}); await layout(page, label + ' 390'); } if (role === 'buyer' && viewport === 'mobile' && (engine === 'chromium' && ['en', 'pt'].includes(lang) || engine === 'webkit' && lang === 'ar')) { await capture(page, engine, label); } results.push({engine, role, lang, viewport, offers: 24, noDirectory: true, factsheetScoped: true, widths: [...new Set(viewport === 'mobile' ? [originalWidth, 320, 390] : [1440])], naturalLanguageSearch: searchExamples[lang], voice: ['unsupported', 'opt-out', 'mock result', 'stop', 'permission denied'], exports: ['JSON', 'HTML'], functionalCSPEnforced: true, passed: true}); } catch (error) { failures.push({label, error: error.stack}); console.error(label + ': ' + error.message); } } } finally { await context.close(); } } for (const table of ['cases', 'rehearsals', 'external_evidence']) assert.equal(app.store.get('SELECT count(*) AS n FROM ' + table).n, 0); } catch (error) { failures.push({label: engine + ' setup/teardown', error: error.stack}); console.error(error); } finally { await browser?.close(); if (fixture) { await fixture.app.close(); fs.rmSync(fixture.dir, {recursive: true, force: true}); } } } const report = {passed: failures.length === 0 && errors.length === 0, at: new Date().toISOString(), expectedMatrix: engines.length * languages.length * 2 * 2, completedMatrix: results.length, results, failures, errors, functionalCSPEnforced: true, webkitScreenshotOnlyBypassCSP: true, physicalDeviceTested: false, nativeSafariTested: false, realMicrophoneTested: false}; if (results.length !== report.expectedMatrix && !failures.length) { report.passed = false; report.failures.push({label: 'incomplete matrix', actual: results.length, expected: report.expectedMatrix}); } fs.writeFileSync(path.join(out, report.passed ? 'RESULTS.json' : 'FAILURES.json'), JSON.stringify(report, null, 2)); console.log(JSON.stringify({passed: report.passed, matrix: results.length, failed: failures.length, output: out})); if (!report.passed) process.exitCode = 1;