src/xml.js
// Minimal, non-validating XML reader for test reports (JUnit and similar). Safe by construction:
// - no DTD processing: any <!DOCTYPE ...> or <!ENTITY ...> is refused, so no entity can be defined,
// expanded recursively ("billion laughs") or point at an external file or URL (XXE);
// - only the five predefined entities and numeric character references are decoded; any other
// &name; is left as literal text (counted, never resolved);
// - no network, no file access, no includes, no processing instructions are acted on;
// - bounded: element count, nesting depth and attribute count are limited; scanning uses indexOf,
// not backtracking regular expressions over the whole document.
import { ToolError } from "./errors.js";
export const XML_LIMITS = { maxElements: 500_000, maxDepth: 64, maxAttributes: 100 };
const NAME_START = /[A-Za-z_:]/;
const NAME_CHAR = /[\w:.\-]/;
function lineAt(text, pos) {
let n = 1;
for (let i = 0; i < pos && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
return n;
}
function decodeEntities(s, stats) {
if (!s.includes("&")) return s;
return s.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[A-Za-z][\w.-]{0,40});/g, (m, body) => {
if (body[0] === "#") {
const cp = body[1] === "x" || body[1] === "X" ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
if (!Number.isFinite(cp) || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) || (cp < 0x20 && cp !== 9 && cp !== 10 && cp !== 13)) return "�";
return String.fromCodePoint(cp);
}
switch (body) {
case "lt":
return "<";
case "gt":
return ">";
case "amp":
return "&";
case "quot":
return '"';
case "apos":
return "'";
default:
stats.unknownEntities++;
return m; // never resolved
}
});
}
/**
* Parses XML text into { name, attrs, children, text } elements. Throws ToolError("unsafe_xml") for
* DTD/entity declarations and ToolError("invalid_input") for malformed XML (with a line number).
* Returns { root, unknownEntities }.
*/
export function parseXml(text, { field = "xml", tick } = {}) {
const stats = { unknownEntities: 0 };
const bad = (pos, msg) => {
throw new ToolError("invalid_input", `${field}: malformed XML at line ${lineAt(text, pos)}: ${msg}.`);
};
const stack = [];
let root = null;
let count = 0;
let i = 0;
const n = text.length;
if (text.charCodeAt(0) === 0xfeff) i = 1;
while (i < n) {
const lt = text.indexOf("<", i);
const chunk = lt < 0 ? text.slice(i) : text.slice(i, lt);
if (chunk) {
if (stack.length) stack[stack.length - 1].textParts.push(decodeEntities(chunk, stats));
else if (chunk.trim()) bad(i, root ? "text after the root element" : "text before the root element");
}
if (lt < 0) break;
i = lt;
if (text.startsWith("<!--", i)) {
const end = text.indexOf("-->", i + 4);
if (end < 0) bad(i, "a comment is not closed");
i = end + 3;
continue;
}
if (text.startsWith("<![CDATA[", i)) {
const end = text.indexOf("]]>", i + 9);
if (end < 0) bad(i, "a CDATA section is not closed");
if (!stack.length) bad(i, "CDATA outside the root element");
stack[stack.length - 1].textParts.push(text.slice(i + 9, end));
i = end + 3;
continue;
}
if (text.startsWith("<!", i)) {
const word = text.slice(i + 2, i + 12).toUpperCase();
if (word.startsWith("DOCTYPE") || word.startsWith("ENTITY") || word.startsWith("ELEMENT") || word.startsWith("ATTLIST")) {
throw new ToolError("unsafe_xml", `${field}: the file contains a <!${word.match(/^[A-Z]+/)[0]} declaration (line ${lineAt(text, i)}). Document type and entity declarations are refused, so no entities are defined or expanded and nothing external is loaded.`);
}
bad(i, "unexpected <! markup");
}
if (text.startsWith("<?", i)) {
const end = text.indexOf("?>", i + 2);
if (end < 0) bad(i, "a processing instruction is not closed");
i = end + 2;
continue;
}
if (text[i + 1] === "/") {
const end = text.indexOf(">", i + 2);
if (end < 0) bad(i, "an end tag is not closed");
const name = text.slice(i + 2, end).trim();
const top = stack.pop();
if (!top) bad(i, `</${name.slice(0, 60)}> closes an element that was never opened`);
if (top.name !== name) bad(i, `</${name.slice(0, 60)}> does not match <${top.name.slice(0, 60)}>`);
finish(top);
i = end + 1;
continue;
}
// Start tag
let j = i + 1;
if (!NAME_START.test(text[j] ?? "")) bad(i, "a tag name is missing or invalid");
while (j < n && NAME_CHAR.test(text[j])) j++;
const name = text.slice(i + 1, j);
const attrs = Object.create(null);
let attrCount = 0;
let selfClose = false;
for (;;) {
while (j < n && /\s/.test(text[j])) j++;
if (j >= n) bad(i, `<${name.slice(0, 60)}> is not closed`);
if (text[j] === ">") {
j++;
break;
}
if (text[j] === "/" && text[j + 1] === ">") {
selfClose = true;
j += 2;
break;
}
const as = j;
if (!NAME_START.test(text[j])) bad(j, `unexpected character in <${name.slice(0, 60)}>`);
while (j < n && NAME_CHAR.test(text[j])) j++;
const an = text.slice(as, j);
while (j < n && /\s/.test(text[j])) j++;
if (text[j] !== "=") bad(j, `attribute ${an.slice(0, 60)} has no value`);
j++;
while (j < n && /\s/.test(text[j])) j++;
const q = text[j];
if (q !== '"' && q !== "'") bad(j, `attribute ${an.slice(0, 60)} value is not quoted`);
const qe = text.indexOf(q, j + 1);
if (qe < 0) bad(j, `attribute ${an.slice(0, 60)} value is not closed`);
const raw = text.slice(j + 1, qe);
if (raw.includes("<")) bad(j, `"<" inside attribute ${an.slice(0, 60)}`);
if (++attrCount > XML_LIMITS.maxAttributes) bad(as, `more than ${XML_LIMITS.maxAttributes} attributes`);
if (an !== "__proto__") attrs[an] = decodeEntities(raw, stats);
j = qe + 1;
}
if (++count > XML_LIMITS.maxElements) throw new ToolError("limit_exceeded", `${field}: more than ${XML_LIMITS.maxElements} XML elements.`);
if (count % 20000 === 0) tick?.();
const el = { name, attrs, children: [], textParts: [], text: "" };
if (stack.length) stack[stack.length - 1].children.push(el);
else if (root) bad(i, "a second root element");
else root = el;
if (selfClose) finish(el);
else {
stack.push(el);
if (stack.length > XML_LIMITS.maxDepth) bad(i, `elements are nested more than ${XML_LIMITS.maxDepth} deep`);
}
i = j;
}
if (stack.length) bad(n, `<${stack[stack.length - 1].name.slice(0, 60)}> is not closed (the file may be truncated)`);
if (!root) bad(0, "no root element");
return { root, unknownEntities: stats.unknownEntities };
}
function finish(el) {
el.text = el.textParts.join("");
delete el.textParts;
}
/** All descendants (depth-first) with the given element name. */
export function findAll(el, name, out = []) {
for (const c of el.children) {
if (c.name === name) out.push(c);
findAll(c, name, out);
}
return out;
}