@stll/docx-core 0.28.1 → 0.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,7 +40,12 @@ bun add @stll/docx-core
40
40
  `applyDocumentOps` apply text and formatting edits addressed by paragraph
41
41
  id and offset, and return the new document, the blocks it touched and its
42
42
  exact inverse (operations addressed the same way), or a typed refusal.
43
- `normalizeForOps` and `validateOpsDocument` establish and check the
43
+ With a `revision` stamp, the text, formatting and paragraph operations
44
+ record their edit as tracked changes instead, and `resolveRevision`
45
+ accepts or rejects tracked changes by revision id. `planTrackedDeletion`
46
+ plans a tracked deletion around the author's own insertions and comment
47
+ anchors, and `revisionIdDemand` counts the new revision ids an operation
48
+ takes. `normalizeForOps` and `validateOpsDocument` establish and check the
44
49
  contract a document meets before operations apply to it; `toOpEnvelope`
45
50
  wraps an operation with its schema version for journaling.
46
51
 
Binary file
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { A as BlockContent, An as Table, I as BreakContent, J as DocumentBody, K as DocumentBackground, Kt as Paragraph, Qt as PositionalTab, Sr as NumberingDefinitions, Un as TextContent, a as DocxPackage, cn as Run, g as Style, hn as SectionProperties, i as DocxConformanceClass, jn as TableCell, ln as RunContent, n as Document, q as DocumentBackgroundDrawing, qt as ParagraphContent, t as DOCX_CONFORMANCE_CLASSES, zn as TableRow } from "./document-DrtmJ_hz.js";
2
+ import JSZip from "jszip";
2
3
  import { Buffer } from "node:buffer";
3
4
  //#region src/legal-source/types.d.ts
4
5
  type LegalDocumentKind = "agreement" | "letter" | "memo" | "checklist" | "pleading" | "other";
@@ -285,6 +286,12 @@ declare const sanitizeXmlCharacters: (value: string) => string;
285
286
  declare const requiresXmlSpacePreserve: (text: string) => boolean;
286
287
  //#endregion
287
288
  //#region src/validate/docx.d.ts
289
+ declare module "jszip" {
290
+ interface JSZipObject {
291
+ /** Chunked read of the entry content, missing from the published typings. */
292
+ internalStream(type: "uint8array"): JSZip.JSZipStreamHelper<Uint8Array>;
293
+ }
294
+ }
288
295
  declare const DOCX_PACKAGE_ISSUE_CODES: {
289
296
  readonly ArchiveBoundsExceeded: "archive_bounds_exceeded";
290
297
  readonly InvalidArchive: "invalid_archive";
package/dist/index.js CHANGED
@@ -468,6 +468,16 @@ const VALIDATE_DOCX_MAX_ENTRIES = 4096;
468
468
  const VALIDATE_DOCX_MAX_ENTRY_BYTES = 128 * 1024 * 1024;
469
469
  const VALIDATE_DOCX_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
470
470
  const VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES = 32 * 1024 * 1024;
471
+ /**
472
+ * Inflated bytes allowed per compressed byte, for a markup or text entry and
473
+ * for the whole archive, once either passes the grace size. Real document
474
+ * parts stay far below this; an entry of one repeated byte sits near
475
+ * DEFLATE's 1032:1 ceiling. Binary entries can legitimately compress that far
476
+ * (an uncompressed bitmap of one colour), so only the archive-wide ratio and
477
+ * the byte limits bound them.
478
+ */
479
+ const VALIDATE_DOCX_MAX_COMPRESSION_RATIO = 200;
480
+ const VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES = 4 * 1024 * 1024;
471
481
  const WORDPROCESSINGML_NAMESPACES = /* @__PURE__ */ new Set(["http://schemas.openxmlformats.org/wordprocessingml/2006/main", "http://purl.oclc.org/ooxml/wordprocessingml/main"]);
472
482
  const packageXmlParser = new XMLParser({
473
483
  preserveOrder: true,
@@ -482,6 +492,101 @@ const getDeclaredUncompressedSize = (file) => {
482
492
  const metadata = file._data;
483
493
  return typeof metadata?.uncompressedSize === "number" ? metadata.uncompressedSize : null;
484
494
  };
495
+ const getCompressedSize = (file) => {
496
+ const metadata = file._data;
497
+ return typeof metadata?.compressedSize === "number" ? metadata.compressedSize : null;
498
+ };
499
+ const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
500
+ "xml",
501
+ "rels",
502
+ "vml",
503
+ "txt",
504
+ "htm",
505
+ "html",
506
+ "mht",
507
+ "mhtml",
508
+ "rtf"
509
+ ]);
510
+ const isRatioBoundedPart = (path) => RATIO_BOUNDED_EXTENSIONS.has(path.slice(path.lastIndexOf(".") + 1).toLowerCase());
511
+ const exceedsCompressionRatio = (inflatedBytes, compressedBytes) => compressedBytes !== null && inflatedBytes > VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES && inflatedBytes > compressedBytes * VALIDATE_DOCX_MAX_COMPRESSION_RATIO;
512
+ /**
513
+ * Upper bound on the archive's central-directory records, counted before JSZip
514
+ * builds an object per record: each record starts with the `PK\x01\x02`
515
+ * signature, so JSZip cannot find more records than there are signatures.
516
+ */
517
+ const countCentralDirectoryRecords = (bytes, stopAfter) => {
518
+ let count = 0;
519
+ let offset = bytes.indexOf(80);
520
+ while (offset !== -1 && offset + 3 < bytes.length) {
521
+ if (bytes[offset + 1] === 75 && bytes[offset + 2] === 1 && bytes[offset + 3] === 2) {
522
+ count += 1;
523
+ if (count > stopAfter) return count;
524
+ }
525
+ offset = bytes.indexOf(80, offset + 1);
526
+ }
527
+ return count;
528
+ };
529
+ const concatChunks = (chunks, totalBytes) => {
530
+ const merged = new Uint8Array(totalBytes);
531
+ let offset = 0;
532
+ for (const chunk of chunks) {
533
+ merged.set(chunk, offset);
534
+ offset += chunk.length;
535
+ }
536
+ return merged;
537
+ };
538
+ /**
539
+ * Inflate one entry chunk by chunk and stop as soon as it passes `maxBytes`,
540
+ * its declared size or the compression-ratio cap. JSZip compares an entry
541
+ * with its declared size only after inflating all of it, so the declared
542
+ * size alone does not bound the allocation.
543
+ */
544
+ const readEntryWithinBounds = async (entry, maxBytes) => {
545
+ const declaredBytes = getDeclaredUncompressedSize(entry);
546
+ const compressedBytes = getCompressedSize(entry);
547
+ return await new Promise((resolve, reject) => {
548
+ const stream = entry.internalStream("uint8array");
549
+ const chunks = [];
550
+ let entryBytes = 0;
551
+ let settled = false;
552
+ const stop = (error) => {
553
+ settled = true;
554
+ stream.pause();
555
+ resolve({
556
+ ok: false,
557
+ error
558
+ });
559
+ };
560
+ stream.on("data", (chunk) => {
561
+ if (settled) return;
562
+ entryBytes += chunk.length;
563
+ if (declaredBytes !== null && entryBytes > declaredBytes) {
564
+ stop(`Generated DOCX entry "${entry.name}" inflates past its declared size.`);
565
+ return;
566
+ }
567
+ if (exceedsCompressionRatio(entryBytes, compressedBytes)) {
568
+ stop(`Generated DOCX entry "${entry.name}" exceeds the ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO}:1 compression ratio limit.`);
569
+ return;
570
+ }
571
+ if (entryBytes > maxBytes) {
572
+ stop(`Generated DOCX ${entry.name} exceeds the ${maxBytes}-byte limit.`);
573
+ return;
574
+ }
575
+ chunks.push(chunk);
576
+ }).on("end", () => {
577
+ if (settled) return;
578
+ settled = true;
579
+ resolve({
580
+ ok: true,
581
+ bytes: concatChunks(chunks, entryBytes)
582
+ });
583
+ }).on("error", (error) => {
584
+ if (settled) return;
585
+ settled = true;
586
+ reject(error);
587
+ }).resume();
588
+ });
589
+ };
485
590
  /**
486
591
  * Reject an archive whose entry count or declared uncompressed size (total
487
592
  * or per-entry) exceeds the local bounds above, before any part is inflated.
@@ -489,7 +594,7 @@ const getDeclaredUncompressedSize = (file) => {
489
594
  * as unbounded — the per-entry cap below still bounds what an inflate call
490
595
  * can actually produce once it runs.
491
596
  */
492
- const checkDocxArchiveBounds = (zip) => {
597
+ const checkDocxArchiveBounds = (zip, archiveBytes) => {
493
598
  const entries = Object.values(zip.files);
494
599
  if (entries.length > VALIDATE_DOCX_MAX_ENTRIES) return `Generated DOCX declares ${entries.length} archive entries, over the ${VALIDATE_DOCX_MAX_ENTRIES}-entry limit.`;
495
600
  let totalUncompressedBytes = 0;
@@ -497,9 +602,11 @@ const checkDocxArchiveBounds = (zip) => {
497
602
  const declaredBytes = getDeclaredUncompressedSize(entry);
498
603
  if (declaredBytes === null) continue;
499
604
  if (declaredBytes > VALIDATE_DOCX_MAX_ENTRY_BYTES) return `Generated DOCX entry "${entry.name}" declares ${declaredBytes} uncompressed bytes, over the ${VALIDATE_DOCX_MAX_ENTRY_BYTES}-byte limit.`;
605
+ if (isRatioBoundedPart(entry.name) && exceedsCompressionRatio(declaredBytes, getCompressedSize(entry))) return `Generated DOCX entry "${entry.name}" declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per compressed byte.`;
500
606
  totalUncompressedBytes += declaredBytes;
501
607
  if (totalUncompressedBytes > VALIDATE_DOCX_MAX_TOTAL_BYTES) return `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_TOTAL_BYTES} cumulative uncompressed bytes.`;
502
608
  }
609
+ if (exceedsCompressionRatio(totalUncompressedBytes, archiveBytes)) return `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per archive byte.`;
503
610
  return null;
504
611
  };
505
612
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -534,8 +641,14 @@ const validateDocumentXml = (xml) => {
534
641
  };
535
642
  const validateDocxPackage = async (buffer) => {
536
643
  try {
644
+ const archiveBytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
645
+ if (countCentralDirectoryRecords(archiveBytes, VALIDATE_DOCX_MAX_ENTRIES) > VALIDATE_DOCX_MAX_ENTRIES) return {
646
+ valid: false,
647
+ code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
648
+ error: `Generated DOCX holds more than ${VALIDATE_DOCX_MAX_ENTRIES} archive entries.`
649
+ };
537
650
  const zip = await JSZip.loadAsync(buffer);
538
- const boundsError = checkDocxArchiveBounds(zip);
651
+ const boundsError = checkDocxArchiveBounds(zip, archiveBytes.byteLength);
539
652
  if (boundsError) return {
540
653
  valid: false,
541
654
  code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
@@ -557,12 +670,13 @@ const validateDocxPackage = async (buffer) => {
557
670
  code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
558
671
  error: `Generated DOCX word/document.xml declares ${declaredDocumentBytes} uncompressed bytes, over the ${VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES}-byte limit.`
559
672
  };
560
- const documentBytes = await documentPart?.async("uint8array");
561
- if (documentBytes !== void 0 && documentBytes.byteLength > VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) return {
673
+ const documentRead = documentPart ? await readEntryWithinBounds(documentPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
674
+ if (documentRead !== void 0 && !documentRead.ok) return {
562
675
  valid: false,
563
676
  code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
564
- error: `Generated DOCX word/document.xml exceeds the ${VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES}-byte limit.`
677
+ error: documentRead.error
565
678
  };
679
+ const documentBytes = documentRead?.bytes;
566
680
  const documentXml = documentBytes ? new TextDecoder().decode(documentBytes) : void 0;
567
681
  const documentError = documentXml ? validateDocumentXml(documentXml) : "Generated DOCX has no word/document.xml root document.";
568
682
  if (documentError) return {
@@ -570,7 +684,14 @@ const validateDocxPackage = async (buffer) => {
570
684
  code: DOCX_PACKAGE_ISSUE_CODES.InvalidDocumentRoot,
571
685
  error: documentError
572
686
  };
573
- if ((await zip.file("word/_rels/document.xml.rels")?.async("string"))?.includes("/relationships/numbering") && !zip.file("word/numbering.xml")) return {
687
+ const documentRelsPart = zip.file("word/_rels/document.xml.rels");
688
+ const documentRelsRead = documentRelsPart ? await readEntryWithinBounds(documentRelsPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
689
+ if (documentRelsRead !== void 0 && !documentRelsRead.ok) return {
690
+ valid: false,
691
+ code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
692
+ error: documentRelsRead.error
693
+ };
694
+ if ((documentRelsRead ? new TextDecoder().decode(documentRelsRead.bytes) : void 0)?.includes("/relationships/numbering") && !zip.file("word/numbering.xml")) return {
574
695
  valid: false,
575
696
  code: DOCX_PACKAGE_ISSUE_CODES.MissingNumberingPart,
576
697
  error: "Generated DOCX references numbering.xml but does not include it."