56 lines
2.7 KiB
JavaScript
56 lines
2.7 KiB
JavaScript
const assert = require('node:assert/strict');
|
|
const fs = require('node:fs');
|
|
const vm = require('node:vm');
|
|
const source = fs.readFileSync('web/templates/index.html', 'utf8');
|
|
const base = fs.readFileSync('web/templates/base.html', 'utf8');
|
|
const nodes = {};
|
|
const listeners = {};
|
|
const calls = [];
|
|
const context = vm.createContext({
|
|
document: {
|
|
getElementById: id => nodes[id] ??= {},
|
|
createElement: () => ({}),
|
|
addEventListener: (name, handler) => listeners[name] = handler,
|
|
},
|
|
setTimeout: () => {},
|
|
cart: [], allComponents: [], currentTab: 'cpu',
|
|
getTabForCategory: () => 'cpu', getDisplayPrice: () => 1,
|
|
qualityDotHtml: () => '', formatMoney: String, formatPriceOrNA: String,
|
|
removeFromCart: lot => calls.push(['remove', lot]),
|
|
updateMultiQuantity: (lot, value) => calls.push(['quantity', lot, value]),
|
|
onRentalConditionChange: (lot, value) => calls.push(['condition', lot, value]),
|
|
showAutocompleteEditItem: lot => calls.push(['edit', lot]),
|
|
});
|
|
function loadFunction(text, name) {
|
|
const start = text.indexOf(`function ${name}(`);
|
|
assert(start >= 0);
|
|
const end = text.indexOf('\n}', start);
|
|
// Functions in base.html have eight spaces of indentation.
|
|
const baseEnd = text.indexOf('\n }', start);
|
|
vm.runInContext(text.slice(start, (end < 0 ? baseEnd + 10 : end + 2)), context);
|
|
}
|
|
vm.runInContext(fs.readFileSync('web/static/html-escape.js', 'utf8'), context);
|
|
loadFunction(source, 'renderMultiSelectTab');
|
|
vm.runInContext(source.split('<script>')[1].split('// Tab configuration')[0], context);
|
|
loadFunction(base, 'showToast');
|
|
nodes.toast = {replaceChildren: child => nodes.toast.child = child};
|
|
for (const lot of [`LOT'\"<img src=x onerror=alert(1)>`, 'LOTa');alert(1)//', 'LOT\\\'()&<>']) {
|
|
context.cart = [{lot_name: lot, quantity: 1, category: 'cpu'}];
|
|
context.renderMultiSelectTab([]);
|
|
const html = nodes['tab-content'].innerHTML;
|
|
assert(html.includes(`data-lot="${context.escapeHtml(lot)}"`));
|
|
assert(!html.includes(lot));
|
|
assert(!html.includes('onclick="removeFromCart('));
|
|
listeners.click({target: {closest: () => ({dataset: {lot}})}});
|
|
listeners.change({target: {dataset: {lot, cartAction: 'quantity'}, value: '2'}});
|
|
listeners.change({target: {dataset: {lot, cartAction: 'condition'}, checked: true}});
|
|
listeners.focusin({target: {dataset: {lot, cartAction: 'edit'}}});
|
|
assert(calls.splice(0).every(call => call[1] === lot));
|
|
context.showToast(lot, 'error');
|
|
assert.equal(nodes.toast.child.textContent, lot);
|
|
assert.equal(nodes.toast.child.innerHTML, undefined);
|
|
}
|
|
assert.equal(context.escapeHtml(0), '0');
|
|
assert.equal(context.escapeHtml(null), '');
|
|
console.log('HTML security regressions passed');
|