const assert = require("node:assert/strict"); const { readFileSync } = require("node:fs"); const { mkdtemp, readFile, readdir, rm, stat, truncate, writeFile, } = require("node:fs/promises"); const { tmpdir } = require("node:os"); const { join } = require("node:path"); const test = require("node:test"); const ts = require("typescript"); // Exercise the real transport/file helpers with native Node FormData and File, // replacing only Raycast's credentials/preferences boundary. function loadTs(name, mocks = {}) { const file = join(__dirname, "../src", name + ".ts"); const source = ts.transpileModule(readFileSync(file, "utf8"), { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2023, esModuleInterop: true, }, }).outputText; const module = { exports: {} }; new Function("require", "module", "exports", source)( (id) => mocks[id] ?? require(id), module, module.exports, ); return module.exports; } const documents = loadTs("documents"); const bytes = Buffer.from("PK\x03\x04pseudonymized-package"); const mapping = { PERSON_01: { original: "Testperson", type: "PERSON" } }; function result(policy = "placeholder", changes = {}) { return { filename: "bericht.pseudonymisiert.docx", content_type: documents.DOCUMENT_TYPES[".docx"], file_base64: bytes.toString("base64"), mapping, entity_count: 1, segment_count: 4, image_policy: policy, images_replaced: policy === "placeholder" ? 2 : 0, images_removed: policy === "remove" ? 2 : 0, media_parts_removed: policy === "keep" ? 0 : 3, warnings: [], ...changes, }; } function json(body, status = 200) { return Response.json(body, { status }); } function client(fetchWithAuth) { return loadTs("velum", { "./auth": { fetchWithAuth }, "./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }), }, "./documents": documents, }); } async function fixture(t, extension = ".docx") { const directory = await mkdtemp(join(tmpdir(), "velum-raycast-documents-")); t.after(() => rm(directory, { recursive: true, force: true })); const path = join(directory, "Quelle" + extension); await writeFile(path, "original image and text"); return { directory, path }; } for (const extension of [".docx", ".xlsx", ".pptx", ".pdf"]) { test(`document form preserves bytes and defaults to placeholder for ${extension}`, async (t) => { const { path } = await fixture(t, extension); const form = await documents.documentForm(path, mapping, []); assert.equal(form.get("image_policy"), "placeholder"); assert.equal(form.get("entity_types"), "[]"); assert.deepEqual(JSON.parse(form.get("mapping")), mapping); const file = form.get("file"); assert.equal(file.name, "Quelle" + extension); assert.equal(file.type, documents.DOCUMENT_TYPES[extension]); assert.equal(await file.text(), "original image and text"); }); } for (const policy of ["placeholder", "remove", "keep"]) { test(`authenticated document flow sends and confirms ${policy}`, async (t) => { const { directory, path } = await fixture(t); const calls = []; const api = client(async (url, init) => { calls.push(url); if (url.endsWith("/api/project-capabilities")) return json({ document_image_policy: true }); assert.equal(init.method, "POST"); assert.equal(init.headers, undefined); // fetch must set the multipart boundary assert.equal(init.body.get("image_policy"), policy); assert.deepEqual(JSON.parse(init.body.get("entity_types")), ["PERSON"]); assert.equal( await init.body.get("file").text(), "original image and text", ); return json(result(policy)); }); const response = await api.pseudonymizeDocument( path, mapping, ["PERSON"], policy, ); assert.deepEqual(calls, [ "https://velum.test/api/project-capabilities", "https://velum.test/api/pseudonymize-document", ]); assert.equal(response.image_policy, policy); assert.equal( response.warnings.includes(documents.KEEP_IMAGE_WARNING), policy === "keep", ); const saved = await documents.saveDocumentCopy(response, directory); assert.deepEqual(await readFile(saved), bytes); assert.equal(await readFile(path, "utf8"), "original image and text"); }); } test("API defaults to placeholder when the caller omits the option", async (t) => { const { path } = await fixture(t); const api = client(async (url, init) => { if (url.endsWith("capabilities")) return json({ document_image_policy: true }); assert.equal(init.body.get("image_policy"), "placeholder"); return json(result()); }); await api.pseudonymizeDocument(path, {}); }); test("old backend is rejected before uploading document data", async (t) => { const { path, directory } = await fixture(t); const calls = []; const api = client(async (url) => { calls.push(url); return json({ document_hit_review: true }); }); await assert.rejects(api.pseudonymizeDocument(path, {}), /aktualisieren/); assert.deepEqual(calls, ["https://velum.test/api/project-capabilities"]); assert.deepEqual(await readdir(directory), ["Quelle.docx"]); }); test("missing or mismatched policy confirmation and HTTP 422 fail closed", async (t) => { const { path, directory } = await fixture(t); for (const response of [ json(result("keep")), json(result(undefined, { image_policy: undefined })), json({ detail: "Office-Datei kann nicht sicher bereinigt werden." }, 422), ]) { const api = client(async (url) => url.endsWith("capabilities") ? json({ document_image_policy: true }) : response, ); await assert.rejects(api.pseudonymizeDocument(path, {})); } assert.deepEqual(await readdir(directory), ["Quelle.docx"]); }); test("invalid files, image options and upload sizes are rejected", async (t) => { const { path, directory } = await fixture(t); await assert.rejects( documents.documentForm(path, {}, [], "unknown"), /Bildbehandlung/, ); await assert.rejects( documents.documentForm(join(directory, "report.doc"), {}), /DOCX/, ); await writeFile(path, ""); await assert.rejects(documents.documentForm(path, {}), /nicht leere/); await truncate(path, 20 * 1024 * 1024 + 1); await assert.rejects(documents.documentForm(path, {}), /zu groß/); }); test("unsafe or incomplete backend results cannot become output files", async (t) => { const { directory } = await fixture(t); for (const changes of [ { filename: "../Original.docx" }, { filename: "..\\Original.docx" }, { filename: "report.pdf" }, { content_type: "text/html" }, { file_base64: "%%%%" }, { file_base64: Buffer.from("not an office file").toString("base64") }, { images_replaced: -1 }, { images_removed: undefined }, { warnings: undefined }, { mapping: { PERSON_01: { type: "PERSON" } } }, ]) { assert.throws(() => documents.validateDocumentResponse( result("placeholder", changes), "placeholder", ), ); } await assert.rejects( documents.saveDocumentCopy( result("placeholder", { filename: "../Original.docx" }), directory, ), ); assert.deepEqual(await readdir(directory), ["Quelle.docx"]); }); test("concurrent exports cannot overwrite the original or earlier copies", async (t) => { const { path, directory } = await fixture(t); const response = result("placeholder", { filename: "Quelle.docx" }); const paths = await Promise.all( Array.from({ length: 5 }, () => documents.saveDocumentCopy(response, directory), ), ); assert.equal(new Set(paths).size, 5); assert.equal(await readFile(path, "utf8"), "original image and text"); for (const exported of paths) { assert.deepEqual(await readFile(exported), bytes); assert.equal((await stat(exported)).mode & 0o777, 0o600); } assert.equal((await readdir(directory)).length, 6); // no temporary directories remain }); test("failed export publishes no partial document and removes temporary data", async (t) => { const { directory } = await fixture(t); const broken = loadTs("documents", { "node:fs/promises": { ...require("node:fs/promises"), writeFile: async (path) => { await writeFile(path, "partial"); throw new Error("simulated disk failure"); }, }, }); await assert.rejects( broken.saveDocumentCopy(result(), directory), /disk failure/, ); assert.deepEqual(await readdir(directory), ["Quelle.docx"]); }); test("keep always displays an image warning while preserving backend warnings", () => { const response = documents.validateDocumentResponse( result("keep", { warnings: ["Backend-Hinweis"] }), "keep", ); assert.deepEqual(response.warnings, [ documents.KEEP_IMAGE_WARNING, "Backend-Hinweis", ]); });