Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : tests/unit/import-validate.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/note-spboucher-ai11 * Project Website : https://note.spboucher.ai12 * Created : 2026-11-1713 * Last Modified : 2026-11-1714 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Pure-logic tests (no database): upload validation, ZIP safety, duplicate keys. Run: npx tsx --test tests/unit/import-validate.test.ts */44import { test } from "node:test";45import assert from "node:assert/strict";46import JSZip from "jszip";47import { ImportError, LIMITS, contentKey, detectKind, normText, readZipDirectory, sniff, unsafeZipPath, validateUpload, validateZip } from "../../src/lib/import/validate";4849/** Minimal ZIP writer (stored entries) that lets a test lie about names and sizes. */50function fakeZip(entries: { name: string; data?: Buffer; declared?: number; flags?: number; external?: number }[]): Buffer {51 const locals: Buffer[] = []; const centrals: Buffer[] = []; let offset = 0;52 for (const e of entries) {53 const name = Buffer.from(e.name, "utf8"); const data = e.data ?? Buffer.alloc(0); const size = e.declared ?? data.length;54 const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(e.flags ?? 0, 6); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(size, 22); local.writeUInt16LE(name.length, 26);55 const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); central.writeUInt16LE(e.flags ?? 0, 8); central.writeUInt32LE(data.length, 20); central.writeUInt32LE(size, 24); central.writeUInt16LE(name.length, 28); central.writeUInt32LE(e.external ?? 0, 38); central.writeUInt32LE(offset, 42);56 locals.push(local, name, data); centrals.push(central, name); offset += 30 + name.length + data.length;57 }58 const cd = Buffer.concat(centrals); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(entries.length, 8); end.writeUInt16LE(entries.length, 10); end.writeUInt32LE(cd.length, 12); end.writeUInt32LE(offset, 16);59 return Buffer.concat([...locals, cd, end]);60}61const code = (fn: () => unknown) => { try { fn(); } catch (e) { assert.ok(e instanceof ImportError, `expected ImportError, got ${e}`); return e.code; } return "no error"; };6263test("sniff recognises ZIP, PDF, legacy Office, text and binary", () => {64 assert.equal(sniff(Buffer.from("PK\x03\x04rest")), "zip");65 assert.equal(sniff(Buffer.from("%PDF-1.7\n…")), "pdf");66 assert.equal(sniff(Buffer.from([0xd0, 0xcf, 0x11, 0xe0, 1, 2])), "ole");67 assert.equal(sniff(Buffer.from("# Title\n\ntext é")), "text");68 assert.equal(sniff(Buffer.from([0x41, 0x00, 0x42])), "binary");69 assert.equal(sniff(Buffer.alloc(0)), "empty");70});7172test("the extension is not trusted: content must match the claimed kind", () => {73 const pdf = Buffer.from("%PDF-1.4\n1 0 obj"); const text = Buffer.from("hello");74 assert.equal(code(() => validateUpload({ kind: "zip", buffer: pdf, filename: "notes.zip" })), "type_mismatch");75 assert.equal(code(() => validateUpload({ kind: "pdf", buffer: text, filename: "paper.pdf" })), "type_mismatch");76 assert.equal(code(() => validateUpload({ kind: "markdown", buffer: pdf, filename: "notes.md" })), "type_mismatch");77 assert.equal(code(() => validateUpload({ kind: "docx", buffer: Buffer.from([0xd0, 0xcf, 0x11, 0xe0]), filename: "old.docx" })), "type_mismatch");78 assert.equal(code(() => validateUpload({ kind: "json", buffer: Buffer.from("[1,2]"), filename: "x.json" })), "bad_json");79 assert.equal(code(() => validateUpload({ kind: "markdown", buffer: Buffer.alloc(0), filename: "x.md" })), "empty_file");80 assert.equal(validateUpload({ kind: "pdf", buffer: pdf, filename: "paper.pdf" }).sniffed, "pdf");81 assert.equal(validateUpload({ kind: "markdown", buffer: text, filename: "a.md" }).kind, "markdown");82});8384test("size limits per kind", () => {85 const big = Buffer.alloc(LIMITS.perKind.markdown + 1, 0x61);86 assert.equal(code(() => validateUpload({ kind: "markdown", buffer: big, filename: "big.md" })), "file_too_large");87});8889test("a real ZIP made by jszip is read and accepted; a .docx needs word/document.xml", async () => {90 const z = new JSZip(); z.file("Notes/Hello.md", "# Hello\n\nworld"); z.file("Notes/img/a.png", Buffer.from([1, 2, 3]));91 const buf = await z.generateAsync({ type: "nodebuffer", compression: "DEFLATE" });92 const facts = validateZip(buf);93 assert.equal(facts.files, 2); assert.deepEqual(facts.entries.filter((e) => !e.dir).map((e) => e.name).sort(), ["Notes/Hello.md", "Notes/img/a.png"]);94 assert.equal(facts.entries.find((e) => e.name === "Notes/Hello.md")!.uncompressedSize, 14);95 assert.equal(validateUpload({ kind: "zip", buffer: buf, filename: "notes.zip" }).zip!.files, 2);96 assert.equal(code(() => validateUpload({ kind: "docx", buffer: buf, filename: "notes.docx" })), "type_mismatch");97 const d = new JSZip(); d.file("[Content_Types].xml", "<Types/>"); d.file("word/document.xml", "<w:document/>");98 assert.equal(validateUpload({ kind: "docx", buffer: await d.generateAsync({ type: "nodebuffer" }), filename: "a.docx" }).kind, "docx");99});100101test("zip-slip: unsafe member names are refused", () => {102 assert.equal(unsafeZipPath("a/b.md"), null);103 assert.equal(unsafeZipPath("a/..b/c..md"), null);104 for (const bad of ["../evil.md", "a/../../evil.md", "/etc/passwd", "\\\\server\\x", "C:\\x.md", "a\\..\\b", "a\0b"]) assert.notEqual(unsafeZipPath(bad), null, bad);105 assert.equal(code(() => validateZip(fakeZip([{ name: "ok.md", data: Buffer.from("x") }, { name: "../../outside.md", data: Buffer.from("x") }]))), "zip_unsafe_path");106 assert.equal(code(() => validateZip(fakeZip([{ name: "/abs.md", data: Buffer.from("x") }]))), "zip_unsafe_path");107});108109test("zip bomb: entry cap, declared size caps and compression ratio", () => {110 const many = fakeZip(Array.from({ length: 30 }, (_v, i) => ({ name: `f${i}.md`, data: Buffer.from("x") })));111 assert.equal(code(() => validateZip(many, { entries: 10 })), "zip_too_many_entries");112 assert.equal(validateZip(many, { entries: 30 }).files, 30);113 const huge = fakeZip([{ name: "a.bin", data: Buffer.from("x"), declared: 400 * 1024 * 1024 }]);114 assert.equal(code(() => validateZip(huge)), "zip_entry_too_large");115 const total = fakeZip(Array.from({ length: 12 }, (_v, i) => ({ name: `f${i}.bin`, data: Buffer.from("x"), declared: 200 * 1024 * 1024 })));116 assert.equal(code(() => validateZip(total)), "zip_too_large");117 const ratio = fakeZip([{ name: "a.bin", data: Buffer.alloc(1024), declared: 200 * 1024 * 1024 }]);118 assert.equal(code(() => validateZip(ratio)), "zip_bomb");119});120121test("encrypted, truncated and ZIP64 archives get a clear error; symlinks are counted, not followed", () => {122 assert.equal(code(() => validateZip(fakeZip([{ name: "a.md", data: Buffer.from("x"), flags: 1 }]))), "zip_encrypted");123 assert.equal(code(() => readZipDirectory(Buffer.from("PK\x03\x04 not really a zip, long enough to scan"))), "bad_zip");124 const z64 = fakeZip([{ name: "a.md", data: Buffer.from("x") }]); z64.writeUInt16LE(0xffff, z64.length - 22 + 10);125 assert.equal(code(() => readZipDirectory(z64)), "zip64");126 const link = validateZip(fakeZip([{ name: "a.md", data: Buffer.from("x") }, { name: "link", data: Buffer.from("/etc/passwd"), external: (0xa1ff << 16) >>> 0 }]));127 assert.equal(link.symlinks, 1); assert.equal(link.files, 1);128});129130test("detectKind and duplicate keys", () => {131 assert.equal(detectKind("Paper.PDF"), "pdf"); assert.equal(detectKind("refs.bib"), "bibtex"); assert.equal(detectKind("x", "application/zip"), "zip");132 assert.equal(code(() => detectKind("virus.exe")), "unsupported_type");133 assert.equal(normText("Hello, World!\n[image: fig 1] ÉTÉ"), "hello world été");134 assert.equal(contentKey(" My Page ", "Some text."), contentKey("my page", "some text"));135 assert.notEqual(contentKey("My Page", "Some text"), contentKey("My Page", "Other text"));136 assert.notEqual(contentKey("A", "x"), contentKey("B", "x"));137});138