test: exercise XSS regressions in headless Chrome (#4)

This commit is contained in:
Mikhail Chusavitin committed 2026-10-26 21:03:36 +03:00
1 parent e8dd03c4f5
commit ffdbe4fbd0
3 files changed
+114 -2

No files matched your search

+4 -1
View File
@@ -349,4 +349,7 @@ Rules:
quoted attributes. Never interpolate data into JavaScript event attributes. quoted attributes. Never interpolate data into JavaScript event attributes.
Cart and rental controls carry escaped LOT values in `data-lot` and dispatch Cart and rental controls carry escaped LOT values in `data-lot` and dispatch
through delegated listeners. Sync errors are escaped as text; toast messages use through delegated listeners. Sync errors are escaped as text; toast messages use
`textContent`. Run `node scripts/tests/html-security.cjs` for the regression check. `textContent`. Run `node scripts/tests/html-security.cjs` for the fast regression check and
`node scripts/tests/html-security-browser.cjs` for real DOM parsing and delegated
events in headless Chrome (`CHROME_BIN` overrides the executable). The browser
check uses synthetic data, controlled API responses and a temporary profile.
+12 -1
View File
@@ -10,7 +10,7 @@ on `fix/issue-acceptance-and-migration-safety`.
| Order | Issue | Implementation and acceptance | Status | | Order | Issue | Implementation and acceptance | Status |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| 1 | [#2](https://git.mchus.pro/mchus/QuoteForge/issues/2) | Block foreign Host/Origin/Referer and cross-site browser requests in both routers; validate API body types; refuse saved-password reuse for a changed host/port/user. Middleware and real setup/runtime router tests reject attacks without changing saved credentials or user data. | Acceptance passed | | 1 | [#2](https://git.mchus.pro/mchus/QuoteForge/issues/2) | Block foreign Host/Origin/Referer and cross-site browser requests in both routers; validate API body types; refuse saved-password reuse for a changed host/port/user. Middleware and real setup/runtime router tests reject attacks without changing saved credentials or user data. | Acceptance passed |
| 2 | [#4](https://git.mchus.pro/mchus/QuoteForge/issues/4) | Move LOT-bearing cart/rental events to delegated listeners and escaped data attributes; escape BOM and sync output; share HTML escaping; render toast as text. Malicious LOT regression checks and template tests must pass. | Implemented | | 2 | [#4](https://git.mchus.pro/mchus/QuoteForge/issues/4) | Move LOT-bearing cart/rental events to delegated listeners and escaped data attributes; escape BOM and sync output; share HTML escaping; render toast as text. Malicious LOT regression checks and headless Chrome DOM checks pass. | Acceptance passed |
| 3 | [#7](https://git.mchus.pro/mchus/QuoteForge/issues/7) | Require a fresh verified archive outside rotation before reset, refuse unsynced/legacy states without explicit force, use transactional deletion, remove environment-triggered reset. Verify refusal, ZIP restore, backup failure and rollback. | Implemented | | 3 | [#7](https://git.mchus.pro/mchus/QuoteForge/issues/7) | Require a fresh verified archive outside rotation before reset, refuse unsynced/legacy states without explicit force, use transactional deletion, remove environment-triggered reset. Verify refusal, ZIP restore, backup failure and rollback. | Implemented |
| 4 | [#5](https://git.mchus.pro/mchus/QuoteForge/issues/5) | Persist TLS mode/CA in SQLite, expose setup controls, share policy across setup/sync/migration DSNs. Verify certificate trust, hostname checks, plaintext fallback policy and settings round-trip. | Implemented | | 4 | [#5](https://git.mchus.pro/mchus/QuoteForge/issues/5) | Persist TLS mode/CA in SQLite, expose setup controls, share policy across setup/sync/migration DSNs. Verify certificate trust, hostname checks, plaintext fallback policy and settings round-trip. | Implemented |
| 5 | [#3](https://git.mchus.pro/mchus/QuoteForge/issues/3) | Keep each migration file in one session, execute verify headers before history insertion, propagate FK failures. Verify failed queries/checks never enter history. | Implemented | | 5 | [#3](https://git.mchus.pro/mchus/QuoteForge/issues/3) | Keep each migration file in one session, execute verify headers before history insertion, propagate FK failures. Verify failed queries/checks never enter history. | Implemented |
@@ -57,3 +57,14 @@ password reuse for a changed destination. Local reads still succeed. Saved
credentials, project/configuration counts and the pending queue remain unchanged. credentials, project/configuration counts and the pending queue remain unchanged.
The setup router construction was extracted without changing its routes so The setup router construction was extracted without changing its routes so
this regression exercises the same middleware registration as startup. this regression exercises the same middleware registration as startup.
### Issue #4
`node scripts/tests/html-security-browser.cjs` passes in headless Chrome with
an isolated temporary profile. It executes the actual template rendering
functions in a browser DOM with controlled API responses. Both cart layouts,
rental, parsed BOM, toast, pending sync errors, error history and repair errors
preserve malicious strings as text. Real click/change/focus events preserve
LOT values through delegated handlers; no injected elements or payload execution
are observed. This is a rendering integration check, not a full application
navigation test. Set `CHROME_BIN` outside macOS to select a Chrome executable.
+98
View File
@@ -0,0 +1,98 @@
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});
}