Toolpal

@toolpal/pii-redact

public

v2.0published 1 download this weekMIT

Scans and redacts personal information (emails, phone numbers, SSNs, Luhn-verified credit cards, IBANs, IP addresses) and credentials/secrets (API keys, JWTs, private keys, database URLs, Bearer tokens) locally from text or files (TXT, MD, CSV, JSON, LOG, ENV, DOCX). Runs 100% offline with zero network access and no API keys.

src/zip.ts6.3 KBRaw
// Hardened minimal ZIP reader/writer (store + deflate) and XML escaping helpers.
// Bounds-checked central directory parsing and bounded inflation protect against zip bombs.
import { Buffer } from "node:buffer";
import { deflateRawSync, inflateRawSync } from "node:zlib";

export interface ZipEntry {
  name: string;
  data: Buffer;
}

const MAX_ENTRY_BYTES = 50 * 1024 * 1024;
const MAX_TOTAL_UNZIP_BYTES = 120 * 1024 * 1024;
const MAX_ENTRIES = 2000;

const CRC_TABLE = new Uint32Array(256).map((_, n) => {
  let c = n;
  for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
  return c >>> 0;
});

function crc32(buf: Buffer): number {
  let c = 0xffffffff;
  for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
  return (c ^ 0xffffffff) >>> 0;
}

// Fixed timestamp (2026-01-01 00:00 DOS format) keeps archives deterministic.
const DOS_DATE = ((2026 - 1980) << 9) | (1 << 5) | 1;

export function zip(files: ZipEntry[]): Buffer {
  const parts: Buffer[] = [];
  const central: Buffer[] = [];
  let offset = 0;
  for (const file of files) {
    const name = Buffer.from(file.name, "utf8");
    const packed = deflateRawSync(file.data);
    const crc = crc32(file.data);
    const local = Buffer.alloc(30);
    local.writeUInt32LE(0x04034b50, 0);
    local.writeUInt16LE(20, 4);
    local.writeUInt16LE(0x0800, 6); // UTF-8 filename flag
    local.writeUInt16LE(8, 8);
    local.writeUInt16LE(0, 10);
    local.writeUInt16LE(DOS_DATE, 12);
    local.writeUInt32LE(crc, 14);
    local.writeUInt32LE(packed.length, 18);
    local.writeUInt32LE(file.data.length, 22);
    local.writeUInt16LE(name.length, 26);
    local.writeUInt16LE(0, 28);
    parts.push(local, name, packed);

    const entry = Buffer.alloc(46);
    entry.writeUInt32LE(0x02014b50, 0);
    entry.writeUInt16LE(20, 4);
    entry.writeUInt16LE(20, 6);
    entry.writeUInt16LE(0x0800, 8); // UTF-8 filename flag
    entry.writeUInt16LE(8, 10);
    entry.writeUInt16LE(0, 12);
    entry.writeUInt16LE(DOS_DATE, 14);
    entry.writeUInt32LE(crc, 16);
    entry.writeUInt32LE(packed.length, 20);
    entry.writeUInt32LE(file.data.length, 24);
    entry.writeUInt16LE(name.length, 28);
    entry.writeUInt16LE(0, 30);
    entry.writeUInt16LE(0, 32);
    entry.writeUInt16LE(0, 34);
    entry.writeUInt16LE(0, 36);
    entry.writeUInt32LE(0, 38);
    entry.writeUInt32LE(offset, 42);
    central.push(entry, name);
    offset += local.length + name.length + packed.length;
  }
  const centralSize = central.reduce((n, b) => n + b.length, 0);
  const end = Buffer.alloc(22);
  end.writeUInt32LE(0x06054b50, 0);
  end.writeUInt16LE(0, 4);
  end.writeUInt16LE(0, 6);
  end.writeUInt16LE(files.length, 8);
  end.writeUInt16LE(files.length, 10);
  end.writeUInt32LE(centralSize, 12);
  end.writeUInt32LE(offset, 16);
  end.writeUInt16LE(0, 20);
  return Buffer.concat([...parts, ...central, end]);
}

/** Extracts entries of a zip archive with bounds and decompression caps. */
export function unzip(buf: Buffer): Map<string, Buffer> {
  if (buf.length < 22) throw new Error("Not a valid zip file.");
  let eocd = -1;
  for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65_536); i--) {
    if (buf.readUInt32LE(i) === 0x06054b50) {
      eocd = i;
      break;
    }
  }
  if (eocd === -1) throw new Error("Not a zip file.");
  const count = buf.readUInt16LE(eocd + 10);
  if (count > MAX_ENTRIES) throw new Error(`Zip archive has too many entries (${count}).`);
  let p = buf.readUInt32LE(eocd + 16);
  const files = new Map<string, Buffer>();
  let totalUnpacked = 0;

  for (let i = 0; i < count; i++) {
    if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) {
      throw new Error("Corrupt zip central directory.");
    }
    const method = buf.readUInt16LE(p + 10);
    const packedSize = buf.readUInt32LE(p + 20);
    const unpackedSize = buf.readUInt32LE(p + 24);
    const nameLen = buf.readUInt16LE(p + 28);
    const extraLen = buf.readUInt16LE(p + 30);
    const commentLen = buf.readUInt16LE(p + 32);
    const local = buf.readUInt32LE(p + 42);
    if (p + 46 + nameLen > buf.length) throw new Error("Corrupt zip entry name.");
    const name = buf.subarray(p + 46, p + 46 + nameLen).toString("utf8");
    if (local + 30 > buf.length || buf.readUInt32LE(local) !== 0x04034b50) {
      throw new Error(`Corrupt zip local header for ${name}.`);
    }
    const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
    if (start + packedSize > buf.length) throw new Error(`Truncated zip entry ${name}.`);
    if (unpackedSize > MAX_ENTRY_BYTES) {
      throw new Error(`Zip entry ${name} exceeds size limit.`);
    }
    const raw = buf.subarray(start, start + packedSize);
    let data: Buffer;
    if (method === 0) {
      data = Buffer.from(raw);
    } else if (method === 8) {
      data = inflateRawSync(raw, { maxOutputLength: MAX_ENTRY_BYTES });
    } else {
      throw new Error(`Unsupported zip compression method ${method} for ${name}.`);
    }
    totalUnpacked += data.length;
    if (totalUnpacked > MAX_TOTAL_UNZIP_BYTES) {
      throw new Error("Unpacked zip size exceeds safety limit.");
    }
    files.set(name, data);
    p += 46 + nameLen + extraLen + commentLen;
  }
  return files;
}

// Strip illegal XML 1.0 control chars before escaping so Word/Excel never reject output.
const ILLEGAL_XML = new RegExp("[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\uFFFE\\uFFFF]", "g");

export function escapeXml(s: string): string {
  return s
    .replace(ILLEGAL_XML, "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function safeFromCodePoint(cp: number, fallback: string): string {
  if (!Number.isInteger(cp) || cp < 0 || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff)) {
    return fallback;
  }
  return String.fromCodePoint(cp);
}

export function unescapeXml(s: string): string {
  // Single pass prevents double-unescaping sequences like &#38;lt;
  return s.replace(/&(#x[0-9a-f]+|#\d+|lt|gt|quot|apos|amp);/gi, (m, ent: string) => {
    const low = ent.toLowerCase();
    if (low === "lt") return "<";
    if (low === "gt") return ">";
    if (low === "quot") return '"';
    if (low === "apos") return "'";
    if (low === "amp") return "&";
    if (low.startsWith("#x")) return safeFromCodePoint(Number.parseInt(low.slice(2), 16), m);
    return safeFromCodePoint(Number.parseInt(low.slice(1), 10), m);
  });
}