Project Files
scripts / test-errors.ts
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import { resolveSafe, PathError } from "../src/pathGuard";
import { readDocx } from "../src/docxRead";
async function expectErr(name: string, fn: () => Promise<unknown>) {
try {
const r = await fn();
if (r && typeof r === "object" && "error" in (r as Record<string, unknown>)) {
console.log(`✓ ${name}: returned error: ${(r as {error:string}).error.slice(0,80)}`);
} else {
console.log(`✗ ${name}: unexpected success`, r);
}
} catch (e) {
if (e instanceof PathError) {
console.log(`✓ ${name}: PathError: ${e.message.slice(0,80)}`);
} else {
console.log(`? ${name}: threw`, e);
}
}
}
(async () => {
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "docx-err-"));
await expectErr("path outside root", () =>
resolveSafe("/etc/passwd", [tmp]),
);
await expectErr("missing file", async () => {
const abs = path.join(tmp, "nope.docx");
return readDocx(abs, { preserveStyles: true, includeMetadata: false });
});
await expectErr("not a real docx", async () => {
const abs = path.join(tmp, "fake.docx");
await fs.writeFile(abs, "not a zip");
return readDocx(abs, { preserveStyles: true, includeMetadata: false });
});
})();