// SPDX-License-Identifier: EUPL-1.2 // Minimal, defensive XML 1.0 parser for UBL documents. Runs unchanged in the browser, in // Node and in Cloudflare Workers. // // Security properties (tests/engine/xml.test.ts): // - any `>; readonly children: XmlNode[]; /** Direct character data of this element, entities decoded, not normalised. */ text: string; readonly parent: XmlNode | null; readonly line: number; } export interface XmlLimits { readonly maxDepth: number; readonly maxNodes: number; readonly maxAttributes: number; } export const DEFAULT_XML_LIMITS: XmlLimits = { maxDepth: 64, maxNodes: 60000, maxAttributes: 32 }; export type XmlParseResult = | { readonly ok: true; readonly root: XmlNode; readonly nodeCount: number } | { readonly ok: false; readonly code: XmlErrorCode; readonly message: string; readonly line: number }; export type XmlErrorCode = "not_well_formed" | "dtd_forbidden" | "unsupported_encoding" | "limit_exceeded" | "empty"; class XmlError extends Error { readonly code: XmlErrorCode; readonly line: number; constructor(code: XmlErrorCode, message: string, line: number) { super(message); this.code = code; this.line = line; } } const PREDEFINED: Readonly> = { lt: "<", gt: ">", amp: "&", quot: '"', apos: "'" }; const NAME_PATTERN = /^[A-Za-z_][\w.-]*(?::[A-Za-z_][\w.-]*)?$/; interface ResolvedName { readonly q: string; readonly local: string; readonly namespace: string; } // Element and attribute names repeat thousands of times; remember which ones are valid. const knownNames = new Map(); function isValidName(name: string): boolean { let valid = knownNames.get(name); if (valid === undefined) { valid = NAME_PATTERN.test(name); if (knownNames.size < 4096) knownNames.set(name, valid); } return valid; } function canonicalName(namespace: string, local: string): string { switch (namespace) { case NS.cbc: return `cbc:${local}`; case NS.cac: return `cac:${local}`; case NS.ext: return `ext:${local}`; case NS.invoice: case NS.creditNote: return local; default: return `{${namespace}}${local}`; } } function isXmlChar(code: number): boolean { return ( code === 0x9 || code === 0xa || code === 0xd || (code >= 0x20 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0xfffd) || (code >= 0x10000 && code <= 0x10ffff) ); } export function parseXml(source: string, limits: XmlLimits = DEFAULT_XML_LIMITS): XmlParseResult { try { return parse(source, limits); } catch (error) { if (error instanceof XmlError) return { ok: false, code: error.code, message: error.message, line: error.line }; throw error; } } function parse(source: string, limits: XmlLimits): XmlParseResult { const input = source.charCodeAt(0) === 0xfeff ? source.slice(1) : source; const length = input.length; let pos = 0; let line = 1; let lineScan = 0; const lineAt = (offset: number): number => { for (;;) { const newline = input.indexOf("\n", lineScan); if (newline === -1 || newline >= offset) break; line += 1; lineScan = newline + 1; } return line; }; const fail = (code: XmlErrorCode, message: string, offset: number): never => { throw new XmlError(code, message, lineAt(offset)); }; const decodeText = (raw: string, offset: number): string => { if (raw.indexOf("&") === -1) return raw; let out = ""; let cursor = 0; for (;;) { const amp = raw.indexOf("&", cursor); if (amp === -1) break; const semi = raw.indexOf(";", amp); if (semi === -1 || semi - amp > 10) fail("not_well_formed", "Unterminated entity reference.", offset); const name = raw.slice(amp + 1, semi); let replacement: string | undefined; if (name.charCodeAt(0) === 0x23 /* # */) { const hex = name.charCodeAt(1) === 0x78; /* x */ const digits = name.slice(hex ? 2 : 1); if (!(hex ? /^[0-9A-Fa-f]{1,6}$/ : /^[0-9]{1,7}$/).test(digits)) { fail("not_well_formed", "Invalid character reference.", offset); } const code = parseInt(digits, hex ? 16 : 10); if (!isXmlChar(code)) fail("not_well_formed", "Character reference outside the XML character range.", offset); replacement = String.fromCodePoint(code); } else { replacement = PREDEFINED[name]; if (replacement === undefined) { fail("not_well_formed", `Unknown entity "&${name};". Custom entities are not supported.`, offset); } } out += raw.slice(cursor, amp) + (replacement ?? ""); cursor = semi + 1; } return out + raw.slice(cursor); }; if (input.startsWith(""); if (end === -1) fail("not_well_formed", "Unterminated XML declaration.", 0); const declaration = input.slice(0, end); const encoding = /encoding\s*=\s*["']([^"']+)["']/.exec(declaration)?.[1]; if (encoding !== undefined && !/^utf-?8$/i.test(encoding)) { fail("unsupported_encoding", `Encoding "${encoding}" is not supported. Save the document as UTF-8.`, 0); } pos = end + 2; } interface Open { readonly node: XmlNode; readonly rawName: string; readonly scope: Readonly>; } const stack: Open[] = []; let root: XmlNode | null = null; let nodeCount = 0; // Positions of the next quote characters, refreshed lazily so the scan stays linear. const positionOrEnd = (position: number): number => (position === -1 ? length : position); let nextDoubleQuote = -1; let nextSingleQuote = -1; const resolutionCache = new Map>, Map>(); const rootScope: Readonly> = { xml: "http://www.w3.org/XML/1998/namespace" }; while (pos < length) { const lt = input.indexOf("<", pos); const top = stack[stack.length - 1]; const textEnd = lt === -1 ? length : lt; if (textEnd > pos) { const raw = input.slice(pos, textEnd); if (top) top.node.text += decodeText(raw, pos); else if (raw.trim() !== "") fail("not_well_formed", "Text outside the root element.", pos); } if (lt === -1) break; const next = input.charCodeAt(lt + 1); if (next === 0x21 /* ! */) { if (input.startsWith("", lt + 4); if (end === -1) fail("not_well_formed", "Unterminated comment.", lt); pos = end + 3; continue; } if (input.startsWith("", lt + 9); if (end === -1) fail("not_well_formed", "Unterminated CDATA section.", lt); if (top) top.node.text += input.slice(lt + 9, end); pos = end + 3; continue; } fail("dtd_forbidden", "DOCTYPE and other markup declarations are not allowed.", lt); } if (next === 0x3f /* ? */) { const end = input.indexOf("?>", lt + 2); if (end === -1) fail("not_well_formed", "Unterminated processing instruction.", lt); if (/^<\?xml[\s?]/i.test(input.slice(lt, lt + 6))) { fail("not_well_formed", "The XML declaration must be at the start of the document.", lt); } pos = end + 2; continue; } if (next === 0x2f /* / */) { const end = input.indexOf(">", lt + 2); if (end === -1) fail("not_well_formed", "Unterminated end tag.", lt); const name = input.slice(lt + 2, end).trim(); if (!top || top.rawName !== name) { fail("not_well_formed", `End tag does not match ${top ? `<${top.rawName}>` : "any open element"}.`, lt); } stack.pop(); pos = end + 1; continue; } // Start tag: find its end. Fast path: no quote before the next ">" means no attributes. let tagEnd = input.indexOf(">", lt + 1); if (tagEnd === -1) fail("not_well_formed", "Unterminated start tag.", lt); if (nextDoubleQuote < lt) nextDoubleQuote = positionOrEnd(input.indexOf('"', lt)); if (nextSingleQuote < lt) nextSingleQuote = positionOrEnd(input.indexOf("'", lt)); const quoted = nextDoubleQuote < tagEnd || nextSingleQuote < tagEnd; if (quoted) { let cursor = lt + 1; let quote = 0; tagEnd = -1; while (cursor < length) { const code = input.charCodeAt(cursor); if (quote !== 0) { if (code === quote) quote = 0; else if (code === 0x3c) fail("not_well_formed", 'Character "<" inside an attribute value.', cursor); } else if (code === 0x22 || code === 0x27) { quote = code; } else if (code === 0x3e) { tagEnd = cursor; break; } else if (code === 0x3c) { fail("not_well_formed", 'Unexpected "<" inside a tag.', cursor); } cursor += 1; } if (tagEnd === -1) fail("not_well_formed", "Unterminated start tag.", lt); } else { const strayLt = input.indexOf("<", lt + 1); if (strayLt !== -1 && strayLt < tagEnd) fail("not_well_formed", 'Unexpected "<" inside a tag.', strayLt); } const selfClosing = input.charCodeAt(tagEnd - 1) === 0x2f; const body = input.slice(lt + 1, selfClosing ? tagEnd - 1 : tagEnd); let nameEnd = 0; while (nameEnd < body.length) { const code = body.charCodeAt(nameEnd); if (code === 0x20 || code === 0x9 || code === 0xa || code === 0xd) break; nameEnd += 1; } const rawName = nameEnd === body.length ? body : body.slice(0, nameEnd); if (!isValidName(rawName)) fail("not_well_formed", `Invalid element name "${rawName.slice(0, 40)}".`, lt); const attrs: Record = {}; let scope: Readonly> = top ? top.scope : rootScope; let ownScope: Record | null = null; const attrText = nameEnd === body.length ? "" : body.slice(nameEnd); if (attrText !== "" && attrText.trim() !== "") { const attrPattern = /\s+([^\s=]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/y; let index = 0; let count = 0; const seen = new Set(); while (index < attrText.length) { attrPattern.lastIndex = index; const match = attrPattern.exec(attrText); if (!match) { if (attrText.slice(index).trim() === "") break; fail("not_well_formed", `Malformed attribute in <${rawName}>.`, lt); break; } index = attrPattern.lastIndex; const attrName = match[1] ?? ""; const attrValue = decodeText((match[2] ?? match[3] ?? "").replace(/[\t\r\n]/g, " "), lt); if (!isValidName(attrName)) fail("not_well_formed", `Invalid attribute name in <${rawName}>.`, lt); if (seen.has(attrName)) fail("not_well_formed", `Duplicate attribute "${attrName}" in <${rawName}>.`, lt); seen.add(attrName); count += 1; if (count > limits.maxAttributes) fail("limit_exceeded", "Too many attributes on one element.", lt); if (attrName === "xmlns" || attrName.startsWith("xmlns:")) { ownScope ??= { ...scope }; ownScope[attrName === "xmlns" ? "" : attrName.slice(6)] = attrValue; } else if (attrName.indexOf(":") === -1) { attrs[attrName] = attrValue; } } } if (ownScope) scope = ownScope; // Name resolution is memoised per namespace scope; most elements share their parent's scope. let resolutions = resolutionCache.get(scope); if (!resolutions) { resolutions = new Map(); resolutionCache.set(scope, resolutions); } let resolvedName = resolutions.get(rawName); if (!resolvedName) { const colon = rawName.indexOf(":"); const prefix = colon === -1 ? "" : rawName.slice(0, colon); const localName = colon === -1 ? rawName : rawName.slice(colon + 1); const namespace = scope[prefix]; if (namespace === undefined && prefix !== "") { fail("not_well_formed", `Namespace prefix "${prefix}" is not declared.`, lt); } resolvedName = { q: canonicalName(namespace ?? "", localName), local: localName, namespace: namespace ?? "" }; resolutions.set(rawName, resolvedName); } const local = resolvedName.local; const resolved = resolvedName.namespace; nodeCount += 1; if (nodeCount > limits.maxNodes) fail("limit_exceeded", `The document has more than ${limits.maxNodes} elements.`, lt); if (stack.length >= limits.maxDepth) fail("limit_exceeded", `Elements are nested deeper than ${limits.maxDepth} levels.`, lt); const node: XmlNode = { q: resolvedName.q, local, namespace: resolved, attrs, children: [], text: "", parent: top ? top.node : null, line: lineAt(lt) }; if (top) { top.node.children.push(node); } else { if (root) fail("not_well_formed", "More than one root element.", lt); root = node; } if (!selfClosing) stack.push({ node, rawName, scope }); pos = tagEnd + 1; } const unclosed = stack[stack.length - 1]; if (unclosed) fail("not_well_formed", `Element <${unclosed.rawName}> is not closed.`, length); if (!root) return { ok: false, code: "empty", message: "The document contains no XML element.", line: 1 }; return { ok: true, root, nodeCount }; }