Files
QuoteForge/scripts/tests/html-security-browser.cjs
T

99 lines
6.1 KiB
JavaScript

const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {spawnSync} = require('node:child_process');
const index = fs.readFileSync('web/templates/index.html', 'utf8');
const base = fs.readFileSync('web/templates/base.html', 'utf8');
function extract(source, name) {
const match = source.match(new RegExp(`^( *)(?:async )?function ${name}\\(`, 'm'));
assert(match, `Missing function ${name}`);
const end = source.indexOf(`\n${match[1]}}`, match.index);
assert(end > match.index);
return source.slice(match.index, end + match[1].length + 2);
}
const functions = [
...['renderMultiSelectTab', 'renderMultiSelectTabWithSections', 'renderRentalTab', '_renderBOMParsedTable'].map(n => extract(index, n)),
...['showToast', 'loadSyncInfo', 'repairPendingChanges'].map(n => extract(base, n)),
].join('\n');
const ids = new Set([...functions.matchAll(/getElementById\('([^']+)'\)/g)].map(m => m[1]));
const fixtures = [...ids].map(id => id.endsWith('-body') ? `<table><tbody id="${id}"></tbody></table>` : `<div id="${id}"></div>`).join('');
const listeners = index.split('<script>')[1].split('// Tab configuration')[0];
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'qfs-browser-security-'));
const target = path.join(directory, 'test.html');
const test = `
let cart = [], allComponents = [], currentTab = 'cpu', configUUID = 'example';
let rentalUpliftPercent = 0, bomRows = [], reply = {}, calls = [];
window.__injected = 0;
const getTabForCategory = () => 'cpu', getDisplayPrice = () => 1;
const qualityDotHtml = () => '', formatMoney = String, formatPriceOrNA = String, formatCurrency = String;
const ciStr = s => s.toLowerCase(), getComponentCategory = c => c.category;
const _setBomUIError = () => {}, _ensureBomDatalist = () => {}, _getRowLotQtyPerPN = () => 1;
const renderBOMLotAllocationsEditor = () => '', buildRentalItemsPayload = () => [];
const removeFromCart = lot => calls.push(['remove', lot]);
const updateMultiQuantity = (lot, value) => calls.push(['quantity', lot, value]);
const onRentalConditionChange = (lot, value) => calls.push(['condition', lot, value]);
const showAutocompleteEditItem = lot => calls.push(['edit', lot]);
window.fetch = async () => ({ok: true, json: async () => reply});
function check(ok, message) { if (!ok) throw new Error(message); }
function inert(id, payload) {
const el = document.getElementById(id);
check(el.textContent.includes(payload), id + ': text did not survive');
check(!el.querySelector('img,script,iframe'), id + ': injected element');
}
(async () => {
for (const lot of [
"LOT'\\\"><img src=x onerror=window.__injected++>",
'LOT&#X61;&#39;);window.__injected++;//',
'LOT\\\\&<>"',
]) {
cart = [{lot_name: lot, description: lot, category: 'cpu', quantity: 1}];
for (const render of [() => renderMultiSelectTab([]), () => renderMultiSelectTabWithSections([{title: 'CPU', categories: ['cpu']}])]) {
render();
const root = document.getElementById('tab-content');
check(!root.querySelector('img,script'), 'cart: injected element');
const quantity = root.querySelector('[data-cart-action="quantity"]');
check(quantity.dataset.lot === lot, 'cart: dataset changed');
quantity.value = '2'; quantity.dispatchEvent(new Event('change', {bubbles: true}));
root.querySelector('[data-cart-action="edit"]').dispatchEvent(new FocusEvent('focusin', {bubbles: true}));
root.querySelector('[data-cart-action="remove"] svg').dispatchEvent(new MouseEvent('click', {bubbles: true}));
check(calls.length === 3 && calls.every(c => c[1] === lot), 'cart: delegated action changed LOT');
calls = [];
}
reply = {items: [{...cart[0], condition: 'new', buy_price: 1, price: 1, one_time: 1, weekly: 1}]};
await renderRentalTab();
inert('rental-body', lot);
const condition = document.querySelector('[data-cart-action="condition"]');
condition.dispatchEvent(new Event('change', {bubbles: true}));
check(calls.length === 1 && calls[0][1] === lot, 'rental: delegated action changed LOT'); calls = [];
bomRows = [{resolved_lot: lot, vendor_pn: lot, description: lot, quantity: 1, resolution_source: 'manual'}];
_renderBOMParsedTable(); inert('bom-table-body', lot);
showToast(lot, 'error'); inert('toast', lot);
reply = {is_online: false, config_count: 0, project_count: 0,
pending_changes: [{entity_uuid: 'example', operation: lot, entity_type: lot, last_error: lot}],
errors: [{message: lot}]};
await loadSyncInfo(); inert('modal-pending-list', lot); inert('modal-errors-list', lot);
reply = {success: true, repaired: 0, remaining_errors: [lot]};
await repairPendingChanges(); inert('repair-result', lot);
}
await new Promise(resolve => setTimeout(resolve, 50));
check(window.__injected === 0, 'payload executed');
document.getElementById('result').textContent = 'PASS';
})().catch(error => {document.getElementById('result').textContent = 'FAIL: ' + error.stack;});
`;
fs.writeFileSync(target, `<!doctype html><meta charset="utf-8">${fixtures}<pre id="result">PENDING</pre><script>${fs.readFileSync('web/static/html-escape.js', 'utf8')}\n${functions}\n${listeners}\n${test}</script>`);
const chrome = process.env.CHROME_BIN || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
try {
const result = spawnSync(chrome, ['--headless', '--disable-gpu', '--no-first-run', '--disable-background-networking',
'--user-data-dir=' + path.join(directory, 'profile'), '--virtual-time-budget=1000', '--dump-dom', 'file://' + target], {encoding: 'utf8', timeout: 30000});
assert.ifError(result.error);
assert.equal(result.status, 0, result.stderr);
const outcome = result.stdout.match(/<pre id="result">([\s\S]*?)<\/pre>/)?.[1];
assert.equal(outcome, 'PASS', outcome || 'Browser did not finish');
console.log('Browser HTML security regressions passed');
} finally {
fs.rmSync(directory, {recursive: true, force: true});
}