Open History to see the last commit
1import JSZip from "jszip";
2import { describe, expect, it } from "vite-plus/test";
3
4import { prepareOffice } from "./officeArchive";
5import { unlockOpenDocument } from "./openDocumentEncryption";
6
7const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
8const V = 'xmlns:v="urn:schemas-microsoft-com:vml"';
9const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
10const relationship = (type: string, target: string) =>
11 `<Relationship Id="${type}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${target}"/>`;
12const paragraph = (text: string, properties = "") =>
13 `<w:p>${properties}<w:r><w:t xml:space="preserve">${text}</w:t></w:r></w:p>`;
14
15async function wordFile(
16 body: string,
17 parts: Partial<Record<"styles" | "numbering" | "header" | "footer" | "footnotes", string>> = {},
18 section = "",
19 extraRels = "",
20 media: Record<string, string> = {},
21) {
22 const zip = new JSZip();
23 zip.file(
24 "[Content_Types].xml",
25 `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="svg" ContentType="image/svg+xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>`,
26 );
27 zip.file(
28 "_rels/.rels",
29 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship("officeDocument", "word/document.xml")}</Relationships>`,
30 );
31 zip.file(
32 "word/_rels/document.xml.rels",
33 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${Object.keys(
34 parts,
35 )
36 .map((part) => relationship(part, `${part}.xml`))
37 .join("")}${extraRels}</Relationships>`,
38 );
39 for (const [part, xml] of Object.entries(parts)) zip.file(`word/${part}.xml`, xml);
40 for (const [path, data] of Object.entries(media)) zip.file(path, data);
41 zip.file(
42 "word/document.xml",
43 `<w:document ${W} ${V} ${R}><w:body>${body}<w:sectPr>${section}<w:pgSz w:w="12240" w:h="15840"/></w:sectPr></w:body></w:document>`,
44 );
45 return zip.generateAsync({ type: "arraybuffer" });
46}
47
48async function prepared(bytes: ArrayBuffer) {
49 const result = await prepareOffice(bytes, "docx");
50 const zip = await JSZip.loadAsync(result.bytes);
51 return { truncated: result.truncated, part: (path: string) => zip.file(path)?.async("string") };
52}
53
54// regression: the budgets sized for a main-thread renderer cut ordinary documents short.
55describe("Word preview limits", () => {
56 it("keeps a document whose table follows a long one", async () => {
57 const rows = Array.from(
58 { length: 500 },
59 (_, row) =>
60 `<w:tr>${Array.from({ length: 5 }, (_, cell) => `<w:tc>${paragraph(`r${row}c${cell}`)}</w:tc>`).join("")}</w:tr>`,
61 ).join("");
62 const result = await prepared(
63 await wordFile(`<w:tbl>${rows}</w:tbl>${paragraph("After the table")}`),
64 );
65 expect(result.truncated).toBe(false);
66 expect(await result.part("word/document.xml")).toContain("After the table");
67 });
68
69 it("keeps the list and style definitions of a long document", async () => {
70 const levels = Array.from(
71 { length: 9 },
72 (_, level) =>
73 `<w:lvl w:ilvl="${level}"><w:numFmt w:val="decimal"/><w:lvlText w:val="%${level + 1}."/></w:lvl>`,
74 ).join("");
75 const numbering = `<w:numbering ${W}>${Array.from({ length: 60 }, (_, list) => `<w:abstractNum w:abstractNumId="${list}">${levels}</w:abstractNum>`).join("")}${Array.from({ length: 60 }, (_, list) => `<w:num w:numId="${list + 1}"><w:abstractNumId w:val="${list}"/></w:num>`).join("")}</w:numbering>`;
76 const styles = `<w:styles ${W}>${Array.from(
77 { length: 1_500 },
78 (_, style) =>
79 `<w:style w:type="paragraph" w:styleId="S${style}">${style % 10 ? `<w:basedOn w:val="S${style - 1}"/>` : ""}<w:pPr><w:spacing w:after="${style}"/></w:pPr><w:rPr><w:sz w:val="22"/></w:rPr></w:style>`,
80 ).join("")}</w:styles>`;
81 const result = await prepared(
82 await wordFile(
83 Array.from({ length: 6_000 }, (_, index) =>
84 paragraph(
85 `Item ${index}`,
86 `<w:pPr><w:pStyle w:val="S${index % 1_500}"/><w:numPr><w:ilvl w:val="0"/><w:numId w:val="${(index % 60) + 1}"/></w:numPr></w:pPr>`,
87 ),
88 ).join(""),
89 { styles, numbering },
90 ),
91 );
92 expect(result.truncated).toBe(false);
93 expect(await result.part("word/numbering.xml")).toBe(numbering);
94 expect(await result.part("word/styles.xml")).toBe(styles);
95 expect(await result.part("word/document.xml")).toContain("Item 5999");
96 });
97
98 it("keeps the lists of a document with picture bullets, with their text bullets", async () => {
99 const picture = `<w:numPicBullet w:numPicBulletId="0"><w:pict><v:shape style="width:9pt;height:9pt"><v:imagedata r:id="rId1"/></v:shape></w:pict></w:numPicBullet>`;
100 const pictured = `<w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/><w:lvlText w:val="\uf0b7"/><w:lvlPicBulletId w:val="0"/></w:lvl></w:abstractNum>`;
101 const numbered = `<w:abstractNum w:abstractNumId="1"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum>`;
102 const lists = `<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num><w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>`;
103 const result = await prepared(
104 await wordFile(paragraph("Item", `<w:pPr><w:numPr><w:numId w:val="2"/></w:numPr></w:pPr>`), {
105 numbering: `<w:numbering ${W} ${V} ${R}>${picture}${pictured}${numbered}${lists}</w:numbering>`,
106 }),
107 );
108 expect(await result.part("word/numbering.xml")).toBe(
109 `<w:numbering ${W} ${V} ${R}>${pictured.replace('<w:lvlPicBulletId w:val="0"/>', "")}${numbered}${lists}</w:numbering>`,
110 );
111 });
112
113 const text = "x".repeat(140_000);
114 it.each([
115 ["on its own", `<w:p><w:r><w:t>${text}</w:t></w:r></w:p>`],
116 [
117 "after an empty paragraph in a text box",
118 `<w:p><w:r><w:pict><v:shape><v:textbox><w:txbxContent><w:p/></w:txbxContent></v:textbox></v:shape></w:pict></w:r><w:r><w:t>${text}</w:t></w:r></w:p>`,
119 ],
120 ["written as CDATA", `<w:p><w:r><w:t><![CDATA[${text}]]></w:t></w:r></w:p>`],
121 ])("stops before a paragraph too long to lay out %s", async (_, long) => {
122 const result = await prepared(
123 await wordFile(paragraph("Kept") + long + paragraph("Not reached")),
124 );
125 expect(result.truncated).toBe(true);
126 const document = await result.part("word/document.xml");
127 expect(document).toContain("Kept");
128 expect(document).not.toContain("Not reached");
129 });
130
131 it("counts only the text a paragraph lays out", async () => {
132 const formatted = `<w:p>${" ".repeat(140_000)}<w:r><w:instrText>${"x".repeat(140_000)}</w:instrText></w:r><w:r><w:t>${"x".repeat(40_000)}</w:t></w:r></w:p>`;
133 const result = await prepared(await wordFile(formatted + paragraph("After")));
134 expect(result.truncated).toBe(false);
135 expect(await result.part("word/document.xml")).toContain("After");
136 });
137
138 it("keeps a long header", async () => {
139 const header = `<w:hdr ${W}>${Array.from({ length: 3_000 }, (_, line) => paragraph(`Header line ${line}`)).join("")}</w:hdr>`;
140 const footer = `<w:ftr ${W}>${paragraph("Footer")}</w:ftr>`;
141 const footnotes = `<w:footnotes ${W}><w:footnote w:id="1">${paragraph("Note")}</w:footnote></w:footnotes>`;
142 const result = await prepared(
143 await wordFile(
144 `<w:p><w:r><w:t>Body</w:t></w:r><w:r><w:footnoteReference w:id="1"/></w:r></w:p>`,
145 { header, footer, footnotes },
146 `<w:headerReference w:type="default" r:id="header"/><w:footerReference w:type="default" r:id="footer"/>`,
147 ),
148 );
149 expect(result.truncated).toBe(false);
150 expect(await result.part("word/header.xml")).toBe(header);
151 expect(await result.part("word/footer.xml")).toBe(footer);
152 expect(await result.part("word/footnotes.xml")).toBe(footnotes);
153 expect(await result.part("word/document.xml")).toContain("Body");
154 });
155
156 it("drops a malformed external hyperlink relationship while keeping body text", async () => {
157 const result = await prepared(
158 await wordFile(
159 paragraph("Body text"),
160 {},
161 "",
162 `<Relationship Id="badLink" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="http://[placeholder]/" TargetMode="External"/>`,
163 ),
164 );
165 expect(result.truncated).toBe(false);
166 expect(await result.part("word/document.xml")).toContain("Body text");
167 expect(await result.part("word/_rels/document.xml.rels")).not.toContain("badLink");
168 });
169
170 it("keeps a document with an embedded SVG image", async () => {
171 const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>';
172 const body = `${paragraph("Before")}<w:p><w:r><w:drawing><a:blip xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" r:embed="image"/></w:drawing></w:r></w:p>`;
173 const result = await prepared(
174 await wordFile(body, {}, "", relationship("image", "media/image1.svg"), {
175 "word/media/image1.svg": svg,
176 }),
177 );
178 expect(result.truncated).toBe(false);
179 expect(await result.part("word/document.xml")).toContain("Before");
180 expect(await result.part("word/media/image1.svg")).toBe(svg);
181 });
182
183 it("keeps a VML picture whose imagedata carries a shape id before r:id", async () => {
184 const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>';
185 const body = `<w:p><w:r><w:pict><v:shape><v:imagedata id="_x0000_i1025" r:id="image"/></v:shape></w:pict></w:r></w:p>`;
186 const result = await prepared(
187 await wordFile(body, {}, "", relationship("image", "media/image1.svg"), {
188 "word/media/image1.svg": svg,
189 }),
190 );
191 expect(await result.part("word/media/image1.svg")).toBe(svg);
192 });
193});
194
195async function workbookFile(
196 target: string,
197 sheetPath: string,
198 extraRels = "",
199 targetMode = "Internal",
200 sheetData = `<row r="1"><c r="A1"><v>42</v></c></row>`,
201) {
202 const zip = new JSZip();
203 zip.file(
204 "[Content_Types].xml",
205 `<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/></Types>`,
206 );
207 zip.file(
208 "_rels/.rels",
209 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">${relationship("officeDocument", "xl/workbook.xml")}</Relationships>`,
210 );
211 zip.file(
212 "xl/workbook.xml",
213 `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ${R}><sheets><sheet name="Sample" sheetId="1" r:id="sheet"/></sheets></workbook>`,
214 );
215 zip.file(
216 "xl/_rels/workbook.xml.rels",
217 `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="sheet" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="${target}" TargetMode="${targetMode}"/>${extraRels}</Relationships>`,
218 );
219 zip.file(
220 sheetPath,
221 `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>${sheetData}</sheetData></worksheet>`,
222 );
223 return zip.generateAsync({ type: "arraybuffer" });
224}
225
226describe("Workbook relationship targets", () => {
227 it.each(["sheet 1.xml", "sheet%201.xml", "sheet#1.xml"])(
228 "prepares a worksheet whose ZIP name matches its target literally (%s)",
229 async (name) => {
230 const result = await prepareOffice(
231 await workbookFile(`worksheets/${name}`, `xl/worksheets/${name}`),
232 "xlsx",
233 );
234 const zip = await JSZip.loadAsync(result.bytes);
235 expect(result.truncated).toBe(false);
236 expect(await zip.file(`xl/worksheets/${name}`)?.async("string")).toContain("42");
237 },
238 );
239
240 it("refuses a worksheet whose relationship is external", async () => {
241 await expect(
242 prepareOffice(
243 await workbookFile("worksheets/sheet2.xml", "xl/worksheets/sheet2.xml", "", "External"),
244 "xlsx",
245 ),
246 ).rejects.toMatchObject({ code: "workbook-sheet-count" });
247 });
248
249 it("handles a malformed external relationship in workbook relationships", async () => {
250 const result = await prepareOffice(
251 await workbookFile(
252 "worksheets/sheet1.xml",
253 "xl/worksheets/sheet1.xml",
254 `<Relationship Id="ext" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/externalLinkPath" Target="http://[placeholder]/" TargetMode="External"/>`,
255 ),
256 "xlsx",
257 );
258 const zip = await JSZip.loadAsync(result.bytes);
259 expect(result.truncated).toBe(false);
260 expect(await zip.file("xl/worksheets/sheet1.xml")?.async("string")).toContain("42");
261 });
262});
263
264describe("Workbook preview limits", () => {
265 it("does not split a surrogate pair when truncating cell text", async () => {
266 const prefix = "a".repeat(4095);
267 const result = await prepareOffice(
268 await workbookFile(
269 "worksheets/sheet1.xml",
270 "xl/worksheets/sheet1.xml",
271 "",
272 "Internal",
273 `<row r="1"><c r="A1" t="inlineStr"><is><t>${prefix}🚀tail</t></is></c></row>`,
274 ),
275 "xlsx",
276 );
277 const zip = await JSZip.loadAsync(result.bytes);
278 const sheet = await zip.file("xl/worksheets/sheet1.xml")?.async("string");
279 expect(result.truncated).toBe(true);
280 expect(sheet).toContain(`<t>${prefix}</t>`);
281 expect(sheet).not.toContain("\ufffd");
282 });
283});
284
285describe("Case-insensitive XML size limits", () => {
286 it("rejects uppercase .XML entries exceeding 8 MiB in office archives", async () => {
287 const zip = new JSZip();
288 zip.file("ppt/slides/slide1.XML", new Uint8Array(8 * 1024 * 1024 + 1));
289 const bytes = await zip.generateAsync({ type: "arraybuffer", compression: "DEFLATE" });
290 await expect(prepareOffice(bytes, "pptx")).rejects.toMatchObject({
291 code: "office-too-large-expanded",
292 });
293 });
294
295 it("rejects uppercase .XML entries exceeding 8 MiB in encrypted OpenDocument manifests", async () => {
296 const zip = new JSZip();
297 const manifestXml =
298 `<?xml version="1.0" encoding="UTF-8"?>` +
299 `<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">` +
300 `<manifest:file-entry manifest:full-path="content.XML" manifest:size="${8 * 1024 * 1024 + 1}">` +
301 `<manifest:encryption-data manifest:checksum-type="SHA1/1K" manifest:checksum="AAAAAAAAAAAAAAAAAAAAAAAAAAA=">` +
302 `<manifest:algorithm manifest:algorithm-name="http://www.w3.org/2001/04/xmlenc#aes256-cbc" manifest:initialisation-vector="AAAAAAAAAAAAAAAAAAAAAA=="/>` +
303 `<manifest:key-derivation manifest:key-derivation-name="PBKDF2" manifest:iteration-count="1" manifest:salt="AAAAAAAAAAAAAAAAAAAAAA=="/>` +
304 `</manifest:encryption-data>` +
305 `</manifest:file-entry>` +
306 `</manifest:manifest>`;
307 zip.file("META-INF/manifest.xml", manifestXml);
308 await expect(unlockOpenDocument(zip, "open me")).rejects.toMatchObject({
309 code: "office-too-large-expanded",
310 });
311 });
312});