SPB Git

Repository Public Research preview

zip.mjs 6.5 KB 110 lines javascript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : LLM API toolkits8 * File             : xlsx/mcp/lib/zip.mjs9 * Module           : xlsx10 * Repository       : https://git.spboucher.ai/llm-api-toolkits11 * Created          : 2026-11-1012 * Last Modified    : 2026-11-1013 *14 * Author           : Simon-Pierre Boucher15 * Position         : Professor of Finance16 * Institution      : Université du Québec en Outaouais (UQO)17 * Organization     : SP Boucher18 * Website          : https://spboucher.ai19 * Git              : https://git.spboucher.ai20 *21 * Preferred Contact: dev@spboucher.ai22 * Development      : dev@spboucher.ai23 * Support          : support@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { inflateRawSync } from "node:zlib";4344/**45 * Minimal, strict ZIP reader for OOXML packages. Reads entries into memory; never writes to disk.46 * Refuses what a spreadsheet never needs: ZIP64, encryption, multi-disk archives, entry names that47 * try to leave the archive, and entries that inflate beyond the configured limits (zip bombs).48 */49export class XlsxError extends Error {50  constructor(code, message) { super(message); this.code = code; }51}5253export const DEFAULT_LIMITS = { maxFileBytes: 50 * 1024 * 1024, maxEntries: 5000, maxEntryBytes: 128 * 1024 * 1024, maxTotalBytes: 384 * 1024 * 1024 };5455export function unsafeEntryName(name) {56  return name.length === 0 || name.includes("\0") || name.startsWith("/") || name.includes("\\") || /^[A-Za-z]:/.test(name) || name.split("/").includes("..");57}5859/** Returns a Map name → Buffer for the wanted entries (all entries when `want` is omitted). */60export function readZip(buf, { limits = DEFAULT_LIMITS, want } = {}) {61  if (!Buffer.isBuffer(buf) || buf.length < 22) throw new XlsxError("not_a_zip", "The file is too small to be a ZIP package.");62  if (buf.length > limits.maxFileBytes) throw new XlsxError("file_too_large", `The file is larger than ${limits.maxFileBytes} bytes.`);63  if (buf.readUInt32LE(0) !== 0x04034b50) throw new XlsxError("not_a_zip", "The file does not start with a ZIP signature. Is it really an .xlsx workbook (not .xls or .csv)?");64  let eocd = -1;65  for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }66  if (eocd < 0) throw new XlsxError("zip_corrupt", "End-of-central-directory record not found: the file is truncated or corrupt.");67  const count = buf.readUInt16LE(eocd + 10), cdSize = buf.readUInt32LE(eocd + 12), cdOffset = buf.readUInt32LE(eocd + 16);68  if (buf.readUInt16LE(eocd + 4) !== 0 || buf.readUInt16LE(eocd + 6) !== 0) throw new XlsxError("zip_unsupported", "Multi-disk ZIP archives are not supported.");69  if (count === 0xffff || cdOffset === 0xffffffff || cdSize === 0xffffffff) throw new XlsxError("zip_unsupported", "ZIP64 archives are not supported.");70  if (count > limits.maxEntries) throw new XlsxError("zip_limit", `The archive has ${count} entries (limit ${limits.maxEntries}).`);71  if (cdOffset + cdSize > buf.length) throw new XlsxError("zip_corrupt", "The central directory points outside the file.");72  const entries = [];73  let p = cdOffset;74  for (let i = 0; i < count; i++) {75    if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) throw new XlsxError("zip_corrupt", "Corrupt central directory entry.");76    const flags = buf.readUInt16LE(p + 8), method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), usize = buf.readUInt32LE(p + 24);77    const nlen = buf.readUInt16LE(p + 28), elen = buf.readUInt16LE(p + 30), clen = buf.readUInt16LE(p + 32), local = buf.readUInt32LE(p + 42);78    const name = buf.subarray(p + 46, p + 46 + nlen).toString("utf8");79    p += 46 + nlen + elen + clen;80    if (unsafeEntryName(name)) throw new XlsxError("zip_unsafe_name", `The archive contains an unsafe entry name (${JSON.stringify(name.slice(0, 80))}).`);81    if (flags & 1) throw new XlsxError("zip_encrypted", "The workbook is encrypted (password-protected). Remove the protection first.");82    entries.push({ name, method, csize, usize, local });83  }84  const out = new Map();85  let total = 0;86  for (const e of entries) {87    if (want && !want(e.name)) continue;88    if (e.name.endsWith("/")) continue;89    if (e.usize > limits.maxEntryBytes) throw new XlsxError("zip_limit", `Entry ${e.name} declares ${e.usize} bytes (limit ${limits.maxEntryBytes}).`);90    if (e.local + 30 > buf.length || buf.readUInt32LE(e.local) !== 0x04034b50) throw new XlsxError("zip_corrupt", `Corrupt local header for ${e.name}.`);91    const start = e.local + 30 + buf.readUInt16LE(e.local + 26) + buf.readUInt16LE(e.local + 28);92    if (start + e.csize > buf.length) throw new XlsxError("zip_corrupt", `Entry ${e.name} runs past the end of the file.`);93    const raw = buf.subarray(start, start + e.csize);94    let data;95    if (e.method === 0) data = Buffer.from(raw);96    else if (e.method === 8) {97      // The declared size is not trusted: inflation stops at the limit whatever the header says.98      try { data = inflateRawSync(raw, { maxOutputLength: limits.maxEntryBytes }); }99      catch (err) {100        if (err.code === "ERR_BUFFER_TOO_LARGE") throw new XlsxError("zip_limit", `Entry ${e.name} inflates beyond ${limits.maxEntryBytes} bytes (possible decompression bomb).`);101        throw new XlsxError("zip_corrupt", `Entry ${e.name} cannot be decompressed.`);102      }103    } else throw new XlsxError("zip_unsupported", `Entry ${e.name} uses compression method ${e.method}, which is not supported.`);104    total += data.length;105    if (total > limits.maxTotalBytes) throw new XlsxError("zip_limit", `The archive expands beyond ${limits.maxTotalBytes} bytes (possible decompression bomb).`);106    out.set(e.name, data);107  }108  return out;109}110
Files main
Menu

Theme