The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Explainer: the Word reader reads in one pass, so a crafted .docx can't stall the server
Claude6284c3e14a01
diff --git a/src/server/assist/docx.ts b/src/server/assist/docx.tsindex 065decda..a8705e46 100644--- a/src/server/assist/docx.ts+++ b/src/server/assist/docx.ts@@ -5,13 +5,17 @@ import { unzip, ZipError } from "./unzip";* The text of a Word document (.docx): the paragraphs of word/document.xml in order (table cells* separated by tabs, line and page breaks kept), and the title from docProps/core.xml. Read with the* bounded unzip: only those two entries are inflated, so pictures in the file cost nothing. Deleted- * text (tracked changes) and field codes are left out. Old binary .doc files are refused with a hint.+ * text (tracked changes), field codes and tab stops are left out. The markup is read in one linear+ * pass from its start until there's enough text, so a crafted file can't hold the server up. Old+ * binary .doc files are refused with a hint.*/export class DocxError extends Error {}const DOCUMENT = "word/document.xml";const CORE = "docProps/core.xml";+/** The most of document.xml's markup that's read (the text a source needs comes long before it). */+const MAX_XML = 16_000_000;/** An OLE compound file: the old binary .doc (also .xls / .ppt). */const OLE = Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]);@@ -25,31 +29,105 @@ function decodeXml(s: string): string {});}-// Markers that can't appear in XML text (C0 controls are not allowed there).-const TAB = "\u0001";-const BREAK = "\u0002";+/** Elements whose content isn't shown: alternate content's fallback copy (text boxes say everything twice), deleted text, field codes and paragraph properties (their tab stops are <w:tab>s too). */+const HIDDEN = new Set(["mc:Fallback", "w:delText", "w:instrText", "w:pPr"]);-/** The visible text of a document.xml, paragraph by paragraph. */-export function documentXmlText(xml: string): string {- const marked = xml- // Alternate content repeats itself in its fallback (text boxes); deleted text and field codes aren't shown.- .replace(/<mc:Fallback\b[\s\S]*?<\/mc:Fallback>/g, "")- .replace(/<w:(delText|instrText)\b[^>]*>[\s\S]*?<\/w:\1>/g, "")- .replace(/<w:(?:tab|ptab)\b[^>]*\/>/g, TAB)- .replace(/<w:(?:br|cr)\b[^>]*\/>/g, BREAK)- // A table row is one line, its cells separated by tabs (a cell's paragraphs run on with spaces).- .replace(/<w:tc\b[^>]*>([\s\S]*?)<\/w:tc>/g, (_, cell: string) => `${cell.replace(/<\/w:p>/g, " ")}${TAB}`)- .replace(/<\/w:(?:p|tr)>|<w:p\b[^>]*\/>/g, BREAK);+const isNameEnd = (c: number) => c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d || c === 0x2f /* / */ || c === 0x3e; /* > */++/**+ * The visible text of a document.xml, paragraph by paragraph: one pass over the tags with indexOf and+ * a few counters (no regex that rescans the rest of the file), so a crafted document — thousands of+ * tags that never close, a run of a million spaces — costs time in proportion to its size. It stops+ * once `limit` characters (before blanks are tidied) are read.+ */+export function documentXmlText(xml: string, limit = Infinity): string {+ let raw = "";+ let hidden = 0; // depth inside HIDDEN elements+ let cells = 0; // depth inside table cells: a row is one line, its cells separated by tabs+ let inText = false; // inside <w:t>+ let i = 0;+ while (i < xml.length && raw.length < limit) {+ const lt = xml.indexOf("<", i);+ const textEnd = lt < 0 ? xml.length : lt;+ // An entity never decodes to more characters than it's written with, so the room left bounds the slice.+ if (inText && !hidden && textEnd > i) raw += decodeXml(xml.slice(i, Math.min(textEnd, i + (limit - raw.length))));+ if (lt < 0) break;+ if (xml.startsWith("<!--", lt)) {+ const end = xml.indexOf("-->", lt + 4);+ if (end < 0) break;+ i = end + 3;+ continue;+ }+ const gt = xml.indexOf(">", lt + 1);+ // A tag that never ends: the rest isn't XML.+ if (gt < 0) break;+ i = gt + 1;+ const closing = xml.charCodeAt(lt + 1) === 0x2f;+ const empty = xml.charCodeAt(gt - 1) === 0x2f;+ let e = closing ? lt + 2 : lt + 1;+ const from = e;+ while (e < gt && !isNameEnd(xml.charCodeAt(e))) e++;+ const name = xml.slice(from, e);+ if (HIDDEN.has(name)) {+ if (closing) hidden = Math.max(0, hidden - 1);+ else if (!empty) hidden++;+ continue;+ }+ if (hidden) continue;+ switch (name) {+ case "w:t":+ inText = !closing && !empty;+ break;+ case "w:tab":+ case "w:ptab":+ if (!closing) raw += "\t";+ break;+ case "w:br":+ case "w:cr":+ if (!closing) raw += cells ? " " : "\n";+ break;+ case "w:tc":+ if (closing) {+ cells = Math.max(0, cells - 1);+ raw += "\t";+ } else if (!empty) cells++;+ break;+ case "w:p":+ case "w:tr":+ // A paragraph ends a line; inside a cell its paragraphs run on with spaces.+ if (closing || (empty && name === "w:p")) raw += cells ? " " : "\n";+ break;+ }+ }+ return raw.split("\n").map(tidyLine).join("\n").replace(/\n{3,}/g, "\n\n").trim();+}++/** One line, cleaned up in one pass: blanks around a tab and at the end dropped, runs of blanks made one space. */+function tidyLine(line: string): string {let out = "";- for (const m of marked.matchAll(/<w:t(?:\s[^>]*)?>([^<]*)<\/w:t>|\u0001|\u0002/g)) {- out += m[1] !== undefined ? decodeXml(m[1]) : m[0] === TAB ? "\t" : "\n";+ let blanks = 0;+ let blank = " ";+ let afterTab = false;+ for (const ch of line) {+ if (ch === " " || ch === "\u00a0") {+ if (!afterTab) {+ blanks++;+ blank = ch;+ }+ } else if (ch === "\t") {+ blanks = 0;+ afterTab = true;+ out += ch;+ } else {+ if (blanks) out += blanks === 1 ? blank : " ";+ blanks = 0;+ afterTab = false;+ out += ch;+ }}- return out- .split("\n")- .map((l) => l.replace(/[ \t\u00a0]+$/g, "").replace(/[ \u00a0]*\t[ \u00a0]*/g, "\t").replace(/[ \u00a0]{2,}/g, " "))- .join("\n")- .replace(/\n{3,}/g, "\n\n")- .trim();+ let end = out.length;+ while (end > 0 && out.charCodeAt(end - 1) === 0x09) end--;+ return out.slice(0, end);}export function docxText(data: Buffer, opts: { maxChars: number }): { text: string; title?: string } {@@ -64,7 +142,10 @@ export function docxText(data: Buffer, opts: { maxChars: number }): { text: stri}const doc = entries.find((e) => e.name === DOCUMENT);if (!doc) throw new DocxError("This file isn't a Word document (.docx) — it has no document text inside");- const text = documentXmlText(doc.data.toString("utf8")).slice(0, opts.maxChars);+ // The text is read from the start of the document until there's enough of it (blanks tidied away can+ // shrink it, hence the margin), and from at most the first MAX_XML bytes of markup.+ const xml = doc.data.toString("utf8", 0, Math.min(doc.data.length, MAX_XML));+ const text = documentXmlText(xml, opts.maxChars * 4 + 1024).slice(0, opts.maxChars);if (!text.trim()) throw new DocxError("This Word file has no text to read (it may only hold pictures) — paste the text into the prompt instead");const core = entries.find((e) => e.name === CORE)?.data.toString("utf8");const title = core && /<dc:title>([^<]*)<\/dc:title>/.exec(core)?.[1];diff --git a/tests/explainer-documents.test.ts b/tests/explainer-documents.test.tsindex a654f835..e17e6711 100644--- a/tests/explainer-documents.test.ts+++ b/tests/explainer-documents.test.ts@@ -174,6 +174,39 @@ describe("Word documents (.docx)", () => {expect(documentXmlText(xml)).toBe(["Tides & the Moon", "Twice a day\tthe sea rises.", "Then it falls.", "Kept text", "High\t06:12", "Low\t12:30", "In a box", "“Quoted” <tag> café", "", "The end."].join("\n"));});+ it("leaves out a paragraph's tab stops (they're <w:tab>s in its properties, not tabs in the text)", () => {+ const stops = '<w:pPr><w:tabs><w:tab w:val="left" w:pos="720"/><w:tab w:val="right" w:leader="dot" w:pos="9000"/></w:tabs></w:pPr>';+ const xml = `<w:document ${W}><w:body><w:p>${stops}<w:r>${t("Contents")}</w:r></w:p><w:p>${stops}<w:r>${t("Second paragraph")}<w:tab/>${t("12")}</w:r></w:p></w:body></w:document>`;+ expect(documentXmlText(xml)).toBe("Contents\nSecond paragraph\t12");+ // A line break inside a table cell keeps the row on one line.+ expect(documentXmlText(`<w:tbl><w:tr><w:tc>${para(t("Two"), "<w:br/>", t("lines"))}</w:tc><w:tc>${para(t("x"))}</w:tc></w:tr></w:tbl>`)).toBe("Two lines\tx");+ });++ it("reads a crafted document in time that grows with its size, not its square", () => {+ // Tags that never close and runs of blanks used to make the regexes rescan the rest of the file for each one.+ const crafted = [+ "<w:tc>".repeat(200_000),+ "<mc:Fallback>".repeat(100_000),+ "<w:delText x>".repeat(100_000),+ `<w:p><w:r><w:t>${" ".repeat(1_000_000)}x${"\u00a0 ".repeat(200_000)}y</w:t></w:r></w:p>`,+ ];+ const started = performance.now();+ for (const xml of crafted) documentXmlText(xml);+ expect(documentXmlText(`<w:p><w:r><w:t>${" ".repeat(1_000_000)}x${" ".repeat(100_000)}\ty</w:t></w:r></w:p>`)).toBe("x\ty");+ expect(performance.now() - started).toBeLessThan(2_000);+ // Through the .docx reader: a few KB that inflate to 12 MB of unclosed cells, refused quickly.+ const bomb = makeDocx("<w:tc>".repeat(2_000_000));+ expect(bomb.length).toBeLessThan(100_000);+ const t0 = performance.now();+ expect(() => docxText(bomb, { maxChars: 40_000 })).toThrow(/no text to read/);+ expect(performance.now() - t0).toBeLessThan(2_000);+ // A long document stops being read once there's enough text.+ const long = makeDocx(para(t("The tide comes in. ")).repeat(200_000));+ const t1 = performance.now();+ expect(docxText(long, { maxChars: 1000 }).text).toHaveLength(1000);+ expect(performance.now() - t1).toBeLessThan(2_000);+ });+it("reads a .docx's text and title, inflating only the document (a large picture inside costs nothing)", () => {const picture = Buffer.alloc(60 * 1024 * 1024); // 60 MB of zeros: deflates to a few KB, would blow every cap if inflatedconst docx = makeDocx([para(t("Why the sea has tides.")), para(t("The Moon pulls the water."))].join(""), { title: "Tides & you", extra: [{ name: "word/media/image1.png", data: picture }] });